]> git.saurik.com Git - wxWidgets.git/blobdiff - src/propgrid/propgrid.cpp
Make m_idleMutex an object instead of a pointer. Use bool for hook-installed flag...
[wxWidgets.git] / src / propgrid / propgrid.cpp
index a424df5033ef38b2aaf728d92a2f5161e0b82b0e..a87ebc07cc9bcd6f709303dfa5940e45f91ab228 100644 (file)
 
 #include "wx/timer.h"
 #include "wx/dcbuffer.h"
 
 #include "wx/timer.h"
 #include "wx/dcbuffer.h"
-#include "wx/clipbrd.h"
-#include "wx/dataobj.h"
-
-#ifdef __WXMSW__
-    #include "wx/msw/private.h"
-#endif
 
 // Two pics for the expand / collapse buttons.
 // Files are not supplied with this project (since it is
 
 // Two pics for the expand / collapse buttons.
 // Files are not supplied with this project (since it is
@@ -154,7 +148,16 @@ public:
 IMPLEMENT_DYNAMIC_CLASS(wxPGGlobalVarsClassManager, wxModule)
 
 
 IMPLEMENT_DYNAMIC_CLASS(wxPGGlobalVarsClassManager, wxModule)
 
 
-wxPGGlobalVarsClass* wxPGGlobalVars = (wxPGGlobalVarsClass*) NULL;
+// When wxPG is loaded dynamically after the application is already running
+// then the built-in module system won't pick this one up.  Add it manually.
+void wxPGInitResourceModule()
+{
+    wxModule* module = new wxPGGlobalVarsClassManager;
+    module->Init();
+    wxModule::RegisterModule(module);
+}
+
+wxPGGlobalVarsClass* wxPGGlobalVars = NULL;
 
 
 wxPGGlobalVarsClass::wxPGGlobalVarsClass()
 
 
 wxPGGlobalVarsClass::wxPGGlobalVarsClass()
@@ -164,7 +167,7 @@ wxPGGlobalVarsClass::wxPGGlobalVarsClass()
     m_boolChoices.Add(_("False"));
     m_boolChoices.Add(_("True"));
 
     m_boolChoices.Add(_("False"));
     m_boolChoices.Add(_("True"));
 
-    m_fontFamilyChoices = (wxPGChoices*) NULL;
+    m_fontFamilyChoices = NULL;
 
     m_defaultRenderer = new wxPGDefaultRenderer();
 
 
     m_defaultRenderer = new wxPGDefaultRenderer();
 
@@ -176,7 +179,7 @@ wxPGGlobalVarsClass::wxPGGlobalVarsClass()
 
     wxVariant v;
 
 
     wxVariant v;
 
-       // Prepare some shared variants
+    // Prepare some shared variants
     m_vEmptyString = wxString();
     m_vZero = (long) 0;
     m_vMinusOne = (long) -1;
     m_vEmptyString = wxString();
     m_vZero = (long) 0;
     m_vMinusOne = (long) -1;
@@ -188,14 +191,13 @@ wxPGGlobalVarsClass::wxPGGlobalVarsClass()
     m_strlong = wxS("long");
     m_strbool = wxS("bool");
     m_strlist = wxS("list");
     m_strlong = wxS("long");
     m_strbool = wxS("bool");
     m_strlist = wxS("list");
+    m_strDefaultValue = wxS("DefaultValue");
     m_strMin = wxS("Min");
     m_strMax = wxS("Max");
     m_strUnits = wxS("Units");
     m_strInlineHelp = wxS("InlineHelp");
 
     m_strMin = wxS("Min");
     m_strMax = wxS("Max");
     m_strUnits = wxS("Units");
     m_strInlineHelp = wxS("InlineHelp");
 
-#ifdef __WXDEBUG__
     m_warnings = 0;
     m_warnings = 0;
-#endif
 }
 
 
 }
 
 
@@ -231,147 +233,6 @@ void wxPropertyGridInitGlobalsIfNeeded()
 {
 }
 
 {
 }
 
-// -----------------------------------------------------------------------
-// wxPGTLWHandler
-//   Intercepts Close-events sent to wxPropertyGrid's top-level parent,
-//   and tries to commit property value.
-// -----------------------------------------------------------------------
-
-class wxPGTLWHandler : public wxEvtHandler
-{
-public:
-
-    wxPGTLWHandler( wxPropertyGrid* pg )
-        : wxEvtHandler()
-    {
-        m_pg = pg;
-    }
-
-protected:
-
-    void OnClose( wxCloseEvent& event )
-    {
-        // ClearSelection forces value validation/commit.
-        if ( event.CanVeto() && !m_pg->ClearSelection() )
-        {
-            event.Veto();
-            return;
-        }
-
-        event.Skip();
-    }
-
-private:
-    wxPropertyGrid*     m_pg;
-
-    DECLARE_EVENT_TABLE()
-};
-
-BEGIN_EVENT_TABLE(wxPGTLWHandler, wxEvtHandler)
-    EVT_CLOSE(wxPGTLWHandler::OnClose)
-END_EVENT_TABLE()
-
-// -----------------------------------------------------------------------
-// wxPGCanvas
-// -----------------------------------------------------------------------
-
-//
-// wxPGCanvas acts as a graphics sub-window of the
-// wxScrolledWindow that wxPropertyGrid is.
-//
-class wxPGCanvas : public wxPanel
-{
-public:
-    wxPGCanvas() : wxPanel()
-    {
-    }
-    virtual ~wxPGCanvas() { }
-
-protected:
-    void OnMouseMove( wxMouseEvent &event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnMouseMove( event );
-    }
-
-    void OnMouseClick( wxMouseEvent &event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnMouseClick( event );
-    }
-
-    void OnMouseUp( wxMouseEvent &event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnMouseUp( event );
-    }
-
-    void OnMouseRightClick( wxMouseEvent &event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnMouseRightClick( event );
-    }
-
-    void OnMouseDoubleClick( wxMouseEvent &event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnMouseDoubleClick( event );
-    }
-
-    void OnKey( wxKeyEvent& event )
-    {
-        wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-        pg->OnKey( event );
-    }
-
-    void OnPaint( wxPaintEvent& event );
-
-    // Always be focussable, even with child windows
-    virtual void SetCanFocus(bool WXUNUSED(canFocus))
-    {  wxPanel::SetCanFocus(true); }
-
-
-private:
-    DECLARE_EVENT_TABLE()
-    DECLARE_ABSTRACT_CLASS(wxPGCanvas)
-};
-
-
-IMPLEMENT_ABSTRACT_CLASS(wxPGCanvas,wxPanel)
-
-BEGIN_EVENT_TABLE(wxPGCanvas, wxPanel)
-    EVT_MOTION(wxPGCanvas::OnMouseMove)
-    EVT_PAINT(wxPGCanvas::OnPaint)
-    EVT_LEFT_DOWN(wxPGCanvas::OnMouseClick)
-    EVT_LEFT_UP(wxPGCanvas::OnMouseUp)
-    EVT_RIGHT_UP(wxPGCanvas::OnMouseRightClick)
-    EVT_LEFT_DCLICK(wxPGCanvas::OnMouseDoubleClick)
-    EVT_KEY_DOWN(wxPGCanvas::OnKey)
-END_EVENT_TABLE()
-
-
-void wxPGCanvas::OnPaint( wxPaintEvent& WXUNUSED(event) )
-{
-    wxPropertyGrid* pg = wxStaticCast(GetParent(), wxPropertyGrid);
-    wxASSERT( pg->IsKindOf(CLASSINFO(wxPropertyGrid)) );
-
-    wxPaintDC dc(this);
-
-    // Don't paint after destruction has begun
-    if ( !(pg->GetInternalFlags() & wxPG_FL_INITIALIZED) )
-        return;
-
-    // Update everything inside the box
-    wxRect r = GetUpdateRegion().GetBox();
-
-    // Repaint this rectangle
-    pg->DrawItems( dc, r.y, r.y + r.height, &r );
-
-    // We assume that the size set when grid is shown
-    // is what is desired.
-    pg->SetInternalFlag(wxPG_FL_GOOD_SIZE_SET);
-}
-
 // -----------------------------------------------------------------------
 // wxPropertyGrid
 // -----------------------------------------------------------------------
 // -----------------------------------------------------------------------
 // wxPropertyGrid
 // -----------------------------------------------------------------------
@@ -380,7 +241,6 @@ IMPLEMENT_DYNAMIC_CLASS(wxPropertyGrid, wxScrolledWindow)
 
 BEGIN_EVENT_TABLE(wxPropertyGrid, wxScrolledWindow)
   EVT_IDLE(wxPropertyGrid::OnIdle)
 
 BEGIN_EVENT_TABLE(wxPropertyGrid, wxScrolledWindow)
   EVT_IDLE(wxPropertyGrid::OnIdle)
-  EVT_MOTION(wxPropertyGrid::OnMouseMoveBottom)
   EVT_PAINT(wxPropertyGrid::OnPaint)
   EVT_SIZE(wxPropertyGrid::OnResize)
   EVT_ENTER_WINDOW(wxPropertyGrid::OnMouseEntry)
   EVT_PAINT(wxPropertyGrid::OnPaint)
   EVT_SIZE(wxPropertyGrid::OnResize)
   EVT_ENTER_WINDOW(wxPropertyGrid::OnMouseEntry)
@@ -391,9 +251,14 @@ BEGIN_EVENT_TABLE(wxPropertyGrid, wxScrolledWindow)
   EVT_SET_FOCUS(wxPropertyGrid::OnFocusEvent)
   EVT_KILL_FOCUS(wxPropertyGrid::OnFocusEvent)
   EVT_SYS_COLOUR_CHANGED(wxPropertyGrid::OnSysColourChanged)
   EVT_SET_FOCUS(wxPropertyGrid::OnFocusEvent)
   EVT_KILL_FOCUS(wxPropertyGrid::OnFocusEvent)
   EVT_SYS_COLOUR_CHANGED(wxPropertyGrid::OnSysColourChanged)
+  EVT_MOTION(wxPropertyGrid::OnMouseMove)
+  EVT_LEFT_DOWN(wxPropertyGrid::OnMouseClick)
+  EVT_LEFT_UP(wxPropertyGrid::OnMouseUp)
+  EVT_RIGHT_UP(wxPropertyGrid::OnMouseRightClick)
+  EVT_LEFT_DCLICK(wxPropertyGrid::OnMouseDoubleClick)
+  EVT_KEY_DOWN(wxPropertyGrid::OnKey)
 END_EVENT_TABLE()
 
 END_EVENT_TABLE()
 
-
 // -----------------------------------------------------------------------
 
 wxPropertyGrid::wxPropertyGrid()
 // -----------------------------------------------------------------------
 
 wxPropertyGrid::wxPropertyGrid()
@@ -426,8 +291,10 @@ bool wxPropertyGrid::Create( wxWindow *parent,
                              const wxString& name )
 {
 
                              const wxString& name )
 {
 
-    if ( !(style&wxBORDER_MASK) )
-        style |= wxSIMPLE_BORDER;
+    if (!(style&wxBORDER_MASK))
+    {
+        style |= wxBORDER_THEME;
+    }
 
     style |= wxVSCROLL;
 
 
     style |= wxVSCROLL;
 
@@ -454,14 +321,17 @@ void wxPropertyGrid::Init1()
         wxPropertyGrid::RegisterDefaultEditors();
 
     m_iFlags = 0;
         wxPropertyGrid::RegisterDefaultEditors();
 
     m_iFlags = 0;
-    m_pState = (wxPropertyGridPageState*) NULL;
-    m_wndEditor = m_wndEditor2 = (wxWindow*) NULL;
-    m_selected = (wxPGProperty*) NULL;
-    m_selColumn = -1;
-    m_propHover = (wxPGProperty*) NULL;
+    m_pState = NULL;
+    m_wndEditor = m_wndEditor2 = NULL;
+    m_selColumn = 1;
+    m_colHover = 1;
+    m_propHover = NULL;
+    m_labelEditor = NULL;
+    m_labelEditorProperty = NULL;
     m_eventObject = this;
     m_eventObject = this;
-    m_curFocused = (wxWindow*) NULL;
-    m_tlwHandler = NULL;
+    m_curFocused = NULL;
+    m_processedEvent = NULL;
+    m_sortFunction = NULL;
     m_inDoPropertyChanged = 0;
     m_inCommitChangesFromEditor = 0;
     m_inDoSelectProperty = 0;
     m_inDoPropertyChanged = 0;
     m_inCommitChangesFromEditor = 0;
     m_inDoSelectProperty = 0;
@@ -484,17 +354,15 @@ void wxPropertyGrid::Init1()
     m_coloursCustomized = 0;
     m_frozen = 0;
 
     m_coloursCustomized = 0;
     m_frozen = 0;
 
-    m_canvas = NULL;
-
 #if wxPG_DOUBLE_BUFFER
 #if wxPG_DOUBLE_BUFFER
-    m_doubleBuffer = (wxBitmap*) NULL;
+    m_doubleBuffer = NULL;
 #endif
 
 #ifndef wxPG_ICON_WIDTH
 #endif
 
 #ifndef wxPG_ICON_WIDTH
-       m_expandbmp = NULL;
-       m_collbmp = NULL;
-       m_iconWidth = 11;
-       m_iconHeight = 11;
+    m_expandbmp = NULL;
+    m_collbmp = NULL;
+    m_iconWidth = 11;
+    m_iconHeight = 11;
 #else
     m_iconWidth = wxPG_ICON_WIDTH;
 #endif
 #else
     m_iconWidth = wxPG_ICON_WIDTH;
 #endif
@@ -538,7 +406,7 @@ void wxPropertyGrid::Init2()
     }
 
     if ( !(m_windowStyle & wxPG_SPLITTER_AUTO_CENTER) )
     }
 
     if ( !(m_windowStyle & wxPG_SPLITTER_AUTO_CENTER) )
-        m_iFlags |= wxPG_FL_DONT_CENTER_SPLITTER;
+        m_pState->m_dontCenterSplitter = true;
 
     if ( m_windowStyle & wxPG_HIDE_CATEGORIES )
     {
 
     if ( m_windowStyle & wxPG_HIDE_CATEGORIES )
     {
@@ -551,31 +419,22 @@ void wxPropertyGrid::Init2()
 
 #ifndef wxPG_ICON_WIDTH
     // create two bitmap nodes for drawing
 
 #ifndef wxPG_ICON_WIDTH
     // create two bitmap nodes for drawing
-       m_expandbmp = new wxBitmap(expand_xpm);
-       m_collbmp = new wxBitmap(collapse_xpm);
+    m_expandbmp = new wxBitmap(expand_xpm);
+    m_collbmp = new wxBitmap(collapse_xpm);
 
 
-       // calculate average font height for bitmap centering
+    // calculate average font height for bitmap centering
 
 
-       m_iconWidth = m_expandbmp->GetWidth();
-       m_iconHeight = m_expandbmp->GetHeight();
+    m_iconWidth = m_expandbmp->GetWidth();
+    m_iconHeight = m_expandbmp->GetHeight();
 #endif
 
     m_curcursor = wxCURSOR_ARROW;
     m_cursorSizeWE = new wxCursor( wxCURSOR_SIZEWE );
 
 #endif
 
     m_curcursor = wxCURSOR_ARROW;
     m_cursorSizeWE = new wxCursor( wxCURSOR_SIZEWE );
 
-       // adjust bitmap icon y position so they are centered
+    // adjust bitmap icon y position so they are centered
     m_vspacing = wxPG_DEFAULT_VSPACING;
 
     m_vspacing = wxPG_DEFAULT_VSPACING;
 
-    if ( !m_font.Ok() )
-    {
-        wxFont useFont = wxScrolledWindow::GetFont();
-        wxScrolledWindow::SetOwnFont( useFont );
-    }
-    else
-    {
-        // This should be otherwise called by SetOwnFont
-           CalculateFontAndBitmapStuff( wxPG_DEFAULT_VSPACING );
-    }
+    CalculateFontAndBitmapStuff( wxPG_DEFAULT_VSPACING );
 
     // Allocate cell datas indirectly by calling setter
     m_propertyDefaultCell.SetBgCol(*wxBLACK);
 
     // Allocate cell datas indirectly by calling setter
     m_propertyDefaultCell.SetBgCol(*wxBLACK);
@@ -586,22 +445,20 @@ void wxPropertyGrid::Init2()
     // This helps with flicker
     SetBackgroundStyle( wxBG_STYLE_CUSTOM );
 
     // This helps with flicker
     SetBackgroundStyle( wxBG_STYLE_CUSTOM );
 
-    // Hook the TLW
-    wxPGTLWHandler* handler = new wxPGTLWHandler(this);
-    m_tlp = ::wxGetTopLevelParent(this);
-    m_tlwHandler = handler;
-    m_tlp->PushEventHandler(handler);
+    // Hook the top-level parent
+    m_tlp = NULL;
+    m_tlpClosed = NULL;
+    m_tlpClosedTime = 0;
 
 
-       // set virtual size to this window size
+    // set virtual size to this window size
     wxSize wndsize = GetSize();
     wxSize wndsize = GetSize();
-       SetVirtualSize(wndsize.GetWidth(), wndsize.GetWidth());
+    SetVirtualSize(wndsize.GetWidth(), wndsize.GetWidth());
 
     m_timeCreated = ::wxGetLocalTimeMillis();
 
 
     m_timeCreated = ::wxGetLocalTimeMillis();
 
-    m_canvas = new wxPGCanvas();
-    m_canvas->Create(this, 1, wxPoint(0, 0), GetClientSize(),
-                     wxWANTS_CHARS | wxCLIP_CHILDREN);
-    m_canvas->SetBackgroundStyle( wxBG_STYLE_CUSTOM );
+    //m_canvas->Create(this, wxID_ANY, wxPoint(0, 0), GetClientSize(),
+    //                 wxWANTS_CHARS | wxCLIP_CHILDREN);
+    SetBackgroundStyle( wxBG_STYLE_CUSTOM );
 
     m_iFlags |= wxPG_FL_INITIALIZED;
 
 
     m_iFlags |= wxPG_FL_INITIALIZED;
 
@@ -619,45 +476,78 @@ wxPropertyGrid::~wxPropertyGrid()
 {
     size_t i;
 
 {
     size_t i;
 
-    DoSelectProperty(NULL);
+#if wxUSE_THREADS
+    wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
+#endif
+
+    //
+    // Remove grid and property pointers from live wxPropertyGridEvents.
+    for ( i=0; i<m_liveEvents.size(); i++ )
+    {
+        wxPropertyGridEvent* evt = m_liveEvents[i];
+        evt->SetPropertyGrid(NULL);
+        evt->SetProperty(NULL);
+    }
+    m_liveEvents.clear();
+
+    if ( m_processedEvent )
+    {
+        // All right... we are being deleted while wxPropertyGrid event
+        // is being sent. Make sure that event propagates as little
+        // as possible (although usually this is not enough to prevent
+        // a crash).
+        m_processedEvent->Skip(false);
+        m_processedEvent->StopPropagation();
+
+        // Let's use wxMessageBox to make the message appear more
+        // reliably (and *before* the crash can happen).
+        ::wxMessageBox("wxPropertyGrid was being destroyed in an event "
+                       "generated by it. This usually leads to a crash "
+                       "so it is recommended to destroy the control "
+                       "at idle time instead.");
+    }
+
+    DoSelectProperty(NULL, wxPG_SEL_NOVALIDATE|wxPG_SEL_DONT_SEND_EVENT);
 
     // This should do prevent things from going too badly wrong
     m_iFlags &= ~(wxPG_FL_INITIALIZED);
 
     if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
 
     // This should do prevent things from going too badly wrong
     m_iFlags &= ~(wxPG_FL_INITIALIZED);
 
     if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
-        m_canvas->ReleaseMouse();
+        ReleaseMouse();
 
 
-    wxPGTLWHandler* handler = (wxPGTLWHandler*) m_tlwHandler;
-    m_tlp->RemoveEventHandler(handler);
-    delete handler;
+    // Call with NULL to disconnect event handling
+    if ( GetExtraStyle() & wxPG_EX_ENABLE_TLP_TRACKING )
+    {
+        OnTLPChanging(NULL);
 
 
-#ifdef __WXDEBUG__
-    if ( IsEditorsValueModified() )
-        ::wxMessageBox(wxS("Most recent change in property editor was lost!!!\n\n(if you don't want this to happen, close your frames and dialogs using Close(false).)"),
-                       wxS("wxPropertyGrid Debug Warning") );
-#endif
+        wxASSERT_MSG( !IsEditorsValueModified(),
+                      wxS("Most recent change in property editor was ")
+                      wxS("lost!!! (if you don't want this to happen, ")
+                      wxS("close your frames and dialogs using ")
+                      wxS("Close(false).)") );
+    }
 
 #if wxPG_DOUBLE_BUFFER
     if ( m_doubleBuffer )
         delete m_doubleBuffer;
 #endif
 
 
 #if wxPG_DOUBLE_BUFFER
     if ( m_doubleBuffer )
         delete m_doubleBuffer;
 #endif
 
-    //m_selected = (wxPGProperty*) NULL;
-
     if ( m_iFlags & wxPG_FL_CREATEDSTATE )
         delete m_pState;
 
     delete m_cursorSizeWE;
 
 #ifndef wxPG_ICON_WIDTH
     if ( m_iFlags & wxPG_FL_CREATEDSTATE )
         delete m_pState;
 
     delete m_cursorSizeWE;
 
 #ifndef wxPG_ICON_WIDTH
-       delete m_expandbmp;
-       delete m_collbmp;
+    delete m_expandbmp;
+    delete m_collbmp;
 #endif
 
     // Delete common value records
     for ( i=0; i<m_commonValues.size(); i++ )
     {
 #endif
 
     // Delete common value records
     for ( i=0; i<m_commonValues.size(); i++ )
     {
-        delete GetCommonValue(i);
+        // Use temporary variable to work around possible strange VC6 (asserts because m_size is zero)
+        wxPGCommonValue* value = m_commonValues[i];
+        delete value;
     }
 }
 
     }
 }
 
@@ -666,7 +556,7 @@ wxPropertyGrid::~wxPropertyGrid()
 bool wxPropertyGrid::Destroy()
 {
     if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
 bool wxPropertyGrid::Destroy()
 {
     if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
-        m_canvas->ReleaseMouse();
+        ReleaseMouse();
 
     return wxScrolledWindow::Destroy();
 }
 
     return wxScrolledWindow::Destroy();
 }
@@ -727,7 +617,7 @@ void wxPropertyGrid::SetWindowStyleFlag( long style )
             //
             // Tooltips disabled
             //
             //
             // Tooltips disabled
             //
-            m_canvas->SetToolTip( (wxToolTip*) NULL );
+            wxScrolledWindow::SetToolTip( NULL );
         }
     #endif
     }
         }
     #endif
     }
