Implement delayed destruction for wxPopupTransientWindow.
[wxWidgets.git] / src / common / popupcmn.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/popupcmn.cpp
3 // Purpose: implementation of wxPopupTransientWindow
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 06.01.01
7 // RCS-ID: $Id$
8 // Copyright: (c) 2001 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_POPUPWIN
28
29 #include "wx/popupwin.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/combobox.h" // wxComboCtrl
33 #include "wx/app.h" // wxPostEvent
34 #include "wx/log.h"
35 #endif //WX_PRECOMP
36
37 #include "wx/display.h"
38 #include "wx/recguard.h"
39
40 #ifdef __WXUNIVERSAL__
41 #include "wx/univ/renderer.h"
42 #include "wx/scrolbar.h"
43 #endif // __WXUNIVERSAL__
44
45 #ifdef __WXGTK__
46 #include <gtk/gtk.h>
47 #if GTK_CHECK_VERSION(2,0,0)
48 #include "wx/gtk/private/gtk2-compat.h"
49 #else
50 #define gtk_widget_get_window(x) x->window
51 #endif
52 #elif defined(__WXMSW__)
53 #include "wx/msw/private.h"
54 #elif defined(__WXX11__)
55 #include "wx/x11/private.h"
56 #endif
57
58 IMPLEMENT_DYNAMIC_CLASS(wxPopupWindow, wxWindow)
59 IMPLEMENT_DYNAMIC_CLASS(wxPopupTransientWindow, wxPopupWindow)
60
61 #if wxUSE_COMBOBOX && defined(__WXUNIVERSAL__)
62 IMPLEMENT_DYNAMIC_CLASS(wxPopupComboWindow, wxPopupTransientWindow)
63 #endif
64
65 // ----------------------------------------------------------------------------
66 // private classes
67 // ----------------------------------------------------------------------------
68
69 // event handlers which we use to intercept events which cause the popup to
70 // disappear
71 class wxPopupWindowHandler : public wxEvtHandler
72 {
73 public:
74 wxPopupWindowHandler(wxPopupTransientWindow *popup) : m_popup(popup) {}
75
76 protected:
77 // event handlers
78 void OnLeftDown(wxMouseEvent& event);
79
80 private:
81 wxPopupTransientWindow *m_popup;
82
83 DECLARE_EVENT_TABLE()
84 wxDECLARE_NO_COPY_CLASS(wxPopupWindowHandler);
85 };
86
87 class wxPopupFocusHandler : public wxEvtHandler
88 {
89 public:
90 wxPopupFocusHandler(wxPopupTransientWindow *popup) : m_popup(popup) {}
91
92 protected:
93 void OnKillFocus(wxFocusEvent& event);
94 void OnChar(wxKeyEvent& event);
95
96 private:
97 wxPopupTransientWindow *m_popup;
98
99 DECLARE_EVENT_TABLE()
100 wxDECLARE_NO_COPY_CLASS(wxPopupFocusHandler);
101 };
102
103 // ----------------------------------------------------------------------------
104 // event tables
105 // ----------------------------------------------------------------------------
106
107 BEGIN_EVENT_TABLE(wxPopupWindowHandler, wxEvtHandler)
108 EVT_LEFT_DOWN(wxPopupWindowHandler::OnLeftDown)
109 END_EVENT_TABLE()
110
111 BEGIN_EVENT_TABLE(wxPopupFocusHandler, wxEvtHandler)
112 EVT_KILL_FOCUS(wxPopupFocusHandler::OnKillFocus)
113 EVT_CHAR(wxPopupFocusHandler::OnChar)
114 END_EVENT_TABLE()
115
116 BEGIN_EVENT_TABLE(wxPopupTransientWindow, wxPopupWindow)
117 #if defined( __WXMSW__ ) || ( defined( __WXMAC__ ) && wxOSX_USE_CARBON )
118 EVT_IDLE(wxPopupTransientWindow::OnIdle)
119 #endif
120 END_EVENT_TABLE()
121
122 // ============================================================================
123 // implementation
124 // ============================================================================
125
126 // ----------------------------------------------------------------------------
127 // wxPopupWindowBase
128 // ----------------------------------------------------------------------------
129
130 wxPopupWindowBase::~wxPopupWindowBase()
131 {
132 // this destructor is required for Darwin
133 }
134
135 bool wxPopupWindowBase::Create(wxWindow* WXUNUSED(parent), int WXUNUSED(flags))
136 {
137 return true;
138 }
139
140 void wxPopupWindowBase::Position(const wxPoint& ptOrigin,
141 const wxSize& size)
142 {
143 // determine the position and size of the screen we clamp the popup to
144 wxPoint posScreen;
145 wxSize sizeScreen;
146
147 const int displayNum = wxDisplay::GetFromPoint(ptOrigin);
148 if ( displayNum != wxNOT_FOUND )
149 {
150 const wxRect rectScreen = wxDisplay(displayNum).GetGeometry();
151 posScreen = rectScreen.GetPosition();
152 sizeScreen = rectScreen.GetSize();
153 }
154 else // outside of any display?
155 {
156 // just use the primary one then
157 posScreen = wxPoint(0, 0);
158 sizeScreen = wxGetDisplaySize();
159 }
160
161
162 const wxSize sizeSelf = GetSize();
163
164 // is there enough space to put the popup below the window (where we put it
165 // by default)?
166 wxCoord y = ptOrigin.y + size.y;
167 if ( y + sizeSelf.y > posScreen.y + sizeScreen.y )
168 {
169 // check if there is enough space above
170 if ( ptOrigin.y > sizeSelf.y )
171 {
172 // do position the control above the window
173 y -= size.y + sizeSelf.y;
174 }
175 //else: not enough space below nor above, leave below
176 }
177
178 // now check left/right too
179 wxCoord x = ptOrigin.x;
180
181 if ( wxTheApp->GetLayoutDirection() == wxLayout_RightToLeft )
182 {
183 // shift the window to the left instead of the right.
184 x -= size.x;
185 x -= sizeSelf.x; // also shift it by window width.
186 }
187 else
188 x += size.x;
189
190
191 if ( x + sizeSelf.x > posScreen.x + sizeScreen.x )
192 {
193 // check if there is enough space to the left
194 if ( ptOrigin.x > sizeSelf.x )
195 {
196 // do position the control to the left
197 x -= size.x + sizeSelf.x;
198 }
199 //else: not enough space there neither, leave in default position
200 }
201
202 Move(x, y, wxSIZE_NO_ADJUSTMENTS);
203 }
204
205 // ----------------------------------------------------------------------------
206 // wxPopupTransientWindow
207 // ----------------------------------------------------------------------------
208
209 void wxPopupTransientWindow::Init()
210 {
211 m_child =
212 m_focus = NULL;
213
214 m_handlerFocus = NULL;
215 m_handlerPopup = NULL;
216 }
217
218 wxPopupTransientWindow::wxPopupTransientWindow(wxWindow *parent, int style)
219 {
220 Init();
221
222 (void)Create(parent, style);
223 }
224
225 wxPopupTransientWindow::~wxPopupTransientWindow()
226 {
227 if (m_handlerPopup && m_handlerPopup->GetNextHandler())
228 PopHandlers();
229
230 wxASSERT(!m_handlerFocus || !m_handlerFocus->GetNextHandler());
231 wxASSERT(!m_handlerPopup || !m_handlerPopup->GetNextHandler());
232
233 delete m_handlerFocus;
234 delete m_handlerPopup;
235 }
236
237 void wxPopupTransientWindow::PopHandlers()
238 {
239 if ( m_child )
240 {
241 if ( !m_child->RemoveEventHandler(m_handlerPopup) )
242 {
243 // something is very wrong and someone else probably deleted our
244 // handler - so don't risk deleting it second time
245 m_handlerPopup = NULL;
246 }
247 if (m_child->HasCapture())
248 {
249 m_child->ReleaseMouse();
250 }
251 m_child = NULL;
252 }
253
254 if ( m_focus )
255 {
256 if ( !m_focus->RemoveEventHandler(m_handlerFocus) )
257 {
258 // see above
259 m_handlerFocus = NULL;
260 }
261 }
262 m_focus = NULL;
263 }
264
265 void wxPopupTransientWindow::Popup(wxWindow *winFocus)
266 {
267 const wxWindowList& children = GetChildren();
268 if ( children.GetCount() )
269 {
270 m_child = children.GetFirst()->GetData();
271 }
272 else
273 {
274 m_child = this;
275 }
276
277 Show();
278
279 // There is a problem if these are still in use
280 wxASSERT(!m_handlerFocus || !m_handlerFocus->GetNextHandler());
281 wxASSERT(!m_handlerPopup || !m_handlerPopup->GetNextHandler());
282
283 if (!m_handlerPopup)
284 m_handlerPopup = new wxPopupWindowHandler(this);
285
286 m_child->PushEventHandler(m_handlerPopup);
287
288 #if defined(__WXMSW__)
289 // Focusing on child of popup window does not work on MSW unless WS_POPUP
290 // style is set. We do not even want to try to set the focus, as it may
291 // provoke errors on some Windows versions (Vista and later).
292 if ( ::GetWindowLong(GetHwnd(), GWL_STYLE) & WS_POPUP )
293 #endif
294 {
295 m_focus = winFocus ? winFocus : this;
296 m_focus->SetFocus();
297 }
298
299 #if defined( __WXMSW__ ) || (defined( __WXMAC__) && wxOSX_USE_CARBON)
300 // MSW doesn't allow to set focus to the popup window, but we need to
301 // subclass the window which has the focus, and not winFocus passed in or
302 // otherwise everything else breaks down
303 m_focus = FindFocus();
304 #elif defined(__WXGTK__)
305 // GTK+ catches the activate events from the popup
306 // window, not the focus events from the child window
307 m_focus = this;
308 #endif
309
310 if ( m_focus )
311 {
312 if (!m_handlerFocus)
313 m_handlerFocus = new wxPopupFocusHandler(this);
314
315 m_focus->PushEventHandler(m_handlerFocus);
316 }
317 }
318
319 bool wxPopupTransientWindow::Show( bool show )
320 {
321 #ifdef __WXGTK__
322 if (!show)
323 {
324 gdk_pointer_ungrab( (guint32)GDK_CURRENT_TIME );
325
326 gtk_grab_remove( m_widget );
327 }
328 #endif
329
330 #ifdef __WXX11__
331 if (!show)
332 {
333 XUngrabPointer( wxGlobalDisplay(), CurrentTime );
334 }
335 #endif
336
337 #if defined( __WXMSW__ ) || defined( __WXMAC__)
338 if (!show && m_child && m_child->HasCapture())
339 {
340 m_child->ReleaseMouse();
341 }
342 #endif
343
344 bool ret = wxPopupWindow::Show( show );
345
346 #ifdef __WXGTK__
347 if (show)
348 {
349 gtk_grab_add( m_widget );
350
351 gdk_pointer_grab( gtk_widget_get_window(m_widget), true,
352 (GdkEventMask)
353 (GDK_BUTTON_PRESS_MASK |
354 GDK_BUTTON_RELEASE_MASK |
355 GDK_POINTER_MOTION_HINT_MASK |
356 GDK_POINTER_MOTION_MASK),
357 NULL,
358 NULL,
359 (guint32)GDK_CURRENT_TIME );
360 }
361 #endif
362
363 #ifdef __WXX11__
364 if (show)
365 {
366 Window xwindow = (Window) m_clientWindow;
367
368 /* int res =*/ XGrabPointer(wxGlobalDisplay(), xwindow,
369 True,
370 ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
371 GrabModeAsync,
372 GrabModeAsync,
373 None,
374 None,
375 CurrentTime );
376 }
377 #endif
378
379 #if defined( __WXMSW__ ) || defined( __WXMAC__)
380 if (show && m_child)
381 {
382 // Assume that the mouse is outside the popup to begin with
383 m_child->CaptureMouse();
384 }
385 #endif
386
387 return ret;
388 }
389
390 bool wxPopupTransientWindow::Destroy()
391 {
392 // The popup window can be deleted at any moment, even while some events
393 // are still being processed for it, so delay its real destruction until
394 // the next idle time when we're sure that it's safe to really destroy it.
395
396 wxCHECK_MSG( !wxPendingDelete.Member(this), false,
397 wxS("Shouldn't destroy the popup twice.") );
398
399 wxPendingDelete.Append(this);
400
401 return true;
402 }
403
404 void wxPopupTransientWindow::Dismiss()
405 {
406 Hide();
407 PopHandlers();
408 }
409
410 void wxPopupTransientWindow::DismissAndNotify()
411 {
412 Dismiss();
413 OnDismiss();
414 }
415
416 void wxPopupTransientWindow::OnDismiss()
417 {
418 // nothing to do here - but it may be interesting for derived class
419 }
420
421 bool wxPopupTransientWindow::ProcessLeftDown(wxMouseEvent& WXUNUSED(event))
422 {
423 // no special processing here
424 return false;
425 }
426
427 #if defined( __WXMSW__ ) || ( defined( __WXMAC__ ) && wxOSX_USE_CARBON )
428 void wxPopupTransientWindow::OnIdle(wxIdleEvent& event)
429 {
430 event.Skip();
431
432 if (IsShown() && m_child)
433 {
434 wxPoint pos = ScreenToClient(wxGetMousePosition());
435 wxRect rect(GetSize());
436
437 if ( rect.Contains(pos) )
438 {
439 if ( m_child->HasCapture() )
440 {
441 m_child->ReleaseMouse();
442 }
443 }
444 else
445 {
446 if ( !m_child->HasCapture() )
447 {
448 m_child->CaptureMouse();
449 }
450 }
451 }
452 }
453 #endif // __WXMSW__
454
455
456 #if wxUSE_COMBOBOX && defined(__WXUNIVERSAL__)
457
458 // ----------------------------------------------------------------------------
459 // wxPopupComboWindow
460 // ----------------------------------------------------------------------------
461
462 BEGIN_EVENT_TABLE(wxPopupComboWindow, wxPopupTransientWindow)
463 EVT_KEY_DOWN(wxPopupComboWindow::OnKeyDown)
464 END_EVENT_TABLE()
465
466 wxPopupComboWindow::wxPopupComboWindow(wxComboCtrl *parent)
467 : wxPopupTransientWindow(parent)
468 {
469 m_combo = parent;
470 }
471
472 bool wxPopupComboWindow::Create(wxComboCtrl *parent)
473 {
474 m_combo = parent;
475
476 return wxPopupWindow::Create(parent);
477 }
478
479 void wxPopupComboWindow::PositionNearCombo()
480 {
481 // the origin point must be in screen coords
482 wxPoint ptOrigin = m_combo->ClientToScreen(wxPoint(0,0));
483
484 #if 0 //def __WXUNIVERSAL__
485 // account for the fact that (0, 0) is not the top left corner of the
486 // window: there is also the border
487 wxRect rectBorders = m_combo->GetRenderer()->
488 GetBorderDimensions(m_combo->GetBorder());
489 ptOrigin.x -= rectBorders.x;
490 ptOrigin.y -= rectBorders.y;
491 #endif // __WXUNIVERSAL__
492
493 // position below or above the combobox: the width is 0 to put it exactly
494 // below us, not to the left or to the right
495 Position(ptOrigin, wxSize(0, m_combo->GetSize().y));
496 }
497
498 void wxPopupComboWindow::OnDismiss()
499 {
500 m_combo->OnPopupDismiss(true);
501 }
502
503 void wxPopupComboWindow::OnKeyDown(wxKeyEvent& event)
504 {
505 m_combo->ProcessWindowEvent(event);
506 }
507
508 #endif // wxUSE_COMBOBOX && defined(__WXUNIVERSAL__)
509
510 // ----------------------------------------------------------------------------
511 // wxPopupWindowHandler
512 // ----------------------------------------------------------------------------
513
514 void wxPopupWindowHandler::OnLeftDown(wxMouseEvent& event)
515 {
516 // let the window have it first (we're the first event handler in the chain
517 // of handlers for this window)
518 if ( m_popup->ProcessLeftDown(event) )
519 {
520 return;
521 }
522
523 wxPoint pos = event.GetPosition();
524
525 // in non-Univ ports the system manages scrollbars for us
526 #if defined(__WXUNIVERSAL__) && wxUSE_SCROLLBAR
527 // scrollbar on which the click occurred
528 wxWindow *sbar = NULL;
529 #endif // __WXUNIVERSAL__ && wxUSE_SCROLLBAR
530
531 wxWindow *win = (wxWindow *)event.GetEventObject();
532
533 switch ( win->HitTest(pos.x, pos.y) )
534 {
535 case wxHT_WINDOW_OUTSIDE:
536 {
537 // do the coords translation now as after DismissAndNotify()
538 // m_popup may be destroyed
539 wxMouseEvent event2(event);
540
541 m_popup->ClientToScreen(&event2.m_x, &event2.m_y);
542
543 // clicking outside a popup dismisses it
544 m_popup->DismissAndNotify();
545
546 // dismissing a tooltip shouldn't waste a click, i.e. you
547 // should be able to dismiss it and press the button with the
548 // same click, so repost this event to the window beneath us
549 wxWindow *winUnder = wxFindWindowAtPoint(event2.GetPosition());
550 if ( winUnder )
551 {
552 // translate the event coords to the ones of the window
553 // which is going to get the event
554 winUnder->ScreenToClient(&event2.m_x, &event2.m_y);
555
556 event2.SetEventObject(winUnder);
557 wxPostEvent(winUnder->GetEventHandler(), event2);
558 }
559 }
560 break;
561
562 #if defined(__WXUNIVERSAL__) && wxUSE_SCROLLBAR
563 case wxHT_WINDOW_HORZ_SCROLLBAR:
564 sbar = win->GetScrollbar(wxHORIZONTAL);
565 break;
566
567 case wxHT_WINDOW_VERT_SCROLLBAR:
568 sbar = win->GetScrollbar(wxVERTICAL);
569 break;
570 #endif // __WXUNIVERSAL__ && wxUSE_SCROLLBAR
571
572 default:
573 // forgot to update the switch after adding a new hit test code?
574 wxFAIL_MSG( wxT("unexpected HitTest() return value") );
575 // fall through
576
577 case wxHT_WINDOW_CORNER:
578 // don't actually know if this one is good for anything, but let it
579 // pass just in case
580
581 case wxHT_WINDOW_INSIDE:
582 // let the normal processing take place
583 event.Skip();
584 break;
585 }
586
587 #if defined(__WXUNIVERSAL__) && wxUSE_SCROLLBAR
588 if ( sbar )
589 {
590 // translate the event coordinates to the scrollbar ones
591 pos = sbar->ScreenToClient(win->ClientToScreen(pos));
592
593 // and give the event to it
594 wxMouseEvent event2 = event;
595 event2.m_x = pos.x;
596 event2.m_y = pos.y;
597
598 (void)sbar->GetEventHandler()->ProcessEvent(event2);
599 }
600 #endif // __WXUNIVERSAL__ && wxUSE_SCROLLBAR
601 }
602
603 // ----------------------------------------------------------------------------
604 // wxPopupFocusHandler
605 // ----------------------------------------------------------------------------
606
607 void wxPopupFocusHandler::OnKillFocus(wxFocusEvent& event)
608 {
609 // when we lose focus we always disappear - unless it goes to the popup (in
610 // which case we don't really lose it)
611 wxWindow *win = event.GetWindow();
612 while ( win )
613 {
614 if ( win == m_popup )
615 return;
616 win = win->GetParent();
617 }
618
619 m_popup->DismissAndNotify();
620 }
621
622 void wxPopupFocusHandler::OnChar(wxKeyEvent& event)
623 {
624 // we can be associated with the popup itself in which case we should avoid
625 // infinite recursion
626 static int s_inside;
627 wxRecursionGuard guard(s_inside);
628 if ( guard.IsInside() )
629 {
630 event.Skip();
631 return;
632 }
633
634 // let the window have it first, it might process the keys
635 if ( !m_popup->GetEventHandler()->ProcessEvent(event) )
636 {
637 // by default, dismiss the popup
638 m_popup->DismissAndNotify();
639 }
640 }
641
642 #endif // wxUSE_POPUPWIN