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