@@ -766,19 +656,368 @@ void wxPropertyGrid::Thaw()
         wxScrolledWindow::Thaw();
         RecalculateVirtualSize();
     #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
         wxScrolledWindow::Thaw();
         RecalculateVirtualSize();
     #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
-        m_canvas->Refresh();
+        Refresh();
     #endif
 
         // Force property re-selection
     #endif
 
         // Force property re-selection
-        if ( m_selected )
-            DoSelectProperty(m_selected, wxPG_SEL_FORCE);
+        // NB: We must copy the selection.
+        wxArrayPGProperty selection = m_pState->m_selection;
+        DoSetSelection(selection, wxPG_SEL_FORCE);
+    }
+}
+
+// -----------------------------------------------------------------------
+
+bool wxPropertyGrid::DoAddToSelection( wxPGProperty* prop, int selFlags )
+{
+    wxCHECK( prop, false );
+
+    if ( !(GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION) )
+        return DoSelectProperty(prop, selFlags);
+
+    wxArrayPGProperty& selection = m_pState->m_selection;
+
+    if ( !selection.size() )
+    {
+        return DoSelectProperty(prop, selFlags);
+    }
+    else
+    {
+        // For categories, only one can be selected at a time
+        if ( prop->IsCategory() || selection[0]->IsCategory() )
+            return true;
+
+        selection.push_back(prop);
+
+        if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
+        {
+            SendEvent( wxEVT_PG_SELECTED, prop, NULL );
+        }
+
+        DrawItem(prop);
+    }
+
+    return true;
+}
+
+// -----------------------------------------------------------------------
+
+bool wxPropertyGrid::DoRemoveFromSelection( wxPGProperty* prop, int selFlags )
+{
+    wxCHECK( prop, false );
+    bool res;
+
+    wxArrayPGProperty& selection = m_pState->m_selection;
+    if ( selection.size() <= 1 )
+    {
+        res = DoSelectProperty(NULL, selFlags);
+    }
+    else
+    {
+        m_pState->DoRemoveFromSelection(prop);
+        DrawItem(prop);
+        res = true;
+    }
+
+    return res;
+}
+
+// -----------------------------------------------------------------------
+
+bool wxPropertyGrid::DoSelectAndEdit( wxPGProperty* prop,
+                                      unsigned int colIndex,
+                                      unsigned int selFlags )
+{
+    //
+    // NB: Enable following if label editor background colour is
+    //     ever changed to any other than m_colSelBack.
+    //
+    // We use this workaround to prevent visible flicker when editing
+    // a cell. Atleast on wxMSW, there is a difficult to find
+    // (and perhaps prevent) redraw somewhere between making property
+    // selected and enabling label editing.
+    //
+    //wxColour prevColSelBack = m_colSelBack;
+    //m_colSelBack = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
+
+    bool res;
+
+    if ( colIndex == 1 )
+    {
+        res = DoSelectProperty(prop, selFlags);
+    }
+    else
+    {
+        // send event
+        DoClearSelection(false, wxPG_SEL_NO_REFRESH);
+
+        if ( m_pState->m_editableColumns.Index(colIndex) == wxNOT_FOUND )
+        {
+            res = DoAddToSelection(prop, selFlags);
+        }
+        else
+        {
+            res = DoAddToSelection(prop, selFlags|wxPG_SEL_NO_REFRESH);
+
+            DoBeginLabelEdit(colIndex, selFlags);
+        }
+    }
+
+    //m_colSelBack = prevColSelBack;
+    return res;
+}
+
+// -----------------------------------------------------------------------
+
+bool wxPropertyGrid::AddToSelectionFromInputEvent( wxPGProperty* prop,
+                                                   unsigned int colIndex,
+                                                   wxMouseEvent* mouseEvent,
+                                                   int selFlags )
+{
+    bool alreadySelected = m_pState->DoIsPropertySelected(prop);
+    bool res = true;
+    bool addToExistingSelection;
+
+    if ( GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION )
+    {
+        if ( mouseEvent )
+        {
+            if ( mouseEvent->GetEventType() == wxEVT_RIGHT_DOWN ||
+                 mouseEvent->GetEventType() == wxEVT_RIGHT_UP )
+            {
+                // Allow right-click for context menu without
+                // disturbing the selection.
+                if ( GetSelectedProperties().size() <= 1 ||
+                     !alreadySelected )
+                    return DoSelectAndEdit(prop, colIndex, selFlags);
+                return true;
+            }
+            else
+            {
+                addToExistingSelection = mouseEvent->ShiftDown();
+            }
+        }
+        else
+        {
+            addToExistingSelection = false;
+        }
+    }
+    else
+    {
+        addToExistingSelection = false;
+    }
+
+    if ( addToExistingSelection )
+    {
+        if ( !alreadySelected )
+        {
+            res = DoAddToSelection(prop, selFlags);
+        }
+        else if ( GetSelectedProperties().size() > 1 )
+        {
+            res = DoRemoveFromSelection(prop, selFlags);
+        }
+    }
+    else
+    {
+        res = DoSelectAndEdit(prop, colIndex, selFlags);
+    }
+
+    return res;
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::DoSetSelection( const wxArrayPGProperty& newSelection,
+                                     int selFlags )
+{
+    if ( newSelection.size() > 0 )
+    {
+        if ( !DoSelectProperty(newSelection[0], selFlags) )
+            return;
+    }
+    else
+    {
+        DoClearSelection(false, selFlags);
+    }
+
+    for ( unsigned int i = 1; i < newSelection.size(); i++ )
+    {
+        DoAddToSelection(newSelection[i], selFlags);
+    }
+
+    Refresh();
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::MakeColumnEditable( unsigned int column,
+                                         bool editable )
+{
+    wxASSERT( column != 1 );
+
+    wxArrayInt& cols = m_pState->m_editableColumns;
+
+    if ( editable )
+    {
+        cols.push_back(column);
+    }
+    else
+    {
+        for ( int i = cols.size() - 1; i > 0; i-- )
+        {
+            if ( cols[i] == (int)column )
+                cols.erase( cols.begin() + i );
+        }
+    }
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::DoBeginLabelEdit( unsigned int colIndex,
+                                       int selFlags )
+{
+    wxPGProperty* selected = GetSelection();
+    wxCHECK_RET(selected, wxT("No property selected"));
+    wxCHECK_RET(colIndex != 1, wxT("Do not use this for column 1"));
+
+    if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
+    {
+        if ( SendEvent( wxEVT_PG_LABEL_EDIT_BEGIN,
+                        selected, NULL, 0,
+                        colIndex ) )
+            return;
+    }
+
+    wxString text;
+    const wxPGCell* cell = NULL;
+    if ( selected->HasCell(colIndex) )
+    {
+        cell = &selected->GetCell(colIndex);
+        if ( !cell->HasText() && colIndex == 0 )
+            text = selected->GetLabel();
+    }
+
+    if ( !cell  )
+    {
+        if ( colIndex == 0 )
+            text = selected->GetLabel();
+        else
+            cell = &selected->GetOrCreateCell(colIndex);
+    }
+
+    if ( cell && cell->HasText() )
+        text = cell->GetText();
+
+    DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE);  // send event
+
+    m_selColumn = colIndex;
+
+    wxRect r = GetEditorWidgetRect(selected, m_selColumn);
+
+    wxWindow* tc = GenerateEditorTextCtrl(r.GetPosition(),
+                                          r.GetSize(),
+                                          text,
+                                          NULL,
+                                          wxTE_PROCESS_ENTER,
+                                          0,
+                                          colIndex);
+
+    wxWindowID id = tc->GetId();
+    tc->Connect(id, wxEVT_COMMAND_TEXT_ENTER,
+        wxCommandEventHandler(wxPropertyGrid::OnLabelEditorEnterPress),
+        NULL, this);
+    tc->Connect(id, wxEVT_KEY_DOWN,
+        wxKeyEventHandler(wxPropertyGrid::OnLabelEditorKeyPress),
+        NULL, this);
+
+    tc->SetFocus();
+
+    m_labelEditor = wxStaticCast(tc, wxTextCtrl);
+    m_labelEditorProperty = selected;
+}
+
+// -----------------------------------------------------------------------
+
+void
+wxPropertyGrid::OnLabelEditorEnterPress( wxCommandEvent& WXUNUSED(event) )
+{
+    DoEndLabelEdit(true);
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::OnLabelEditorKeyPress( wxKeyEvent& event )
+{
+    int keycode = event.GetKeyCode();
+
+    if ( keycode == WXK_ESCAPE )
+    {
+        DoEndLabelEdit(false);
+    }
+    else
+    {
+        event.Skip();
+    }
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::DoEndLabelEdit( bool commit, int selFlags )
+{
+    if ( !m_labelEditor )
+        return;
+
+    wxPGProperty* prop = m_labelEditorProperty;
+    wxASSERT(prop);
+
+    if ( commit )
+    {
+        if ( !(selFlags & wxPG_SEL_DONT_SEND_EVENT) )
+        {
+            // wxPG_SEL_NOVALIDATE is passed correctly in selFlags
+            if ( SendEvent( wxEVT_PG_LABEL_EDIT_ENDING,
+                            prop, NULL, selFlags,
+                            m_selColumn ) )
+                return;
+        }
+
+        wxString text = m_labelEditor->GetValue();
+        wxPGCell* cell = NULL;
+        if ( prop->HasCell(m_selColumn) )
+        {
+            cell = &prop->GetCell(m_selColumn);
+        }
+        else
+        {
+            if ( m_selColumn == 0 )
+                prop->SetLabel(text);
+            else
+                cell = &prop->GetOrCreateCell(m_selColumn);
+        }
+
+        if ( cell )
+            cell->SetText(text);
     }
     }
+
+    m_selColumn = 1;
+
+    DestroyEditorWnd(m_labelEditor);
+    m_labelEditor = NULL;
+    m_labelEditorProperty = NULL;
+
+    DrawItem(prop);
 }
 
 // -----------------------------------------------------------------------
 
 void wxPropertyGrid::SetExtraStyle( long exStyle )
 {
 }
 
 // -----------------------------------------------------------------------
 
 void wxPropertyGrid::SetExtraStyle( long exStyle )
 {
+    if ( exStyle & wxPG_EX_ENABLE_TLP_TRACKING )
+        OnTLPChanging(::wxGetTopLevelParent(this));
+    else
+        OnTLPChanging(NULL);
+
     if ( exStyle & wxPG_EX_NATIVE_DOUBLE_BUFFERING )
     {
 #if defined(__WXMSW__)
     if ( exStyle & wxPG_EX_NATIVE_DOUBLE_BUFFERING )
     {
 #if defined(__WXMSW__)
@@ -830,28 +1069,113 @@ void wxPropertyGrid::SetExtraStyle( long exStyle )
 // returns the best acceptable minimal size
 wxSize wxPropertyGrid::DoGetBestSize() const
 {
 // returns the best acceptable minimal size
 wxSize wxPropertyGrid::DoGetBestSize() const
 {
-    int hei = 15;
-    if ( m_lineHeight > hei )
-        hei = m_lineHeight;
-    wxSize sz = wxSize( 60, hei+40 );
+    int lineHeight = wxMax(15, m_lineHeight);
+
+    // don't make the grid too tall (limit height to 10 items) but don't
+    // make it too small neither
+    int numLines = wxMin
+                   (
+                    wxMax(m_pState->m_properties->GetChildCount(), 3),
+                    10
+                   );
+
+    wxClientDC dc(const_cast<wxPropertyGrid *>(this));
+    int width = m_marginWidth;
+    for ( unsigned int i = 0; i < m_pState->m_colWidths.size(); i++ )
+    {
+        width += m_pState->GetColumnFitWidth(dc, m_pState->DoGetRoot(), i, true);
+    }
+
+    const wxSize sz = wxSize(width, lineHeight*numLines + 40);
 
     CacheBestSize(sz);
     return sz;
 }
 
 
     CacheBestSize(sz);
     return sz;
 }
 
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::OnTLPChanging( wxWindow* newTLP )
+{
+    if ( newTLP == m_tlp )
+        return;
+
+    wxLongLong currentTime = ::wxGetLocalTimeMillis();
+
+    //
+    // Parent changed so let's redetermine and re-hook the
+    // correct top-level window.
+    if ( m_tlp )
+    {
+        m_tlp->Disconnect( wxEVT_CLOSE_WINDOW,
+                           wxCloseEventHandler(wxPropertyGrid::OnTLPClose),
+                           NULL, this );
+        m_tlpClosed = m_tlp;
+        m_tlpClosedTime = currentTime;
+    }
+
+    if ( newTLP )
+    {
+        // Only accept new tlp if same one was not just dismissed.
+        if ( newTLP != m_tlpClosed ||
+             m_tlpClosedTime+250 < currentTime )
+        {
+            newTLP->Connect( wxEVT_CLOSE_WINDOW,
+                             wxCloseEventHandler(wxPropertyGrid::OnTLPClose),
+                             NULL, this );
+            m_tlpClosed = NULL;
+        }
+        else
+        {
+            newTLP = NULL;
+        }
+    }
+
+    m_tlp = newTLP;
+}
+
+// -----------------------------------------------------------------------
+
+void wxPropertyGrid::OnTLPClose( wxCloseEvent& event )
+{
+    // ClearSelection forces value validation/commit.
+    if ( event.CanVeto() && !DoClearSelection() )
+    {
+        event.Veto();
+        return;
+    }
+
+    // Ok, it can close, set tlp pointer to NULL. Some other event
+    // handler can of course veto the close, but our OnIdle() should
+    // then be able to regain the tlp pointer.
+    OnTLPChanging(NULL);
+
+    event.Skip();
+}
+
+// -----------------------------------------------------------------------
+
+bool wxPropertyGrid::Reparent( wxWindowBase *newParent )
+{
+    OnTLPChanging((wxWindow*)newParent);
+
+    bool res = wxScrolledWindow::Reparent(newParent);
+
+    return res;
+}
+
 // -----------------------------------------------------------------------
 // wxPropertyGrid Font and Colour Methods
 // -----------------------------------------------------------------------
 
 void wxPropertyGrid::CalculateFontAndBitmapStuff( int vspacing )
 {
 // -----------------------------------------------------------------------
 // wxPropertyGrid Font and Colour Methods
 // -----------------------------------------------------------------------
 
 void wxPropertyGrid::CalculateFontAndBitmapStuff( int vspacing )
 {
-       int x = 0, y = 0;
+    int x = 0, y = 0;
 
     m_captionFont = wxScrolledWindow::GetFont();
 
 
     m_captionFont = wxScrolledWindow::GetFont();
 
-       GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
+    GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
     m_subgroup_extramargin = x + (x/2);
     m_subgroup_extramargin = x + (x/2);
-       m_fontHeight = y;
+    m_fontHeight = y;
 
 #if wxPG_USE_RENDERER_NATIVE
     m_iconWidth = wxPG_ICON_WIDTH;
 
 #if wxPG_USE_RENDERER_NATIVE
     m_iconWidth = wxPG_ICON_WIDTH;
@@ -880,7 +1204,7 @@ void wxPropertyGrid::CalculateFontAndBitmapStuff( int vspacing )
         m_marginWidth = m_gutterWidth*2 + m_iconWidth;
 
     m_captionFont.SetWeight(wxBOLD);
         m_marginWidth = m_gutterWidth*2 + m_iconWidth;
 
     m_captionFont.SetWeight(wxBOLD);
-       GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
+    GetTextExtent(wxS("jG"), &x, &y, 0, 0, &m_captionFont);
 
     m_lineHeight = m_fontHeight+(2*m_spacingy)+1;
 
 
     m_lineHeight = m_fontHeight+(2*m_spacingy)+1;
 
@@ -1036,34 +1360,16 @@ void wxPropertyGrid::ResetColours()
 bool wxPropertyGrid::SetFont( const wxFont& font )
 {
     // Must disable active editor.
 bool wxPropertyGrid::SetFont( const wxFont& font )
 {
     // Must disable active editor.
-    ClearSelection(false);
+    DoClearSelection();
 
 
-    // TODO: Following code is disabled with wxMac because
-    //   it is reported to fail. I (JMS) cannot debug it
-    //   personally right now.
-    // CS: should be fixed now, leaving old code in just in case, TODO: REMOVE
-#if 1 // !defined(__WXMAC__)
     bool res = wxScrolledWindow::SetFont( font );
     bool res = wxScrolledWindow::SetFont( font );
-    if ( res )
+    if ( res && GetParent()) // may not have been Create()ed yet if SetFont called from SetWindowVariant
     {
         CalculateFontAndBitmapStuff( m_vspacing );
     {
         CalculateFontAndBitmapStuff( m_vspacing );
-
-        if ( m_pState )
-            m_pState->CalculateFontAndBitmapStuff(m_vspacing);
-
         Refresh();
     }
 
     return res;
         Refresh();
     }
 
     return res;
-#else
-    // ** wxMAC Only **
-    // TODO: Remove after SetFont crash fixed.
-    if ( m_iFlags & wxPG_FL_INITIALIZED )
-    {
-        wxLogDebug(wxT("WARNING: propGrid.cpp: wxPropertyGrid::SetFont has been disabled on wxMac since there has been crash reported in it. If you are willing to debug the cause, replace line '#if !defined(__WXMAC__)' with line '#if 1' in wxPropertyGrid::SetFont."));
-    }
-    return false;
-#endif
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -1179,29 +1485,11 @@ void wxPropertyGrid::PrepareAfterItemsAdded()
     m_pState->m_itemsAdded = 0;
 
     if ( m_windowStyle & wxPG_AUTO_SORT )
     m_pState->m_itemsAdded = 0;
 
     if ( m_windowStyle & wxPG_AUTO_SORT )
-        Sort();
+        Sort(wxPG_SORT_TOP_LEVEL_ONLY);
 
     RecalculateVirtualSize();
 }
 
 
     RecalculateVirtualSize();
 }
 
-// -----------------------------------------------------------------------
-// wxPropertyGrid property value setting and getting
-// -----------------------------------------------------------------------
-
-void wxPropertyGrid::DoSetPropertyValueUnspecified( wxPGProperty* p )
-{
-    m_pState->DoSetPropertyValueUnspecified(p);
-    DrawItemAndChildren(p);
-
-    wxPGProperty* parent = p->GetParent();
-    while ( parent &&
-            (parent->GetFlags() & wxPG_PROP_PARENTAL_FLAGS) == wxPG_PROP_MISC_PARENT )
-    {
-        DrawItem(parent);
-        parent = parent->GetParent();
-    }
-}
-
 // -----------------------------------------------------------------------
 // wxPropertyGrid property operations
 // -----------------------------------------------------------------------
 // -----------------------------------------------------------------------
 // wxPropertyGrid property operations
 // -----------------------------------------------------------------------
@@ -1421,7 +1709,7 @@ wxPGProperty* wxPropertyGrid::DoGetItemAtY( int y ) const
 {
     // Outside?
     if ( y < 0 )
 {
     // Outside?
     if ( y < 0 )
-        return (wxPGProperty*) NULL;
+        return NULL;
 
     unsigned int a = 0;
     return m_pState->m_properties->GetItemAtY(y, m_lineHeight, &a);
 
     unsigned int a = 0;
     return m_pState->m_properties->GetItemAtY(y, m_lineHeight, &a);
@@ -1434,13 +1722,34 @@ wxPGProperty* wxPropertyGrid::DoGetItemAtY( int y ) const
 void wxPropertyGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
 {
     wxPaintDC dc(this);
 void wxPropertyGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
 {
     wxPaintDC dc(this);
+    PrepareDC(dc);
+
+    // Don't paint after destruction has begun
+    if ( !HasInternalFlag(wxPG_FL_INITIALIZED) )
+        return;
+
+    // Find out where the window is scrolled to
+    int vx,vy;                     // Top left corner of client
+    GetViewStart(&vx,&vy);
+    vy *= wxPG_PIXELS_PER_UNIT;
 
     // Update everything inside the box
     wxRect r = GetUpdateRegion().GetBox();
 
 
     // Update everything inside the box
     wxRect r = GetUpdateRegion().GetBox();
 
-    dc.SetPen(m_colEmptySpace);
-    dc.SetBrush(m_colEmptySpace);
-    dc.DrawRectangle(r);
+    r.y += vy;
+
+    // FIXME: This is just a workaround for a bug that causes splitters not
+    //        to paint when other windows are being dragged over the grid.
+    wxRect fullRect = GetRect();
+    r.x = fullRect.x;
+    r.width = fullRect.width;
+
+    // Repaint this rectangle
+    DrawItems( dc, r.y, r.y + r.height, &r );
+
+    // We assume that the size set when grid is shown
+    // is what is desired.
+    SetInternalFlag(wxPG_FL_GOOD_SIZE_SET);
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -1522,19 +1831,25 @@ void wxPropertyGrid::DrawExpanderButton( wxDC& dc, const wxRect& rect,
 // topy and bottomy are already unscrolled (ie. physical)
 //
 void wxPropertyGrid::DrawItems( wxDC& dc,
 // topy and bottomy are already unscrolled (ie. physical)
 //
 void wxPropertyGrid::DrawItems( wxDC& dc,
-                                unsigned int topy,
-                                unsigned int bottomy,
-                                const wxRect* clipRect )
-{
-    if ( m_frozen || m_height < 1 || bottomy < topy || !m_pState ) return;
+                                unsigned int topItemY,
+                                unsigned int bottomItemY,
+                                const wxRect* drawRect )
+{
+    if ( m_frozen ||
+         m_height < 1 ||
+         bottomItemY < topItemY ||
+         !m_pState )
+        return;
 
     m_pState->EnsureVirtualHeight();
 
 
     m_pState->EnsureVirtualHeight();
 
-    wxRect tempClipRect;
-    if ( !clipRect )
+    wxRect tempDrawRect;
+    if ( !drawRect )
     {
     {
-        tempClipRect = wxRect(0,topy,m_pState->m_width,bottomy);
-        clipRect = &tempClipRect;
+        tempDrawRect = wxRect(0, topItemY,
+                              m_pState->m_width,
+                              bottomItemY);
+        drawRect = &tempDrawRect;
     }
 
     // items added check
     }
 
     // items added check
@@ -1554,7 +1869,7 @@ void wxPropertyGrid::DrawItems( wxDC& dc,
         {
             if ( !m_doubleBuffer )
             {
         {
             if ( !m_doubleBuffer )
             {
-                paintFinishY = clipRect->y;
+                paintFinishY = drawRect->y;
                 dcPtr = NULL;
             }
             else
                 dcPtr = NULL;
             }
             else
@@ -1572,62 +1887,62 @@ void wxPropertyGrid::DrawItems( wxDC& dc,
 
         if ( dcPtr )
         {
 
         if ( dcPtr )
         {
-            dc.SetClippingRegion( *clipRect );
-            paintFinishY = DoDrawItems( *dcPtr, NULL, NULL, clipRect, isBuffered );
+            dc.SetClippingRegion( *drawRect );
+            paintFinishY = DoDrawItems( *dcPtr, drawRect, isBuffered );
+            int drawBottomY = drawRect->y + drawRect->height;
+
+            // Clear area beyond last painted property
+            if ( paintFinishY < drawBottomY )
+            {
+                dcPtr->SetPen(m_colEmptySpace);
+                dcPtr->SetBrush(m_colEmptySpace);
+                dcPtr->DrawRectangle(0, paintFinishY,
+                                     m_width,
+                                     drawBottomY );
+            }
+
+            dc.DestroyClippingRegion();
         }
 
     #if wxPG_DOUBLE_BUFFER
         if ( bufferDC )
         {
         }
 
     #if wxPG_DOUBLE_BUFFER
         if ( bufferDC )
         {
-            dc.Blit( clipRect->x, clipRect->y, clipRect->width, clipRect->height,
-                bufferDC, 0, 0, wxCOPY );
-            dc.DestroyClippingRegion(); // Is this really necessary?
+            dc.Blit( drawRect->x, drawRect->y, drawRect->width,
+                     drawRect->height,
+                     bufferDC, 0, 0, wxCOPY );
             delete bufferDC;
         }
     #endif
     }
             delete bufferDC;
         }
     #endif
     }
-
-    // Clear area beyond bottomY?
-    if ( paintFinishY < (clipRect->y+clipRect->height) )
+    else
     {
     {
+        // Just clear the area
         dc.SetPen(m_colEmptySpace);
         dc.SetBrush(m_colEmptySpace);
         dc.SetPen(m_colEmptySpace);
         dc.SetBrush(m_colEmptySpace);
-        dc.DrawRectangle( 0, paintFinishY, m_width, (clipRect->y+clipRect->height) );
+        dc.DrawRectangle(*drawRect);
     }
 }
 
 // -----------------------------------------------------------------------
 
 int wxPropertyGrid::DoDrawItems( wxDC& dc,
     }
 }
 
 // -----------------------------------------------------------------------
 
 int wxPropertyGrid::DoDrawItems( wxDC& dc,
-                                 const wxPGProperty* firstItem,
-                                 const wxPGProperty* lastItem,
-                                 const wxRect* clipRect,
+                                 const wxRect* drawRect,
                                  bool isBuffered ) const
 {
                                  bool isBuffered ) const
 {
-    // TODO: This should somehow be eliminated.
-    wxRect tempClipRect;
-    if ( !clipRect )
-    {
-        wxASSERT(firstItem);
-        wxASSERT(lastItem);
-        tempClipRect = GetPropertyRect(firstItem, lastItem);
-        clipRect = &tempClipRect;
-    }
+    const wxPGProperty* firstItem;
+    const wxPGProperty* lastItem;
 
 
-    if ( !firstItem )
-        firstItem = DoGetItemAtY(clipRect->y);
+    firstItem = DoGetItemAtY(drawRect->y);
+    lastItem = DoGetItemAtY(drawRect->y+drawRect->height-1);
 
     if ( !lastItem )
 
     if ( !lastItem )
-    {
-        lastItem = DoGetItemAtY(clipRect->y+clipRect->height-1);
-        if ( !lastItem )
-            lastItem = GetLastItem( wxPG_ITERATE_VISIBLE );
-    }
+        lastItem = GetLastItem( wxPG_ITERATE_VISIBLE );
 
     if ( m_frozen || m_height < 1 || firstItem == NULL )
 
     if ( m_frozen || m_height < 1 || firstItem == NULL )
-        return clipRect->y;
+        return drawRect->y;
 
 
-    wxCHECK_MSG( !m_pState->m_itemsAdded, clipRect->y, wxT("no items added") );
+    wxCHECK_MSG( !m_pState->m_itemsAdded, drawRect->y,
+                 "no items added" );
     wxASSERT( m_pState->m_properties->GetChildCount() );
 
     int lh = m_lineHeight;
     wxASSERT( m_pState->m_properties->GetChildCount() );
 
     int lh = m_lineHeight;
@@ -1635,8 +1950,8 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
     int firstItemTopY;
     int lastItemBottomY;
 
     int firstItemTopY;
     int lastItemBottomY;
 
-    firstItemTopY = clipRect->y;
-    lastItemBottomY = clipRect->y + clipRect->height;
+    firstItemTopY = drawRect->y;
+    lastItemBottomY = drawRect->y + drawRect->height;
 
     // Align y coordinates to item boundaries
     firstItemTopY -= firstItemTopY % lh;
 
     // Align y coordinates to item boundaries
     firstItemTopY -= firstItemTopY % lh;
@@ -1644,19 +1959,22 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
     lastItemBottomY -= 1;
 
     // Entire range outside scrolled, visible area?
     lastItemBottomY -= 1;
 
     // Entire range outside scrolled, visible area?
-    if ( firstItemTopY >= (int)m_pState->GetVirtualHeight() || lastItemBottomY <= 0 )
-        return clipRect->y;
-
-    wxCHECK_MSG( firstItemTopY < lastItemBottomY, clipRect->y, wxT("invalid y values") );
+    if ( firstItemTopY >= (int)m_pState->GetVirtualHeight() ||
+         lastItemBottomY <= 0 )
+        return drawRect->y;
 
 
+    wxCHECK_MSG( firstItemTopY < lastItemBottomY,
+                 drawRect->y,
+                 "invalid y values" );
 
     /*
 
     /*
-    wxLogDebug(wxT("  -> DoDrawItems ( \"%s\" -> \"%s\", height=%i (ch=%i), clipRect = 0x%lX )"),
+    wxLogDebug("  -> DoDrawItems ( \"%s\" -> \"%s\"
+               "height=%i (ch=%i), drawRect = 0x%lX )",
         firstItem->GetLabel().c_str(),
         lastItem->GetLabel().c_str(),
         (int)(lastItemBottomY - firstItemTopY),
         (int)m_height,
         firstItem->GetLabel().c_str(),
         lastItem->GetLabel().c_str(),
         (int)(lastItemBottomY - firstItemTopY),
         (int)m_height,
-        (unsigned long)clipRect );
+        (unsigned long)drawRect );
     */
 
     wxRect r;
     */
 
     wxRect r;
@@ -1668,7 +1986,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
     //
     // With wxPG_DOUBLE_BUFFER, do double buffering
 
     //
     // With wxPG_DOUBLE_BUFFER, do double buffering
-    // - buffer's y = 0, so align cliprect and coordinates to that
+    // - buffer's y = 0, so align drawRect and coordinates to that
     //
 #if wxPG_DOUBLE_BUFFER
 
     //
 #if wxPG_DOUBLE_BUFFER
 
@@ -1676,15 +1994,15 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
     if ( isBuffered )
     {
 
     if ( isBuffered )
     {
-        xRelMod = clipRect->x;
-        yRelMod = clipRect->y;
+        xRelMod = drawRect->x;
+        yRelMod = drawRect->y;
 
         //
 
         //
-        // clipRect conversion
-        cr2 = *clipRect;
+        // drawRect conversion
+        cr2 = *drawRect;
         cr2.x -= xRelMod;
         cr2.y -= yRelMod;
         cr2.x -= xRelMod;
         cr2.y -= yRelMod;
-        clipRect = &cr2;
+        drawRect = &cr2;
         firstItemTopY -= yRelMod;
         lastItemBottomY -= yRelMod;
     }
         firstItemTopY -= yRelMod;
         lastItemBottomY -= yRelMod;
     }
@@ -1694,11 +2012,11 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
     int x = m_marginWidth - xRelMod;
 
 
     int x = m_marginWidth - xRelMod;
 
-    const wxFont& normalfont = m_font;
+    wxFont normalFont = GetFont();
 
     bool reallyFocused = (m_iFlags & wxPG_FL_FOCUSED) != 0;
 
 
     bool reallyFocused = (m_iFlags & wxPG_FL_FOCUSED) != 0;
 
-    bool isEnabled = IsEnabled();
+    bool isPgEnabled = IsEnabled();
 
     //
     // Prepare some pens and brushes that are often changed to.
 
     //
     // Prepare some pens and brushes that are often changed to.
@@ -1709,6 +2027,12 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
     wxBrush capbgbrush(m_colCapBack,wxSOLID);
     wxPen linepen(m_colLine,1,wxSOLID);
 
     wxBrush capbgbrush(m_colCapBack,wxSOLID);
     wxPen linepen(m_colLine,1,wxSOLID);
 
+    wxColour selBackCol;
+    if ( isPgEnabled )
+        selBackCol = m_colSelBack;
+    else
+        selBackCol = m_colMargin;
+
     // pen that has same colour as text
     wxPen outlinepen(m_colPropFore,1,wxSOLID);
 
     // pen that has same colour as text
     wxPen outlinepen(m_colPropFore,1,wxSOLID);
 
@@ -1722,7 +2046,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
         dc.DrawRectangle(-1-xRelMod,firstItemTopY-1,x+2,lastItemBottomY-firstItemTopY+2);
     }
 
         dc.DrawRectangle(-1-xRelMod,firstItemTopY-1,x+2,lastItemBottomY-firstItemTopY+2);
     }
 
-    const wxPGProperty* selected = m_selected;
+    const wxPGProperty* firstSelected = GetSelection();
     const wxPropertyGridPageState* state = m_pState;
 
 #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
     const wxPropertyGridPageState* state = m_pState;
 
 #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
@@ -1731,7 +2055,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
     // TODO: Only render columns that are within clipping region.
 
 
     // TODO: Only render columns that are within clipping region.
 
-    dc.SetFont(normalfont);
+    dc.SetFont(normalFont);
 
     wxPropertyGridConstIterator it( state, wxPG_ITERATE_VISIBLE, firstItem );
     int endScanBottomY = lastItemBottomY + lh;
 
     wxPropertyGridConstIterator it( state, wxPG_ITERATE_VISIBLE, firstItem );
     int endScanBottomY = lastItemBottomY + lh;
@@ -1796,8 +2120,28 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
         int y2 = y + lh;
 
 
         int y2 = y + lh;
 
+#ifdef __WXMSW__
         // Margin Edge
         // Margin Edge
-        dc.DrawLine( greyDepthX, y, greyDepthX, y2 );
+        // Modified by JACS to not draw a margin if wxPG_HIDE_MARGIN is specified, since it
+        // looks better, at least under Windows when we have a themed border (the themed-window-specific
+        // whitespace between the real border and the propgrid margin exacerbates the double-border look).
+
+        // Is this or its parent themed?
+        bool suppressMarginEdge = (GetWindowStyle() & wxPG_HIDE_MARGIN) &&
+            (((GetWindowStyle() & wxBORDER_MASK) == wxBORDER_THEME) ||
+            (((GetWindowStyle() & wxBORDER_MASK) == wxBORDER_NONE) && ((GetParent()->GetWindowStyle() & wxBORDER_MASK) == wxBORDER_THEME)));
+#else
+        bool suppressMarginEdge = false;
+#endif
+        if (!suppressMarginEdge)
+            dc.DrawLine( greyDepthX, y, greyDepthX, y2 );
+        else
+        {
+            // Blank out the margin edge
+            dc.SetPen(wxPen(GetBackgroundColour()));
+            dc.DrawLine( greyDepthX, y, greyDepthX, y2 );
+            dc.SetPen( linepen );
+        }
 
         // Splitters
         unsigned int si;
 
         // Splitters
         unsigned int si;
@@ -1822,7 +2166,9 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
         wxColour rowFgCol;
         wxColour rowBgCol;
 
         wxColour rowFgCol;
         wxColour rowBgCol;
 
-        if ( p != selected )
+        bool isSelected = state->DoIsPropertySelected(p);
+
+        if ( !isSelected )
         {
             // Disabled may get different colour.
             if ( !p->IsEnabled() )
         {
             // Disabled may get different colour.
             if ( !p->IsEnabled() )
@@ -1834,6 +2180,11 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
         }
         else
         {
         }
         else
         {
+#if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
+            if ( p == firstSelected )
+                wasSelectedPainted = true;
+#endif
+
             renderFlags |= wxPGCellRenderer::Selected;
 
             if ( !p->IsCategory() )
             renderFlags |= wxPGCellRenderer::Selected;
 
             if ( !p->IsCategory() )
@@ -1841,25 +2192,23 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
                 renderFlags |= wxPGCellRenderer::DontUseCellFgCol |
                                wxPGCellRenderer::DontUseCellBgCol;
 
                 renderFlags |= wxPGCellRenderer::DontUseCellFgCol |
                                wxPGCellRenderer::DontUseCellBgCol;
 
-#if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
-                wasSelectedPainted = true;
-#endif
-
-                // Selected gets different colour.
-                if ( reallyFocused )
+                if ( reallyFocused && p == firstSelected )
                 {
                     rowFgCol = m_colSelFore;
                 {
                     rowFgCol = m_colSelFore;
-                    rowBgCol = m_colSelBack;
+                    rowBgCol = selBackCol;
                 }
                 }
-                else if ( isEnabled )
+                else if ( isPgEnabled )
                 {
                     rowFgCol = m_colPropFore;
                 {
                     rowFgCol = m_colPropFore;
-                    rowBgCol = m_colMargin;
+                    if ( p == firstSelected )
+                        rowBgCol = m_colMargin;
+                    else
+                        rowBgCol = selBackCol;
                 }
                 else
                 {
                     rowFgCol = m_colDisPropFore;
                 }
                 else
                 {
                     rowFgCol = m_colDisPropFore;
-                    rowBgCol = m_colSelBack;
+                    rowBgCol = selBackCol;
                 }
             }
         }
                 }
             }
         }
@@ -1931,7 +2280,8 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
 
             unsigned int ci;
             int cellX = x + 1;
 
             unsigned int ci;
             int cellX = x + 1;
-            int nextCellWidth = state->m_colWidths[0];
+            int nextCellWidth = state->m_colWidths[0] -
+                                (greyDepthX - m_marginWidth);
             wxRect cellRect(greyDepthX+1, y, 0, rowHeight-1);
             int textXAdd = textMarginHere - greyDepthX;
 
             wxRect cellRect(greyDepthX+1, y, 0, rowHeight-1);
             int textXAdd = textMarginHere - greyDepthX;
 
@@ -1939,24 +2289,47 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
             {
                 cellRect.width = nextCellWidth - 1;
 
             {
                 cellRect.width = nextCellWidth - 1;
 
-                bool ctrlCell = false;
+                wxWindow* cellEditor = NULL;
                 int cellRenderFlags = renderFlags;
 
                 int cellRenderFlags = renderFlags;
 
-                // Tree Item Button
+                // Tree Item Button (must be drawn before clipping is set up)
                 if ( ci == 0 && !HasFlag(wxPG_HIDE_MARGIN) && p->HasVisibleChildren() )
                     DrawExpanderButton( dc, butRect, p );
 
                 // Background
                 if ( ci == 0 && !HasFlag(wxPG_HIDE_MARGIN) && p->HasVisibleChildren() )
                     DrawExpanderButton( dc, butRect, p );
 
                 // Background
-                if ( p == selected && m_wndEditor && ci == 1 )
+                if ( isSelected && (ci == 1 || ci == m_selColumn) )
                 {
                 {
-                    wxColour editorBgCol = GetEditorControl()->GetBackgroundColour();
-                    dc.SetBrush(editorBgCol);
-                    dc.SetPen(editorBgCol);
-                    dc.SetTextForeground(m_colPropFore);
-                    dc.DrawRectangle(cellRect);
-
-                    if ( m_dragStatus == 0 && !(m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE) )
-                        ctrlCell = true;
+                    if ( p == firstSelected )
+                    {
+                        if ( ci == 1 && m_wndEditor )
+                            cellEditor = m_wndEditor;
+                        else if ( ci == m_selColumn && m_labelEditor )
+                            cellEditor = m_labelEditor;
+                    }
+
+                    if ( cellEditor )
+                    {
+                        wxColour editorBgCol =
+                            cellEditor->GetBackgroundColour();
+                        dc.SetBrush(editorBgCol);
+                        dc.SetPen(editorBgCol);
+                        dc.SetTextForeground(m_colPropFore);
+                        dc.DrawRectangle(cellRect);
+
+                        if ( m_dragStatus != 0 ||
+                             (m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE) )
+                            cellEditor = NULL;
+                    }
+                    else
+                    {
+                        dc.SetBrush(m_colPropBack);
+                        dc.SetPen(m_colPropBack);
+                        dc.SetTextForeground(m_colDisPropFore);
+                        if ( p->IsEnabled() )
+                            dc.SetTextForeground(rowFgCol);
+                        else
+                            dc.SetTextForeground(m_colDisPropFore);
+                    }
                 }
                 else
                 {
                 }
                 else
                 {
@@ -1978,7 +2351,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
                 cellRect.width -= textXAdd;
 
                 // Foreground
                 cellRect.width -= textXAdd;
 
                 // Foreground
-                if ( !ctrlCell )
+                if ( !cellEditor )
                 {
                     wxPGCellRenderer* renderer;
                     int cmnVal = p->GetCommonValue();
                 {
                     wxPGCellRenderer* renderer;
                     int cmnVal = p->GetCommonValue();
@@ -2006,7 +2379,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
         }
 
         if ( fontChanged )
         }
 
         if ( fontChanged )
-            dc.SetFont(normalfont);
+            dc.SetFont(normalFont);
 
         y += rowHeight;
     }
 
         y += rowHeight;
     }
@@ -2023,7 +2396,7 @@ int wxPropertyGrid::DoDrawItems( wxDC& dc,
     }
 #endif
 
     }
 #endif
 
-    return y + yRelMod;
+    return y;
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -2034,7 +2407,7 @@ wxRect wxPropertyGrid::GetPropertyRect( const wxPGProperty* p1, const wxPGProper
 
     if ( m_width < 10 || m_height < 10 ||
          !m_pState->m_properties->GetChildCount() ||
 
     if ( m_width < 10 || m_height < 10 ||
          !m_pState->m_properties->GetChildCount() ||
-         p1 == (wxPGProperty*) NULL )
+         p1 == NULL )
         return wxRect(0,0,0,0);
 
     int vy = 0;
         return wxRect(0,0,0,0);
 
     int vy = 0;
@@ -2051,7 +2424,7 @@ wxRect wxPropertyGrid::GetPropertyRect( const wxPGProperty* p1, const wxPGProper
 
     // If seleced property is inside the range, we'll extend the range to include
     // control's size.
 
     // If seleced property is inside the range, we'll extend the range to include
     // control's size.
-    wxPGProperty* selected = m_selected;
+    wxPGProperty* selected = GetSelection();
     if ( selected )
     {
         int selectedY = selected->GetY();
     if ( selected )
     {
         int selectedY = selected->GetY();
@@ -2083,7 +2456,7 @@ void wxPropertyGrid::DrawItems( const wxPGProperty* p1, const wxPGProperty* p2 )
     wxRect r = GetPropertyRect(p1, p2);
     if ( r.width > 0 )
     {
     wxRect r = GetPropertyRect(p1, p2);
     if ( r.width > 0 )
     {
-        m_canvas->RefreshRect(r);
+        RefreshRect(r);
     }
 }
 
     }
 }
 
@@ -2091,8 +2464,12 @@ void wxPropertyGrid::DrawItems( const wxPGProperty* p1, const wxPGProperty* p2 )
 
 void wxPropertyGrid::RefreshProperty( wxPGProperty* p )
 {
 
 void wxPropertyGrid::RefreshProperty( wxPGProperty* p )
 {
-    if ( p == m_selected )
-        DoSelectProperty(p, wxPG_SEL_FORCE);
+    if ( m_pState->DoIsPropertySelected(p) )
+    {
+        // NB: We must copy the selection.
+        wxArrayPGProperty selection = m_pState->m_selection;
+        DoSetSelection(selection, wxPG_SEL_FORCE);
+    }
 
     DrawItemAndChildren(p);
 }
 
     DrawItemAndChildren(p);
 }
@@ -2131,7 +2508,8 @@ void wxPropertyGrid::DrawItemAndChildren( wxPGProperty* p )
         return;
 
     // Update child control.
         return;
 
     // Update child control.
-    if ( m_selected && m_selected->GetParent() == p )
+    wxPGProperty* selected = GetSelection();
+    if ( selected && selected->GetParent() == p )
         RefreshEditor();
 
     const wxPGProperty* lastDrawn = p->GetLastVisibleSubItem();
         RefreshEditor();
 
     const wxPGProperty* lastDrawn = p->GetLastVisibleSubItem();
@@ -2146,10 +2524,7 @@ void wxPropertyGrid::Refresh( bool WXUNUSED(eraseBackground),
 {
     PrepareAfterItemsAdded();
 
 {
     PrepareAfterItemsAdded();
 
-    wxWindow::Refresh(false);
-    if ( m_canvas )
-        // TODO: Coordinate translation
-        m_canvas->Refresh(false, rect);
+    wxWindow::Refresh(false, rect);
 
 #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
     // I think this really helps only GTK+1.2
 
 #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
     // I think this really helps only GTK+1.2
@@ -2164,8 +2539,6 @@ void wxPropertyGrid::Refresh( bool WXUNUSED(eraseBackground),
 
 void wxPropertyGrid::Clear()
 {
 
 void wxPropertyGrid::Clear()
 {
-    ClearSelection(false);
-
     m_pState->DoClear();
 
     m_propHover = NULL;
     m_pState->DoClear();
 
     m_propHover = NULL;
@@ -2183,7 +2556,7 @@ void wxPropertyGrid::Clear()
 
 bool wxPropertyGrid::EnableCategories( bool enable )
 {
 
 bool wxPropertyGrid::EnableCategories( bool enable )
 {
-    ClearSelection(false);
+    DoClearSelection();
 
     if ( enable )
     {
 
     if ( enable )
     {
@@ -2233,11 +2606,13 @@ void wxPropertyGrid::SwitchState( wxPropertyGridPageState* pNewState )
     if ( pNewState == m_pState )
         return;
 
     if ( pNewState == m_pState )
         return;
 
-    wxPGProperty* oldSelection = m_selected;
+    wxArrayPGProperty oldSelection = m_pState->m_selection;
 
 
-    ClearSelection(false);
+    // Call ClearSelection() instead of DoClearSelection()
+    // so that selection clear events are not sent.
+    ClearSelection();
 
 
-    m_pState->m_selected = oldSelection;
+    m_pState->m_selection = oldSelection;
 
     bool orig_mode = m_pState->IsInNonCatMode();
     bool new_state_mode = pNewState->IsInNonCatMode();
 
     bool orig_mode = m_pState->IsInNonCatMode();
     bool new_state_mode = pNewState->IsInNonCatMode();
@@ -2259,13 +2634,14 @@ void wxPropertyGrid::SwitchState( wxPropertyGridPageState* pNewState )
     {
         //
         // Just in case, fully re-center splitter
     {
         //
         // Just in case, fully re-center splitter
-        if ( HasFlag( wxPG_SPLITTER_AUTO_CENTER ) )
-            pNewState->m_fSplitterX = -1.0;
+        //if ( HasFlag( wxPG_SPLITTER_AUTO_CENTER ) )
+        //    pNewState->m_fSplitterX = -1.0;
 
 
-        pNewState->OnClientWidthChange( pgWidth, pgWidth - pNewState->m_width );
+        pNewState->OnClientWidthChange(pgWidth,
+                                       pgWidth - pNewState->m_width);
     }
 
     }
 
-    m_propHover = (wxPGProperty*) NULL;
+    m_propHover = NULL;
 
     // If necessary, convert state to correct mode.
     if ( orig_mode != new_state_mode )
 
     // If necessary, convert state to correct mode.
     if ( orig_mode != new_state_mode )
@@ -2276,12 +2652,11 @@ void wxPropertyGrid::SwitchState( wxPropertyGridPageState* pNewState )
     else if ( !m_frozen )
     {
         // Refresh, if not frozen.
     else if ( !m_frozen )
     {
         // Refresh, if not frozen.
-        if ( m_pState->m_itemsAdded )
-            PrepareAfterItemsAdded();
+        m_pState->PrepareAfterItemsAdded();
 
 
-        // Reselect
-        if ( m_pState->m_selected )
-            DoSelectProperty( m_pState->m_selected );
+        // Reselect (Use SetSelection() instead of Do-variant so that
+        // events won't be sent).
+        SetSelection(m_pState->m_selection);
 
         RecalculateVirtualSize(0);
         Refresh();
 
         RecalculateVirtualSize(0);
         Refresh();
@@ -2292,27 +2667,11 @@ void wxPropertyGrid::SwitchState( wxPropertyGridPageState* pNewState )
 
 // -----------------------------------------------------------------------
 
 
 // -----------------------------------------------------------------------
 
-void wxPropertyGrid::SortChildren( wxPGPropArg id )
-{
-    wxPG_PROP_ARG_CALL_PROLOG()
-
-    m_pState->SortChildren( p );
-}
-
-// -----------------------------------------------------------------------
-
-void wxPropertyGrid::Sort()
-{
-    ClearSelection(false);  // This must be before state clear
-
-    m_pState->Sort();
-}
-
-// -----------------------------------------------------------------------
-
 // Call to SetSplitterPosition will always disable splitter auto-centering
 // if parent window is shown.
 // Call to SetSplitterPosition will always disable splitter auto-centering
 // if parent window is shown.
-void wxPropertyGrid::DoSetSplitterPosition_( int newxpos, bool refresh, int splitterIndex, bool allPages )
+void wxPropertyGrid::DoSetSplitterPosition_( int newxpos, bool refresh,
+                                             int splitterIndex,
+                                             bool allPages )
 {
     if ( ( newxpos < wxPG_DRAG_MARGIN ) )
         return;
 {
     if ( ( newxpos < wxPG_DRAG_MARGIN ) )
         return;
@@ -2323,7 +2682,7 @@ void wxPropertyGrid::DoSetSplitterPosition_( int newxpos, bool refresh, int spli
 
     if ( refresh )
     {
 
     if ( refresh )
     {
-        if ( m_selected )
+        if ( GetSelection() )
             CorrectEditorWidgetSizeX();
 
         Refresh();
             CorrectEditorWidgetSizeX();
 
         Refresh();
@@ -2334,9 +2693,9 @@ void wxPropertyGrid::DoSetSplitterPosition_( int newxpos, bool refresh, int spli
 
 void wxPropertyGrid::CenterSplitter( bool enableAutoCentering )
 {
 
 void wxPropertyGrid::CenterSplitter( bool enableAutoCentering )
 {
-    SetSplitterPosition( m_width/2, true );
-    if ( enableAutoCentering && ( m_windowStyle & wxPG_SPLITTER_AUTO_CENTER ) )
-        m_iFlags &= ~(wxPG_FL_DONT_CENTER_SPLITTER);
+    SetSplitterPosition( m_width/2 );
+    if ( enableAutoCentering && HasFlag(wxPG_SPLITTER_AUTO_CENTER) )
+        m_pState->m_dontCenterSplitter = false;
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -2394,14 +2753,16 @@ bool wxPropertyGrid::CommitChangesFromEditor( wxUint32 flags )
         return false;
     }
 
         return false;
     }
 
+    wxPGProperty* selected = GetSelection();
+
     if ( m_wndEditor &&
          IsEditorsValueModified() &&
          (m_iFlags & wxPG_FL_INITIALIZED) &&
     if ( m_wndEditor &&
          IsEditorsValueModified() &&
          (m_iFlags & wxPG_FL_INITIALIZED) &&
-         m_selected )
+         selected )
     {
         m_inCommitChangesFromEditor = 1;
 
     {
         m_inCommitChangesFromEditor = 1;
 
-        wxVariant variant(m_selected->GetValueRef());
+        wxVariant variant(selected->GetValueRef());
         bool valueIsPending = false;
 
         // JACS - necessary to avoid new focus being found spuriously within OnIdle
         bool valueIsPending = false;
 
         // JACS - necessary to avoid new focus being found spuriously within OnIdle
@@ -2414,10 +2775,13 @@ bool wxPropertyGrid::CommitChangesFromEditor( wxUint32 flags )
         m_chgInfo_changedProperty = NULL;
 
         // If truly modified, schedule value as pending.
         m_chgInfo_changedProperty = NULL;
 
         // If truly modified, schedule value as pending.
-        if ( m_selected->GetEditorClass()->GetValueFromControl( variant, m_selected, GetEditorControl() ) )
+        if ( selected->GetEditorClass()->
+                GetValueFromControl( variant,
+                                     selected,
+                                     GetEditorControl() ) )
         {
             if ( DoEditorValidate() &&
         {
             if ( DoEditorValidate() &&
-                 PerformValidation(m_selected, variant) )
+                 PerformValidation(selected, variant) )
             {
                 valueIsPending = true;
             }
             {
                 valueIsPending = true;
             }
@@ -2443,18 +2807,18 @@ bool wxPropertyGrid::CommitChangesFromEditor( wxUint32 flags )
                 m_curFocused = oldFocus;
             }
 
                 m_curFocused = oldFocus;
             }
 
-            res = OnValidationFailure(m_selected, variant);
+            res = OnValidationFailure(selected, variant);
 
             // Now prevent further validation failure messages
             if ( res )
             {
                 EditorsValueWasNotModified();
 
             // Now prevent further validation failure messages
             if ( res )
             {
                 EditorsValueWasNotModified();
-                OnValidationFailureReset(m_selected);
+                OnValidationFailureReset(selected);
             }
         }
         else if ( valueIsPending )
         {
             }
         }
         else if ( valueIsPending )
         {
-            DoPropertyChanged( m_selected, flags );
+            DoPropertyChanged( selected, flags );
             EditorsValueWasNotModified();
         }
 
             EditorsValueWasNotModified();
         }
 
@@ -2476,7 +2840,10 @@ bool wxPropertyGrid::PerformValidation( wxPGProperty* p, wxVariant& pendingValue
 
     m_validationInfo.m_failureBehavior = m_permanentValidationFailureBehavior;
 
 
     m_validationInfo.m_failureBehavior = m_permanentValidationFailureBehavior;
 
-    if ( pendingValue.GetType() == wxPG_VARIANT_TYPE_LIST )
+    //
+    // Variant list a special value that cannot be validated
+    // by normal means.
+    if ( pendingValue.GetType() != wxPG_VARIANT_TYPE_LIST )
     {
         if ( !p->ValidateValue(pendingValue, m_validationInfo) )
             return false;
     {
         if ( !p->ValidateValue(pendingValue, m_validationInfo) )
             return false;
@@ -2557,7 +2924,7 @@ bool wxPropertyGrid::PerformValidation( wxPGProperty* p, wxVariant& pendingValue
 
         if ( evtChangingProperty->HasFlag(wxPG_PROP_COMPOSED_VALUE) )
         {
 
         if ( evtChangingProperty->HasFlag(wxPG_PROP_COMPOSED_VALUE) )
         {
-            if ( changedProperty == m_selected )
+            if ( changedProperty == GetSelection() )
             {
                 wxWindow* editor = GetEditorControl();
                 wxASSERT( editor->IsKindOf(CLASSINFO(wxTextCtrl)) );
             {
                 wxWindow* editor = GetEditorControl();
                 wxASSERT( editor->IsKindOf(CLASSINFO(wxTextCtrl)) );
@@ -2591,7 +2958,8 @@ bool wxPropertyGrid::PerformValidation( wxPGProperty* p, wxVariant& pendingValue
     if ( flags & SendEvtChanging )
     {
         // SendEvent returns true if event was vetoed
     if ( flags & SendEvtChanging )
     {
         // SendEvent returns true if event was vetoed
-        if ( SendEvent( wxEVT_PG_CHANGING, evtChangingProperty, &evtChangingValue, 0 ) )
+        if ( SendEvent( wxEVT_PG_CHANGING, evtChangingProperty,
+                        &evtChangingValue ) )
             return false;
     }
 
             return false;
     }
 
@@ -2633,11 +3001,34 @@ void wxPropertyGrid::DoShowPropertyError( wxPGProperty* WXUNUSED(property), cons
     }
 #endif
 
     }
 #endif
 
-    ::wxMessageBox(msg, _T("Property Error"));
+    ::wxMessageBox(msg, wxT("Property Error"));
 }
 
 // -----------------------------------------------------------------------
 
 }
 
 // -----------------------------------------------------------------------
 
+bool wxPropertyGrid::OnValidationFailure( wxPGProperty* property,
+                                          wxVariant& invalidValue )
+{
+    wxWindow* editor = GetEditorControl();
+
+    // First call property's handler
+    property->OnValidationFailure(invalidValue);
+
+    bool res = DoOnValidationFailure(property, invalidValue);
+
+    //
+    // For non-wxTextCtrl editors, we do need to revert the value
+    if ( !editor->IsKindOf(CLASSINFO(wxTextCtrl)) &&
+         property == GetSelection() )
+    {
+        property->GetEditorClass()->UpdateControl(property, editor);
+    }
+
+    property->SetFlag(wxPG_PROP_INVALID_VALUE);
+
+    return res;
+}
+
 bool wxPropertyGrid::DoOnValidationFailure( wxPGProperty* property, wxVariant& WXUNUSED(invalidValue) )
 {
     int vfb = m_validationInfo.m_failureBehavior;
 bool wxPropertyGrid::DoOnValidationFailure( wxPGProperty* property, wxVariant& WXUNUSED(invalidValue) )
 {
     int vfb = m_validationInfo.m_failureBehavior;
@@ -2667,7 +3058,7 @@ bool wxPropertyGrid::DoOnValidationFailure( wxPGProperty* property, wxVariant& W
 
         DrawItemAndChildren(property);
 
 
         DrawItemAndChildren(property);
 
-        if ( property == m_selected )
+        if ( property == GetSelection() )
         {
             SetInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
 
         {
             SetInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
 
@@ -2685,7 +3076,7 @@ bool wxPropertyGrid::DoOnValidationFailure( wxPGProperty* property, wxVariant& W
         wxString msg = m_validationInfo.m_failureMessage;
 
         if ( !msg.length() )
         wxString msg = m_validationInfo.m_failureMessage;
 
         if ( !msg.length() )
-            msg = _T("You have entered invalid value. Press ESC to cancel editing.");
+            msg = wxT("You have entered invalid value. Press ESC to cancel editing.");
 
         DoShowPropertyError(property, msg);
     }
 
         DoShowPropertyError(property, msg);
     }
@@ -2706,7 +3097,7 @@ void wxPropertyGrid::DoOnValidationFailureReset( wxPGProperty* property )
 
         ClearInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
 
 
         ClearInternalFlag(wxPG_FL_CELL_OVERRIDES_SEL);
 
-        if ( property == m_selected && GetEditorControl() )
+        if ( property == GetSelection() && GetEditorControl() )
         {
             // Calling this will recreate the control, thus resetting its colour
             RefreshProperty(property);
         {
             // Calling this will recreate the control, thus resetting its colour
             RefreshProperty(property);
@@ -2727,6 +3118,7 @@ bool wxPropertyGrid::DoPropertyChanged( wxPGProperty* p, unsigned int selFlags )
         return true;
 
     wxWindow* editor = GetEditorControl();
         return true;
 
     wxWindow* editor = GetEditorControl();
+    wxPGProperty* selected = GetSelection();
 
     m_pState->m_anyModified = 1;
 
 
     m_pState->m_anyModified = 1;
 
@@ -2753,7 +3145,7 @@ bool wxPropertyGrid::DoPropertyChanged( wxPGProperty* p, unsigned int selFlags )
     if ( !(p->m_flags & wxPG_PROP_MODIFIED) )
     {
         p->m_flags |= wxPG_PROP_MODIFIED;
     if ( !(p->m_flags & wxPG_PROP_MODIFIED) )
     {
         p->m_flags |= wxPG_PROP_MODIFIED;
-        if ( p == m_selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
+        if ( p == selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
         {
             if ( editor )
                 SetCurControlBoldFont();
         {
             if ( editor )
                 SetCurControlBoldFont();
@@ -2770,7 +3162,7 @@ bool wxPropertyGrid::DoPropertyChanged( wxPGProperty* p, unsigned int selFlags )
     {
         pwc->m_flags |= wxPG_PROP_MODIFIED;
 
     {
         pwc->m_flags |= wxPG_PROP_MODIFIED;
 
-        if ( pwc == m_selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
+        if ( pwc == selected && (m_windowStyle & wxPG_BOLD_MODIFIED) )
         {
             if ( editor )
                 SetCurControlBoldFont();
         {
             if ( editor )
                 SetCurControlBoldFont();
@@ -2809,12 +3201,12 @@ bool wxPropertyGrid::DoPropertyChanged( wxPGProperty* p, unsigned int selFlags )
 
         while ( pwc != changedProperty )
         {
 
         while ( pwc != changedProperty )
         {
-            SendEvent( wxEVT_PG_CHANGED, pwc, NULL, selFlags );
+            SendEvent( wxEVT_PG_CHANGED, pwc, NULL );
             pwc = pwc->GetParent();
         }
     }
 
             pwc = pwc->GetParent();
         }
     }
 
-    SendEvent( wxEVT_PG_CHANGED, changedProperty, NULL, selFlags );
+    SendEvent( wxEVT_PG_CHANGED, changedProperty, NULL );
 
     m_inDoPropertyChanged = 0;
 
 
     m_inDoPropertyChanged = 0;
 
@@ -2878,11 +3270,16 @@ bool wxPropertyGrid::DoEditorValidate()
 
 void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
 {
 
 void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
 {
-    wxPGProperty* selected = m_selected;
+    wxPGProperty* selected = GetSelection();
 
     // Somehow, event is handled after property has been deselected.
     // Possibly, but very rare.
 
     // Somehow, event is handled after property has been deselected.
     // Possibly, but very rare.
-    if ( !selected )
+    if ( !selected ||
+          selected->HasFlag(wxPG_PROP_BEING_DELETED) ||
+          // Also don't handle editor event if wxEVT_PG_CHANGED or
+          // similar is currently doing something (showing a
+          // message box, for instance).
+          m_processedEvent )
         return;
 
     if ( m_iFlags & wxPG_FL_IN_HANDLECUSTOMEDITOREVENT )
         return;
 
     if ( m_iFlags & wxPG_FL_IN_HANDLECUSTOMEDITOREVENT )
@@ -2890,10 +3287,10 @@ void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
 
     wxVariant pendingValue(selected->GetValueRef());
     wxWindow* wnd = GetEditorControl();
 
     wxVariant pendingValue(selected->GetValueRef());
     wxWindow* wnd = GetEditorControl();
+    wxWindow* editorWnd = wxDynamicCast(event.GetEventObject(), wxWindow);
     int selFlags = 0;
     bool wasUnspecified = selected->IsValueUnspecified();
     int usesAutoUnspecified = selected->UsesAutoUnspecified();
     int selFlags = 0;
     bool wasUnspecified = selected->IsValueUnspecified();
     int usesAutoUnspecified = selected->UsesAutoUnspecified();
-
     bool valueIsPending = false;
 
     m_chgInfo_changedProperty = NULL;
     bool valueIsPending = false;
 
     m_chgInfo_changedProperty = NULL;
@@ -2939,17 +3336,19 @@ void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
 
     if ( !buttonWasHandled )
     {
 
     if ( !buttonWasHandled )
     {
-        if ( wnd )
+        if ( wnd || m_wndEditor2 )
         {
             // First call editor class' event handler.
             const wxPGEditor* editor = selected->GetEditorClass();
 
         {
             // First call editor class' event handler.
             const wxPGEditor* editor = selected->GetEditorClass();
 
-            if ( editor->OnEvent( this, selected, wnd, event ) )
+            if ( editor->OnEvent( this, selected, editorWnd, event ) )
             {
                 // If changes, validate them
                 if ( DoEditorValidate() )
                 {
             {
                 // If changes, validate them
                 if ( DoEditorValidate() )
                 {
-                    if ( editor->GetValueFromControl( pendingValue, m_selected, wnd ) )
+                    if ( editor->GetValueFromControl( pendingValue,
+                                                      selected,
+                                                      wnd ) )
                         valueIsPending = true;
                 }
                 else
                         valueIsPending = true;
                 }
                 else
@@ -2962,7 +3361,7 @@ void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
         // Then the property's custom handler (must be always called, unless
         // validation failed).
         if ( !validationFailure )
         // Then the property's custom handler (must be always called, unless
         // validation failed).
         if ( !validationFailure )
-            buttonWasHandled = selected->OnEvent( this, wnd, event );
+            buttonWasHandled = selected->OnEvent( this, editorWnd, event );
     }
 
     // SetValueInEvent(), as called in one of the functions referred above
     }
 
     // SetValueInEvent(), as called in one of the functions referred above
@@ -2975,7 +3374,7 @@ void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
     }
 
     if ( !validationFailure && valueIsPending )
     }
 
     if ( !validationFailure && valueIsPending )
-        if ( !PerformValidation(m_selected, pendingValue) )
+        if ( !PerformValidation(selected, pendingValue) )
             validationFailure = true;
 
     if ( validationFailure)
             validationFailure = true;
 
     if ( validationFailure)
@@ -3025,25 +3424,29 @@ void wxPropertyGrid::HandleCustomEditorEvent( wxEvent &event )
 wxRect wxPropertyGrid::GetEditorWidgetRect( wxPGProperty* p, int column ) const
 {
     int itemy = p->GetY2(m_lineHeight);
 wxRect wxPropertyGrid::GetEditorWidgetRect( wxPGProperty* p, int column ) const
 {
     int itemy = p->GetY2(m_lineHeight);
-    int vy = 0;
-    int cust_img_space = 0;
     int splitterX = m_pState->DoGetSplitterPosition(column-1);
     int colEnd = splitterX + m_pState->m_colWidths[column];
     int splitterX = m_pState->DoGetSplitterPosition(column-1);
     int colEnd = splitterX + m_pState->m_colWidths[column];
+    int imageOffset = 0;
+
+    int vx, vy;  // Top left corner of client
+    GetViewStart(&vx, &vy);
+    vy *= wxPG_PIXELS_PER_UNIT;
 
     // TODO: If custom image detection changes from current, change this.
 
     // TODO: If custom image detection changes from current, change this.
-    if ( m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE /*p->m_flags & wxPG_PROP_CUSTOMIMAGE*/ )
+    if ( m_iFlags & wxPG_FL_CUR_USES_CUSTOM_IMAGE )
     {
         //m_iFlags |= wxPG_FL_CUR_USES_CUSTOM_IMAGE;
     {
         //m_iFlags |= wxPG_FL_CUR_USES_CUSTOM_IMAGE;
-        int imwid = p->OnMeasureImage().x;
-        if ( imwid < 1 ) imwid = wxPG_CUSTOM_IMAGE_WIDTH;
-        cust_img_space = imwid + wxCC_CUSTOM_IMAGE_MARGIN1 + wxCC_CUSTOM_IMAGE_MARGIN2;
+        int iw = p->OnMeasureImage().x;
+        if ( iw < 1 )
+            iw = wxPG_CUSTOM_IMAGE_WIDTH;
+        imageOffset = p->GetImageOffset(iw);
     }
 
     return wxRect
       (
     }
 
     return wxRect
       (
-        splitterX+cust_img_space+wxPG_XBEFOREWIDGET+wxPG_CONTROL_MARGIN+1,
+        splitterX+imageOffset+wxPG_XBEFOREWIDGET+wxPG_CONTROL_MARGIN+1,
         itemy-vy,
         itemy-vy,
-        colEnd-splitterX-wxPG_XBEFOREWIDGET-wxPG_CONTROL_MARGIN-cust_img_space-1,
+        colEnd-splitterX-wxPG_XBEFOREWIDGET-wxPG_CONTROL_MARGIN-imageOffset-1,
         m_lineHeight-1
       );
 }
         m_lineHeight-1
       );
 }
@@ -3134,7 +3537,7 @@ void wxPropertyGrid::CustomSetCursor( int type, bool override )
     if ( type == wxCURSOR_SIZEWE )
         cursor = m_cursorSizeWE;
 
     if ( type == wxCURSOR_SIZEWE )
         cursor = m_cursorSizeWE;
 
-    m_canvas->SetCursor( *cursor );
+    SetCursor( *cursor );
 
     m_curcursor = type;
 }
 
     m_curcursor = type;
 }
@@ -3207,6 +3610,17 @@ void wxPropertyGrid::SetupChildEventHandling( wxWindow* argWnd )
         NULL, this);
 }
 
         NULL, this);
 }
 
+void wxPropertyGrid::DestroyEditorWnd( wxWindow* wnd )
+{
+    if ( !wnd )
+        return;
+
+    wnd->Hide();
+
+    // Do not free editors immediately (for sake of processing events)
+    wxPendingDelete.Append(wnd);
+}
+
 void wxPropertyGrid::FreeEditors()
 {
     //
 void wxPropertyGrid::FreeEditors()
 {
     //
@@ -3219,7 +3633,7 @@ void wxPropertyGrid::FreeEditors()
         wxWindow* parent = focus->GetParent();
         while ( parent )
         {
         wxWindow* parent = focus->GetParent();
         while ( parent )
         {
-            if ( parent == m_canvas )
+            if ( parent == this )
             {
                 SetFocusOnCanvas();
                 break;
             {
                 SetFocusOnCanvas();
                 break;
@@ -3231,18 +3645,20 @@ void wxPropertyGrid::FreeEditors()
     // Do not free editors immediately if processing events
     if ( m_wndEditor2 )
     {
     // Do not free editors immediately if processing events
     if ( m_wndEditor2 )
     {
-        m_wndEditor2->PopEventHandler(true);
+        wxEvtHandler* handler = m_wndEditor2->PopEventHandler(false);
         m_wndEditor2->Hide();
         m_wndEditor2->Hide();
-        wxPendingDelete.Append( m_wndEditor2 );
-        m_wndEditor2 = (wxWindow*) NULL;
+        wxPendingDelete.Append( handler );
+        DestroyEditorWnd(m_wndEditor2);
+        m_wndEditor2 = NULL;
     }
 
     if ( m_wndEditor )
     {
     }
 
     if ( m_wndEditor )
     {
-        m_wndEditor->PopEventHandler(true);
+        wxEvtHandler* handler = m_wndEditor->PopEventHandler(false);
         m_wndEditor->Hide();
         m_wndEditor->Hide();
-        wxPendingDelete.Append( m_wndEditor );
-        m_wndEditor = (wxWindow*) NULL;
+        wxPendingDelete.Append( handler );
+        DestroyEditorWnd(m_wndEditor);
+        m_wndEditor = NULL;
     }
 }
 
     }
 }
 
@@ -3251,10 +3667,14 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 {
     /*
     if (p)
 {
     /*
     if (p)
+    {
         wxLogDebug(wxT("SelectProperty( %s (%s[%i]) )"),p->m_label.c_str(),
             p->m_parent->m_label.c_str(),p->GetIndexInParent());
         wxLogDebug(wxT("SelectProperty( %s (%s[%i]) )"),p->m_label.c_str(),
             p->m_parent->m_label.c_str(),p->GetIndexInParent());
+    }
     else
     else
+    {
         wxLogDebug(wxT("SelectProperty( NULL, -1 )"));
         wxLogDebug(wxT("SelectProperty( NULL, -1 )"));
+    }
     */
 
     if ( m_inDoSelectProperty )
     */
 
     if ( m_inDoSelectProperty )
@@ -3262,17 +3682,29 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
     m_inDoSelectProperty = 1;
 
 
     m_inDoSelectProperty = 1;
 
-    wxPGProperty* prev = m_selected;
-
     if ( !m_pState )
     {
         m_inDoSelectProperty = 0;
         return false;
     }
 
     if ( !m_pState )
     {
         m_inDoSelectProperty = 0;
         return false;
     }
 
+    wxArrayPGProperty prevSelection = m_pState->m_selection;
+    wxPGProperty* prevFirstSel;
+
+    if ( prevSelection.size() > 0 )
+        prevFirstSel = prevSelection[0];
+    else
+        prevFirstSel = NULL;
+
+    if ( prevFirstSel && prevFirstSel->HasFlag(wxPG_PROP_BEING_DELETED) )
+        prevFirstSel = NULL;
+
+    // Always send event, as this is indirect call
+    DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE);
+
 /*
 /*
-    if (m_selected)
-        wxPrintf( "Selected %s\n", m_selected->GetClassInfo()->GetClassName() );
+    if ( prevFirstSel )
+        wxPrintf( "Selected %s\n", prevFirstSel->GetClassInfo()->GetClassName() );
     else
         wxPrintf( "None selected\n" );
 
     else
         wxPrintf( "None selected\n" );
 
@@ -3287,21 +3719,21 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
     {
         m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
         m_editorFocused = 0;
     {
         m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
         m_editorFocused = 0;
-        m_selected = p;
-        m_selColumn = 1;
-        m_pState->m_selected = p;
+        m_pState->DoSetSelection(p);
 
         // If frozen, always free controls. But don't worry, as Thaw will
         // recall SelectProperty to recreate them.
         FreeEditors();
 
         // Prevent any further selection measures in this call
 
         // If frozen, always free controls. But don't worry, as Thaw will
         // recall SelectProperty to recreate them.
         FreeEditors();
 
         // Prevent any further selection measures in this call
-        p = (wxPGProperty*) NULL;
+        p = NULL;
     }
     else
     {
         // Is it the same?
     }
     else
     {
         // Is it the same?
-        if ( m_selected == p && !(flags & wxPG_SEL_FORCE) )
+        if ( prevFirstSel == p &&
+             prevSelection.size() <= 1 &&
+             !(flags & wxPG_SEL_FORCE) )
         {
             // Only set focus if not deselecting
             if ( p )
         {
             // Only set focus if not deselecting
             if ( p )
@@ -3326,13 +3758,12 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
         //
         // First, deactivate previous
 
         //
         // First, deactivate previous
-        if ( m_selected )
+        if ( prevFirstSel )
         {
         {
-
-            OnValidationFailureReset(m_selected);
+            OnValidationFailureReset(prevFirstSel);
 
             // Must double-check if this is an selected in case of forceswitch
 
             // Must double-check if this is an selected in case of forceswitch
-            if ( p != prev )
+            if ( p != prevFirstSel )
             {
                 if ( !CommitChangesFromEditor(flags) )
                 {
             {
                 if ( !CommitChangesFromEditor(flags) )
                 {
@@ -3345,13 +3776,6 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
             }
 
             FreeEditors();
             }
 
             FreeEditors();
-            m_selColumn = -1;
-
-            m_selected = (wxPGProperty*) NULL;
-            m_pState->m_selected = (wxPGProperty*) NULL;
-
-            // We need to always fully refresh the grid here
-            Refresh(false);
 
             m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
             EditorsValueWasNotModified();
 
             m_iFlags &= ~(wxPG_FL_ABNORMAL_EDITOR);
             EditorsValueWasNotModified();
@@ -3359,6 +3783,14 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
         SetInternalFlag(wxPG_FL_IN_SELECT_PROPERTY);
 
 
         SetInternalFlag(wxPG_FL_IN_SELECT_PROPERTY);
 
+        m_pState->DoSetSelection(p);
+
+        // Redraw unselected
+        for ( unsigned int i=0; i<prevSelection.size(); i++ )
+        {
+            DrawItem(prevSelection[i]);
+        }
+
         //
         // Then, activate the one given.
         if ( p )
         //
         // Then, activate the one given.
         if ( p )
@@ -3367,13 +3799,11 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
             int splitterX = GetSplitterPosition();
             m_editorFocused = 0;
 
             int splitterX = GetSplitterPosition();
             m_editorFocused = 0;
-            m_selected = p;
-            m_pState->m_selected = p;
             m_iFlags |= wxPG_FL_PRIMARY_FILLS_ENTIRE;
             m_iFlags |= wxPG_FL_PRIMARY_FILLS_ENTIRE;
-            if ( p != prev )
+            if ( p != prevFirstSel )
                 m_iFlags &= ~(wxPG_FL_VALIDATION_FAILED);
 
                 m_iFlags &= ~(wxPG_FL_VALIDATION_FAILED);
 
-            wxASSERT( m_wndEditor == (wxWindow*) NULL );
+            wxASSERT( m_wndEditor == NULL );
 
             //
             // Only create editor for non-disabled non-caption
 
             //
             // Only create editor for non-disabled non-caption
@@ -3392,10 +3822,6 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
                 wxRect grect = GetEditorWidgetRect(p, m_selColumn);
                 wxPoint goodPos = grect.GetPosition();
 
                 wxRect grect = GetEditorWidgetRect(p, m_selColumn);
                 wxPoint goodPos = grect.GetPosition();
-            #if wxPG_CREATE_CONTROLS_HIDDEN
-                int coord_adjust = m_height - goodPos.y;
-                goodPos.y += coord_adjust;
-            #endif
 
                 const wxPGEditor* editor = p->GetEditorClass();
                 wxCHECK_MSG(editor, false,
 
                 const wxPGEditor* editor = p->GetEditorClass();
                 wxCHECK_MSG(editor, false,
@@ -3403,10 +3829,11 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
                 m_iFlags &= ~wxPG_FL_FIXED_WIDTH_EDITOR;
 
 
                 m_iFlags &= ~wxPG_FL_FIXED_WIDTH_EDITOR;
 
-                wxPGWindowList wndList = editor->CreateControls(this,
-                                                                p,
-                                                                goodPos,
-                                                                grect.GetSize());
+                wxPGWindowList wndList =
+                    editor->CreateControls(this,
+                                           p,
+                                           goodPos,
+                                           grect.GetSize());
 
                 m_wndEditor = wndList.m_primary;
                 m_wndEditor2 = wndList.m_secondary;
 
                 m_wndEditor = wndList.m_primary;
                 m_wndEditor2 = wndList.m_secondary;
@@ -3416,15 +3843,17 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
                 // Essentially, primaryCtrl == m_wndEditor
                 //
 
                 // Essentially, primaryCtrl == m_wndEditor
                 //
 
-                // NOTE: It is allowed for m_wndEditor to be NULL - in this case
-                //       value is drawn as normal, and m_wndEditor2 is assumed
-                //       to be a right-aligned button that triggers a separate editorCtrl
-                //       window.
+                // NOTE: It is allowed for m_wndEditor to be NULL - in this
+                //       case value is drawn as normal, and m_wndEditor2 is
+                //       assumed to be a right-aligned button that triggers
+                //       a separate editorCtrl window.
 
                 if ( m_wndEditor )
                 {
                     wxASSERT_MSG( m_wndEditor->GetParent() == GetPanel(),
 
                 if ( m_wndEditor )
                 {
                     wxASSERT_MSG( m_wndEditor->GetParent() == GetPanel(),
-                                  wxT("CreateControls must use result of wxPropertyGrid::GetPanel() as parent of controls.") );
+                                  "CreateControls must use result of "
+                                  "wxPropertyGrid::GetPanel() as parent "
+                                  "of controls." );
 
                     // Set validator, if any
                 #if wxUSE_VALIDATORS
 
                     // Set validator, if any
                 #if wxUSE_VALIDATORS
@@ -3438,21 +3867,10 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
                     // If it has modified status, use bold font
                     // (must be done before capturing m_ctrlXAdjust)
 
                     // If it has modified status, use bold font
                     // (must be done before capturing m_ctrlXAdjust)
-                    if ( (p->m_flags & wxPG_PROP_MODIFIED) && (m_windowStyle & wxPG_BOLD_MODIFIED) )
+                    if ( (p->m_flags & wxPG_PROP_MODIFIED) &&
+                         (m_windowStyle & wxPG_BOLD_MODIFIED) )
                         SetCurControlBoldFont();
 
                         SetCurControlBoldFont();
 
-                    //
-                    // Fix TextCtrl indentation
-                #if defined(__WXMSW__) && !defined(__WXWINCE__)
-                    wxTextCtrl* tc = NULL;
-                    if ( primaryCtrl->IsKindOf(CLASSINFO(wxOwnerDrawnComboBox)) )
-                        tc = ((wxOwnerDrawnComboBox*)primaryCtrl)->GetTextCtrl();
-                    else
-                        tc = wxDynamicCast(primaryCtrl, wxTextCtrl);
-                    if ( tc )
-                        ::SendMessage(GetHwndOf(tc), EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELONG(0, 0));
-                #endif
-
                     // Store x relative to splitter (we'll need it).
                     m_ctrlXAdjust = m_wndEditor->GetPosition().x - splitterX;
 
                     // Store x relative to splitter (we'll need it).
                     m_ctrlXAdjust = m_wndEditor->GetPosition().x - splitterX;
 
@@ -3465,15 +3883,6 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
                     m_wndEditor->SetSizeHints(3, 3);
 
 
                     m_wndEditor->SetSizeHints(3, 3);
 
-                #if wxPG_CREATE_CONTROLS_HIDDEN
-                    m_wndEditor->Show(false);
-                    m_wndEditor->Freeze();
-
-                    goodPos = m_wndEditor->GetPosition();
-                    goodPos.y -= coord_adjust;
-                    m_wndEditor->Move( goodPos );
-                #endif
-
                     SetupChildEventHandling(primaryCtrl);
 
                     // Focus and select all (wxTextCtrl, wxComboBox etc)
                     SetupChildEventHandling(primaryCtrl);
 
                     // Focus and select all (wxTextCtrl, wxComboBox etc)
@@ -3488,7 +3897,9 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
                 if ( m_wndEditor2 )
                 {
                     wxASSERT_MSG( m_wndEditor2->GetParent() == GetPanel(),
                 if ( m_wndEditor2 )
                 {
                     wxASSERT_MSG( m_wndEditor2->GetParent() == GetPanel(),
-                                  wxT("CreateControls must use result of wxPropertyGrid::GetPanel() as parent of controls.") );
+                                  "CreateControls must use result of "
+                                  "wxPropertyGrid::GetPanel() as parent "
+                                  "of controls." );
 
                     // Get proper id for wndSecondary
                     m_wndSecId = m_wndEditor2->GetId();
 
                     // Get proper id for wndSecondary
                     m_wndSecId = m_wndEditor2->GetId();
@@ -3499,19 +3910,6 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
                     m_wndEditor2->SetSizeHints(3,3);
 
 
                     m_wndEditor2->SetSizeHints(3,3);
 
-                #if wxPG_CREATE_CONTROLS_HIDDEN
-                    wxRect sec_rect = m_wndEditor2->GetRect();
-                    sec_rect.y -= coord_adjust;
-
-                    // Fine tuning required to fix "oversized"
-                    // button disappearance bug.
-                    if ( sec_rect.y < 0 )
-                    {
-                        sec_rect.height += sec_rect.y;
-                        sec_rect.y = 0;
-                    }
-                    m_wndEditor2->SetSize( sec_rect );
-                #endif
                     m_wndEditor2->Show();
 
                     SetupChildEventHandling(m_wndEditor2);
                     m_wndEditor2->Show();
 
                     SetupChildEventHandling(m_wndEditor2);
@@ -3532,7 +3930,8 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
             }
             else
             {
             }
             else
             {
-                // Make sure focus is in grid canvas (important for wxGTK, at least)
+                // Make sure focus is in grid canvas (important for wxGTK,
+                // at least)
                 SetFocusOnCanvas();
             }
 
                 SetFocusOnCanvas();
             }
 
@@ -3545,13 +3944,11 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
             if ( m_wndEditor )
             {
 
             if ( m_wndEditor )
             {
-            #if wxPG_CREATE_CONTROLS_HIDDEN
-                m_wndEditor->Thaw();
-            #endif
                 m_wndEditor->Show(true);
             }
 
                 m_wndEditor->Show(true);
             }
 
-            DrawItems(p, p);
+            if ( !(flags & wxPG_SEL_NO_REFRESH) )
+                DrawItem(p);
         }
         else
         {
         }
         else
         {
@@ -3572,7 +3969,7 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
     if ( !(GetExtraStyle() & wxPG_EX_HELP_AS_TOOLTIPS) )
     {
 
     if ( !(GetExtraStyle() & wxPG_EX_HELP_AS_TOOLTIPS) )
     {
-        wxStatusBar* statusbar = (wxStatusBar*) NULL;
+        wxStatusBar* statusbar = NULL;
         if ( !(m_iFlags & wxPG_FL_NOSTATUSBARHELP) )
         {
             wxFrame* frame = wxDynamicCast(::wxGetTopLevelParent(this),wxFrame);
         if ( !(m_iFlags & wxPG_FL_NOSTATUSBARHELP) )
         {
             wxFrame* frame = wxDynamicCast(::wxGetTopLevelParent(this),wxFrame);
@@ -3610,7 +4007,8 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
     m_inDoSelectProperty = 0;
 
     // call wx event handler (here so that it also occurs on deselection)
     m_inDoSelectProperty = 0;
 
     // call wx event handler (here so that it also occurs on deselection)
-    SendEvent( wxEVT_PG_SELECTED, m_selected, NULL, flags );
+    if ( !(flags & wxPG_SEL_DONT_SEND_EVENT) )
+        SendEvent( wxEVT_PG_SELECTED, p, NULL );
 
     return true;
 }
 
     return true;
 }
@@ -3619,14 +4017,16 @@ bool wxPropertyGrid::DoSelectProperty( wxPGProperty* p, unsigned int flags )
 
 bool wxPropertyGrid::UnfocusEditor()
 {
 
 bool wxPropertyGrid::UnfocusEditor()
 {
-    if ( !m_selected || !m_wndEditor || m_frozen )
+    wxPGProperty* selected = GetSelection();
+
+    if ( !selected || !m_wndEditor || m_frozen )
         return true;
 
     if ( !CommitChangesFromEditor(0) )
         return false;
 
     SetFocusOnCanvas();
         return true;
 
     if ( !CommitChangesFromEditor(0) )
         return false;
 
     SetFocusOnCanvas();
-    DrawItem(m_selected);
+    DrawItem(selected);
 
     return true;
 }
 
     return true;
 }
@@ -3635,8 +4035,8 @@ bool wxPropertyGrid::UnfocusEditor()
 
 void wxPropertyGrid::RefreshEditor()
 {
 
 void wxPropertyGrid::RefreshEditor()
 {
-    wxPGProperty* p = m_selected;
-    if ( !p ) 
+    wxPGProperty* p = GetSelection();
+    if ( !p )
         return;
 
     wxWindow* wnd = GetEditorControl();
         return;
 
     wxWindow* wnd = GetEditorControl();
@@ -3653,16 +4053,25 @@ void wxPropertyGrid::RefreshEditor()
             wnd->SetFont(GetFont());
     }
 
             wnd->SetFont(GetFont());
     }
 
-    p->GetEditorClass()->UpdateControl(p, wnd);
+    const wxPGEditor* editorClass = p->GetEditorClass();
+
+    editorClass->UpdateControl(p, wnd);
+
+    if ( p->IsValueUnspecified() )
+        editorClass ->SetValueToUnspecified(p, wnd);
 }
 
 // -----------------------------------------------------------------------
 
 }
 
 // -----------------------------------------------------------------------
 
-// This method is not inline because it called dozens of times
-// (i.e. two-arg function calls create smaller code size).
-bool wxPropertyGrid::DoClearSelection()
+bool wxPropertyGrid::SelectProperty( wxPGPropArg id, bool focus )
 {
 {
-    return DoSelectProperty((wxPGProperty*)NULL);
+    wxPG_PROP_ARG_CALL_PROLOG_RETVAL(false)
+
+    int flags = wxPG_SEL_DONT_SEND_EVENT;
+    if ( focus )
+        flags |= wxPG_SEL_FOCUS;
+
+    return DoSelectProperty(p, flags);
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -3672,16 +4081,17 @@ bool wxPropertyGrid::DoClearSelection()
 bool wxPropertyGrid::DoCollapse( wxPGProperty* p, bool sendEvents )
 {
     wxPGProperty* pwc = wxStaticCast(p, wxPGProperty);
 bool wxPropertyGrid::DoCollapse( wxPGProperty* p, bool sendEvents )
 {
     wxPGProperty* pwc = wxStaticCast(p, wxPGProperty);
+    wxPGProperty* selected = GetSelection();
 
     // If active editor was inside collapsed section, then disable it
 
     // If active editor was inside collapsed section, then disable it
-    if ( m_selected && m_selected->IsSomeParent(p) )
+    if ( selected && selected->IsSomeParent(p) )
     {
     {
-        ClearSelection(false);
+        DoClearSelection();
     }
 
     // Store dont-center-splitter flag 'cause we need to temporarily set it
     }
 
     // Store dont-center-splitter flag 'cause we need to temporarily set it
-    wxUint32 old_flag = m_iFlags & wxPG_FL_DONT_CENTER_SPLITTER;
-    m_iFlags |= wxPG_FL_DONT_CENTER_SPLITTER;
+    bool prevDontCenterSplitter = m_pState->m_dontCenterSplitter;
+    m_pState->m_dontCenterSplitter = true;
 
     bool res = m_pState->DoCollapse(pwc);
 
 
     bool res = m_pState->DoCollapse(pwc);
 
@@ -3691,20 +4101,10 @@ bool wxPropertyGrid::DoCollapse( wxPGProperty* p, bool sendEvents )
             SendEvent( wxEVT_PG_ITEM_COLLAPSED, p );
 
         RecalculateVirtualSize();
             SendEvent( wxEVT_PG_ITEM_COLLAPSED, p );
 
         RecalculateVirtualSize();
-
-        // Redraw etc. only if collapsed was visible.
-        if (pwc->IsVisible() &&
-            !m_frozen &&
-            ( !pwc->IsCategory() || !(m_windowStyle & wxPG_HIDE_CATEGORIES) ) )
-        {
-            // When item is collapsed so that scrollbar would move,
-            // graphics mess is about (unless we redraw everything).
-            Refresh();
-        }
+        Refresh();
     }
 
     }
 
-    // Clear dont-center-splitter flag if it wasn't set
-    m_iFlags = (m_iFlags & ~wxPG_FL_DONT_CENTER_SPLITTER) | old_flag;
+    m_pState->m_dontCenterSplitter = prevDontCenterSplitter;
 
     return res;
 }
 
     return res;
 }
@@ -3718,8 +4118,8 @@ bool wxPropertyGrid::DoExpand( wxPGProperty* p, bool sendEvents )
     wxPGProperty* pwc = (wxPGProperty*)p;
 
     // Store dont-center-splitter flag 'cause we need to temporarily set it
     wxPGProperty* pwc = (wxPGProperty*)p;
 
     // Store dont-center-splitter flag 'cause we need to temporarily set it
-    wxUint32 old_flag = m_iFlags & wxPG_FL_DONT_CENTER_SPLITTER;
-    m_iFlags |= wxPG_FL_DONT_CENTER_SPLITTER;
+    bool prevDontCenterSplitter = m_pState->m_dontCenterSplitter;
+    m_pState->m_dontCenterSplitter = true;
 
     bool res = m_pState->DoExpand(pwc);
 
 
     bool res = m_pState->DoExpand(pwc);
 
@@ -3729,23 +4129,10 @@ bool wxPropertyGrid::DoExpand( wxPGProperty* p, bool sendEvents )
             SendEvent( wxEVT_PG_ITEM_EXPANDED, p );
 
         RecalculateVirtualSize();
             SendEvent( wxEVT_PG_ITEM_EXPANDED, p );
 
         RecalculateVirtualSize();
-
-        // Redraw etc. only if expanded was visible.
-        if ( pwc->IsVisible() && !m_frozen &&
-             ( !pwc->IsCategory() || !(m_windowStyle & wxPG_HIDE_CATEGORIES) )
-           )
-        {
-            // Redraw
-        #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
-            Refresh();
-        #else
-            DrawItems(pwc, NULL);
-        #endif
-        }
+        Refresh();
     }
 
     }
 
-    // Clear dont-center-splitter flag if it wasn't set
-    m_iFlags = (m_iFlags & ~wxPG_FL_DONT_CENTER_SPLITTER) | old_flag;
+    m_pState->m_dontCenterSplitter = prevDontCenterSplitter;
 
     return res;
 }
 
     return res;
 }
@@ -3757,12 +4144,18 @@ bool wxPropertyGrid::DoHideProperty( wxPGProperty* p, bool hide, int flags )
     if ( m_frozen )
         return m_pState->DoHideProperty(p, hide, flags);
 
     if ( m_frozen )
         return m_pState->DoHideProperty(p, hide, flags);
 
-    if ( m_selected &&
-         ( m_selected == p || m_selected->IsSomeParent(p) )
-       )
+    wxArrayPGProperty selection = m_pState->m_selection;  // Must use a copy
+    int selRemoveCount = 0;
+    for ( unsigned int i=0; i<selection.size(); i++ )
+    {
+        wxPGProperty* selected = selection[i];
+        if ( selected == p || selected->IsSomeParent(p) )
         {
         {
-            ClearSelection(false);
+            if ( !DoRemoveFromSelection(p, flags) )
+                return false;
+            selRemoveCount += 1;
         }
         }
+    }
 
     m_pState->DoHideProperty(p, hide, flags);
 
 
     m_pState->DoHideProperty(p, hide, flags);
 
@@ -3789,16 +4182,10 @@ void wxPropertyGrid::RecalculateVirtualSize( int forceXPos )
 
     m_pState->EnsureVirtualHeight();
 
 
     m_pState->EnsureVirtualHeight();
 
-#ifdef __WXDEBUG__
-    int by1 = m_pState->GetVirtualHeight();
-    int by2 = m_pState->GetActualVirtualHeight();
-    if ( by1 != by2 )
-    {
-        wxString s = wxString::Format(wxT("VirtualHeight=%i, ActualVirtualHeight=%i, should match!"), by1, by2);
-        wxFAIL_MSG(s.c_str());
-        wxLogDebug(s);
-    }
-#endif
+    wxASSERT_LEVEL_2_MSG(
+        m_pState->GetVirtualHeight() == m_pState->GetActualVirtualHeight(),
+        "VirtualHeight and ActualVirtualHeight should match"
+    );
 
     m_iFlags |= wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
 
 
     m_iFlags |= wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
 
@@ -3809,7 +4196,7 @@ void wxPropertyGrid::RecalculateVirtualSize( int forceXPos )
     GetClientSize(&width,&height);
 
     // Now adjust virtual size.
     GetClientSize(&width,&height);
 
     // Now adjust virtual size.
-       SetVirtualSize(x, y);
+    SetVirtualSize(x, y);
 
     int xAmount = 0;
     int xPos = 0;
 
     int xAmount = 0;
     int xPos = 0;
@@ -3828,7 +4215,7 @@ void wxPropertyGrid::RecalculateVirtualSize( int forceXPos )
     else if ( xPos > (xAmount-(width/wxPG_PIXELS_PER_UNIT)) )
         xPos = 0;
 
     else if ( xPos > (xAmount-(width/wxPG_PIXELS_PER_UNIT)) )
         xPos = 0;
 
-    int yAmount = (y+wxPG_PIXELS_PER_UNIT+2)/wxPG_PIXELS_PER_UNIT;
+    int yAmount = y / wxPG_PIXELS_PER_UNIT;
     int yPos = GetScrollPos( wxVERTICAL );
 
     SetScrollbars( wxPG_PIXELS_PER_UNIT, wxPG_PIXELS_PER_UNIT,
     int yPos = GetScrollPos( wxVERTICAL );
 
     SetScrollbars( wxPG_PIXELS_PER_UNIT, wxPG_PIXELS_PER_UNIT,
@@ -3846,11 +4233,9 @@ void wxPropertyGrid::RecalculateVirtualSize( int forceXPos )
     m_width = width;
     m_height = height;
 
     m_width = width;
     m_height = height;
 
-    m_canvas->SetSize( x, y );
-
     m_pState->CheckColumnWidths();
 
     m_pState->CheckColumnWidths();
 
-    if ( m_selected )
+    if ( GetSelection() )
         CorrectEditorWidgetSizeX();
 
     m_iFlags &= ~wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
         CorrectEditorWidgetSizeX();
 
     m_iFlags &= ~wxPG_FL_RECALCULATING_VIRTUAL_SIZE;
@@ -3864,7 +4249,7 @@ void wxPropertyGrid::OnResize( wxSizeEvent& event )
         return;
 
     int width, height;
         return;
 
     int width, height;
-    GetClientSize(&width,&height);
+    GetClientSize(&width, &height);
 
     m_width = width;
     m_height = height;
 
     m_width = width;
     m_height = height;
@@ -3934,7 +4319,7 @@ void wxPropertyGrid::SetVirtualWidth( int width )
 
 void wxPropertyGrid::SetFocusOnCanvas()
 {
 
 void wxPropertyGrid::SetFocusOnCanvas()
 {
-    m_canvas->SetFocusIgnoringChildren();
+    SetFocusIgnoringChildren();
     m_editorFocused = 0;
 }
 
     m_editorFocused = 0;
 }
 
@@ -3944,22 +4329,36 @@ void wxPropertyGrid::SetFocusOnCanvas()
 
 // selFlags uses same values DoSelectProperty's flags
 // Returns true if event was vetoed.
 
 // selFlags uses same values DoSelectProperty's flags
 // Returns true if event was vetoed.
-bool wxPropertyGrid::SendEvent( int eventType, wxPGProperty* p, wxVariant* pValue, unsigned int WXUNUSED(selFlags) )
+bool wxPropertyGrid::SendEvent( int eventType, wxPGProperty* p,
+                                wxVariant* pValue,
+                                unsigned int selFlags,
+                                unsigned int column )
 {
     // Send property grid event of specific type and with specific property
     wxPropertyGridEvent evt( eventType, m_eventObject->GetId() );
     evt.SetPropertyGrid(this);
     evt.SetEventObject(m_eventObject);
     evt.SetProperty(p);
 {
     // Send property grid event of specific type and with specific property
     wxPropertyGridEvent evt( eventType, m_eventObject->GetId() );
     evt.SetPropertyGrid(this);
     evt.SetEventObject(m_eventObject);
     evt.SetProperty(p);
-    if ( pValue )
+    evt.SetColumn(column);
+    if ( eventType == wxEVT_PG_CHANGING )
     {
     {
+        wxASSERT( pValue );
         evt.SetCanVeto(true);
         evt.SetCanVeto(true);
-        evt.SetupValidationInfo();
         m_validationInfo.m_pValue = pValue;
         m_validationInfo.m_pValue = pValue;
+        evt.SetupValidationInfo();
+    }
+    else
+    {
+        if ( p )
+            evt.SetPropertyValue(p->GetValue());
+
+        if ( !(selFlags & wxPG_SEL_NOVALIDATE) )
+            evt.SetCanVeto(true);
     }
     }
-    wxEvtHandler* evtHandler = m_eventObject->GetEventHandler();
 
 
-    evtHandler->ProcessEvent(evt);
+    m_processedEvent = &evt;
+    m_eventObject->HandleWindowEvent(evt);
+    m_processedEvent = NULL;
 
     return evt.WasVetoed();
 }
 
     return evt.WasVetoed();
 }
@@ -4009,7 +4408,9 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
                      )
                     )
                 {
                      )
                     )
                 {
-                    if ( !DoSelectProperty( p ) )
+                    if ( !AddToSelectionFromInputEvent( p,
+                                                        columnHit,
+                                                        &event ) )
                         return res;
 
                     // On double-click, expand/collapse.
                         return res;
 
                     // On double-click, expand/collapse.
@@ -4029,7 +4430,10 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
                     m_iFlags |= wxPG_FL_ACTIVATION_BY_CLICK;
                     selFlag = wxPG_SEL_FOCUS;
                 }
                     m_iFlags |= wxPG_FL_ACTIVATION_BY_CLICK;
                     selFlag = wxPG_SEL_FOCUS;
                 }
-                if ( !DoSelectProperty( p, selFlag ) )
+                if ( !AddToSelectionFromInputEvent( p,
+                                                    columnHit,
+                                                    &event,
+                                                    selFlag ) )
                     return res;
 
                 m_iFlags &= ~(wxPG_FL_ACTIVATION_BY_CLICK);
                     return res;
 
                 m_iFlags &= ~(wxPG_FL_ACTIVATION_BY_CLICK);
@@ -4057,9 +4461,13 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
                     }
                     else if ( m_dragStatus == 0 )
                     {
                     }
                     else if ( m_dragStatus == 0 )
                     {
-                    //
-                    // Begin draggin the splitter
-                    //
+                        //
+                        // Begin draggin the splitter
+                        //
+
+                        // send event
+                        DoEndLabelEdit(true, wxPG_SEL_NOVALIDATE);
+
                         if ( m_wndEditor )
                         {
                             // Changes must be committed here or the
                         if ( m_wndEditor )
                         {
                             // Changes must be committed here or the
@@ -4072,7 +4480,7 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
 
                         if ( !(m_iFlags & wxPG_FL_MOUSE_CAPTURED) )
                         {
 
                         if ( !(m_iFlags & wxPG_FL_MOUSE_CAPTURED) )
                         {
-                            m_canvas->CaptureMouse();
+                            CaptureMouse();
                             m_iFlags |= wxPG_FL_MOUSE_CAPTURED;
                         }
 
                             m_iFlags |= wxPG_FL_MOUSE_CAPTURED;
                         }
 
@@ -4080,8 +4488,6 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
                         m_draggedSplitter = splitterHit;
                         m_dragOffset = splitterHitOffset;
 
                         m_draggedSplitter = splitterHit;
                         m_dragOffset = splitterHitOffset;
 
-                        wxClientDC dc(m_canvas);
-
                     #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
                         // Fixes button disappearance bug
                         if ( m_wndEditor2 )
                     #if wxPG_REFRESH_CONTROLS_AFTER_REPAINT
                         // Fixes button disappearance bug
                         if ( m_wndEditor2 )
@@ -4120,15 +4526,15 @@ bool wxPropertyGrid::HandleMouseClick( int x, unsigned int y, wxMouseEvent &even
 
 // -----------------------------------------------------------------------
 
 
 // -----------------------------------------------------------------------
 
-bool wxPropertyGrid::HandleMouseRightClick( int WXUNUSED(x), unsigned int WXUNUSED(y),
-                                            wxMouseEvent& WXUNUSED(event) )
+bool wxPropertyGrid::HandleMouseRightClick( int WXUNUSED(x),
+                                            unsigned int WXUNUSED(y),
+                                            wxMouseEvent& event )
 {
     if ( m_propHover )
     {
         // Select property here as well
         wxPGProperty* p = m_propHover;
 {
     if ( m_propHover )
     {
         // Select property here as well
         wxPGProperty* p = m_propHover;
-        if ( p != m_selected )
-            DoSelectProperty( p );
+        AddToSelectionFromInputEvent(p, m_colHover, &event);
 
         // Send right click event.
         SendEvent( wxEVT_PG_RIGHT_CLICK, p );
 
         // Send right click event.
         SendEvent( wxEVT_PG_RIGHT_CLICK, p );
@@ -4140,16 +4546,16 @@ bool wxPropertyGrid::HandleMouseRightClick( int WXUNUSED(x), unsigned int WXUNUS
 
 // -----------------------------------------------------------------------
 
 
 // -----------------------------------------------------------------------
 
-bool wxPropertyGrid::HandleMouseDoubleClick( int WXUNUSED(x), unsigned int WXUNUSED(y),
-                                             wxMouseEvent& WXUNUSED(event) )
+bool wxPropertyGrid::HandleMouseDoubleClick( int WXUNUSED(x),
+                                             unsigned int WXUNUSED(y),
+                                             wxMouseEvent& event )
 {
     if ( m_propHover )
     {
         // Select property here as well
         wxPGProperty* p = m_propHover;
 
 {
     if ( m_propHover )
     {
         // Select property here as well
         wxPGProperty* p = m_propHover;
 
-        if ( p != m_selected )
-            DoSelectProperty( p );
+        AddToSelectionFromInputEvent(p, m_colHover, &event);
 
         // Send double-click event.
         SendEvent( wxEVT_PG_DOUBLE_CLICK, m_propHover );
 
         // Send double-click event.
         SendEvent( wxEVT_PG_DOUBLE_CLICK, m_propHover );
@@ -4167,14 +4573,14 @@ void wxPropertyGrid::SetToolTip( const wxString& tipString )
 {
     if ( tipString.length() )
     {
 {
     if ( tipString.length() )
     {
-        m_canvas->SetToolTip(tipString);
+        wxScrolledWindow::SetToolTip(tipString);
     }
     else
     {
     #if wxPG_ALLOW_EMPTY_TOOLTIPS
     }
     else
     {
     #if wxPG_ALLOW_EMPTY_TOOLTIPS
-        m_canvas->SetToolTip( m_emptyString );
+        wxScrolledWindow::SetToolTip( m_emptyString );
     #else
     #else
-        m_canvas->SetToolTip( NULL );
+        wxScrolledWindow::SetToolTip( NULL );
     #endif
     }
 }
     #endif
     }
 }
@@ -4184,13 +4590,14 @@ void wxPropertyGrid::SetToolTip( const wxString& tipString )
 // -----------------------------------------------------------------------
 
 // Return false if should be skipped
 // -----------------------------------------------------------------------
 
 // Return false if should be skipped
-bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event )
+bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y,
+                                      wxMouseEvent &event )
 {
     // Safety check (needed because mouse capturing may
     // otherwise freeze the control)
     if ( m_dragStatus > 0 && !event.Dragging() )
     {
 {
     // Safety check (needed because mouse capturing may
     // otherwise freeze the control)
     if ( m_dragStatus > 0 && !event.Dragging() )
     {
-        HandleMouseUp(x,y,event);
+        HandleMouseUp(x, y, event);
     }
 
     wxPropertyGridPageState* state = m_pState;
     }
 
     wxPropertyGridPageState* state = m_pState;
@@ -4199,6 +4606,8 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
     int columnHit = state->HitTestH( x, &splitterHit, &splitterHitOffset );
     int splitterX = x - splitterHitOffset;
 
     int columnHit = state->HitTestH( x, &splitterHit, &splitterHitOffset );
     int splitterX = x - splitterHitOffset;
 
+    m_colHover = columnHit;
+
     if ( m_dragStatus > 0 )
     {
         if ( x > (m_marginWidth + wxPG_DRAG_MARGIN) &&
     if ( m_dragStatus > 0 )
     {
         if ( x > (m_marginWidth + wxPG_DRAG_MARGIN) &&
@@ -4212,11 +4621,13 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
             if ( newSplitterX != splitterX )
             {
                 // Move everything
             if ( newSplitterX != splitterX )
             {
                 // Move everything
-                SetInternalFlag(wxPG_FL_DONT_CENTER_SPLITTER);
-                state->DoSetSplitterPosition( newSplitterX, m_draggedSplitter, false );
+                state->m_dontCenterSplitter = true;
+                state->DoSetSplitterPosition(newSplitterX,
+                                             m_draggedSplitter,
+                                             false);
                 state->m_fSplitterX = (float) newSplitterX;
 
                 state->m_fSplitterX = (float) newSplitterX;
 
-                if ( m_selected )
+                if ( GetSelection() )
                     CorrectEditorWidgetSizeX();
 
                 Update();
                     CorrectEditorWidgetSizeX();
 
                 Update();
@@ -4269,7 +4680,7 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
         //
         if ( m_windowStyle & wxPG_TOOLTIPS )
         {
         //
         if ( m_windowStyle & wxPG_TOOLTIPS )
         {
-            wxToolTip* tooltip = m_canvas->GetToolTip();
+            wxToolTip* tooltip = GetToolTip();
 
             if ( m_propHover != prevHover || prevSide != m_mouseSide )
             {
 
             if ( m_propHover != prevHover || prevSide != m_mouseSide )
             {
@@ -4300,13 +4711,15 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
 
                             space = m_width - splitterX;
                             if ( m_propHover->m_flags & wxPG_PROP_CUSTOMIMAGE )
 
                             space = m_width - splitterX;
                             if ( m_propHover->m_flags & wxPG_PROP_CUSTOMIMAGE )
-                                space -= wxPG_CUSTOM_IMAGE_WIDTH + wxCC_CUSTOM_IMAGE_MARGIN1 + wxCC_CUSTOM_IMAGE_MARGIN2;
+                                space -= wxPG_CUSTOM_IMAGE_WIDTH +
+                                         wxCC_CUSTOM_IMAGE_MARGIN1 +
+                                         wxCC_CUSTOM_IMAGE_MARGIN2;
                         }
 
                         if ( space )
                         {
                             int tw, th;
                         }
 
                         if ( space )
                         {
                             int tw, th;
-                           GetTextExtent( tipString, &tw, &th, 0, 0, &m_font );
+                            GetTextExtent( tipString, &tw, &th, 0, 0 );
                             if ( tw > space )
                             {
                                 SetToolTip( tipString );
                             if ( tw > space )
                             {
                                 SetToolTip( tipString );
@@ -4317,9 +4730,9 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
                             if ( tooltip )
                             {
                             #if wxPG_ALLOW_EMPTY_TOOLTIPS
                             if ( tooltip )
                             {
                             #if wxPG_ALLOW_EMPTY_TOOLTIPS
-                                m_canvas->SetToolTip( m_emptyString );
+                                SetToolTip( m_emptyString );
                             #else
                             #else
-                                m_canvas->SetToolTip( NULL );
+                                wxScrolledWindow::SetToolTip( NULL );
                             #endif
                             }
                         }
                             #endif
                             }
                         }
@@ -4331,9 +4744,9 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
                     if ( tooltip )
                     {
                     #if wxPG_ALLOW_EMPTY_TOOLTIPS
                     if ( tooltip )
                     {
                     #if wxPG_ALLOW_EMPTY_TOOLTIPS
-                        m_canvas->SetToolTip( m_emptyString );
+                        SetToolTip( m_emptyString );
                     #else
                     #else
-                        m_canvas->SetToolTip( NULL );
+                        wxScrolledWindow::SetToolTip( NULL );
                     #endif
                     }
                 }
                     #endif
                     }
                 }
@@ -4361,8 +4774,8 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
 
                 // hovering on splitter
 
 
                 // hovering on splitter
 
-                // NB: Condition disabled since MouseLeave event (from the editor control) cannot be
-                //     reliably detected.
+                // NB: Condition disabled since MouseLeave event (from the
+                //     editor control) cannot be reliably detected.
                 //if ( m_curcursor != wxCURSOR_SIZEWE )
                 CustomSetCursor( wxCURSOR_SIZEWE, true );
 
                 //if ( m_curcursor != wxCURSOR_SIZEWE )
                 CustomSetCursor( wxCURSOR_SIZEWE, true );
 
@@ -4375,6 +4788,38 @@ bool wxPropertyGrid::HandleMouseMove( int x, unsigned int y, wxMouseEvent &event
                     CustomSetCursor( wxCURSOR_ARROW );
             }
         }
                     CustomSetCursor( wxCURSOR_ARROW );
             }
         }
+
+        //
+        // Multi select by dragging
+        //
+        if ( (GetExtraStyle() & wxPG_EX_MULTIPLE_SELECTION) &&
+             event.LeftIsDown() &&
+             m_propHover &&
+             GetSelection() &&
+             columnHit != 1 &&
+             !state->DoIsPropertySelected(m_propHover) )
+        {
+            // Additional requirement is that the hovered property
+            // is adjacent to edges of selection.
+            const wxArrayPGProperty& selection = GetSelectedProperties();
+
+            // Since categories cannot be selected along with 'other'
+            // properties, exclude them from iterator flags.
+            int iterFlags = wxPG_ITERATE_VISIBLE & (~wxPG_PROP_CATEGORY);
+
+            for ( int i=(selection.size()-1); i>=0; i-- )
+            {
+                // TODO: This could be optimized by keeping track of
+                //       which properties are at the edges of selection.
+                wxPGProperty* selProp = selection[i];
+                if ( state->ArePropertiesAdjacent(m_propHover, selProp,
+                                                  iterFlags) )
+                {
+                    DoAddToSelection(m_propHover);
+                    break;
+                }
+            }
+        }
     }
     return true;
 }
     }
     return true;
 }
@@ -4405,12 +4850,12 @@ bool wxPropertyGrid::HandleMouseUp( int x, unsigned int WXUNUSED(y),
         //splitterX = x;
 
         // Disable splitter auto-centering
         //splitterX = x;
 
         // Disable splitter auto-centering
-        m_iFlags |= wxPG_FL_DONT_CENTER_SPLITTER;
+        state->m_dontCenterSplitter = true;
 
         // This is necessary to return cursor
         if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
         {
 
         // This is necessary to return cursor
         if ( m_iFlags & wxPG_FL_MOUSE_CAPTURED )
         {
-            m_canvas->ReleaseMouse();
+            ReleaseMouse();
             m_iFlags &= ~(wxPG_FL_MOUSE_CAPTURED);
         }
 
             m_iFlags &= ~(wxPG_FL_MOUSE_CAPTURED);
         }
 
@@ -4424,8 +4869,9 @@ bool wxPropertyGrid::HandleMouseUp( int x, unsigned int WXUNUSED(y),
         m_dragStatus = 0;
 
         // Control background needs to be cleared
         m_dragStatus = 0;
 
         // Control background needs to be cleared
-        if ( !(m_iFlags & wxPG_FL_PRIMARY_FILLS_ENTIRE) && m_selected )
-            DrawItem( m_selected );
+        wxPGProperty* selected = GetSelection();
+        if ( !(m_iFlags & wxPG_FL_PRIMARY_FILLS_ENTIRE) && selected )
+            DrawItem( selected );
 
         if ( m_wndEditor )
         {
 
         if ( m_wndEditor )
         {
@@ -4451,10 +4897,8 @@ bool wxPropertyGrid::OnMouseCommon( wxMouseEvent& event, int* px, int* py )
 {
     int splitterX = GetSplitterPosition();
 
 {
     int splitterX = GetSplitterPosition();
 
-    //int ux, uy;
-    //CalcUnscrolledPosition( event.m_x, event.m_y, &ux, &uy );
-    int ux = event.m_x;
-    int uy = event.m_y;
+    int ux, uy;
+    CalcUnscrolledPosition( event.m_x, event.m_y, &ux, &uy );
 
     wxWindow* wnd = GetEditorControl();
 
 
     wxWindow* wnd = GetEditorControl();
 
@@ -4468,7 +4912,7 @@ bool wxPropertyGrid::OnMouseCommon( wxMouseEvent& event, int* px, int* py )
     wxRect r;
     if ( wnd )
         r = wnd->GetRect();
     wxRect r;
     if ( wnd )
         r = wnd->GetRect();
-    if ( wnd == (wxWindow*) NULL || m_dragStatus ||
+    if ( wnd == NULL || m_dragStatus ||
          (
            ux <= (splitterX + wxPG_SPLITTERX_DETECTMARGIN2) ||
            ux >= (r.x+r.width) ||
          (
            ux <= (splitterX + wxPG_SPLITTERX_DETECTMARGIN2) ||
            ux >= (r.x+r.width) ||
@@ -4537,14 +4981,6 @@ void wxPropertyGrid::OnMouseMove( wxMouseEvent &event )
 
 // -----------------------------------------------------------------------
 
 
 // -----------------------------------------------------------------------
 
-void wxPropertyGrid::OnMouseMoveBottom( wxMouseEvent& WXUNUSED(event) )
-{
-    // Called when mouse moves in the empty space below the properties.
-    CustomSetCursor( wxCURSOR_ARROW );
-}
-
-// -----------------------------------------------------------------------
-
 void wxPropertyGrid::OnMouseUp( wxMouseEvent &event )
 {
     int x, y;
 void wxPropertyGrid::OnMouseUp( wxMouseEvent &event )
 {
     int x, y;
@@ -4579,7 +5015,7 @@ void wxPropertyGrid::OnMouseEntry( wxMouseEvent &event )
     else if ( event.Leaving() )
     {
         // Without this, wxSpinCtrl editor will sometimes have wrong cursor
     else if ( event.Leaving() )
     {
         // Without this, wxSpinCtrl editor will sometimes have wrong cursor
-        m_canvas->SetCursor( wxNullCursor );
+        SetCursor( wxNullCursor );
 
         // Get real cursor position
         wxPoint pt = ScreenToClient(::wxGetMousePosition());
 
         // Get real cursor position
         wxPoint pt = ScreenToClient(::wxGetMousePosition());
@@ -4649,8 +5085,10 @@ void wxPropertyGrid::OnMouseRightClickChild( wxMouseEvent &event )
     // but that should not matter (right click is about item, not position).
     wxPoint pt = m_wndEditor->GetPosition();
     CalcUnscrolledPosition( event.m_x + pt.x, event.m_y + pt.y, &x, &y );
     // but that should not matter (right click is about item, not position).
     wxPoint pt = m_wndEditor->GetPosition();
     CalcUnscrolledPosition( event.m_x + pt.x, event.m_y + pt.y, &x, &y );
-    wxASSERT( m_selected );
-    m_propHover = m_selected;
+
+    // FIXME: Used to set m_propHover to selection here. Was it really
+    //        necessary?
+
     bool res = HandleMouseRightClick(x,y,event);
     if ( !res ) event.Skip();
 }
     bool res = HandleMouseRightClick(x,y,event);
     if ( !res ) event.Skip();
 }
@@ -4729,14 +5167,25 @@ void wxPropertyGrid::AddActionTrigger( int action, int keycode, int modifiers )
 void wxPropertyGrid::ClearActionTriggers( int action )
 {
     wxPGHashMapI2I::iterator it;
 void wxPropertyGrid::ClearActionTriggers( int action )
 {
     wxPGHashMapI2I::iterator it;
+    bool didSomething;
 
 
-    for ( it = m_actionTriggers.begin(); it != m_actionTriggers.end(); ++it )
+    do
     {
     {
-        if ( it->second == action )
+        didSomething = false;
+
+        for ( it = m_actionTriggers.begin();
+              it != m_actionTriggers.end();
+              it++ )
         {
         {
-            m_actionTriggers.erase(it);
+            if ( it->second == action )
+            {
+                m_actionTriggers.erase(it);
+                didSomething = true;
+                break;
+            }
         }
     }
         }
     }
+    while ( didSomething );
 }
 
 void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
 }
 
 void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
@@ -4748,6 +5197,7 @@ void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
     wxCHECK2(!m_frozen, return);
 
     // Travelsal between items, collapsing/expanding, etc.
     wxCHECK2(!m_frozen, return);
 
     // Travelsal between items, collapsing/expanding, etc.
+    wxPGProperty* selected = GetSelection();
     int keycode = event.GetKeyCode();
     bool editorFocused = IsEditorFocused();
 
     int keycode = event.GetKeyCode();
     bool editorFocused = IsEditorFocused();
 
@@ -4764,7 +5214,7 @@ void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
         {
             if ( !editorFocused && m_wndEditor )
             {
         {
             if ( !editorFocused && m_wndEditor )
             {
-                DoSelectProperty( m_selected, wxPG_SEL_FOCUS );
+                DoSelectProperty( selected, wxPG_SEL_FOCUS );
             }
             else
             {
             }
             else
             {
@@ -4823,12 +5273,13 @@ void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
             EditorsValueWasNotModified();
 
             // Update the control as well
             EditorsValueWasNotModified();
 
             // Update the control as well
-            m_selected->GetEditorClass()->SetControlStringValue( m_selected,
-                                                                 GetEditorControl(),
-                                                                 m_selected->GetDisplayedString() );
+            selected->GetEditorClass()->
+                SetControlStringValue( selected,
+                                       GetEditorControl(),
+                                       selected->GetDisplayedString() );
         }
 
         }
 
-        OnValidationFailureReset(m_selected);
+        OnValidationFailureReset(selected);
 
         UnfocusEditor();
         return;
 
         UnfocusEditor();
         return;
@@ -4837,26 +5288,29 @@ void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
     // Except for TAB and ESC, handle child control events in child control
     if ( fromChild )
     {
     // Except for TAB and ESC, handle child control events in child control
     if ( fromChild )
     {
+        // Only propagate event if it had modifiers
+        if ( !event.HasModifiers() )
+        {
+            event.StopPropagation();
+        }
         event.Skip();
         return;
     }
 
     bool wasHandled = false;
 
         event.Skip();
         return;
     }
 
     bool wasHandled = false;
 
-    if ( m_selected )
+    if ( selected )
     {
         // Show dialog?
         if ( ButtonTriggerKeyTest(action, event) )
             return;
 
     {
         // Show dialog?
         if ( ButtonTriggerKeyTest(action, event) )
             return;
 
-        wxPGProperty* p = m_selected;
+        wxPGProperty* p = selected;
 
         // Travel and expand/collapse
         int selectDir = -2;
 
 
         // Travel and expand/collapse
         int selectDir = -2;
 
-        if ( p->GetChildCount() &&
-             !(p->m_flags & wxPG_PROP_DISABLED)
-           )
+        if ( p->GetChildCount() )
         {
             if ( action == wxPG_ACTION_COLLAPSE_PROPERTY || secondAction == wxPG_ACTION_COLLAPSE_PROPERTY )
             {
         {
             if ( action == wxPG_ACTION_COLLAPSE_PROPERTY || secondAction == wxPG_ACTION_COLLAPSE_PROPERTY )
             {
@@ -4910,6 +5364,19 @@ void wxPropertyGrid::HandleKeyEvent( wxKeyEvent &event, bool fromChild )
 
 void wxPropertyGrid::OnKey( wxKeyEvent &event )
 {
 
 void wxPropertyGrid::OnKey( wxKeyEvent &event )
 {
+    // If there was editor open and focused, then this event should not
+    // really be processed here.
+    if ( IsEditorFocused() )
+    {
+        // However, if event had modifiers, it is probably still best
+        // to skip it.
+        if ( event.HasModifiers() )
+            event.Skip();
+        else
+            event.StopPropagation();
+        return;
+    }
+
     HandleKeyEvent(event, false);
 }
 
     HandleKeyEvent(event, false);
 }
 
@@ -4954,6 +5421,15 @@ void wxPropertyGrid::OnIdle( wxIdleEvent& WXUNUSED(event) )
 
     if ( newFocused != m_curFocused )
         HandleFocusChange( newFocused );
 
     if ( newFocused != m_curFocused )
         HandleFocusChange( newFocused );
+
+    //
+    // Check if top-level parent has changed
+    if ( GetExtraStyle() & wxPG_EX_ENABLE_TLP_TRACKING )
+    {
+        wxWindow* tlp = ::wxGetTopLevelParent(this);
+        if ( tlp != m_tlp )
+            OnTLPChanging(tlp);
+    }
 }
 
 bool wxPropertyGrid::IsEditorFocused() const
 }
 
 bool wxPropertyGrid::IsEditorFocused() const
@@ -5031,8 +5507,9 @@ void wxPropertyGrid::HandleFocusChange( wxWindow* newFocused )
         }
 
         // Redraw selected
         }
 
         // Redraw selected
-        if ( m_selected && (m_iFlags & wxPG_FL_INITIALIZED) )
-            DrawItem( m_selected );
+        wxPGProperty* selected = GetSelection();
+        if ( selected && (m_iFlags & wxPG_FL_INITIALIZED) )
+            DrawItem( selected );
     }
 }
 
     }
 }
 
@@ -5053,11 +5530,7 @@ void wxPropertyGrid::OnFocusEvent( wxFocusEvent& event )
 void wxPropertyGrid::OnChildFocusEvent( wxChildFocusEvent& event )
 {
     HandleFocusChange((wxWindow*)event.GetEventObject());
 void wxPropertyGrid::OnChildFocusEvent( wxChildFocusEvent& event )
 {
     HandleFocusChange((wxWindow*)event.GetEventObject());
-
-    //
-    // event.Skip() being commented out is aworkaround for bug reported
-    // in ticket #4840 (wxScrolledWindow problem with automatic scrolling).
-    //event.Skip();
+    event.Skip();
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------
@@ -5084,15 +5557,18 @@ void wxPropertyGrid::OnCaptureChange( wxMouseCaptureChangedEvent& WXUNUSED(event
 // -----------------------------------------------------------------------
 
 // noDefCheck = true prevents infinite recursion.
 // -----------------------------------------------------------------------
 
 // noDefCheck = true prevents infinite recursion.
-wxPGEditor* wxPropertyGrid::RegisterEditorClass( wxPGEditor* editorClass,
-                                                 bool noDefCheck )
+wxPGEditor* wxPropertyGrid::DoRegisterEditorClass( wxPGEditor* editorClass,
+                                                   const wxString& editorName,
+                                                   bool noDefCheck )
 {
     wxASSERT( editorClass );
 
     if ( !noDefCheck && wxPGGlobalVars->m_mapEditorClasses.empty() )
         RegisterDefaultEditors();
 
 {
     wxASSERT( editorClass );
 
     if ( !noDefCheck && wxPGGlobalVars->m_mapEditorClasses.empty() )
         RegisterDefaultEditors();
 
-    wxString name = editorClass->GetName();
+    wxString name = editorName;
+    if ( name.length() == 0 )
+        name = editorClass->GetName();
 
     // Existing editor under this name?
     wxPGHashMapS2P::iterator vt_it = wxPGGlobalVars->m_mapEditorClasses.find(name);
 
     // Existing editor under this name?
     wxPGHashMapS2P::iterator vt_it = wxPGGlobalVars->m_mapEditorClasses.find(name);
@@ -5115,7 +5591,7 @@ wxPGEditor* wxPropertyGrid::RegisterEditorClass( wxPGEditor* editorClass,
 
 // Use this in RegisterDefaultEditors.
 #define wxPGRegisterDefaultEditorClass(EDITOR) \
 
 // Use this in RegisterDefaultEditors.
 #define wxPGRegisterDefaultEditorClass(EDITOR) \
-    if ( wxPGEditor_##EDITOR == (wxPGEditor*) NULL ) \
+    if ( wxPGEditor_##EDITOR == NULL ) \
     { \
         wxPGEditor_##EDITOR = wxPropertyGrid::RegisterEditorClass( \
             new wxPG##EDITOR##Editor, true ); \
     { \
         wxPGEditor_##EDITOR = wxPropertyGrid::RegisterEditorClass( \
             new wxPG##EDITOR##Editor, true ); \
@@ -5229,7 +5705,6 @@ wxPGChoiceEntry::wxPGChoiceEntry()
 
 wxPGChoicesData::wxPGChoicesData()
 {
 
 wxPGChoicesData::wxPGChoicesData()
 {
-    m_refCount = 1;
 }
 
 wxPGChoicesData::~wxPGChoicesData()
 }
 
 wxPGChoicesData::~wxPGChoicesData()
@@ -5274,241 +5749,6 @@ wxPGChoiceEntry& wxPGChoicesData::Insert( int index,
     return ownEntry;
 }
 
     return ownEntry;
 }
 
-// -----------------------------------------------------------------------
-// wxPGChoices
-// -----------------------------------------------------------------------
-
-wxPGChoiceEntry& wxPGChoices::Add( const wxString& label, int value )
-{
-    EnsureData();
-
-    wxPGChoiceEntry entry(label, value);
-    return m_data->Insert( -1, entry );
-}
-
-// -----------------------------------------------------------------------
-
-wxPGChoiceEntry& wxPGChoices::Add( const wxString& label, const wxBitmap& bitmap, int value )
-{
-    EnsureData();
-
-    wxPGChoiceEntry entry(label, value);
-    entry.SetBitmap(bitmap);
-    return m_data->Insert( -1, entry );
-}
-
-// -----------------------------------------------------------------------
-
-wxPGChoiceEntry& wxPGChoices::Insert( const wxPGChoiceEntry& entry, int index )
-{
-    EnsureData();
-    return m_data->Insert( index, entry );
-}
-
-// -----------------------------------------------------------------------
-
-wxPGChoiceEntry& wxPGChoices::Insert( const wxString& label, int index, int value )
-{
-    EnsureData();
-
-    wxPGChoiceEntry entry(label, value);
-    return m_data->Insert( index, entry );
-}
-
-// -----------------------------------------------------------------------
-
-wxPGChoiceEntry& wxPGChoices::AddAsSorted( const wxString& label, int value )
-{
-    EnsureData();
-
-    size_t index = 0;
-
-    while ( index < GetCount() )
-    {
-        int cmpRes = GetLabel(index).Cmp(label);
-        if ( cmpRes > 0 )
-            break;
-        index++;
-    }
-
-    wxPGChoiceEntry entry(label, value);
-    return m_data->Insert( index, entry );
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::Add( const wxChar** labels, const ValArrItem* values )
-{
-    EnsureData();
-
-    unsigned int itemcount = 0;
-    const wxChar** p = &labels[0];
-    while ( *p ) { p++; itemcount++; }
-
-    unsigned int i;
-    for ( i = 0; i < itemcount; i++ )
-    {
-        int value = i;
-        if ( values )
-            value = values[i];
-        wxPGChoiceEntry entry(labels[i], value);
-        m_data->Insert( i, entry );
-    }
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::Add( const wxArrayString& arr, const wxArrayInt& arrint )
-{
-    EnsureData();
-
-    unsigned int i;
-    unsigned int itemcount = arr.size();
-
-    for ( i = 0; i < itemcount; i++ )
-    {
-        int value = i;
-        if ( &arrint && arrint.size() )
-            value = arrint[i];
-        wxPGChoiceEntry entry(arr[i], value);
-        m_data->Insert( i, entry );
-    }
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::RemoveAt(size_t nIndex, size_t count)
-{
-    wxASSERT( m_data->m_refCount != 0xFFFFFFF );
-    m_data->m_items.erase(m_data->m_items.begin()+nIndex,
-                          m_data->m_items.begin()+nIndex+count);
-}
-
-// -----------------------------------------------------------------------
-
-int wxPGChoices::Index( const wxString& str ) const
-{
-    if ( IsOk() )
-    {
-        unsigned int i;
-        for ( i=0; i< m_data->GetCount(); i++ )
-        {
-            const wxPGChoiceEntry& entry = m_data->Item(i);
-            if ( entry.HasText() && entry.GetText() == str )
-                return i;
-        }
-    }
-    return -1;
-}
-
-// -----------------------------------------------------------------------
-
-int wxPGChoices::Index( int val ) const
-{
-    if ( IsOk() )
-    {
-        unsigned int i;
-        for ( i=0; i< m_data->GetCount(); i++ )
-        {
-            const wxPGChoiceEntry& entry = m_data->Item(i);
-            if ( entry.GetValue() == val )
-                return i;
-        }
-    }
-    return -1;
-}
-
-// -----------------------------------------------------------------------
-
-wxArrayString wxPGChoices::GetLabels() const
-{
-    wxArrayString arr;
-    unsigned int i;
-
-    if ( this && IsOk() )
-        for ( i=0; i<GetCount(); i++ )
-            arr.push_back(GetLabel(i));
-
-    return arr;
-}
-
-// -----------------------------------------------------------------------
-
-wxArrayInt wxPGChoices::GetValuesForStrings( const wxArrayString& strings ) const
-{
-    wxArrayInt arr;
-
-    if ( IsOk() )
-    {
-        unsigned int i;
-        for ( i=0; i< strings.size(); i++ )
-        {
-            int index = Index(strings[i]);
-            if ( index >= 0 )
-                arr.Add(GetValue(index));
-            else
-                arr.Add(wxPG_INVALID_VALUE);
-        }
-    }
-
-    return arr;
-}
-
-// -----------------------------------------------------------------------
-
-wxArrayInt wxPGChoices::GetIndicesForStrings( const wxArrayString& strings,
-                                              wxArrayString* unmatched ) const
-{
-    wxArrayInt arr;
-
-    if ( IsOk() )
-    {
-        unsigned int i;
-        for ( i=0; i< strings.size(); i++ )
-        {
-            const wxString& str = strings[i];
-            int index = Index(str);
-            if ( index >= 0 )
-                arr.Add(index);
-            else if ( unmatched )
-                unmatched->Add(str);
-        }
-    }
-
-    return arr;
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::AssignData( wxPGChoicesData* data )
-{
-    Free();
-
-    if ( data != wxPGChoicesEmptyData )
-    {
-        m_data = data;
-        data->m_refCount++;
-    }
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::Init()
-{
-    m_data = wxPGChoicesEmptyData;
-}
-
-// -----------------------------------------------------------------------
-
-void wxPGChoices::Free()
-{
-    if ( m_data != wxPGChoicesEmptyData )
-    {
-        m_data->DecRef();
-        m_data = wxPGChoicesEmptyData;
-    }
-}
-
 // -----------------------------------------------------------------------
 // wxPropertyGridEvent
 // -----------------------------------------------------------------------
 // -----------------------------------------------------------------------
 // wxPropertyGridEvent
 // -----------------------------------------------------------------------
@@ -5516,22 +5756,24 @@ void wxPGChoices::Free()
 IMPLEMENT_DYNAMIC_CLASS(wxPropertyGridEvent, wxCommandEvent)
 
 
 IMPLEMENT_DYNAMIC_CLASS(wxPropertyGridEvent, wxCommandEvent)
 
 
-DEFINE_EVENT_TYPE( wxEVT_PG_SELECTED )
-DEFINE_EVENT_TYPE( wxEVT_PG_CHANGING )
-DEFINE_EVENT_TYPE( wxEVT_PG_CHANGED )
-DEFINE_EVENT_TYPE( wxEVT_PG_HIGHLIGHTED )
-DEFINE_EVENT_TYPE( wxEVT_PG_RIGHT_CLICK )
-DEFINE_EVENT_TYPE( wxEVT_PG_PAGE_CHANGED )
-DEFINE_EVENT_TYPE( wxEVT_PG_ITEM_EXPANDED )
-DEFINE_EVENT_TYPE( wxEVT_PG_ITEM_COLLAPSED )
-DEFINE_EVENT_TYPE( wxEVT_PG_DOUBLE_CLICK )
-
+wxDEFINE_EVENT( wxEVT_PG_SELECTED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_CHANGING, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_CHANGED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_HIGHLIGHTED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_RIGHT_CLICK, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_PAGE_CHANGED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_ITEM_EXPANDED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_ITEM_COLLAPSED, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_DOUBLE_CLICK, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_LABEL_EDIT_BEGIN, wxPropertyGridEvent );
+wxDEFINE_EVENT( wxEVT_PG_LABEL_EDIT_ENDING, wxPropertyGridEvent );
 
 // -----------------------------------------------------------------------
 
 void wxPropertyGridEvent::Init()
 {
     m_validationInfo = NULL;
 
 // -----------------------------------------------------------------------
 
 void wxPropertyGridEvent::Init()
 {
     m_validationInfo = NULL;
+    m_column = 1;
     m_canVeto = false;
     m_wasVetoed = false;
 }
     m_canVeto = false;
     m_wasVetoed = false;
 }
@@ -5553,6 +5795,7 @@ wxPropertyGridEvent::wxPropertyGridEvent(const wxPropertyGridEvent& event)
     m_eventType = event.GetEventType();
     m_eventObject = event.m_eventObject;
     m_pg = event.m_pg;
     m_eventType = event.GetEventType();
     m_eventObject = event.m_eventObject;
     m_pg = event.m_pg;
+    OnPropertyGridSet();
     m_property = event.m_property;
     m_validationInfo = event.m_validationInfo;
     m_canVeto = event.m_canVeto;
     m_property = event.m_property;
     m_validationInfo = event.m_validationInfo;
     m_canVeto = event.m_canVeto;
@@ -5561,8 +5804,40 @@ wxPropertyGridEvent::wxPropertyGridEvent(const wxPropertyGridEvent& event)
 
 // -----------------------------------------------------------------------
 
 
 // -----------------------------------------------------------------------
 
+void wxPropertyGridEvent::OnPropertyGridSet()
+{
+    if ( !m_pg )
+        return;
+
+#if wxUSE_THREADS
+    wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
+#endif
+    m_pg->m_liveEvents.push_back(this);
+}
+
+// -----------------------------------------------------------------------
+
 wxPropertyGridEvent::~wxPropertyGridEvent()
 {
 wxPropertyGridEvent::~wxPropertyGridEvent()
 {
+    if ( m_pg )
+    {
+    #if wxUSE_THREADS
+        wxCriticalSectionLocker(wxPGGlobalVars->m_critSect);
+    #endif
+
+        // Use iterate from the back since it is more likely that the event
+        // being desroyed is at the end of the array.
+        wxVector<wxPropertyGridEvent*>& liveEvents = m_pg->m_liveEvents;
+
+        for ( int i = liveEvents.size()-1; i >= 0; i-- )
+        {
+            if ( liveEvents[i] == this )
+            {
+                liveEvents.erase(liveEvents.begin() + i);
+                break;
+            }
+        }
+    }
 }
 
 // -----------------------------------------------------------------------
 }
 
 // -----------------------------------------------------------------------