Refactor wxStatusBar creation in wxMSW to do it in standard way.
[wxWidgets.git] / src / msw / statusbar.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/statusbar.cpp
3 // Purpose: native implementation of wxStatusBar
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 04.04.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
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_STATUSBAR && wxUSE_NATIVE_STATUSBAR
28
29 #include "wx/statusbr.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/frame.h"
34 #include "wx/settings.h"
35 #include "wx/dcclient.h"
36 #include "wx/intl.h"
37 #include "wx/log.h"
38 #include "wx/control.h"
39 #endif
40
41 #include "wx/msw/private.h"
42 #include "wx/tooltip.h"
43 #include <windowsx.h>
44
45 #if wxUSE_UXTHEME
46 #include "wx/msw/uxtheme.h"
47 #endif
48
49 // ----------------------------------------------------------------------------
50 // constants
51 // ----------------------------------------------------------------------------
52
53 namespace
54 {
55
56 // no idea for a default width, just choose something
57 static const int DEFAULT_FIELD_WIDTH = 25;
58
59 } // anonymous namespace
60
61 // ----------------------------------------------------------------------------
62 // macros
63 // ----------------------------------------------------------------------------
64
65 // windowsx.h and commctrl.h don't define those, so we do it here
66 #define StatusBar_SetParts(h, n, w) SendMessage(h, SB_SETPARTS, (WPARAM)n, (LPARAM)w)
67 #define StatusBar_SetText(h, n, t) SendMessage(h, SB_SETTEXT, (WPARAM)n, (LPARAM)(LPCTSTR)t)
68 #define StatusBar_GetTextLen(h, n) LOWORD(SendMessage(h, SB_GETTEXTLENGTH, (WPARAM)n, 0))
69 #define StatusBar_GetText(h, n, s) LOWORD(SendMessage(h, SB_GETTEXT, (WPARAM)n, (LPARAM)(LPTSTR)s))
70
71 // ============================================================================
72 // implementation
73 // ============================================================================
74
75 // ----------------------------------------------------------------------------
76 // wxStatusBar class
77 // ----------------------------------------------------------------------------
78
79 wxStatusBar::wxStatusBar()
80 {
81 SetParent(NULL);
82 m_hWnd = 0;
83 m_windowId = 0;
84 m_pDC = NULL;
85 }
86
87 WXDWORD wxStatusBar::MSWGetStyle(long style, WXDWORD *exstyle) const
88 {
89 WXDWORD msStyle = wxStatusBarBase::MSWGetStyle(style, exstyle);
90
91 // wxSTB_SIZEGRIP is part of our default style but it doesn't make sense to
92 // show size grip if this is the status bar of a non-resizeable TLW so turn
93 // it off in such case
94 wxWindow * const parent = GetParent();
95 wxCHECK_MSG( parent, msStyle, wxS("Status bar must have a parent") );
96 if ( parent->IsTopLevel() && !parent->HasFlag(wxRESIZE_BORDER) )
97 style &= ~wxSTB_SIZEGRIP;
98
99 // setting SBARS_SIZEGRIP is perfectly useless: it's always on by default
100 // (at least in the version of comctl32.dll I'm using), and the only way to
101 // turn it off is to use CCS_TOP style - as we position the status bar
102 // manually anyhow (see DoMoveWindow), use CCS_TOP style if wxSTB_SIZEGRIP
103 // is not given
104 if ( !(style & wxSTB_SIZEGRIP) )
105 {
106 *exstyle |= CCS_TOP;
107 }
108 else
109 {
110 #ifndef __WXWINCE__
111 // may be some versions of comctl32.dll do need it - anyhow, it won't
112 // do any harm
113 *exstyle |= SBARS_SIZEGRIP;
114 #endif
115 }
116
117 return msStyle;
118 }
119
120 bool wxStatusBar::Create(wxWindow *parent,
121 wxWindowID id,
122 long style,
123 const wxString& name)
124 {
125 if ( !CreateControl(parent, id, wxDefaultPosition, wxDefaultSize,
126 style, wxDefaultValidator, name) )
127 return false;
128
129 if ( !MSWCreateControl(STATUSCLASSNAME, wxString(),
130 wxDefaultPosition, wxDefaultSize) )
131 return false;
132
133 SetFieldsCount(1);
134
135 // cache the DC instance used by DoUpdateStatusText:
136 m_pDC = new wxClientDC(this);
137
138 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_MENUBAR));
139
140 // we must refresh the frame size when the statusbar is created, because
141 // its client area might change
142 //
143 // notice that we must post the event, not send it, as the frame doesn't
144 // know that we're its status bar yet so laying it out right now wouldn't
145 // work correctly, we need to wait until we return to the main loop
146 PostSizeEventToParent();
147
148 return true;
149 }
150
151 wxStatusBar::~wxStatusBar()
152 {
153 // we must refresh the frame size when the statusbar is deleted but the
154 // frame is not - otherwise statusbar leaves a hole in the place it used to
155 // occupy
156 PostSizeEventToParent();
157
158 // delete existing tooltips
159 for (size_t i=0; i<m_tooltips.size(); i++)
160 {
161 wxDELETE(m_tooltips[i]);
162 }
163
164 wxDELETE(m_pDC);
165 }
166
167 bool wxStatusBar::SetFont(const wxFont& font)
168 {
169 if (!wxWindow::SetFont(font))
170 return false;
171
172 if (m_pDC) m_pDC->SetFont(font);
173 return true;
174 }
175
176 void wxStatusBar::SetFieldsCount(int nFields, const int *widths)
177 {
178 // this is a Windows limitation
179 wxASSERT_MSG( (nFields > 0) && (nFields < 255), "too many fields" );
180
181 wxStatusBarBase::SetFieldsCount(nFields, widths);
182
183 MSWUpdateFieldsWidths();
184
185 // keep in synch also our m_tooltips array
186
187 // reset all current tooltips
188 for (size_t i=0; i<m_tooltips.size(); i++)
189 {
190 wxDELETE(m_tooltips[i]);
191 }
192
193 // shrink/expand the array:
194 m_tooltips.resize(m_panes.GetCount(), NULL);
195 }
196
197 void wxStatusBar::SetStatusWidths(int n, const int widths[])
198 {
199 wxStatusBarBase::SetStatusWidths(n, widths);
200
201 MSWUpdateFieldsWidths();
202 }
203
204 void wxStatusBar::MSWUpdateFieldsWidths()
205 {
206 if ( m_panes.IsEmpty() )
207 return;
208
209 const int count = m_panes.GetCount();
210
211 const int extraWidth = MSWGetBorderWidth() + MSWGetMetrics().textMargin;
212
213 // compute the effectively available amount of space:
214 int widthAvailable = GetClientSize().x; // start with the entire width
215 widthAvailable -= extraWidth*(count - 1); // extra space between fields
216 widthAvailable -= MSWGetMetrics().textMargin; // and for the last field
217
218 if ( HasFlag(wxSTB_SIZEGRIP) )
219 widthAvailable -= MSWGetMetrics().gripWidth;
220
221 // distribute the available space (client width) among the various fields:
222
223 wxArrayInt widthsAbs = CalculateAbsWidths(widthAvailable);
224
225
226 // update the field widths in the native control:
227
228 int *pWidths = new int[count];
229
230 int nCurPos = 0;
231 for ( int i = 0; i < count; i++ )
232 {
233 nCurPos += widthsAbs[i] + extraWidth;
234 pWidths[i] = nCurPos;
235 }
236
237 if ( !StatusBar_SetParts(GetHwnd(), count, pWidths) )
238 {
239 wxLogLastError("StatusBar_SetParts");
240 }
241
242 delete [] pWidths;
243
244
245 // FIXME: we may want to call DoUpdateStatusText() here since we may need to (de)ellipsize status texts
246 }
247
248 void wxStatusBar::DoUpdateStatusText(int nField)
249 {
250 if (!m_pDC)
251 return;
252
253 // Get field style, if any
254 int style;
255 switch(m_panes[nField].GetStyle())
256 {
257 case wxSB_RAISED:
258 style = SBT_POPOUT;
259 break;
260 case wxSB_FLAT:
261 style = SBT_NOBORDERS;
262 break;
263
264 case wxSB_NORMAL:
265 default:
266 style = 0;
267 break;
268 }
269
270 wxRect rc;
271 GetFieldRect(nField, rc);
272
273 const int maxWidth = rc.GetWidth() - MSWGetMetrics().textMargin;
274
275 wxString text = GetStatusText(nField);
276
277 // do we need to ellipsize this string?
278 wxEllipsizeMode ellmode = (wxEllipsizeMode)-1;
279 if (HasFlag(wxSTB_ELLIPSIZE_START)) ellmode = wxELLIPSIZE_START;
280 else if (HasFlag(wxSTB_ELLIPSIZE_MIDDLE)) ellmode = wxELLIPSIZE_MIDDLE;
281 else if (HasFlag(wxSTB_ELLIPSIZE_END)) ellmode = wxELLIPSIZE_END;
282
283 if (ellmode == (wxEllipsizeMode)-1)
284 {
285 // if we have the wxSTB_SHOW_TIPS we must set the ellipsized flag even if
286 // we don't ellipsize the text but just truncate it
287 if (HasFlag(wxSTB_SHOW_TIPS))
288 SetEllipsizedFlag(nField, m_pDC->GetTextExtent(text).GetWidth() > maxWidth);
289 }
290 else
291 {
292 text = wxControl::Ellipsize(text,
293 *m_pDC,
294 ellmode,
295 maxWidth,
296 wxELLIPSIZE_FLAGS_EXPAND_TABS);
297
298 // update the ellipsization status for this pane; this is used later to
299 // decide whether a tooltip should be shown or not for this pane
300 // (if we have wxSTB_SHOW_TIPS)
301 SetEllipsizedFlag(nField, text != GetStatusText(nField));
302 }
303
304 // Set the status text in the native control passing both field number and style.
305 // NOTE: MSDN library doesn't mention that nField and style have to be 'ORed'
306 if ( !StatusBar_SetText(GetHwnd(), nField | style, text.wx_str()) )
307 {
308 wxLogLastError("StatusBar_SetText");
309 }
310
311 if (HasFlag(wxSTB_SHOW_TIPS))
312 {
313 wxASSERT(m_tooltips.size() == m_panes.GetCount());
314
315 if (m_tooltips[nField])
316 {
317 if (GetField(nField).IsEllipsized())
318 {
319 // update the rect of this tooltip:
320 m_tooltips[nField]->SetRect(rc);
321
322 // update also the text:
323 m_tooltips[nField]->SetTip(GetStatusText(nField));
324 }
325 else
326 {
327 // delete the tooltip associated with this pane; it's not needed anymore
328 wxDELETE(m_tooltips[nField]);
329 }
330 }
331 else
332 {
333 // create a new tooltip for this pane if needed
334 if (GetField(nField).IsEllipsized())
335 m_tooltips[nField] = new wxToolTip(this, nField, GetStatusText(nField), rc);
336 //else: leave m_tooltips[nField]==NULL
337 }
338 }
339 }
340
341 wxStatusBar::MSWBorders wxStatusBar::MSWGetBorders() const
342 {
343 int aBorders[3];
344 SendMessage(GetHwnd(), SB_GETBORDERS, 0, (LPARAM)aBorders);
345
346 MSWBorders borders;
347 borders.horz = aBorders[0];
348 borders.vert = aBorders[1];
349 borders.between = aBorders[2];
350 return borders;
351 }
352
353 int wxStatusBar::GetBorderX() const
354 {
355 return MSWGetBorders().horz;
356 }
357
358 int wxStatusBar::GetBorderY() const
359 {
360 return MSWGetBorders().vert;
361 }
362
363 int wxStatusBar::MSWGetBorderWidth() const
364 {
365 return MSWGetBorders().between;
366 }
367
368 /* static */
369 const wxStatusBar::MSWMetrics& wxStatusBar::MSWGetMetrics()
370 {
371 static MSWMetrics s_metrics = { 0 };
372 if ( !s_metrics.textMargin )
373 {
374 // Grip size should be self explanatory (the only problem with it is
375 // that it's hard coded as we don't know how to find its size using
376 // API) but the margin might merit an explanation: Windows offsets the
377 // text drawn in status bar panes so we need to take this extra margin
378 // into account to make sure the text drawn by user fits inside the
379 // pane. Notice that it's not the value returned by SB_GETBORDERS
380 // which, at least on this Windows 2003 system, returns {0, 2, 2}
381 if ( wxUxThemeEngine::GetIfActive() )
382 {
383 s_metrics.gripWidth = 20;
384 s_metrics.textMargin = 8;
385 }
386 else // classic/unthemed look
387 {
388 s_metrics.gripWidth = 18;
389 s_metrics.textMargin = 4;
390 }
391 }
392
393 return s_metrics;
394 }
395
396 void wxStatusBar::SetMinHeight(int height)
397 {
398 SendMessage(GetHwnd(), SB_SETMINHEIGHT, height + 2*GetBorderY(), 0);
399
400 // we have to send a (dummy) WM_SIZE to redraw it now
401 SendMessage(GetHwnd(), WM_SIZE, 0, 0);
402 }
403
404 bool wxStatusBar::GetFieldRect(int i, wxRect& rect) const
405 {
406 wxCHECK_MSG( (i >= 0) && ((size_t)i < m_panes.GetCount()), false,
407 "invalid statusbar field index" );
408
409 RECT r;
410 if ( !::SendMessage(GetHwnd(), SB_GETRECT, i, (LPARAM)&r) )
411 {
412 wxLogLastError("SendMessage(SB_GETRECT)");
413 }
414
415 #if wxUSE_UXTHEME
416 wxUxThemeHandle theme(const_cast<wxStatusBar*>(this), L"Status");
417 if ( theme )
418 {
419 // by default Windows has a 2 pixel border to the right of the left
420 // divider (or it could be a bug) but it looks wrong so remove it
421 if ( i != 0 )
422 {
423 r.left -= 2;
424 }
425
426 wxUxThemeEngine::Get()->GetThemeBackgroundContentRect(theme, NULL,
427 1 /* SP_PANE */, 0,
428 &r, &r);
429 }
430 #endif
431
432 wxCopyRECTToRect(r, rect);
433
434 // Windows seems to under-report the size of the last field rectangle,
435 // presumably in order to prevent the buggy applications from overflowing
436 // onto the size grip but we want to return the real size to wx users
437 if ( HasFlag(wxSTB_SIZEGRIP) && i == (int)m_panes.GetCount() - 1 )
438 {
439 rect.width += MSWGetMetrics().gripWidth - MSWGetBorderWidth();
440 }
441
442 return true;
443 }
444
445 wxSize wxStatusBar::DoGetBestSize() const
446 {
447 const MSWBorders borders = MSWGetBorders();
448
449 // calculate width
450 int width = 0;
451 for ( size_t i = 0; i < m_panes.GetCount(); ++i )
452 {
453 int widthField =
454 m_bSameWidthForAllPanes ? DEFAULT_FIELD_WIDTH : m_panes[i].GetWidth();
455 if ( widthField >= 0 )
456 {
457 width += widthField;
458 }
459 else
460 {
461 // variable width field, its width is really a proportion
462 // related to the other fields
463 width += -widthField*DEFAULT_FIELD_WIDTH;
464 }
465
466 // add the space between fields
467 width += borders.between;
468 }
469
470 if ( !width )
471 {
472 // still need something even for an empty status bar
473 width = 2*DEFAULT_FIELD_WIDTH;
474 }
475
476 // calculate height
477 int height;
478 wxGetCharSize(GetHWND(), NULL, &height, GetFont());
479 height = EDIT_HEIGHT_FROM_CHAR_HEIGHT(height);
480 height += borders.vert;
481
482 wxSize best(width, height);
483 CacheBestSize(best);
484 return best;
485 }
486
487 void wxStatusBar::DoMoveWindow(int x, int y, int width, int height)
488 {
489 if ( GetParent()->IsSizeDeferred() )
490 {
491 wxWindowMSW::DoMoveWindow(x, y, width, height);
492 }
493 else
494 {
495 // parent pos/size isn't deferred so do it now but don't send
496 // WM_WINDOWPOSCHANGING since we don't want to change pos/size later
497 // we must use SWP_NOCOPYBITS here otherwise it paints incorrectly
498 // if other windows are size deferred
499 ::SetWindowPos(GetHwnd(), NULL, x, y, width, height,
500 SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE
501 #ifndef __WXWINCE__
502 | SWP_NOCOPYBITS | SWP_NOSENDCHANGING
503 #endif
504 );
505 }
506
507 // adjust fields widths to the new size
508 MSWUpdateFieldsWidths();
509
510 // we have to trigger wxSizeEvent if there are children window in status
511 // bar because GetFieldRect returned incorrect (not updated) values up to
512 // here, which almost certainly resulted in incorrectly redrawn statusbar
513 if ( m_children.GetCount() > 0 )
514 {
515 wxSizeEvent event(GetClientSize(), m_windowId);
516 event.SetEventObject(this);
517 HandleWindowEvent(event);
518 }
519 }
520
521 void wxStatusBar::SetStatusStyles(int n, const int styles[])
522 {
523 wxStatusBarBase::SetStatusStyles(n, styles);
524
525 if (n != (int)m_panes.GetCount())
526 return;
527
528 for (int i = 0; i < n; i++)
529 {
530 int style;
531 switch(styles[i])
532 {
533 case wxSB_RAISED:
534 style = SBT_POPOUT;
535 break;
536 case wxSB_FLAT:
537 style = SBT_NOBORDERS;
538 break;
539 case wxSB_NORMAL:
540 default:
541 style = 0;
542 break;
543 }
544
545 // The SB_SETTEXT message is both used to set the field's text as well as
546 // the fields' styles.
547 // NOTE: MSDN library doesn't mention that nField and style have to be 'ORed'
548 wxString text = GetStatusText(i);
549 if (!StatusBar_SetText(GetHwnd(), style | i, text.wx_str()))
550 {
551 wxLogLastError("StatusBar_SetText");
552 }
553 }
554 }
555
556 WXLRESULT
557 wxStatusBar::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
558 {
559 #ifndef __WXWINCE__
560 if ( nMsg == WM_WINDOWPOSCHANGING )
561 {
562 WINDOWPOS *lpPos = (WINDOWPOS *)lParam;
563 int x, y, w, h;
564 GetPosition(&x, &y);
565 GetSize(&w, &h);
566
567 // we need real window coords and not wx client coords
568 AdjustForParentClientOrigin(x, y);
569
570 lpPos->x = x;
571 lpPos->y = y;
572 lpPos->cx = w;
573 lpPos->cy = h;
574
575 return 0;
576 }
577
578 if ( nMsg == WM_NCLBUTTONDOWN )
579 {
580 // if hit-test is on gripper then send message to TLW to begin
581 // resizing. It is possible to send this message to any window.
582 if ( wParam == HTBOTTOMRIGHT )
583 {
584 wxWindow *win;
585
586 for ( win = GetParent(); win; win = win->GetParent() )
587 {
588 if ( win->IsTopLevel() )
589 {
590 SendMessage(GetHwndOf(win), WM_NCLBUTTONDOWN,
591 wParam, lParam);
592
593 return 0;
594 }
595 }
596 }
597 }
598 #endif
599
600 bool needsEllipsization = HasFlag(wxSTB_ELLIPSIZE_START) ||
601 HasFlag(wxSTB_ELLIPSIZE_MIDDLE) ||
602 HasFlag(wxSTB_ELLIPSIZE_END);
603 if ( nMsg == WM_SIZE && needsEllipsization )
604 {
605 for (int i=0; i<GetFieldsCount(); i++)
606 DoUpdateStatusText(i);
607 // re-set the field text, in case we need to ellipsize
608 // (or de-ellipsize) some parts of it
609 }
610
611 return wxStatusBarBase::MSWWindowProc(nMsg, wParam, lParam);
612 }
613
614 #if wxUSE_TOOLTIPS
615 bool wxStatusBar::MSWProcessMessage(WXMSG* pMsg)
616 {
617 if ( HasFlag(wxSTB_SHOW_TIPS) )
618 {
619 // for a tooltip to be shown, we need to relay mouse events to it;
620 // this is typically done by wxWindowMSW::MSWProcessMessage but only
621 // if wxWindow::m_tooltip pointer is non-NULL.
622 // Since wxStatusBar has multiple tooltips for a single HWND, it keeps
623 // wxWindow::m_tooltip == NULL and then relays mouse events here:
624 MSG *msg = (MSG *)pMsg;
625 if ( msg->message == WM_MOUSEMOVE )
626 wxToolTip::RelayEvent(pMsg);
627 }
628
629 return wxWindow::MSWProcessMessage(pMsg);
630 }
631
632 bool wxStatusBar::MSWOnNotify(int WXUNUSED(idCtrl), WXLPARAM lParam, WXLPARAM* WXUNUSED(result))
633 {
634 if ( HasFlag(wxSTB_SHOW_TIPS) )
635 {
636 // see comment in wxStatusBar::MSWProcessMessage for more info;
637 // basically we need to override wxWindow::MSWOnNotify because
638 // we have wxWindow::m_tooltip always NULL but we still use tooltips...
639
640 NMHDR* hdr = (NMHDR *)lParam;
641
642 wxString str;
643 if (hdr->idFrom < m_tooltips.size() && m_tooltips[hdr->idFrom])
644 str = m_tooltips[hdr->idFrom]->GetTip();
645
646 if ( HandleTooltipNotify(hdr->code, lParam, str))
647 {
648 // processed
649 return true;
650 }
651 }
652
653 return false;
654 }
655 #endif // wxUSE_TOOLTIPS
656
657 #endif // wxUSE_STATUSBAR && wxUSE_NATIVE_STATUSBAR