Automatically adjust toolbar's tool size if the provided bitmaps
[wxWidgets.git] / src / msw / toolbar.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/toolbar.cpp
3 // Purpose: wxToolBar
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_TOOLBAR && wxUSE_TOOLBAR_NATIVE && !defined(__SMARTPHONE__)
28
29 #include "wx/toolbar.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/dynarray.h"
34 #include "wx/frame.h"
35 #include "wx/log.h"
36 #include "wx/intl.h"
37 #include "wx/settings.h"
38 #include "wx/bitmap.h"
39 #include "wx/dcmemory.h"
40 #include "wx/control.h"
41 #include "wx/app.h" // for GetComCtl32Version
42 #include "wx/image.h"
43 #include "wx/stattext.h"
44 #endif
45
46 #include "wx/artprov.h"
47 #include "wx/sysopt.h"
48 #include "wx/dcclient.h"
49
50 #include "wx/msw/private.h"
51 #include "wx/msw/dc.h"
52
53 #if wxUSE_UXTHEME
54 #include "wx/msw/uxtheme.h"
55 #endif
56
57 // this define controls whether the code for button colours remapping (only
58 // useful for 16 or 256 colour images) is active at all, it's always turned off
59 // for CE where it doesn't compile (and is probably not needed anyhow) and may
60 // also be turned off for other systems if you always use 24bpp images and so
61 // never need it
62 #ifndef __WXWINCE__
63 #define wxREMAP_BUTTON_COLOURS
64 #endif // !__WXWINCE__
65
66 // ----------------------------------------------------------------------------
67 // constants
68 // ----------------------------------------------------------------------------
69
70 // these standard constants are not always defined in compilers headers
71
72 // Styles
73 #ifndef TBSTYLE_FLAT
74 #define TBSTYLE_LIST 0x1000
75 #define TBSTYLE_FLAT 0x0800
76 #endif
77
78 #ifndef TBSTYLE_TRANSPARENT
79 #define TBSTYLE_TRANSPARENT 0x8000
80 #endif
81
82 #ifndef TBSTYLE_TOOLTIPS
83 #define TBSTYLE_TOOLTIPS 0x0100
84 #endif
85
86 // Messages
87 #ifndef TB_GETSTYLE
88 #define TB_SETSTYLE (WM_USER + 56)
89 #define TB_GETSTYLE (WM_USER + 57)
90 #endif
91
92 #ifndef TB_HITTEST
93 #define TB_HITTEST (WM_USER + 69)
94 #endif
95
96 #ifndef TB_GETMAXSIZE
97 #define TB_GETMAXSIZE (WM_USER + 83)
98 #endif
99
100 // ----------------------------------------------------------------------------
101 // wxWin macros
102 // ----------------------------------------------------------------------------
103
104 IMPLEMENT_DYNAMIC_CLASS(wxToolBar, wxControl)
105
106 /*
107 TOOLBAR PROPERTIES
108 tool
109 bitmap
110 bitmap2
111 tooltip
112 longhelp
113 radio (bool)
114 toggle (bool)
115 separator
116 style ( wxNO_BORDER | wxTB_HORIZONTAL)
117 bitmapsize
118 margins
119 packing
120 separation
121
122 dontattachtoframe
123 */
124
125 BEGIN_EVENT_TABLE(wxToolBar, wxToolBarBase)
126 EVT_MOUSE_EVENTS(wxToolBar::OnMouseEvent)
127 EVT_SYS_COLOUR_CHANGED(wxToolBar::OnSysColourChanged)
128 EVT_ERASE_BACKGROUND(wxToolBar::OnEraseBackground)
129 END_EVENT_TABLE()
130
131 // ----------------------------------------------------------------------------
132 // private classes
133 // ----------------------------------------------------------------------------
134
135 class wxToolBarTool : public wxToolBarToolBase
136 {
137 public:
138 wxToolBarTool(wxToolBar *tbar,
139 int id,
140 const wxString& label,
141 const wxBitmap& bmpNormal,
142 const wxBitmap& bmpDisabled,
143 wxItemKind kind,
144 wxObject *clientData,
145 const wxString& shortHelp,
146 const wxString& longHelp)
147 : wxToolBarToolBase(tbar, id, label, bmpNormal, bmpDisabled, kind,
148 clientData, shortHelp, longHelp)
149 {
150 m_nSepCount = 0;
151 m_staticText = 0;
152 }
153
154 wxToolBarTool(wxToolBar *tbar, wxControl *control, const wxString& label)
155 : wxToolBarToolBase(tbar, control, label)
156 {
157 if ( IsControl() && !m_label.empty() )
158 {
159 // create a control to render the control's label
160 m_staticText = new wxStaticText
161 (
162 m_tbar,
163 wxID_ANY,
164 m_label,
165 wxDefaultPosition,
166 wxDefaultSize,
167 wxALIGN_CENTRE | wxST_NO_AUTORESIZE
168 );
169 }
170 else // no label
171 {
172 m_staticText = NULL;
173 }
174
175 m_nSepCount = 1;
176 }
177
178 virtual ~wxToolBarTool()
179 {
180 delete m_staticText;
181 }
182
183 virtual void SetLabel(const wxString& label)
184 {
185 if ( label == m_label )
186 return;
187
188 wxToolBarToolBase::SetLabel(label);
189
190 if ( m_staticText )
191 m_staticText->SetLabel(label);
192
193 // we need to update the label shown in the toolbar because it has a
194 // pointer to the internal buffer of the old label
195 //
196 // TODO: use TB_SETBUTTONINFO
197 }
198
199 wxStaticText* GetStaticText()
200 {
201 wxASSERT_MSG( IsControl(),
202 _T("only makes sense for embedded control tools") );
203
204 return m_staticText;
205 }
206
207 // set/get the number of separators which we use to cover the space used by
208 // a control in the toolbar
209 void SetSeparatorsCount(size_t count) { m_nSepCount = count; }
210 size_t GetSeparatorsCount() const { return m_nSepCount; }
211
212 private:
213 size_t m_nSepCount;
214 wxStaticText *m_staticText;
215
216 DECLARE_NO_COPY_CLASS(wxToolBarTool)
217 };
218
219 // ----------------------------------------------------------------------------
220 // helper functions
221 // ----------------------------------------------------------------------------
222
223 // return the rectangle of the item at the given index
224 //
225 // returns an empty (0, 0, 0, 0) rectangle if fails so the caller may compare
226 // r.right or r.bottom with 0 to check for this
227 static RECT wxGetTBItemRect(HWND hwnd, int index)
228 {
229 RECT r;
230
231 // note that we use TB_GETITEMRECT and not TB_GETRECT because the latter
232 // only appeared in v4.70 of comctl32.dll
233 if ( !::SendMessage(hwnd, TB_GETITEMRECT, index, (LPARAM)&r) )
234 {
235 wxLogLastError(wxT("TB_GETITEMRECT"));
236
237 r.top =
238 r.left =
239 r.right =
240 r.bottom = 0;
241 }
242
243 return r;
244 }
245
246 // ============================================================================
247 // implementation
248 // ============================================================================
249
250 // ----------------------------------------------------------------------------
251 // wxToolBarTool
252 // ----------------------------------------------------------------------------
253
254 wxToolBarToolBase *wxToolBar::CreateTool(int id,
255 const wxString& label,
256 const wxBitmap& bmpNormal,
257 const wxBitmap& bmpDisabled,
258 wxItemKind kind,
259 wxObject *clientData,
260 const wxString& shortHelp,
261 const wxString& longHelp)
262 {
263 return new wxToolBarTool(this, id, label, bmpNormal, bmpDisabled, kind,
264 clientData, shortHelp, longHelp);
265 }
266
267 wxToolBarToolBase *
268 wxToolBar::CreateTool(wxControl *control, const wxString& label)
269 {
270 return new wxToolBarTool(this, control, label);
271 }
272
273 // ----------------------------------------------------------------------------
274 // wxToolBar construction
275 // ----------------------------------------------------------------------------
276
277 void wxToolBar::Init()
278 {
279 m_hBitmap = 0;
280 m_disabledImgList = NULL;
281
282 m_nButtons = 0;
283
284 const wxSize size = wxArtProvider::GetNativeSizeHint(wxART_TOOLBAR);
285 m_defaultWidth = size.x;
286 m_defaultHeight = size.y;
287
288 m_pInTool = NULL;
289 }
290
291 bool wxToolBar::Create(wxWindow *parent,
292 wxWindowID id,
293 const wxPoint& pos,
294 const wxSize& size,
295 long style,
296 const wxString& name)
297 {
298 // common initialisation
299 if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
300 return false;
301
302 FixupStyle();
303
304 // MSW-specific initialisation
305 if ( !MSWCreateToolbar(pos, size) )
306 return false;
307
308 wxSetCCUnicodeFormat(GetHwnd());
309
310 // workaround for flat toolbar on Windows XP classic style: we have to set
311 // the style after creating the control; doing it at creation time doesn't work
312 #if wxUSE_UXTHEME
313 if ( style & wxTB_FLAT )
314 {
315 LRESULT style = GetMSWToolbarStyle();
316
317 if ( !(style & TBSTYLE_FLAT) )
318 ::SendMessage(GetHwnd(), TB_SETSTYLE, 0, style | TBSTYLE_FLAT);
319 }
320 #endif // wxUSE_UXTHEME
321
322 return true;
323 }
324
325 bool wxToolBar::MSWCreateToolbar(const wxPoint& pos, const wxSize& size)
326 {
327 if ( !MSWCreateControl(TOOLBARCLASSNAME, wxEmptyString, pos, size) )
328 return false;
329
330 // toolbar-specific post initialisation
331 ::SendMessage(GetHwnd(), TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);
332
333 #ifdef TB_SETEXTENDEDSTYLE
334 if ( wxApp::GetComCtl32Version() >= 471 )
335 ::SendMessage(GetHwnd(), TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_DRAWDDARROWS);
336 #endif
337
338 return true;
339 }
340
341 void wxToolBar::Recreate()
342 {
343 const HWND hwndOld = GetHwnd();
344 if ( !hwndOld )
345 {
346 // we haven't been created yet, no need to recreate
347 return;
348 }
349
350 // get the position and size before unsubclassing the old toolbar
351 const wxPoint pos = GetPosition();
352 const wxSize size = GetSize();
353
354 UnsubclassWin();
355
356 if ( !MSWCreateToolbar(pos, size) )
357 {
358 // what can we do?
359 wxFAIL_MSG( _T("recreating the toolbar failed") );
360
361 return;
362 }
363
364 // reparent all our children under the new toolbar
365 for ( wxWindowList::compatibility_iterator node = m_children.GetFirst();
366 node;
367 node = node->GetNext() )
368 {
369 wxWindow *win = node->GetData();
370 if ( !win->IsTopLevel() )
371 ::SetParent(GetHwndOf(win), GetHwnd());
372 }
373
374 // only destroy the old toolbar now --
375 // after all the children had been reparented
376 ::DestroyWindow(hwndOld);
377
378 // it is for the old bitmap control and can't be used with the new one
379 if ( m_hBitmap )
380 {
381 ::DeleteObject((HBITMAP) m_hBitmap);
382 m_hBitmap = 0;
383 }
384
385 if ( m_disabledImgList )
386 {
387 delete m_disabledImgList;
388 m_disabledImgList = NULL;
389 }
390
391 Realize();
392 }
393
394 wxToolBar::~wxToolBar()
395 {
396 // we must refresh the frame size when the toolbar is deleted but the frame
397 // is not - otherwise toolbar leaves a hole in the place it used to occupy
398 SendSizeEventToParent();
399
400 if ( m_hBitmap )
401 ::DeleteObject((HBITMAP) m_hBitmap);
402
403 delete m_disabledImgList;
404 }
405
406 wxSize wxToolBar::DoGetBestSize() const
407 {
408 wxSize sizeBest;
409
410 SIZE size;
411 if ( !::SendMessage(GetHwnd(), TB_GETMAXSIZE, 0, (LPARAM)&size) )
412 {
413 // maybe an old (< 0x400) Windows version? try to approximate the
414 // toolbar size ourselves
415 sizeBest = GetToolSize();
416 sizeBest.y += 2 * ::GetSystemMetrics(SM_CYBORDER); // Add borders
417 sizeBest.x *= GetToolsCount();
418
419 // reverse horz and vertical components if necessary
420 if ( IsVertical() )
421 {
422 int t = sizeBest.x;
423 sizeBest.x = sizeBest.y;
424 sizeBest.y = t;
425 }
426 }
427 else // TB_GETMAXSIZE succeeded
428 {
429 // but it could still return an incorrect result due to what appears to
430 // be a bug in old comctl32.dll versions which don't handle controls in
431 // the toolbar correctly, so work around it (see SF patch 1902358)
432 if ( !IsVertical() && wxApp::GetComCtl32Version() < 600 )
433 {
434 // calculate the toolbar width in alternative way
435 const RECT rcFirst = wxGetTBItemRect(GetHwnd(), 0);
436 const RECT rcLast = wxGetTBItemRect(GetHwnd(), GetToolsCount() - 1);
437
438 const int widthAlt = rcLast.right - rcFirst.left;
439 if ( widthAlt > size.cx )
440 size.cx = widthAlt;
441 }
442
443 sizeBest.x = size.cx;
444 sizeBest.y = size.cy;
445 }
446
447 if ( !IsVertical() )
448 {
449 // Without the extra height, DoGetBestSize can report a size that's
450 // smaller than the actual window, causing windows to overlap slightly
451 // in some circumstances, leading to missing borders (especially noticeable
452 // in AUI layouts).
453 if (!(GetWindowStyle() & wxTB_NODIVIDER))
454 sizeBest.y += 2;
455 sizeBest.y ++;
456 }
457
458 CacheBestSize(sizeBest);
459
460 return sizeBest;
461 }
462
463 WXDWORD wxToolBar::MSWGetStyle(long style, WXDWORD *exstyle) const
464 {
465 // toolbars never have border, giving one to them results in broken
466 // appearance
467 WXDWORD msStyle = wxControl::MSWGetStyle
468 (
469 (style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
470 );
471
472 if ( !(style & wxTB_NO_TOOLTIPS) )
473 msStyle |= TBSTYLE_TOOLTIPS;
474
475 if ( style & (wxTB_FLAT | wxTB_HORZ_LAYOUT) )
476 {
477 // static as it doesn't change during the program lifetime
478 static const int s_verComCtl = wxApp::GetComCtl32Version();
479
480 // comctl32.dll 4.00 doesn't support the flat toolbars and using this
481 // style with 6.00 (part of Windows XP) leads to the toolbar with
482 // incorrect background colour - and not using it still results in the
483 // correct (flat) toolbar, so don't use it there
484 if ( s_verComCtl > 400 && s_verComCtl < 600 )
485 msStyle |= TBSTYLE_FLAT | TBSTYLE_TRANSPARENT;
486
487 if ( s_verComCtl >= 470 && style & wxTB_HORZ_LAYOUT )
488 msStyle |= TBSTYLE_LIST;
489 }
490
491 if ( style & wxTB_NODIVIDER )
492 msStyle |= CCS_NODIVIDER;
493
494 if ( style & wxTB_NOALIGN )
495 msStyle |= CCS_NOPARENTALIGN;
496
497 if ( style & wxTB_VERTICAL )
498 msStyle |= CCS_VERT;
499
500 if( style & wxTB_BOTTOM )
501 msStyle |= CCS_BOTTOM;
502
503 if ( style & wxTB_RIGHT )
504 msStyle |= CCS_RIGHT;
505
506 return msStyle;
507 }
508
509 // ----------------------------------------------------------------------------
510 // adding/removing tools
511 // ----------------------------------------------------------------------------
512
513 bool wxToolBar::DoInsertTool(size_t WXUNUSED(pos),
514 wxToolBarToolBase * WXUNUSED(tool))
515 {
516 // nothing special to do here - we really create the toolbar buttons in
517 // Realize() later
518 InvalidateBestSize();
519 return true;
520 }
521
522 bool wxToolBar::DoDeleteTool(size_t pos, wxToolBarToolBase *tool)
523 {
524 // the main difficulty we have here is with the controls in the toolbars:
525 // as we (sometimes) use several separators to cover up the space used by
526 // them, the indices are not the same for us and the toolbar
527
528 // first determine the position of the first button to delete: it may be
529 // different from pos if we use several separators to cover the space used
530 // by a control
531 wxToolBarToolsList::compatibility_iterator node;
532 for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
533 {
534 wxToolBarToolBase *tool2 = node->GetData();
535 if ( tool2 == tool )
536 {
537 // let node point to the next node in the list
538 node = node->GetNext();
539
540 break;
541 }
542
543 if ( tool2->IsControl() )
544 pos += ((wxToolBarTool *)tool2)->GetSeparatorsCount() - 1;
545 }
546
547 // now determine the number of buttons to delete and the area taken by them
548 size_t nButtonsToDelete = 1;
549
550 // get the size of the button we're going to delete
551 const RECT r = wxGetTBItemRect(GetHwnd(), pos);
552
553 int width = r.right - r.left;
554
555 if ( tool->IsControl() )
556 {
557 nButtonsToDelete = ((wxToolBarTool *)tool)->GetSeparatorsCount();
558 width *= nButtonsToDelete;
559 }
560
561 // do delete all buttons
562 m_nButtons -= nButtonsToDelete;
563 while ( nButtonsToDelete-- > 0 )
564 {
565 if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, pos, 0) )
566 {
567 wxLogLastError(wxT("TB_DELETEBUTTON"));
568
569 return false;
570 }
571 }
572
573 // and finally reposition all the controls after this button (the toolbar
574 // takes care of all normal items)
575 for ( /* node -> first after deleted */ ; node; node = node->GetNext() )
576 {
577 wxToolBarTool *tool2 = (wxToolBarTool*)node->GetData();
578 if ( tool2->IsControl() )
579 {
580 wxControl * const control = tool2->GetControl();
581
582 int x;
583 control->GetPosition(&x, NULL);
584 control->Move(x - width, wxDefaultCoord);
585
586 wxStaticText * const staticText = tool2->GetStaticText();
587 if ( staticText )
588 staticText->Move(x - width, wxDefaultCoord);
589 }
590 }
591
592 InvalidateBestSize();
593
594 return true;
595 }
596
597 void wxToolBar::CreateDisabledImageList()
598 {
599 if (m_disabledImgList != NULL)
600 {
601 delete m_disabledImgList;
602 m_disabledImgList = NULL;
603 }
604
605 // as we can't use disabled image list with older versions of comctl32.dll,
606 // don't even bother creating it
607 if ( wxApp::GetComCtl32Version() >= 470 )
608 {
609 // search for the first disabled button img in the toolbar, if any
610 for ( wxToolBarToolsList::compatibility_iterator
611 node = m_tools.GetFirst(); node; node = node->GetNext() )
612 {
613 wxToolBarToolBase *tool = node->GetData();
614 wxBitmap bmpDisabled = tool->GetDisabledBitmap();
615 if ( bmpDisabled.Ok() )
616 {
617 m_disabledImgList = new wxImageList
618 (
619 m_defaultWidth,
620 m_defaultHeight,
621 bmpDisabled.GetMask() != NULL,
622 GetToolsCount()
623 );
624 break;
625 }
626 }
627
628 // we don't have any disabled bitmaps
629 }
630 }
631
632 void wxToolBar::AdjustToolBitmapSize()
633 {
634 wxSize s(m_defaultWidth, m_defaultHeight);
635 const wxSize orig_s(s);
636
637 for ( wxToolBarToolsList::const_iterator i = m_tools.begin();
638 i != m_tools.end();
639 ++i )
640 {
641 const wxBitmap& bmp = (*i)->GetNormalBitmap();
642 s.IncTo(bmp.GetSize());
643 }
644
645 if ( s != orig_s )
646 SetToolBitmapSize(s);
647 }
648
649 bool wxToolBar::Realize()
650 {
651 const size_t nTools = GetToolsCount();
652 if ( nTools == 0 )
653 // nothing to do
654 return true;
655
656 // make sure tool size is larger enough for all all bitmaps to fit in
657 // (this is consistent with what other ports do):
658 AdjustToolBitmapSize();
659
660 #ifdef wxREMAP_BUTTON_COLOURS
661 // don't change the values of these constants, they can be set from the
662 // user code via wxSystemOptions
663 enum
664 {
665 Remap_None = -1,
666 Remap_Bg,
667 Remap_Buttons,
668 Remap_TransparentBg
669 };
670
671 // the user-specified option overrides anything, but if it wasn't set, only
672 // remap the buttons on 8bpp displays as otherwise the bitmaps usually look
673 // much worse after remapping
674 static const wxChar *remapOption = wxT("msw.remap");
675 const int remapValue = wxSystemOptions::HasOption(remapOption)
676 ? wxSystemOptions::GetOptionInt(remapOption)
677 : wxDisplayDepth() <= 8 ? Remap_Buttons
678 : Remap_None;
679
680 #endif // wxREMAP_BUTTON_COLOURS
681
682 // delete all old buttons, if any
683 for ( size_t pos = 0; pos < m_nButtons; pos++ )
684 {
685 if ( !::SendMessage(GetHwnd(), TB_DELETEBUTTON, 0, 0) )
686 {
687 wxLogDebug(wxT("TB_DELETEBUTTON failed"));
688 }
689 }
690
691 // First, add the bitmap: we use one bitmap for all toolbar buttons
692 // ----------------------------------------------------------------
693
694 wxToolBarToolsList::compatibility_iterator node;
695 int bitmapId = 0;
696
697 wxSize sizeBmp;
698 if ( HasFlag(wxTB_NOICONS) )
699 {
700 // no icons, don't leave space for them
701 sizeBmp.x =
702 sizeBmp.y = 0;
703 }
704 else // do show icons
705 {
706 // if we already have a bitmap, we'll replace the existing one --
707 // otherwise we'll install a new one
708 HBITMAP oldToolBarBitmap = (HBITMAP)m_hBitmap;
709
710 sizeBmp.x = m_defaultWidth;
711 sizeBmp.y = m_defaultHeight;
712
713 const wxCoord totalBitmapWidth = m_defaultWidth *
714 wx_truncate_cast(wxCoord, nTools),
715 totalBitmapHeight = m_defaultHeight;
716
717 // Create a bitmap and copy all the tool bitmaps into it
718 wxMemoryDC dcAllButtons;
719 wxBitmap bitmap(totalBitmapWidth, totalBitmapHeight);
720 dcAllButtons.SelectObject(bitmap);
721
722 #ifdef wxREMAP_BUTTON_COLOURS
723 if ( remapValue != Remap_TransparentBg )
724 #endif // wxREMAP_BUTTON_COLOURS
725 {
726 // VZ: why do we hardcode grey colour for CE?
727 dcAllButtons.SetBackground(wxBrush(
728 #ifdef __WXWINCE__
729 wxColour(0xc0, 0xc0, 0xc0)
730 #else // !__WXWINCE__
731 GetBackgroundColour()
732 #endif // __WXWINCE__/!__WXWINCE__
733 ));
734 dcAllButtons.Clear();
735 }
736
737 m_hBitmap = bitmap.GetHBITMAP();
738 HBITMAP hBitmap = (HBITMAP)m_hBitmap;
739
740 #ifdef wxREMAP_BUTTON_COLOURS
741 if ( remapValue == Remap_Bg )
742 {
743 dcAllButtons.SelectObject(wxNullBitmap);
744
745 // Even if we're not remapping the bitmap
746 // content, we still have to remap the background.
747 hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap,
748 totalBitmapWidth, totalBitmapHeight);
749
750 dcAllButtons.SelectObject(bitmap);
751 }
752 #endif // wxREMAP_BUTTON_COLOURS
753
754 // the button position
755 wxCoord x = 0;
756
757 // the number of buttons (not separators)
758 int nButtons = 0;
759
760 CreateDisabledImageList();
761 for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
762 {
763 wxToolBarToolBase *tool = node->GetData();
764 if ( tool->IsButton() )
765 {
766 const wxBitmap& bmp = tool->GetNormalBitmap();
767
768 const int w = bmp.GetWidth();
769 const int h = bmp.GetHeight();
770
771 if ( bmp.Ok() )
772 {
773 int xOffset = wxMax(0, (m_defaultWidth - w)/2);
774 int yOffset = wxMax(0, (m_defaultHeight - h)/2);
775
776 // notice the last parameter: do use mask
777 dcAllButtons.DrawBitmap(bmp, x + xOffset, yOffset, true);
778 }
779 else
780 {
781 wxFAIL_MSG( _T("invalid tool button bitmap") );
782 }
783
784 // also deal with disabled bitmap if we want to use them
785 if ( m_disabledImgList )
786 {
787 wxBitmap bmpDisabled = tool->GetDisabledBitmap();
788 #if wxUSE_IMAGE && wxUSE_WXDIB
789 if ( !bmpDisabled.Ok() )
790 {
791 // no disabled bitmap specified but we still need to
792 // fill the space in the image list with something, so
793 // we grey out the normal bitmap
794 wxImage
795 imgGreyed = bmp.ConvertToImage().ConvertToGreyscale();
796
797 #ifdef wxREMAP_BUTTON_COLOURS
798 if ( remapValue == Remap_Buttons )
799 {
800 // we need to have light grey background colour for
801 // MapBitmap() to work correctly
802 for ( int y = 0; y < h; y++ )
803 {
804 for ( int x = 0; x < w; x++ )
805 {
806 if ( imgGreyed.IsTransparent(x, y) )
807 imgGreyed.SetRGB(x, y,
808 wxLIGHT_GREY->Red(),
809 wxLIGHT_GREY->Green(),
810 wxLIGHT_GREY->Blue());
811 }
812 }
813 }
814 #endif // wxREMAP_BUTTON_COLOURS
815
816 bmpDisabled = wxBitmap(imgGreyed);
817 }
818 #endif // wxUSE_IMAGE
819
820 #ifdef wxREMAP_BUTTON_COLOURS
821 if ( remapValue == Remap_Buttons )
822 MapBitmap(bmpDisabled.GetHBITMAP(), w, h);
823 #endif // wxREMAP_BUTTON_COLOURS
824
825 m_disabledImgList->Add(bmpDisabled);
826 }
827
828 // still inc width and number of buttons because otherwise the
829 // subsequent buttons will all be shifted which is rather confusing
830 // (and like this you'd see immediately which bitmap was bad)
831 x += m_defaultWidth;
832 nButtons++;
833 }
834 }
835
836 dcAllButtons.SelectObject(wxNullBitmap);
837
838 // don't delete this HBITMAP!
839 bitmap.SetHBITMAP(0);
840
841 #ifdef wxREMAP_BUTTON_COLOURS
842 if ( remapValue == Remap_Buttons )
843 {
844 // Map to system colours
845 hBitmap = (HBITMAP)MapBitmap((WXHBITMAP) hBitmap,
846 totalBitmapWidth, totalBitmapHeight);
847 }
848 #endif // wxREMAP_BUTTON_COLOURS
849
850 bool addBitmap = true;
851
852 if ( oldToolBarBitmap )
853 {
854 #ifdef TB_REPLACEBITMAP
855 if ( wxApp::GetComCtl32Version() >= 400 )
856 {
857 TBREPLACEBITMAP replaceBitmap;
858 replaceBitmap.hInstOld = NULL;
859 replaceBitmap.hInstNew = NULL;
860 replaceBitmap.nIDOld = (UINT_PTR)oldToolBarBitmap;
861 replaceBitmap.nIDNew = (UINT_PTR)hBitmap;
862 replaceBitmap.nButtons = nButtons;
863 if ( !::SendMessage(GetHwnd(), TB_REPLACEBITMAP,
864 0, (LPARAM) &replaceBitmap) )
865 {
866 wxFAIL_MSG(wxT("Could not replace the old bitmap"));
867 }
868
869 ::DeleteObject(oldToolBarBitmap);
870
871 // already done
872 addBitmap = false;
873 }
874 else
875 #endif // TB_REPLACEBITMAP
876 {
877 // we can't replace the old bitmap, so we will add another one
878 // (awfully inefficient, but what else to do?) and shift the bitmap
879 // indices accordingly
880 addBitmap = true;
881
882 bitmapId = m_nButtons;
883 }
884 }
885
886 if ( addBitmap ) // no old bitmap or we can't replace it
887 {
888 TBADDBITMAP addBitmap;
889 addBitmap.hInst = 0;
890 addBitmap.nID = (UINT_PTR)hBitmap;
891 if ( ::SendMessage(GetHwnd(), TB_ADDBITMAP,
892 (WPARAM) nButtons, (LPARAM)&addBitmap) == -1 )
893 {
894 wxFAIL_MSG(wxT("Could not add bitmap to toolbar"));
895 }
896 }
897
898 // disable image lists are only supported in comctl32.dll 4.70+
899 if ( wxApp::GetComCtl32Version() >= 470 )
900 {
901 HIMAGELIST hil = m_disabledImgList
902 ? GetHimagelistOf(m_disabledImgList)
903 : 0;
904
905 // notice that we set the image list even if don't have one right
906 // now as we could have it before and need to reset it in this case
907 HIMAGELIST oldImageList = (HIMAGELIST)
908 ::SendMessage(GetHwnd(), TB_SETDISABLEDIMAGELIST, 0, (LPARAM)hil);
909
910 // delete previous image list if any
911 if ( oldImageList )
912 ::DeleteObject(oldImageList);
913 }
914 }
915
916 // don't call SetToolBitmapSize() as we don't want to change the values of
917 // m_defaultWidth/Height
918 if ( !::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0,
919 MAKELONG(sizeBmp.x, sizeBmp.y)) )
920 {
921 wxLogLastError(_T("TB_SETBITMAPSIZE"));
922 }
923
924 // Next add the buttons and separators
925 // -----------------------------------
926
927 TBBUTTON *buttons = new TBBUTTON[nTools];
928
929 // this array will hold the indices of all controls in the toolbar
930 wxArrayInt controlIds;
931
932 bool lastWasRadio = false;
933 int i = 0;
934 for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
935 {
936 wxToolBarToolBase *tool = node->GetData();
937
938 // don't add separators to the vertical toolbar with old comctl32.dll
939 // versions as they didn't handle this properly
940 if ( IsVertical() && tool->IsSeparator() &&
941 wxApp::GetComCtl32Version() <= 472 )
942 {
943 continue;
944 }
945
946 TBBUTTON& button = buttons[i];
947
948 wxZeroMemory(button);
949
950 bool isRadio = false;
951 switch ( tool->GetStyle() )
952 {
953 case wxTOOL_STYLE_CONTROL:
954 button.idCommand = tool->GetId();
955 // fall through: create just a separator too
956
957 case wxTOOL_STYLE_SEPARATOR:
958 button.fsState = TBSTATE_ENABLED;
959 button.fsStyle = TBSTYLE_SEP;
960 break;
961
962 case wxTOOL_STYLE_BUTTON:
963 if ( !HasFlag(wxTB_NOICONS) )
964 button.iBitmap = bitmapId;
965
966 if ( HasFlag(wxTB_TEXT) )
967 {
968 const wxString& label = tool->GetLabel();
969 if ( !label.empty() )
970 button.iString = (INT_PTR)label.wx_str();
971 }
972
973 button.idCommand = tool->GetId();
974
975 if ( tool->IsEnabled() )
976 button.fsState |= TBSTATE_ENABLED;
977 if ( tool->IsToggled() )
978 button.fsState |= TBSTATE_CHECKED;
979
980 switch ( tool->GetKind() )
981 {
982 case wxITEM_RADIO:
983 button.fsStyle = TBSTYLE_CHECKGROUP;
984
985 if ( !lastWasRadio )
986 {
987 // the first item in the radio group is checked by
988 // default to be consistent with wxGTK and the menu
989 // radio items
990 button.fsState |= TBSTATE_CHECKED;
991
992 if (tool->Toggle(true))
993 {
994 DoToggleTool(tool, true);
995 }
996 }
997 else if ( tool->IsToggled() )
998 {
999 wxToolBarToolsList::compatibility_iterator nodePrev = node->GetPrevious();
1000 int prevIndex = i - 1;
1001 while ( nodePrev )
1002 {
1003 TBBUTTON& prevButton = buttons[prevIndex];
1004 wxToolBarToolBase *tool = nodePrev->GetData();
1005 if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO )
1006 break;
1007
1008 if ( tool->Toggle(false) )
1009 DoToggleTool(tool, false);
1010
1011 prevButton.fsState &= ~TBSTATE_CHECKED;
1012 nodePrev = nodePrev->GetPrevious();
1013 prevIndex--;
1014 }
1015 }
1016
1017 isRadio = true;
1018 break;
1019
1020 case wxITEM_CHECK:
1021 button.fsStyle = TBSTYLE_CHECK;
1022 break;
1023
1024 case wxITEM_NORMAL:
1025 button.fsStyle = TBSTYLE_BUTTON;
1026 break;
1027
1028 case wxITEM_DROPDOWN:
1029 button.fsStyle = TBSTYLE_DROPDOWN;
1030 break;
1031
1032 default:
1033 wxFAIL_MSG( _T("unexpected toolbar button kind") );
1034 button.fsStyle = TBSTYLE_BUTTON;
1035 break;
1036 }
1037
1038 bitmapId++;
1039 break;
1040 }
1041
1042 lastWasRadio = isRadio;
1043
1044 i++;
1045 }
1046
1047 if ( !::SendMessage(GetHwnd(), TB_ADDBUTTONS, (WPARAM)i, (LPARAM)buttons) )
1048 {
1049 wxLogLastError(wxT("TB_ADDBUTTONS"));
1050 }
1051
1052 delete [] buttons;
1053
1054 // Deal with the controls finally
1055 // ------------------------------
1056
1057 // adjust the controls size to fit nicely in the toolbar
1058 int y = 0;
1059 size_t index = 0;
1060 for ( node = m_tools.GetFirst(); node; node = node->GetNext(), index++ )
1061 {
1062 wxToolBarTool *tool = (wxToolBarTool*)node->GetData();
1063
1064 // we calculate the running y coord for vertical toolbars so we need to
1065 // get the items size for all items but for the horizontal ones we
1066 // don't need to deal with the non controls
1067 bool isControl = tool->IsControl();
1068 if ( !isControl && !IsVertical() )
1069 continue;
1070
1071 const RECT r = wxGetTBItemRect(GetHwnd(), index);
1072 if ( !isControl )
1073 {
1074 // can only be control if isVertical
1075 y += r.bottom - r.top;
1076
1077 continue;
1078 }
1079
1080 wxControl *control = tool->GetControl();
1081 wxStaticText * const staticText = tool->GetStaticText();
1082
1083 wxSize size = control->GetSize();
1084 wxSize staticTextSize;
1085 if ( staticText )
1086 {
1087 staticTextSize = staticText->GetSize();
1088 staticTextSize.y += 3; // margin between control and its label
1089 }
1090
1091 // the position of the leftmost controls corner
1092 int left = wxDefaultCoord;
1093
1094 // TB_SETBUTTONINFO message is only supported by comctl32.dll 4.71+
1095 #ifdef TB_SETBUTTONINFO
1096 // available in headers, now check whether it is available now
1097 // (during run-time)
1098 if ( wxApp::GetComCtl32Version() >= 471 )
1099 {
1100 // set the (underlying) separators width to be that of the
1101 // control
1102 TBBUTTONINFO tbbi;
1103 tbbi.cbSize = sizeof(tbbi);
1104 tbbi.dwMask = TBIF_SIZE;
1105 tbbi.cx = (WORD)size.x;
1106 if ( !::SendMessage(GetHwnd(), TB_SETBUTTONINFO,
1107 tool->GetId(), (LPARAM)&tbbi) )
1108 {
1109 // the id is probably invalid?
1110 wxLogLastError(wxT("TB_SETBUTTONINFO"));
1111 }
1112 }
1113 else
1114 #endif // comctl32.dll 4.71
1115 // TB_SETBUTTONINFO unavailable
1116 {
1117 // try adding several separators to fit the controls width
1118 int widthSep = r.right - r.left;
1119 left = r.left;
1120
1121 TBBUTTON tbb;
1122 wxZeroMemory(tbb);
1123 tbb.idCommand = 0;
1124 tbb.fsState = TBSTATE_ENABLED;
1125 tbb.fsStyle = TBSTYLE_SEP;
1126
1127 size_t nSeparators = size.x / widthSep;
1128 for ( size_t nSep = 0; nSep < nSeparators; nSep++ )
1129 {
1130 if ( !::SendMessage(GetHwnd(), TB_INSERTBUTTON,
1131 index, (LPARAM)&tbb) )
1132 {
1133 wxLogLastError(wxT("TB_INSERTBUTTON"));
1134 }
1135
1136 index++;
1137 }
1138
1139 // remember the number of separators we used - we'd have to
1140 // delete all of them later
1141 ((wxToolBarTool *)tool)->SetSeparatorsCount(nSeparators);
1142
1143 // adjust the controls width to exactly cover the separators
1144 size.x = (nSeparators + 1)*widthSep;
1145 control->SetSize(size.x, wxDefaultCoord);
1146 }
1147
1148 // position the control itself correctly vertically centering it on the
1149 // icon area of the toolbar
1150 int height = r.bottom - r.top - staticTextSize.y;
1151
1152 int diff = height - size.y;
1153 if ( diff < 0 || !HasFlag(wxTB_TEXT) )
1154 {
1155 // not enough room for the static text
1156 if ( staticText )
1157 staticText->Hide();
1158
1159 // recalculate height & diff without the staticText control
1160 height = r.bottom - r.top;
1161 diff = height - size.y;
1162 if ( diff < 0 )
1163 {
1164 // the control is too high, resize to fit
1165 control->SetSize(wxDefaultCoord, height - 2);
1166
1167 diff = 2;
1168 }
1169 }
1170 else // enough space for both the control and the label
1171 {
1172 if ( staticText )
1173 staticText->Show();
1174 }
1175
1176 int top;
1177 if ( IsVertical() )
1178 {
1179 left = 0;
1180 top = y;
1181
1182 y += height + 2 * GetMargins().y;
1183 }
1184 else // horizontal toolbar
1185 {
1186 if ( left == wxDefaultCoord )
1187 left = r.left;
1188
1189 top = r.top;
1190 }
1191
1192 control->Move(left, top + (diff + 1) / 2);
1193 if ( staticText )
1194 {
1195 staticText->Move(left + (size.x - staticTextSize.x)/2,
1196 r.bottom - staticTextSize.y);
1197 }
1198 }
1199
1200 // the max index is the "real" number of buttons - i.e. counting even the
1201 // separators which we added just for aligning the controls
1202 m_nButtons = index;
1203
1204 if ( !IsVertical() )
1205 {
1206 if ( m_maxRows == 0 )
1207 // if not set yet, only one row
1208 SetRows(1);
1209 }
1210 else if ( m_nButtons > 0 ) // vertical non empty toolbar
1211 {
1212 // if not set yet, have one column
1213 m_maxRows = 1;
1214 SetRows(m_nButtons);
1215 }
1216
1217 InvalidateBestSize();
1218 UpdateSize();
1219
1220 return true;
1221 }
1222
1223 // ----------------------------------------------------------------------------
1224 // message handlers
1225 // ----------------------------------------------------------------------------
1226
1227 bool wxToolBar::MSWCommand(WXUINT WXUNUSED(cmd), WXWORD id_)
1228 {
1229 // cast to signed is important as we compare this id with (signed) ints in
1230 // FindById() and without the cast we'd get a positive int from a
1231 // "negative" (i.e. > 32767) WORD
1232 const int id = (signed short)id_;
1233
1234 wxToolBarToolBase *tool = FindById(id);
1235 if ( !tool )
1236 return false;
1237
1238 bool toggled = false; // just to suppress warnings
1239
1240 LRESULT state = ::SendMessage(GetHwnd(), TB_GETSTATE, id, 0);
1241
1242 if ( tool->CanBeToggled() )
1243 {
1244 toggled = (state & TBSTATE_CHECKED) != 0;
1245
1246 // ignore the event when a radio button is released, as this doesn't
1247 // seem to happen at all, and is handled otherwise
1248 if ( tool->GetKind() == wxITEM_RADIO && !toggled )
1249 return true;
1250
1251 tool->Toggle(toggled);
1252 UnToggleRadioGroup(tool);
1253 }
1254
1255 // Without the two lines of code below, if the toolbar was repainted during
1256 // OnLeftClick(), then it could end up without the tool bitmap temporarily
1257 // (see http://lists.nongnu.org/archive/html/lmi/2008-10/msg00014.html).
1258 // The Update() call bellow ensures that this won't happen, by repainting
1259 // invalidated areas of the toolbar immediately.
1260 //
1261 // To complicate matters, the tool would be drawn in depressed state (this
1262 // code is called when mouse button is released, not pressed). That's not
1263 // ideal, having the tool pressed for the duration of OnLeftClick()
1264 // provides the user with useful visual clue that the app is busy reacting
1265 // to the event. So we manually put the tool into pressed state, handle the
1266 // event and then finally restore tool's original state.
1267 ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state | TBSTATE_PRESSED, 0));
1268 Update();
1269
1270 bool allowLeftClick = OnLeftClick(id, toggled);
1271
1272 // Restore the unpressed state. Enabled/toggled state might have been
1273 // changed since so take care of it.
1274 if (tool->IsEnabled())
1275 state |= TBSTATE_ENABLED;
1276 else
1277 state &= ~TBSTATE_ENABLED;
1278 if (tool->IsToggled())
1279 state |= TBSTATE_CHECKED;
1280 else
1281 state &= ~TBSTATE_CHECKED;
1282 ::SendMessage(GetHwnd(), TB_SETSTATE, id, MAKELONG(state, 0));
1283
1284 // OnLeftClick() can veto the button state change - for buttons which
1285 // may be toggled only, of couse
1286 if ( !allowLeftClick && tool->CanBeToggled() )
1287 {
1288 // revert back
1289 tool->Toggle(!toggled);
1290
1291 ::SendMessage(GetHwnd(), TB_CHECKBUTTON, id, MAKELONG(!toggled, 0));
1292 }
1293
1294 return true;
1295 }
1296
1297 bool wxToolBar::MSWOnNotify(int WXUNUSED(idCtrl),
1298 WXLPARAM lParam,
1299 WXLPARAM *WXUNUSED(result))
1300 {
1301 LPNMHDR hdr = (LPNMHDR)lParam;
1302 if ( hdr->code == TBN_DROPDOWN )
1303 {
1304 LPNMTOOLBAR tbhdr = (LPNMTOOLBAR)lParam;
1305
1306 wxCommandEvent evt(wxEVT_COMMAND_TOOL_DROPDOWN_CLICKED, tbhdr->iItem);
1307 if ( HandleWindowEvent(evt) )
1308 {
1309 // Event got handled, don't display default popup menu
1310 return false;
1311 }
1312
1313 const wxToolBarToolBase * const tool = FindById(tbhdr->iItem);
1314 wxCHECK_MSG( tool, false, _T("drop down message for unknown tool") );
1315
1316 wxMenu * const menu = tool->GetDropdownMenu();
1317 if ( !menu )
1318 return false;
1319
1320 // Display popup menu below button
1321 const RECT r = wxGetTBItemRect(GetHwnd(), GetToolPos(tbhdr->iItem));
1322 if ( r.right )
1323 PopupMenu(menu, r.left, r.bottom);
1324
1325 return true;
1326 }
1327
1328
1329 if( !HasFlag(wxTB_NO_TOOLTIPS) )
1330 {
1331 #if wxUSE_TOOLTIPS
1332 // First check if this applies to us
1333
1334 // the tooltips control created by the toolbar is sometimes Unicode, even
1335 // in an ANSI application - this seems to be a bug in comctl32.dll v5
1336 UINT code = hdr->code;
1337 if ( (code != (UINT) TTN_NEEDTEXTA) && (code != (UINT) TTN_NEEDTEXTW) )
1338 return false;
1339
1340 HWND toolTipWnd = (HWND)::SendMessage(GetHwnd(), TB_GETTOOLTIPS, 0, 0);
1341 if ( toolTipWnd != hdr->hwndFrom )
1342 return false;
1343
1344 LPTOOLTIPTEXT ttText = (LPTOOLTIPTEXT)lParam;
1345 int id = (int)ttText->hdr.idFrom;
1346
1347 wxToolBarToolBase *tool = FindById(id);
1348 if ( tool )
1349 return HandleTooltipNotify(code, lParam, tool->GetShortHelp());
1350 #else
1351 wxUnusedVar(lParam);
1352 #endif
1353 }
1354
1355 return false;
1356 }
1357
1358 // ----------------------------------------------------------------------------
1359 // toolbar geometry
1360 // ----------------------------------------------------------------------------
1361
1362 void wxToolBar::SetToolBitmapSize(const wxSize& size)
1363 {
1364 wxToolBarBase::SetToolBitmapSize(size);
1365
1366 ::SendMessage(GetHwnd(), TB_SETBITMAPSIZE, 0, MAKELONG(size.x, size.y));
1367 }
1368
1369 void wxToolBar::SetRows(int nRows)
1370 {
1371 if ( nRows == m_maxRows )
1372 {
1373 // avoid resizing the frame uselessly
1374 return;
1375 }
1376
1377 // TRUE in wParam means to create at least as many rows, FALSE -
1378 // at most as many
1379 RECT rect;
1380 ::SendMessage(GetHwnd(), TB_SETROWS,
1381 MAKEWPARAM(nRows, !(GetWindowStyle() & wxTB_VERTICAL)),
1382 (LPARAM) &rect);
1383
1384 m_maxRows = nRows;
1385
1386 UpdateSize();
1387 }
1388
1389 // The button size is bigger than the bitmap size
1390 wxSize wxToolBar::GetToolSize() const
1391 {
1392 // TB_GETBUTTONSIZE is supported from version 4.70
1393 #if defined(_WIN32_IE) && (_WIN32_IE >= 0x300 ) \
1394 && !( defined(__GNUWIN32__) && !wxCHECK_W32API_VERSION( 1, 0 ) ) \
1395 && !defined (__DIGITALMARS__)
1396 if ( wxApp::GetComCtl32Version() >= 470 )
1397 {
1398 DWORD dw = ::SendMessage(GetHwnd(), TB_GETBUTTONSIZE, 0, 0);
1399
1400 return wxSize(LOWORD(dw), HIWORD(dw));
1401 }
1402 else
1403 #endif // comctl32.dll 4.70+
1404 {
1405 // defaults
1406 return wxSize(m_defaultWidth + 8, m_defaultHeight + 7);
1407 }
1408 }
1409
1410 static
1411 wxToolBarToolBase *GetItemSkippingDummySpacers(const wxToolBarToolsList& tools,
1412 size_t index )
1413 {
1414 wxToolBarToolsList::compatibility_iterator current = tools.GetFirst();
1415
1416 for ( ; current ; current = current->GetNext() )
1417 {
1418 if ( index == 0 )
1419 return current->GetData();
1420
1421 wxToolBarTool *tool = (wxToolBarTool *)current->GetData();
1422 size_t separators = tool->GetSeparatorsCount();
1423
1424 // if it is a normal button, sepcount == 0, so skip 1 item (the button)
1425 // otherwise, skip as many items as the separator count, plus the
1426 // control itself
1427 index -= separators ? separators + 1 : 1;
1428 }
1429
1430 return 0;
1431 }
1432
1433 wxToolBarToolBase *wxToolBar::FindToolForPosition(wxCoord x, wxCoord y) const
1434 {
1435 POINT pt;
1436 pt.x = x;
1437 pt.y = y;
1438 int index = (int)::SendMessage(GetHwnd(), TB_HITTEST, 0, (LPARAM)&pt);
1439
1440 // MBN: when the point ( x, y ) is close to the toolbar border
1441 // TB_HITTEST returns m_nButtons ( not -1 )
1442 if ( index < 0 || (size_t)index >= m_nButtons )
1443 // it's a separator or there is no tool at all there
1444 return NULL;
1445
1446 // when TB_SETBUTTONINFO is available (both during compile- and run-time),
1447 // we don't use the dummy separators hack
1448 #ifdef TB_SETBUTTONINFO
1449 if ( wxApp::GetComCtl32Version() >= 471 )
1450 {
1451 return m_tools.Item((size_t)index)->GetData();
1452 }
1453 else
1454 #endif // TB_SETBUTTONINFO
1455 {
1456 return GetItemSkippingDummySpacers( m_tools, (size_t) index );
1457 }
1458 }
1459
1460 void wxToolBar::UpdateSize()
1461 {
1462 wxPoint pos = GetPosition();
1463 ::SendMessage(GetHwnd(), TB_AUTOSIZE, 0, 0);
1464 if (pos != GetPosition())
1465 Move(pos);
1466
1467 // In case Realize is called after the initial display (IOW the programmer
1468 // may have rebuilt the toolbar) give the frame the option of resizing the
1469 // toolbar to full width again, but only if the parent is a frame and the
1470 // toolbar is managed by the frame. Otherwise assume that some other
1471 // layout mechanism is controlling the toolbar size and leave it alone.
1472 SendSizeEventToParent();
1473 }
1474
1475 // ----------------------------------------------------------------------------
1476 // toolbar styles
1477 // ---------------------------------------------------------------------------
1478
1479 // get the TBSTYLE of the given toolbar window
1480 long wxToolBar::GetMSWToolbarStyle() const
1481 {
1482 return ::SendMessage(GetHwnd(), TB_GETSTYLE, 0, 0L);
1483 }
1484
1485 void wxToolBar::SetWindowStyleFlag(long style)
1486 {
1487 // the style bits whose changes force us to recreate the toolbar
1488 static const long MASK_NEEDS_RECREATE = wxTB_TEXT | wxTB_NOICONS;
1489
1490 const long styleOld = GetWindowStyle();
1491
1492 wxToolBarBase::SetWindowStyleFlag(style);
1493
1494 // don't recreate an empty toolbar: not only this is unnecessary, but it is
1495 // also fatal as we'd then try to recreate the toolbar when it's just being
1496 // created
1497 if ( GetToolsCount() &&
1498 (style & MASK_NEEDS_RECREATE) != (styleOld & MASK_NEEDS_RECREATE) )
1499 {
1500 // to remove the text labels, simply re-realizing the toolbar is enough
1501 // but I don't know of any way to add the text to an existing toolbar
1502 // other than by recreating it entirely
1503 Recreate();
1504 }
1505 }
1506
1507 // ----------------------------------------------------------------------------
1508 // tool state
1509 // ----------------------------------------------------------------------------
1510
1511 void wxToolBar::DoEnableTool(wxToolBarToolBase *tool, bool enable)
1512 {
1513 ::SendMessage(GetHwnd(), TB_ENABLEBUTTON,
1514 (WPARAM)tool->GetId(), (LPARAM)MAKELONG(enable, 0));
1515 }
1516
1517 void wxToolBar::DoToggleTool(wxToolBarToolBase *tool, bool toggle)
1518 {
1519 ::SendMessage(GetHwnd(), TB_CHECKBUTTON,
1520 (WPARAM)tool->GetId(), (LPARAM)MAKELONG(toggle, 0));
1521 }
1522
1523 void wxToolBar::DoSetToggle(wxToolBarToolBase *WXUNUSED(tool), bool WXUNUSED(toggle))
1524 {
1525 // VZ: AFAIK, the button has to be created either with TBSTYLE_CHECK or
1526 // without, so we really need to delete the button and recreate it here
1527 wxFAIL_MSG( _T("not implemented") );
1528 }
1529
1530 void wxToolBar::SetToolNormalBitmap( int id, const wxBitmap& bitmap )
1531 {
1532 wxToolBarTool* tool = static_cast<wxToolBarTool*>(FindById(id));
1533 if ( tool )
1534 {
1535 wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools."));
1536
1537 tool->SetNormalBitmap(bitmap);
1538 Realize();
1539 }
1540 }
1541
1542 void wxToolBar::SetToolDisabledBitmap( int id, const wxBitmap& bitmap )
1543 {
1544 wxToolBarTool* tool = static_cast<wxToolBarTool*>(FindById(id));
1545 if ( tool )
1546 {
1547 wxCHECK_RET( tool->IsButton(), wxT("Can only set bitmap on button tools."));
1548
1549 tool->SetDisabledBitmap(bitmap);
1550 Realize();
1551 }
1552 }
1553
1554 // ----------------------------------------------------------------------------
1555 // event handlers
1556 // ----------------------------------------------------------------------------
1557
1558 // Responds to colour changes, and passes event on to children.
1559 void wxToolBar::OnSysColourChanged(wxSysColourChangedEvent& event)
1560 {
1561 wxRGBToColour(m_backgroundColour, ::GetSysColor(COLOR_BTNFACE));
1562
1563 // Remap the buttons
1564 Realize();
1565
1566 // Relayout the toolbar
1567 int nrows = m_maxRows;
1568 m_maxRows = 0; // otherwise SetRows() wouldn't do anything
1569 SetRows(nrows);
1570
1571 Refresh();
1572
1573 // let the event propagate further
1574 event.Skip();
1575 }
1576
1577 void wxToolBar::OnMouseEvent(wxMouseEvent& event)
1578 {
1579 if ( event.Leaving() )
1580 {
1581 if ( m_pInTool )
1582 {
1583 OnMouseEnter(wxID_ANY);
1584 m_pInTool = NULL;
1585 }
1586
1587 event.Skip();
1588 return;
1589 }
1590
1591 if ( event.RightDown() )
1592 {
1593 // find the tool under the mouse
1594 wxCoord x = 0, y = 0;
1595 event.GetPosition(&x, &y);
1596
1597 wxToolBarToolBase *tool = FindToolForPosition(x, y);
1598 OnRightClick(tool ? tool->GetId() : -1, x, y);
1599 }
1600 else
1601 {
1602 event.Skip();
1603 }
1604 }
1605
1606 // This handler is required to allow the toolbar to be set to a non-default
1607 // colour: for example, when it must blend in with a notebook page.
1608 void wxToolBar::OnEraseBackground(wxEraseEvent& event)
1609 {
1610 RECT rect = wxGetClientRect(GetHwnd());
1611
1612 wxDC *dc = event.GetDC();
1613 if (!dc) return;
1614 wxMSWDCImpl *impl = (wxMSWDCImpl*) dc->GetImpl();
1615 HDC hdc = GetHdcOf(*impl);
1616
1617 int majorVersion, minorVersion;
1618 wxGetOsVersion(& majorVersion, & minorVersion);
1619
1620 #if wxUSE_UXTHEME
1621 // we may need to draw themed colour so that we appear correctly on
1622 // e.g. notebook page under XP with themes but only do it if the parent
1623 // draws themed background itself
1624 if ( !UseBgCol() && !GetParent()->UseBgCol() )
1625 {
1626 wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive();
1627 if ( theme )
1628 {
1629 HRESULT
1630 hr = theme->DrawThemeParentBackground(GetHwnd(), hdc, &rect);
1631 if ( hr == S_OK )
1632 return;
1633
1634 // it can also return S_FALSE which seems to simply say that it
1635 // didn't draw anything but no error really occurred
1636 if ( FAILED(hr) )
1637 wxLogApiError(_T("DrawThemeParentBackground(toolbar)"), hr);
1638 }
1639 }
1640
1641 // Only draw a rebar theme on Vista, since it doesn't jive so well with XP
1642 if ( !UseBgCol() && majorVersion >= 6 )
1643 {
1644 wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive();
1645 if ( theme )
1646 {
1647 wxUxThemeHandle hTheme(this, L"REBAR");
1648
1649 RECT r;
1650 wxRect rect = GetClientRect();
1651 wxCopyRectToRECT(rect, r);
1652
1653 HRESULT hr = theme->DrawThemeBackground(hTheme, hdc, 0, 0, & r, NULL);
1654 if ( hr == S_OK )
1655 return;
1656
1657 // it can also return S_FALSE which seems to simply say that it
1658 // didn't draw anything but no error really occurred
1659 if ( FAILED(hr) )
1660 wxLogApiError(_T("DrawThemeParentBackground(toolbar)"), hr);
1661 }
1662 }
1663
1664 #endif // wxUSE_UXTHEME
1665
1666 // we need to always draw our background under XP, as otherwise it doesn't
1667 // appear correctly with some themes (e.g. Zune one)
1668 if ( majorVersion == 5 ||
1669 UseBgCol() || (GetMSWToolbarStyle() & TBSTYLE_TRANSPARENT) )
1670 {
1671 // do draw our background
1672 //
1673 // notice that this 'dumb' implementation may cause flicker for some of
1674 // the controls in which case they should intercept wxEraseEvent and
1675 // process it themselves somehow
1676 AutoHBRUSH hBrush(wxColourToRGB(GetBackgroundColour()));
1677
1678 wxCHANGE_HDC_MAP_MODE(hdc, MM_TEXT);
1679 ::FillRect(hdc, &rect, hBrush);
1680 }
1681 else // we have no non default background colour
1682 {
1683 // let the system do it for us
1684 event.Skip();
1685 }
1686 }
1687
1688 bool wxToolBar::HandleSize(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam)
1689 {
1690 // wait until we have some tools
1691 if ( !GetToolsCount() )
1692 return false;
1693
1694 // calculate our minor dimension ourselves - we're confusing the standard
1695 // logic (TB_AUTOSIZE) with our horizontal toolbars and other hacks
1696 const RECT r = wxGetTBItemRect(GetHwnd(), 0);
1697 if ( !r.right )
1698 return false;
1699
1700 int w, h;
1701
1702 if ( IsVertical() )
1703 {
1704 w = r.right - r.left;
1705 if ( m_maxRows )
1706 {
1707 w *= (m_nButtons + m_maxRows - 1)/m_maxRows;
1708 }
1709 h = HIWORD(lParam);
1710 }
1711 else
1712 {
1713 w = LOWORD(lParam);
1714 if (HasFlag( wxTB_FLAT ))
1715 h = r.bottom - r.top - 3;
1716 else
1717 h = r.bottom - r.top;
1718 if ( m_maxRows )
1719 {
1720 // FIXME: hardcoded separator line height...
1721 h += HasFlag(wxTB_NODIVIDER) ? 4 : 6;
1722 h *= m_maxRows;
1723 }
1724 }
1725
1726 if ( MAKELPARAM(w, h) != lParam )
1727 {
1728 // size really changed
1729 SetSize(w, h);
1730 }
1731
1732 // message processed
1733 return true;
1734 }
1735
1736 bool wxToolBar::HandlePaint(WXWPARAM wParam, WXLPARAM lParam)
1737 {
1738 // erase any dummy separators which were used
1739 // for aligning the controls if any here
1740
1741 // first of all, are there any controls at all?
1742 wxToolBarToolsList::compatibility_iterator node;
1743 for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
1744 {
1745 if ( node->GetData()->IsControl() )
1746 break;
1747 }
1748
1749 if ( !node )
1750 // no controls, nothing to erase
1751 return false;
1752
1753 wxSize clientSize = GetClientSize();
1754 int majorVersion, minorVersion;
1755 wxGetOsVersion(& majorVersion, & minorVersion);
1756
1757 // prepare the DC on which we'll be drawing
1758 wxClientDC dc(this);
1759 dc.SetBrush(wxBrush(GetBackgroundColour(), wxSOLID));
1760 dc.SetPen(*wxTRANSPARENT_PEN);
1761
1762 RECT r;
1763 if ( !::GetUpdateRect(GetHwnd(), &r, FALSE) )
1764 // nothing to redraw anyhow
1765 return false;
1766
1767 wxRect rectUpdate;
1768 wxCopyRECTToRect(r, rectUpdate);
1769
1770 dc.SetClippingRegion(rectUpdate);
1771
1772 // draw the toolbar tools, separators &c normally
1773 wxControl::MSWWindowProc(WM_PAINT, wParam, lParam);
1774
1775 // for each control in the toolbar find all the separators intersecting it
1776 // and erase them
1777 //
1778 // NB: this is really the only way to do it as we don't know if a separator
1779 // corresponds to a control (i.e. is a dummy one) or a real one
1780 // otherwise
1781 for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
1782 {
1783 wxToolBarTool *tool = (wxToolBarTool*)node->GetData();
1784 if ( tool->IsControl() )
1785 {
1786 // get the control rect in our client coords
1787 wxControl *control = tool->GetControl();
1788 wxStaticText *staticText = tool->GetStaticText();
1789 wxRect rectCtrl = control->GetRect();
1790 wxRect rectStaticText(0,0,0,0);
1791 if ( staticText )
1792 {
1793 rectStaticText = staticText->GetRect();
1794 }
1795
1796 // iterate over all buttons
1797 TBBUTTON tbb;
1798 int count = ::SendMessage(GetHwnd(), TB_BUTTONCOUNT, 0, 0);
1799 for ( int n = 0; n < count; n++ )
1800 {
1801 // is it a separator?
1802 if ( !::SendMessage(GetHwnd(), TB_GETBUTTON,
1803 n, (LPARAM)&tbb) )
1804 {
1805 wxLogDebug(_T("TB_GETBUTTON failed?"));
1806
1807 continue;
1808 }
1809
1810 if ( tbb.fsStyle != TBSTYLE_SEP )
1811 continue;
1812
1813 // get the bounding rect of the separator
1814 RECT r = wxGetTBItemRect(GetHwnd(), n);
1815 if ( !r.right )
1816 continue;
1817
1818 // does it intersect the control?
1819 wxRect rectItem;
1820 wxCopyRECTToRect(r, rectItem);
1821 if ( rectCtrl.Intersects(rectItem) || (staticText && rectStaticText.Intersects(rectItem)))
1822 {
1823 // yes, do erase it!
1824
1825 bool haveRefreshed = false;
1826
1827 #if wxUSE_UXTHEME
1828 if ( !UseBgCol() && !GetParent()->UseBgCol() )
1829 {
1830 // Don't use DrawThemeBackground
1831 }
1832 else if ( !UseBgCol() && majorVersion >= 6 )
1833 {
1834 wxUxThemeEngine *theme = wxUxThemeEngine::GetIfActive();
1835 if ( theme )
1836 {
1837 wxUxThemeHandle hTheme(this, L"REBAR");
1838
1839 RECT clipRect = r;
1840
1841 // Draw the whole background since the pattern may be position sensitive;
1842 // but clip it to the area of interest.
1843 r.left = 0;
1844 r.right = clientSize.x;
1845 r.top = 0;
1846 r.bottom = clientSize.y;
1847
1848 wxMSWDCImpl *impl = (wxMSWDCImpl*) dc.GetImpl();
1849 HRESULT hr = theme->DrawThemeBackground(hTheme, GetHdcOf(*impl), 0, 0, & r, & clipRect);
1850 if ( hr == S_OK )
1851 haveRefreshed = true;
1852 }
1853 }
1854 #endif
1855
1856 if (!haveRefreshed)
1857 dc.DrawRectangle(rectItem);
1858 }
1859
1860 if ( rectCtrl.Intersects(rectItem) )
1861 {
1862 // Necessary in case we use a no-paint-on-size
1863 // style in the parent: the controls can disappear
1864 control->Refresh(false);
1865 }
1866
1867 if ( staticText && rectStaticText.Intersects(rectItem) )
1868 {
1869 // Necessary in case we use a no-paint-on-size
1870 // style in the parent: the controls can disappear
1871 staticText->Refresh(false);
1872 }
1873 }
1874 }
1875 }
1876
1877 return true;
1878 }
1879
1880 void wxToolBar::HandleMouseMove(WXWPARAM WXUNUSED(wParam), WXLPARAM lParam)
1881 {
1882 wxCoord x = GET_X_LPARAM(lParam),
1883 y = GET_Y_LPARAM(lParam);
1884 wxToolBarToolBase* tool = FindToolForPosition( x, y );
1885
1886 // has the current tool changed?
1887 if ( tool != m_pInTool )
1888 {
1889 m_pInTool = tool;
1890 OnMouseEnter(tool ? tool->GetId() : wxID_ANY);
1891 }
1892 }
1893
1894 WXLRESULT wxToolBar::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
1895 {
1896 switch ( nMsg )
1897 {
1898 case WM_MOUSEMOVE:
1899 // we don't handle mouse moves, so always pass the message to
1900 // wxControl::MSWWindowProc (HandleMouseMove just calls OnMouseEnter)
1901 HandleMouseMove(wParam, lParam);
1902 break;
1903
1904 case WM_SIZE:
1905 if ( HandleSize(wParam, lParam) )
1906 return 0;
1907 break;
1908
1909 #ifndef __WXWINCE__
1910 case WM_PAINT:
1911 // refreshing the controls in the toolbar inside a composite window
1912 // results in an endless stream of WM_PAINT messages -- and seems
1913 // to be unnecessary anyhow as everything works just fine without
1914 // any special workarounds in this case
1915 if ( !IsDoubleBuffered() && HandlePaint(wParam, lParam) )
1916 return 0;
1917 break;
1918 #endif // __WXWINCE__
1919 }
1920
1921 return wxControl::MSWWindowProc(nMsg, wParam, lParam);
1922 }
1923
1924 // ----------------------------------------------------------------------------
1925 // private functions
1926 // ----------------------------------------------------------------------------
1927
1928 #ifdef wxREMAP_BUTTON_COLOURS
1929
1930 WXHBITMAP wxToolBar::MapBitmap(WXHBITMAP bitmap, int width, int height)
1931 {
1932 MemoryHDC hdcMem;
1933
1934 if ( !hdcMem )
1935 {
1936 wxLogLastError(_T("CreateCompatibleDC"));
1937
1938 return bitmap;
1939 }
1940
1941 SelectInHDC bmpInHDC(hdcMem, (HBITMAP)bitmap);
1942
1943 if ( !bmpInHDC )
1944 {
1945 wxLogLastError(_T("SelectObject"));
1946
1947 return bitmap;
1948 }
1949
1950 wxCOLORMAP *cmap = wxGetStdColourMap();
1951
1952 for ( int i = 0; i < width; i++ )
1953 {
1954 for ( int j = 0; j < height; j++ )
1955 {
1956 COLORREF pixel = ::GetPixel(hdcMem, i, j);
1957
1958 for ( size_t k = 0; k < wxSTD_COL_MAX; k++ )
1959 {
1960 COLORREF col = cmap[k].from;
1961 if ( abs(GetRValue(pixel) - GetRValue(col)) < 10 &&
1962 abs(GetGValue(pixel) - GetGValue(col)) < 10 &&
1963 abs(GetBValue(pixel) - GetBValue(col)) < 10 )
1964 {
1965 if ( cmap[k].to != pixel )
1966 ::SetPixel(hdcMem, i, j, cmap[k].to);
1967 break;
1968 }
1969 }
1970 }
1971 }
1972
1973 return bitmap;
1974 }
1975
1976 #endif // wxREMAP_BUTTON_COLOURS
1977
1978 #endif // wxUSE_TOOLBAR