]> git.saurik.com Git - wxWidgets.git/blob - src/msw/tooltip.cpp
853b96ac633d751858aabe1d71b5c41ee5d5fe38
[wxWidgets.git] / src / msw / tooltip.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/tooltip.cpp
3 // Purpose: wxToolTip class implementation for MSW
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 31.01.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #if wxUSE_TOOLTIPS
27
28 #include "wx/tooltip.h"
29
30 #ifndef WX_PRECOMP
31 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
32 #include "wx/app.h"
33 #include "wx/control.h"
34 #endif
35
36 #include "wx/tokenzr.h"
37 #include "wx/vector.h"
38 #include "wx/msw/private.h"
39
40 #ifndef TTTOOLINFO_V1_SIZE
41 #define TTTOOLINFO_V1_SIZE 0x28
42 #endif
43
44 #ifndef TTF_TRANSPARENT
45 #define TTF_TRANSPARENT 0x0100
46 #endif
47
48 // VZ: normally, the trick with subclassing the tooltip control and processing
49 // TTM_WINDOWFROMPOINT should work but, somehow, it doesn't. I leave the
50 // code here for now (but it's not compiled) in case we need it later.
51 //
52 // For now I use an ugly workaround and process TTN_NEEDTEXT directly in
53 // radio button wnd proc - fixing TTM_WINDOWFROMPOINT code would be nice
54 // because it would then work for all controls, not only radioboxes but for
55 // now I don't understand what's wrong with it...
56 #define wxUSE_TTM_WINDOWFROMPOINT 0
57
58 // ----------------------------------------------------------------------------
59 // global variables
60 // ----------------------------------------------------------------------------
61
62 // the tooltip parent window
63 WXHWND wxToolTip::ms_hwndTT = (WXHWND)NULL;
64
65 // new tooltip maximum width, default value is set on first call to wxToolTip::Add()
66 int wxToolTip::ms_maxWidth = 0;
67
68 #if wxUSE_TTM_WINDOWFROMPOINT
69
70 // the tooltip window proc
71 static WNDPROC gs_wndprocToolTip = (WNDPROC)NULL;
72
73 #endif // wxUSE_TTM_WINDOWFROMPOINT
74
75 // ----------------------------------------------------------------------------
76 // private classes
77 // ----------------------------------------------------------------------------
78
79 // This is simply a wrapper for vector<HWND> but defined as a class to hide the
80 // details from the public header.
81 class wxToolTipOtherWindows : public wxVector<WXHWND>
82 {
83 };
84
85 // a wrapper around TOOLINFO Win32 structure
86 #ifdef __VISUALC__
87 #pragma warning( disable : 4097 ) // we inherit from a typedef - so what?
88 #endif
89
90 class wxToolInfo : public TOOLINFO
91 {
92 public:
93 wxToolInfo(HWND hwndOwner, unsigned int id, const wxRect& rc)
94 {
95 // initialize all members
96 ::ZeroMemory(this, sizeof(TOOLINFO));
97
98 // the structure TOOLINFO has been extended with a 4 byte field in
99 // version 4.70 of comctl32.dll and another one in 5.01 but we don't
100 // use these extended fields so use the old struct size to ensure that
101 // the tooltips work on old (Windows 95) systems too
102 cbSize = TTTOOLINFO_V1_SIZE;
103
104 hwnd = hwndOwner;
105
106 if (rc.IsEmpty())
107 {
108 uFlags = TTF_IDISHWND;
109 uId = (UINT_PTR)hwndOwner;
110 }
111 else
112 {
113 // this tooltip must be shown only if the mouse hovers a specific rect
114 // of the hwnd parameter!
115 rect.left = rc.GetLeft();
116 rect.right = rc.GetRight();
117 rect.top = rc.GetTop();
118 rect.bottom = rc.GetBottom();
119
120 // note that not setting TTF_IDISHWND from the uFlags member means that the
121 // ti.uId field should not contain the HWND but rather as MSDN says an
122 // "Application-defined identifier of the tool"; this is used internally by
123 // Windows to distinguish the different tooltips attached to the same window
124 uId = id;
125 }
126
127 // we use TTF_TRANSPARENT to fix a problem which arises at least with
128 // the text controls but may presumably happen with other controls
129 // which display the tooltip at mouse position: it can start flashing
130 // then as the control gets "focus lost" events and dismisses the
131 // tooltip which then reappears because mouse remains hovering over the
132 // control, see SF patch 1821229
133 if ( wxApp::GetComCtl32Version() >= 470 )
134 {
135 uFlags |= TTF_TRANSPARENT;
136 }
137 }
138 };
139
140 #ifdef __VISUALC__
141 #pragma warning( default : 4097 )
142 #endif
143
144 // ----------------------------------------------------------------------------
145 // private functions
146 // ----------------------------------------------------------------------------
147
148 // send a message to the tooltip control if it exists
149 //
150 // NB: wParam is always 0 for the TTM_XXX messages we use
151 static inline LRESULT SendTooltipMessage(WXHWND hwnd, UINT msg, void *lParam)
152 {
153 return hwnd ? ::SendMessage((HWND)hwnd, msg, 0, (LPARAM)lParam) : 0;
154 }
155
156 // send a message to all existing tooltip controls
157 static inline void
158 SendTooltipMessageToAll(WXHWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
159 {
160 if ( hwnd )
161 ::SendMessage((HWND)hwnd, msg, wParam, lParam);
162 }
163
164 // ============================================================================
165 // implementation
166 // ============================================================================
167
168 #if wxUSE_TTM_WINDOWFROMPOINT
169
170 // ----------------------------------------------------------------------------
171 // window proc for our tooltip control
172 // ----------------------------------------------------------------------------
173
174 LRESULT APIENTRY wxToolTipWndProc(HWND hwndTT,
175 UINT msg,
176 WPARAM wParam,
177 LPARAM lParam)
178 {
179 if ( msg == TTM_WINDOWFROMPOINT )
180 {
181 LPPOINT ppt = (LPPOINT)lParam;
182
183 // the window on which event occurred
184 HWND hwnd = ::WindowFromPoint(*ppt);
185
186 OutputDebugString("TTM_WINDOWFROMPOINT: ");
187 OutputDebugString(wxString::Format("0x%08x => ", hwnd));
188
189 // return a HWND corresponding to a wxWindow because only wxWidgets are
190 // associated with tooltips using TTM_ADDTOOL
191 wxWindow *win = wxGetWindowFromHWND((WXHWND)hwnd);
192
193 if ( win )
194 {
195 hwnd = GetHwndOf(win);
196 OutputDebugString(wxString::Format("0x%08x\r\n", hwnd));
197
198 #if 0
199 // modify the point too!
200 RECT rect;
201 GetWindowRect(hwnd, &rect);
202
203 ppt->x = (rect.right - rect.left) / 2;
204 ppt->y = (rect.bottom - rect.top) / 2;
205 #endif // 0
206 return (LRESULT)hwnd;
207 }
208 else
209 {
210 OutputDebugString("no window\r\n");
211 }
212 }
213
214 return ::CallWindowProc(CASTWNDPROC gs_wndprocToolTip, hwndTT, msg, wParam, lParam);
215 }
216
217 #endif // wxUSE_TTM_WINDOWFROMPOINT
218
219 // ----------------------------------------------------------------------------
220 // static functions
221 // ----------------------------------------------------------------------------
222
223 void wxToolTip::Enable(bool flag)
224 {
225 // Make sure the tooltip has been created
226 (void) GetToolTipCtrl();
227
228 SendTooltipMessageToAll(ms_hwndTT, TTM_ACTIVATE, flag, 0);
229 }
230
231 void wxToolTip::SetDelay(long milliseconds)
232 {
233 // Make sure the tooltip has been created
234 (void) GetToolTipCtrl();
235
236 SendTooltipMessageToAll(ms_hwndTT, TTM_SETDELAYTIME,
237 TTDT_INITIAL, milliseconds);
238 }
239
240 void wxToolTip::SetAutoPop(long milliseconds)
241 {
242 SendTooltipMessageToAll(ms_hwndTT, TTM_SETDELAYTIME,
243 TTDT_AUTOPOP, milliseconds);
244 }
245
246 void wxToolTip::SetReshow(long milliseconds)
247 {
248 SendTooltipMessageToAll(ms_hwndTT, TTM_SETDELAYTIME,
249 TTDT_RESHOW, milliseconds);
250 }
251
252 void wxToolTip::SetMaxWidth(int width)
253 {
254 wxASSERT_MSG( width == -1 || width >= 0, wxT("invalid width value") );
255
256 ms_maxWidth = width;
257 }
258
259 // ---------------------------------------------------------------------------
260 // implementation helpers
261 // ---------------------------------------------------------------------------
262
263 // create the tooltip ctrl for our parent frame if it doesn't exist yet
264 /* static */
265 WXHWND wxToolTip::GetToolTipCtrl()
266 {
267 if ( !ms_hwndTT )
268 {
269 WXDWORD exflags = 0;
270 if ( wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft )
271 {
272 exflags |= WS_EX_LAYOUTRTL;
273 }
274
275 // we want to show the tooltips always (even when the window is not
276 // active) and we don't want to strip "&"s from them
277 ms_hwndTT = (WXHWND)::CreateWindowEx(exflags,
278 TOOLTIPS_CLASS,
279 (LPCTSTR)NULL,
280 TTS_ALWAYSTIP | TTS_NOPREFIX,
281 CW_USEDEFAULT, CW_USEDEFAULT,
282 CW_USEDEFAULT, CW_USEDEFAULT,
283 NULL, (HMENU)NULL,
284 wxGetInstance(),
285 NULL);
286 if ( ms_hwndTT )
287 {
288 HWND hwnd = (HWND)ms_hwndTT;
289 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
290 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
291
292 #if wxUSE_TTM_WINDOWFROMPOINT
293 // subclass the newly created control
294 gs_wndprocToolTip = wxSetWindowProc(hwnd, wxToolTipWndProc);
295 #endif // wxUSE_TTM_WINDOWFROMPOINT
296 }
297 }
298
299 return ms_hwndTT;
300 }
301
302 /* static */
303 void wxToolTip::RelayEvent(WXMSG *msg)
304 {
305 (void)SendTooltipMessage(GetToolTipCtrl(), TTM_RELAYEVENT, msg);
306 }
307
308 // ----------------------------------------------------------------------------
309 // ctor & dtor
310 // ----------------------------------------------------------------------------
311
312 IMPLEMENT_ABSTRACT_CLASS(wxToolTip, wxObject)
313
314 wxToolTip::wxToolTip(const wxString &tip)
315 : m_text(tip)
316 {
317 m_window = NULL;
318 m_others = NULL;
319
320 // make sure m_rect.IsEmpty() == true
321 m_rect.SetWidth(0);
322 m_rect.SetHeight(0);
323
324 // since m_rect is not valid, m_id is ignored by wxToolInfo ctor...
325 m_id = 0;
326 }
327
328 wxToolTip::wxToolTip(wxWindow* win, unsigned int id, const wxString &tip, const wxRect& rc)
329 : m_text(tip), m_rect(rc), m_id(id)
330 {
331 m_window = NULL;
332 m_others = NULL;
333
334 SetWindow(win);
335 }
336
337 wxToolTip::~wxToolTip()
338 {
339 // the tooltip has to be removed before deleting. Otherwise, if it is visible
340 // while being deleted, there will be a delay before it goes away.
341 Remove();
342
343 delete m_others;
344 }
345
346 // ----------------------------------------------------------------------------
347 // others
348 // ----------------------------------------------------------------------------
349
350 /* static */
351 void wxToolTip::Remove(WXHWND hWnd, unsigned int id, const wxRect& rc)
352 {
353 wxToolInfo ti((HWND)hWnd, id, rc);
354
355 (void)SendTooltipMessage(GetToolTipCtrl(), TTM_DELTOOL, &ti);
356 }
357
358 void wxToolTip::DoRemove(WXHWND hWnd)
359 {
360 if ( m_window && hWnd == m_window->GetHWND() )
361 {
362 // Remove the tooltip from the main window.
363 Remove(hWnd, m_id, m_rect);
364 }
365 else
366 {
367 // Not really sure what to pass to remove in this case...
368 Remove(hWnd, 0, wxRect());
369 }
370 }
371
372 void wxToolTip::Remove()
373 {
374 DoForAllWindows(&wxToolTip::DoRemove);
375 }
376
377 void wxToolTip::AddOtherWindow(WXHWND hWnd)
378 {
379 if ( !m_others )
380 m_others = new wxToolTipOtherWindows;
381
382 m_others->push_back(hWnd);
383
384 DoAddHWND(hWnd);
385 }
386
387 void wxToolTip::DoAddHWND(WXHWND hWnd)
388 {
389 HWND hwnd = (HWND)hWnd;
390
391 wxToolInfo ti(hwnd, m_id, m_rect);
392
393 // another possibility would be to specify LPSTR_TEXTCALLBACK here as we
394 // store the tooltip text ourselves anyhow, and provide it in response to
395 // TTN_NEEDTEXT (sent via WM_NOTIFY), but then we would be limited to 79
396 // character tooltips as this is the size of the szText buffer in
397 // NMTTDISPINFO struct -- and setting the tooltip here we can have tooltips
398 // of any length
399 ti.hwnd = hwnd;
400 ti.lpszText = const_cast<wxChar *>(m_text.wx_str());
401
402 if ( !SendTooltipMessage(GetToolTipCtrl(), TTM_ADDTOOL, &ti) )
403 {
404 wxLogDebug(wxT("Failed to create the tooltip '%s'"), m_text.c_str());
405
406 return;
407 }
408
409 #ifdef TTM_SETMAXTIPWIDTH
410 if ( wxApp::GetComCtl32Version() >= 470 )
411 {
412 // use TTM_SETMAXTIPWIDTH to make tooltip multiline using the
413 // extent of its first line as max value
414 HFONT hfont = (HFONT)
415 SendTooltipMessage(GetToolTipCtrl(), WM_GETFONT, 0);
416
417 if ( !hfont )
418 {
419 hfont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
420 if ( !hfont )
421 {
422 wxLogLastError(wxT("GetStockObject(DEFAULT_GUI_FONT)"));
423 }
424 }
425
426 MemoryHDC hdc;
427 if ( !hdc )
428 {
429 wxLogLastError(wxT("CreateCompatibleDC(NULL)"));
430 }
431
432 if ( !SelectObject(hdc, hfont) )
433 {
434 wxLogLastError(wxT("SelectObject(hfont)"));
435 }
436
437 // find the width of the widest line
438 int maxWidth = 0;
439 wxStringTokenizer tokenizer(m_text, wxT("\n"));
440 while ( tokenizer.HasMoreTokens() )
441 {
442 const wxString token = tokenizer.GetNextToken();
443
444 SIZE sz;
445 if ( !::GetTextExtentPoint32(hdc, token.wx_str(),
446 token.length(), &sz) )
447 {
448 wxLogLastError(wxT("GetTextExtentPoint32"));
449 }
450
451 if ( sz.cx > maxWidth )
452 maxWidth = sz.cx;
453 }
454
455 // limit size to ms_maxWidth, if set
456 if ( ms_maxWidth == 0 )
457 {
458 // this is more or less arbitrary but seems to work well
459 static const int DEFAULT_MAX_WIDTH = 400;
460
461 ms_maxWidth = wxGetClientDisplayRect().width / 2;
462
463 if ( ms_maxWidth > DEFAULT_MAX_WIDTH )
464 ms_maxWidth = DEFAULT_MAX_WIDTH;
465 }
466
467 if ( ms_maxWidth != -1 && maxWidth > ms_maxWidth )
468 maxWidth = ms_maxWidth;
469
470 // only set a new width if it is bigger than the current setting:
471 // otherwise adding a tooltip with shorter line(s) than a previous
472 // one would result in breaking the longer lines unnecessarily as
473 // all our tooltips share the same maximal width
474 if ( maxWidth > SendTooltipMessage(GetToolTipCtrl(),
475 TTM_GETMAXTIPWIDTH, 0) )
476 {
477 SendTooltipMessage(GetToolTipCtrl(), TTM_SETMAXTIPWIDTH,
478 wxUIntToPtr(maxWidth));
479 }
480 }
481 else
482 #endif // TTM_SETMAXTIPWIDTH
483 {
484 // replace the '\n's with spaces because otherwise they appear as
485 // unprintable characters in the tooltip string
486 m_text.Replace(wxT("\n"), wxT(" "));
487 ti.lpszText = const_cast<wxChar *>(m_text.wx_str());
488
489 if ( !SendTooltipMessage(GetToolTipCtrl(), TTM_ADDTOOL, &ti) )
490 {
491 wxLogDebug(wxT("Failed to create the tooltip '%s'"), m_text.c_str());
492 }
493 }
494 }
495
496 void wxToolTip::SetWindow(wxWindow *win)
497 {
498 Remove();
499
500 m_window = win;
501
502 // add the window itself
503 if ( m_window )
504 {
505 AddOtherWindow(m_window->GetHWND());
506 }
507 #if !defined(__WXUNIVERSAL__)
508 // and all of its subcontrols (e.g. radio buttons in a radiobox) as well
509 wxControl *control = wxDynamicCast(m_window, wxControl);
510 if ( control )
511 {
512 const wxArrayLong& subcontrols = control->GetSubcontrols();
513 size_t count = subcontrols.GetCount();
514 for ( size_t n = 0; n < count; n++ )
515 {
516 int id = subcontrols[n];
517 HWND hwnd = GetDlgItem(GetHwndOf(m_window), id);
518 if ( !hwnd )
519 {
520 // maybe it's a child of parent of the control, in fact?
521 // (radiobuttons are subcontrols, i.e. children of the radiobox
522 // for wxWidgets but are its siblings at Windows level)
523 hwnd = GetDlgItem(GetHwndOf(m_window->GetParent()), id);
524 }
525
526 // must have it by now!
527 wxASSERT_MSG( hwnd, wxT("no hwnd for subcontrol?") );
528
529 AddOtherWindow((WXHWND)hwnd);
530 }
531 }
532 #endif // !defined(__WXUNIVERSAL__)
533 }
534
535 void wxToolTip::SetRect(const wxRect& rc)
536 {
537 m_rect = rc;
538
539 if ( m_window )
540 {
541 wxToolInfo ti(GetHwndOf(m_window), m_id, m_rect);
542 (void)SendTooltipMessage(GetToolTipCtrl(), TTM_NEWTOOLRECT, &ti);
543 }
544 }
545
546 void wxToolTip::SetTip(const wxString& tip)
547 {
548 m_text = tip;
549
550 DoForAllWindows(&wxToolTip::DoSetTip);
551 }
552
553 void wxToolTip::DoSetTip(WXHWND hWnd)
554 {
555 // update the tip text shown by the control
556 wxToolInfo ti((HWND)hWnd, m_id, m_rect);
557
558 // for some reason, changing the tooltip text directly results in
559 // repaint of the controls under it, see #10520 -- but this doesn't
560 // happen if we reset it first
561 ti.lpszText = const_cast<wxChar *>(wxT(""));
562 (void)SendTooltipMessage(GetToolTipCtrl(), TTM_UPDATETIPTEXT, &ti);
563
564 ti.lpszText = const_cast<wxChar *>(m_text.wx_str());
565 (void)SendTooltipMessage(GetToolTipCtrl(), TTM_UPDATETIPTEXT, &ti);
566 }
567
568 void wxToolTip::DoForAllWindows(void (wxToolTip::*func)(WXHWND))
569 {
570 if ( m_window )
571 {
572 (this->*func)(m_window->GetHWND());
573 }
574
575 if ( m_others )
576 {
577 for ( wxToolTipOtherWindows::const_iterator it = m_others->begin();
578 it != m_others->end();
579 ++it )
580 {
581 (this->*func)(*it);
582 }
583 }
584 }
585
586 #endif // wxUSE_TOOLTIPS