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