Restore height tweaking in wxMSWButton::GetFittingSize().
[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 using namespace wxMSWImpl;
52
53 #if wxUSE_UXTHEME
54 #include "wx/msw/uxtheme.h"
55
56 // no need to include tmschema.h
57 #ifndef BP_PUSHBUTTON
58 #define BP_PUSHBUTTON 1
59
60 #define PBS_NORMAL 1
61 #define PBS_HOT 2
62 #define PBS_PRESSED 3
63 #define PBS_DISABLED 4
64 #define PBS_DEFAULTED 5
65
66 #define TMT_CONTENTMARGINS 3602
67 #endif
68
69 // provide the necessary declarations ourselves if they're missing from
70 // headers
71 #ifndef BCM_SETIMAGELIST
72 #define BCM_SETIMAGELIST 0x1602
73 #define BCM_SETTEXTMARGIN 0x1604
74
75 enum
76 {
77 BUTTON_IMAGELIST_ALIGN_LEFT,
78 BUTTON_IMAGELIST_ALIGN_RIGHT,
79 BUTTON_IMAGELIST_ALIGN_TOP,
80 BUTTON_IMAGELIST_ALIGN_BOTTOM
81 };
82
83 struct BUTTON_IMAGELIST
84 {
85 HIMAGELIST himl;
86 RECT margin;
87 UINT uAlign;
88 };
89 #endif
90 #endif // wxUSE_UXTHEME
91
92 #ifndef WM_THEMECHANGED
93 #define WM_THEMECHANGED 0x031A
94 #endif
95
96 #ifndef ODS_NOACCEL
97 #define ODS_NOACCEL 0x0100
98 #endif
99
100 #ifndef ODS_NOFOCUSRECT
101 #define ODS_NOFOCUSRECT 0x0200
102 #endif
103
104 #ifndef DT_HIDEPREFIX
105 #define DT_HIDEPREFIX 0x00100000
106 #endif
107
108 // set the value for BCM_SETSHIELD (for the UAC shield) if it's not defined in
109 // the header
110 #ifndef BCM_SETSHIELD
111 #define BCM_SETSHIELD 0x160c
112 #endif
113
114 // ----------------------------------------------------------------------------
115 // button image data
116 // ----------------------------------------------------------------------------
117
118 // we use different data classes for owner drawn buttons and for themed XP ones
119
120 class wxButtonImageData
121 {
122 public:
123 wxButtonImageData() { }
124 virtual ~wxButtonImageData() { }
125
126 virtual wxBitmap GetBitmap(wxButton::State which) const = 0;
127 virtual void SetBitmap(const wxBitmap& bitmap, wxButton::State which) = 0;
128
129 virtual wxSize GetBitmapMargins() const = 0;
130 virtual void SetBitmapMargins(wxCoord x, wxCoord y) = 0;
131
132 virtual wxDirection GetBitmapPosition() const = 0;
133 virtual void SetBitmapPosition(wxDirection dir) = 0;
134
135 private:
136 wxDECLARE_NO_COPY_CLASS(wxButtonImageData);
137 };
138
139 namespace
140 {
141
142 // the gap between button edge and the interior area used by Windows for the
143 // standard buttons
144 const int OD_BUTTON_MARGIN = 4;
145
146 class wxODButtonImageData : public wxButtonImageData
147 {
148 public:
149 wxODButtonImageData(wxButton *btn, const wxBitmap& bitmap)
150 {
151 SetBitmap(bitmap, wxButton::State_Normal);
152
153 m_dir = wxLEFT;
154
155 // we use margins when we have both bitmap and text, but when we have
156 // only the bitmap it should take up the entire button area
157 if ( btn->ShowsLabel() )
158 {
159 m_margin.x = btn->GetCharWidth();
160 m_margin.y = btn->GetCharHeight() / 2;
161 }
162 }
163
164 virtual wxBitmap GetBitmap(wxButton::State which) const
165 {
166 return m_bitmaps[which];
167 }
168
169 virtual void SetBitmap(const wxBitmap& bitmap, wxButton::State which)
170 {
171 m_bitmaps[which] = bitmap;
172 }
173
174 virtual wxSize GetBitmapMargins() const
175 {
176 return m_margin;
177 }
178
179 virtual void SetBitmapMargins(wxCoord x, wxCoord y)
180 {
181 m_margin = wxSize(x, y);
182 }
183
184 virtual wxDirection GetBitmapPosition() const
185 {
186 return m_dir;
187 }
188
189 virtual void SetBitmapPosition(wxDirection dir)
190 {
191 m_dir = dir;
192 }
193
194 private:
195 // just store the values passed to us to be able to retrieve them later
196 // from the drawing code
197 wxBitmap m_bitmaps[wxButton::State_Max];
198 wxSize m_margin;
199 wxDirection m_dir;
200
201 wxDECLARE_NO_COPY_CLASS(wxODButtonImageData);
202 };
203
204 #if wxUSE_UXTHEME
205
206 // somehow the margin is one pixel greater than the value returned by
207 // GetThemeMargins() call
208 const int XP_BUTTON_EXTRA_MARGIN = 1;
209
210 class wxXPButtonImageData : public wxButtonImageData
211 {
212 public:
213 // we must be constructed with the size of our images as we need to create
214 // the image list
215 wxXPButtonImageData(wxButton *btn, const wxBitmap& bitmap)
216 : m_iml(bitmap.GetWidth(), bitmap.GetHeight(), true /* use mask */,
217 wxButton::State_Max),
218 m_hwndBtn(GetHwndOf(btn))
219 {
220 // initialize all bitmaps to normal state
221 for ( int n = 0; n < wxButton::State_Max; n++ )
222 {
223 m_iml.Add(bitmap);
224 }
225
226 m_data.himl = GetHimagelistOf(&m_iml);
227
228 // no margins by default
229 m_data.margin.left =
230 m_data.margin.right =
231 m_data.margin.top =
232 m_data.margin.bottom = 0;
233
234 // use default alignment
235 m_data.uAlign = BUTTON_IMAGELIST_ALIGN_LEFT;
236
237 UpdateImageInfo();
238 }
239
240 virtual wxBitmap GetBitmap(wxButton::State which) const
241 {
242 return m_iml.GetBitmap(which);
243 }
244
245 virtual void SetBitmap(const wxBitmap& bitmap, wxButton::State which)
246 {
247 m_iml.Replace(which, bitmap);
248
249 UpdateImageInfo();
250 }
251
252 virtual wxSize GetBitmapMargins() const
253 {
254 return wxSize(m_data.margin.left, m_data.margin.top);
255 }
256
257 virtual void SetBitmapMargins(wxCoord x, wxCoord y)
258 {
259 RECT& margin = m_data.margin;
260 margin.left =
261 margin.right = x;
262 margin.top =
263 margin.bottom = y;
264
265 if ( !::SendMessage(m_hwndBtn, BCM_SETTEXTMARGIN, 0, (LPARAM)&margin) )
266 {
267 wxLogDebug("SendMessage(BCM_SETTEXTMARGIN) failed");
268 }
269 }
270
271 virtual wxDirection GetBitmapPosition() const
272 {
273 switch ( m_data.uAlign )
274 {
275 default:
276 wxFAIL_MSG( "invalid image alignment" );
277 // fall through
278
279 case BUTTON_IMAGELIST_ALIGN_LEFT:
280 return wxLEFT;
281
282 case BUTTON_IMAGELIST_ALIGN_RIGHT:
283 return wxRIGHT;
284
285 case BUTTON_IMAGELIST_ALIGN_TOP:
286 return wxTOP;
287
288 case BUTTON_IMAGELIST_ALIGN_BOTTOM:
289 return wxBOTTOM;
290 }
291 }
292
293 virtual void SetBitmapPosition(wxDirection dir)
294 {
295 UINT alignNew;
296 switch ( dir )
297 {
298 default:
299 wxFAIL_MSG( "invalid direction" );
300 // fall through
301
302 case wxLEFT:
303 alignNew = BUTTON_IMAGELIST_ALIGN_LEFT;
304 break;
305
306 case wxRIGHT:
307 alignNew = BUTTON_IMAGELIST_ALIGN_RIGHT;
308 break;
309
310 case wxTOP:
311 alignNew = BUTTON_IMAGELIST_ALIGN_TOP;
312 break;
313
314 case wxBOTTOM:
315 alignNew = BUTTON_IMAGELIST_ALIGN_BOTTOM;
316 break;
317 }
318
319 if ( alignNew != m_data.uAlign )
320 {
321 m_data.uAlign = alignNew;
322 UpdateImageInfo();
323 }
324 }
325
326 private:
327 void UpdateImageInfo()
328 {
329 if ( !::SendMessage(m_hwndBtn, BCM_SETIMAGELIST, 0, (LPARAM)&m_data) )
330 {
331 wxLogDebug("SendMessage(BCM_SETIMAGELIST) failed");
332 }
333 }
334
335 // we store image list separately to be able to use convenient wxImageList
336 // methods instead of working with raw HIMAGELIST
337 wxImageList m_iml;
338
339 // store the rest of the data in BCM_SETIMAGELIST-friendly form
340 BUTTON_IMAGELIST m_data;
341
342 // the button we're associated with
343 const HWND m_hwndBtn;
344
345
346 wxDECLARE_NO_COPY_CLASS(wxXPButtonImageData);
347 };
348
349 #endif // wxUSE_UXTHEME
350
351 } // anonymous namespace
352
353 // ----------------------------------------------------------------------------
354 // macros
355 // ----------------------------------------------------------------------------
356
357 // ============================================================================
358 // implementation
359 // ============================================================================
360
361 // ----------------------------------------------------------------------------
362 // helper functions from wx/msw/private/button.h
363 // ----------------------------------------------------------------------------
364
365 void wxMSWButton::UpdateMultilineStyle(HWND hwnd, const wxString& label)
366 {
367 // update BS_MULTILINE style depending on the new label (resetting it
368 // doesn't seem to do anything very useful but it shouldn't hurt and we do
369 // have to set it whenever the label becomes multi line as otherwise it
370 // wouldn't be shown correctly as we don't use BS_MULTILINE when creating
371 // the control unless it already has new lines in its label)
372 long styleOld = ::GetWindowLong(hwnd, GWL_STYLE),
373 styleNew;
374 if ( label.find(wxT('\n')) != wxString::npos )
375 styleNew = styleOld | BS_MULTILINE;
376 else
377 styleNew = styleOld & ~BS_MULTILINE;
378
379 if ( styleNew != styleOld )
380 ::SetWindowLong(hwnd, GWL_STYLE, styleNew);
381 }
382
383 wxSize wxMSWButton::GetFittingSize(wxWindow *win,
384 const wxSize& sizeLabel,
385 int flags)
386 {
387 // FIXME: this is pure guesswork, need to retrieve the real button margins
388 wxSize sizeBtn = sizeLabel;
389
390 sizeBtn.x += 3*win->GetCharWidth();
391 sizeBtn.y += win->GetCharHeight()/2;
392
393 // account for the shield UAC icon if we have it
394 if ( flags & Size_AuthNeeded )
395 sizeBtn.x += wxSystemSettings::GetMetric(wxSYS_SMALLICON_X);
396
397 return sizeBtn;
398 }
399
400 wxSize wxMSWButton::ComputeBestFittingSize(wxControl *btn, int flags)
401 {
402 wxClientDC dc(btn);
403
404 wxSize sizeBtn;
405 dc.GetMultiLineTextExtent(btn->GetLabelText(), &sizeBtn.x, &sizeBtn.y);
406
407 return GetFittingSize(btn, sizeBtn, flags);
408 }
409
410 wxSize wxMSWButton::IncreaseToStdSizeAndCache(wxControl *btn, const wxSize& size)
411 {
412 wxSize sizeBtn(size);
413
414 // All buttons have at least the standard height and, unless the user
415 // explicitly wants them to be as small as possible and used wxBU_EXACTFIT
416 // style to indicate this, of at least the standard width too.
417 //
418 // Notice that we really want to make all buttons equally high, otherwise
419 // they look ugly and the existing code using wxBU_EXACTFIT only uses it to
420 // control width and not height.
421
422 // The 50x14 button size is documented in the "Recommended sizing and
423 // spacing" section of MSDN layout article.
424 //
425 // Note that we intentionally don't use GetDefaultSize() here, because
426 // it's inexact -- dialog units depend on this dialog's font.
427 const wxSize sizeDef = btn->ConvertDialogToPixels(wxSize(50, 14));
428 if ( !btn->HasFlag(wxBU_EXACTFIT) )
429 {
430 if ( sizeBtn.x < sizeDef.x )
431 sizeBtn.x = sizeDef.x;
432 }
433 if ( sizeBtn.y < sizeDef.y )
434 sizeBtn.y = sizeDef.y;
435
436 btn->CacheBestSize(sizeBtn);
437
438 return sizeBtn;
439 }
440
441 // ----------------------------------------------------------------------------
442 // creation/destruction
443 // ----------------------------------------------------------------------------
444
445 bool wxButton::Create(wxWindow *parent,
446 wxWindowID id,
447 const wxString& lbl,
448 const wxPoint& pos,
449 const wxSize& size,
450 long style,
451 const wxValidator& validator,
452 const wxString& name)
453 {
454 wxString label(lbl);
455 if (label.empty() && wxIsStockID(id))
456 {
457 // On Windows, some buttons aren't supposed to have mnemonics
458 label = wxGetStockLabel
459 (
460 id,
461 id == wxID_OK || id == wxID_CANCEL || id == wxID_CLOSE
462 ? wxSTOCK_NOFLAGS
463 : wxSTOCK_WITH_MNEMONIC
464 );
465 }
466
467 if ( !CreateControl(parent, id, pos, size, style, validator, name) )
468 return false;
469
470 WXDWORD exstyle;
471 WXDWORD msStyle = MSWGetStyle(style, &exstyle);
472
473 // if the label contains several lines we must explicitly tell the button
474 // about it or it wouldn't draw it correctly ("\n"s would just appear as
475 // black boxes)
476 //
477 // NB: we do it here and not in MSWGetStyle() because we need the label
478 // value and the label is not set yet when MSWGetStyle() is called
479 msStyle |= wxMSWButton::GetMultilineStyle(label);
480
481 return MSWCreateControl(wxT("BUTTON"), msStyle, pos, size, label, exstyle);
482 }
483
484 wxButton::~wxButton()
485 {
486 wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
487 if ( tlw && tlw->GetTmpDefaultItem() == this )
488 {
489 UnsetTmpDefault();
490 }
491
492 delete m_imageData;
493 }
494
495 // ----------------------------------------------------------------------------
496 // flags
497 // ----------------------------------------------------------------------------
498
499 WXDWORD wxButton::MSWGetStyle(long style, WXDWORD *exstyle) const
500 {
501 // buttons never have an external border, they draw their own one
502 WXDWORD msStyle = wxControl::MSWGetStyle
503 (
504 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
505 );
506
507 // we must use WS_CLIPSIBLINGS with the buttons or they would draw over
508 // each other in any resizeable dialog which has more than one button in
509 // the bottom
510 msStyle |= WS_CLIPSIBLINGS;
511
512 // don't use "else if" here: weird as it is, but you may combine wxBU_LEFT
513 // and wxBU_RIGHT to get BS_CENTER!
514 if ( style & wxBU_LEFT )
515 msStyle |= BS_LEFT;
516 if ( style & wxBU_RIGHT )
517 msStyle |= BS_RIGHT;
518 if ( style & wxBU_TOP )
519 msStyle |= BS_TOP;
520 if ( style & wxBU_BOTTOM )
521 msStyle |= BS_BOTTOM;
522 #ifndef __WXWINCE__
523 // flat 2d buttons
524 if ( style & wxNO_BORDER )
525 msStyle |= BS_FLAT;
526 #endif // __WXWINCE__
527
528 return msStyle;
529 }
530
531 void wxButton::SetLabel(const wxString& label)
532 {
533 wxMSWButton::UpdateMultilineStyle(GetHwnd(), label);
534
535 wxButtonBase::SetLabel(label);
536 }
537
538 // ----------------------------------------------------------------------------
539 // size management including autosizing
540 // ----------------------------------------------------------------------------
541
542 void wxButton::AdjustForBitmapSize(wxSize &size) const
543 {
544 wxCHECK_RET( m_imageData, wxT("shouldn't be called if no image") );
545
546 // account for the bitmap size
547 const wxSize sizeBmp = m_imageData->GetBitmap(State_Normal).GetSize();
548 const wxDirection dirBmp = m_imageData->GetBitmapPosition();
549 if ( dirBmp == wxLEFT || dirBmp == wxRIGHT )
550 {
551 size.x += sizeBmp.x;
552 if ( sizeBmp.y > size.y )
553 size.y = sizeBmp.y;
554 }
555 else // bitmap on top/below the text
556 {
557 size.y += sizeBmp.y;
558 if ( sizeBmp.x > size.x )
559 size.x = sizeBmp.x;
560 }
561
562 // account for the user-specified margins
563 size += 2*m_imageData->GetBitmapMargins();
564
565 // and also for the margins we always add internally (unless we have no
566 // border at all in which case the button has exactly the same size as
567 // bitmap and so no margins should be used)
568 if ( !HasFlag(wxBORDER_NONE) )
569 {
570 int marginH = 0,
571 marginV = 0;
572 #if wxUSE_UXTHEME
573 if ( wxUxThemeEngine::GetIfActive() )
574 {
575 wxUxThemeHandle theme(const_cast<wxButton *>(this), L"BUTTON");
576
577 MARGINS margins;
578 wxUxThemeEngine::Get()->GetThemeMargins(theme, NULL,
579 BP_PUSHBUTTON,
580 PBS_NORMAL,
581 TMT_CONTENTMARGINS,
582 NULL,
583 &margins);
584
585 // XP doesn't draw themed buttons correctly when the client
586 // area is smaller than 8x8 - enforce this minimum size for
587 // small bitmaps
588 size.IncTo(wxSize(8, 8));
589
590 marginH = margins.cxLeftWidth + margins.cxRightWidth
591 + 2*XP_BUTTON_EXTRA_MARGIN;
592 marginV = margins.cyTopHeight + margins.cyBottomHeight
593 + 2*XP_BUTTON_EXTRA_MARGIN;
594 }
595 else
596 #endif // wxUSE_UXTHEME
597 {
598 marginH =
599 marginV = OD_BUTTON_MARGIN;
600 }
601
602 size.IncBy(marginH, marginV);
603 }
604 }
605
606 wxSize wxButton::DoGetBestSize() const
607 {
608 wxButton * const self = const_cast<wxButton *>(this);
609
610 wxSize size;
611
612 // Account for the text part if we have it.
613 if ( ShowsLabel() )
614 {
615 int flags = 0;
616 if ( GetAuthNeeded() )
617 flags |= wxMSWButton::Size_AuthNeeded;
618
619 size = wxMSWButton::ComputeBestFittingSize(self, flags);
620 }
621
622 if ( m_imageData )
623 AdjustForBitmapSize(size);
624
625 return wxMSWButton::IncreaseToStdSizeAndCache(self, size);
626 }
627
628 /* static */
629 wxSize wxButtonBase::GetDefaultSize()
630 {
631 static wxSize s_sizeBtn;
632
633 if ( s_sizeBtn.x == 0 )
634 {
635 wxScreenDC dc;
636 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
637
638 // The size of a standard button in the dialog units is 50x14,
639 // translate this to pixels.
640 //
641 // Windows' computes dialog units using average character width over
642 // upper- and lower-case ASCII alphabet and not using the average
643 // character width metadata stored in the font; see
644 // http://support.microsoft.com/default.aspx/kb/145994 for detailed
645 // discussion.
646 //
647 // NB: wxMulDivInt32() is used, because it correctly rounds the result
648
649 const wxSize base = wxPrivate::GetAverageASCIILetterSize(dc);
650 s_sizeBtn.x = wxMulDivInt32(50, base.x, 4);
651 s_sizeBtn.y = wxMulDivInt32(14, base.y, 8);
652 }
653
654 return s_sizeBtn;
655 }
656
657 // ----------------------------------------------------------------------------
658 // default button handling
659 // ----------------------------------------------------------------------------
660
661 /*
662 The comment below and all this code is probably due to not using WM_NEXTDLGCTL
663 message when changing focus (but just SetFocus() which is not enough), see
664 http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx for the
665 full explanation.
666
667 TODO: Do use WM_NEXTDLGCTL and get rid of all this code.
668
669
670 "Everything you ever wanted to know about the default buttons" or "Why do we
671 have to do all this?"
672
673 In MSW the default button should be activated when the user presses Enter
674 and the current control doesn't process Enter itself somehow. This is
675 handled by ::DefWindowProc() (or maybe ::DefDialogProc()) using DM_SETDEFID
676 Another aspect of "defaultness" is that the default button has different
677 appearance: this is due to BS_DEFPUSHBUTTON style which is completely
678 separate from DM_SETDEFID stuff (!). Also note that BS_DEFPUSHBUTTON should
679 be unset if our parent window is not active so it should be unset whenever
680 we lose activation and set back when we regain it.
681
682 Final complication is that when a button is active, it should be the default
683 one, i.e. pressing Enter on a button always activates it and not another
684 one.
685
686 We handle this by maintaining a permanent and a temporary default items in
687 wxControlContainer (both may be NULL). When a button becomes the current
688 control (i.e. gets focus) it sets itself as the temporary default which
689 ensures that it has the right appearance and that Enter will be redirected
690 to it. When the button loses focus, it unsets the temporary default and so
691 the default item will be the permanent default -- that is the default button
692 if any had been set or none otherwise, which is just what we want.
693
694 NB: all this is quite complicated by now and the worst is that normally
695 it shouldn't be necessary at all as for the normal Windows programs
696 DefWindowProc() and IsDialogMessage() take care of all this
697 automatically -- however in wxWidgets programs this doesn't work for
698 nested hierarchies (i.e. a notebook inside a notebook) for unknown
699 reason and so we have to reproduce all this code ourselves. It would be
700 very nice if we could avoid doing it.
701 */
702
703 // set this button as the (permanently) default one in its panel
704 wxWindow *wxButton::SetDefault()
705 {
706 // set this one as the default button both for wxWidgets ...
707 wxWindow *winOldDefault = wxButtonBase::SetDefault();
708
709 // ... and Windows
710 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
711 SetDefaultStyle(this, true);
712
713 return winOldDefault;
714 }
715
716 // return the top level parent window if it's not being deleted yet, otherwise
717 // return NULL
718 static wxTopLevelWindow *GetTLWParentIfNotBeingDeleted(wxWindow *win)
719 {
720 for ( ;; )
721 {
722 // IsTopLevel() will return false for a wxTLW being deleted, so we also
723 // need the parent test for this case
724 wxWindow * const parent = win->GetParent();
725 if ( !parent || win->IsTopLevel() )
726 {
727 if ( win->IsBeingDeleted() )
728 return NULL;
729
730 break;
731 }
732
733 win = parent;
734 }
735
736 wxASSERT_MSG( win, wxT("button without top level parent?") );
737
738 wxTopLevelWindow * const tlw = wxDynamicCast(win, wxTopLevelWindow);
739 wxASSERT_MSG( tlw, wxT("logic error in GetTLWParentIfNotBeingDeleted()") );
740
741 return tlw;
742 }
743
744 // set this button as being currently default
745 void wxButton::SetTmpDefault()
746 {
747 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(GetParent());
748 if ( !tlw )
749 return;
750
751 wxWindow *winOldDefault = tlw->GetDefaultItem();
752 tlw->SetTmpDefaultItem(this);
753
754 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), false);
755 SetDefaultStyle(this, true);
756 }
757
758 // unset this button as currently default, it may still stay permanent default
759 void wxButton::UnsetTmpDefault()
760 {
761 wxTopLevelWindow * const tlw = GetTLWParentIfNotBeingDeleted(GetParent());
762 if ( !tlw )
763 return;
764
765 tlw->SetTmpDefaultItem(NULL);
766
767 wxWindow *winOldDefault = tlw->GetDefaultItem();
768
769 SetDefaultStyle(this, false);
770 SetDefaultStyle(wxDynamicCast(winOldDefault, wxButton), true);
771 }
772
773 /* static */
774 void
775 wxButton::SetDefaultStyle(wxButton *btn, bool on)
776 {
777 // we may be called with NULL pointer -- simpler to do the check here than
778 // in the caller which does wxDynamicCast()
779 if ( !btn )
780 return;
781
782 // first, let DefDlgProc() know about the new default button
783 if ( on )
784 {
785 // we shouldn't set BS_DEFPUSHBUTTON for any button if we don't have
786 // focus at all any more
787 if ( !wxTheApp->IsActive() )
788 return;
789
790 wxWindow * const tlw = wxGetTopLevelParent(btn);
791 wxCHECK_RET( tlw, wxT("button without top level window?") );
792
793 ::SendMessage(GetHwndOf(tlw), DM_SETDEFID, btn->GetId(), 0L);
794
795 // sending DM_SETDEFID also changes the button style to
796 // BS_DEFPUSHBUTTON so there is nothing more to do
797 }
798
799 // then also change the style as needed
800 long style = ::GetWindowLong(GetHwndOf(btn), GWL_STYLE);
801 if ( !(style & BS_DEFPUSHBUTTON) == on )
802 {
803 // don't do it with the owner drawn buttons because it will
804 // reset BS_OWNERDRAW style bit too (as BS_OWNERDRAW &
805 // BS_DEFPUSHBUTTON != 0)!
806 if ( (style & BS_OWNERDRAW) != BS_OWNERDRAW )
807 {
808 ::SendMessage(GetHwndOf(btn), BM_SETSTYLE,
809 on ? style | BS_DEFPUSHBUTTON
810 : style & ~BS_DEFPUSHBUTTON,
811 1L /* redraw */);
812 }
813 else // owner drawn
814 {
815 // redraw the button - it will notice itself that it's
816 // [not] the default one [any longer]
817 btn->Refresh();
818 }
819 }
820 //else: already has correct style
821 }
822
823 // ----------------------------------------------------------------------------
824 // helpers
825 // ----------------------------------------------------------------------------
826
827 bool wxButton::SendClickEvent()
828 {
829 wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, GetId());
830 event.SetEventObject(this);
831
832 return ProcessCommand(event);
833 }
834
835 void wxButton::Command(wxCommandEvent & event)
836 {
837 ProcessCommand(event);
838 }
839
840 // ----------------------------------------------------------------------------
841 // event/message handlers
842 // ----------------------------------------------------------------------------
843
844 bool wxButton::MSWCommand(WXUINT param, WXWORD WXUNUSED(id))
845 {
846 bool processed = false;
847 switch ( param )
848 {
849 // NOTE: Apparently older versions (NT 4?) of the common controls send
850 // BN_DOUBLECLICKED but not a second BN_CLICKED for owner-drawn
851 // buttons, so in order to send two EVT_BUTTON events we should
852 // catch both types. Currently (Feb 2003) up-to-date versions of
853 // win98, win2k and winXP all send two BN_CLICKED messages for
854 // all button types, so we don't catch BN_DOUBLECLICKED anymore
855 // in order to not get 3 EVT_BUTTON events. If this is a problem
856 // then we need to figure out which version of the comctl32 changed
857 // this behaviour and test for it.
858
859 case 1: // message came from an accelerator
860 case BN_CLICKED: // normal buttons send this
861 processed = SendClickEvent();
862 break;
863 }
864
865 return processed;
866 }
867
868 WXLRESULT wxButton::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
869 {
870 // when we receive focus, we want to temporarily become the default button in
871 // our parent panel so that pressing "Enter" would activate us -- and when
872 // losing it we should restore the previous default button as well
873 if ( nMsg == WM_SETFOCUS )
874 {
875 SetTmpDefault();
876
877 // let the default processing take place too
878 }
879 else if ( nMsg == WM_KILLFOCUS )
880 {
881 UnsetTmpDefault();
882 }
883 else if ( nMsg == WM_LBUTTONDBLCLK )
884 {
885 // emulate a click event to force an owner-drawn button to change its
886 // appearance - without this, it won't do it
887 (void)wxControl::MSWWindowProc(WM_LBUTTONDOWN, wParam, lParam);
888
889 // and continue with processing the message normally as well
890 }
891 #if wxUSE_UXTHEME
892 else if ( nMsg == WM_THEMECHANGED )
893 {
894 // need to recalculate the best size here
895 // as the theme size might have changed
896 InvalidateBestSize();
897 }
898 #endif // wxUSE_UXTHEME
899 // must use m_mouseInWindow here instead of IsMouseInWindow()
900 // since we need to know the first time the mouse enters the window
901 // and IsMouseInWindow() would return true in this case
902 else if ( (nMsg == WM_MOUSEMOVE && !m_mouseInWindow) ||
903 nMsg == WM_MOUSELEAVE )
904 {
905 if (
906 IsEnabled() &&
907 (
908 #if wxUSE_UXTHEME
909 wxUxThemeEngine::GetIfActive() ||
910 #endif // wxUSE_UXTHEME
911 (m_imageData && m_imageData->GetBitmap(State_Current).IsOk())
912 )
913 )
914 {
915 Refresh();
916 }
917 }
918
919 // let the base class do all real processing
920 return wxControl::MSWWindowProc(nMsg, wParam, lParam);
921 }
922
923 // ----------------------------------------------------------------------------
924 // authentication needed handling
925 // ----------------------------------------------------------------------------
926
927 bool wxButton::DoGetAuthNeeded() const
928 {
929 return m_authNeeded;
930 }
931
932 void wxButton::DoSetAuthNeeded(bool show)
933 {
934 // show/hide UAC symbol on Windows Vista and later
935 if ( wxGetWinVersion() >= wxWinVersion_6 )
936 {
937 m_authNeeded = show;
938 ::SendMessage(GetHwnd(), BCM_SETSHIELD, 0, show);
939 InvalidateBestSize();
940 }
941 }
942
943 // ----------------------------------------------------------------------------
944 // button images
945 // ----------------------------------------------------------------------------
946
947 wxBitmap wxButton::DoGetBitmap(State which) const
948 {
949 return m_imageData ? m_imageData->GetBitmap(which) : wxBitmap();
950 }
951
952 void wxButton::DoSetBitmap(const wxBitmap& bitmap, State which)
953 {
954 // allocate the image data when the first bitmap is set
955 if ( !m_imageData )
956 {
957 #if wxUSE_UXTHEME
958 // using image list doesn't work correctly if we don't have any label
959 // (even if we use BUTTON_IMAGELIST_ALIGN_CENTER alignment and
960 // BS_BITMAP style), at least under Windows 2003 so use owner drawn
961 // strategy for bitmap-only buttons
962 if ( ShowsLabel() && wxUxThemeEngine::GetIfActive() )
963 {
964 m_imageData = new wxXPButtonImageData(this, bitmap);
965 }
966 else
967 #endif // wxUSE_UXTHEME
968 {
969 m_imageData = new wxODButtonImageData(this, bitmap);
970 MakeOwnerDrawn();
971 }
972 }
973 else
974 {
975 m_imageData->SetBitmap(bitmap, which);
976 }
977
978 // it should be enough to only invalidate the best size when the normal
979 // bitmap changes as all bitmaps assigned to the button should be of the
980 // same size anyhow
981 if ( which == State_Normal )
982 InvalidateBestSize();
983
984 Refresh();
985 }
986
987 wxSize wxButton::DoGetBitmapMargins() const
988 {
989 return m_imageData ? m_imageData->GetBitmapMargins() : wxSize(0, 0);
990 }
991
992 void wxButton::DoSetBitmapMargins(wxCoord x, wxCoord y)
993 {
994 wxCHECK_RET( m_imageData, "SetBitmap() must be called first" );
995
996 m_imageData->SetBitmapMargins(x, y);
997 InvalidateBestSize();
998 }
999
1000 void wxButton::DoSetBitmapPosition(wxDirection dir)
1001 {
1002 wxCHECK_RET( m_imageData, "SetBitmap() must be called first" );
1003
1004 m_imageData->SetBitmapPosition(dir);
1005 InvalidateBestSize();
1006 }
1007
1008 // ----------------------------------------------------------------------------
1009 // owner-drawn buttons support
1010 // ----------------------------------------------------------------------------
1011
1012 // drawing helpers
1013 namespace
1014 {
1015
1016 // return the button state using both the ODS_XXX flags specified in state
1017 // parameter and the current button state
1018 wxButton::State GetButtonState(wxButton *btn, UINT state)
1019 {
1020 if ( state & ODS_DISABLED )
1021 return wxButton::State_Disabled;
1022
1023 if ( state & ODS_SELECTED )
1024 return wxButton::State_Pressed;
1025
1026 if ( btn->HasCapture() || btn->IsMouseInWindow() )
1027 return wxButton::State_Current;
1028
1029 if ( state & ODS_FOCUS )
1030 return wxButton::State_Focused;
1031
1032 return wxButton::State_Normal;
1033 }
1034
1035 void DrawButtonText(HDC hdc,
1036 RECT *pRect,
1037 const wxString& text,
1038 COLORREF col,
1039 int flags)
1040 {
1041 wxTextColoursChanger changeFg(hdc, col, CLR_INVALID);
1042 wxBkModeChanger changeBkMode(hdc, wxBRUSHSTYLE_TRANSPARENT);
1043
1044 // center text horizontally in any case
1045 flags |= DT_CENTER;
1046
1047 if ( text.find(wxT('\n')) != wxString::npos )
1048 {
1049 // draw multiline label
1050
1051 // first we need to compute its bounding rect
1052 RECT rc;
1053 ::CopyRect(&rc, pRect);
1054 ::DrawText(hdc, text.wx_str(), text.length(), &rc,
1055 DT_CENTER | DT_CALCRECT);
1056
1057 // now center this rect inside the entire button area
1058 const LONG w = rc.right - rc.left;
1059 const LONG h = rc.bottom - rc.top;
1060 rc.left = (pRect->right - pRect->left)/2 - w/2;
1061 rc.right = rc.left+w;
1062 rc.top = (pRect->bottom - pRect->top)/2 - h/2;
1063 rc.bottom = rc.top+h;
1064
1065 ::DrawText(hdc, text.wx_str(), text.length(), &rc, flags);
1066 }
1067 else // single line label
1068 {
1069 // centre text vertically too (notice that we must have DT_SINGLELINE
1070 // for DT_VCENTER to work)
1071 ::DrawText(hdc, text.wx_str(), text.length(), pRect,
1072 flags | DT_SINGLELINE | DT_VCENTER);
1073 }
1074 }
1075
1076 void DrawRect(HDC hdc, const RECT& r)
1077 {
1078 wxDrawLine(hdc, r.left, r.top, r.right, r.top);
1079 wxDrawLine(hdc, r.right, r.top, r.right, r.bottom);
1080 wxDrawLine(hdc, r.right, r.bottom, r.left, r.bottom);
1081 wxDrawLine(hdc, r.left, r.bottom, r.left, r.top);
1082 }
1083
1084 /*
1085 The button frame looks like this normally:
1086
1087 WWWWWWWWWWWWWWWWWWB
1088 WHHHHHHHHHHHHHHHHGB W = white (HILIGHT)
1089 WH GB H = light grey (LIGHT)
1090 WH GB G = dark grey (SHADOW)
1091 WH GB B = black (DKSHADOW)
1092 WH GB
1093 WGGGGGGGGGGGGGGGGGB
1094 BBBBBBBBBBBBBBBBBBB
1095
1096 When the button is selected, the button becomes like this (the total button
1097 size doesn't change):
1098
1099 BBBBBBBBBBBBBBBBBBB
1100 BWWWWWWWWWWWWWWWWBB
1101 BWHHHHHHHHHHHHHHGBB
1102 BWH GBB
1103 BWH GBB
1104 BWGGGGGGGGGGGGGGGBB
1105 BBBBBBBBBBBBBBBBBBB
1106 BBBBBBBBBBBBBBBBBBB
1107
1108 When the button is pushed (while selected) it is like:
1109
1110 BBBBBBBBBBBBBBBBBBB
1111 BGGGGGGGGGGGGGGGGGB
1112 BG GB
1113 BG GB
1114 BG GB
1115 BG GB
1116 BGGGGGGGGGGGGGGGGGB
1117 BBBBBBBBBBBBBBBBBBB
1118 */
1119 void DrawButtonFrame(HDC hdc, RECT& rectBtn,
1120 bool selected, bool pushed)
1121 {
1122 RECT r;
1123 CopyRect(&r, &rectBtn);
1124
1125 AutoHPEN hpenBlack(GetSysColor(COLOR_3DDKSHADOW)),
1126 hpenGrey(GetSysColor(COLOR_3DSHADOW)),
1127 hpenLightGr(GetSysColor(COLOR_3DLIGHT)),
1128 hpenWhite(GetSysColor(COLOR_3DHILIGHT));
1129
1130 SelectInHDC selectPen(hdc, hpenBlack);
1131
1132 r.right--;
1133 r.bottom--;
1134
1135 if ( pushed )
1136 {
1137 DrawRect(hdc, r);
1138
1139 (void)SelectObject(hdc, hpenGrey);
1140 ::InflateRect(&r, -1, -1);
1141
1142 DrawRect(hdc, r);
1143 }
1144 else // !pushed
1145 {
1146 if ( selected )
1147 {
1148 DrawRect(hdc, r);
1149
1150 ::InflateRect(&r, -1, -1);
1151 }
1152
1153 wxDrawLine(hdc, r.left, r.bottom, r.right, r.bottom);
1154 wxDrawLine(hdc, r.right, r.bottom, r.right, r.top - 1);
1155
1156 (void)SelectObject(hdc, hpenWhite);
1157 wxDrawLine(hdc, r.left, r.bottom - 1, r.left, r.top);
1158 wxDrawLine(hdc, r.left, r.top, r.right, r.top);
1159
1160 (void)SelectObject(hdc, hpenLightGr);
1161 wxDrawLine(hdc, r.left + 1, r.bottom - 2, r.left + 1, r.top + 1);
1162 wxDrawLine(hdc, r.left + 1, r.top + 1, r.right - 1, r.top + 1);
1163
1164 (void)SelectObject(hdc, hpenGrey);
1165 wxDrawLine(hdc, r.left + 1, r.bottom - 1, r.right - 1, r.bottom - 1);
1166 wxDrawLine(hdc, r.right - 1, r.bottom - 1, r.right - 1, r.top);
1167 }
1168
1169 InflateRect(&rectBtn, -OD_BUTTON_MARGIN, -OD_BUTTON_MARGIN);
1170 }
1171
1172 #if wxUSE_UXTHEME
1173 void DrawXPBackground(wxButton *button, HDC hdc, RECT& rectBtn, UINT state)
1174 {
1175 wxUxThemeHandle theme(button, L"BUTTON");
1176
1177 // this array is indexed by wxButton::State values and so must be kept in
1178 // sync with it
1179 static const int uxStates[] =
1180 {
1181 PBS_NORMAL, PBS_HOT, PBS_PRESSED, PBS_DISABLED, PBS_DEFAULTED
1182 };
1183
1184 int iState = uxStates[GetButtonState(button, state)];
1185
1186 wxUxThemeEngine * const engine = wxUxThemeEngine::Get();
1187
1188 // draw parent background if needed
1189 if ( engine->IsThemeBackgroundPartiallyTransparent
1190 (
1191 theme,
1192 BP_PUSHBUTTON,
1193 iState
1194 ) )
1195 {
1196 engine->DrawThemeParentBackground(GetHwndOf(button), hdc, &rectBtn);
1197 }
1198
1199 // draw background
1200 engine->DrawThemeBackground(theme, hdc, BP_PUSHBUTTON, iState,
1201 &rectBtn, NULL);
1202
1203 // calculate content area margins
1204 MARGINS margins;
1205 engine->GetThemeMargins(theme, hdc, BP_PUSHBUTTON, iState,
1206 TMT_CONTENTMARGINS, &rectBtn, &margins);
1207 ::InflateRect(&rectBtn, -margins.cxLeftWidth, -margins.cyTopHeight);
1208 ::InflateRect(&rectBtn, -XP_BUTTON_EXTRA_MARGIN, -XP_BUTTON_EXTRA_MARGIN);
1209
1210 if ( button->UseBgCol() )
1211 {
1212 COLORREF colBg = wxColourToRGB(button->GetBackgroundColour());
1213 AutoHBRUSH hbrushBackground(colBg);
1214
1215 // don't overwrite the focus rect
1216 RECT rectClient;
1217 ::CopyRect(&rectClient, &rectBtn);
1218 ::InflateRect(&rectClient, -1, -1);
1219 FillRect(hdc, &rectClient, hbrushBackground);
1220 }
1221 }
1222 #endif // wxUSE_UXTHEME
1223
1224 } // anonymous namespace
1225
1226 // ----------------------------------------------------------------------------
1227 // owner drawn buttons support
1228 // ----------------------------------------------------------------------------
1229
1230 void wxButton::MakeOwnerDrawn()
1231 {
1232 long style = GetWindowLong(GetHwnd(), GWL_STYLE);
1233 if ( (style & BS_OWNERDRAW) != BS_OWNERDRAW )
1234 {
1235 // make it so
1236 style |= BS_OWNERDRAW;
1237 SetWindowLong(GetHwnd(), GWL_STYLE, style);
1238 }
1239 }
1240
1241 bool wxButton::SetBackgroundColour(const wxColour &colour)
1242 {
1243 if ( !wxControl::SetBackgroundColour(colour) )
1244 {
1245 // nothing to do
1246 return false;
1247 }
1248
1249 MakeOwnerDrawn();
1250
1251 Refresh();
1252
1253 return true;
1254 }
1255
1256 bool wxButton::SetForegroundColour(const wxColour &colour)
1257 {
1258 if ( !wxControl::SetForegroundColour(colour) )
1259 {
1260 // nothing to do
1261 return false;
1262 }
1263
1264 MakeOwnerDrawn();
1265
1266 Refresh();
1267
1268 return true;
1269 }
1270
1271 bool wxButton::MSWOnDraw(WXDRAWITEMSTRUCT *wxdis)
1272 {
1273 LPDRAWITEMSTRUCT lpDIS = (LPDRAWITEMSTRUCT)wxdis;
1274 HDC hdc = lpDIS->hDC;
1275
1276 UINT state = lpDIS->itemState;
1277 bool pushed = (SendMessage(GetHwnd(), BM_GETSTATE, 0, 0) & BST_PUSHED) != 0;
1278
1279 RECT rectBtn;
1280 CopyRect(&rectBtn, &lpDIS->rcItem);
1281
1282 // draw the button background
1283 if ( !HasFlag(wxBORDER_NONE) )
1284 {
1285 #if wxUSE_UXTHEME
1286 if ( wxUxThemeEngine::GetIfActive() )
1287 {
1288 DrawXPBackground(this, hdc, rectBtn, state);
1289 }
1290 else
1291 #endif // wxUSE_UXTHEME
1292 {
1293 COLORREF colBg = wxColourToRGB(GetBackgroundColour());
1294
1295 // first, draw the background
1296 AutoHBRUSH hbrushBackground(colBg);
1297 FillRect(hdc, &rectBtn, hbrushBackground);
1298
1299 // draw the border for the current state
1300 bool selected = (state & ODS_SELECTED) != 0;
1301 if ( !selected )
1302 {
1303 wxTopLevelWindow *
1304 tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow);
1305 if ( tlw )
1306 {
1307 selected = tlw->GetDefaultItem() == this;
1308 }
1309 }
1310
1311 DrawButtonFrame(hdc, rectBtn, selected, pushed);
1312 }
1313
1314 // draw the focus rectangle if we need it
1315 if ( (state & ODS_FOCUS) && !(state & ODS_NOFOCUSRECT) )
1316 {
1317 DrawFocusRect(hdc, &rectBtn);
1318
1319 #if wxUSE_UXTHEME
1320 if ( !wxUxThemeEngine::GetIfActive() )
1321 #endif // wxUSE_UXTHEME
1322 {
1323 if ( pushed )
1324 {
1325 // the label is shifted by 1 pixel to create "pushed" effect
1326 OffsetRect(&rectBtn, 1, 1);
1327 }
1328 }
1329 }
1330 }
1331
1332
1333 // draw the image, if any
1334 if ( m_imageData )
1335 {
1336 wxBitmap bmp = m_imageData->GetBitmap(GetButtonState(this, state));
1337 if ( !bmp.IsOk() )
1338 bmp = m_imageData->GetBitmap(State_Normal);
1339
1340 const wxSize sizeBmp = bmp.GetSize();
1341 const wxSize margin = m_imageData->GetBitmapMargins();
1342 const wxSize sizeBmpWithMargins(sizeBmp + 2*margin);
1343 wxRect rectButton(wxRectFromRECT(rectBtn));
1344
1345 // for simplicity, we start with centred rectangle and then move it to
1346 // the appropriate edge
1347 wxRect rectBitmap = wxRect(sizeBmp).CentreIn(rectButton);
1348
1349 // move bitmap only if we have a label, otherwise keep it centered
1350 if ( ShowsLabel() )
1351 {
1352 switch ( m_imageData->GetBitmapPosition() )
1353 {
1354 default:
1355 wxFAIL_MSG( "invalid direction" );
1356 // fall through
1357
1358 case wxLEFT:
1359 rectBitmap.x = rectButton.x + margin.x;
1360 rectButton.x += sizeBmpWithMargins.x;
1361 rectButton.width -= sizeBmpWithMargins.x;
1362 break;
1363
1364 case wxRIGHT:
1365 rectBitmap.x = rectButton.GetRight() - sizeBmp.x - margin.x;
1366 rectButton.width -= sizeBmpWithMargins.x;
1367 break;
1368
1369 case wxTOP:
1370 rectBitmap.y = rectButton.y + margin.y;
1371 rectButton.y += sizeBmpWithMargins.y;
1372 rectButton.height -= sizeBmpWithMargins.y;
1373 break;
1374
1375 case wxBOTTOM:
1376 rectBitmap.y = rectButton.GetBottom() - sizeBmp.y - margin.y;
1377 rectButton.height -= sizeBmpWithMargins.y;
1378 break;
1379 }
1380 }
1381
1382 wxDCTemp dst((WXHDC)hdc);
1383 dst.DrawBitmap(bmp, rectBitmap.GetPosition(), true);
1384
1385 wxCopyRectToRECT(rectButton, rectBtn);
1386 }
1387
1388
1389 // finally draw the label
1390 if ( ShowsLabel() )
1391 {
1392 COLORREF colFg = state & ODS_DISABLED
1393 ? ::GetSysColor(COLOR_GRAYTEXT)
1394 : wxColourToRGB(GetForegroundColour());
1395
1396 // notice that DT_HIDEPREFIX doesn't work on old (pre-Windows 2000)
1397 // systems but by happy coincidence ODS_NOACCEL is not used under them
1398 // neither so DT_HIDEPREFIX should never be used there
1399 DrawButtonText(hdc, &rectBtn, GetLabel(), colFg,
1400 state & ODS_NOACCEL ? DT_HIDEPREFIX : 0);
1401 }
1402
1403 return true;
1404 }
1405
1406 #endif // wxUSE_BUTTON
1407