]> git.saurik.com Git - wxWidgets.git/blob - src/msw/button.cpp
simplify code so it always returns the same object
[wxWidgets.git] / src / msw / button.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/button.cpp
3 // Purpose: wxButton
4 // Author: Julian Smart
5 // Modified by:
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 // 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_BUTTON
28
29 #include "wx/button.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/app.h"
33 #include "wx/brush.h"
34 #include "wx/panel.h"
35 #include "wx/bmpbuttn.h"
36 #include "wx/settings.h"
37 #include "wx/dcscreen.h"
38 #include "wx/dcclient.h"
39 #include "wx/toplevel.h"
40 #include "wx/msw/wrapcctl.h"
41 #include "wx/msw/private.h"
42 #include "wx/msw/missing.h"
43 #endif
44
45 #include "wx/imaglist.h"
46 #include "wx/stockitem.h"
47 #include "wx/msw/private/button.h"
48 #include "wx/msw/private/dc.h"
49 #include "wx/private/window.h"
50
51 #if wxUSE_MARKUP
52 #include "wx/generic/private/markuptext.h"
53 #endif // wxUSE_MARKUP
54
55 // set the value for BCM_SETSHIELD (for the UAC shield) if it's not defined in
56 // the header
57 #ifndef BCM_SETSHIELD
58 #define BCM_SETSHIELD 0x160c
59 #endif
60
61 // ----------------------------------------------------------------------------
62 // macros
63 // ----------------------------------------------------------------------------
64
65 BEGIN_EVENT_TABLE(wxButton, wxButtonBase)
66 EVT_CHAR_HOOK(wxButton::OnCharHook)
67 END_EVENT_TABLE()
68
69 // ============================================================================
70 // implementation
71 // ============================================================================
72
73 // ----------------------------------------------------------------------------
74 // creation/destruction
75 // ----------------------------------------------------------------------------
76
77 bool wxButton::Create(wxWindow *parent,
78 wxWindowID id,
79 const wxString& lbl,
80 const wxPoint& pos,
81 const wxSize& size,
82 long style,
83 const wxValidator& validator,
84 const wxString& name)
85 {
86 wxString label(lbl);
87 if (label.empty() && wxIsStockID(id))
88 {
89 // On Windows, some buttons aren't supposed to have mnemonics
90 label = wxGetStockLabel
91 (
92 id,
93 id == wxID_OK || id == wxID_CANCEL || id == wxID_CLOSE
94 ? wxSTOCK_NOFLAGS
95 : wxSTOCK_WITH_MNEMONIC
96 );
97 }
98
99 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
100 return false;
101
102 WXDWORD exstyle;
103 WXDWORD msStyle = MSWGetStyle(style, &exstyle);
104
105 // if the label contains several lines we must explicitly tell the button
106 // about it or it wouldn't draw it correctly ("\n"s would just appear as
107 // black boxes)
108 //
109 // NB: we do it here and not in MSWGetStyle() because we need the label
110 // value and the label is not set yet when MSWGetStyle() is called
111 msStyle |= wxMSWButton::GetMultilineStyle(label);
112
113 return MSWCreateControl(wxT("BUTTON"), msStyle, pos, size, label, exstyle);
114 }
115
116 wxButton::~wxButton()
117 {
118 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
119 if ( tlw && tlw->GetTmpDefaultItem() == this )
120 {
121 UnsetTmpDefault();
122 }
123 }
124
125 // ----------------------------------------------------------------------------
126 // flags
127 // ----------------------------------------------------------------------------
128
129 WXDWORD wxButton::MSWGetStyle(long style, WXDWORD *exstyle) const
130 {
131 // buttons never have an external border, they draw their own one
132 WXDWORD msStyle = wxControl::MSWGetStyle
133 (
134 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
135 );
136
137 // we must use WS_CLIPSIBLINGS with the buttons or they would draw over
138 // each other in any resizable dialog which has more than one button in
139 // the bottom
140 msStyle |= WS_CLIPSIBLINGS;
141
142 // don't use "else if" here: weird as it is, but you may combine wxBU_LEFT
143 // and wxBU_RIGHT to get BS_CENTER!
144 if ( style & wxBU_LEFT )
145 msStyle |= BS_LEFT;
146 if ( style & wxBU_RIGHT )
147 msStyle |= BS_RIGHT;
148 if ( style & wxBU_TOP )
149 msStyle |= BS_TOP;
150 if ( style & wxBU_BOTTOM )
151 msStyle |= BS_BOTTOM;
152 #ifndef __WXWINCE__
153 // flat 2d buttons
154 if ( style & wxNO_BORDER )
155 msStyle |= BS_FLAT;
156 #endif // __WXWINCE__
157
158 return msStyle;
159 }
160
161 /* static */
162 wxSize wxButtonBase::GetDefaultSize()
163 {
164 static wxSize s_sizeBtn;
165
166 if ( s_sizeBtn.x == 0 )
167 {
168 wxScreenDC dc;
169 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
170
171 // The size of a standard button in the dialog units is 50x14,
172 // translate this to pixels.
173 //
174 // Windows' computes dialog units using average character width over
175 // upper- and lower-case ASCII alphabet and not using the average
176 // character width metadata stored in the font; see
177 // http://support.microsoft.com/default.aspx/kb/145994 for detailed
178 // discussion.
179 //
180 // NB: wxMulDivInt32() is used, because it correctly rounds the result
181
182 const wxSize base = wxPrivate::GetAverageASCIILetterSize(dc);
183 s_sizeBtn.x = wxMulDivInt32(50, base.x, 4);
184 s_sizeBtn.y = wxMulDivInt32(14, base.y, 8);
185 }
186
187 return s_sizeBtn;
188 }
189
190 // ----------------------------------------------------------------------------
191 // default button handling
192 // ----------------------------------------------------------------------------
193
194 /*
195 In normal Windows programs there is no need to handle default button
196 manually because this is taken care by the system provided you use
197 WM_NEXTDLGCTL and not just SetFocus() to switch focus betweeh the controls
198 (see http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx for
199 the full explanation why just calling SetFocus() is not enough).
200
201 However this only works if the window is a dialog, i.e. uses DefDlgProc(),
202 but not with plain windows using DefWindowProc() and we do want to have
203 default buttons inside frames as well, so we're forced to reimplement all
204 this logic ourselves. It would be great to avoid having to do this but using
205 DefDlgProc() for all the windows would almost certainly result in more
206 problems, we'd need to carefully filter messages and pass some of them to
207 DefWindowProc() and some of them to DefDlgProc() which looks dangerous (what
208 if the handling of some message changes in some Windows version?), so doing
209 this ourselves is probably a lesser evil.
210
211 Read the rest to learn everything you ever wanted to know about the default
212 buttons but were afraid to ask.
213
214
215 In MSW the default button should be activated when the user presses Enter
216 and the current control doesn't process Enter itself somehow. This is
217 handled by ::DefWindowProc() (or maybe ::DefDialogProc()) using DM_SETDEFID
218 Another aspect of "defaultness" is that the default button has different
219 appearance: this is due to BS_DEFPUSHBUTTON style which is completely
220 separate from DM_SETDEFID stuff (!). Also note that BS_DEFPUSHBUTTON should
221 be unset if our parent window is not active so it should be unset whenever
222 we lose activation and set back when we regain it.
223
224 Final complication is that when a button is active, it should be the default
225 one, i.e. pressing Enter on a button always activates it and not another
226 one.
227
228 We handle this by maintaining a permanent and a temporary default items in
229 wxControlContainer (both may be NULL). When a button becomes the current
230 control (i.e. gets focus) it sets itself as the temporary default which
231 ensures that it has the right appearance and that Enter will be redirected
232 to it. When the button loses focus, it unsets the temporary default and so
233 the default item will be the permanent default -- that is the default button
234 if any had been set or none otherwise, which is just what we want.
235 */
236
237 // set this button as the (permanently) default one in its panel
238 wxWindow *wxButton::SetDefault()
239 {
240 // set this one as the default button both for wxWidgets ...
241 wxWindow *winOldDefault = wxButtonBase::SetDefault();
242
243 // ... and Windows
244 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
245 SetDefaultStyle(this, true);
246
247 return winOldDefault;
248 }
249
250 // return the top level parent window if it's not being deleted yet, otherwise
251 // return NULL
252 static wxTopLevelWindow *GetTLWParentIfNotBeingDeleted(wxWindow *win)
253 {
254 for ( ;; )
255 {
256 // IsTopLevel() will return false for a wxTLW being deleted, so we also
257 // need the parent test for this case
258 wxWindow * const parent = win->GetParent();
259 if ( !parent || win->IsTopLevel() )
260 {
261 if ( win->IsBeingDeleted() )
262 return NULL;
263
264 break;
265 }
266
267 win = parent;
268 }
269
270 wxASSERT_MSG( win, wxT("button without top level parent?") );
271
272 wxTopLevelWindow * const tlw = wxDynamicCast(win, wxTopLevelWindow);
273 wxASSERT_MSG( tlw, wxT("logic error in GetTLWParentIfNotBeingDeleted()") );
274
275 return tlw;
276 }
277
278 // set this button as being currently default
279 void wxButton::SetTmpDefault()
280 {
281 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(this);
282 if ( !tlw )
283 return;
284
285 wxWindow *winOldDefault = tlw->GetDefaultItem();
286 tlw->SetTmpDefaultItem(this);
287
288 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
289 SetDefaultStyle(this, true);
290 }
291
292 // unset this button as currently default, it may still stay permanent default
293 void wxButton::UnsetTmpDefault()
294 {
295 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(this);
296 if ( !tlw )
297 return;
298
299 tlw->SetTmpDefaultItem(NULL);
300
301 wxWindow *winOldDefault = tlw->GetDefaultItem();
302
303 SetDefaultStyle(this, false);
304 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), true);
305 }
306
307 /* static */
308 void
309 wxButton::SetDefaultStyle(wxButton *btn, bool on)
310 {
311 // we may be called with NULL pointer -- simpler to do the check here than
312 // in the caller which does wxDynamicCast()
313 if ( !btn )
314 return;
315
316 // first, let DefDlgProc() know about the new default button
317 if ( on )
318 {
319 // we shouldn't set BS_DEFPUSHBUTTON for any button if we don't have
320 // focus at all any more
321 if ( !wxTheApp->IsActive() )
322 return;
323
324 wxWindow * const tlw = wxGetTopLevelParent(btn);
325 wxCHECK_RET( tlw, wxT("button without top level window?") );
326
327 ::SendMessage(GetHwndOf(tlw), DM_SETDEFID, btn->GetId(), 0L);
328
329 // sending DM_SETDEFID also changes the button style to
330 // BS_DEFPUSHBUTTON so there is nothing more to do
331 }
332
333 // then also change the style as needed
334 long style = ::GetWindowLong(GetHwndOf(btn), GWL_STYLE);
335 if ( !(style & BS_DEFPUSHBUTTON) == on )
336 {
337 // don't do it with the owner drawn buttons because it will
338 // reset BS_OWNERDRAW style bit too (as BS_OWNERDRAW &
339 // BS_DEFPUSHBUTTON != 0)!
340 if ( (style & BS_OWNERDRAW) != BS_OWNERDRAW )
341 {
342 ::SendMessage(GetHwndOf(btn), BM_SETSTYLE,
343 on ? style | BS_DEFPUSHBUTTON
344 : style & ~BS_DEFPUSHBUTTON,
345 1L /* redraw */);
346 }
347 else // owner drawn
348 {
349 // redraw the button - it will notice itself that it's
350 // [not] the default one [any longer]
351 btn->Refresh();
352 }
353 }
354 //else: already has correct style
355 }
356
357 // ----------------------------------------------------------------------------
358 // helpers
359 // ----------------------------------------------------------------------------
360
361 bool wxButton::SendClickEvent()
362 {
363 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, GetId());
364 event.SetEventObject(this);
365
366 return ProcessCommand(event);
367 }
368
369 void wxButton::Command(wxCommandEvent & event)
370 {
371 ProcessCommand(event);
372 }
373
374 // ----------------------------------------------------------------------------
375 // event/message handlers
376 // ----------------------------------------------------------------------------
377
378 void wxButton::OnCharHook(wxKeyEvent& event)
379 {
380 // We want to ensure that the button always processes Enter key events
381 // itself, even if it's inside some control that normally takes over them
382 // (this happens when the button is part of an in-place editor control for
383 // example).
384 if ( event.GetKeyCode() == WXK_RETURN )
385 {
386 // We should ensure that subsequent key events are still generated even
387 // if we did handle EVT_CHAR_HOOK (normally this would suppress their
388 // generation).
389 event.DoAllowNextEvent();
390 }
391 else
392 {
393 event.Skip();
394 }
395 }
396
397 bool wxButton::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
398 {
399 bool processed = false;
400 switch ( param )
401 {
402 // NOTE: Apparently older versions (NT 4?) of the common controls send
403 // BN_DOUBLECLICKED but not a second BN_CLICKED for owner-drawn
404 // buttons, so in order to send two EVT_BUTTON events we should
405 // catch both types. Currently (Feb 2003) up-to-date versions of
406 // win98, win2k and winXP all send two BN_CLICKED messages for
407 // all button types, so we don't catch BN_DOUBLECLICKED anymore
408 // in order to not get 3 EVT_BUTTON events. If this is a problem
409 // then we need to figure out which version of the comctl32 changed
410 // this behaviour and test for it.
411
412 case 1: // message came from an accelerator
413 case BN_CLICKED: // normal buttons send this
414 processed = SendClickEvent();
415 break;
416 }
417
418 return processed;
419 }
420
421 WXLRESULT wxButton::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
422 {
423 // when we receive focus, we want to temporarily become the default button in
424 // our parent panel so that pressing "Enter" would activate us -- and when
425 // losing it we should restore the previous default button as well
426 if ( nMsg == WM_SETFOCUS )
427 {
428 SetTmpDefault();
429
430 // let the default processing take place too
431 }
432 else if ( nMsg == WM_KILLFOCUS )
433 {
434 UnsetTmpDefault();
435 }
436
437 // let the base class do all real processing
438 return wxAnyButton::MSWWindowProc(nMsg, wParam, lParam);
439 }
440
441 // ----------------------------------------------------------------------------
442 // authentication needed handling
443 // ----------------------------------------------------------------------------
444
445 bool wxButton::DoGetAuthNeeded() const
446 {
447 return m_authNeeded;
448 }
449
450 void wxButton::DoSetAuthNeeded(bool show)
451 {
452 // show/hide UAC symbol on Windows Vista and later
453 if ( wxGetWinVersion() >= wxWinVersion_6 )
454 {
455 m_authNeeded = show;
456 ::SendMessage(GetHwnd(), BCM_SETSHIELD, 0, show);
457 InvalidateBestSize();
458 }
459 }
460
461 #endif // wxUSE_BUTTON
462