X-Git-Url: https://git.saurik.com/wxWidgets.git/blobdiff_plain/78e788120814699ab0a0d2fab1131285f5e0fd7a..c13815810e8ff427614ca82fe0dfd4b1e773f0f3:/src/generic/grid.cpp diff --git a/src/generic/grid.cpp b/src/generic/grid.cpp index d7ec66fcb2..6e276fe316 100644 --- a/src/generic/grid.cpp +++ b/src/generic/grid.cpp @@ -48,6 +48,7 @@ #include "wx/tokenzr.h" #include "wx/renderer.h" #include "wx/headerctrl.h" +#include "wx/hashset.h" #include "wx/generic/gridsel.h" #include "wx/generic/gridctrl.h" @@ -71,17 +72,36 @@ const char wxGridNameStr[] = "grid"; // Required for wxIs... functions #include +WX_DECLARE_HASH_SET_WITH_DECL_PTR(int, wxIntegerHash, wxIntegerEqual, + wxGridFixedIndicesSet, class WXDLLIMPEXP_ADV); + // ---------------------------------------------------------------------------- // globals // ---------------------------------------------------------------------------- +namespace +{ + //#define DEBUG_ATTR_CACHE #ifdef DEBUG_ATTR_CACHE static size_t gs_nAttrCacheHits = 0; static size_t gs_nAttrCacheMisses = 0; #endif +// this struct simply combines together the default header renderers +// +// as the renderers ctors are trivial, there is no problem with making them +// globals +struct DefaultHeaderRenderers +{ + wxGridColumnHeaderRendererDefault colRenderer; + wxGridRowHeaderRendererDefault rowRenderer; + wxGridCornerHeaderRendererDefault cornerRenderer; +} gs_defaultHeaderRenderers; + +} // anonymous namespace + // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- @@ -135,6 +155,24 @@ wxDEFINE_EVENT( wxEVT_GRID_SELECT_CELL, wxGridEvent ); wxDEFINE_EVENT( wxEVT_GRID_EDITOR_SHOWN, wxGridEvent ); wxDEFINE_EVENT( wxEVT_GRID_EDITOR_HIDDEN, wxGridEvent ); wxDEFINE_EVENT( wxEVT_GRID_EDITOR_CREATED, wxGridEditorCreatedEvent ); +wxDEFINE_EVENT( wxEVT_GRID_TABBING, wxGridEvent ); + +// ---------------------------------------------------------------------------- +// private helpers +// ---------------------------------------------------------------------------- + +namespace +{ + + // ensure that first is less or equal to second, swapping the values if + // necessary + void EnsureFirstLessThanSecond(int& first, int& second) + { + if ( first > second ) + wxSwap(first, second); + } + +} // anonymous namespace // ============================================================================ // implementation @@ -150,6 +188,8 @@ END_EVENT_TABLE() BEGIN_EVENT_TABLE(wxGridHeaderCtrl, wxHeaderCtrl) EVT_HEADER_CLICK(wxID_ANY, wxGridHeaderCtrl::OnClick) + EVT_HEADER_DCLICK(wxID_ANY, wxGridHeaderCtrl::OnDoubleClick) + EVT_HEADER_RIGHT_CLICK(wxID_ANY, wxGridHeaderCtrl::OnRightClick) EVT_HEADER_BEGIN_RESIZE(wxID_ANY, wxGridHeaderCtrl::OnBeginResize) EVT_HEADER_RESIZING(wxID_ANY, wxGridHeaderCtrl::OnResizing) @@ -187,14 +227,96 @@ wxGridCellWorker::~wxGridCellWorker() { } +// ---------------------------------------------------------------------------- +// wxGridHeaderLabelsRenderer and related classes +// ---------------------------------------------------------------------------- + +void wxGridHeaderLabelsRenderer::DrawLabel(const wxGrid& grid, + wxDC& dc, + const wxString& value, + const wxRect& rect, + int horizAlign, + int vertAlign, + int textOrientation) const +{ + dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT); + dc.SetTextForeground(grid.GetLabelTextColour()); + dc.SetFont(grid.GetLabelFont()); + grid.DrawTextRectangle(dc, value, rect, horizAlign, vertAlign, textOrientation); +} + + +void wxGridRowHeaderRendererDefault::DrawBorder(const wxGrid& WXUNUSED(grid), + wxDC& dc, + wxRect& rect) const +{ + dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); + dc.DrawLine(rect.GetRight(), rect.GetTop(), + rect.GetRight(), rect.GetBottom()); + dc.DrawLine(rect.GetLeft(), rect.GetTop(), + rect.GetLeft(), rect.GetBottom()); + dc.DrawLine(rect.GetLeft(), rect.GetBottom(), + rect.GetRight() + 1, rect.GetBottom()); + + dc.SetPen(*wxWHITE_PEN); + dc.DrawLine(rect.GetLeft() + 1, rect.GetTop(), + rect.GetLeft() + 1, rect.GetBottom()); + dc.DrawLine(rect.GetLeft() + 1, rect.GetTop(), + rect.GetRight(), rect.GetTop()); + + rect.Deflate(2); +} + +void wxGridColumnHeaderRendererDefault::DrawBorder(const wxGrid& WXUNUSED(grid), + wxDC& dc, + wxRect& rect) const +{ + dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); + dc.DrawLine(rect.GetRight(), rect.GetTop(), + rect.GetRight(), rect.GetBottom()); + dc.DrawLine(rect.GetLeft(), rect.GetTop(), + rect.GetRight(), rect.GetTop()); + dc.DrawLine(rect.GetLeft(), rect.GetBottom(), + rect.GetRight() + 1, rect.GetBottom()); + + dc.SetPen(*wxWHITE_PEN); + dc.DrawLine(rect.GetLeft(), rect.GetTop() + 1, + rect.GetLeft(), rect.GetBottom()); + dc.DrawLine(rect.GetLeft(), rect.GetTop() + 1, + rect.GetRight(), rect.GetTop() + 1); + + rect.Deflate(2); +} + +void wxGridCornerHeaderRendererDefault::DrawBorder(const wxGrid& WXUNUSED(grid), + wxDC& dc, + wxRect& rect) const +{ + dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); + dc.DrawLine(rect.GetRight() - 1, rect.GetBottom() - 1, + rect.GetRight() - 1, rect.GetTop()); + dc.DrawLine(rect.GetRight() - 1, rect.GetBottom() - 1, + rect.GetLeft(), rect.GetBottom() - 1); + dc.DrawLine(rect.GetLeft(), rect.GetTop(), + rect.GetRight(), rect.GetTop()); + dc.DrawLine(rect.GetLeft(), rect.GetTop(), + rect.GetLeft(), rect.GetBottom()); + + dc.SetPen(*wxWHITE_PEN); + dc.DrawLine(rect.GetLeft() + 1, rect.GetTop() + 1, + rect.GetRight() - 1, rect.GetTop() + 1); + dc.DrawLine(rect.GetLeft() + 1, rect.GetTop() + 1, + rect.GetLeft() + 1, rect.GetBottom() - 1); + + rect.Deflate(2); +} + // ---------------------------------------------------------------------------- // wxGridCellAttr // ---------------------------------------------------------------------------- void wxGridCellAttr::Init(wxGridCellAttr *attrDefault) { - m_nRef = 1; - m_isReadOnly = Unset; m_renderer = NULL; @@ -298,7 +420,7 @@ void wxGridCellAttr::SetSize(int num_rows, int num_cols) wxASSERT_MSG( (!((num_rows > 0) && (num_cols <= 0)) || !((num_rows <= 0) && (num_cols > 0)) || !((num_rows == 0) && (num_cols == 0))), - wxT("wxGridCellAttr::SetSize only takes two postive values or negative/zero values")); + wxT("wxGridCellAttr::SetSize only takes two positive values or negative/zero values")); m_sizeRows = num_rows; m_sizeCols = num_cols; @@ -374,6 +496,15 @@ void wxGridCellAttr::GetAlignment(int *hAlign, int *vAlign) const } } +void wxGridCellAttr::GetNonDefaultAlignment(int *hAlign, int *vAlign) const +{ + if ( hAlign && m_hAlign != wxALIGN_INVALID ) + *hAlign = m_hAlign; + + if ( vAlign && m_vAlign != wxALIGN_INVALID ) + *vAlign = m_vAlign; +} + void wxGridCellAttr::GetSize( int *num_rows, int *num_cols ) const { if ( num_rows ) @@ -641,30 +772,30 @@ void wxGridRowOrColAttrData::SetAttr(wxGridCellAttr *attr, int rowOrCol) { if ( attr ) { - // add the attribute - no need to do anything to reference count - // since we take ownership of the attribute. + // store the new attribute, taking its ownership m_rowsOrCols.Add(rowOrCol); m_attrs.Add(attr); } // nothing to remove } - else + else // we have an attribute for this row or column { size_t n = (size_t)i; - if ( m_attrs[n] == attr ) - // nothing to do - return; + + // notice that this code works correctly even when the old attribute is + // the same as the new one: as we own of it, we must call DecRef() on + // it in any case and this won't result in destruction of the new + // attribute if it's the same as old one because it must have ref count + // of at least 2 to be passed to us while we keep a reference to it too + m_attrs[n]->DecRef(); + if ( attr ) { - // change the attribute, handling reference count manually, - // taking ownership of the new attribute. - m_attrs[n]->DecRef(); + // replace the attribute with the new one m_attrs[n] = attr; } - else + else // remove the attribute { - // remove this attribute, handling reference count manually - m_attrs[n]->DecRef(); m_rowsOrCols.RemoveAt(n); m_attrs.RemoveAt(n); } @@ -857,6 +988,23 @@ void wxGridCellAttrProvider::UpdateAttrCols( size_t pos, int numCols ) } } +const wxGridColumnHeaderRenderer& +wxGridCellAttrProvider::GetColumnHeaderRenderer(int WXUNUSED(col)) +{ + return gs_defaultHeaderRenderers.colRenderer; +} + +const wxGridRowHeaderRenderer& +wxGridCellAttrProvider::GetRowHeaderRenderer(int WXUNUSED(row)) +{ + return gs_defaultHeaderRenderers.rowRenderer; +} + +const wxGridCornerHeaderRenderer& wxGridCellAttrProvider::GetCornerRenderer() +{ + return gs_defaultHeaderRenderers.cornerRenderer; +} + // ---------------------------------------------------------------------------- // wxGridTableBase // ---------------------------------------------------------------------------- @@ -1013,7 +1161,7 @@ wxString wxGridTableBase::GetColLabelValue( int col ) unsigned int i, n; for ( n = 1; ; n++ ) { - s += (wxChar) (_T('A') + (wxChar)(col % 26)); + s += (wxChar) (wxT('A') + (wxChar)(col % 26)); col = col / 26 - 1; if ( col < 0 ) break; @@ -1123,11 +1271,14 @@ IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable, wxGridTableBase ) wxGridStringTable::wxGridStringTable() : wxGridTableBase() { + m_numCols = 0; } wxGridStringTable::wxGridStringTable( int numRows, int numCols ) : wxGridTableBase() { + m_numCols = numCols; + m_data.Alloc( numRows ); wxArrayString sa; @@ -1137,36 +1288,21 @@ wxGridStringTable::wxGridStringTable( int numRows, int numCols ) m_data.Add( sa, numRows ); } -wxGridStringTable::~wxGridStringTable() -{ -} - -int wxGridStringTable::GetNumberRows() -{ - return m_data.GetCount(); -} - -int wxGridStringTable::GetNumberCols() -{ - if ( m_data.GetCount() > 0 ) - return m_data[0].GetCount(); - else - return 0; -} - wxString wxGridStringTable::GetValue( int row, int col ) { - wxCHECK_MSG( (row < GetNumberRows()) && (col < GetNumberCols()), + wxCHECK_MSG( (row >= 0 && row < GetNumberRows()) && + (col >= 0 && col < GetNumberCols()), wxEmptyString, - _T("invalid row or column index in wxGridStringTable") ); + wxT("invalid row or column index in wxGridStringTable") ); return m_data[row][col]; } void wxGridStringTable::SetValue( int row, int col, const wxString& value ) { - wxCHECK_RET( (row < GetNumberRows()) && (col < GetNumberCols()), - _T("invalid row or column index in wxGridStringTable") ); + wxCHECK_RET( (row >= 0 && row < GetNumberRows()) && + (col >= 0 && col < GetNumberCols()), + wxT("invalid row or column index in wxGridStringTable") ); m_data[row][col] = value; } @@ -1323,6 +1459,8 @@ bool wxGridStringTable::InsertCols( size_t pos, size_t numCols ) } } + m_numCols += numCols; + if ( GetView() ) { wxGridTableMessage msg( this, @@ -1347,6 +1485,8 @@ bool wxGridStringTable::AppendCols( size_t numCols ) m_data[row].Add( wxEmptyString, numCols ); } + m_numCols += numCols; + if ( GetView() ) { wxGridTableMessage msg( this, @@ -1395,21 +1535,28 @@ bool wxGridStringTable::DeleteCols( size_t pos, size_t numCols ) // m_colLabels stores just as many elements as it needs, e.g. if only // the label of the first column had been set it would have only one // element and not numCols, so account for it - int nToRm = m_colLabels.size() - colID; - if ( nToRm > 0 ) - m_colLabels.RemoveAt( colID, nToRm ); + int numRemaining = m_colLabels.size() - colID; + if (numRemaining > 0) + m_colLabels.RemoveAt( colID, wxMin(numCols, numRemaining) ); } - for ( row = 0; row < curNumRows; row++ ) + if ( numCols >= curNumCols ) { - if ( numCols >= curNumCols ) + for ( row = 0; row < curNumRows; row++ ) { m_data[row].Clear(); } - else + + m_numCols = 0; + } + else // something will be left + { + for ( row = 0; row < curNumRows; row++ ) { m_data[row].RemoveAt( colID, numCols ); } + + m_numCols -= numCols; } if ( GetView() ) @@ -1630,6 +1777,300 @@ void wxGridWindow::OnPaint( wxPaintEvent &WXUNUSED(event) ) m_owner->DrawHighlight( dc, dirtyCells ); } +void wxGrid::Render( wxDC& dc, + const wxPoint& position, + const wxSize& size, + const wxGridCellCoords& topLeft, + const wxGridCellCoords& bottomRight, + int style ) +{ + wxCHECK_RET( bottomRight.GetCol() < GetNumberCols(), + "Invalid right column" ); + wxCHECK_RET( bottomRight.GetRow() < GetNumberRows(), + "Invalid bottom row" ); + + // store user settings and reset later + + // remove grid selection, don't paint selection colour + // unless we have wxGRID_DRAW_SELECTION + // block selections are the only ones catered for here + wxGridCellCoordsArray selectedCells; + bool hasSelection = IsSelection(); + if ( hasSelection && !( style & wxGRID_DRAW_SELECTION ) ) + { + selectedCells = GetSelectionBlockTopLeft(); + // non block selections may not have a bottom right + if ( GetSelectionBlockBottomRight().size() ) + selectedCells.Add( GetSelectionBlockBottomRight()[ 0 ] ); + + ClearSelection(); + } + + // store user device origin + wxCoord userOriginX, userOriginY; + dc.GetDeviceOrigin( &userOriginX, &userOriginY ); + + // store user scale + double scaleUserX, scaleUserY; + dc.GetUserScale( &scaleUserX, &scaleUserY ); + + // set defaults if necessary + wxGridCellCoords leftTop( topLeft ), rightBottom( bottomRight ); + if ( leftTop.GetCol() < 0 ) + leftTop.SetCol(0); + if ( leftTop.GetRow() < 0 ) + leftTop.SetRow(0); + if ( rightBottom.GetCol() < 0 ) + rightBottom.SetCol(GetNumberCols() - 1); + if ( rightBottom.GetRow() < 0 ) + rightBottom.SetRow(GetNumberRows() - 1); + + // get grid offset, size and cell parameters + wxPoint pointOffSet; + wxSize sizeGrid; + wxGridCellCoordsArray renderCells; + wxArrayInt arrayCols; + wxArrayInt arrayRows; + + GetRenderSizes( leftTop, rightBottom, + pointOffSet, sizeGrid, + renderCells, + arrayCols, arrayRows ); + + // add headers/labels to dimensions + if ( style & wxGRID_DRAW_ROWS_HEADER ) + sizeGrid.x += GetRowLabelSize(); + if ( style & wxGRID_DRAW_COLS_HEADER ) + sizeGrid.y += GetColLabelSize(); + + // get render start position in logical units + wxPoint positionRender = GetRenderPosition( dc, position ); + + wxCoord originX = dc.LogicalToDeviceX( positionRender.x ); + wxCoord originY = dc.LogicalToDeviceY( positionRender.y ); + + dc.SetDeviceOrigin( originX, originY ); + + SetRenderScale( dc, positionRender, size, sizeGrid ); + + // draw row headers at specified origin + if ( GetRowLabelSize() > 0 && ( style & wxGRID_DRAW_ROWS_HEADER ) ) + { + if ( style & wxGRID_DRAW_COLS_HEADER ) + { + DrawCornerLabel( dc ); // do only if both col and row labels drawn + originY += dc.LogicalToDeviceYRel( GetColLabelSize() ); + } + + originY -= dc.LogicalToDeviceYRel( pointOffSet.y ); + dc.SetDeviceOrigin( originX, originY ); + + DrawRowLabels( dc, arrayRows ); + + // reset for columns + if ( style & wxGRID_DRAW_COLS_HEADER ) + originY -= dc.LogicalToDeviceYRel( GetColLabelSize() ); + + originY += dc.LogicalToDeviceYRel( pointOffSet.y ); + // X offset so we don't overwrite row labels + originX += dc.LogicalToDeviceXRel( GetRowLabelSize() ); + } + + // subtract col offset where startcol > 0 + originX -= dc.LogicalToDeviceXRel( pointOffSet.x ); + // no y offset for col labels, they are at the Y origin + + // draw column labels + if ( style & wxGRID_DRAW_COLS_HEADER ) + { + dc.SetDeviceOrigin( originX, originY ); + DrawColLabels( dc, arrayCols ); + // don't overwrite the labels, increment originY + originY += dc.LogicalToDeviceYRel( GetColLabelSize() ); + } + + // set device origin to draw grid cells and lines + originY -= dc.LogicalToDeviceYRel( pointOffSet.y ); + dc.SetDeviceOrigin( originX, originY ); + + // draw cell area background + dc.SetBrush( GetDefaultCellBackgroundColour() ); + dc.SetPen( *wxTRANSPARENT_PEN ); + // subtract headers from grid area dimensions + wxSize sizeCells( sizeGrid ); + if ( style & wxGRID_DRAW_ROWS_HEADER ) + sizeCells.x -= GetRowLabelSize(); + if ( style & wxGRID_DRAW_COLS_HEADER ) + sizeCells.y -= GetColLabelSize(); + + dc.DrawRectangle( pointOffSet, sizeCells ); + + // draw cells + DrawGridCellArea( dc, renderCells ); + + // draw grid lines + if ( style & wxGRID_DRAW_CELL_LINES ) + { + wxRegion regionClip( pointOffSet.x, pointOffSet.y, + sizeCells.x, sizeCells.y ); + + DrawRangeGridLines(dc, regionClip, renderCells[0], renderCells.Last()); + } + + // draw render rectangle bounding lines + DoRenderBox( dc, style, + pointOffSet, sizeCells, + leftTop, rightBottom ); + + // restore user setings + dc.SetDeviceOrigin( userOriginX, userOriginY ); + dc.SetUserScale( scaleUserX, scaleUserY ); + + if ( selectedCells.size() && !( style & wxGRID_DRAW_SELECTION ) ) + { + SelectBlock( selectedCells[ 0 ].GetRow(), + selectedCells[ 0 ].GetCol(), + selectedCells[ selectedCells.size() -1 ].GetRow(), + selectedCells[ selectedCells.size() -1 ].GetCol() ); + } +} + +void +wxGrid::SetRenderScale(wxDC& dc, + const wxPoint& pos, const wxSize& size, + const wxSize& sizeGrid ) +{ + double scaleX, scaleY; + wxSize sizeTemp; + + if ( size.GetWidth() != wxDefaultSize.GetWidth() ) // size.x was specified + sizeTemp.SetWidth( size.GetWidth() ); + else + sizeTemp.SetWidth( dc.DeviceToLogicalXRel( dc.GetSize().GetWidth() ) + - pos.x ); + + if ( size.GetHeight() != wxDefaultSize.GetHeight() ) // size.y was specified + sizeTemp.SetHeight( size.GetHeight() ); + else + sizeTemp.SetHeight( dc.DeviceToLogicalYRel( dc.GetSize().GetHeight() ) + - pos.y ); + + scaleX = (double)( (double) sizeTemp.GetWidth() / (double) sizeGrid.GetWidth() ); + scaleY = (double)( (double) sizeTemp.GetHeight() / (double) sizeGrid.GetHeight() ); + + dc.SetUserScale( wxMin( scaleX, scaleY), wxMin( scaleX, scaleY ) ); +} + +// get grid rendered size, origin offset and fill cell arrays +void wxGrid::GetRenderSizes( const wxGridCellCoords& topLeft, + const wxGridCellCoords& bottomRight, + wxPoint& pointOffSet, wxSize& sizeGrid, + wxGridCellCoordsArray& renderCells, + wxArrayInt& arrayCols, wxArrayInt& arrayRows ) +{ + pointOffSet.x = 0; + pointOffSet.y = 0; + sizeGrid.SetWidth( 0 ); + sizeGrid.SetHeight( 0 ); + + int col, row; + + wxGridSizesInfo sizeinfo = GetColSizes(); + for ( col = 0; col <= bottomRight.GetCol(); col++ ) + { + if ( col < topLeft.GetCol() ) + { + pointOffSet.x += sizeinfo.GetSize( col ); + } + else + { + for ( row = topLeft.GetRow(); row <= bottomRight.GetRow(); row++ ) + { + renderCells.Add( wxGridCellCoords( row, col )); + arrayRows.Add( row ); // column labels rendered in DrawColLabels + } + arrayCols.Add( col ); // row labels rendered in DrawRowLabels + sizeGrid.x += sizeinfo.GetSize( col ); + } + } + + sizeinfo = GetRowSizes(); + for ( row = 0; row <= bottomRight.GetRow(); row++ ) + { + if ( row < topLeft.GetRow() ) + pointOffSet.y += sizeinfo.GetSize( row ); + else + sizeGrid.y += sizeinfo.GetSize( row ); + } +} + +// get render start position +// if position not specified use dc draw extents MaxX and MaxY +wxPoint wxGrid::GetRenderPosition( wxDC& dc, const wxPoint& position ) +{ + wxPoint positionRender( position ); + + if ( !positionRender.IsFullySpecified() ) + { + if ( positionRender.x == wxDefaultPosition.x ) + positionRender.x = dc.MaxX(); + + if ( positionRender.y == wxDefaultPosition.y ) + positionRender.y = dc.MaxY(); + } + + return positionRender; +} + +// draw render rectangle bounding lines +// useful where there is multi cell row or col clipping and no cell border +void wxGrid::DoRenderBox( wxDC& dc, const int& style, + const wxPoint& pointOffSet, + const wxSize& sizeCells, + const wxGridCellCoords& topLeft, + const wxGridCellCoords& bottomRight ) +{ + if ( !( style & wxGRID_DRAW_BOX_RECT ) ) + return; + + int bottom = pointOffSet.y + sizeCells.GetY(), + right = pointOffSet.x + sizeCells.GetX() - 1; + + // horiz top line if we are not drawing column header/labels + if ( !( style & wxGRID_DRAW_COLS_HEADER ) ) + { + int left = pointOffSet.x; + left += ( style & wxGRID_DRAW_COLS_HEADER ) + ? - GetRowLabelSize() : 0; + dc.SetPen( GetRowGridLinePen( topLeft.GetRow() ) ); + dc.DrawLine( left, + pointOffSet.y, + right, + pointOffSet.y ); + } + + // horiz bottom line + dc.SetPen( GetRowGridLinePen( bottomRight.GetRow() ) ); + dc.DrawLine( pointOffSet.x, bottom - 1, right, bottom - 1 ); + + // left vertical line if we are not drawing row header/labels + if ( !( style & wxGRID_DRAW_ROWS_HEADER ) ) + { + int top = pointOffSet.y; + top += ( style & wxGRID_DRAW_COLS_HEADER ) + ? - GetColLabelSize() : 0; + dc.SetPen( GetColGridLinePen( topLeft.GetCol() ) ); + dc.DrawLine( pointOffSet.x -1, + top, + pointOffSet.x - 1, + bottom - 1 ); + } + + // right vertical line + dc.SetPen( GetColGridLinePen( bottomRight.GetCol() ) ); + dc.DrawLine( right, pointOffSet.y, right, bottom - 1 ); +} + void wxGridWindow::ScrollWindow( int dx, int dy, const wxRect *rect ) { wxWindow::ScrollWindow( dx, dy, rect ); @@ -1710,58 +2151,6 @@ void wxGridWindow::OnFocus(wxFocusEvent& event) ///////////////////////////////////////////////////////////////////// -#if wxUSE_EXTENDED_RTTI -WX_DEFINE_FLAGS( wxGridStyle ) - -wxBEGIN_FLAGS( wxGridStyle ) - // new style border flags, we put them first to - // use them for streaming out - wxFLAGS_MEMBER(wxBORDER_SIMPLE) - wxFLAGS_MEMBER(wxBORDER_SUNKEN) - wxFLAGS_MEMBER(wxBORDER_DOUBLE) - wxFLAGS_MEMBER(wxBORDER_RAISED) - wxFLAGS_MEMBER(wxBORDER_STATIC) - wxFLAGS_MEMBER(wxBORDER_NONE) - - // old style border flags - wxFLAGS_MEMBER(wxSIMPLE_BORDER) - wxFLAGS_MEMBER(wxSUNKEN_BORDER) - wxFLAGS_MEMBER(wxDOUBLE_BORDER) - wxFLAGS_MEMBER(wxRAISED_BORDER) - wxFLAGS_MEMBER(wxSTATIC_BORDER) - wxFLAGS_MEMBER(wxBORDER) - - // standard window styles - wxFLAGS_MEMBER(wxTAB_TRAVERSAL) - wxFLAGS_MEMBER(wxCLIP_CHILDREN) - wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) - wxFLAGS_MEMBER(wxWANTS_CHARS) - wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE) - wxFLAGS_MEMBER(wxALWAYS_SHOW_SB) - wxFLAGS_MEMBER(wxVSCROLL) - wxFLAGS_MEMBER(wxHSCROLL) - -wxEND_FLAGS( wxGridStyle ) - -IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid, wxScrolledWindow,"wx/grid.h") - -wxBEGIN_PROPERTIES_TABLE(wxGrid) - wxHIDE_PROPERTY( Children ) - wxPROPERTY_FLAGS( WindowStyle , wxGridStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style -wxEND_PROPERTIES_TABLE() - -wxBEGIN_HANDLERS_TABLE(wxGrid) -wxEND_HANDLERS_TABLE() - -wxCONSTRUCTOR_5( wxGrid , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle ) - -/* - TODO : Expose more information of a list's layout, etc. via appropriate objects (e.g., NotebookPageInfo) -*/ -#else -IMPLEMENT_DYNAMIC_CLASS( wxGrid, wxScrolledWindow ) -#endif - BEGIN_EVENT_TABLE( wxGrid, wxScrolledWindow ) EVT_PAINT( wxGrid::OnPaint ) EVT_SIZE( wxGrid::OnSize ) @@ -1784,7 +2173,6 @@ bool wxGrid::Create(wxWindow *parent, wxWindowID id, Create(); SetInitialSize(size); - SetScrollRate(m_scrollLineX, m_scrollLineY); CalcDimensions(); return true; @@ -1807,7 +2195,7 @@ wxGrid::~wxGrid() #ifdef DEBUG_ATTR_CACHE size_t total = gs_nAttrCacheHits + gs_nAttrCacheMisses; - wxPrintf(_T("wxGrid attribute cache statistics: " + wxPrintf(wxT("wxGrid attribute cache statistics: " "total: %u, hits: %u (%u%%)\n"), total, gs_nAttrCacheHits, total ? (gs_nAttrCacheHits*100) / total : 0); @@ -1822,6 +2210,9 @@ wxGrid::~wxGrid() delete m_typeRegistry; delete m_selection; + + delete m_setFixedRows; + delete m_setFixedCols; } // @@ -1970,8 +2361,7 @@ wxGrid::SetTable(wxGridTableBase *table, m_table = NULL; } - delete m_selection; - m_selection = NULL; + wxDELETE(m_selection); m_ownTable = false; m_numRows = 0; @@ -2024,6 +2414,8 @@ wxGrid::SetTable(wxGridTableBase *table, m_created = true; } + InvalidateBestSize(); + return m_created; } @@ -2047,6 +2439,9 @@ void wxGrid::Init() m_rowLabelWidth = WXGRID_DEFAULT_ROW_LABEL_WIDTH; m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT; + m_setFixedRows = + m_setFixedCols = NULL; + // init attr cache m_attrCache.row = -1; m_attrCache.col = -1; @@ -2117,8 +2512,13 @@ void wxGrid::Init() m_extraWidth = m_extraHeight = 0; - m_scrollLineX = GRID_SCROLL_LINE_X; - m_scrollLineY = GRID_SCROLL_LINE_Y; + // we can't call SetScrollRate() as the window isn't created yet but OTOH + // we don't need to call it neither as the scroll position is (0, 0) right + // now anyhow, so just set the parameters directly + m_xScrollPixelsPerLine = GRID_SCROLL_LINE_X; + m_yScrollPixelsPerLine = GRID_SCROLL_LINE_Y; + + m_tabBehaviour = Tab_Stop; } // ---------------------------------------------------------------------------- @@ -2169,13 +2569,19 @@ void wxGrid::InitColWidths() int wxGrid::GetColWidth(int col) const { - return m_colWidths.IsEmpty() ? m_defaultColWidth : m_colWidths[col]; + if ( m_colWidths.IsEmpty() ) + return m_defaultColWidth; + + // a negative width indicates a hidden column + return m_colWidths[col] > 0 ? m_colWidths[col] : 0; } int wxGrid::GetColLeft(int col) const { - return m_colRights.IsEmpty() ? GetColPos( col ) * m_defaultColWidth - : m_colRights[col] - m_colWidths[col]; + if ( m_colRights.IsEmpty() ) + return GetColPos( col ) * m_defaultColWidth; + + return m_colRights[col] - GetColWidth(col); } int wxGrid::GetColRight(int col) const @@ -2186,13 +2592,20 @@ int wxGrid::GetColRight(int col) const int wxGrid::GetRowHeight(int row) const { - return m_rowHeights.IsEmpty() ? m_defaultRowHeight : m_rowHeights[row]; + // no custom heights / hidden rows + if ( m_rowHeights.IsEmpty() ) + return m_defaultRowHeight; + + // a negative height indicates a hidden row + return m_rowHeights[row] > 0 ? m_rowHeights[row] : 0; } int wxGrid::GetRowTop(int row) const { - return m_rowBottoms.IsEmpty() ? row * m_defaultRowHeight - : m_rowBottoms[row] - m_rowHeights[row]; + if ( m_rowBottoms.IsEmpty() ) + return row * m_defaultRowHeight; + + return m_rowBottoms[row] - GetRowHeight(row); } int wxGrid::GetRowBottom(int row) const @@ -2469,7 +2882,6 @@ bool wxGrid::Redimension( wxGridTableMessage& msg ) if ( !m_colAt.IsEmpty() ) { //Shift the column IDs - int i; for ( i = 0; i < m_numCols - numCols; i++ ) { if ( m_colAt[i] >= (int)pos ) @@ -2539,7 +2951,6 @@ bool wxGrid::Redimension( wxGridTableMessage& msg ) m_colAt.Add( 0, numCols ); //Set the new columns' positions - int i; for ( i = oldNumCols; i < m_numCols; i++ ) { m_colAt[i] = i; @@ -2659,6 +3070,8 @@ bool wxGrid::Redimension( wxGridTableMessage& msg ) break; } + InvalidateBestSize(); + if (result && !GetBatchCount() ) m_gridWin->Refresh(); @@ -2772,16 +3185,20 @@ wxArrayInt wxGrid::CalcColLabelsExposed( const wxRegion& reg ) const wxGridCellCoordsArray wxGrid::CalcCellsExposed( const wxRegion& reg ) const { - wxRegionIterator iter( reg ); wxRect r; wxGridCellCoordsArray cellsExposed; int left, top, right, bottom; - while ( iter ) + for ( wxRegionIterator iter(reg); iter; ++iter ) { r = iter.GetRect(); + // Skip 0-height cells, they're invisible anyhow, don't waste time + // getting their rectangles and so on. + if ( !r.GetHeight() ) + continue; + // TODO: remove this when we can... // There is a bug in wxMotif that gives garbage update // rectangles if you jump-scroll a long way by clicking the @@ -2829,8 +3246,6 @@ wxGridCellCoordsArray wxGrid::CalcCellsExposed( const wxRegion& reg ) const for ( size_t n = 0; n < count; n++ ) cellsExposed.Add(wxGridCellCoords(row, cols[n])); } - - ++iter; } return cellsExposed; @@ -2916,11 +3331,12 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) // else if ( event.LeftDown() ) { - // don't send a label click event for a hit on the - // edge of the row label - this is probably the user - // wanting to resize the row - // - if ( YToEdgeOfRow(y) < 0 ) + row = YToEdgeOfRow(y); + if ( row != wxNOT_FOUND && CanDragRowSize(row) ) + { + ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin); + } + else // not a request to start resizing { row = YToRow(y); if ( row >= 0 && @@ -2948,12 +3364,6 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW, m_rowLabelWin); } } - else - { - // starting to drag-resize a row - if ( CanDragRowSize() ) - ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin); - } } // ------------ Left double click @@ -2961,7 +3371,19 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) else if (event.LeftDClick() ) { row = YToEdgeOfRow(y); - if ( row < 0 ) + if ( row != wxNOT_FOUND && CanDragRowSize(row) ) + { + // adjust row height depending on label text + // + // TODO: generate RESIZING event, see #10754 + AutoSizeRowLabelSize( row ); + + SendGridSizeEvent(wxEVT_GRID_ROW_SIZE, row, -1, event); + + ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow()); + m_dragLastPos = -1; + } + else // not on row separator or it's not resizable { row = YToRow(y); if ( row >=0 && @@ -2970,14 +3392,6 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) // no default action at the moment } } - else - { - // adjust row height depending on label text - AutoSizeRowLabelSize( row ); - - ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow()); - m_dragLastPos = -1; - } } // ------------ Left button released @@ -2985,14 +3399,7 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) else if ( event.LeftUp() ) { if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ) - { - DoEndDragResizeRow(); - - // Note: we are ending the event *after* doing - // default processing in this case - // - SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event ); - } + DoEndDragResizeRow(event); ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin); m_dragLastPos = -1; @@ -3027,12 +3434,11 @@ void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event ) else if ( event.Moving() ) { m_dragRowOrCol = YToEdgeOfRow( y ); - if ( m_dragRowOrCol >= 0 ) + if ( m_dragRowOrCol != wxNOT_FOUND ) { if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL ) { - // don't capture the mouse yet - if ( CanDragRowSize() ) + if ( CanDragRowSize(m_dragRowOrCol) ) ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin, false); } } @@ -3130,9 +3536,8 @@ void wxGrid::DoUpdateResizeColWidth(int w) void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) { - int x, y; - wxPoint pos( event.GetPosition() ); - CalcUnscrolledPosition( pos.x, pos.y, &x, &y ); + int x; + CalcUnscrolledPosition( event.GetPosition().x, 0, &x, NULL ); int col = XToCol(x); if ( event.Dragging() ) @@ -3248,11 +3653,12 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) // else if ( event.LeftDown() ) { - // don't send a label click event for a hit on the - // edge of the col label - this is probably the user - // wanting to resize the col - // - if ( XToEdgeOfCol(x) < 0 ) + int colEdge = XToEdgeOfCol(x); + if ( colEdge != wxNOT_FOUND && CanDragColSize(colEdge) ) + { + ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow()); + } + else // not a request to start resizing { if ( col >= 0 && !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, col, event ) ) @@ -3294,13 +3700,6 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) } } } - else - { - // starting to drag-resize a col - // - if ( CanDragColSize() ) - ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow()); - } } // ------------ Left double click @@ -3319,8 +3718,12 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) else { // adjust column width depending on label text + // + // TODO: generate RESIZING event, see #10754 AutoSizeColLabelSize( colEdge ); + SendGridSizeEvent(wxEVT_GRID_COL_SIZE, -1, colEdge, event); + ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow()); m_dragLastPos = -1; } @@ -3333,7 +3736,7 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) switch ( m_cursorMode ) { case WXGRID_CURSOR_RESIZE_COL: - DoEndDragResizeCol(); + DoEndDragResizeCol(event); break; case WXGRID_CURSOR_MOVE_COL: @@ -3346,7 +3749,34 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) } else { - DoEndMoveCol(XToPos(x)); + // get the position of the column we're over + int pos = XToPos(x); + + // we may need to adjust the drop position but don't bother + // checking for it if we can't anyhow + if ( pos > 1 ) + { + // also find the index of the column we're over: notice + // that the existing "col" variable may be invalid but + // we need a valid one here + const int colValid = GetColAt(pos); + + // if we're on the "near" (usually left but right in + // RTL case) part of the column, the actual position we + // should be placed in is actually the one before it + bool onNearPart; + const int middle = GetColLeft(colValid) + + GetColWidth(colValid)/2; + if ( GetLayoutDirection() == wxLayout_LeftToRight ) + onNearPart = (x <= middle); + else // wxLayout_RightToLeft + onNearPart = (x > middle); + + if ( onNearPart ) + pos--; + } + + DoEndMoveCol(pos); } break; @@ -3394,8 +3824,7 @@ void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event ) { if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL ) { - // don't capture the cursor yet - if ( CanDragColSize() ) + if ( CanDragColSize(m_dragRowOrCol) ) ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow(), false); } } @@ -3459,24 +3888,24 @@ void wxGrid::ChangeCursorMode(CursorMode mode, wxWindow *win, bool captureMouse) { -#ifdef __WXDEBUG__ - static const wxChar *cursorModes[] = +#if wxUSE_LOG_TRACE + static const wxChar *const cursorModes[] = { - _T("SELECT_CELL"), - _T("RESIZE_ROW"), - _T("RESIZE_COL"), - _T("SELECT_ROW"), - _T("SELECT_COL"), - _T("MOVE_COL"), + wxT("SELECT_CELL"), + wxT("RESIZE_ROW"), + wxT("RESIZE_COL"), + wxT("SELECT_ROW"), + wxT("SELECT_COL"), + wxT("MOVE_COL"), }; - wxLogTrace(_T("grid"), - _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"), - win == m_colWindow ? _T("colLabelWin") - : win ? _T("rowLabelWin") - : _T("gridWin"), + wxLogTrace(wxT("grid"), + wxT("wxGrid cursor mode (mouse capture for %s): %s -> %s"), + win == m_colWindow ? wxT("colLabelWin") + : win ? wxT("rowLabelWin") + : wxT("gridWin"), cursorModes[m_cursorMode], cursorModes[mode]); -#endif +#endif // wxUSE_LOG_TRACE if ( mode == m_cursorMode && win == m_winCapture && @@ -3531,13 +3960,15 @@ void wxGrid::ChangeCursorMode(CursorMode mode, // grid mouse event processing // ---------------------------------------------------------------------------- -void +bool wxGrid::DoGridCellDrag(wxMouseEvent& event, const wxGridCellCoords& coords, bool isFirstDrag) { + bool performDefault = true ; + if ( coords == wxGridNoCellCoords ) - return; // we're outside any valid cell + return performDefault; // we're outside any valid cell // Hide the edit control, so it won't interfere with drag-shrinking. if ( IsCellEditControlShown() ) @@ -3548,7 +3979,7 @@ wxGrid::DoGridCellDrag(wxMouseEvent& event, switch ( event.GetModifiers() ) { - case wxMOD_CMD: + case wxMOD_CONTROL: if ( m_selectedBlockCorner == wxGridNoCellCoords) m_selectedBlockCorner = coords; UpdateBlockBeingSelected(m_selectedBlockCorner, coords); @@ -3562,8 +3993,11 @@ wxGrid::DoGridCellDrag(wxMouseEvent& event, if ( m_selectedBlockCorner == wxGridNoCellCoords) m_selectedBlockCorner = coords; - SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG, coords, event); - return; + // if event is handled by user code, no further processing + if ( SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG, coords, event) != 0 ) + performDefault = false; + + return performDefault; } } @@ -3574,6 +4008,8 @@ wxGrid::DoGridCellDrag(wxMouseEvent& event, // we don't handle the other key modifiers event.Skip(); } + + return performDefault; } void wxGrid::DoGridLineDrag(wxMouseEvent& event, const wxGridOperations& oper) @@ -3626,7 +4062,9 @@ void wxGrid::DoGridDragEvent(wxMouseEvent& event, const wxGridCellCoords& coords switch ( m_cursorMode ) { case WXGRID_CURSOR_SELECT_CELL: - DoGridCellDrag(event, coords, isFirstDrag); + // no further handling if handled by user + if ( DoGridCellDrag(event, coords, isFirstDrag) == false ) + return; break; case WXGRID_CURSOR_RESIZE_ROW: @@ -3643,6 +4081,8 @@ void wxGrid::DoGridDragEvent(wxMouseEvent& event, const wxGridCellCoords& coords if ( isFirstDrag ) { + wxASSERT_MSG( !m_winCapture, "shouldn't capture the mouse twice" ); + m_winCapture = m_gridWin; m_winCapture->CaptureMouse(); } @@ -3688,6 +4128,29 @@ wxGrid::DoGridCellLeftDown(wxMouseEvent& event, } else { + if ( m_selection ) + { + // In row or column selection mode just clicking on the cell + // should select the row or column containing it: this is more + // convenient for the kinds of controls that use such selection + // mode and is compatible with 2.8 behaviour (see #12062). + switch ( m_selection->GetSelectionMode() ) + { + case wxGridSelectCells: + case wxGridSelectRowsOrColumns: + // nothing to do in these cases + break; + + case wxGridSelectRows: + m_selection->SelectRow(coords.GetRow()); + break; + + case wxGridSelectColumns: + m_selection->SelectCol(coords.GetCol()); + break; + } + } + m_waitForSlowClick = m_currentCellCoords == coords && coords != wxGridNoCellCoords; SetCurrentCell( coords ); @@ -3756,17 +4219,12 @@ wxGrid::DoGridCellLeftUp(wxMouseEvent& event, const wxGridCellCoords& coords) else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ) { ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL); - DoEndDragResizeRow(); - - // Note: we are ending the event *after* doing - // default processing in this case - // - SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event ); + DoEndDragResizeRow(event); } else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL ) { ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL); - DoEndDragResizeCol(); + DoEndDragResizeCol(event); } m_dragLastPos = -1; @@ -3796,27 +4254,24 @@ wxGrid::DoGridMouseMoveEvent(wxMouseEvent& WXUNUSED(event), return; } - if ( dragRow >= 0 ) + if ( dragRow >= 0 && CanDragGridSize() && CanDragRowSize(dragRow) ) { - m_dragRowOrCol = dragRow; - if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL ) { - if ( CanDragRowSize() && CanDragGridSize() ) - ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, NULL, false); + m_dragRowOrCol = dragRow; + ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, NULL, false); } } // When using the native header window we can only resize the columns by // dragging the dividers in it because we can't make it enter into the // column resizing mode programmatically - else if ( dragCol >= 0 && !m_useNativeHeader ) + else if ( dragCol >= 0 && !m_useNativeHeader && + CanDragGridSize() && CanDragColSize(dragCol) ) { - m_dragRowOrCol = dragCol; - if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL ) { - if ( CanDragColSize() && CanDragGridSize() ) - ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, NULL, false); + m_dragRowOrCol = dragCol; + ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, NULL, false); } } else // Neither on a row or col edge @@ -3830,6 +4285,14 @@ wxGrid::DoGridMouseMoveEvent(wxMouseEvent& WXUNUSED(event), void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event) { + if ( event.Entering() || event.Leaving() ) + { + // we don't care about these events but we must not reset m_isDragging + // if they happen so return before anything else is done + event.Skip(); + return; + } + const wxPoint pos = CalcUnscrolledPosition(event.GetPosition()); // coordinates of the cell under mouse @@ -3855,17 +4318,6 @@ void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event) m_isDragging = false; m_startDragPos = wxDefaultPosition; - // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL - // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under - // wxGTK -#if 0 - if ( event.Entering() || event.Leaving() ) - { - ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL); - m_gridWin->SetCursor( *wxSTANDARD_CURSOR ); - } -#endif // 0 - // deal with various button presses if ( event.IsButton() ) { @@ -3899,10 +4351,11 @@ void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event) } } -void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper) +// this function returns true only if the size really changed +bool wxGrid::DoEndDragResizeLine(const wxGridOperations& oper) { if ( m_dragLastPos == -1 ) - return; + return false; const wxGridOperations& doper = oper.Dual(); @@ -3926,9 +4379,12 @@ void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper) // do resize the line const int lineStart = oper.GetLineStartPos(this, m_dragRowOrCol); + const int lineSizeOld = oper.GetLineSize(this, m_dragRowOrCol); oper.SetLineSize(this, m_dragRowOrCol, wxMax(m_dragLastPos - lineStart, oper.GetMinimalLineSize(this, m_dragRowOrCol))); + const bool + sizeChanged = oper.GetLineSize(this, m_dragRowOrCol) != lineSizeOld; m_dragLastPos = -1; @@ -3962,14 +4418,14 @@ void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper) oper.SelectSize(rect) = oper.Select(size); int subtractLines = 0; - const int lineStart = oper.PosToLine(this, posLineStart); - if ( lineStart >= 0 ) + int line = doper.PosToLine(this, posLineStart); + if ( line >= 0 ) { // ensure that if we have a multi-cell block we redraw all of // it by increasing the refresh area to cover it entirely if a // part of it is affected - const int lineEnd = oper.PosToLine(this, posLineEnd, true); - for ( int line = lineStart; line < lineEnd; line++ ) + const int lineEnd = doper.PosToLine(this, posLineEnd, true); + for ( ; line < lineEnd; line++ ) { int cellLines = oper.Select( GetCellSize(oper.MakeCoords(m_dragRowOrCol, line))); @@ -3991,24 +4447,24 @@ void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper) // show the edit control back again ShowCellEditControl(); + + return sizeChanged; } -void wxGrid::DoEndDragResizeRow() +void wxGrid::DoEndDragResizeRow(const wxMouseEvent& event) { - DoEndDragResizeLine(wxGridRowOperations()); + // TODO: generate RESIZING event, see #10754 + + if ( DoEndDragResizeLine(wxGridRowOperations()) ) + SendGridSizeEvent(wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event); } -void wxGrid::DoEndDragResizeCol(wxMouseEvent *event) +void wxGrid::DoEndDragResizeCol(const wxMouseEvent& event) { - DoEndDragResizeLine(wxGridColumnOperations()); + // TODO: generate RESIZING event, see #10754 - // Note: we are ending the event *after* doing - // default processing in this case - // - if ( event ) - SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, *event ); - else - SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol ); + if ( DoEndDragResizeLine(wxGridColumnOperations()) ) + SendGridSizeEvent(wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, event); } void wxGrid::DoStartMoveCol(int col) @@ -4182,37 +4638,40 @@ wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend)(size_t), return (m_table->*funcAppend)(num); } -// -// ----- event handlers -// +// ---------------------------------------------------------------------------- +// event generation helpers +// ---------------------------------------------------------------------------- -// Generate a grid event based on a mouse event and return: -// -1 if the event was vetoed -// +1 if the event was processed (but not vetoed) -// 0 if the event wasn't handled -int -wxGrid::SendEvent(const wxEventType type, - int row, int col, - wxMouseEvent& mouseEv) +void +wxGrid::SendGridSizeEvent(wxEventType type, + int row, int col, + const wxMouseEvent& mouseEv) { - bool claimed, vetoed; + int rowOrCol = row == -1 ? col : row; - if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE ) - { - int rowOrCol = (row == -1 ? col : row); + wxGridSizeEvent gridEvt( GetId(), + type, + this, + rowOrCol, + mouseEv.GetX() + GetRowLabelSize(), + mouseEv.GetY() + GetColLabelSize(), + mouseEv); - wxGridSizeEvent gridEvt( GetId(), - type, - this, - rowOrCol, - mouseEv.GetX() + GetRowLabelSize(), - mouseEv.GetY() + GetColLabelSize(), - mouseEv); + GetEventHandler()->ProcessEvent(gridEvt); +} + +// Generate a grid event based on a mouse event and return: +// -1 if the event was vetoed +// +1 if the event was processed (but not vetoed) +// 0 if the event wasn't handled +int +wxGrid::SendEvent(const wxEventType type, + int row, int col, + const wxMouseEvent& mouseEv) +{ + bool claimed, vetoed; - claimed = GetEventHandler()->ProcessEvent(gridEvt); - vetoed = !gridEvt.IsAllowed(); - } - else if ( type == wxEVT_GRID_RANGE_SELECT ) + if ( type == wxEVT_GRID_RANGE_SELECT ) { // Right now, it should _never_ end up here! wxGridRangeSelectEvent gridEvt( GetId(), @@ -4259,6 +4718,14 @@ wxGrid::SendEvent(const wxEventType type, mouseEv.GetY() + GetColLabelSize(), false, mouseEv); + + if ( type == wxEVT_GRID_CELL_BEGIN_DRAG ) + { + // by default the dragging is not supported, the user code must + // explicitly allow the event for it to take place + gridEvt.Veto(); + } + claimed = GetEventHandler()->ProcessEvent(gridEvt); vetoed = !gridEvt.IsAllowed(); } @@ -4275,28 +4742,13 @@ wxGrid::SendEvent(const wxEventType type, int wxGrid::SendEvent(const wxEventType type, int row, int col, const wxString& s) { - bool claimed, vetoed; - - if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE ) - { - int rowOrCol = (row == -1 ? col : row); - - wxGridSizeEvent gridEvt( GetId(), type, this, rowOrCol ); - - claimed = GetEventHandler()->ProcessEvent(gridEvt); - vetoed = !gridEvt.IsAllowed(); - } - else - { - wxGridEvent gridEvt( GetId(), type, this, row, col ); - gridEvt.SetString(s); + wxGridEvent gridEvt( GetId(), type, this, row, col ); + gridEvt.SetString(s); - claimed = GetEventHandler()->ProcessEvent(gridEvt); - vetoed = !gridEvt.IsAllowed(); - } + const bool claimed = GetEventHandler()->ProcessEvent(gridEvt); // A Veto'd event may not be `claimed' so test this first - if (vetoed) + if ( !gridEvt.IsAllowed() ) return -1; return claimed ? 1 : 0; @@ -4488,52 +4940,30 @@ void wxGrid::OnKeyDown( wxKeyEvent& event ) break; case WXK_TAB: - if (event.ShiftDown()) - { - if ( GetGridCursorCol() > 0 ) - { - MoveCursorLeft( false ); - } - else - { - // at left of grid - DisableCellEditControl(); - } - } - else { - if ( GetGridCursorCol() < GetNumberCols() - 1 ) - { - MoveCursorRight( false ); - } - else + // send an event to the grid's parents for custom handling + wxGridEvent gridEvt(GetId(), wxEVT_GRID_TABBING, this, + GetGridCursorRow(), GetGridCursorCol(), + -1, -1, false, event); + if ( ProcessWindowEvent(gridEvt) ) { - // at right of grid - DisableCellEditControl(); + // the event has been handled so no need for more processing + break; } } + DoGridProcessTab( event ); break; case WXK_HOME: - if ( event.ControlDown() ) - { - GoToCell(0, 0); - } - else - { - event.Skip(); - } + GoToCell(event.ControlDown() ? 0 + : m_currentCellCoords.GetRow(), + 0); break; case WXK_END: - if ( event.ControlDown() ) - { - GoToCell(m_numRows - 1, m_numCols - 1); - } - else - { - event.Skip(); - } + GoToCell(event.ControlDown() ? m_numRows - 1 + : m_currentCellCoords.GetRow(), + m_numCols - 1); break; case WXK_PAGEUP: @@ -4653,6 +5083,69 @@ void wxGrid::OnEraseBackground(wxEraseEvent&) { } +void wxGrid::DoGridProcessTab(wxKeyboardState& kbdState) +{ + const bool isForwardTab = !kbdState.ShiftDown(); + + // TAB processing only changes when we are at the borders of the grid, so + // let's first handle the common behaviour when we are not at the border. + if ( isForwardTab ) + { + if ( GetGridCursorCol() < GetNumberCols() - 1 ) + { + MoveCursorRight( false ); + return; + } + } + else // going back + { + if ( GetGridCursorCol() ) + { + MoveCursorLeft( false ); + return; + } + } + + + // We only get here if the cursor is at the border of the grid, apply the + // configured behaviour. + switch ( m_tabBehaviour ) + { + case Tab_Stop: + // Nothing special to do, we remain at the current cell. + break; + + case Tab_Wrap: + // Go to the beginning of the next or the end of the previous row. + if ( isForwardTab ) + { + if ( GetGridCursorRow() < GetNumberRows() - 1 ) + { + GoToCell( GetGridCursorRow() + 1, 0 ); + return; + } + } + else + { + if ( GetGridCursorRow() > 0 ) + { + GoToCell( GetGridCursorRow() - 1, GetNumberCols() - 1 ); + return; + } + } + break; + + case Tab_Leave: + if ( Navigate( isForwardTab ? wxNavigationKeyEvent::IsForward + : wxNavigationKeyEvent::IsBackward ) ) + return; + break; + } + + // If we remain in this cell, stop editing it if we were doing so. + DisableCellEditControl(); +} + bool wxGrid::SetCurrentCell( const wxGridCellCoords& coords ) { if ( SendEvent(wxEVT_GRID_SELECT_CELL, coords) == -1 ) @@ -4711,6 +5204,9 @@ void wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol, int bottomRow, int rightCol) { + MakeCellVisible(m_selectedBlockCorner); + m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol); + if ( m_selection ) { switch ( m_selection->GetSelectionMode() ) @@ -4747,9 +5243,6 @@ wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol, } } - m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol); - MakeCellVisible(m_selectedBlockCorner); - EnsureFirstLessThanSecond(topRow, bottomRow); EnsureFirstLessThanSecond(leftCol, rightCol); @@ -5069,7 +5562,7 @@ void wxGrid::DrawCell( wxDC& dc, const wxGridCellCoords& coords ) // implicitly, causing this out-of order render. #if !defined(__WXMAC__) wxGridCellEditor *editor = attr->GetEditor(this, row, col); - editor->PaintBackground(rect, attr); + editor->PaintBackground(dc, rect, *attr); editor->DecRef(); #endif } @@ -5216,6 +5709,67 @@ void wxGrid::DrawHighlight(wxDC& dc, const wxGridCellCoordsArray& cells) } } +// Used by wxGrid::Render() to draw the grid lines only for the cells in the +// specified range. +void +wxGrid::DrawRangeGridLines(wxDC& dc, + const wxRegion& reg, + const wxGridCellCoords& topLeft, + const wxGridCellCoords& bottomRight) +{ + if ( !m_gridLinesEnabled ) + return; + + int top, left, width, height; + reg.GetBox( left, top, width, height ); + + // create a clipping region + wxRegion clippedcells( dc.LogicalToDeviceX( left ), + dc.LogicalToDeviceY( top ), + dc.LogicalToDeviceXRel( width ), + dc.LogicalToDeviceYRel( height ) ); + + // subtract multi cell span area from clipping region for lines + wxRect rect; + for ( int row = topLeft.GetRow(); row <= bottomRight.GetRow(); row++ ) + { + for ( int col = topLeft.GetCol(); col <= bottomRight.GetCol(); col++ ) + { + int cell_rows, cell_cols; + GetCellSize( row, col, &cell_rows, &cell_cols ); + if ( cell_rows > 1 || cell_cols > 1 ) // multi cell + { + rect = CellToRect( row, col ); + // cater for scaling + // device origin already set in ::Render() for x, y + rect.x = dc.LogicalToDeviceX( rect.x ); + rect.y = dc.LogicalToDeviceY( rect.y ); + rect.width = dc.LogicalToDeviceXRel( rect.width ); + rect.height = dc.LogicalToDeviceYRel( rect.height ) - 1; + clippedcells.Subtract( rect ); + } + else if ( cell_rows < 0 || cell_cols < 0 ) // part of multicell + { + rect = CellToRect( row + cell_rows, col + cell_cols ); + rect.x = dc.LogicalToDeviceX( rect.x ); + rect.y = dc.LogicalToDeviceY( rect.y ); + rect.width = dc.LogicalToDeviceXRel( rect.width ); + rect.height = dc.LogicalToDeviceYRel( rect.height ) - 1; + clippedcells.Subtract( rect ); + } + } + } + + dc.SetDeviceClippingRegion( clippedcells ); + + DoDrawGridLines(dc, + top, left, top + height, left + width, + topLeft.GetRow(), topLeft.GetCol(), + bottomRight.GetRow(), bottomRight.GetCol()); + + dc.DestroyClippingRegion(); +} + // This is used to redraw all grid lines e.g. when the grid line colour // has been changed // @@ -5287,9 +5841,22 @@ void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) ) dc.SetDeviceClippingRegion( clippedcells ); + DoDrawGridLines(dc, + top, left, bottom, right, + topRow, leftCol, m_numRows, m_numCols); + dc.DestroyClippingRegion(); +} + +void +wxGrid::DoDrawGridLines(wxDC& dc, + int top, int left, + int bottom, int right, + int topRow, int leftCol, + int bottomRow, int rightCol) +{ // horizontal grid lines - for ( int i = internalYToRow(top); i < m_numRows; i++ ) + for ( int i = topRow; i < bottomRow; i++ ) { int bot = GetRowBottom(i) - 1; @@ -5304,7 +5871,7 @@ void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) ) } // vertical grid lines - for ( int colPos = leftCol; colPos < m_numCols; colPos++ ) + for ( int colPos = leftCol; colPos < rightCol; colPos++ ) { int i = GetColAt( colPos ); @@ -5323,8 +5890,6 @@ void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) ) dc.DrawLine( colRight, top, colRight, bottom ); } } - - dc.DestroyClippingRegion(); } void wxGrid::DrawRowLabels( wxDC& dc, const wxArrayInt& rows) @@ -5344,32 +5909,25 @@ void wxGrid::DrawRowLabel( wxDC& dc, int row ) if ( GetRowHeight(row) <= 0 || m_rowLabelWidth <= 0 ) return; - wxRect rect; - - int rowTop = GetRowTop(row), - rowBottom = GetRowBottom(row) - 1; - - dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); - dc.DrawLine( m_rowLabelWidth - 1, rowTop, m_rowLabelWidth - 1, rowBottom ); - dc.DrawLine( 0, rowTop, 0, rowBottom ); - dc.DrawLine( 0, rowBottom, m_rowLabelWidth, rowBottom ); + wxGridCellAttrProvider * const + attrProvider = m_table ? m_table->GetAttrProvider() : NULL; - dc.SetPen( *wxWHITE_PEN ); - dc.DrawLine( 1, rowTop, 1, rowBottom ); - dc.DrawLine( 1, rowTop, m_rowLabelWidth - 1, rowTop ); + // notice that an explicit static_cast is needed to avoid a compilation + // error with VC7.1 which, for some reason, tries to instantiate (abstract) + // wxGridRowHeaderRenderer class without it + const wxGridRowHeaderRenderer& + rend = attrProvider ? attrProvider->GetRowHeaderRenderer(row) + : static_cast + (gs_defaultHeaderRenderers.rowRenderer); - dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT ); - dc.SetTextForeground( GetLabelTextColour() ); - dc.SetFont( GetLabelFont() ); + wxRect rect(0, GetRowTop(row), m_rowLabelWidth, GetRowHeight(row)); + rend.DrawBorder(*this, dc, rect); int hAlign, vAlign; - GetRowLabelAlignment( &hAlign, &vAlign ); + GetRowLabelAlignment(&hAlign, &vAlign); - rect.SetX( 2 ); - rect.SetY( GetRowTop(row) + 2 ); - rect.SetWidth( m_rowLabelWidth - 4 ); - rect.SetHeight( GetRowHeight(row) - 4 ); - DrawTextRectangle( dc, GetRowLabelValue( row ), rect, hAlign, vAlign ); + rend.DrawLabel(*this, dc, GetRowLabelValue(row), + rect, hAlign, vAlign, wxHORIZONTAL); } void wxGrid::UseNativeColHeader(bool native) @@ -5417,26 +5975,27 @@ void wxGrid::DrawColLabels( wxDC& dc,const wxArrayInt& cols ) void wxGrid::DrawCornerLabel(wxDC& dc) { + wxRect rect(wxSize(m_rowLabelWidth, m_colLabelHeight)); + if ( m_nativeColumnLabels ) { - wxRect rect(wxSize(m_rowLabelWidth, m_colLabelHeight)); rect.Deflate(1); wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin, dc, rect, 0); } else { - dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); - dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1, - m_rowLabelWidth - 1, 0 ); - dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1, - 0, m_colLabelHeight - 1 ); - dc.DrawLine( 0, 0, m_rowLabelWidth, 0 ); - dc.DrawLine( 0, 0, 0, m_colLabelHeight ); + rect.width++; + rect.height++; - dc.SetPen( *wxWHITE_PEN ); - dc.DrawLine( 1, 1, m_rowLabelWidth - 1, 1 ); - dc.DrawLine( 1, 1, 1, m_colLabelHeight - 1 ); + wxGridCellAttrProvider * const + attrProvider = m_table ? m_table->GetAttrProvider() : NULL; + const wxGridCornerHeaderRenderer& + rend = attrProvider ? attrProvider->GetCornerRenderer() + : static_cast + (gs_defaultHeaderRenderers.cornerRenderer); + + rend.DrawBorder(*this, dc, rect); } } @@ -5448,6 +6007,12 @@ void wxGrid::DrawColLabel(wxDC& dc, int col) int colLeft = GetColLeft(col); wxRect rect(colLeft, 0, GetColWidth(col), m_colLabelHeight); + wxGridCellAttrProvider * const + attrProvider = m_table ? m_table->GetAttrProvider() : NULL; + const wxGridColumnHeaderRenderer& + rend = attrProvider ? attrProvider->GetColumnHeaderRenderer(col) + : static_cast + (gs_defaultHeaderRenderers.colRenderer); if ( m_nativeColumnLabels ) { @@ -5463,34 +6028,23 @@ void wxGrid::DrawColLabel(wxDC& dc, int col) : wxHDR_SORT_ICON_DOWN : wxHDR_SORT_ICON_NONE ); + rect.Deflate(2); } else { - int colRight = GetColRight(col) - 1; - - dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW))); - dc.DrawLine( colRight, 0, - colRight, m_colLabelHeight - 1 ); - dc.DrawLine( colLeft, 0, - colRight, 0 ); - dc.DrawLine( colLeft, m_colLabelHeight - 1, - colRight + 1, m_colLabelHeight - 1 ); + // It is reported that we need to erase the background to avoid display + // artefacts, see #12055. + wxDCBrushChanger setBrush(dc, m_colWindow->GetBackgroundColour()); + dc.DrawRectangle(rect); - dc.SetPen( *wxWHITE_PEN ); - dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight - 1 ); - dc.DrawLine( colLeft, 1, colRight, 1 ); + rend.DrawBorder(*this, dc, rect); } - dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT ); - dc.SetTextForeground( GetLabelTextColour() ); - dc.SetFont( GetLabelFont() ); - int hAlign, vAlign; - GetColLabelAlignment( &hAlign, &vAlign ); + GetColLabelAlignment(&hAlign, &vAlign); const int orient = GetColLabelTextOrientation(); - rect.Deflate(2); - DrawTextRectangle(dc, GetColLabelValue(col), rect, hAlign, vAlign, orient); + rend.DrawLabel(*this, dc, GetColLabelValue(col), rect, hAlign, vAlign, orient); } // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which @@ -5500,7 +6054,7 @@ void wxGrid::DrawTextRectangle( wxDC& dc, const wxRect& rect, int horizAlign, int vertAlign, - int textOrientation ) + int textOrientation ) const { wxArrayString lines; @@ -5514,7 +6068,7 @@ void wxGrid::DrawTextRectangle(wxDC& dc, const wxRect& rect, int horizAlign, int vertAlign, - int textOrientation) + int textOrientation) const { if ( lines.empty() ) return; @@ -5733,7 +6287,7 @@ void wxGrid::EnableCellEditControl( bool enable ) return; // this should be checked by the caller! - wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") ); + wxASSERT_MSG( CanEnableCellControl(), wxT("can't enable editing for this cell!") ); // do it before ShowCellEditControl() m_cellEditCtrlEnabled = enable; @@ -5755,8 +6309,8 @@ void wxGrid::EnableCellEditControl( bool enable ) bool wxGrid::IsCurrentCellReadOnly() const { - // const_cast - wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords); + wxGridCellAttr* + attr = const_cast(this)->GetCellAttr(m_currentCellCoords); bool readonly = attr->IsReadOnly(); attr->DecRef(); @@ -6015,8 +6569,8 @@ wxGridCellCoords wxGrid::XYToCell(int x, int y) const // compute row or column from some (unscrolled) coordinate value, using either // m_defaultRowHeight/m_defaultColWidth or binary search on array of -// m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used -// for large grids) +// m_rowBottoms/m_colRights to do it quickly in O(log n) time. +// NOTE: This may not work correctly for reordered columns. int wxGrid::PosToLinePos(int coord, bool clipToMinMax, const wxGridOperations& oper) const @@ -6044,26 +6598,11 @@ int wxGrid::PosToLinePos(int coord, } - // adjust maxPos before starting the binary search - if ( maxPos >= numLines ) - { - maxPos = numLines - 1; - } - else - { - if ( coord >= lineEnds[oper.GetLineAt(this, maxPos)]) - { - minPos = maxPos; - const int minDist = oper.GetMinimalAcceptableLineSize(this); - if ( minDist ) - maxPos = coord / minDist; - else - maxPos = numLines - 1; - } - - if ( maxPos >= numLines ) - maxPos = numLines - 1; - } + // binary search is quite efficient and we can't really make any assumptions + // on where to start here since row and columns could be of size 0 if they are + // hidden. While this could be made more efficient, some profiling will be + // necessary to determine if it really is a performance bottleneck + maxPos = numLines - 1; // check if the position is beyond the last column const int lineAtMaxPos = oper.GetLineAt(this, maxPos); @@ -6124,23 +6663,15 @@ int wxGrid::XToPos(int x) const return PosToLinePos(x, true /* clip */, wxGridColumnOperations()); } -// return the row number that that the y coord is near the edge of, or -1 if +// return the row number such that the y coord is near the edge of, or -1 if // not near an edge. // -// coords can only possibly be near an edge if -// (a) the row/column is large enough to still allow for an "inner" area -// that is _not_ near the edge (i.e., if the height/width is smaller -// than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be -// near the edge). -// and -// (b) resizing rows/columns (the thing for which edge detection is -// relevant at all) is enabled. -// +// notice that position can only possibly be near an edge if the row/column is +// large enough to still allow for an "inner" area that is _not_ near the edge +// (i.e., if the height/width is smaller than WXGRID_LABEL_EDGE_ZONE, pos will +// _never_ be considered to be near the edge). int wxGrid::PosToEdgeOfLine(int pos, const wxGridOperations& oper) const { - if ( !oper.CanResizeLines(this) ) - return -1; - const int line = oper.PosToLine(this, pos, true); if ( oper.GetLineSize(this, line) > WXGRID_LABEL_EDGE_ZONE ) @@ -6152,7 +6683,9 @@ int wxGrid::PosToEdgeOfLine(int pos, const wxGridOperations& oper) const else if ( line > 0 && pos - oper.GetLineStartPos(this, line) < WXGRID_LABEL_EDGE_ZONE ) - return line - 1; + { + return oper.GetLineBefore(this, line); + } } return -1; @@ -6280,7 +6813,7 @@ void wxGrid::MakeCellVisible( int row, int col ) // // Sometimes GRID_SCROLL_LINE / 2 is not enough, // so just add a full scroll unit... - ypos += m_scrollLineY; + ypos += m_yScrollPixelsPerLine; } // special handling for wide cells - show always left part of the cell! @@ -6299,15 +6832,15 @@ void wxGrid::MakeCellVisible( int row, int col ) xpos = x0 + (right - cw); // see comment for ypos above - xpos += m_scrollLineX; + xpos += m_xScrollPixelsPerLine; } if ( xpos != -1 || ypos != -1 ) { if ( xpos != -1 ) - xpos /= m_scrollLineX; + xpos /= m_xScrollPixelsPerLine; if ( ypos != -1 ) - ypos /= m_scrollLineY; + ypos /= m_yScrollPixelsPerLine; Scroll( xpos, ypos ); AdjustScrollbars(); } @@ -6588,6 +7121,7 @@ void wxGrid::SetRowLabelSize( int width ) } m_rowLabelWidth = width; + InvalidateBestSize(); CalcWindowSizes(); wxScrolledWindow::Refresh( true ); } @@ -6617,6 +7151,7 @@ void wxGrid::SetColLabelSize( int height ) } m_colLabelHeight = height; + InvalidateBestSize(); CalcWindowSizes(); wxScrolledWindow::Refresh( true ); } @@ -6822,7 +7357,7 @@ void wxGrid::SetCellHighlightPenWidth(int width) m_cellHighlightPenWidth = width; // Just redrawing the cell highlight is not enough since that won't - // make any visible change if the the thickness is getting smaller. + // make any visible change if the thickness is getting smaller. int row = m_currentCellCoords.GetRow(); int col = m_currentCellCoords.GetCol(); if ( row == -1 || col == -1 || GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 ) @@ -6840,7 +7375,7 @@ void wxGrid::SetCellHighlightROPenWidth(int width) m_cellHighlightROPenWidth = width; // Just redrawing the cell highlight is not enough since that won't - // make any visible change if the the thickness is getting smaller. + // make any visible change if the thickness is getting smaller. int row = m_currentCellCoords.GetRow(); int col = m_currentCellCoords.GetCol(); if ( row == -1 || col == -1 || @@ -6898,7 +7433,7 @@ int wxGrid::GetDefaultRowSize() const int wxGrid::GetRowSize( int row ) const { - wxCHECK_MSG( row >= 0 && row < m_numRows, 0, _T("invalid row index") ); + wxCHECK_MSG( row >= 0 && row < m_numRows, 0, wxT("invalid row index") ); return GetRowHeight(row); } @@ -6910,7 +7445,7 @@ int wxGrid::GetDefaultColSize() const int wxGrid::GetColSize( int col ) const { - wxCHECK_MSG( col >= 0 && col < m_numCols, 0, _T("invalid column index") ); + wxCHECK_MSG( col >= 0 && col < m_numCols, 0, wxT("invalid column index") ); return GetColWidth(col); } @@ -7057,11 +7592,21 @@ bool wxGrid::GetCellOverflow( int row, int col ) const return allow; } -void wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const +wxGrid::CellSpan +wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const { wxGridCellAttr *attr = GetCellAttr(row, col); attr->GetSize( num_rows, num_cols ); attr->DecRef(); + + if ( *num_rows == 1 && *num_cols == 1 ) + return CellSpan_None; // just a normal cell + + if ( *num_rows < 0 || *num_cols < 0 ) + return CellSpan_Inside; // covered by a multi-span cell + + // this cell spans multiple cells to its right/bottom + return CellSpan_Main; } wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col) const @@ -7120,11 +7665,18 @@ void wxGrid::ClearAttrCache() } } +void wxGrid::RefreshAttr(int row, int col) +{ + if ( m_attrCache.row == row && m_attrCache.col == col ) + ClearAttrCache(); +} + + void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const { if ( attr != NULL ) { - wxGrid *self = (wxGrid *)this; // const_cast + wxGrid * const self = const_cast(this); self->ClearAttrCache(); self->m_attrCache.row = row; @@ -7190,8 +7742,8 @@ wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const wxGridCellAttr *attr = NULL; bool canHave = ((wxGrid*)this)->CanHaveAttributes(); - wxCHECK_MSG( canHave, attr, _T("Cell attributes not allowed")); - wxCHECK_MSG( m_table, attr, _T("must have a table") ); + wxCHECK_MSG( canHave, attr, wxT("Cell attributes not allowed")); + wxCHECK_MSG( m_table, attr, wxT("must have a table") ); attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell); if ( !attr ) @@ -7225,7 +7777,7 @@ void wxGrid::SetColFormatFloat(int col, int width, int precision) wxString typeName = wxGRID_VALUE_FLOAT; if ( (width != -1) || (precision != -1) ) { - typeName << _T(':') << width << _T(',') << precision; + typeName << wxT(':') << width << wxT(',') << precision; } SetColFormatCustom(col, typeName); @@ -7481,6 +8033,22 @@ wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) // row/col size // ---------------------------------------------------------------------------- +void wxGrid::DoDisableLineResize(int line, wxGridFixedIndicesSet *& setFixed) +{ + if ( !setFixed ) + { + setFixed = new wxGridFixedIndicesSet; + } + + setFixed->insert(line); +} + +bool +wxGrid::DoCanResizeLine(int line, const wxGridFixedIndicesSet *setFixed) const +{ + return !setFixed || !setFixed->count(line); +} + void wxGrid::EnableDragRowSize( bool enable ) { m_canDragRowSize = enable; @@ -7518,13 +8086,69 @@ void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows ) } } +namespace +{ + +// This is a common part of SetRowSize() and SetColSize() which takes care of +// updating the height/width of a row/column depending on its current value and +// the new one. +// +// Returns the difference between the new and the old size. +int UpdateRowOrColSize(int& sizeCurrent, int sizeNew) +{ + // On input here sizeCurrent can be negative if it's currently hidden (the + // real size is its absolute value then). And sizeNew can be 0 to indicate + // that the row/column should be hidden or -1 to indicate that it should be + // shown again. + + if ( sizeNew < 0 ) + { + // We're showing back a previously hidden row/column. + wxASSERT_MSG( sizeNew == -1, wxS("New size must be positive or -1.") ); + + wxASSERT_MSG( sizeCurrent < 0, wxS("May only show back if hidden.") ); + + sizeCurrent = -sizeCurrent; + + // This is positive which is correct. + return sizeCurrent; + } + else if ( sizeNew == 0 ) + { + // We're hiding a row/column. + wxASSERT_MSG( sizeCurrent > 0, wxS("Can't hide if already hidden.") ); + + sizeCurrent = -sizeCurrent; + + // This is negative which is correct. + return sizeCurrent; + } + else // We're just changing the row/column size. + { + // Here it could have been hidden or not previously. + const int sizeOld = sizeCurrent < 0 ? 0 : sizeCurrent; + + sizeCurrent = sizeNew; + + return sizeCurrent - sizeOld; + } +} + +} // anonymous namespace + void wxGrid::SetRowSize( int row, int height ) { - wxCHECK_RET( row >= 0 && row < m_numRows, _T("invalid row index") ); + // See comment in SetColSize + if ( height > 0 && height < GetRowMinimalAcceptableHeight()) + return; - // if < 0 then calculate new height from label - if ( height < 0 ) + // The value of -1 is special and means to fit the height to the row label. + if ( height == -1 ) { + // As with the columns, ignore attempts to auto-size the hidden rows. + if ( GetRowHeight(row) == 0 ) + return; + long w, h; wxArrayString lines; wxClientDC dc(m_rowLabelWin); @@ -7535,9 +8159,12 @@ void wxGrid::SetRowSize( int row, int height ) height = wxMax(h, GetRowMinimalAcceptableHeight()); } - // See comment in SetColSize - if ( height < GetRowMinimalAcceptableHeight()) - return; + DoSetRowSize(row, height); +} + +void wxGrid::DoSetRowSize( int row, int height ) +{ + wxCHECK_RET( row >= 0 && row < m_numRows, wxT("invalid row index") ); if ( m_rowHeights.IsEmpty() ) { @@ -7545,17 +8172,22 @@ void wxGrid::SetRowSize( int row, int height ) InitRowHeights(); } - int h = wxMax( 0, height ); - int diff = h - m_rowHeights[row]; + const int diff = UpdateRowOrColSize(m_rowHeights[row], height); + if ( !diff ) + return; - m_rowHeights[row] = h; for ( int i = row; i < m_numRows; i++ ) { m_rowBottoms[i] += diff; } + InvalidateBestSize(); + if ( !GetBatchCount() ) + { CalcDimensions(); + Refresh(); + } } void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols ) @@ -7578,11 +8210,23 @@ void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols ) void wxGrid::SetColSize( int col, int width ) { - wxCHECK_RET( col >= 0 && col < m_numCols, _T("invalid column index") ); + // we intentionally don't test whether the width is less than + // GetColMinimalWidth() here but we do compare it with + // GetColMinimalAcceptableWidth() as otherwise things currently break (see + // #651) -- and we also always allow the width of 0 as it has the special + // sense of hiding the column + if ( width > 0 && width < GetColMinimalAcceptableWidth() ) + return; - // if < 0 then calculate new width from label - if ( width < 0 ) + // The value of -1 is special and means to fit the width to the column label. + if ( width == -1 ) { + // We currently don't support auto-sizing hidden columns. We could, but + // it's not clear whether this is really needed and it would make the + // code more complex. + if ( GetColWidth(col) == 0 ) + return; + long w, h; wxArrayString lines; wxClientDC dc(m_colWindow); @@ -7597,13 +8241,12 @@ void wxGrid::SetColSize( int col, int width ) width = wxMax(width, GetColMinimalAcceptableWidth()); } - // we intentionally don't test whether the width is less than - // GetColMinimalWidth() here but we do compare it with - // GetColMinimalAcceptableWidth() as otherwise things currently break (see - // #651) -- and we also always allow the width of 0 as it has the special - // sense of hiding the column - if ( width > 0 && width < GetColMinimalAcceptableWidth() ) - return; + DoSetColSize(col, width); +} + +void wxGrid::DoSetColSize( int col, int width ) +{ + wxCHECK_RET( col >= 0 && col < m_numCols, wxT("invalid column index") ); if ( m_colWidths.IsEmpty() ) { @@ -7611,8 +8254,10 @@ void wxGrid::SetColSize( int col, int width ) InitColWidths(); } - const int diff = width - m_colWidths[col]; - m_colWidths[col] = width; + const int diff = UpdateRowOrColSize(m_colWidths[col], width); + if ( !diff ) + return; + if ( m_useNativeHeader ) GetGridColHeader()->UpdateColumn(col); //else: will be refreshed when the header is redrawn @@ -7622,6 +8267,8 @@ void wxGrid::SetColSize( int col, int width ) m_colRights[GetColAt(colPos)] += diff; } + InvalidateBestSize(); + if ( !GetBatchCount() ) { CalcDimensions(); @@ -7698,35 +8345,91 @@ wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction) { const bool column = direction == wxGRID_COLUMN; + // We don't support auto-sizing hidden rows or columns, this doesn't seem + // to make much sense. + if ( column ) + { + if ( GetColWidth(colOrRow) == 0 ) + return; + } + else + { + if ( GetRowHeight(colOrRow) == 0 ) + return; + } + wxClientDC dc(m_gridWin); // cancel editing of cell HideCellEditControl(); SaveEditControlValue(); - // init both of them to avoid compiler warnings, even if we only need one - int row = -1, - col = -1; + // initialize both of them just to avoid compiler warnings even if only + // really needs to be initialized here + int row, + col; if ( column ) + { + row = -1; col = colOrRow; + } else + { row = colOrRow; + col = -1; + } wxCoord extent, extentMax = 0; int max = column ? m_numRows : m_numCols; for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ ) { if ( column ) + { row = rowOrCol; + col = colOrRow; + } else + { + row = colOrRow; col = rowOrCol; + } + // we need to account for the cells spanning multiple columns/rows: + // while they may need a lot of space, they don't need all of it in + // this column/row + int numRows, numCols; + const CellSpan span = GetCellSize(row, col, &numRows, &numCols); + if ( span == CellSpan_Inside ) + { + // we need to get the size of the main cell, not of a cell hidden + // by it + row += numRows; + col += numCols; + + // get the size of the main cell too + GetCellSize(row, col, &numRows, &numCols); + } + + // get cell ( main cell if CellSpan_Inside ) renderer best size wxGridCellAttr *attr = GetCellAttr(row, col); wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col); if ( renderer ) { wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col); extent = column ? size.x : size.y; + + if ( span != CellSpan_None ) + { + // we spread the size of a spanning cell over all the cells it + // covers evenly -- this is probably not ideal but we can't + // really do much better here + // + // notice that numCols and numRows are never 0 as they + // correspond to the size of the main cell of the span and not + // of the cell inside it + extent /= column ? numCols : numRows; + } + if ( extent > extentMax ) extentMax = extent; @@ -7742,12 +8445,12 @@ wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction) if ( column ) { - dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h ); + dc.GetMultiLineTextExtent( GetColLabelValue(colOrRow), &w, &h ); if ( GetColLabelTextOrientation() == wxVERTICAL ) w = h; } else - dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h ); + dc.GetMultiLineTextExtent( GetRowLabelValue(colOrRow), &w, &h ); extent = column ? w : h; if ( extent > extentMax ) @@ -7774,20 +8477,20 @@ wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction) // comment in SetColSize() for explanation of why this isn't done // in SetColSize(). if ( !setAsMin ) - extentMax = wxMax(extentMax, GetColMinimalWidth(col)); + extentMax = wxMax(extentMax, GetColMinimalWidth(colOrRow)); - SetColSize( col, extentMax ); + SetColSize( colOrRow, extentMax ); if ( !GetBatchCount() ) { if ( m_useNativeHeader ) { - GetGridColHeader()->UpdateColumn(col); + GetGridColHeader()->UpdateColumn(colOrRow); } else { int cw, ch, dummy; m_gridWin->GetClientSize( &cw, &ch ); - wxRect rect ( CellToRect( 0, col ) ); + wxRect rect ( CellToRect( 0, colOrRow ) ); rect.y = 0; CalcScrolledPosition(rect.x, 0, &rect.x, &dummy); rect.width = cw - rect.x; @@ -7802,14 +8505,14 @@ wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction) // comment in SetColSize() for explanation of why this isn't done // in SetRowSize(). if ( !setAsMin ) - extentMax = wxMax(extentMax, GetRowMinimalHeight(row)); + extentMax = wxMax(extentMax, GetRowMinimalHeight(colOrRow)); - SetRowSize(row, extentMax); + SetRowSize(colOrRow, extentMax); if ( !GetBatchCount() ) { int cw, ch, dummy; m_gridWin->GetClientSize( &cw, &ch ); - wxRect rect( CellToRect( row, 0 ) ); + wxRect rect( CellToRect( colOrRow, 0 ) ); rect.x = 0; CalcScrolledPosition(0, rect.y, &dummy, &rect.y); rect.width = m_rowLabelWidth; @@ -7821,9 +8524,9 @@ wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction) if ( setAsMin ) { if ( column ) - SetColMinimalWidth(col, extentMax); + SetColMinimalWidth(colOrRow, extentMax); else - SetRowMinimalHeight(row, extentMax); + SetRowMinimalHeight(colOrRow, extentMax); } } @@ -7928,10 +8631,8 @@ void wxGrid::AutoSize() // we know that we're not going to have scrollbars so disable them now to // avoid trouble in SetClientSize() which can otherwise set the correct // client size but also leave space for (not needed any more) scrollbars - SetScrollbars(0, 0, 0, 0, 0, 0, true); - - // restore the scroll rate parameters overwritten by SetScrollbars() - SetScrollRate(m_scrollLineX, m_scrollLineY); + SetScrollbars(m_xScrollPixelsPerLine, m_yScrollPixelsPerLine, + 0, 0, 0, 0, true); SetClientSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight); } @@ -7948,6 +8649,7 @@ void wxGrid::AutoSizeRowLabelSize( int row ) // autosize row height depending on label text SetRowSize(row, -1); + ForceRefresh(); } @@ -7963,23 +8665,19 @@ void wxGrid::AutoSizeColLabelSize( int col ) // autosize column width depending on label text SetColSize(col, -1); + ForceRefresh(); } wxSize wxGrid::DoGetBestSize() const { - wxGrid *self = (wxGrid *)this; // const_cast + wxGrid * const self = const_cast(this); // we do the same as in AutoSize() here with the exception that we don't // change the column/row sizes, only calculate them wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth, self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight); - // NOTE: This size should be cached, but first we need to add calls to - // InvalidateBestSize everywhere that could change the results of this - // calculation. - // CacheBestSize(size); - return wxSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight) + GetWindowBorderSize(); } @@ -7989,10 +8687,12 @@ void wxGrid::Fit() AutoSize(); } +#if WXWIN_COMPATIBILITY_2_8 wxPen& wxGrid::GetDividerPen() const { return wxNullPen; } +#endif // WXWIN_COMPATIBILITY_2_8 // ---------------------------------------------------------------------------- // cell value accessor functions @@ -8083,7 +8783,8 @@ void wxGrid::DeselectLine(int line, const wxGridOperations& oper) return; const wxGridSelectionModes mode = m_selection->GetSelectionMode(); - if ( mode == oper.GetSelectionMode() ) + if ( mode == oper.GetSelectionMode() || + mode == wxGrid::wxGridSelectRowsOrColumns ) { const wxGridCellCoords c(oper.MakeCoords(line, 0)); if ( m_selection->IsInSelection(c) ) @@ -8375,7 +9076,16 @@ int wxGridSizesInfo::GetSize(unsigned pos) const { wxUnsignedToIntHashMap::const_iterator it = m_customSizes.find(pos); - return it == m_customSizes.end() ? m_sizeDefault : it->second; + // if it's not found return the default + if ( it == m_customSizes.end() ) + return m_sizeDefault; + + // otherwise return 0 if it's hidden, currently there is no way to get + // its size before it had been hidden + if ( it->second < 0 ) + return 0; + + return it->second; } // ---------------------------------------------------------------------------- @@ -8565,7 +9275,7 @@ int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName) { // the first part of the typename is the "real" type, anything after ':' // are the parameters for the renderer - index = FindDataType(typeName.BeforeFirst(_T(':'))); + index = FindDataType(typeName.BeforeFirst(wxT(':'))); if ( index == wxNOT_FOUND ) { return wxNOT_FOUND; @@ -8582,7 +9292,7 @@ int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName) editorOld->DecRef(); // do it even if there are no parameters to reset them to defaults - wxString params = typeName.AfterFirst(_T(':')); + wxString params = typeName.AfterFirst(wxT(':')); renderer->SetParameters(params); editor->SetParameters(params);