1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/common/window.cpp
3 // Purpose:     common (to all ports) wxWindow functions
4 // Author:      Julian Smart, Vadim Zeitlin
5 // Modified by:
6 // Created:     13/07/98
7 // RCS-ID:      $Id: wincmn.cpp 63032 2009-12-31 13:37:24Z VZ $
8 // Copyright:   (c) wxWidgets team
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 #ifndef WX_PRECOMP
28     #include "wx/string.h"
29     #include "wx/log.h"
30     #include "wx/intl.h"
31     #include "wx/frame.h"
32     #include "wx/window.h"
33     #include "wx/control.h"
34     #include "wx/checkbox.h"
35     #include "wx/radiobut.h"
36     #include "wx/statbox.h"
37     #include "wx/textctrl.h"
38     #include "wx/settings.h"
39     #include "wx/dialog.h"
40     #include "wx/msgdlg.h"
41     #include "wx/statusbr.h"
42     #include "wx/toolbar.h"
43     #include "wx/dcclient.h"
44     #include "wx/scrolbar.h"
45     #include "wx/layout.h"
46     #include "wx/sizer.h"
47 #endif //WX_PRECOMP
48 
49 #if wxUSE_DRAG_AND_DROP
50     #include "wx/dnd.h"
51 #endif // wxUSE_DRAG_AND_DROP
52 
53 #if wxUSE_ACCESSIBILITY
54     #include "wx/access.h"
55 #endif
56 
57 #if wxUSE_HELP
58     #include "wx/cshelp.h"
59 #endif // wxUSE_HELP
60 
61 #if wxUSE_TOOLTIPS
62     #include "wx/tooltip.h"
63 #endif // wxUSE_TOOLTIPS
64 
65 #if wxUSE_CARET
66     #include "wx/caret.h"
67 #endif // wxUSE_CARET
68 
69 #if wxUSE_SYSTEM_OPTIONS
70     #include "wx/sysopt.h"
71 #endif
72 
73 // For reporting compile- and runtime version of GTK+ in the ctrl+alt+mclick dialog.
74 // The gtk includes don't pull any other headers in, at least not on my system - MR
75 #ifdef __WXGTK__
76     #ifdef __WXGTK20__
77         #include <gtk/gtkversion.h>
78     #else
79         #include <gtk/gtkfeatures.h>
80     #endif
81     extern const unsigned int gtk_major_version;
82     extern const unsigned int gtk_minor_version;
83     extern const unsigned int gtk_micro_version;
84 #endif
85 
86 #include "wx/platinfo.h"
87 
88 // Windows List
89 WXDLLIMPEXP_DATA_CORE(wxWindowList) wxTopLevelWindows;
90 
91 // ----------------------------------------------------------------------------
92 // static data
93 // ----------------------------------------------------------------------------
94 
95 #if defined(__WXPALMOS__)
96 int wxWindowBase::ms_lastControlId = 32767;
97 #elif defined(__WXPM__)
98 int wxWindowBase::ms_lastControlId = 2000;
99 #else
100 int wxWindowBase::ms_lastControlId = -200;
101 #endif
102 
IMPLEMENT_ABSTRACT_CLASS(wxWindowBase,wxEvtHandler)103 IMPLEMENT_ABSTRACT_CLASS(wxWindowBase, wxEvtHandler)
104 
105 // ----------------------------------------------------------------------------
106 // event table
107 // ----------------------------------------------------------------------------
108 
109 BEGIN_EVENT_TABLE(wxWindowBase, wxEvtHandler)
110     EVT_SYS_COLOUR_CHANGED(wxWindowBase::OnSysColourChanged)
111     EVT_INIT_DIALOG(wxWindowBase::OnInitDialog)
112     EVT_MIDDLE_DOWN(wxWindowBase::OnMiddleClick)
113 
114 #if wxUSE_HELP
115     EVT_HELP(wxID_ANY, wxWindowBase::OnHelp)
116 #endif // wxUSE_HELP
117 
118 END_EVENT_TABLE()
119 
120 // ============================================================================
121 // implementation of the common functionality of the wxWindow class
122 // ============================================================================
123 
124 // ----------------------------------------------------------------------------
125 // initialization
126 // ----------------------------------------------------------------------------
127 
128 // the default initialization
129 wxWindowBase::wxWindowBase()
130 {
131     // no window yet, no parent nor children
132     m_parent = (wxWindow *)NULL;
133     m_windowId = wxID_ANY;
134 
135     // no constraints on the minimal window size
136     m_minWidth =
137     m_maxWidth = wxDefaultCoord;
138     m_minHeight =
139     m_maxHeight = wxDefaultCoord;
140 
141     // invalidiated cache value
142     m_bestSizeCache = wxDefaultSize;
143 
144     // window are created enabled and visible by default
145     m_isShown =
146     m_isEnabled = true;
147 
148     // the default event handler is just this window
149     m_eventHandler = this;
150 
151 #if wxUSE_VALIDATORS
152     // no validator
153     m_windowValidator = (wxValidator *) NULL;
154 #endif // wxUSE_VALIDATORS
155 
156     // the colours/fonts are default for now, so leave m_font,
157     // m_backgroundColour and m_foregroundColour uninitialized and set those
158     m_hasBgCol =
159     m_hasFgCol =
160     m_hasFont = false;
161     m_inheritBgCol =
162     m_inheritFgCol =
163     m_inheritFont = false;
164 
165     // no style bits
166     m_exStyle =
167     m_windowStyle = 0;
168 
169     m_backgroundStyle = wxBG_STYLE_SYSTEM;
170 
171 #if wxUSE_CONSTRAINTS
172     // no constraints whatsoever
173     m_constraints = (wxLayoutConstraints *) NULL;
174     m_constraintsInvolvedIn = (wxWindowList *) NULL;
175 #endif // wxUSE_CONSTRAINTS
176 
177     m_windowSizer = (wxSizer *) NULL;
178     m_containingSizer = (wxSizer *) NULL;
179     m_autoLayout = false;
180 
181 #if wxUSE_DRAG_AND_DROP
182     m_dropTarget = (wxDropTarget *)NULL;
183 #endif // wxUSE_DRAG_AND_DROP
184 
185 #if wxUSE_TOOLTIPS
186     m_tooltip = (wxToolTip *)NULL;
187 #endif // wxUSE_TOOLTIPS
188 
189 #if wxUSE_CARET
190     m_caret = (wxCaret *)NULL;
191 #endif // wxUSE_CARET
192 
193 #if wxUSE_PALETTE
194     m_hasCustomPalette = false;
195 #endif // wxUSE_PALETTE
196 
197 #if wxUSE_ACCESSIBILITY
198     m_accessible = NULL;
199 #endif
200 
201     m_virtualSize = wxDefaultSize;
202 
203     m_scrollHelper = (wxScrollHelper *) NULL;
204 
205     m_minVirtualWidth =
206     m_maxVirtualWidth = wxDefaultCoord;
207     m_minVirtualHeight =
208     m_maxVirtualHeight = wxDefaultCoord;
209 
210     m_windowVariant = wxWINDOW_VARIANT_NORMAL;
211 #if wxUSE_SYSTEM_OPTIONS
212     if ( wxSystemOptions::HasOption(wxWINDOW_DEFAULT_VARIANT) )
213     {
214        m_windowVariant = (wxWindowVariant) wxSystemOptions::GetOptionInt( wxWINDOW_DEFAULT_VARIANT ) ;
215     }
216 #endif
217 
218     // Whether we're using the current theme for this window (wxGTK only for now)
219     m_themeEnabled = false;
220 
221     // VZ: this one shouldn't exist...
222     m_isBeingDeleted = false;
223 }
224 
225 // common part of window creation process
CreateBase(wxWindowBase * parent,wxWindowID id,const wxPoint & WXUNUSED (pos),const wxSize & WXUNUSED (size),long style,const wxValidator & wxVALIDATOR_PARAM (validator),const wxString & name)226 bool wxWindowBase::CreateBase(wxWindowBase *parent,
227                               wxWindowID id,
228                               const wxPoint& WXUNUSED(pos),
229                               const wxSize& WXUNUSED(size),
230                               long style,
231                               const wxValidator& wxVALIDATOR_PARAM(validator),
232                               const wxString& name)
233 {
234 #if wxUSE_STATBOX
235     // wxGTK doesn't allow to create controls with static box as the parent so
236     // this will result in a crash when the program is ported to wxGTK so warn
237     // the user about it
238 
239     // if you get this assert, the correct solution is to create the controls
240     // as siblings of the static box
241     wxASSERT_MSG( !parent || !wxDynamicCast(parent, wxStaticBox),
242                   _T("wxStaticBox can't be used as a window parent!") );
243 #endif // wxUSE_STATBOX
244 
245     // ids are limited to 16 bits under MSW so if you care about portability,
246     // it's not a good idea to use ids out of this range (and negative ids are
247     // reserved for wxWidgets own usage)
248     wxASSERT_MSG( id == wxID_ANY || (id >= 0 && id < 32767),
249                   _T("invalid id value") );
250 
251     // generate a new id if the user doesn't care about it
252     m_windowId = id == wxID_ANY ? NewControlId() : id;
253 
254     // don't use SetWindowStyleFlag() here, this function should only be called
255     // to change the flag after creation as it tries to reflect the changes in
256     // flags by updating the window dynamically and we don't need this here
257     m_windowStyle = style;
258 
259     SetName(name);
260     SetParent(parent);
261 
262 #if wxUSE_VALIDATORS
263     SetValidator(validator);
264 #endif // wxUSE_VALIDATORS
265 
266     // if the parent window has wxWS_EX_VALIDATE_RECURSIVELY set, we want to
267     // have it too - like this it's possible to set it only in the top level
268     // dialog/frame and all children will inherit it by defult
269     if ( parent && (parent->GetExtraStyle() & wxWS_EX_VALIDATE_RECURSIVELY) )
270     {
271         SetExtraStyle(GetExtraStyle() | wxWS_EX_VALIDATE_RECURSIVELY);
272     }
273 
274     return true;
275 }
276 
ToggleWindowStyle(int flag)277 bool wxWindowBase::ToggleWindowStyle(int flag)
278 {
279     wxASSERT_MSG( flag, _T("flags with 0 value can't be toggled") );
280 
281     bool rc;
282     long style = GetWindowStyleFlag();
283     if ( style & flag )
284     {
285         style &= ~flag;
286         rc = false;
287     }
288     else // currently off
289     {
290         style |= flag;
291         rc = true;
292     }
293 
294     SetWindowStyleFlag(style);
295 
296     return rc;
297 }
298 
299 // ----------------------------------------------------------------------------
300 // destruction
301 // ----------------------------------------------------------------------------
302 
303 // common clean up
~wxWindowBase()304 wxWindowBase::~wxWindowBase()
305 {
306     wxASSERT_MSG( GetCapture() != this, wxT("attempt to destroy window with mouse capture") );
307 
308     // FIXME if these 2 cases result from programming errors in the user code
309     //       we should probably assert here instead of silently fixing them
310 
311     // Just in case the window has been Closed, but we're then deleting
312     // immediately: don't leave dangling pointers.
313     wxPendingDelete.DeleteObject(this);
314 
315     // Just in case we've loaded a top-level window via LoadNativeDialog but
316     // we weren't a dialog class
317     wxTopLevelWindows.DeleteObject((wxWindow*)this);
318 
319     wxASSERT_MSG( GetChildren().GetCount() == 0, wxT("children not destroyed") );
320 
321     // reset the top-level parent's default item if it is this widget
322     if ( m_parent )
323     {
324         wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent((wxWindow*)this),
325                                               wxTopLevelWindow);
326 
327         if ( tlw )
328         {
329             wxWindow* tmpDefaultItem = tlw->GetTmpDefaultItem();
330             if ( tmpDefaultItem == this )
331                 tlw->SetTmpDefaultItem(NULL);
332             else if ( tmpDefaultItem )
333             {
334                 // A temporary default item masks the real default item, so
335                 // temporarily unset the temporary default item so we can access the
336                 // real default item.
337                 tlw->SetTmpDefaultItem(NULL);
338 
339                 if ( tlw->GetDefaultItem() == this )
340                     tlw->SetDefaultItem(NULL);
341 
342                 // Set the temporary default item back.
343                 tlw->SetTmpDefaultItem(tmpDefaultItem);
344             }
345             else if ( tlw->GetDefaultItem() == this )
346                 tlw->SetDefaultItem(NULL);
347         }
348     }
349 
350     // reset the dangling pointer our parent window may keep to us
351     if ( m_parent )
352     {
353         m_parent->RemoveChild(this);
354     }
355 
356 #if wxUSE_CARET
357     delete m_caret;
358 #endif // wxUSE_CARET
359 
360 #if wxUSE_VALIDATORS
361     delete m_windowValidator;
362 #endif // wxUSE_VALIDATORS
363 
364 #if wxUSE_CONSTRAINTS
365     // Have to delete constraints/sizer FIRST otherwise sizers may try to look
366     // at deleted windows as they delete themselves.
367     DeleteRelatedConstraints();
368 
369     if ( m_constraints )
370     {
371         // This removes any dangling pointers to this window in other windows'
372         // constraintsInvolvedIn lists.
373         UnsetConstraints(m_constraints);
374         delete m_constraints;
375         m_constraints = NULL;
376     }
377 #endif // wxUSE_CONSTRAINTS
378 
379     if ( m_containingSizer )
380         m_containingSizer->Detach( (wxWindow*)this );
381 
382     delete m_windowSizer;
383 
384 #if wxUSE_DRAG_AND_DROP
385     delete m_dropTarget;
386 #endif // wxUSE_DRAG_AND_DROP
387 
388 #if wxUSE_TOOLTIPS
389     delete m_tooltip;
390 #endif // wxUSE_TOOLTIPS
391 
392 #if wxUSE_ACCESSIBILITY
393     delete m_accessible;
394 #endif
395 
396 #if wxUSE_HELP
397     // NB: this has to be called unconditionally, because we don't
398     //     know whether this window has associated help text or not
399     wxHelpProvider *helpProvider = wxHelpProvider::Get();
400     if ( helpProvider )
401         helpProvider->RemoveHelp(this);
402 #endif
403 }
404 
SendDestroyEvent()405 void wxWindowBase::SendDestroyEvent()
406 {
407     wxWindowDestroyEvent event;
408     event.SetEventObject(this);
409     event.SetId(GetId());
410     GetEventHandler()->ProcessEvent(event);
411 }
412 
Destroy()413 bool wxWindowBase::Destroy()
414 {
415     delete this;
416 
417     return true;
418 }
419 
Close(bool force)420 bool wxWindowBase::Close(bool force)
421 {
422     wxCloseEvent event(wxEVT_CLOSE_WINDOW, m_windowId);
423     event.SetEventObject(this);
424     event.SetCanVeto(!force);
425 
426     // return false if window wasn't closed because the application vetoed the
427     // close event
428     return GetEventHandler()->ProcessEvent(event) && !event.GetVeto();
429 }
430 
DestroyChildren()431 bool wxWindowBase::DestroyChildren()
432 {
433     wxWindowList::compatibility_iterator node;
434     for ( ;; )
435     {
436         // we iterate until the list becomes empty
437         node = GetChildren().GetFirst();
438         if ( !node )
439             break;
440 
441         wxWindow *child = node->GetData();
442 
443         // note that we really want to call delete and not ->Destroy() here
444         // because we want to delete the child immediately, before we are
445         // deleted, and delayed deletion would result in problems as our (top
446         // level) child could outlive its parent
447         delete child;
448 
449         wxASSERT_MSG( !GetChildren().Find(child),
450                       wxT("child didn't remove itself using RemoveChild()") );
451     }
452 
453     return true;
454 }
455 
456 // ----------------------------------------------------------------------------
457 // size/position related methods
458 // ----------------------------------------------------------------------------
459 
460 // centre the window with respect to its parent in either (or both) directions
DoCentre(int dir)461 void wxWindowBase::DoCentre(int dir)
462 {
463     wxCHECK_RET( !(dir & wxCENTRE_ON_SCREEN) && GetParent(),
464                  _T("this method only implements centering child windows") );
465 
466     SetSize(GetRect().CentreIn(GetParent()->GetClientSize(), dir));
467 }
468 
469 // fits the window around the children
Fit()470 void wxWindowBase::Fit()
471 {
472     if ( !GetChildren().empty() )
473     {
474         SetSize(GetBestSize());
475     }
476     //else: do nothing if we have no children
477 }
478 
479 // fits virtual size (ie. scrolled area etc.) around children
FitInside()480 void wxWindowBase::FitInside()
481 {
482     if ( GetChildren().GetCount() > 0 )
483     {
484         SetVirtualSize( GetBestVirtualSize() );
485     }
486 }
487 
488 // On Mac, scrollbars are explicitly children.
489 #ifdef __WXMAC__
wxHasRealChildren(const wxWindowBase * win)490 static bool wxHasRealChildren(const wxWindowBase* win)
491 {
492     int realChildCount = 0;
493 
494     for ( wxWindowList::compatibility_iterator node = win->GetChildren().GetFirst();
495           node;
496           node = node->GetNext() )
497     {
498         wxWindow *win = node->GetData();
499         if ( !win->IsTopLevel() && win->IsShown() && !win->IsKindOf(CLASSINFO(wxScrollBar)))
500             realChildCount ++;
501     }
502     return (realChildCount > 0);
503 }
504 #endif
505 
InvalidateBestSize()506 void wxWindowBase::InvalidateBestSize()
507 {
508     m_bestSizeCache = wxDefaultSize;
509 
510     // parent's best size calculation may depend on its children's
511     // as long as child window we are in is not top level window itself
512     // (because the TLW size is never resized automatically)
513     // so let's invalidate it as well to be safe:
514     if (m_parent && !IsTopLevel())
515         m_parent->InvalidateBestSize();
516 }
517 
518 // return the size best suited for the current window
DoGetBestSize() const519 wxSize wxWindowBase::DoGetBestSize() const
520 {
521     wxSize best;
522 
523     if ( m_windowSizer )
524     {
525         // Adjust to window size, since the return value of GetWindowSizeForVirtualSize is
526         // expressed in window and not client size
527         wxSize minSize = m_windowSizer->GetMinSize();
528         wxSize size(GetSize());
529         wxSize clientSize(GetClientSize());
530 
531         wxSize minWindowSize(minSize.x + size.x - clientSize.x,
532                              minSize.y + size.y - clientSize.y);
533 
534         best = GetWindowSizeForVirtualSize(minWindowSize);
535 
536         return best;
537     }
538 #if wxUSE_CONSTRAINTS
539     else if ( m_constraints )
540     {
541         wxConstCast(this, wxWindowBase)->SatisfyConstraints();
542 
543         // our minimal acceptable size is such that all our windows fit inside
544         int maxX = 0,
545             maxY = 0;
546 
547         for ( wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
548               node;
549               node = node->GetNext() )
550         {
551             wxLayoutConstraints *c = node->GetData()->GetConstraints();
552             if ( !c )
553             {
554                 // it's not normal that we have an unconstrained child, but
555                 // what can we do about it?
556                 continue;
557             }
558 
559             int x = c->right.GetValue(),
560                 y = c->bottom.GetValue();
561 
562             if ( x > maxX )
563                 maxX = x;
564 
565             if ( y > maxY )
566                 maxY = y;
567 
568             // TODO: we must calculate the overlaps somehow, otherwise we
569             //       will never return a size bigger than the current one :-(
570         }
571 
572         best = wxSize(maxX, maxY);
573     }
574 #endif // wxUSE_CONSTRAINTS
575     else if ( !GetChildren().empty()
576 #ifdef __WXMAC__
577               && wxHasRealChildren(this)
578 #endif
579               )
580     {
581         // our minimal acceptable size is such that all our visible child
582         // windows fit inside
583         int maxX = 0,
584             maxY = 0;
585 
586         for ( wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
587               node;
588               node = node->GetNext() )
589         {
590             wxWindow *win = node->GetData();
591             if ( win->IsTopLevel()
592                     || !win->IsShown()
593 #if wxUSE_STATUSBAR
594                         || wxDynamicCast(win, wxStatusBar)
595 #endif // wxUSE_STATUSBAR
596                )
597             {
598                 // dialogs and frames lie in different top level windows -
599                 // don't deal with them here; as for the status bars, they
600                 // don't lie in the client area at all
601                 continue;
602             }
603 
604             int wx, wy, ww, wh;
605             win->GetPosition(&wx, &wy);
606 
607             // if the window hadn't been positioned yet, assume that it is in
608             // the origin
609             if ( wx == wxDefaultCoord )
610                 wx = 0;
611             if ( wy == wxDefaultCoord )
612                 wy = 0;
613 
614             win->GetSize(&ww, &wh);
615             if ( wx + ww > maxX )
616                 maxX = wx + ww;
617             if ( wy + wh > maxY )
618                 maxY = wy + wh;
619         }
620 
621         best = wxSize(maxX, maxY);
622     }
623     else // ! has children
624     {
625         // for a generic window there is no natural best size so, if the
626         // minimal size is not set, use the current size but take care to
627         // remember it as minimal size for the next time because our best size
628         // should be constant: otherwise we could get into a situation when the
629         // window is initially at some size, then expanded to a larger size and
630         // then, when the containing window is shrunk back (because our initial
631         // best size had been used for computing the parent min size), we can't
632         // be shrunk back any more because our best size is now bigger
633         wxSize size = GetMinSize();
634         if ( !size.IsFullySpecified() )
635         {
636             size.SetDefaults(GetSize());
637             wxConstCast(this, wxWindowBase)->SetMinSize(size);
638         }
639 
640         // return as-is, unadjusted by the client size difference.
641         return size;
642     }
643 
644     // Add any difference between size and client size
645     wxSize diff = GetSize() - GetClientSize();
646     best.x += wxMax(0, diff.x);
647     best.y += wxMax(0, diff.y);
648 
649     return best;
650 }
651 
652 // helper of GetWindowBorderSize(): as many ports don't implement support for
653 // wxSYS_BORDER/EDGE_X/Y metrics in their wxSystemSettings, use hard coded
654 // fallbacks in this case
wxGetMetricOrDefault(wxSystemMetric what)655 static int wxGetMetricOrDefault(wxSystemMetric what)
656 {
657     int rc = wxSystemSettings::GetMetric(what);
658     if ( rc == -1 )
659     {
660         switch ( what )
661         {
662             case wxSYS_BORDER_X:
663             case wxSYS_BORDER_Y:
664                 // 2D border is by default 1 pixel wide
665                 rc = 1;
666                 break;
667 
668             case wxSYS_EDGE_X:
669             case wxSYS_EDGE_Y:
670                 // 3D borders are by default 2 pixels
671                 rc = 2;
672                 break;
673 
674             default:
675                 wxFAIL_MSG( _T("unexpected wxGetMetricOrDefault() argument") );
676                 rc = 0;
677         }
678     }
679 
680     return rc;
681 }
682 
GetWindowBorderSize() const683 wxSize wxWindowBase::GetWindowBorderSize() const
684 {
685     wxSize size;
686 
687     switch ( GetBorder() )
688     {
689         case wxBORDER_NONE:
690             // nothing to do, size is already (0, 0)
691             break;
692 
693         case wxBORDER_SIMPLE:
694         case wxBORDER_STATIC:
695             size.x = wxGetMetricOrDefault(wxSYS_BORDER_X);
696             size.y = wxGetMetricOrDefault(wxSYS_BORDER_Y);
697             break;
698 
699         case wxBORDER_SUNKEN:
700         case wxBORDER_RAISED:
701             size.x = wxMax(wxGetMetricOrDefault(wxSYS_EDGE_X),
702                            wxGetMetricOrDefault(wxSYS_BORDER_X));
703             size.y = wxMax(wxGetMetricOrDefault(wxSYS_EDGE_Y),
704                            wxGetMetricOrDefault(wxSYS_BORDER_Y));
705             break;
706 
707         case wxBORDER_DOUBLE:
708             size.x = wxGetMetricOrDefault(wxSYS_EDGE_X) +
709                         wxGetMetricOrDefault(wxSYS_BORDER_X);
710             size.y = wxGetMetricOrDefault(wxSYS_EDGE_Y) +
711                         wxGetMetricOrDefault(wxSYS_BORDER_Y);
712             break;
713 
714         default:
715             wxFAIL_MSG(_T("Unknown border style."));
716             break;
717     }
718 
719     // we have borders on both sides
720     return size*2;
721 }
722 
GetEffectiveMinSize() const723 wxSize wxWindowBase::GetEffectiveMinSize() const
724 {
725     // merge the best size with the min size, giving priority to the min size
726     wxSize min = GetMinSize();
727     if (min.x == wxDefaultCoord || min.y == wxDefaultCoord)
728     {
729         wxSize best = GetBestSize();
730         if (min.x == wxDefaultCoord) min.x =  best.x;
731         if (min.y == wxDefaultCoord) min.y =  best.y;
732     }
733     return min;
734 }
735 
736 
SetInitialSize(const wxSize & size)737 void wxWindowBase::SetInitialSize(const wxSize& size)
738 {
739     // Set the min size to the size passed in.  This will usually either be
740     // wxDefaultSize or the size passed to this window's ctor/Create function.
741     SetMinSize(size);
742 
743     // Merge the size with the best size if needed
744     wxSize best = GetEffectiveMinSize();
745 
746     // If the current size doesn't match then change it
747     if (GetSize() != best)
748         SetSize(best);
749 }
750 
751 
752 // by default the origin is not shifted
GetClientAreaOrigin() const753 wxPoint wxWindowBase::GetClientAreaOrigin() const
754 {
755     return wxPoint(0,0);
756 }
757 
ClientToWindowSize(const wxSize & size) const758 wxSize wxWindowBase::ClientToWindowSize(const wxSize& size) const
759 {
760     const wxSize diff(GetSize() - GetClientSize());
761 
762     return wxSize(size.x == -1 ? -1 : size.x + diff.x,
763                   size.y == -1 ? -1 : size.y + diff.y);
764 }
765 
WindowToClientSize(const wxSize & size) const766 wxSize wxWindowBase::WindowToClientSize(const wxSize& size) const
767 {
768     const wxSize diff(GetSize() - GetClientSize());
769 
770     return wxSize(size.x == -1 ? -1 : size.x - diff.x,
771                   size.y == -1 ? -1 : size.y - diff.y);
772 }
773 
SetWindowVariant(wxWindowVariant variant)774 void wxWindowBase::SetWindowVariant( wxWindowVariant variant )
775 {
776     if ( m_windowVariant != variant )
777     {
778         m_windowVariant = variant;
779 
780         DoSetWindowVariant(variant);
781     }
782 }
783 
DoSetWindowVariant(wxWindowVariant variant)784 void wxWindowBase::DoSetWindowVariant( wxWindowVariant variant )
785 {
786     // adjust the font height to correspond to our new variant (notice that
787     // we're only called if something really changed)
788     wxFont font = GetFont();
789     int size = font.GetPointSize();
790     switch ( variant )
791     {
792         case wxWINDOW_VARIANT_NORMAL:
793             break;
794 
795         case wxWINDOW_VARIANT_SMALL:
796             size *= 3;
797             size /= 4;
798             break;
799 
800         case wxWINDOW_VARIANT_MINI:
801             size *= 2;
802             size /= 3;
803             break;
804 
805         case wxWINDOW_VARIANT_LARGE:
806             size *= 5;
807             size /= 4;
808             break;
809 
810         default:
811             wxFAIL_MSG(_T("unexpected window variant"));
812             break;
813     }
814 
815     font.SetPointSize(size);
816     SetFont(font);
817 }
818 
DoSetSizeHints(int minW,int minH,int maxW,int maxH,int WXUNUSED (incW),int WXUNUSED (incH))819 void wxWindowBase::DoSetSizeHints( int minW, int minH,
820                                    int maxW, int maxH,
821                                    int WXUNUSED(incW), int WXUNUSED(incH) )
822 {
823     wxCHECK_RET( (minW == wxDefaultCoord || maxW == wxDefaultCoord || minW <= maxW) &&
824                     (minH == wxDefaultCoord || maxH == wxDefaultCoord || minH <= maxH),
825                  _T("min width/height must be less than max width/height!") );
826 
827     m_minWidth = minW;
828     m_maxWidth = maxW;
829     m_minHeight = minH;
830     m_maxHeight = maxH;
831 }
832 
833 
SetVirtualSizeHints(int minW,int minH,int maxW,int maxH)834 void wxWindowBase::SetVirtualSizeHints( int minW, int minH,
835                                         int maxW, int maxH )
836 {
837     m_minVirtualWidth = minW;
838     m_maxVirtualWidth = maxW;
839     m_minVirtualHeight = minH;
840     m_maxVirtualHeight = maxH;
841 }
842 
DoSetVirtualSize(int x,int y)843 void wxWindowBase::DoSetVirtualSize( int x, int y )
844 {
845     if ( m_minVirtualWidth != wxDefaultCoord && m_minVirtualWidth > x )
846         x = m_minVirtualWidth;
847     if ( m_maxVirtualWidth != wxDefaultCoord && m_maxVirtualWidth < x )
848         x = m_maxVirtualWidth;
849     if ( m_minVirtualHeight != wxDefaultCoord && m_minVirtualHeight > y )
850         y = m_minVirtualHeight;
851     if ( m_maxVirtualHeight != wxDefaultCoord && m_maxVirtualHeight < y )
852         y = m_maxVirtualHeight;
853 
854     m_virtualSize = wxSize(x, y);
855 }
856 
DoGetVirtualSize() const857 wxSize wxWindowBase::DoGetVirtualSize() const
858 {
859     // we should use the entire client area so if it is greater than our
860     // virtual size, expand it to fit (otherwise if the window is big enough we
861     // wouldn't be using parts of it)
862     wxSize size = GetClientSize();
863     if ( m_virtualSize.x > size.x )
864         size.x = m_virtualSize.x;
865 
866     if ( m_virtualSize.y >= size.y )
867         size.y = m_virtualSize.y;
868 
869     return size;
870 }
871 
DoGetScreenPosition(int * x,int * y) const872 void wxWindowBase::DoGetScreenPosition(int *x, int *y) const
873 {
874     // screen position is the same as (0, 0) in client coords for non TLWs (and
875     // TLWs override this method)
876     if ( x )
877         *x = 0;
878     if ( y )
879         *y = 0;
880 
881     ClientToScreen(x, y);
882 }
883 
884 // ----------------------------------------------------------------------------
885 // show/hide/enable/disable the window
886 // ----------------------------------------------------------------------------
887 
Show(bool show)888 bool wxWindowBase::Show(bool show)
889 {
890     if ( show != m_isShown )
891     {
892         m_isShown = show;
893 
894         return true;
895     }
896     else
897     {
898         return false;
899     }
900 }
901 
Enable(bool enable)902 bool wxWindowBase::Enable(bool enable)
903 {
904     if ( enable != m_isEnabled )
905     {
906         m_isEnabled = enable;
907 
908         return true;
909     }
910     else
911     {
912         return false;
913     }
914 }
915 
IsShownOnScreen() const916 bool wxWindowBase::IsShownOnScreen() const
917 {
918     // A window is shown on screen if it itself is shown and so are all its
919     // parents. But if a window is toplevel one, then its always visible on
920     // screen if IsShown() returns true, even if it has a hidden parent.
921     return IsShown() &&
922            (IsTopLevel() || !GetParent() || GetParent()->IsShownOnScreen());
923 }
924 
925 // ----------------------------------------------------------------------------
926 // RTTI
927 // ----------------------------------------------------------------------------
928 
IsTopLevel() const929 bool wxWindowBase::IsTopLevel() const
930 {
931     return false;
932 }
933 
934 // ----------------------------------------------------------------------------
935 // reparenting the window
936 // ----------------------------------------------------------------------------
937 
AddChild(wxWindowBase * child)938 void wxWindowBase::AddChild(wxWindowBase *child)
939 {
940     wxCHECK_RET( child, wxT("can't add a NULL child") );
941 
942     // this should never happen and it will lead to a crash later if it does
943     // because RemoveChild() will remove only one node from the children list
944     // and the other(s) one(s) will be left with dangling pointers in them
945     wxASSERT_MSG( !GetChildren().Find((wxWindow*)child), _T("AddChild() called twice") );
946 
947     GetChildren().Append((wxWindow*)child);
948     child->SetParent(this);
949 }
950 
RemoveChild(wxWindowBase * child)951 void wxWindowBase::RemoveChild(wxWindowBase *child)
952 {
953     wxCHECK_RET( child, wxT("can't remove a NULL child") );
954 
955     GetChildren().DeleteObject((wxWindow *)child);
956     child->SetParent(NULL);
957 }
958 
Reparent(wxWindowBase * newParent)959 bool wxWindowBase::Reparent(wxWindowBase *newParent)
960 {
961     wxWindow *oldParent = GetParent();
962     if ( newParent == oldParent )
963     {
964         // nothing done
965         return false;
966     }
967 
968     // unlink this window from the existing parent.
969     if ( oldParent )
970     {
971         oldParent->RemoveChild(this);
972     }
973     else
974     {
975         wxTopLevelWindows.DeleteObject((wxWindow *)this);
976     }
977 
978     // add it to the new one
979     if ( newParent )
980     {
981         newParent->AddChild(this);
982     }
983     else
984     {
985         wxTopLevelWindows.Append((wxWindow *)this);
986     }
987 
988     return true;
989 }
990 
991 // ----------------------------------------------------------------------------
992 // event handler stuff
993 // ----------------------------------------------------------------------------
994 
PushEventHandler(wxEvtHandler * handler)995 void wxWindowBase::PushEventHandler(wxEvtHandler *handler)
996 {
997     wxEvtHandler *handlerOld = GetEventHandler();
998 
999     handler->SetNextHandler(handlerOld);
1000 
1001     if ( handlerOld )
1002         GetEventHandler()->SetPreviousHandler(handler);
1003 
1004     SetEventHandler(handler);
1005 }
1006 
PopEventHandler(bool deleteHandler)1007 wxEvtHandler *wxWindowBase::PopEventHandler(bool deleteHandler)
1008 {
1009     wxEvtHandler *handlerA = GetEventHandler();
1010     if ( handlerA )
1011     {
1012         wxEvtHandler *handlerB = handlerA->GetNextHandler();
1013         handlerA->SetNextHandler((wxEvtHandler *)NULL);
1014 
1015         if ( handlerB )
1016             handlerB->SetPreviousHandler((wxEvtHandler *)NULL);
1017         SetEventHandler(handlerB);
1018 
1019         if ( deleteHandler )
1020         {
1021             delete handlerA;
1022             handlerA = (wxEvtHandler *)NULL;
1023         }
1024     }
1025 
1026     return handlerA;
1027 }
1028 
RemoveEventHandler(wxEvtHandler * handler)1029 bool wxWindowBase::RemoveEventHandler(wxEvtHandler *handler)
1030 {
1031     wxCHECK_MSG( handler, false, _T("RemoveEventHandler(NULL) called") );
1032 
1033     wxEvtHandler *handlerPrev = NULL,
1034                  *handlerCur = GetEventHandler();
1035     while ( handlerCur )
1036     {
1037         wxEvtHandler *handlerNext = handlerCur->GetNextHandler();
1038 
1039         if ( handlerCur == handler )
1040         {
1041             if ( handlerPrev )
1042             {
1043                 handlerPrev->SetNextHandler(handlerNext);
1044             }
1045             else
1046             {
1047                 SetEventHandler(handlerNext);
1048             }
1049 
1050             if ( handlerNext )
1051             {
1052                 handlerNext->SetPreviousHandler ( handlerPrev );
1053             }
1054 
1055             handler->SetNextHandler(NULL);
1056             handler->SetPreviousHandler(NULL);
1057 
1058             return true;
1059         }
1060 
1061         handlerPrev = handlerCur;
1062         handlerCur = handlerNext;
1063     }
1064 
1065     wxFAIL_MSG( _T("where has the event handler gone?") );
1066 
1067     return false;
1068 }
1069 
1070 // ----------------------------------------------------------------------------
1071 // colours, fonts &c
1072 // ----------------------------------------------------------------------------
1073 
InheritAttributes()1074 void wxWindowBase::InheritAttributes()
1075 {
1076     const wxWindowBase * const parent = GetParent();
1077     if ( !parent )
1078         return;
1079 
1080     // we only inherit attributes which had been explicitly set for the parent
1081     // which ensures that this only happens if the user really wants it and
1082     // not by default which wouldn't make any sense in modern GUIs where the
1083     // controls don't all use the same fonts (nor colours)
1084     if ( parent->m_inheritFont && !m_hasFont )
1085         SetFont(parent->GetFont());
1086 
1087     // in addition, there is a possibility to explicitly forbid inheriting
1088     // colours at each class level by overriding ShouldInheritColours()
1089     if ( ShouldInheritColours() )
1090     {
1091         if ( parent->m_inheritFgCol && !m_hasFgCol )
1092             SetForegroundColour(parent->GetForegroundColour());
1093 
1094         // inheriting (solid) background colour is wrong as it totally breaks
1095         // any kind of themed backgrounds
1096         //
1097         // instead, the controls should use the same background as their parent
1098         // (ideally by not drawing it at all)
1099 #if 0
1100         if ( parent->m_inheritBgCol && !m_hasBgCol )
1101             SetBackgroundColour(parent->GetBackgroundColour());
1102 #endif // 0
1103     }
1104 }
1105 
1106 /* static */ wxVisualAttributes
GetClassDefaultAttributes(wxWindowVariant WXUNUSED (variant))1107 wxWindowBase::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
1108 {
1109     // it is important to return valid values for all attributes from here,
1110     // GetXXX() below rely on this
1111     wxVisualAttributes attrs;
1112     attrs.font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
1113     attrs.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
1114 
1115     // On Smartphone/PocketPC, wxSYS_COLOUR_WINDOW is a better reflection of
1116     // the usual background colour than wxSYS_COLOUR_BTNFACE.
1117     // It's a pity that wxSYS_COLOUR_WINDOW isn't always a suitable background
1118     // colour on other platforms.
1119 
1120 #if defined(__WXWINCE__) && (defined(__SMARTPHONE__) || defined(__POCKETPC__))
1121     attrs.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
1122 #else
1123     attrs.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
1124 #endif
1125     return attrs;
1126 }
1127 
GetBackgroundColour() const1128 wxColour wxWindowBase::GetBackgroundColour() const
1129 {
1130     if ( !m_backgroundColour.Ok() )
1131     {
1132         wxASSERT_MSG( !m_hasBgCol, _T("we have invalid explicit bg colour?") );
1133 
1134         // get our default background colour
1135         wxColour colBg = GetDefaultAttributes().colBg;
1136 
1137         // we must return some valid colour to avoid redoing this every time
1138         // and also to avoid surprizing the applications written for older
1139         // wxWidgets versions where GetBackgroundColour() always returned
1140         // something -- so give them something even if it doesn't make sense
1141         // for this window (e.g. it has a themed background)
1142         if ( !colBg.Ok() )
1143             colBg = GetClassDefaultAttributes().colBg;
1144 
1145         return colBg;
1146     }
1147     else
1148         return m_backgroundColour;
1149 }
1150 
GetForegroundColour() const1151 wxColour wxWindowBase::GetForegroundColour() const
1152 {
1153     // logic is the same as above
1154     if ( !m_hasFgCol && !m_foregroundColour.Ok() )
1155     {
1156         wxASSERT_MSG( !m_hasFgCol, _T("we have invalid explicit fg colour?") );
1157 
1158         wxColour colFg = GetDefaultAttributes().colFg;
1159 
1160         if ( !colFg.Ok() )
1161             colFg = GetClassDefaultAttributes().colFg;
1162 
1163         return colFg;
1164     }
1165     else
1166         return m_foregroundColour;
1167 }
1168 
SetBackgroundColour(const wxColour & colour)1169 bool wxWindowBase::SetBackgroundColour( const wxColour &colour )
1170 {
1171     if ( colour == m_backgroundColour )
1172         return false;
1173 
1174     m_hasBgCol = colour.Ok();
1175     if ( m_backgroundStyle != wxBG_STYLE_CUSTOM )
1176         m_backgroundStyle = m_hasBgCol ? wxBG_STYLE_COLOUR : wxBG_STYLE_SYSTEM;
1177 
1178     m_inheritBgCol = m_hasBgCol;
1179     m_backgroundColour = colour;
1180     SetThemeEnabled( !m_hasBgCol && !m_foregroundColour.Ok() );
1181     return true;
1182 }
1183 
SetForegroundColour(const wxColour & colour)1184 bool wxWindowBase::SetForegroundColour( const wxColour &colour )
1185 {
1186     if (colour == m_foregroundColour )
1187         return false;
1188 
1189     m_hasFgCol = colour.Ok();
1190     m_inheritFgCol = m_hasFgCol;
1191     m_foregroundColour = colour;
1192     SetThemeEnabled( !m_hasFgCol && !m_backgroundColour.Ok() );
1193     return true;
1194 }
1195 
SetCursor(const wxCursor & cursor)1196 bool wxWindowBase::SetCursor(const wxCursor& cursor)
1197 {
1198     // setting an invalid cursor is ok, it means that we don't have any special
1199     // cursor
1200     if ( m_cursor.IsSameAs(cursor) )
1201     {
1202         // no change
1203         return false;
1204     }
1205 
1206     m_cursor = cursor;
1207 
1208     return true;
1209 }
1210 
GetFont() const1211 wxFont wxWindowBase::GetFont() const
1212 {
1213     // logic is the same as in GetBackgroundColour()
1214     if ( !m_font.Ok() )
1215     {
1216         wxASSERT_MSG( !m_hasFont, _T("we have invalid explicit font?") );
1217 
1218         wxFont font = GetDefaultAttributes().font;
1219         if ( !font.Ok() )
1220             font = GetClassDefaultAttributes().font;
1221 
1222         return font;
1223     }
1224     else
1225         return m_font;
1226 }
1227 
SetFont(const wxFont & font)1228 bool wxWindowBase::SetFont(const wxFont& font)
1229 {
1230     if ( font == m_font )
1231     {
1232         // no change
1233         return false;
1234     }
1235 
1236     m_font = font;
1237     m_hasFont = font.Ok();
1238     m_inheritFont = m_hasFont;
1239 
1240     InvalidateBestSize();
1241 
1242     return true;
1243 }
1244 
1245 #if wxUSE_PALETTE
1246 
SetPalette(const wxPalette & pal)1247 void wxWindowBase::SetPalette(const wxPalette& pal)
1248 {
1249     m_hasCustomPalette = true;
1250     m_palette = pal;
1251 
1252     // VZ: can anyone explain me what do we do here?
1253     wxWindowDC d((wxWindow *) this);
1254     d.SetPalette(pal);
1255 }
1256 
GetAncestorWithCustomPalette() const1257 wxWindow *wxWindowBase::GetAncestorWithCustomPalette() const
1258 {
1259     wxWindow *win = (wxWindow *)this;
1260     while ( win && !win->HasCustomPalette() )
1261     {
1262         win = win->GetParent();
1263     }
1264 
1265     return win;
1266 }
1267 
1268 #endif // wxUSE_PALETTE
1269 
1270 #if wxUSE_CARET
SetCaret(wxCaret * caret)1271 void wxWindowBase::SetCaret(wxCaret *caret)
1272 {
1273     if ( m_caret )
1274     {
1275         delete m_caret;
1276     }
1277 
1278     m_caret = caret;
1279 
1280     if ( m_caret )
1281     {
1282         wxASSERT_MSG( m_caret->GetWindow() == this,
1283                       wxT("caret should be created associated to this window") );
1284     }
1285 }
1286 #endif // wxUSE_CARET
1287 
1288 #if wxUSE_VALIDATORS
1289 // ----------------------------------------------------------------------------
1290 // validators
1291 // ----------------------------------------------------------------------------
1292 
SetValidator(const wxValidator & validator)1293 void wxWindowBase::SetValidator(const wxValidator& validator)
1294 {
1295     if ( m_windowValidator )
1296         delete m_windowValidator;
1297 
1298     m_windowValidator = (wxValidator *)validator.Clone();
1299 
1300     if ( m_windowValidator )
1301         m_windowValidator->SetWindow(this);
1302 }
1303 #endif // wxUSE_VALIDATORS
1304 
1305 // ----------------------------------------------------------------------------
1306 // update region stuff
1307 // ----------------------------------------------------------------------------
1308 
GetUpdateClientRect() const1309 wxRect wxWindowBase::GetUpdateClientRect() const
1310 {
1311     wxRegion rgnUpdate = GetUpdateRegion();
1312     rgnUpdate.Intersect(GetClientRect());
1313     wxRect rectUpdate = rgnUpdate.GetBox();
1314     wxPoint ptOrigin = GetClientAreaOrigin();
1315     rectUpdate.x -= ptOrigin.x;
1316     rectUpdate.y -= ptOrigin.y;
1317 
1318     return rectUpdate;
1319 }
1320 
DoIsExposed(int x,int y) const1321 bool wxWindowBase::DoIsExposed(int x, int y) const
1322 {
1323     return m_updateRegion.Contains(x, y) != wxOutRegion;
1324 }
1325 
DoIsExposed(int x,int y,int w,int h) const1326 bool wxWindowBase::DoIsExposed(int x, int y, int w, int h) const
1327 {
1328     return m_updateRegion.Contains(x, y, w, h) != wxOutRegion;
1329 }
1330 
ClearBackground()1331 void wxWindowBase::ClearBackground()
1332 {
1333     // wxGTK uses its own version, no need to add never used code
1334 #ifndef __WXGTK__
1335     wxClientDC dc((wxWindow *)this);
1336     wxBrush brush(GetBackgroundColour(), wxSOLID);
1337     dc.SetBackground(brush);
1338     dc.Clear();
1339 #endif // __WXGTK__
1340 }
1341 
1342 // ----------------------------------------------------------------------------
1343 // find child window by id or name
1344 // ----------------------------------------------------------------------------
1345 
FindWindow(long id) const1346 wxWindow *wxWindowBase::FindWindow(long id) const
1347 {
1348     if ( id == m_windowId )
1349         return (wxWindow *)this;
1350 
1351     wxWindowBase *res = (wxWindow *)NULL;
1352     wxWindowList::compatibility_iterator node;
1353     for ( node = m_children.GetFirst(); node && !res; node = node->GetNext() )
1354     {
1355         wxWindowBase *child = node->GetData();
1356         res = child->FindWindow( id );
1357     }
1358 
1359     return (wxWindow *)res;
1360 }
1361 
FindWindow(const wxString & name) const1362 wxWindow *wxWindowBase::FindWindow(const wxString& name) const
1363 {
1364     if ( name == m_windowName )
1365         return (wxWindow *)this;
1366 
1367     wxWindowBase *res = (wxWindow *)NULL;
1368     wxWindowList::compatibility_iterator node;
1369     for ( node = m_children.GetFirst(); node && !res; node = node->GetNext() )
1370     {
1371         wxWindow *child = node->GetData();
1372         res = child->FindWindow(name);
1373     }
1374 
1375     return (wxWindow *)res;
1376 }
1377 
1378 
1379 // find any window by id or name or label: If parent is non-NULL, look through
1380 // children for a label or title matching the specified string. If NULL, look
1381 // through all top-level windows.
1382 //
1383 // to avoid duplicating code we reuse the same helper function but with
1384 // different comparators
1385 
1386 typedef bool (*wxFindWindowCmp)(const wxWindow *win,
1387                                 const wxString& label, long id);
1388 
1389 static
wxFindWindowCmpLabels(const wxWindow * win,const wxString & label,long WXUNUSED (id))1390 bool wxFindWindowCmpLabels(const wxWindow *win, const wxString& label,
1391                            long WXUNUSED(id))
1392 {
1393     return win->GetLabel() == label;
1394 }
1395 
1396 static
wxFindWindowCmpNames(const wxWindow * win,const wxString & label,long WXUNUSED (id))1397 bool wxFindWindowCmpNames(const wxWindow *win, const wxString& label,
1398                           long WXUNUSED(id))
1399 {
1400     return win->GetName() == label;
1401 }
1402 
1403 static
wxFindWindowCmpIds(const wxWindow * win,const wxString & WXUNUSED (label),long id)1404 bool wxFindWindowCmpIds(const wxWindow *win, const wxString& WXUNUSED(label),
1405                         long id)
1406 {
1407     return win->GetId() == id;
1408 }
1409 
1410 // recursive helper for the FindWindowByXXX() functions
1411 static
wxFindWindowRecursively(const wxWindow * parent,const wxString & label,long id,wxFindWindowCmp cmp)1412 wxWindow *wxFindWindowRecursively(const wxWindow *parent,
1413                                   const wxString& label,
1414                                   long id,
1415                                   wxFindWindowCmp cmp)
1416 {
1417     if ( parent )
1418     {
1419         // see if this is the one we're looking for
1420         if ( (*cmp)(parent, label, id) )
1421             return (wxWindow *)parent;
1422 
1423         // It wasn't, so check all its children
1424         for ( wxWindowList::compatibility_iterator node = parent->GetChildren().GetFirst();
1425               node;
1426               node = node->GetNext() )
1427         {
1428             // recursively check each child
1429             wxWindow *win = (wxWindow *)node->GetData();
1430             wxWindow *retwin = wxFindWindowRecursively(win, label, id, cmp);
1431             if (retwin)
1432                 return retwin;
1433         }
1434     }
1435 
1436     // Not found
1437     return NULL;
1438 }
1439 
1440 // helper for FindWindowByXXX()
1441 static
wxFindWindowHelper(const wxWindow * parent,const wxString & label,long id,wxFindWindowCmp cmp)1442 wxWindow *wxFindWindowHelper(const wxWindow *parent,
1443                              const wxString& label,
1444                              long id,
1445                              wxFindWindowCmp cmp)
1446 {
1447     if ( parent )
1448     {
1449         // just check parent and all its children
1450         return wxFindWindowRecursively(parent, label, id, cmp);
1451     }
1452 
1453     // start at very top of wx's windows
1454     for ( wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
1455           node;
1456           node = node->GetNext() )
1457     {
1458         // recursively check each window & its children
1459         wxWindow *win = node->GetData();
1460         wxWindow *retwin = wxFindWindowRecursively(win, label, id, cmp);
1461         if (retwin)
1462             return retwin;
1463     }
1464 
1465     return NULL;
1466 }
1467 
1468 /* static */
1469 wxWindow *
FindWindowByLabel(const wxString & title,const wxWindow * parent)1470 wxWindowBase::FindWindowByLabel(const wxString& title, const wxWindow *parent)
1471 {
1472     return wxFindWindowHelper(parent, title, 0, wxFindWindowCmpLabels);
1473 }
1474 
1475 /* static */
1476 wxWindow *
FindWindowByName(const wxString & title,const wxWindow * parent)1477 wxWindowBase::FindWindowByName(const wxString& title, const wxWindow *parent)
1478 {
1479     wxWindow *win = wxFindWindowHelper(parent, title, 0, wxFindWindowCmpNames);
1480 
1481     if ( !win )
1482     {
1483         // fall back to the label
1484         win = FindWindowByLabel(title, parent);
1485     }
1486 
1487     return win;
1488 }
1489 
1490 /* static */
1491 wxWindow *
FindWindowById(long id,const wxWindow * parent)1492 wxWindowBase::FindWindowById( long id, const wxWindow* parent )
1493 {
1494     return wxFindWindowHelper(parent, wxEmptyString, id, wxFindWindowCmpIds);
1495 }
1496 
1497 // ----------------------------------------------------------------------------
1498 // dialog oriented functions
1499 // ----------------------------------------------------------------------------
1500 
MakeModal(bool modal)1501 void wxWindowBase::MakeModal(bool modal)
1502 {
1503     // Disable all other windows
1504     if ( IsTopLevel() )
1505     {
1506         wxWindowList::compatibility_iterator node = wxTopLevelWindows.GetFirst();
1507         while (node)
1508         {
1509             wxWindow *win = node->GetData();
1510             if (win != this)
1511                 win->Enable(!modal);
1512 
1513             node = node->GetNext();
1514         }
1515     }
1516 }
1517 
Validate()1518 bool wxWindowBase::Validate()
1519 {
1520 #if wxUSE_VALIDATORS
1521     bool recurse = (GetExtraStyle() & wxWS_EX_VALIDATE_RECURSIVELY) != 0;
1522 
1523     wxWindowList::compatibility_iterator node;
1524     for ( node = m_children.GetFirst(); node; node = node->GetNext() )
1525     {
1526         wxWindowBase *child = node->GetData();
1527         wxValidator *validator = child->GetValidator();
1528         if ( validator && !validator->Validate((wxWindow *)this) )
1529         {
1530             return false;
1531         }
1532 
1533         if ( recurse && !child->Validate() )
1534         {
1535             return false;
1536         }
1537     }
1538 #endif // wxUSE_VALIDATORS
1539 
1540     return true;
1541 }
1542 
TransferDataToWindow()1543 bool wxWindowBase::TransferDataToWindow()
1544 {
1545 #if wxUSE_VALIDATORS
1546     bool recurse = (GetExtraStyle() & wxWS_EX_VALIDATE_RECURSIVELY) != 0;
1547 
1548     wxWindowList::compatibility_iterator node;
1549     for ( node = m_children.GetFirst(); node; node = node->GetNext() )
1550     {
1551         wxWindowBase *child = node->GetData();
1552         wxValidator *validator = child->GetValidator();
1553         if ( validator && !validator->TransferToWindow() )
1554         {
1555             wxLogWarning(_("Could not transfer data to window"));
1556 #if wxUSE_LOG
1557             wxLog::FlushActive();
1558 #endif // wxUSE_LOG
1559 
1560             return false;
1561         }
1562 
1563         if ( recurse )
1564         {
1565             if ( !child->TransferDataToWindow() )
1566             {
1567                 // warning already given
1568                 return false;
1569             }
1570         }
1571     }
1572 #endif // wxUSE_VALIDATORS
1573 
1574     return true;
1575 }
1576 
TransferDataFromWindow()1577 bool wxWindowBase::TransferDataFromWindow()
1578 {
1579 #if wxUSE_VALIDATORS
1580     bool recurse = (GetExtraStyle() & wxWS_EX_VALIDATE_RECURSIVELY) != 0;
1581 
1582     wxWindowList::compatibility_iterator node;
1583     for ( node = m_children.GetFirst(); node; node = node->GetNext() )
1584     {
1585         wxWindow *child = node->GetData();
1586         wxValidator *validator = child->GetValidator();
1587         if ( validator && !validator->TransferFromWindow() )
1588         {
1589             // nop warning here because the application is supposed to give
1590             // one itself - we don't know here what might have gone wrongly
1591 
1592             return false;
1593         }
1594 
1595         if ( recurse )
1596         {
1597             if ( !child->TransferDataFromWindow() )
1598             {
1599                 // warning already given
1600                 return false;
1601             }
1602         }
1603     }
1604 #endif // wxUSE_VALIDATORS
1605 
1606     return true;
1607 }
1608 
InitDialog()1609 void wxWindowBase::InitDialog()
1610 {
1611     wxInitDialogEvent event(GetId());
1612     event.SetEventObject( this );
1613     GetEventHandler()->ProcessEvent(event);
1614 }
1615 
1616 // ----------------------------------------------------------------------------
1617 // context-sensitive help support
1618 // ----------------------------------------------------------------------------
1619 
1620 #if wxUSE_HELP
1621 
1622 // associate this help text with this window
SetHelpText(const wxString & text)1623 void wxWindowBase::SetHelpText(const wxString& text)
1624 {
1625     wxHelpProvider *helpProvider = wxHelpProvider::Get();
1626     if ( helpProvider )
1627     {
1628         helpProvider->AddHelp(this, text);
1629     }
1630 }
1631 
1632 // associate this help text with all windows with the same id as this
1633 // one
SetHelpTextForId(const wxString & text)1634 void wxWindowBase::SetHelpTextForId(const wxString& text)
1635 {
1636     wxHelpProvider *helpProvider = wxHelpProvider::Get();
1637     if ( helpProvider )
1638     {
1639         helpProvider->AddHelp(GetId(), text);
1640     }
1641 }
1642 
1643 // get the help string associated with this window (may be empty)
1644 // default implementation forwards calls to the help provider
1645 wxString
GetHelpTextAtPoint(const wxPoint & WXUNUSED (pt),wxHelpEvent::Origin WXUNUSED (origin)) const1646 wxWindowBase::GetHelpTextAtPoint(const wxPoint & WXUNUSED(pt),
1647                                  wxHelpEvent::Origin WXUNUSED(origin)) const
1648 {
1649     wxString text;
1650     wxHelpProvider *helpProvider = wxHelpProvider::Get();
1651     if ( helpProvider )
1652     {
1653         text = helpProvider->GetHelp(this);
1654     }
1655 
1656     return text;
1657 }
1658 
1659 // show help for this window
OnHelp(wxHelpEvent & event)1660 void wxWindowBase::OnHelp(wxHelpEvent& event)
1661 {
1662     wxHelpProvider *helpProvider = wxHelpProvider::Get();
1663     if ( helpProvider )
1664     {
1665         wxPoint pos = event.GetPosition();
1666         const wxHelpEvent::Origin origin = event.GetOrigin();
1667         if ( origin == wxHelpEvent::Origin_Keyboard )
1668         {
1669             // if the help event was generated from keyboard it shouldn't
1670             // appear at the mouse position (which is still the only position
1671             // associated with help event) if the mouse is far away, although
1672             // we still do use the mouse position if it's over the window
1673             // because we suppose the user looks approximately at the mouse
1674             // already and so it would be more convenient than showing tooltip
1675             // at some arbitrary position which can be quite far from it
1676             const wxRect rectClient = GetClientRect();
1677             if ( !rectClient.Contains(ScreenToClient(pos)) )
1678             {
1679                 // position help slightly under and to the right of this window
1680                 pos = ClientToScreen(wxPoint(
1681                         2*GetCharWidth(),
1682                         rectClient.height + GetCharHeight()
1683                       ));
1684             }
1685         }
1686 
1687         if ( helpProvider->ShowHelpAtPoint(this, pos, origin) )
1688         {
1689             // skip the event.Skip() below
1690             return;
1691         }
1692     }
1693 
1694     event.Skip();
1695 }
1696 
1697 #endif // wxUSE_HELP
1698 
1699 // ----------------------------------------------------------------------------
1700 // tooltips
1701 // ----------------------------------------------------------------------------
1702 
1703 #if wxUSE_TOOLTIPS
1704 
SetToolTip(const wxString & tip)1705 void wxWindowBase::SetToolTip( const wxString &tip )
1706 {
1707     // don't create the new tooltip if we already have one
1708     if ( m_tooltip )
1709     {
1710         m_tooltip->SetTip( tip );
1711     }
1712     else
1713     {
1714         SetToolTip( new wxToolTip( tip ) );
1715     }
1716 
1717     // setting empty tooltip text does not remove the tooltip any more - use
1718     // SetToolTip((wxToolTip *)NULL) for this
1719 }
1720 
DoSetToolTip(wxToolTip * tooltip)1721 void wxWindowBase::DoSetToolTip(wxToolTip *tooltip)
1722 {
1723     if ( m_tooltip != tooltip )
1724     {
1725         if ( m_tooltip )
1726             delete m_tooltip;
1727 
1728         m_tooltip = tooltip;
1729     }
1730 }
1731 
1732 #endif // wxUSE_TOOLTIPS
1733 
1734 // ----------------------------------------------------------------------------
1735 // constraints and sizers
1736 // ----------------------------------------------------------------------------
1737 
1738 #if wxUSE_CONSTRAINTS
1739 
SetConstraints(wxLayoutConstraints * constraints)1740 void wxWindowBase::SetConstraints( wxLayoutConstraints *constraints )
1741 {
1742     if ( m_constraints )
1743     {
1744         UnsetConstraints(m_constraints);
1745         delete m_constraints;
1746     }
1747     m_constraints = constraints;
1748     if ( m_constraints )
1749     {
1750         // Make sure other windows know they're part of a 'meaningful relationship'
1751         if ( m_constraints->left.GetOtherWindow() && (m_constraints->left.GetOtherWindow() != this) )
1752             m_constraints->left.GetOtherWindow()->AddConstraintReference(this);
1753         if ( m_constraints->top.GetOtherWindow() && (m_constraints->top.GetOtherWindow() != this) )
1754             m_constraints->top.GetOtherWindow()->AddConstraintReference(this);
1755         if ( m_constraints->right.GetOtherWindow() && (m_constraints->right.GetOtherWindow() != this) )
1756             m_constraints->right.GetOtherWindow()->AddConstraintReference(this);
1757         if ( m_constraints->bottom.GetOtherWindow() && (m_constraints->bottom.GetOtherWindow() != this) )
1758             m_constraints->bottom.GetOtherWindow()->AddConstraintReference(this);
1759         if ( m_constraints->width.GetOtherWindow() && (m_constraints->width.GetOtherWindow() != this) )
1760             m_constraints->width.GetOtherWindow()->AddConstraintReference(this);
1761         if ( m_constraints->height.GetOtherWindow() && (m_constraints->height.GetOtherWindow() != this) )
1762             m_constraints->height.GetOtherWindow()->AddConstraintReference(this);
1763         if ( m_constraints->centreX.GetOtherWindow() && (m_constraints->centreX.GetOtherWindow() != this) )
1764             m_constraints->centreX.GetOtherWindow()->AddConstraintReference(this);
1765         if ( m_constraints->centreY.GetOtherWindow() && (m_constraints->centreY.GetOtherWindow() != this) )
1766             m_constraints->centreY.GetOtherWindow()->AddConstraintReference(this);
1767     }
1768 }
1769 
1770 // This removes any dangling pointers to this window in other windows'
1771 // constraintsInvolvedIn lists.
UnsetConstraints(wxLayoutConstraints * c)1772 void wxWindowBase::UnsetConstraints(wxLayoutConstraints *c)
1773 {
1774     if ( c )
1775     {
1776         if ( c->left.GetOtherWindow() && (c->top.GetOtherWindow() != this) )
1777             c->left.GetOtherWindow()->RemoveConstraintReference(this);
1778         if ( c->top.GetOtherWindow() && (c->top.GetOtherWindow() != this) )
1779             c->top.GetOtherWindow()->RemoveConstraintReference(this);
1780         if ( c->right.GetOtherWindow() && (c->right.GetOtherWindow() != this) )
1781             c->right.GetOtherWindow()->RemoveConstraintReference(this);
1782         if ( c->bottom.GetOtherWindow() && (c->bottom.GetOtherWindow() != this) )
1783             c->bottom.GetOtherWindow()->RemoveConstraintReference(this);
1784         if ( c->width.GetOtherWindow() && (c->width.GetOtherWindow() != this) )
1785             c->width.GetOtherWindow()->RemoveConstraintReference(this);
1786         if ( c->height.GetOtherWindow() && (c->height.GetOtherWindow() != this) )
1787             c->height.GetOtherWindow()->RemoveConstraintReference(this);
1788         if ( c->centreX.GetOtherWindow() && (c->centreX.GetOtherWindow() != this) )
1789             c->centreX.GetOtherWindow()->RemoveConstraintReference(this);
1790         if ( c->centreY.GetOtherWindow() && (c->centreY.GetOtherWindow() != this) )
1791             c->centreY.GetOtherWindow()->RemoveConstraintReference(this);
1792     }
1793 }
1794 
1795 // Back-pointer to other windows we're involved with, so if we delete this
1796 // window, we must delete any constraints we're involved with.
AddConstraintReference(wxWindowBase * otherWin)1797 void wxWindowBase::AddConstraintReference(wxWindowBase *otherWin)
1798 {
1799     if ( !m_constraintsInvolvedIn )
1800         m_constraintsInvolvedIn = new wxWindowList;
1801     if ( !m_constraintsInvolvedIn->Find((wxWindow *)otherWin) )
1802         m_constraintsInvolvedIn->Append((wxWindow *)otherWin);
1803 }
1804 
1805 // REMOVE back-pointer to other windows we're involved with.
RemoveConstraintReference(wxWindowBase * otherWin)1806 void wxWindowBase::RemoveConstraintReference(wxWindowBase *otherWin)
1807 {
1808     if ( m_constraintsInvolvedIn )
1809         m_constraintsInvolvedIn->DeleteObject((wxWindow *)otherWin);
1810 }
1811 
1812 // Reset any constraints that mention this window
DeleteRelatedConstraints()1813 void wxWindowBase::DeleteRelatedConstraints()
1814 {
1815     if ( m_constraintsInvolvedIn )
1816     {
1817         wxWindowList::compatibility_iterator node = m_constraintsInvolvedIn->GetFirst();
1818         while (node)
1819         {
1820             wxWindow *win = node->GetData();
1821             wxLayoutConstraints *constr = win->GetConstraints();
1822 
1823             // Reset any constraints involving this window
1824             if ( constr )
1825             {
1826                 constr->left.ResetIfWin(this);
1827                 constr->top.ResetIfWin(this);
1828                 constr->right.ResetIfWin(this);
1829                 constr->bottom.ResetIfWin(this);
1830                 constr->width.ResetIfWin(this);
1831                 constr->height.ResetIfWin(this);
1832                 constr->centreX.ResetIfWin(this);
1833                 constr->centreY.ResetIfWin(this);
1834             }
1835 
1836             wxWindowList::compatibility_iterator next = node->GetNext();
1837             m_constraintsInvolvedIn->Erase(node);
1838             node = next;
1839         }
1840 
1841         delete m_constraintsInvolvedIn;
1842         m_constraintsInvolvedIn = (wxWindowList *) NULL;
1843     }
1844 }
1845 
1846 #endif // wxUSE_CONSTRAINTS
1847 
SetSizer(wxSizer * sizer,bool deleteOld)1848 void wxWindowBase::SetSizer(wxSizer *sizer, bool deleteOld)
1849 {
1850     if ( sizer == m_windowSizer)
1851         return;
1852 
1853     if ( m_windowSizer )
1854     {
1855         m_windowSizer->SetContainingWindow(NULL);
1856 
1857         if ( deleteOld )
1858             delete m_windowSizer;
1859     }
1860 
1861     m_windowSizer = sizer;
1862     if ( m_windowSizer )
1863     {
1864         m_windowSizer->SetContainingWindow((wxWindow *)this);
1865     }
1866 
1867     SetAutoLayout(m_windowSizer != NULL);
1868 }
1869 
SetSizerAndFit(wxSizer * sizer,bool deleteOld)1870 void wxWindowBase::SetSizerAndFit(wxSizer *sizer, bool deleteOld)
1871 {
1872     SetSizer( sizer, deleteOld );
1873     sizer->SetSizeHints( (wxWindow*) this );
1874 }
1875 
1876 
SetContainingSizer(wxSizer * sizer)1877 void wxWindowBase::SetContainingSizer(wxSizer* sizer)
1878 {
1879     // adding a window to a sizer twice is going to result in fatal and
1880     // hard to debug problems later because when deleting the second
1881     // associated wxSizerItem we're going to dereference a dangling
1882     // pointer; so try to detect this as early as possible
1883     wxASSERT_MSG( !sizer || m_containingSizer != sizer,
1884                   _T("Adding a window to the same sizer twice?") );
1885 
1886     m_containingSizer = sizer;
1887 }
1888 
1889 #if wxUSE_CONSTRAINTS
1890 
SatisfyConstraints()1891 void wxWindowBase::SatisfyConstraints()
1892 {
1893     wxLayoutConstraints *constr = GetConstraints();
1894     bool wasOk = constr && constr->AreSatisfied();
1895 
1896     ResetConstraints();   // Mark all constraints as unevaluated
1897 
1898     int noChanges = 1;
1899 
1900     // if we're a top level panel (i.e. our parent is frame/dialog), our
1901     // own constraints will never be satisfied any more unless we do it
1902     // here
1903     if ( wasOk )
1904     {
1905         while ( noChanges > 0 )
1906         {
1907             LayoutPhase1(&noChanges);
1908         }
1909     }
1910 
1911     LayoutPhase2(&noChanges);
1912 }
1913 
1914 #endif // wxUSE_CONSTRAINTS
1915 
Layout()1916 bool wxWindowBase::Layout()
1917 {
1918     // If there is a sizer, use it instead of the constraints
1919     if ( GetSizer() )
1920     {
1921         int w = 0, h = 0;
1922         GetVirtualSize(&w, &h);
1923         GetSizer()->SetDimension( 0, 0, w, h );
1924     }
1925 #if wxUSE_CONSTRAINTS
1926     else
1927     {
1928         SatisfyConstraints(); // Find the right constraints values
1929         SetConstraintSizes(); // Recursively set the real window sizes
1930     }
1931 #endif
1932 
1933     return true;
1934 }
1935 
1936 #if wxUSE_CONSTRAINTS
1937 
1938 // first phase of the constraints evaluation: set our own constraints
LayoutPhase1(int * noChanges)1939 bool wxWindowBase::LayoutPhase1(int *noChanges)
1940 {
1941     wxLayoutConstraints *constr = GetConstraints();
1942 
1943     return !constr || constr->SatisfyConstraints(this, noChanges);
1944 }
1945 
1946 // second phase: set the constraints for our children
LayoutPhase2(int * noChanges)1947 bool wxWindowBase::LayoutPhase2(int *noChanges)
1948 {
1949     *noChanges = 0;
1950 
1951     // Layout children
1952     DoPhase(1);
1953 
1954     // Layout grand children
1955     DoPhase(2);
1956 
1957     return true;
1958 }
1959 
1960 // Do a phase of evaluating child constraints
DoPhase(int phase)1961 bool wxWindowBase::DoPhase(int phase)
1962 {
1963     // the list containing the children for which the constraints are already
1964     // set correctly
1965     wxWindowList succeeded;
1966 
1967     // the max number of iterations we loop before concluding that we can't set
1968     // the constraints
1969     static const int maxIterations = 500;
1970 
1971     for ( int noIterations = 0; noIterations < maxIterations; noIterations++ )
1972     {
1973         int noChanges = 0;
1974 
1975         // loop over all children setting their constraints
1976         for ( wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
1977               node;
1978               node = node->GetNext() )
1979         {
1980             wxWindow *child = node->GetData();
1981             if ( child->IsTopLevel() )
1982             {
1983                 // top level children are not inside our client area
1984                 continue;
1985             }
1986 
1987             if ( !child->GetConstraints() || succeeded.Find(child) )
1988             {
1989                 // this one is either already ok or nothing we can do about it
1990                 continue;
1991             }
1992 
1993             int tempNoChanges = 0;
1994             bool success = phase == 1 ? child->LayoutPhase1(&tempNoChanges)
1995                                       : child->LayoutPhase2(&tempNoChanges);
1996             noChanges += tempNoChanges;
1997 
1998             if ( success )
1999             {
2000                 succeeded.Append(child);
2001             }
2002         }
2003 
2004         if ( !noChanges )
2005         {
2006             // constraints are set
2007             break;
2008         }
2009     }
2010 
2011     return true;
2012 }
2013 
ResetConstraints()2014 void wxWindowBase::ResetConstraints()
2015 {
2016     wxLayoutConstraints *constr = GetConstraints();
2017     if ( constr )
2018     {
2019         constr->left.SetDone(false);
2020         constr->top.SetDone(false);
2021         constr->right.SetDone(false);
2022         constr->bottom.SetDone(false);
2023         constr->width.SetDone(false);
2024         constr->height.SetDone(false);
2025         constr->centreX.SetDone(false);
2026         constr->centreY.SetDone(false);
2027     }
2028 
2029     wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
2030     while (node)
2031     {
2032         wxWindow *win = node->GetData();
2033         if ( !win->IsTopLevel() )
2034             win->ResetConstraints();
2035         node = node->GetNext();
2036     }
2037 }
2038 
2039 // Need to distinguish between setting the 'fake' size for windows and sizers,
2040 // and setting the real values.
SetConstraintSizes(bool recurse)2041 void wxWindowBase::SetConstraintSizes(bool recurse)
2042 {
2043     wxLayoutConstraints *constr = GetConstraints();
2044     if ( constr && constr->AreSatisfied() )
2045     {
2046         int x = constr->left.GetValue();
2047         int y = constr->top.GetValue();
2048         int w = constr->width.GetValue();
2049         int h = constr->height.GetValue();
2050 
2051         if ( (constr->width.GetRelationship() != wxAsIs ) ||
2052              (constr->height.GetRelationship() != wxAsIs) )
2053         {
2054             SetSize(x, y, w, h);
2055         }
2056         else
2057         {
2058             // If we don't want to resize this window, just move it...
2059             Move(x, y);
2060         }
2061     }
2062     else if ( constr )
2063     {
2064         wxLogDebug(wxT("Constraints not satisfied for %s named '%s'."),
2065                    GetClassInfo()->GetClassName(),
2066                    GetName().c_str());
2067     }
2068 
2069     if ( recurse )
2070     {
2071         wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
2072         while (node)
2073         {
2074             wxWindow *win = node->GetData();
2075             if ( !win->IsTopLevel() && win->GetConstraints() )
2076                 win->SetConstraintSizes();
2077             node = node->GetNext();
2078         }
2079     }
2080 }
2081 
2082 // Only set the size/position of the constraint (if any)
SetSizeConstraint(int x,int y,int w,int h)2083 void wxWindowBase::SetSizeConstraint(int x, int y, int w, int h)
2084 {
2085     wxLayoutConstraints *constr = GetConstraints();
2086     if ( constr )
2087     {
2088         if ( x != wxDefaultCoord )
2089         {
2090             constr->left.SetValue(x);
2091             constr->left.SetDone(true);
2092         }
2093         if ( y != wxDefaultCoord )
2094         {
2095             constr->top.SetValue(y);
2096             constr->top.SetDone(true);
2097         }
2098         if ( w != wxDefaultCoord )
2099         {
2100             constr->width.SetValue(w);
2101             constr->width.SetDone(true);
2102         }
2103         if ( h != wxDefaultCoord )
2104         {
2105             constr->height.SetValue(h);
2106             constr->height.SetDone(true);
2107         }
2108     }
2109 }
2110 
MoveConstraint(int x,int y)2111 void wxWindowBase::MoveConstraint(int x, int y)
2112 {
2113     wxLayoutConstraints *constr = GetConstraints();
2114     if ( constr )
2115     {
2116         if ( x != wxDefaultCoord )
2117         {
2118             constr->left.SetValue(x);
2119             constr->left.SetDone(true);
2120         }
2121         if ( y != wxDefaultCoord )
2122         {
2123             constr->top.SetValue(y);
2124             constr->top.SetDone(true);
2125         }
2126     }
2127 }
2128 
GetSizeConstraint(int * w,int * h) const2129 void wxWindowBase::GetSizeConstraint(int *w, int *h) const
2130 {
2131     wxLayoutConstraints *constr = GetConstraints();
2132     if ( constr )
2133     {
2134         *w = constr->width.GetValue();
2135         *h = constr->height.GetValue();
2136     }
2137     else
2138         GetSize(w, h);
2139 }
2140 
GetClientSizeConstraint(int * w,int * h) const2141 void wxWindowBase::GetClientSizeConstraint(int *w, int *h) const
2142 {
2143     wxLayoutConstraints *constr = GetConstraints();
2144     if ( constr )
2145     {
2146         *w = constr->width.GetValue();
2147         *h = constr->height.GetValue();
2148     }
2149     else
2150         GetClientSize(w, h);
2151 }
2152 
GetPositionConstraint(int * x,int * y) const2153 void wxWindowBase::GetPositionConstraint(int *x, int *y) const
2154 {
2155     wxLayoutConstraints *constr = GetConstraints();
2156     if ( constr )
2157     {
2158         *x = constr->left.GetValue();
2159         *y = constr->top.GetValue();
2160     }
2161     else
2162         GetPosition(x, y);
2163 }
2164 
2165 #endif // wxUSE_CONSTRAINTS
2166 
AdjustForParentClientOrigin(int & x,int & y,int sizeFlags) const2167 void wxWindowBase::AdjustForParentClientOrigin(int& x, int& y, int sizeFlags) const
2168 {
2169     // don't do it for the dialogs/frames - they float independently of their
2170     // parent
2171     if ( !IsTopLevel() )
2172     {
2173         wxWindow *parent = GetParent();
2174         if ( !(sizeFlags & wxSIZE_NO_ADJUSTMENTS) && parent )
2175         {
2176             wxPoint pt(parent->GetClientAreaOrigin());
2177             x += pt.x;
2178             y += pt.y;
2179         }
2180     }
2181 }
2182 
2183 // ----------------------------------------------------------------------------
2184 // Update UI processing
2185 // ----------------------------------------------------------------------------
2186 
UpdateWindowUI(long flags)2187 void wxWindowBase::UpdateWindowUI(long flags)
2188 {
2189     wxUpdateUIEvent event(GetId());
2190     event.SetEventObject(this);
2191 
2192     if ( GetEventHandler()->ProcessEvent(event) )
2193     {
2194         DoUpdateWindowUI(event);
2195     }
2196 
2197     if (flags & wxUPDATE_UI_RECURSE)
2198     {
2199         wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
2200         while (node)
2201         {
2202             wxWindow* child = (wxWindow*) node->GetData();
2203             child->UpdateWindowUI(flags);
2204             node = node->GetNext();
2205         }
2206     }
2207 }
2208 
2209 // do the window-specific processing after processing the update event
DoUpdateWindowUI(wxUpdateUIEvent & event)2210 void wxWindowBase::DoUpdateWindowUI(wxUpdateUIEvent& event)
2211 {
2212     if ( event.GetSetEnabled() )
2213         Enable(event.GetEnabled());
2214 
2215     if ( event.GetSetShown() )
2216         Show(event.GetShown());
2217 }
2218 
2219 // ----------------------------------------------------------------------------
2220 // dialog units translations
2221 // ----------------------------------------------------------------------------
2222 
ConvertPixelsToDialog(const wxPoint & pt)2223 wxPoint wxWindowBase::ConvertPixelsToDialog(const wxPoint& pt)
2224 {
2225     int charWidth = GetCharWidth();
2226     int charHeight = GetCharHeight();
2227     wxPoint pt2 = wxDefaultPosition;
2228     if (pt.x != wxDefaultCoord)
2229         pt2.x = (int) ((pt.x * 4) / charWidth);
2230     if (pt.y != wxDefaultCoord)
2231         pt2.y = (int) ((pt.y * 8) / charHeight);
2232 
2233     return pt2;
2234 }
2235 
ConvertDialogToPixels(const wxPoint & pt)2236 wxPoint wxWindowBase::ConvertDialogToPixels(const wxPoint& pt)
2237 {
2238     int charWidth = GetCharWidth();
2239     int charHeight = GetCharHeight();
2240     wxPoint pt2 = wxDefaultPosition;
2241     if (pt.x != wxDefaultCoord)
2242         pt2.x = (int) ((pt.x * charWidth) / 4);
2243     if (pt.y != wxDefaultCoord)
2244         pt2.y = (int) ((pt.y * charHeight) / 8);
2245 
2246     return pt2;
2247 }
2248 
2249 // ----------------------------------------------------------------------------
2250 // event handlers
2251 // ----------------------------------------------------------------------------
2252 
2253 // propagate the colour change event to the subwindows
OnSysColourChanged(wxSysColourChangedEvent & event)2254 void wxWindowBase::OnSysColourChanged(wxSysColourChangedEvent& event)
2255 {
2256     wxWindowList::compatibility_iterator node = GetChildren().GetFirst();
2257     while ( node )
2258     {
2259         // Only propagate to non-top-level windows
2260         wxWindow *win = node->GetData();
2261         if ( !win->IsTopLevel() )
2262         {
2263             wxSysColourChangedEvent event2;
2264             event.SetEventObject(win);
2265             win->GetEventHandler()->ProcessEvent(event2);
2266         }
2267 
2268         node = node->GetNext();
2269     }
2270 
2271     Refresh();
2272 }
2273 
2274 // the default action is to populate dialog with data when it's created,
2275 // and nudge the UI into displaying itself correctly in case
2276 // we've turned the wxUpdateUIEvents frequency down low.
OnInitDialog(wxInitDialogEvent & WXUNUSED (event))2277 void wxWindowBase::OnInitDialog( wxInitDialogEvent &WXUNUSED(event) )
2278 {
2279     TransferDataToWindow();
2280 
2281     // Update the UI at this point
2282     UpdateWindowUI(wxUPDATE_UI_RECURSE);
2283 }
2284 
2285 // methods for drawing the sizers in a visible way
2286 #ifdef __WXDEBUG__
2287 
2288 static void DrawSizers(wxWindowBase *win);
2289 
DrawBorder(wxWindowBase * win,const wxRect & rect,bool fill=false)2290 static void DrawBorder(wxWindowBase *win, const wxRect& rect, bool fill = false)
2291 {
2292     wxClientDC dc((wxWindow *)win);
2293     dc.SetPen(*wxRED_PEN);
2294     dc.SetBrush(fill ? wxBrush(*wxRED, wxCROSSDIAG_HATCH): *wxTRANSPARENT_BRUSH);
2295     dc.DrawRectangle(rect.Deflate(1, 1));
2296 }
2297 
DrawSizer(wxWindowBase * win,wxSizer * sizer)2298 static void DrawSizer(wxWindowBase *win, wxSizer *sizer)
2299 {
2300     const wxSizerItemList& items = sizer->GetChildren();
2301     for ( wxSizerItemList::const_iterator i = items.begin(),
2302                                         end = items.end();
2303           i != end;
2304           ++i )
2305     {
2306         wxSizerItem *item = *i;
2307         if ( item->IsSizer() )
2308         {
2309             DrawBorder(win, item->GetRect().Deflate(2));
2310             DrawSizer(win, item->GetSizer());
2311         }
2312         else if ( item->IsSpacer() )
2313         {
2314             DrawBorder(win, item->GetRect().Deflate(2), true);
2315         }
2316         else if ( item->IsWindow() )
2317         {
2318             DrawSizers(item->GetWindow());
2319         }
2320     }
2321 }
2322 
DrawSizers(wxWindowBase * win)2323 static void DrawSizers(wxWindowBase *win)
2324 {
2325     wxSizer *sizer = win->GetSizer();
2326     if ( sizer )
2327     {
2328         DrawBorder(win, win->GetClientSize());
2329         DrawSizer(win, sizer);
2330     }
2331     else // no sizer, still recurse into the children
2332     {
2333         const wxWindowList& children = win->GetChildren();
2334         for ( wxWindowList::const_iterator i = children.begin(),
2335                                          end = children.end();
2336               i != end;
2337               ++i )
2338         {
2339             DrawSizers(*i);
2340         }
2341     }
2342 }
2343 
2344 #endif // __WXDEBUG__
2345 
2346 // process special middle clicks
OnMiddleClick(wxMouseEvent & event)2347 void wxWindowBase::OnMiddleClick( wxMouseEvent& event )
2348 {
2349     if ( event.ControlDown() && event.AltDown() )
2350     {
2351 #ifdef __WXDEBUG__
2352         // Ctrl-Alt-Shift-mclick makes the sizers visible in debug builds
2353         if ( event.ShiftDown() )
2354         {
2355             DrawSizers(this);
2356             return;
2357         }
2358 #endif // __WXDEBUG__
2359 
2360 #if wxUSE_MSGDLG
2361         // don't translate these strings, they're for diagnostics purposes only
2362         wxString msg;
2363         msg.Printf(_T("wxWidgets Library (%s port)\n")
2364                    _T("Version %d.%d.%d%s%s, compiled at %s %s\n")
2365                    _T("Runtime version of toolkit used is %d.%d.%s\n")
2366                    _T("Copyright (c) 1995-2010 wxWidgets team"),
2367                    wxPlatformInfo::Get().GetPortIdName().c_str(),
2368                    wxMAJOR_VERSION,
2369                    wxMINOR_VERSION,
2370                    wxRELEASE_NUMBER,
2371 #if wxUSE_UNICODE
2372                    L" (Unicode)",
2373 #else
2374                    wxEmptyString,
2375 #endif
2376 #ifdef __WXDEBUG__
2377                    _T(" Debug build"),
2378 #else
2379                    wxEmptyString,
2380 #endif
2381                    __TDATE__,
2382                    __TTIME__,
2383                    wxPlatformInfo::Get().GetToolkitMajorVersion(),
2384                    wxPlatformInfo::Get().GetToolkitMinorVersion(),
2385 #ifdef __WXGTK__
2386                    wxString::Format(_T("\nThe compile-time GTK+ version is %d.%d.%d."), GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION).c_str()
2387 #else
2388                    wxEmptyString
2389 #endif
2390                    );
2391 
2392         wxMessageBox(msg, _T("wxWidgets information"),
2393                      wxICON_INFORMATION | wxOK,
2394                      (wxWindow *)this);
2395     }
2396     else
2397 #endif // wxUSE_MSGDLG
2398     {
2399         event.Skip();
2400     }
2401 }
2402 
2403 // ----------------------------------------------------------------------------
2404 // accessibility
2405 // ----------------------------------------------------------------------------
2406 
2407 #if wxUSE_ACCESSIBILITY
SetAccessible(wxAccessible * accessible)2408 void wxWindowBase::SetAccessible(wxAccessible* accessible)
2409 {
2410     if (m_accessible && (accessible != m_accessible))
2411         delete m_accessible;
2412     m_accessible = accessible;
2413     if (m_accessible)
2414         m_accessible->SetWindow((wxWindow*) this);
2415 }
2416 
2417 // Returns the accessible object, creating if necessary.
GetOrCreateAccessible()2418 wxAccessible* wxWindowBase::GetOrCreateAccessible()
2419 {
2420     if (!m_accessible)
2421         m_accessible = CreateAccessible();
2422     return m_accessible;
2423 }
2424 
2425 // Override to create a specific accessible object.
CreateAccessible()2426 wxAccessible* wxWindowBase::CreateAccessible()
2427 {
2428     return new wxWindowAccessible((wxWindow*) this);
2429 }
2430 
2431 #endif
2432 
2433 // ----------------------------------------------------------------------------
2434 // list classes implementation
2435 // ----------------------------------------------------------------------------
2436 
2437 #if wxUSE_STL
2438 
2439 #include "wx/listimpl.cpp"
WX_DEFINE_LIST(wxWindowList)2440 WX_DEFINE_LIST(wxWindowList)
2441 
2442 #else // !wxUSE_STL
2443 
2444 void wxWindowListNode::DeleteData()
2445 {
2446     delete (wxWindow *)GetData();
2447 }
2448 
2449 #endif // wxUSE_STL/!wxUSE_STL
2450 
2451 // ----------------------------------------------------------------------------
2452 // borders
2453 // ----------------------------------------------------------------------------
2454 
2455 wxBorder wxWindowBase::GetBorder(long flags) const
2456 {
2457     wxBorder border = (wxBorder)(flags & wxBORDER_MASK);
2458     if ( border == wxBORDER_DEFAULT )
2459     {
2460         border = GetDefaultBorder();
2461     }
2462 
2463     return border;
2464 }
2465 
GetDefaultBorder() const2466 wxBorder wxWindowBase::GetDefaultBorder() const
2467 {
2468     return wxBORDER_NONE;
2469 }
2470 
2471 // ----------------------------------------------------------------------------
2472 // hit testing
2473 // ----------------------------------------------------------------------------
2474 
DoHitTest(wxCoord x,wxCoord y) const2475 wxHitTest wxWindowBase::DoHitTest(wxCoord x, wxCoord y) const
2476 {
2477     // here we just check if the point is inside the window or not
2478 
2479     // check the top and left border first
2480     bool outside = x < 0 || y < 0;
2481     if ( !outside )
2482     {
2483         // check the right and bottom borders too
2484         wxSize size = GetSize();
2485         outside = x >= size.x || y >= size.y;
2486     }
2487 
2488     return outside ? wxHT_WINDOW_OUTSIDE : wxHT_WINDOW_INSIDE;
2489 }
2490 
2491 // ----------------------------------------------------------------------------
2492 // mouse capture
2493 // ----------------------------------------------------------------------------
2494 
2495 struct WXDLLEXPORT wxWindowNext
2496 {
2497     wxWindow *win;
2498     wxWindowNext *next;
2499 } *wxWindowBase::ms_winCaptureNext = NULL;
2500 wxWindow *wxWindowBase::ms_winCaptureCurrent = NULL;
2501 bool wxWindowBase::ms_winCaptureChanging = false;
2502 
CaptureMouse()2503 void wxWindowBase::CaptureMouse()
2504 {
2505     wxLogTrace(_T("mousecapture"), _T("CaptureMouse(%p)"), wx_static_cast(void*, this));
2506 
2507     wxASSERT_MSG( !ms_winCaptureChanging, _T("recursive CaptureMouse call?") );
2508 
2509     ms_winCaptureChanging = true;
2510 
2511     wxWindow *winOld = GetCapture();
2512     if ( winOld )
2513     {
2514         ((wxWindowBase*) winOld)->DoReleaseMouse();
2515 
2516         // save it on stack
2517         wxWindowNext *item = new wxWindowNext;
2518         item->win = winOld;
2519         item->next = ms_winCaptureNext;
2520         ms_winCaptureNext = item;
2521     }
2522     //else: no mouse capture to save
2523 
2524     DoCaptureMouse();
2525     ms_winCaptureCurrent = (wxWindow*)this;
2526 
2527     ms_winCaptureChanging = false;
2528 }
2529 
ReleaseMouse()2530 void wxWindowBase::ReleaseMouse()
2531 {
2532     wxLogTrace(_T("mousecapture"), _T("ReleaseMouse(%p)"), wx_static_cast(void*, this));
2533 
2534     wxASSERT_MSG( !ms_winCaptureChanging, _T("recursive ReleaseMouse call?") );
2535 
2536     wxASSERT_MSG( GetCapture() == this, wxT("attempt to release mouse, but this window hasn't captured it") );
2537 
2538     ms_winCaptureChanging = true;
2539 
2540     DoReleaseMouse();
2541     ms_winCaptureCurrent = NULL;
2542 
2543     if ( ms_winCaptureNext )
2544     {
2545         ((wxWindowBase*)ms_winCaptureNext->win)->DoCaptureMouse();
2546         ms_winCaptureCurrent = ms_winCaptureNext->win;
2547 
2548         wxWindowNext *item = ms_winCaptureNext;
2549         ms_winCaptureNext = item->next;
2550         delete item;
2551     }
2552     //else: stack is empty, no previous capture
2553 
2554     ms_winCaptureChanging = false;
2555 
2556     wxLogTrace(_T("mousecapture"),
2557         (const wxChar *) _T("After ReleaseMouse() mouse is captured by %p"),
2558         wx_static_cast(void*, GetCapture()));
2559 }
2560 
DoNotifyWindowAboutCaptureLost(wxWindow * win)2561 static void DoNotifyWindowAboutCaptureLost(wxWindow *win)
2562 {
2563     wxMouseCaptureLostEvent event(win->GetId());
2564     event.SetEventObject(win);
2565     if ( !win->GetEventHandler()->ProcessEvent(event) )
2566     {
2567         // windows must handle this event, otherwise the app wouldn't behave
2568         // correctly if it loses capture unexpectedly; see the discussion here:
2569         // http://sourceforge.net/tracker/index.php?func=detail&aid=1153662&group_id=9863&atid=109863
2570         // http://article.gmane.org/gmane.comp.lib.wxwidgets.devel/82376
2571         wxFAIL_MSG( _T("window that captured the mouse didn't process wxEVT_MOUSE_CAPTURE_LOST") );
2572     }
2573 }
2574 
2575 /* static */
NotifyCaptureLost()2576 void wxWindowBase::NotifyCaptureLost()
2577 {
2578     // don't do anything if capture lost was expected, i.e. resulted from
2579     // a wx call to ReleaseMouse or CaptureMouse:
2580     if ( ms_winCaptureChanging )
2581         return;
2582 
2583     // if the capture was lost unexpectedly, notify every window that has
2584     // capture (on stack or current) about it and clear the stack:
2585 
2586     if ( ms_winCaptureCurrent )
2587     {
2588         DoNotifyWindowAboutCaptureLost(ms_winCaptureCurrent);
2589         ms_winCaptureCurrent = NULL;
2590     }
2591 
2592     while ( ms_winCaptureNext )
2593     {
2594         wxWindowNext *item = ms_winCaptureNext;
2595         ms_winCaptureNext = item->next;
2596 
2597         DoNotifyWindowAboutCaptureLost(item->win);
2598 
2599         delete item;
2600     }
2601 }
2602 
2603 #if wxUSE_HOTKEY
2604 
2605 bool
RegisterHotKey(int WXUNUSED (hotkeyId),int WXUNUSED (modifiers),int WXUNUSED (keycode))2606 wxWindowBase::RegisterHotKey(int WXUNUSED(hotkeyId),
2607                              int WXUNUSED(modifiers),
2608                              int WXUNUSED(keycode))
2609 {
2610     // not implemented
2611     return false;
2612 }
2613 
UnregisterHotKey(int WXUNUSED (hotkeyId))2614 bool wxWindowBase::UnregisterHotKey(int WXUNUSED(hotkeyId))
2615 {
2616     // not implemented
2617     return false;
2618 }
2619 
2620 #endif // wxUSE_HOTKEY
2621 
2622 // ----------------------------------------------------------------------------
2623 // event processing
2624 // ----------------------------------------------------------------------------
2625 
TryValidator(wxEvent & wxVALIDATOR_PARAM (event))2626 bool wxWindowBase::TryValidator(wxEvent& wxVALIDATOR_PARAM(event))
2627 {
2628 #if wxUSE_VALIDATORS
2629     // Can only use the validator of the window which
2630     // is receiving the event
2631     if ( event.GetEventObject() == this )
2632     {
2633         wxValidator *validator = GetValidator();
2634         if ( validator && validator->ProcessEvent(event) )
2635         {
2636             return true;
2637         }
2638     }
2639 #endif // wxUSE_VALIDATORS
2640 
2641     return false;
2642 }
2643 
TryParent(wxEvent & event)2644 bool wxWindowBase::TryParent(wxEvent& event)
2645 {
2646     // carry on up the parent-child hierarchy if the propagation count hasn't
2647     // reached zero yet
2648     if ( event.ShouldPropagate() )
2649     {
2650         // honour the requests to stop propagation at this window: this is
2651         // used by the dialogs, for example, to prevent processing the events
2652         // from the dialog controls in the parent frame which rarely, if ever,
2653         // makes sense
2654         if ( !(GetExtraStyle() & wxWS_EX_BLOCK_EVENTS) )
2655         {
2656             wxWindow *parent = GetParent();
2657             if ( parent && !parent->IsBeingDeleted() )
2658             {
2659                 wxPropagateOnce propagateOnce(event);
2660 
2661                 return parent->GetEventHandler()->ProcessEvent(event);
2662             }
2663         }
2664     }
2665 
2666     return wxEvtHandler::TryParent(event);
2667 }
2668 
2669 // ----------------------------------------------------------------------------
2670 // window relationships
2671 // ----------------------------------------------------------------------------
2672 
DoGetSibling(MoveKind order) const2673 wxWindow *wxWindowBase::DoGetSibling(MoveKind order) const
2674 {
2675     wxCHECK_MSG( GetParent(), NULL,
2676                     _T("GetPrev/NextSibling() don't work for TLWs!") );
2677 
2678     wxWindowList& siblings = GetParent()->GetChildren();
2679     wxWindowList::compatibility_iterator i = siblings.Find((wxWindow *)this);
2680     wxCHECK_MSG( i, NULL, _T("window not a child of its parent?") );
2681 
2682     if ( order == MoveBefore )
2683         i = i->GetPrevious();
2684     else // MoveAfter
2685         i = i->GetNext();
2686 
2687     return i ? i->GetData() : NULL;
2688 }
2689 
2690 // ----------------------------------------------------------------------------
2691 // keyboard navigation
2692 // ----------------------------------------------------------------------------
2693 
2694 // Navigates in the specified direction.
Navigate(int flags)2695 bool wxWindowBase::Navigate(int flags)
2696 {
2697     wxNavigationKeyEvent eventNav;
2698     eventNav.SetFlags(flags);
2699     eventNav.SetEventObject(this);
2700     if ( GetParent()->GetEventHandler()->ProcessEvent(eventNav) )
2701     {
2702         return true;
2703     }
2704     return false;
2705 }
2706 
DoMoveInTabOrder(wxWindow * win,MoveKind move)2707 void wxWindowBase::DoMoveInTabOrder(wxWindow *win, MoveKind move)
2708 {
2709     // check that we're not a top level window
2710     wxCHECK_RET( GetParent(),
2711                     _T("MoveBefore/AfterInTabOrder() don't work for TLWs!") );
2712 
2713     // detect the special case when we have nothing to do anyhow and when the
2714     // code below wouldn't work
2715     if ( win == this )
2716         return;
2717 
2718     // find the target window in the siblings list
2719     wxWindowList& siblings = GetParent()->GetChildren();
2720     wxWindowList::compatibility_iterator i = siblings.Find(win);
2721     wxCHECK_RET( i, _T("MoveBefore/AfterInTabOrder(): win is not a sibling") );
2722 
2723     // unfortunately, when wxUSE_STL == 1 DetachNode() is not implemented so we
2724     // can't just move the node around
2725     wxWindow *self = (wxWindow *)this;
2726     siblings.DeleteObject(self);
2727     if ( move == MoveAfter )
2728     {
2729         i = i->GetNext();
2730     }
2731 
2732     if ( i )
2733     {
2734         siblings.Insert(i, self);
2735     }
2736     else // MoveAfter and win was the last sibling
2737     {
2738         siblings.Append(self);
2739     }
2740 }
2741 
2742 // ----------------------------------------------------------------------------
2743 // focus handling
2744 // ----------------------------------------------------------------------------
2745 
FindFocus()2746 /*static*/ wxWindow* wxWindowBase::FindFocus()
2747 {
2748     wxWindowBase *win = DoFindFocus();
2749     return win ? win->GetMainWindowOfCompositeControl() : NULL;
2750 }
2751 
2752 // ----------------------------------------------------------------------------
2753 // drag and drop
2754 // ----------------------------------------------------------------------------
2755 
2756 #if wxUSE_DRAG_AND_DROP && !defined(__WXMSW__)
2757 
2758 class wxDragAcceptFilesImplTarget : public wxFileDropTarget
2759 {
2760 public:
wxDragAcceptFilesImplTarget(wxWindowBase * win)2761     wxDragAcceptFilesImplTarget(wxWindowBase *win) : m_win(win) {}
2762 
OnDropFiles(wxCoord x,wxCoord y,const wxArrayString & filenames)2763     virtual bool OnDropFiles(wxCoord x, wxCoord y,
2764                              const wxArrayString& filenames)
2765     {
2766         wxDropFilesEvent event(wxEVT_DROP_FILES,
2767                                filenames.size(),
2768                                wxCArrayString(filenames).Release());
2769         event.SetEventObject(m_win);
2770         event.m_pos.x = x;
2771         event.m_pos.y = y;
2772 
2773         return m_win->GetEventHandler()->ProcessEvent(event);
2774     }
2775 
2776 private:
2777     wxWindowBase * const m_win;
2778 
2779     DECLARE_NO_COPY_CLASS(wxDragAcceptFilesImplTarget)
2780 };
2781 
2782 
2783 // Generic version of DragAcceptFiles(). It works by installing a simple
2784 // wxFileDropTarget-to-EVT_DROP_FILES adaptor and therefore cannot be used
2785 // together with explicit SetDropTarget() calls.
DragAcceptFiles(bool accept)2786 void wxWindowBase::DragAcceptFiles(bool accept)
2787 {
2788     if ( accept )
2789     {
2790         wxASSERT_MSG( !GetDropTarget(),
2791                       _T("cannot use DragAcceptFiles() and SetDropTarget() together") );
2792         SetDropTarget(new wxDragAcceptFilesImplTarget(this));
2793     }
2794     else
2795     {
2796         SetDropTarget(NULL);
2797     }
2798 }
2799 
2800 #endif // wxUSE_DRAG_AND_DROP && !defined(__WXMSW__)
2801 
2802 // ----------------------------------------------------------------------------
2803 // global functions
2804 // ----------------------------------------------------------------------------
2805 
wxGetTopLevelParent(wxWindow * win)2806 wxWindow* wxGetTopLevelParent(wxWindow *win)
2807 {
2808     while ( win && !win->IsTopLevel() )
2809          win = win->GetParent();
2810 
2811     return win;
2812 }
2813 
2814 #if wxUSE_ACCESSIBILITY
2815 // ----------------------------------------------------------------------------
2816 // accessible object for windows
2817 // ----------------------------------------------------------------------------
2818 
2819 // Can return either a child object, or an integer
2820 // representing the child element, starting from 1.
HitTest(const wxPoint & WXUNUSED (pt),int * WXUNUSED (childId),wxAccessible ** WXUNUSED (childObject))2821 wxAccStatus wxWindowAccessible::HitTest(const wxPoint& WXUNUSED(pt), int* WXUNUSED(childId), wxAccessible** WXUNUSED(childObject))
2822 {
2823     wxASSERT( GetWindow() != NULL );
2824     if (!GetWindow())
2825         return wxACC_FAIL;
2826 
2827     return wxACC_NOT_IMPLEMENTED;
2828 }
2829 
2830 // Returns the rectangle for this object (id = 0) or a child element (id > 0).
GetLocation(wxRect & rect,int elementId)2831 wxAccStatus wxWindowAccessible::GetLocation(wxRect& rect, int elementId)
2832 {
2833     wxASSERT( GetWindow() != NULL );
2834     if (!GetWindow())
2835         return wxACC_FAIL;
2836 
2837     wxWindow* win = NULL;
2838     if (elementId == 0)
2839     {
2840         win = GetWindow();
2841     }
2842     else
2843     {
2844         if (elementId <= (int) GetWindow()->GetChildren().GetCount())
2845         {
2846             win = GetWindow()->GetChildren().Item(elementId-1)->GetData();
2847         }
2848         else
2849             return wxACC_FAIL;
2850     }
2851     if (win)
2852     {
2853         rect = win->GetRect();
2854         if (win->GetParent() && !win->IsKindOf(CLASSINFO(wxTopLevelWindow)))
2855             rect.SetPosition(win->GetParent()->ClientToScreen(rect.GetPosition()));
2856         return wxACC_OK;
2857     }
2858 
2859     return wxACC_NOT_IMPLEMENTED;
2860 }
2861 
2862 // Navigates from fromId to toId/toObject.
Navigate(wxNavDir navDir,int fromId,int * WXUNUSED (toId),wxAccessible ** toObject)2863 wxAccStatus wxWindowAccessible::Navigate(wxNavDir navDir, int fromId,
2864                              int* WXUNUSED(toId), wxAccessible** toObject)
2865 {
2866     wxASSERT( GetWindow() != NULL );
2867     if (!GetWindow())
2868         return wxACC_FAIL;
2869 
2870     switch (navDir)
2871     {
2872     case wxNAVDIR_FIRSTCHILD:
2873         {
2874             if (GetWindow()->GetChildren().GetCount() == 0)
2875                 return wxACC_FALSE;
2876             wxWindow* childWindow = (wxWindow*) GetWindow()->GetChildren().GetFirst()->GetData();
2877             *toObject = childWindow->GetOrCreateAccessible();
2878 
2879             return wxACC_OK;
2880         }
2881     case wxNAVDIR_LASTCHILD:
2882         {
2883             if (GetWindow()->GetChildren().GetCount() == 0)
2884                 return wxACC_FALSE;
2885             wxWindow* childWindow = (wxWindow*) GetWindow()->GetChildren().GetLast()->GetData();
2886             *toObject = childWindow->GetOrCreateAccessible();
2887 
2888             return wxACC_OK;
2889         }
2890     case wxNAVDIR_RIGHT:
2891     case wxNAVDIR_DOWN:
2892     case wxNAVDIR_NEXT:
2893         {
2894             wxWindowList::compatibility_iterator node =
2895                 wxWindowList::compatibility_iterator();
2896             if (fromId == 0)
2897             {
2898                 // Can't navigate to sibling of this window
2899                 // if we're a top-level window.
2900                 if (!GetWindow()->GetParent())
2901                     return wxACC_NOT_IMPLEMENTED;
2902 
2903                 node = GetWindow()->GetParent()->GetChildren().Find(GetWindow());
2904             }
2905             else
2906             {
2907                 if (fromId <= (int) GetWindow()->GetChildren().GetCount())
2908                     node = GetWindow()->GetChildren().Item(fromId-1);
2909             }
2910 
2911             if (node && node->GetNext())
2912             {
2913                 wxWindow* nextWindow = node->GetNext()->GetData();
2914                 *toObject = nextWindow->GetOrCreateAccessible();
2915                 return wxACC_OK;
2916             }
2917             else
2918                 return wxACC_FALSE;
2919         }
2920     case wxNAVDIR_LEFT:
2921     case wxNAVDIR_UP:
2922     case wxNAVDIR_PREVIOUS:
2923         {
2924             wxWindowList::compatibility_iterator node =
2925                 wxWindowList::compatibility_iterator();
2926             if (fromId == 0)
2927             {
2928                 // Can't navigate to sibling of this window
2929                 // if we're a top-level window.
2930                 if (!GetWindow()->GetParent())
2931                     return wxACC_NOT_IMPLEMENTED;
2932 
2933                 node = GetWindow()->GetParent()->GetChildren().Find(GetWindow());
2934             }
2935             else
2936             {
2937                 if (fromId <= (int) GetWindow()->GetChildren().GetCount())
2938                     node = GetWindow()->GetChildren().Item(fromId-1);
2939             }
2940 
2941             if (node && node->GetPrevious())
2942             {
2943                 wxWindow* previousWindow = node->GetPrevious()->GetData();
2944                 *toObject = previousWindow->GetOrCreateAccessible();
2945                 return wxACC_OK;
2946             }
2947             else
2948                 return wxACC_FALSE;
2949         }
2950     }
2951 
2952     return wxACC_NOT_IMPLEMENTED;
2953 }
2954 
2955 // Gets the name of the specified object.
GetName(int childId,wxString * name)2956 wxAccStatus wxWindowAccessible::GetName(int childId, wxString* name)
2957 {
2958     wxASSERT( GetWindow() != NULL );
2959     if (!GetWindow())
2960         return wxACC_FAIL;
2961 
2962     wxString title;
2963 
2964     // If a child, leave wxWidgets to call the function on the actual
2965     // child object.
2966     if (childId > 0)
2967         return wxACC_NOT_IMPLEMENTED;
2968 
2969     // This will eventually be replaced by specialised
2970     // accessible classes, one for each kind of wxWidgets
2971     // control or window.
2972 #if wxUSE_BUTTON
2973     if (GetWindow()->IsKindOf(CLASSINFO(wxButton)))
2974         title = ((wxButton*) GetWindow())->GetLabel();
2975     else
2976 #endif
2977         title = GetWindow()->GetName();
2978 
2979     if (!title.empty())
2980     {
2981         *name = title;
2982         return wxACC_OK;
2983     }
2984     else
2985         return wxACC_NOT_IMPLEMENTED;
2986 }
2987 
2988 // Gets the number of children.
GetChildCount(int * childId)2989 wxAccStatus wxWindowAccessible::GetChildCount(int* childId)
2990 {
2991     wxASSERT( GetWindow() != NULL );
2992     if (!GetWindow())
2993         return wxACC_FAIL;
2994 
2995     *childId = (int) GetWindow()->GetChildren().GetCount();
2996     return wxACC_OK;
2997 }
2998 
2999 // Gets the specified child (starting from 1).
3000 // If *child is NULL and return value is wxACC_OK,
3001 // this means that the child is a simple element and
3002 // not an accessible object.
GetChild(int childId,wxAccessible ** child)3003 wxAccStatus wxWindowAccessible::GetChild(int childId, wxAccessible** child)
3004 {
3005     wxASSERT( GetWindow() != NULL );
3006     if (!GetWindow())
3007         return wxACC_FAIL;
3008 
3009     if (childId == 0)
3010     {
3011         *child = this;
3012         return wxACC_OK;
3013     }
3014 
3015     if (childId > (int) GetWindow()->GetChildren().GetCount())
3016         return wxACC_FAIL;
3017 
3018     wxWindow* childWindow = GetWindow()->GetChildren().Item(childId-1)->GetData();
3019     *child = childWindow->GetOrCreateAccessible();
3020     if (*child)
3021         return wxACC_OK;
3022     else
3023         return wxACC_FAIL;
3024 }
3025 
3026 // Gets the parent, or NULL.
GetParent(wxAccessible ** parent)3027 wxAccStatus wxWindowAccessible::GetParent(wxAccessible** parent)
3028 {
3029     wxASSERT( GetWindow() != NULL );
3030     if (!GetWindow())
3031         return wxACC_FAIL;
3032 
3033     wxWindow* parentWindow = GetWindow()->GetParent();
3034     if (!parentWindow)
3035     {
3036         *parent = NULL;
3037         return wxACC_OK;
3038     }
3039     else
3040     {
3041         *parent = parentWindow->GetOrCreateAccessible();
3042         if (*parent)
3043             return wxACC_OK;
3044         else
3045             return wxACC_FAIL;
3046     }
3047 }
3048 
3049 // Performs the default action. childId is 0 (the action for this object)
3050 // or > 0 (the action for a child).
3051 // Return wxACC_NOT_SUPPORTED if there is no default action for this
3052 // window (e.g. an edit control).
DoDefaultAction(int WXUNUSED (childId))3053 wxAccStatus wxWindowAccessible::DoDefaultAction(int WXUNUSED(childId))
3054 {
3055     wxASSERT( GetWindow() != NULL );
3056     if (!GetWindow())
3057         return wxACC_FAIL;
3058 
3059     return wxACC_NOT_IMPLEMENTED;
3060 }
3061 
3062 // Gets the default action for this object (0) or > 0 (the action for a child).
3063 // Return wxACC_OK even if there is no action. actionName is the action, or the empty
3064 // string if there is no action.
3065 // The retrieved string describes the action that is performed on an object,
3066 // not what the object does as a result. For example, a toolbar button that prints
3067 // a document has a default action of "Press" rather than "Prints the current document."
GetDefaultAction(int WXUNUSED (childId),wxString * WXUNUSED (actionName))3068 wxAccStatus wxWindowAccessible::GetDefaultAction(int WXUNUSED(childId), wxString* WXUNUSED(actionName))
3069 {
3070     wxASSERT( GetWindow() != NULL );
3071     if (!GetWindow())
3072         return wxACC_FAIL;
3073 
3074     return wxACC_NOT_IMPLEMENTED;
3075 }
3076 
3077 // Returns the description for this object or a child.
GetDescription(int WXUNUSED (childId),wxString * description)3078 wxAccStatus wxWindowAccessible::GetDescription(int WXUNUSED(childId), wxString* description)
3079 {
3080     wxASSERT( GetWindow() != NULL );
3081     if (!GetWindow())
3082         return wxACC_FAIL;
3083 
3084     wxString ht(GetWindow()->GetHelpTextAtPoint(wxDefaultPosition, wxHelpEvent::Origin_Keyboard));
3085     if (!ht.empty())
3086     {
3087         *description = ht;
3088         return wxACC_OK;
3089     }
3090     return wxACC_NOT_IMPLEMENTED;
3091 }
3092 
3093 // Returns help text for this object or a child, similar to tooltip text.
GetHelpText(int WXUNUSED (childId),wxString * helpText)3094 wxAccStatus wxWindowAccessible::GetHelpText(int WXUNUSED(childId), wxString* helpText)
3095 {
3096     wxASSERT( GetWindow() != NULL );
3097     if (!GetWindow())
3098         return wxACC_FAIL;
3099 
3100     wxString ht(GetWindow()->GetHelpTextAtPoint(wxDefaultPosition, wxHelpEvent::Origin_Keyboard));
3101     if (!ht.empty())
3102     {
3103         *helpText = ht;
3104         return wxACC_OK;
3105     }
3106     return wxACC_NOT_IMPLEMENTED;
3107 }
3108 
3109 // Returns the keyboard shortcut for this object or child.
3110 // Return e.g. ALT+K
GetKeyboardShortcut(int WXUNUSED (childId),wxString * WXUNUSED (shortcut))3111 wxAccStatus wxWindowAccessible::GetKeyboardShortcut(int WXUNUSED(childId), wxString* WXUNUSED(shortcut))
3112 {
3113     wxASSERT( GetWindow() != NULL );
3114     if (!GetWindow())
3115         return wxACC_FAIL;
3116 
3117     return wxACC_NOT_IMPLEMENTED;
3118 }
3119 
3120 // Returns a role constant.
GetRole(int childId,wxAccRole * role)3121 wxAccStatus wxWindowAccessible::GetRole(int childId, wxAccRole* role)
3122 {
3123     wxASSERT( GetWindow() != NULL );
3124     if (!GetWindow())
3125         return wxACC_FAIL;
3126 
3127     // If a child, leave wxWidgets to call the function on the actual
3128     // child object.
3129     if (childId > 0)
3130         return wxACC_NOT_IMPLEMENTED;
3131 
3132     if (GetWindow()->IsKindOf(CLASSINFO(wxControl)))
3133         return wxACC_NOT_IMPLEMENTED;
3134 #if wxUSE_STATUSBAR
3135     if (GetWindow()->IsKindOf(CLASSINFO(wxStatusBar)))
3136         return wxACC_NOT_IMPLEMENTED;
3137 #endif
3138 #if wxUSE_TOOLBAR
3139     if (GetWindow()->IsKindOf(CLASSINFO(wxToolBar)))
3140         return wxACC_NOT_IMPLEMENTED;
3141 #endif
3142 
3143     //*role = wxROLE_SYSTEM_CLIENT;
3144     *role = wxROLE_SYSTEM_CLIENT;
3145     return wxACC_OK;
3146 
3147     #if 0
3148     return wxACC_NOT_IMPLEMENTED;
3149     #endif
3150 }
3151 
3152 // Returns a state constant.
GetState(int childId,long * state)3153 wxAccStatus wxWindowAccessible::GetState(int childId, long* state)
3154 {
3155     wxASSERT( GetWindow() != NULL );
3156     if (!GetWindow())
3157         return wxACC_FAIL;
3158 
3159     // If a child, leave wxWidgets to call the function on the actual
3160     // child object.
3161     if (childId > 0)
3162         return wxACC_NOT_IMPLEMENTED;
3163 
3164     if (GetWindow()->IsKindOf(CLASSINFO(wxControl)))
3165         return wxACC_NOT_IMPLEMENTED;
3166 
3167 #if wxUSE_STATUSBAR
3168     if (GetWindow()->IsKindOf(CLASSINFO(wxStatusBar)))
3169         return wxACC_NOT_IMPLEMENTED;
3170 #endif
3171 #if wxUSE_TOOLBAR
3172     if (GetWindow()->IsKindOf(CLASSINFO(wxToolBar)))
3173         return wxACC_NOT_IMPLEMENTED;
3174 #endif
3175 
3176     *state = 0;
3177     return wxACC_OK;
3178 
3179     #if 0
3180     return wxACC_NOT_IMPLEMENTED;
3181     #endif
3182 }
3183 
3184 // Returns a localized string representing the value for the object
3185 // or child.
GetValue(int WXUNUSED (childId),wxString * WXUNUSED (strValue))3186 wxAccStatus wxWindowAccessible::GetValue(int WXUNUSED(childId), wxString* WXUNUSED(strValue))
3187 {
3188     wxASSERT( GetWindow() != NULL );
3189     if (!GetWindow())
3190         return wxACC_FAIL;
3191 
3192     return wxACC_NOT_IMPLEMENTED;
3193 }
3194 
3195 // Selects the object or child.
Select(int WXUNUSED (childId),wxAccSelectionFlags WXUNUSED (selectFlags))3196 wxAccStatus wxWindowAccessible::Select(int WXUNUSED(childId), wxAccSelectionFlags WXUNUSED(selectFlags))
3197 {
3198     wxASSERT( GetWindow() != NULL );
3199     if (!GetWindow())
3200         return wxACC_FAIL;
3201 
3202     return wxACC_NOT_IMPLEMENTED;
3203 }
3204 
3205 // Gets the window with the keyboard focus.
3206 // If childId is 0 and child is NULL, no object in
3207 // this subhierarchy has the focus.
3208 // If this object has the focus, child should be 'this'.
GetFocus(int * WXUNUSED (childId),wxAccessible ** WXUNUSED (child))3209 wxAccStatus wxWindowAccessible::GetFocus(int* WXUNUSED(childId), wxAccessible** WXUNUSED(child))
3210 {
3211     wxASSERT( GetWindow() != NULL );
3212     if (!GetWindow())
3213         return wxACC_FAIL;
3214 
3215     return wxACC_NOT_IMPLEMENTED;
3216 }
3217 
3218 #if wxUSE_VARIANT
3219 // Gets a variant representing the selected children
3220 // of this object.
3221 // Acceptable values:
3222 // - a null variant (IsNull() returns true)
3223 // - a list variant (GetType() == wxT("list")
3224 // - an integer representing the selected child element,
3225 //   or 0 if this object is selected (GetType() == wxT("long")
3226 // - a "void*" pointer to a wxAccessible child object
GetSelections(wxVariant * WXUNUSED (selections))3227 wxAccStatus wxWindowAccessible::GetSelections(wxVariant* WXUNUSED(selections))
3228 {
3229     wxASSERT( GetWindow() != NULL );
3230     if (!GetWindow())
3231         return wxACC_FAIL;
3232 
3233     return wxACC_NOT_IMPLEMENTED;
3234 }
3235 #endif // wxUSE_VARIANT
3236 
3237 #endif // wxUSE_ACCESSIBILITY
3238 
3239 // ----------------------------------------------------------------------------
3240 // RTL support
3241 // ----------------------------------------------------------------------------
3242 
3243 wxCoord
AdjustForLayoutDirection(wxCoord x,wxCoord width,wxCoord widthTotal) const3244 wxWindowBase::AdjustForLayoutDirection(wxCoord x,
3245                                        wxCoord width,
3246                                        wxCoord widthTotal) const
3247 {
3248     if ( GetLayoutDirection() == wxLayout_RightToLeft )
3249     {
3250         x = widthTotal - x - width;
3251     }
3252 
3253     return x;
3254 }
3255 
3256