1 ///////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/grid.cpp
3 // Purpose: wxGrid and related classes
4 // Author: Michael Bedward (based on code by Julian Smart, Robin Dunn)
5 // Modified by: Robin Dunn, Vadim Zeitlin, Santiago Palacios
8 // Copyright: (c) Michael Bedward (mbedward@ozemail.com.au)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
15 - Replace use of wxINVERT with wxOverlay
16 - Make Begin/EndBatch() the same as the generic Freeze/Thaw()
17 - Review the column reordering code, it's a mess.
18 - Implement row reordering after dealing with the columns.
21 // For compilers that support precompilation, includes "wx/wx.h".
22 #include "wx/wxprec.h"
34 #include "wx/dcclient.h"
35 #include "wx/settings.h"
37 #include "wx/textctrl.h"
38 #include "wx/checkbox.h"
39 #include "wx/combobox.h"
40 #include "wx/valtext.h"
43 #include "wx/listbox.h"
46 #include "wx/textfile.h"
47 #include "wx/spinctrl.h"
48 #include "wx/tokenzr.h"
49 #include "wx/renderer.h"
50 #include "wx/headerctrl.h"
52 #include "wx/generic/gridsel.h"
54 const char wxGridNameStr
[] = "grid";
56 #if defined(__WXMOTIF__)
57 #define WXUNUSED_MOTIF(identifier) WXUNUSED(identifier)
59 #define WXUNUSED_MOTIF(identifier) identifier
62 #if defined(__WXGTK__)
63 #define WXUNUSED_GTK(identifier) WXUNUSED(identifier)
65 #define WXUNUSED_GTK(identifier) identifier
68 // Required for wxIs... functions
71 // ----------------------------------------------------------------------------
73 // ----------------------------------------------------------------------------
75 WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridCellAttr
*, wxArrayAttrs
,
76 class WXDLLIMPEXP_ADV
);
78 struct wxGridCellWithAttr
80 wxGridCellWithAttr(int row
, int col
, wxGridCellAttr
*attr_
)
81 : coords(row
, col
), attr(attr_
)
86 wxGridCellWithAttr(const wxGridCellWithAttr
& other
)
87 : coords(other
.coords
),
93 wxGridCellWithAttr
& operator=(const wxGridCellWithAttr
& other
)
95 coords
= other
.coords
;
96 if (attr
!= other
.attr
)
105 void ChangeAttr(wxGridCellAttr
* new_attr
)
107 if (attr
!= new_attr
)
109 // "Delete" (i.e. DecRef) the old attribute.
112 // Take ownership of the new attribute, i.e. no IncRef.
116 ~wxGridCellWithAttr()
121 wxGridCellCoords coords
;
122 wxGridCellAttr
*attr
;
125 WX_DECLARE_OBJARRAY_WITH_DECL(wxGridCellWithAttr
, wxGridCellWithAttrArray
,
126 class WXDLLIMPEXP_ADV
);
128 #include "wx/arrimpl.cpp"
130 WX_DEFINE_OBJARRAY(wxGridCellCoordsArray
)
131 WX_DEFINE_OBJARRAY(wxGridCellWithAttrArray
)
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_LEFT_CLICK
)
138 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_RIGHT_CLICK
)
139 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_LEFT_DCLICK
)
140 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_RIGHT_DCLICK
)
141 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_BEGIN_DRAG
)
142 DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_LEFT_CLICK
)
143 DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_RIGHT_CLICK
)
144 DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_LEFT_DCLICK
)
145 DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_RIGHT_DCLICK
)
146 DEFINE_EVENT_TYPE(wxEVT_GRID_ROW_SIZE
)
147 DEFINE_EVENT_TYPE(wxEVT_GRID_COL_SIZE
)
148 DEFINE_EVENT_TYPE(wxEVT_GRID_COL_MOVE
)
149 DEFINE_EVENT_TYPE(wxEVT_GRID_COL_SORT
)
150 DEFINE_EVENT_TYPE(wxEVT_GRID_RANGE_SELECT
)
151 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_CHANGE
)
152 DEFINE_EVENT_TYPE(wxEVT_GRID_SELECT_CELL
)
153 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_SHOWN
)
154 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_HIDDEN
)
155 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_CREATED
)
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 // header column providing access to the column information stored in wxGrid
162 // via wxHeaderColumn interface
163 class wxGridHeaderColumn
: public wxHeaderColumn
166 wxGridHeaderColumn(wxGrid
*grid
, int col
)
172 virtual wxString
GetTitle() const { return m_grid
->GetColLabelValue(m_col
); }
173 virtual wxBitmap
GetBitmap() const { return wxNullBitmap
; }
174 virtual int GetWidth() const { return m_grid
->GetColSize(m_col
); }
175 virtual int GetMinWidth() const { return 0; }
176 virtual wxAlignment
GetAlignment() const
180 m_grid
->GetColLabelAlignment(&horz
, &vert
);
182 return static_cast<wxAlignment
>(horz
);
185 virtual int GetFlags() const
187 // we can't know in advance whether we can sort by this column or not
188 // with wxGrid API so suppose we can by default
189 int flags
= wxCOL_SORTABLE
;
190 if ( m_grid
->CanDragColSize() )
191 flags
|= wxCOL_RESIZABLE
;
192 if ( m_grid
->CanDragColMove() )
193 flags
|= wxCOL_REORDERABLE
;
194 if ( GetWidth() == 0 )
195 flags
|= wxCOL_HIDDEN
;
200 virtual bool IsSortKey() const
202 return m_grid
->IsSortingBy(m_col
);
205 virtual bool IsSortOrderAscending() const
207 return m_grid
->IsSortOrderAscending();
211 // these really should be const but are not because the column needs to be
212 // assignable to be used in a wxVector (in STL build, in non-STL build we
213 // avoid the need for this)
218 // header control retreiving column information from the grid
219 class wxGridHeaderCtrl
: public wxHeaderCtrl
222 wxGridHeaderCtrl(wxGrid
*owner
)
223 : wxHeaderCtrl(owner
,
228 (owner
->CanDragColMove() ? wxHD_ALLOW_REORDER
: 0))
233 virtual const wxHeaderColumn
& GetColumn(unsigned int idx
) const
235 return m_columns
[idx
];
239 wxGrid
*GetOwner() const { return static_cast<wxGrid
*>(GetParent()); }
241 // override the base class method to update our m_columns array
242 virtual void OnColumnCountChanging(unsigned int count
)
244 const unsigned countOld
= m_columns
.size();
245 if ( count
< countOld
)
247 // just discard the columns which don't exist any more (notice that
248 // we can't use resize() here as it would require the vector
249 // value_type, i.e. wxGridHeaderColumn to be default constructible,
251 m_columns
.erase(m_columns
.begin() + count
, m_columns
.end());
253 else // new columns added
255 // add columns for the new elements
256 for ( unsigned n
= countOld
; n
< count
; n
++ )
257 m_columns
.push_back(wxGridHeaderColumn(GetOwner(), n
));
261 // override to implement column auto sizing
262 virtual bool UpdateColumnWidthToFit(unsigned int idx
, int widthTitle
)
264 // TODO: currently grid doesn't support computing the column best width
265 // from its contents so we just use the best label width as is
266 GetOwner()->SetColSize(idx
, widthTitle
);
271 // overridden to react to the actions using the columns popup menu
272 virtual void UpdateColumnVisibility(unsigned int idx
, bool show
)
274 GetOwner()->SetColSize(idx
, show
? wxGRID_AUTOSIZE
: 0);
276 // as this is done by the user we should notify the main program about
278 GetOwner()->SendEvent(wxEVT_GRID_COL_SIZE
, -1, idx
);
281 // overridden to react to the columns order changes in the customization
283 virtual void UpdateColumnsOrder(const wxArrayInt
& order
)
285 GetOwner()->SetColumnsOrder(order
);
289 // event handlers forwarding wxHeaderCtrl events to wxGrid
290 void OnClick(wxHeaderCtrlEvent
& event
)
292 GetOwner()->DoColHeaderClick(event
.GetColumn());
295 void OnBeginResize(wxHeaderCtrlEvent
& event
)
297 GetOwner()->DoStartResizeCol(event
.GetColumn());
302 void OnResizing(wxHeaderCtrlEvent
& event
)
304 GetOwner()->DoUpdateResizeColWidth(event
.GetWidth());
307 void OnEndResize(wxHeaderCtrlEvent
& event
)
309 GetOwner()->DoEndDragResizeCol();
314 void OnBeginReorder(wxHeaderCtrlEvent
& event
)
316 GetOwner()->DoStartMoveCol(event
.GetColumn());
319 void OnEndReorder(wxHeaderCtrlEvent
& event
)
321 GetOwner()->DoEndMoveCol(event
.GetNewOrder());
324 wxVector
<wxGridHeaderColumn
> m_columns
;
326 DECLARE_EVENT_TABLE()
327 DECLARE_NO_COPY_CLASS(wxGridHeaderCtrl
)
330 BEGIN_EVENT_TABLE(wxGridHeaderCtrl
, wxHeaderCtrl
)
331 EVT_HEADER_CLICK(wxID_ANY
, wxGridHeaderCtrl::OnClick
)
333 EVT_HEADER_BEGIN_RESIZE(wxID_ANY
, wxGridHeaderCtrl::OnBeginResize
)
334 EVT_HEADER_RESIZING(wxID_ANY
, wxGridHeaderCtrl::OnResizing
)
335 EVT_HEADER_END_RESIZE(wxID_ANY
, wxGridHeaderCtrl::OnEndResize
)
337 EVT_HEADER_BEGIN_REORDER(wxID_ANY
, wxGridHeaderCtrl::OnBeginReorder
)
338 EVT_HEADER_END_REORDER(wxID_ANY
, wxGridHeaderCtrl::OnEndReorder
)
341 // common base class for various grid subwindows
342 class WXDLLIMPEXP_ADV wxGridSubwindow
: public wxWindow
345 wxGridSubwindow(wxGrid
*owner
,
346 int additionalStyle
= 0,
347 const wxString
& name
= wxPanelNameStr
)
348 : wxWindow(owner
, wxID_ANY
,
349 wxDefaultPosition
, wxDefaultSize
,
350 wxBORDER_NONE
| additionalStyle
,
356 virtual bool AcceptsFocus() const { return false; }
358 wxGrid
*GetOwner() { return m_owner
; }
361 void OnMouseCaptureLost(wxMouseCaptureLostEvent
& event
);
365 DECLARE_EVENT_TABLE()
366 DECLARE_NO_COPY_CLASS(wxGridSubwindow
)
369 class WXDLLIMPEXP_ADV wxGridRowLabelWindow
: public wxGridSubwindow
372 wxGridRowLabelWindow(wxGrid
*parent
)
373 : wxGridSubwindow(parent
)
379 void OnPaint( wxPaintEvent
& event
);
380 void OnMouseEvent( wxMouseEvent
& event
);
381 void OnMouseWheel( wxMouseEvent
& event
);
383 DECLARE_EVENT_TABLE()
384 DECLARE_NO_COPY_CLASS(wxGridRowLabelWindow
)
388 class WXDLLIMPEXP_ADV wxGridColLabelWindow
: public wxGridSubwindow
391 wxGridColLabelWindow(wxGrid
*parent
)
392 : wxGridSubwindow(parent
)
398 void OnPaint( wxPaintEvent
& event
);
399 void OnMouseEvent( wxMouseEvent
& event
);
400 void OnMouseWheel( wxMouseEvent
& event
);
402 DECLARE_EVENT_TABLE()
403 DECLARE_NO_COPY_CLASS(wxGridColLabelWindow
)
407 class WXDLLIMPEXP_ADV wxGridCornerLabelWindow
: public wxGridSubwindow
410 wxGridCornerLabelWindow(wxGrid
*parent
)
411 : wxGridSubwindow(parent
)
416 void OnMouseEvent( wxMouseEvent
& event
);
417 void OnMouseWheel( wxMouseEvent
& event
);
418 void OnPaint( wxPaintEvent
& event
);
420 DECLARE_EVENT_TABLE()
421 DECLARE_NO_COPY_CLASS(wxGridCornerLabelWindow
)
424 class WXDLLIMPEXP_ADV wxGridWindow
: public wxGridSubwindow
427 wxGridWindow(wxGrid
*parent
)
428 : wxGridSubwindow(parent
,
429 wxWANTS_CHARS
| wxCLIP_CHILDREN
,
435 virtual void ScrollWindow( int dx
, int dy
, const wxRect
*rect
);
437 virtual bool AcceptsFocus() const { return true; }
440 void OnPaint( wxPaintEvent
&event
);
441 void OnMouseWheel( wxMouseEvent
& event
);
442 void OnMouseEvent( wxMouseEvent
& event
);
443 void OnKeyDown( wxKeyEvent
& );
444 void OnKeyUp( wxKeyEvent
& );
445 void OnChar( wxKeyEvent
& );
446 void OnEraseBackground( wxEraseEvent
& );
447 void OnFocus( wxFocusEvent
& );
449 DECLARE_EVENT_TABLE()
450 DECLARE_NO_COPY_CLASS(wxGridWindow
)
454 class wxGridCellEditorEvtHandler
: public wxEvtHandler
457 wxGridCellEditorEvtHandler(wxGrid
* grid
, wxGridCellEditor
* editor
)
464 void OnKillFocus(wxFocusEvent
& event
);
465 void OnKeyDown(wxKeyEvent
& event
);
466 void OnChar(wxKeyEvent
& event
);
468 void SetInSetFocus(bool inSetFocus
) { m_inSetFocus
= inSetFocus
; }
472 wxGridCellEditor
*m_editor
;
474 // Work around the fact that a focus kill event can be sent to
475 // a combobox within a set focus event.
478 DECLARE_EVENT_TABLE()
479 DECLARE_DYNAMIC_CLASS(wxGridCellEditorEvtHandler
)
480 DECLARE_NO_COPY_CLASS(wxGridCellEditorEvtHandler
)
484 IMPLEMENT_ABSTRACT_CLASS(wxGridCellEditorEvtHandler
, wxEvtHandler
)
486 BEGIN_EVENT_TABLE( wxGridCellEditorEvtHandler
, wxEvtHandler
)
487 EVT_KILL_FOCUS( wxGridCellEditorEvtHandler::OnKillFocus
)
488 EVT_KEY_DOWN( wxGridCellEditorEvtHandler::OnKeyDown
)
489 EVT_CHAR( wxGridCellEditorEvtHandler::OnChar
)
493 // ----------------------------------------------------------------------------
494 // the internal data representation used by wxGridCellAttrProvider
495 // ----------------------------------------------------------------------------
497 // this class stores attributes set for cells
498 class WXDLLIMPEXP_ADV wxGridCellAttrData
501 void SetAttr(wxGridCellAttr
*attr
, int row
, int col
);
502 wxGridCellAttr
*GetAttr(int row
, int col
) const;
503 void UpdateAttrRows( size_t pos
, int numRows
);
504 void UpdateAttrCols( size_t pos
, int numCols
);
507 // searches for the attr for given cell, returns wxNOT_FOUND if not found
508 int FindIndex(int row
, int col
) const;
510 wxGridCellWithAttrArray m_attrs
;
513 // this class stores attributes set for rows or columns
514 class WXDLLIMPEXP_ADV wxGridRowOrColAttrData
517 // empty ctor to suppress warnings
518 wxGridRowOrColAttrData() {}
519 ~wxGridRowOrColAttrData();
521 void SetAttr(wxGridCellAttr
*attr
, int rowOrCol
);
522 wxGridCellAttr
*GetAttr(int rowOrCol
) const;
523 void UpdateAttrRowsOrCols( size_t pos
, int numRowsOrCols
);
526 wxArrayInt m_rowsOrCols
;
527 wxArrayAttrs m_attrs
;
530 // NB: this is just a wrapper around 3 objects: one which stores cell
531 // attributes, and 2 others for row/col ones
532 class WXDLLIMPEXP_ADV wxGridCellAttrProviderData
535 wxGridCellAttrData m_cellAttrs
;
536 wxGridRowOrColAttrData m_rowAttrs
,
541 // ----------------------------------------------------------------------------
542 // data structures used for the data type registry
543 // ----------------------------------------------------------------------------
545 struct wxGridDataTypeInfo
547 wxGridDataTypeInfo(const wxString
& typeName
,
548 wxGridCellRenderer
* renderer
,
549 wxGridCellEditor
* editor
)
550 : m_typeName(typeName
), m_renderer(renderer
), m_editor(editor
)
553 ~wxGridDataTypeInfo()
555 wxSafeDecRef(m_renderer
);
556 wxSafeDecRef(m_editor
);
560 wxGridCellRenderer
* m_renderer
;
561 wxGridCellEditor
* m_editor
;
563 DECLARE_NO_COPY_CLASS(wxGridDataTypeInfo
)
567 WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridDataTypeInfo
*, wxGridDataTypeInfoArray
,
568 class WXDLLIMPEXP_ADV
);
571 class WXDLLIMPEXP_ADV wxGridTypeRegistry
574 wxGridTypeRegistry() {}
575 ~wxGridTypeRegistry();
577 void RegisterDataType(const wxString
& typeName
,
578 wxGridCellRenderer
* renderer
,
579 wxGridCellEditor
* editor
);
581 // find one of already registered data types
582 int FindRegisteredDataType(const wxString
& typeName
);
584 // try to FindRegisteredDataType(), if this fails and typeName is one of
585 // standard typenames, register it and return its index
586 int FindDataType(const wxString
& typeName
);
588 // try to FindDataType(), if it fails see if it is not one of already
589 // registered data types with some params in which case clone the
590 // registered data type and set params for it
591 int FindOrCloneDataType(const wxString
& typeName
);
593 wxGridCellRenderer
* GetRenderer(int index
);
594 wxGridCellEditor
* GetEditor(int index
);
597 wxGridDataTypeInfoArray m_typeinfo
;
600 // ----------------------------------------------------------------------------
601 // operations classes abstracting the difference between operating on rows and
603 // ----------------------------------------------------------------------------
605 // This class allows to write a function only once because by using its methods
606 // it will apply to both columns and rows.
608 // This is an abstract interface definition, the two concrete implementations
609 // below should be used when working with rows and columns respectively.
610 class wxGridOperations
613 // Returns the operations in the other direction, i.e. wxGridRowOperations
614 // if this object is a wxGridColumnOperations and vice versa.
615 virtual wxGridOperations
& Dual() const = 0;
617 // Return the number of rows or columns.
618 virtual int GetNumberOfLines(const wxGrid
*grid
) const = 0;
620 // Return the selection mode which allows selecting rows or columns.
621 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const = 0;
623 // Make a wxGridCellCoords from the given components: thisDir is row or
624 // column and otherDir is column or row
625 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const = 0;
627 // Calculate the scrolled position of the given abscissa or ordinate.
628 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const = 0;
630 // Selects the horizontal or vertical component from the given object.
631 virtual int Select(const wxGridCellCoords
& coords
) const = 0;
632 virtual int Select(const wxPoint
& pt
) const = 0;
633 virtual int Select(const wxSize
& sz
) const = 0;
634 virtual int Select(const wxRect
& r
) const = 0;
635 virtual int& Select(wxRect
& r
) const = 0;
637 // Returns width or height of the rectangle
638 virtual int& SelectSize(wxRect
& r
) const = 0;
640 // Make a wxSize such that Select() applied to it returns first component
641 virtual wxSize
MakeSize(int first
, int second
) const = 0;
643 // Sets the row or column component of the given cell coordinates
644 virtual void Set(wxGridCellCoords
& coords
, int line
) const = 0;
647 // Draws a line parallel to the row or column, i.e. horizontal or vertical:
648 // pos is the horizontal or vertical position of the line and start and end
649 // are the coordinates of the line extremities in the other direction
651 DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const = 0;
653 // Draw a horizontal or vertical line across the given rectangle
654 // (this is implemented in terms of above and uses Select() to extract
655 // start and end from the given rectangle)
656 void DrawParallelLineInRect(wxDC
& dc
, const wxRect
& rect
, int pos
) const
658 const int posStart
= Select(rect
.GetPosition());
659 DrawParallelLine(dc
, posStart
, posStart
+ Select(rect
.GetSize()), pos
);
663 // Return the index of the row or column at the given pixel coordinate.
665 PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const = 0;
667 // Get the top/left position, in pixels, of the given row or column
668 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const = 0;
670 // Get the bottom/right position, in pixels, of the given row or column
671 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const = 0;
673 // Get the height/width of the given row/column
674 virtual int GetLineSize(const wxGrid
*grid
, int line
) const = 0;
676 // Get wxGrid::m_rowBottoms/m_colRights array
677 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const = 0;
679 // Get default height row height or column width
680 virtual int GetDefaultLineSize(const wxGrid
*grid
) const = 0;
682 // Return the minimal acceptable row height or column width
683 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const = 0;
685 // Return the minimal row height or column width
686 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const = 0;
688 // Set the row height or column width
689 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const = 0;
691 // True if rows/columns can be resized by user
692 virtual bool CanResizeLines(const wxGrid
*grid
) const = 0;
695 // Return the index of the line at the given position
697 // NB: currently this is always identity for the rows as reordering is only
698 // implemented for the lines
699 virtual int GetLineAt(const wxGrid
*grid
, int line
) const = 0;
702 // Get the row or column label window
703 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const = 0;
705 // Get the width or height of the row or column label window
706 virtual int GetHeaderWindowSize(wxGrid
*grid
) const = 0;
709 // This class is never used polymorphically but give it a virtual dtor
710 // anyhow to suppress g++ complaints about it
711 virtual ~wxGridOperations() { }
714 class wxGridRowOperations
: public wxGridOperations
717 virtual wxGridOperations
& Dual() const;
719 virtual int GetNumberOfLines(const wxGrid
*grid
) const
720 { return grid
->GetNumberRows(); }
722 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const
723 { return wxGrid::wxGridSelectRows
; }
725 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const
726 { return wxGridCellCoords(thisDir
, otherDir
); }
728 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const
729 { return grid
->CalcScrolledPosition(wxPoint(pos
, 0)).x
; }
731 virtual int Select(const wxGridCellCoords
& c
) const { return c
.GetRow(); }
732 virtual int Select(const wxPoint
& pt
) const { return pt
.x
; }
733 virtual int Select(const wxSize
& sz
) const { return sz
.x
; }
734 virtual int Select(const wxRect
& r
) const { return r
.x
; }
735 virtual int& Select(wxRect
& r
) const { return r
.x
; }
736 virtual int& SelectSize(wxRect
& r
) const { return r
.width
; }
737 virtual wxSize
MakeSize(int first
, int second
) const
738 { return wxSize(first
, second
); }
739 virtual void Set(wxGridCellCoords
& coords
, int line
) const
740 { coords
.SetRow(line
); }
742 virtual void DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const
743 { dc
.DrawLine(start
, pos
, end
, pos
); }
745 virtual int PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const
746 { return grid
->YToRow(pos
, clip
); }
747 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const
748 { return grid
->GetRowTop(line
); }
749 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const
750 { return grid
->GetRowBottom(line
); }
751 virtual int GetLineSize(const wxGrid
*grid
, int line
) const
752 { return grid
->GetRowHeight(line
); }
753 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const
754 { return grid
->m_rowBottoms
; }
755 virtual int GetDefaultLineSize(const wxGrid
*grid
) const
756 { return grid
->GetDefaultRowSize(); }
757 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const
758 { return grid
->GetRowMinimalAcceptableHeight(); }
759 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const
760 { return grid
->GetRowMinimalHeight(line
); }
761 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const
762 { grid
->SetRowSize(line
, size
); }
763 virtual bool CanResizeLines(const wxGrid
*grid
) const
764 { return grid
->CanDragRowSize(); }
766 virtual int GetLineAt(const wxGrid
* WXUNUSED(grid
), int line
) const
767 { return line
; } // TODO: implement row reordering
769 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const
770 { return grid
->GetGridRowLabelWindow(); }
771 virtual int GetHeaderWindowSize(wxGrid
*grid
) const
772 { return grid
->GetRowLabelSize(); }
775 class wxGridColumnOperations
: public wxGridOperations
778 virtual wxGridOperations
& Dual() const;
780 virtual int GetNumberOfLines(const wxGrid
*grid
) const
781 { return grid
->GetNumberCols(); }
783 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const
784 { return wxGrid::wxGridSelectColumns
; }
786 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const
787 { return wxGridCellCoords(otherDir
, thisDir
); }
789 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const
790 { return grid
->CalcScrolledPosition(wxPoint(0, pos
)).y
; }
792 virtual int Select(const wxGridCellCoords
& c
) const { return c
.GetCol(); }
793 virtual int Select(const wxPoint
& pt
) const { return pt
.y
; }
794 virtual int Select(const wxSize
& sz
) const { return sz
.y
; }
795 virtual int Select(const wxRect
& r
) const { return r
.y
; }
796 virtual int& Select(wxRect
& r
) const { return r
.y
; }
797 virtual int& SelectSize(wxRect
& r
) const { return r
.height
; }
798 virtual wxSize
MakeSize(int first
, int second
) const
799 { return wxSize(second
, first
); }
800 virtual void Set(wxGridCellCoords
& coords
, int line
) const
801 { coords
.SetCol(line
); }
803 virtual void DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const
804 { dc
.DrawLine(pos
, start
, pos
, end
); }
806 virtual int PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const
807 { return grid
->XToCol(pos
, clip
); }
808 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const
809 { return grid
->GetColLeft(line
); }
810 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const
811 { return grid
->GetColRight(line
); }
812 virtual int GetLineSize(const wxGrid
*grid
, int line
) const
813 { return grid
->GetColWidth(line
); }
814 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const
815 { return grid
->m_colRights
; }
816 virtual int GetDefaultLineSize(const wxGrid
*grid
) const
817 { return grid
->GetDefaultColSize(); }
818 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const
819 { return grid
->GetColMinimalAcceptableWidth(); }
820 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const
821 { return grid
->GetColMinimalWidth(line
); }
822 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const
823 { grid
->SetColSize(line
, size
); }
824 virtual bool CanResizeLines(const wxGrid
*grid
) const
825 { return grid
->CanDragColSize(); }
827 virtual int GetLineAt(const wxGrid
*grid
, int line
) const
828 { return grid
->GetColAt(line
); }
830 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const
831 { return grid
->GetGridColLabelWindow(); }
832 virtual int GetHeaderWindowSize(wxGrid
*grid
) const
833 { return grid
->GetColLabelSize(); }
836 wxGridOperations
& wxGridRowOperations::Dual() const
838 static wxGridColumnOperations s_colOper
;
843 wxGridOperations
& wxGridColumnOperations::Dual() const
845 static wxGridRowOperations s_rowOper
;
850 // This class abstracts the difference between operations going forward
851 // (down/right) and backward (up/left) and allows to use the same code for
852 // functions which differ only in the direction of grid traversal
854 // Like wxGridOperations it's an ABC with two concrete subclasses below. Unlike
855 // it, this is a normal object and not just a function dispatch table and has a
858 // Note: the explanation of this discrepancy is the existence of (very useful)
859 // Dual() method in wxGridOperations which forces us to make wxGridOperations a
860 // function dispatcher only.
861 class wxGridDirectionOperations
864 // The oper parameter to ctor selects whether we work with rows or columns
865 wxGridDirectionOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
871 // Check if the component of this point in our direction is at the
872 // boundary, i.e. is the first/last row/column
873 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const = 0;
875 // Increment the component of this point in our direction
876 virtual void Advance(wxGridCellCoords
& coords
) const = 0;
878 // Find the line at the given distance, in pixels, away from this one
879 // (this uses clipping, i.e. anything after the last line is counted as the
880 // last one and anything before the first one as 0)
881 virtual int MoveByPixelDistance(int line
, int distance
) const = 0;
883 // This class is never used polymorphically but give it a virtual dtor
884 // anyhow to suppress g++ complaints about it
885 virtual ~wxGridDirectionOperations() { }
888 wxGrid
* const m_grid
;
889 const wxGridOperations
& m_oper
;
892 class wxGridBackwardOperations
: public wxGridDirectionOperations
895 wxGridBackwardOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
896 : wxGridDirectionOperations(grid
, oper
)
900 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const
902 wxASSERT_MSG( m_oper
.Select(coords
) >= 0, "invalid row/column" );
904 return m_oper
.Select(coords
) == 0;
907 virtual void Advance(wxGridCellCoords
& coords
) const
909 wxASSERT( !IsAtBoundary(coords
) );
911 m_oper
.Set(coords
, m_oper
.Select(coords
) - 1);
914 virtual int MoveByPixelDistance(int line
, int distance
) const
916 int pos
= m_oper
.GetLineStartPos(m_grid
, line
);
917 return m_oper
.PosToLine(m_grid
, pos
- distance
+ 1, true);
921 class wxGridForwardOperations
: public wxGridDirectionOperations
924 wxGridForwardOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
925 : wxGridDirectionOperations(grid
, oper
),
926 m_numLines(oper
.GetNumberOfLines(grid
))
930 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const
932 wxASSERT_MSG( m_oper
.Select(coords
) < m_numLines
, "invalid row/column" );
934 return m_oper
.Select(coords
) == m_numLines
- 1;
937 virtual void Advance(wxGridCellCoords
& coords
) const
939 wxASSERT( !IsAtBoundary(coords
) );
941 m_oper
.Set(coords
, m_oper
.Select(coords
) + 1);
944 virtual int MoveByPixelDistance(int line
, int distance
) const
946 int pos
= m_oper
.GetLineStartPos(m_grid
, line
);
947 return m_oper
.PosToLine(m_grid
, pos
+ distance
, true);
951 const int m_numLines
;
954 // ----------------------------------------------------------------------------
956 // ----------------------------------------------------------------------------
958 //#define DEBUG_ATTR_CACHE
959 #ifdef DEBUG_ATTR_CACHE
960 static size_t gs_nAttrCacheHits
= 0;
961 static size_t gs_nAttrCacheMisses
= 0;
964 // ----------------------------------------------------------------------------
966 // ----------------------------------------------------------------------------
968 wxGridCellCoords
wxGridNoCellCoords( -1, -1 );
969 wxRect
wxGridNoCellRect( -1, -1, -1, -1 );
975 const size_t GRID_SCROLL_LINE_X
= 15;
976 const size_t GRID_SCROLL_LINE_Y
= GRID_SCROLL_LINE_X
;
978 // the size of hash tables used a bit everywhere (the max number of elements
979 // in these hash tables is the number of rows/columns)
980 const int GRID_HASH_SIZE
= 100;
982 // the minimal distance in pixels the mouse needs to move to start a drag
984 const int DRAG_SENSITIVITY
= 3;
986 } // anonymous namespace
988 // ----------------------------------------------------------------------------
990 // ----------------------------------------------------------------------------
995 // ensure that first is less or equal to second, swapping the values if
997 void EnsureFirstLessThanSecond(int& first
, int& second
)
999 if ( first
> second
)
1000 wxSwap(first
, second
);
1003 } // anonymous namespace
1005 // ============================================================================
1007 // ============================================================================
1009 // ----------------------------------------------------------------------------
1011 // ----------------------------------------------------------------------------
1013 wxGridCellEditor::wxGridCellEditor()
1019 wxGridCellEditor::~wxGridCellEditor()
1024 void wxGridCellEditor::Create(wxWindow
* WXUNUSED(parent
),
1025 wxWindowID
WXUNUSED(id
),
1026 wxEvtHandler
* evtHandler
)
1029 m_control
->PushEventHandler(evtHandler
);
1032 void wxGridCellEditor::PaintBackground(const wxRect
& rectCell
,
1033 wxGridCellAttr
*attr
)
1035 // erase the background because we might not fill the cell
1036 wxClientDC
dc(m_control
->GetParent());
1037 wxGridWindow
* gridWindow
= wxDynamicCast(m_control
->GetParent(), wxGridWindow
);
1039 gridWindow
->GetOwner()->PrepareDC(dc
);
1041 dc
.SetPen(*wxTRANSPARENT_PEN
);
1042 dc
.SetBrush(wxBrush(attr
->GetBackgroundColour()));
1043 dc
.DrawRectangle(rectCell
);
1045 // redraw the control we just painted over
1046 m_control
->Refresh();
1049 void wxGridCellEditor::Destroy()
1053 m_control
->PopEventHandler( true /* delete it*/ );
1055 m_control
->Destroy();
1060 void wxGridCellEditor::Show(bool show
, wxGridCellAttr
*attr
)
1062 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1064 m_control
->Show(show
);
1068 // set the colours/fonts if we have any
1071 m_colFgOld
= m_control
->GetForegroundColour();
1072 m_control
->SetForegroundColour(attr
->GetTextColour());
1074 m_colBgOld
= m_control
->GetBackgroundColour();
1075 m_control
->SetBackgroundColour(attr
->GetBackgroundColour());
1077 // Workaround for GTK+1 font setting problem on some platforms
1078 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1079 m_fontOld
= m_control
->GetFont();
1080 m_control
->SetFont(attr
->GetFont());
1083 // can't do anything more in the base class version, the other
1084 // attributes may only be used by the derived classes
1089 // restore the standard colours fonts
1090 if ( m_colFgOld
.Ok() )
1092 m_control
->SetForegroundColour(m_colFgOld
);
1093 m_colFgOld
= wxNullColour
;
1096 if ( m_colBgOld
.Ok() )
1098 m_control
->SetBackgroundColour(m_colBgOld
);
1099 m_colBgOld
= wxNullColour
;
1102 // Workaround for GTK+1 font setting problem on some platforms
1103 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1104 if ( m_fontOld
.Ok() )
1106 m_control
->SetFont(m_fontOld
);
1107 m_fontOld
= wxNullFont
;
1113 void wxGridCellEditor::SetSize(const wxRect
& rect
)
1115 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1117 m_control
->SetSize(rect
, wxSIZE_ALLOW_MINUS_ONE
);
1120 void wxGridCellEditor::HandleReturn(wxKeyEvent
& event
)
1125 bool wxGridCellEditor::IsAcceptedKey(wxKeyEvent
& event
)
1127 bool ctrl
= event
.ControlDown();
1128 bool alt
= event
.AltDown();
1131 // On the Mac the Alt key is more like shift and is used for entry of
1132 // valid characters, so check for Ctrl and Meta instead.
1133 alt
= event
.MetaDown();
1136 // Assume it's not a valid char if ctrl or alt is down, but if both are
1137 // down then it may be because of an AltGr key combination, so let them
1138 // through in that case.
1139 if ((ctrl
|| alt
) && !(ctrl
&& alt
))
1143 // if the unicode key code is not really a unicode character (it may
1144 // be a function key or etc., the platforms appear to always give us a
1145 // small value in this case) then fallback to the ASCII key code but
1146 // don't do anything for function keys or etc.
1147 if ( event
.GetUnicodeKey() > 127 && event
.GetKeyCode() > 127 )
1150 if ( event
.GetKeyCode() > 255 )
1157 void wxGridCellEditor::StartingKey(wxKeyEvent
& event
)
1162 void wxGridCellEditor::StartingClick()
1168 // ----------------------------------------------------------------------------
1169 // wxGridCellTextEditor
1170 // ----------------------------------------------------------------------------
1172 wxGridCellTextEditor::wxGridCellTextEditor()
1177 void wxGridCellTextEditor::Create(wxWindow
* parent
,
1179 wxEvtHandler
* evtHandler
)
1181 DoCreate(parent
, id
, evtHandler
);
1184 void wxGridCellTextEditor::DoCreate(wxWindow
* parent
,
1186 wxEvtHandler
* evtHandler
,
1189 style
|= wxTE_PROCESS_ENTER
| wxTE_PROCESS_TAB
| wxNO_BORDER
;
1191 m_control
= new wxTextCtrl(parent
, id
, wxEmptyString
,
1192 wxDefaultPosition
, wxDefaultSize
,
1195 // set max length allowed in the textctrl, if the parameter was set
1196 if ( m_maxChars
!= 0 )
1198 Text()->SetMaxLength(m_maxChars
);
1201 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1204 void wxGridCellTextEditor::PaintBackground(const wxRect
& WXUNUSED(rectCell
),
1205 wxGridCellAttr
* WXUNUSED(attr
))
1207 // as we fill the entire client area,
1208 // don't do anything here to minimize flicker
1211 void wxGridCellTextEditor::SetSize(const wxRect
& rectOrig
)
1213 wxRect
rect(rectOrig
);
1215 // Make the edit control large enough to allow for internal margins
1217 // TODO: remove this if the text ctrl sizing is improved esp. for unix
1219 #if defined(__WXGTK__)
1227 #elif defined(__WXMSW__)
1241 int extra_x
= ( rect
.x
> 2 ) ? 2 : 1;
1242 int extra_y
= ( rect
.y
> 2 ) ? 2 : 1;
1244 #if defined(__WXMOTIF__)
1249 rect
.SetLeft( wxMax(0, rect
.x
- extra_x
) );
1250 rect
.SetTop( wxMax(0, rect
.y
- extra_y
) );
1251 rect
.SetRight( rect
.GetRight() + 2 * extra_x
);
1252 rect
.SetBottom( rect
.GetBottom() + 2 * extra_y
);
1255 wxGridCellEditor::SetSize(rect
);
1258 void wxGridCellTextEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1260 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1262 m_startValue
= grid
->GetTable()->GetValue(row
, col
);
1264 DoBeginEdit(m_startValue
);
1267 void wxGridCellTextEditor::DoBeginEdit(const wxString
& startValue
)
1269 Text()->SetValue(startValue
);
1270 Text()->SetInsertionPointEnd();
1271 Text()->SetSelection(-1, -1);
1275 bool wxGridCellTextEditor::EndEdit(int row
, int col
, wxGrid
* grid
)
1277 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1279 bool changed
= false;
1280 wxString value
= Text()->GetValue();
1281 if (value
!= m_startValue
)
1285 grid
->GetTable()->SetValue(row
, col
, value
);
1287 m_startValue
= wxEmptyString
;
1289 // No point in setting the text of the hidden control
1290 //Text()->SetValue(m_startValue);
1295 void wxGridCellTextEditor::Reset()
1297 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1299 DoReset(m_startValue
);
1302 void wxGridCellTextEditor::DoReset(const wxString
& startValue
)
1304 Text()->SetValue(startValue
);
1305 Text()->SetInsertionPointEnd();
1308 bool wxGridCellTextEditor::IsAcceptedKey(wxKeyEvent
& event
)
1310 return wxGridCellEditor::IsAcceptedKey(event
);
1313 void wxGridCellTextEditor::StartingKey(wxKeyEvent
& event
)
1315 // Since this is now happening in the EVT_CHAR event EmulateKeyPress is no
1316 // longer an appropriate way to get the character into the text control.
1317 // Do it ourselves instead. We know that if we get this far that we have
1318 // a valid character, so not a whole lot of testing needs to be done.
1320 wxTextCtrl
* tc
= Text();
1325 ch
= event
.GetUnicodeKey();
1327 ch
= (wxChar
)event
.GetKeyCode();
1329 ch
= (wxChar
)event
.GetKeyCode();
1335 // delete the character at the cursor
1336 pos
= tc
->GetInsertionPoint();
1337 if (pos
< tc
->GetLastPosition())
1338 tc
->Remove(pos
, pos
+ 1);
1342 // delete the character before the cursor
1343 pos
= tc
->GetInsertionPoint();
1345 tc
->Remove(pos
- 1, pos
);
1354 void wxGridCellTextEditor::HandleReturn( wxKeyEvent
&
1355 WXUNUSED_GTK(WXUNUSED_MOTIF(event
)) )
1357 #if defined(__WXMOTIF__) || defined(__WXGTK__)
1358 // wxMotif needs a little extra help...
1359 size_t pos
= (size_t)( Text()->GetInsertionPoint() );
1360 wxString
s( Text()->GetValue() );
1361 s
= s
.Left(pos
) + wxT("\n") + s
.Mid(pos
);
1362 Text()->SetValue(s
);
1363 Text()->SetInsertionPoint( pos
);
1365 // the other ports can handle a Return key press
1371 void wxGridCellTextEditor::SetParameters(const wxString
& params
)
1381 if ( params
.ToLong(&tmp
) )
1383 m_maxChars
= (size_t)tmp
;
1387 wxLogDebug( _T("Invalid wxGridCellTextEditor parameter string '%s' ignored"), params
.c_str() );
1392 // return the value in the text control
1393 wxString
wxGridCellTextEditor::GetValue() const
1395 return Text()->GetValue();
1398 // ----------------------------------------------------------------------------
1399 // wxGridCellNumberEditor
1400 // ----------------------------------------------------------------------------
1402 wxGridCellNumberEditor::wxGridCellNumberEditor(int min
, int max
)
1408 void wxGridCellNumberEditor::Create(wxWindow
* parent
,
1410 wxEvtHandler
* evtHandler
)
1415 // create a spin ctrl
1416 m_control
= new wxSpinCtrl(parent
, wxID_ANY
, wxEmptyString
,
1417 wxDefaultPosition
, wxDefaultSize
,
1421 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1426 // just a text control
1427 wxGridCellTextEditor::Create(parent
, id
, evtHandler
);
1429 #if wxUSE_VALIDATORS
1430 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC
));
1435 void wxGridCellNumberEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1437 // first get the value
1438 wxGridTableBase
*table
= grid
->GetTable();
1439 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
1441 m_valueOld
= table
->GetValueAsLong(row
, col
);
1446 wxString sValue
= table
->GetValue(row
, col
);
1447 if (! sValue
.ToLong(&m_valueOld
) && ! sValue
.empty())
1449 wxFAIL_MSG( _T("this cell doesn't have numeric value") );
1457 Spin()->SetValue((int)m_valueOld
);
1463 DoBeginEdit(GetString());
1467 bool wxGridCellNumberEditor::EndEdit(int row
, int col
,
1476 value
= Spin()->GetValue();
1477 if ( value
== m_valueOld
)
1480 text
.Printf(wxT("%ld"), value
);
1482 else // using unconstrained input
1483 #endif // wxUSE_SPINCTRL
1485 const wxString
textOld(grid
->GetCellValue(row
, col
));
1486 text
= Text()->GetValue();
1489 if ( textOld
.empty() )
1492 else // non-empty text now (maybe 0)
1494 if ( !text
.ToLong(&value
) )
1497 // if value == m_valueOld == 0 but old text was "" and new one is
1498 // "0" something still did change
1499 if ( value
== m_valueOld
&& (value
|| !textOld
.empty()) )
1504 wxGridTableBase
* const table
= grid
->GetTable();
1505 if ( table
->CanSetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
1506 table
->SetValueAsLong(row
, col
, value
);
1508 table
->SetValue(row
, col
, text
);
1513 void wxGridCellNumberEditor::Reset()
1518 Spin()->SetValue((int)m_valueOld
);
1523 DoReset(GetString());
1527 bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent
& event
)
1529 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1531 int keycode
= event
.GetKeyCode();
1532 if ( (keycode
< 128) &&
1533 (wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-'))
1542 void wxGridCellNumberEditor::StartingKey(wxKeyEvent
& event
)
1544 int keycode
= event
.GetKeyCode();
1547 if ( wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-')
1549 wxGridCellTextEditor::StartingKey(event
);
1551 // skip Skip() below
1558 if ( wxIsdigit(keycode
) )
1560 wxSpinCtrl
* spin
= (wxSpinCtrl
*)m_control
;
1561 spin
->SetValue(keycode
- '0');
1562 spin
->SetSelection(1,1);
1571 void wxGridCellNumberEditor::SetParameters(const wxString
& params
)
1582 if ( params
.BeforeFirst(_T(',')).ToLong(&tmp
) )
1586 if ( params
.AfterFirst(_T(',')).ToLong(&tmp
) )
1590 // skip the error message below
1595 wxLogDebug(_T("Invalid wxGridCellNumberEditor parameter string '%s' ignored"), params
.c_str());
1599 // return the value in the spin control if it is there (the text control otherwise)
1600 wxString
wxGridCellNumberEditor::GetValue() const
1607 long value
= Spin()->GetValue();
1608 s
.Printf(wxT("%ld"), value
);
1613 s
= Text()->GetValue();
1619 // ----------------------------------------------------------------------------
1620 // wxGridCellFloatEditor
1621 // ----------------------------------------------------------------------------
1623 wxGridCellFloatEditor::wxGridCellFloatEditor(int width
, int precision
)
1626 m_precision
= precision
;
1629 void wxGridCellFloatEditor::Create(wxWindow
* parent
,
1631 wxEvtHandler
* evtHandler
)
1633 wxGridCellTextEditor::Create(parent
, id
, evtHandler
);
1635 #if wxUSE_VALIDATORS
1636 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC
));
1640 void wxGridCellFloatEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1642 // first get the value
1643 wxGridTableBase
* const table
= grid
->GetTable();
1644 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
1646 m_valueOld
= table
->GetValueAsDouble(row
, col
);
1652 const wxString value
= table
->GetValue(row
, col
);
1653 if ( !value
.empty() )
1655 if ( !value
.ToDouble(&m_valueOld
) )
1657 wxFAIL_MSG( _T("this cell doesn't have float value") );
1663 DoBeginEdit(GetString());
1666 bool wxGridCellFloatEditor::EndEdit(int row
, int col
, wxGrid
* grid
)
1668 const wxString
text(Text()->GetValue()),
1669 textOld(grid
->GetCellValue(row
, col
));
1672 if ( !text
.empty() )
1674 if ( !text
.ToDouble(&value
) )
1677 else // new value is empty string
1679 if ( textOld
.empty() )
1680 return false; // nothing changed
1685 // the test for empty strings ensures that we don't skip the value setting
1686 // when "" is replaced by "0" or vice versa as "" numeric value is also 0.
1687 if ( wxIsSameDouble(value
, m_valueOld
) && !text
.empty() && !textOld
.empty() )
1688 return false; // nothing changed
1690 wxGridTableBase
* const table
= grid
->GetTable();
1692 if ( table
->CanSetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
1693 table
->SetValueAsDouble(row
, col
, value
);
1695 table
->SetValue(row
, col
, text
);
1700 void wxGridCellFloatEditor::Reset()
1702 DoReset(GetString());
1705 void wxGridCellFloatEditor::StartingKey(wxKeyEvent
& event
)
1707 int keycode
= event
.GetKeyCode();
1709 tmpbuf
[0] = (char) keycode
;
1711 wxString
strbuf(tmpbuf
, *wxConvCurrent
);
1714 bool is_decimal_point
= ( strbuf
==
1715 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT
, wxLOCALE_CAT_NUMBER
) );
1717 bool is_decimal_point
= ( strbuf
== _T(".") );
1720 if ( wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-'
1721 || is_decimal_point
)
1723 wxGridCellTextEditor::StartingKey(event
);
1725 // skip Skip() below
1732 void wxGridCellFloatEditor::SetParameters(const wxString
& params
)
1743 if ( params
.BeforeFirst(_T(',')).ToLong(&tmp
) )
1747 if ( params
.AfterFirst(_T(',')).ToLong(&tmp
) )
1749 m_precision
= (int)tmp
;
1751 // skip the error message below
1756 wxLogDebug(_T("Invalid wxGridCellFloatEditor parameter string '%s' ignored"), params
.c_str());
1760 wxString
wxGridCellFloatEditor::GetString() const
1763 if ( m_precision
== -1 && m_width
!= -1)
1765 // default precision
1766 fmt
.Printf(_T("%%%d.f"), m_width
);
1768 else if ( m_precision
!= -1 && m_width
== -1)
1771 fmt
.Printf(_T("%%.%df"), m_precision
);
1773 else if ( m_precision
!= -1 && m_width
!= -1 )
1775 fmt
.Printf(_T("%%%d.%df"), m_width
, m_precision
);
1779 // default width/precision
1783 return wxString::Format(fmt
, m_valueOld
);
1786 bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent
& event
)
1788 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1790 const int keycode
= event
.GetKeyCode();
1791 if ( isascii(keycode
) )
1794 tmpbuf
[0] = (char) keycode
;
1796 wxString
strbuf(tmpbuf
, *wxConvCurrent
);
1799 const wxString decimalPoint
=
1800 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT
, wxLOCALE_CAT_NUMBER
);
1802 const wxString
decimalPoint(_T('.'));
1805 // accept digits, 'e' as in '1e+6', also '-', '+', and '.'
1806 if ( wxIsdigit(keycode
) ||
1807 tolower(keycode
) == 'e' ||
1808 keycode
== decimalPoint
||
1820 #endif // wxUSE_TEXTCTRL
1824 // ----------------------------------------------------------------------------
1825 // wxGridCellBoolEditor
1826 // ----------------------------------------------------------------------------
1828 // the default values for GetValue()
1829 wxString
wxGridCellBoolEditor::ms_stringValues
[2] = { _T(""), _T("1") };
1831 void wxGridCellBoolEditor::Create(wxWindow
* parent
,
1833 wxEvtHandler
* evtHandler
)
1835 m_control
= new wxCheckBox(parent
, id
, wxEmptyString
,
1836 wxDefaultPosition
, wxDefaultSize
,
1839 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1842 void wxGridCellBoolEditor::SetSize(const wxRect
& r
)
1844 bool resize
= false;
1845 wxSize size
= m_control
->GetSize();
1846 wxCoord minSize
= wxMin(r
.width
, r
.height
);
1848 // check if the checkbox is not too big/small for this cell
1849 wxSize sizeBest
= m_control
->GetBestSize();
1850 if ( !(size
== sizeBest
) )
1852 // reset to default size if it had been made smaller
1858 if ( size
.x
>= minSize
|| size
.y
>= minSize
)
1860 // leave 1 pixel margin
1861 size
.x
= size
.y
= minSize
- 2;
1868 m_control
->SetSize(size
);
1871 // position it in the centre of the rectangle (TODO: support alignment?)
1873 #if defined(__WXGTK__) || defined (__WXMOTIF__)
1874 // the checkbox without label still has some space to the right in wxGTK,
1875 // so shift it to the right
1877 #elif defined(__WXMSW__)
1878 // here too, but in other way
1883 int hAlign
= wxALIGN_CENTRE
;
1884 int vAlign
= wxALIGN_CENTRE
;
1886 GetCellAttr()->GetAlignment(& hAlign
, & vAlign
);
1889 if (hAlign
== wxALIGN_LEFT
)
1897 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1899 else if (hAlign
== wxALIGN_RIGHT
)
1901 x
= r
.x
+ r
.width
- size
.x
- 2;
1902 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1904 else if (hAlign
== wxALIGN_CENTRE
)
1906 x
= r
.x
+ r
.width
/ 2 - size
.x
/ 2;
1907 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1910 m_control
->Move(x
, y
);
1913 void wxGridCellBoolEditor::Show(bool show
, wxGridCellAttr
*attr
)
1915 m_control
->Show(show
);
1919 wxColour colBg
= attr
? attr
->GetBackgroundColour() : *wxLIGHT_GREY
;
1920 CBox()->SetBackgroundColour(colBg
);
1924 void wxGridCellBoolEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1926 wxASSERT_MSG(m_control
,
1927 wxT("The wxGridCellEditor must be created first!"));
1929 if (grid
->GetTable()->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
))
1931 m_startValue
= grid
->GetTable()->GetValueAsBool(row
, col
);
1935 wxString
cellval( grid
->GetTable()->GetValue(row
, col
) );
1937 if ( cellval
== ms_stringValues
[false] )
1938 m_startValue
= false;
1939 else if ( cellval
== ms_stringValues
[true] )
1940 m_startValue
= true;
1943 // do not try to be smart here and convert it to true or false
1944 // because we'll still overwrite it with something different and
1945 // this risks to be very surprising for the user code, let them
1947 wxFAIL_MSG( _T("invalid value for a cell with bool editor!") );
1951 CBox()->SetValue(m_startValue
);
1955 bool wxGridCellBoolEditor::EndEdit(int row
, int col
,
1958 wxASSERT_MSG(m_control
,
1959 wxT("The wxGridCellEditor must be created first!"));
1961 bool changed
= false;
1962 bool value
= CBox()->GetValue();
1963 if ( value
!= m_startValue
)
1968 wxGridTableBase
* const table
= grid
->GetTable();
1969 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
) )
1970 table
->SetValueAsBool(row
, col
, value
);
1972 table
->SetValue(row
, col
, GetValue());
1978 void wxGridCellBoolEditor::Reset()
1980 wxASSERT_MSG(m_control
,
1981 wxT("The wxGridCellEditor must be created first!"));
1983 CBox()->SetValue(m_startValue
);
1986 void wxGridCellBoolEditor::StartingClick()
1988 CBox()->SetValue(!CBox()->GetValue());
1991 bool wxGridCellBoolEditor::IsAcceptedKey(wxKeyEvent
& event
)
1993 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1995 int keycode
= event
.GetKeyCode();
2008 void wxGridCellBoolEditor::StartingKey(wxKeyEvent
& event
)
2010 int keycode
= event
.GetKeyCode();
2014 CBox()->SetValue(!CBox()->GetValue());
2018 CBox()->SetValue(true);
2022 CBox()->SetValue(false);
2027 wxString
wxGridCellBoolEditor::GetValue() const
2029 return ms_stringValues
[CBox()->GetValue()];
2033 wxGridCellBoolEditor::UseStringValues(const wxString
& valueTrue
,
2034 const wxString
& valueFalse
)
2036 ms_stringValues
[false] = valueFalse
;
2037 ms_stringValues
[true] = valueTrue
;
2041 wxGridCellBoolEditor::IsTrueValue(const wxString
& value
)
2043 return value
== ms_stringValues
[true];
2046 #endif // wxUSE_CHECKBOX
2050 // ----------------------------------------------------------------------------
2051 // wxGridCellChoiceEditor
2052 // ----------------------------------------------------------------------------
2054 wxGridCellChoiceEditor::wxGridCellChoiceEditor(const wxArrayString
& choices
,
2056 : m_choices(choices
),
2057 m_allowOthers(allowOthers
) { }
2059 wxGridCellChoiceEditor::wxGridCellChoiceEditor(size_t count
,
2060 const wxString choices
[],
2062 : m_allowOthers(allowOthers
)
2066 m_choices
.Alloc(count
);
2067 for ( size_t n
= 0; n
< count
; n
++ )
2069 m_choices
.Add(choices
[n
]);
2074 wxGridCellEditor
*wxGridCellChoiceEditor::Clone() const
2076 wxGridCellChoiceEditor
*editor
= new wxGridCellChoiceEditor
;
2077 editor
->m_allowOthers
= m_allowOthers
;
2078 editor
->m_choices
= m_choices
;
2083 void wxGridCellChoiceEditor::Create(wxWindow
* parent
,
2085 wxEvtHandler
* evtHandler
)
2087 int style
= wxTE_PROCESS_ENTER
|
2091 if ( !m_allowOthers
)
2092 style
|= wxCB_READONLY
;
2093 m_control
= new wxComboBox(parent
, id
, wxEmptyString
,
2094 wxDefaultPosition
, wxDefaultSize
,
2098 wxGridCellEditor::Create(parent
, id
, evtHandler
);
2101 void wxGridCellChoiceEditor::PaintBackground(const wxRect
& rectCell
,
2102 wxGridCellAttr
* attr
)
2104 // as we fill the entire client area, don't do anything here to minimize
2107 // TODO: It doesn't actually fill the client area since the height of a
2108 // combo always defaults to the standard. Until someone has time to
2109 // figure out the right rectangle to paint, just do it the normal way.
2110 wxGridCellEditor::PaintBackground(rectCell
, attr
);
2113 void wxGridCellChoiceEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
2115 wxASSERT_MSG(m_control
,
2116 wxT("The wxGridCellEditor must be created first!"));
2118 wxGridCellEditorEvtHandler
* evtHandler
= NULL
;
2120 evtHandler
= wxDynamicCast(m_control
->GetEventHandler(), wxGridCellEditorEvtHandler
);
2122 // Don't immediately end if we get a kill focus event within BeginEdit
2124 evtHandler
->SetInSetFocus(true);
2126 m_startValue
= grid
->GetTable()->GetValue(row
, col
);
2128 Reset(); // this updates combo box to correspond to m_startValue
2130 Combo()->SetFocus();
2134 // When dropping down the menu, a kill focus event
2135 // happens after this point, so we can't reset the flag yet.
2136 #if !defined(__WXGTK20__)
2137 evtHandler
->SetInSetFocus(false);
2142 bool wxGridCellChoiceEditor::EndEdit(int row
, int col
,
2145 wxString value
= Combo()->GetValue();
2146 if ( value
== m_startValue
)
2149 grid
->GetTable()->SetValue(row
, col
, value
);
2154 void wxGridCellChoiceEditor::Reset()
2158 Combo()->SetValue(m_startValue
);
2159 Combo()->SetInsertionPointEnd();
2161 else // the combobox is read-only
2163 // find the right position, or default to the first if not found
2164 int pos
= Combo()->FindString(m_startValue
);
2165 if (pos
== wxNOT_FOUND
)
2167 Combo()->SetSelection(pos
);
2171 void wxGridCellChoiceEditor::SetParameters(const wxString
& params
)
2181 wxStringTokenizer
tk(params
, _T(','));
2182 while ( tk
.HasMoreTokens() )
2184 m_choices
.Add(tk
.GetNextToken());
2188 // return the value in the text control
2189 wxString
wxGridCellChoiceEditor::GetValue() const
2191 return Combo()->GetValue();
2194 #endif // wxUSE_COMBOBOX
2196 // ----------------------------------------------------------------------------
2197 // wxGridCellEditorEvtHandler
2198 // ----------------------------------------------------------------------------
2200 void wxGridCellEditorEvtHandler::OnKillFocus(wxFocusEvent
& event
)
2202 // Don't disable the cell if we're just starting to edit it
2207 m_grid
->DisableCellEditControl();
2212 void wxGridCellEditorEvtHandler::OnKeyDown(wxKeyEvent
& event
)
2214 switch ( event
.GetKeyCode() )
2218 m_grid
->DisableCellEditControl();
2222 m_grid
->GetEventHandler()->ProcessEvent( event
);
2226 case WXK_NUMPAD_ENTER
:
2227 if (!m_grid
->GetEventHandler()->ProcessEvent(event
))
2228 m_editor
->HandleReturn(event
);
2237 void wxGridCellEditorEvtHandler::OnChar(wxKeyEvent
& event
)
2239 int row
= m_grid
->GetGridCursorRow();
2240 int col
= m_grid
->GetGridCursorCol();
2241 wxRect rect
= m_grid
->CellToRect( row
, col
);
2243 m_grid
->GetGridWindow()->GetClientSize( &cw
, &ch
);
2245 // if cell width is smaller than grid client area, cell is wholly visible
2246 bool wholeCellVisible
= (rect
.GetWidth() < cw
);
2248 switch ( event
.GetKeyCode() )
2253 case WXK_NUMPAD_ENTER
:
2258 if ( wholeCellVisible
)
2260 // no special processing needed...
2265 // do special processing for partly visible cell...
2267 // get the widths of all cells previous to this one
2269 for ( int i
= 0; i
< col
; i
++ )
2271 colXPos
+= m_grid
->GetColSize(i
);
2274 int xUnit
= 1, yUnit
= 1;
2275 m_grid
->GetScrollPixelsPerUnit(&xUnit
, &yUnit
);
2278 m_grid
->Scroll(colXPos
/ xUnit
- 1, m_grid
->GetScrollPos(wxVERTICAL
));
2282 m_grid
->Scroll(colXPos
/ xUnit
, m_grid
->GetScrollPos(wxVERTICAL
));
2290 if ( wholeCellVisible
)
2292 // no special processing needed...
2297 // do special processing for partly visible cell...
2300 wxString value
= m_grid
->GetCellValue(row
, col
);
2301 if ( wxEmptyString
!= value
)
2303 // get width of cell CONTENTS (text)
2305 wxFont font
= m_grid
->GetCellFont(row
, col
);
2306 m_grid
->GetTextExtent(value
, &textWidth
, &y
, NULL
, NULL
, &font
);
2308 // try to RIGHT align the text by scrolling
2309 int client_right
= m_grid
->GetGridWindow()->GetClientSize().GetWidth();
2311 // (m_grid->GetScrollLineX()*2) is a factor for not scrolling to far,
2312 // otherwise the last part of the cell content might be hidden below the scroll bar
2313 // FIXME: maybe there is a more suitable correction?
2314 textWidth
-= (client_right
- (m_grid
->GetScrollLineX() * 2));
2315 if ( textWidth
< 0 )
2321 // get the widths of all cells previous to this one
2323 for ( int i
= 0; i
< col
; i
++ )
2325 colXPos
+= m_grid
->GetColSize(i
);
2328 // and add the (modified) text width of the cell contents
2329 // as we'd like to see the last part of the cell contents
2330 colXPos
+= textWidth
;
2332 int xUnit
= 1, yUnit
= 1;
2333 m_grid
->GetScrollPixelsPerUnit(&xUnit
, &yUnit
);
2334 m_grid
->Scroll(colXPos
/ xUnit
- 1, m_grid
->GetScrollPos(wxVERTICAL
));
2345 // ----------------------------------------------------------------------------
2346 // wxGridCellWorker is an (almost) empty common base class for
2347 // wxGridCellRenderer and wxGridCellEditor managing ref counting
2348 // ----------------------------------------------------------------------------
2350 void wxGridCellWorker::SetParameters(const wxString
& WXUNUSED(params
))
2355 wxGridCellWorker::~wxGridCellWorker()
2359 // ============================================================================
2361 // ============================================================================
2363 // ----------------------------------------------------------------------------
2364 // wxGridCellRenderer
2365 // ----------------------------------------------------------------------------
2367 void wxGridCellRenderer::Draw(wxGrid
& grid
,
2368 wxGridCellAttr
& attr
,
2371 int WXUNUSED(row
), int WXUNUSED(col
),
2374 dc
.SetBackgroundMode( wxBRUSHSTYLE_SOLID
);
2377 if ( grid
.IsEnabled() )
2381 if ( grid
.HasFocus() )
2382 clr
= grid
.GetSelectionBackground();
2384 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW
);
2388 clr
= attr
.GetBackgroundColour();
2391 else // grey out fields if the grid is disabled
2393 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE
);
2397 dc
.SetPen( *wxTRANSPARENT_PEN
);
2398 dc
.DrawRectangle(rect
);
2401 // ----------------------------------------------------------------------------
2402 // wxGridCellStringRenderer
2403 // ----------------------------------------------------------------------------
2405 void wxGridCellStringRenderer::SetTextColoursAndFont(const wxGrid
& grid
,
2406 const wxGridCellAttr
& attr
,
2410 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
2412 // TODO some special colours for attr.IsReadOnly() case?
2414 // different coloured text when the grid is disabled
2415 if ( grid
.IsEnabled() )
2420 if ( grid
.HasFocus() )
2421 clr
= grid
.GetSelectionBackground();
2423 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW
);
2424 dc
.SetTextBackground( clr
);
2425 dc
.SetTextForeground( grid
.GetSelectionForeground() );
2429 dc
.SetTextBackground( attr
.GetBackgroundColour() );
2430 dc
.SetTextForeground( attr
.GetTextColour() );
2435 dc
.SetTextBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE
));
2436 dc
.SetTextForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT
));
2439 dc
.SetFont( attr
.GetFont() );
2442 wxSize
wxGridCellStringRenderer::DoGetBestSize(const wxGridCellAttr
& attr
,
2444 const wxString
& text
)
2446 wxCoord x
= 0, y
= 0, max_x
= 0;
2447 dc
.SetFont(attr
.GetFont());
2448 wxStringTokenizer
tk(text
, _T('\n'));
2449 while ( tk
.HasMoreTokens() )
2451 dc
.GetTextExtent(tk
.GetNextToken(), &x
, &y
);
2452 max_x
= wxMax(max_x
, x
);
2455 y
*= 1 + text
.Freq(wxT('\n')); // multiply by the number of lines.
2457 return wxSize(max_x
, y
);
2460 wxSize
wxGridCellStringRenderer::GetBestSize(wxGrid
& grid
,
2461 wxGridCellAttr
& attr
,
2465 return DoGetBestSize(attr
, dc
, grid
.GetCellValue(row
, col
));
2468 void wxGridCellStringRenderer::Draw(wxGrid
& grid
,
2469 wxGridCellAttr
& attr
,
2471 const wxRect
& rectCell
,
2475 wxRect rect
= rectCell
;
2478 // erase only this cells background, overflow cells should have been erased
2479 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2482 attr
.GetAlignment(&hAlign
, &vAlign
);
2484 int overflowCols
= 0;
2486 if (attr
.GetOverflow())
2488 int cols
= grid
.GetNumberCols();
2489 int best_width
= GetBestSize(grid
,attr
,dc
,row
,col
).GetWidth();
2490 int cell_rows
, cell_cols
;
2491 attr
.GetSize( &cell_rows
, &cell_cols
); // shouldn't get here if <= 0
2492 if ((best_width
> rectCell
.width
) && (col
< cols
) && grid
.GetTable())
2494 int i
, c_cols
, c_rows
;
2495 for (i
= col
+cell_cols
; i
< cols
; i
++)
2497 bool is_empty
= true;
2498 for (int j
=row
; j
< row
+ cell_rows
; j
++)
2500 // check w/ anchor cell for multicell block
2501 grid
.GetCellSize(j
, i
, &c_rows
, &c_cols
);
2504 if (!grid
.GetTable()->IsEmptyCell(j
+ c_rows
, i
))
2513 rect
.width
+= grid
.GetColSize(i
);
2521 if (rect
.width
>= best_width
)
2525 overflowCols
= i
- col
- cell_cols
+ 1;
2526 if (overflowCols
>= cols
)
2527 overflowCols
= cols
- 1;
2530 if (overflowCols
> 0) // redraw overflow cells w/ proper hilight
2532 hAlign
= wxALIGN_LEFT
; // if oveflowed then it's left aligned
2534 clip
.x
+= rectCell
.width
;
2535 // draw each overflow cell individually
2536 int col_end
= col
+ cell_cols
+ overflowCols
;
2537 if (col_end
>= grid
.GetNumberCols())
2538 col_end
= grid
.GetNumberCols() - 1;
2539 for (int i
= col
+ cell_cols
; i
<= col_end
; i
++)
2541 clip
.width
= grid
.GetColSize(i
) - 1;
2542 dc
.DestroyClippingRegion();
2543 dc
.SetClippingRegion(clip
);
2545 SetTextColoursAndFont(grid
, attr
, dc
,
2546 grid
.IsInSelection(row
,i
));
2548 grid
.DrawTextRectangle(dc
, grid
.GetCellValue(row
, col
),
2549 rect
, hAlign
, vAlign
);
2550 clip
.x
+= grid
.GetColSize(i
) - 1;
2556 dc
.DestroyClippingRegion();
2560 // now we only have to draw the text
2561 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2563 grid
.DrawTextRectangle(dc
, grid
.GetCellValue(row
, col
),
2564 rect
, hAlign
, vAlign
);
2567 // ----------------------------------------------------------------------------
2568 // wxGridCellNumberRenderer
2569 // ----------------------------------------------------------------------------
2571 wxString
wxGridCellNumberRenderer::GetString(const wxGrid
& grid
, int row
, int col
)
2573 wxGridTableBase
*table
= grid
.GetTable();
2575 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
2577 text
.Printf(_T("%ld"), table
->GetValueAsLong(row
, col
));
2581 text
= table
->GetValue(row
, col
);
2587 void wxGridCellNumberRenderer::Draw(wxGrid
& grid
,
2588 wxGridCellAttr
& attr
,
2590 const wxRect
& rectCell
,
2594 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2596 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2598 // draw the text right aligned by default
2600 attr
.GetAlignment(&hAlign
, &vAlign
);
2601 hAlign
= wxALIGN_RIGHT
;
2603 wxRect rect
= rectCell
;
2606 grid
.DrawTextRectangle(dc
, GetString(grid
, row
, col
), rect
, hAlign
, vAlign
);
2609 wxSize
wxGridCellNumberRenderer::GetBestSize(wxGrid
& grid
,
2610 wxGridCellAttr
& attr
,
2614 return DoGetBestSize(attr
, dc
, GetString(grid
, row
, col
));
2617 // ----------------------------------------------------------------------------
2618 // wxGridCellFloatRenderer
2619 // ----------------------------------------------------------------------------
2621 wxGridCellFloatRenderer::wxGridCellFloatRenderer(int width
, int precision
)
2624 SetPrecision(precision
);
2627 wxGridCellRenderer
*wxGridCellFloatRenderer::Clone() const
2629 wxGridCellFloatRenderer
*renderer
= new wxGridCellFloatRenderer
;
2630 renderer
->m_width
= m_width
;
2631 renderer
->m_precision
= m_precision
;
2632 renderer
->m_format
= m_format
;
2637 wxString
wxGridCellFloatRenderer::GetString(const wxGrid
& grid
, int row
, int col
)
2639 wxGridTableBase
*table
= grid
.GetTable();
2644 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
2646 val
= table
->GetValueAsDouble(row
, col
);
2651 text
= table
->GetValue(row
, col
);
2652 hasDouble
= text
.ToDouble(&val
);
2659 if ( m_width
== -1 )
2661 if ( m_precision
== -1 )
2663 // default width/precision
2664 m_format
= _T("%f");
2668 m_format
.Printf(_T("%%.%df"), m_precision
);
2671 else if ( m_precision
== -1 )
2673 // default precision
2674 m_format
.Printf(_T("%%%d.f"), m_width
);
2678 m_format
.Printf(_T("%%%d.%df"), m_width
, m_precision
);
2682 text
.Printf(m_format
, val
);
2685 //else: text already contains the string
2690 void wxGridCellFloatRenderer::Draw(wxGrid
& grid
,
2691 wxGridCellAttr
& attr
,
2693 const wxRect
& rectCell
,
2697 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2699 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2701 // draw the text right aligned by default
2703 attr
.GetAlignment(&hAlign
, &vAlign
);
2704 hAlign
= wxALIGN_RIGHT
;
2706 wxRect rect
= rectCell
;
2709 grid
.DrawTextRectangle(dc
, GetString(grid
, row
, col
), rect
, hAlign
, vAlign
);
2712 wxSize
wxGridCellFloatRenderer::GetBestSize(wxGrid
& grid
,
2713 wxGridCellAttr
& attr
,
2717 return DoGetBestSize(attr
, dc
, GetString(grid
, row
, col
));
2720 void wxGridCellFloatRenderer::SetParameters(const wxString
& params
)
2724 // reset to defaults
2730 wxString tmp
= params
.BeforeFirst(_T(','));
2734 if ( tmp
.ToLong(&width
) )
2736 SetWidth((int)width
);
2740 wxLogDebug(_T("Invalid wxGridCellFloatRenderer width parameter string '%s ignored"), params
.c_str());
2744 tmp
= params
.AfterFirst(_T(','));
2748 if ( tmp
.ToLong(&precision
) )
2750 SetPrecision((int)precision
);
2754 wxLogDebug(_T("Invalid wxGridCellFloatRenderer precision parameter string '%s ignored"), params
.c_str());
2760 // ----------------------------------------------------------------------------
2761 // wxGridCellBoolRenderer
2762 // ----------------------------------------------------------------------------
2764 wxSize
wxGridCellBoolRenderer::ms_sizeCheckMark
;
2766 // FIXME these checkbox size calculations are really ugly...
2768 // between checkmark and box
2769 static const wxCoord wxGRID_CHECKMARK_MARGIN
= 2;
2771 wxSize
wxGridCellBoolRenderer::GetBestSize(wxGrid
& grid
,
2772 wxGridCellAttr
& WXUNUSED(attr
),
2777 // compute it only once (no locks for MT safeness in GUI thread...)
2778 if ( !ms_sizeCheckMark
.x
)
2780 // get checkbox size
2781 wxCheckBox
*checkbox
= new wxCheckBox(&grid
, wxID_ANY
, wxEmptyString
);
2782 wxSize size
= checkbox
->GetBestSize();
2783 wxCoord checkSize
= size
.y
+ 2 * wxGRID_CHECKMARK_MARGIN
;
2785 #if defined(__WXMOTIF__)
2786 checkSize
-= size
.y
/ 2;
2791 ms_sizeCheckMark
.x
= ms_sizeCheckMark
.y
= checkSize
;
2794 return ms_sizeCheckMark
;
2797 void wxGridCellBoolRenderer::Draw(wxGrid
& grid
,
2798 wxGridCellAttr
& attr
,
2804 wxGridCellRenderer::Draw(grid
, attr
, dc
, rect
, row
, col
, isSelected
);
2806 // draw a check mark in the centre (ignoring alignment - TODO)
2807 wxSize size
= GetBestSize(grid
, attr
, dc
, row
, col
);
2809 // don't draw outside the cell
2810 wxCoord minSize
= wxMin(rect
.width
, rect
.height
);
2811 if ( size
.x
>= minSize
|| size
.y
>= minSize
)
2813 // and even leave (at least) 1 pixel margin
2814 size
.x
= size
.y
= minSize
;
2817 // draw a border around checkmark
2819 attr
.GetAlignment(&hAlign
, &vAlign
);
2822 if (hAlign
== wxALIGN_CENTRE
)
2824 rectBorder
.x
= rect
.x
+ rect
.width
/ 2 - size
.x
/ 2;
2825 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2826 rectBorder
.width
= size
.x
;
2827 rectBorder
.height
= size
.y
;
2829 else if (hAlign
== wxALIGN_LEFT
)
2831 rectBorder
.x
= rect
.x
+ 2;
2832 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2833 rectBorder
.width
= size
.x
;
2834 rectBorder
.height
= size
.y
;
2836 else if (hAlign
== wxALIGN_RIGHT
)
2838 rectBorder
.x
= rect
.x
+ rect
.width
- size
.x
- 2;
2839 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2840 rectBorder
.width
= size
.x
;
2841 rectBorder
.height
= size
.y
;
2845 if ( grid
.GetTable()->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
) )
2847 value
= grid
.GetTable()->GetValueAsBool(row
, col
);
2851 wxString
cellval( grid
.GetTable()->GetValue(row
, col
) );
2852 value
= wxGridCellBoolEditor::IsTrueValue(cellval
);
2857 flags
|= wxCONTROL_CHECKED
;
2859 wxRendererNative::Get().DrawCheckBox( &grid
, dc
, rectBorder
, flags
);
2862 // ----------------------------------------------------------------------------
2864 // ----------------------------------------------------------------------------
2866 void wxGridCellAttr::Init(wxGridCellAttr
*attrDefault
)
2870 m_isReadOnly
= Unset
;
2875 m_attrkind
= wxGridCellAttr::Cell
;
2877 m_sizeRows
= m_sizeCols
= 1;
2878 m_overflow
= UnsetOverflow
;
2880 SetDefAttr(attrDefault
);
2883 wxGridCellAttr
*wxGridCellAttr::Clone() const
2885 wxGridCellAttr
*attr
= new wxGridCellAttr(m_defGridAttr
);
2887 if ( HasTextColour() )
2888 attr
->SetTextColour(GetTextColour());
2889 if ( HasBackgroundColour() )
2890 attr
->SetBackgroundColour(GetBackgroundColour());
2892 attr
->SetFont(GetFont());
2893 if ( HasAlignment() )
2894 attr
->SetAlignment(m_hAlign
, m_vAlign
);
2896 attr
->SetSize( m_sizeRows
, m_sizeCols
);
2900 attr
->SetRenderer(m_renderer
);
2901 m_renderer
->IncRef();
2905 attr
->SetEditor(m_editor
);
2910 attr
->SetReadOnly();
2912 attr
->SetOverflow( m_overflow
== Overflow
);
2913 attr
->SetKind( m_attrkind
);
2918 void wxGridCellAttr::MergeWith(wxGridCellAttr
*mergefrom
)
2920 if ( !HasTextColour() && mergefrom
->HasTextColour() )
2921 SetTextColour(mergefrom
->GetTextColour());
2922 if ( !HasBackgroundColour() && mergefrom
->HasBackgroundColour() )
2923 SetBackgroundColour(mergefrom
->GetBackgroundColour());
2924 if ( !HasFont() && mergefrom
->HasFont() )
2925 SetFont(mergefrom
->GetFont());
2926 if ( !HasAlignment() && mergefrom
->HasAlignment() )
2929 mergefrom
->GetAlignment( &hAlign
, &vAlign
);
2930 SetAlignment(hAlign
, vAlign
);
2932 if ( !HasSize() && mergefrom
->HasSize() )
2933 mergefrom
->GetSize( &m_sizeRows
, &m_sizeCols
);
2935 // Directly access member functions as GetRender/Editor don't just return
2936 // m_renderer/m_editor
2938 // Maybe add support for merge of Render and Editor?
2939 if (!HasRenderer() && mergefrom
->HasRenderer() )
2941 m_renderer
= mergefrom
->m_renderer
;
2942 m_renderer
->IncRef();
2944 if ( !HasEditor() && mergefrom
->HasEditor() )
2946 m_editor
= mergefrom
->m_editor
;
2949 if ( !HasReadWriteMode() && mergefrom
->HasReadWriteMode() )
2950 SetReadOnly(mergefrom
->IsReadOnly());
2952 if (!HasOverflowMode() && mergefrom
->HasOverflowMode() )
2953 SetOverflow(mergefrom
->GetOverflow());
2955 SetDefAttr(mergefrom
->m_defGridAttr
);
2958 void wxGridCellAttr::SetSize(int num_rows
, int num_cols
)
2960 // The size of a cell is normally 1,1
2962 // If this cell is larger (2,2) then this is the top left cell
2963 // the other cells that will be covered (lower right cells) must be
2964 // set to negative or zero values such that
2965 // row + num_rows of the covered cell points to the larger cell (this cell)
2966 // same goes for the col + num_cols.
2968 // Size of 0,0 is NOT valid, neither is <=0 and any positive value
2970 wxASSERT_MSG( (!((num_rows
> 0) && (num_cols
<= 0)) ||
2971 !((num_rows
<= 0) && (num_cols
> 0)) ||
2972 !((num_rows
== 0) && (num_cols
== 0))),
2973 wxT("wxGridCellAttr::SetSize only takes two postive values or negative/zero values"));
2975 m_sizeRows
= num_rows
;
2976 m_sizeCols
= num_cols
;
2979 const wxColour
& wxGridCellAttr::GetTextColour() const
2981 if (HasTextColour())
2985 else if (m_defGridAttr
&& m_defGridAttr
!= this)
2987 return m_defGridAttr
->GetTextColour();
2991 wxFAIL_MSG(wxT("Missing default cell attribute"));
2992 return wxNullColour
;
2996 const wxColour
& wxGridCellAttr::GetBackgroundColour() const
2998 if (HasBackgroundColour())
3002 else if (m_defGridAttr
&& m_defGridAttr
!= this)
3004 return m_defGridAttr
->GetBackgroundColour();
3008 wxFAIL_MSG(wxT("Missing default cell attribute"));
3009 return wxNullColour
;
3013 const wxFont
& wxGridCellAttr::GetFont() const
3019 else if (m_defGridAttr
&& m_defGridAttr
!= this)
3021 return m_defGridAttr
->GetFont();
3025 wxFAIL_MSG(wxT("Missing default cell attribute"));
3030 void wxGridCellAttr::GetAlignment(int *hAlign
, int *vAlign
) const
3039 else if (m_defGridAttr
&& m_defGridAttr
!= this)
3041 m_defGridAttr
->GetAlignment(hAlign
, vAlign
);
3045 wxFAIL_MSG(wxT("Missing default cell attribute"));
3049 void wxGridCellAttr::GetSize( int *num_rows
, int *num_cols
) const
3052 *num_rows
= m_sizeRows
;
3054 *num_cols
= m_sizeCols
;
3057 // GetRenderer and GetEditor use a slightly different decision path about
3058 // which attribute to use. If a non-default attr object has one then it is
3059 // used, otherwise the default editor or renderer is fetched from the grid and
3060 // used. It should be the default for the data type of the cell. If it is
3061 // NULL (because the table has a type that the grid does not have in its
3062 // registry), then the grid's default editor or renderer is used.
3064 wxGridCellRenderer
* wxGridCellAttr::GetRenderer(const wxGrid
* grid
, int row
, int col
) const
3066 wxGridCellRenderer
*renderer
= NULL
;
3068 if ( m_renderer
&& this != m_defGridAttr
)
3070 // use the cells renderer if it has one
3071 renderer
= m_renderer
;
3074 else // no non-default cell renderer
3076 // get default renderer for the data type
3079 // GetDefaultRendererForCell() will do IncRef() for us
3080 renderer
= grid
->GetDefaultRendererForCell(row
, col
);
3083 if ( renderer
== NULL
)
3085 if ( (m_defGridAttr
!= NULL
) && (m_defGridAttr
!= this) )
3087 // if we still don't have one then use the grid default
3088 // (no need for IncRef() here neither)
3089 renderer
= m_defGridAttr
->GetRenderer(NULL
, 0, 0);
3091 else // default grid attr
3093 // use m_renderer which we had decided not to use initially
3094 renderer
= m_renderer
;
3101 // we're supposed to always find something
3102 wxASSERT_MSG(renderer
, wxT("Missing default cell renderer"));
3107 // same as above, except for s/renderer/editor/g
3108 wxGridCellEditor
* wxGridCellAttr::GetEditor(const wxGrid
* grid
, int row
, int col
) const
3110 wxGridCellEditor
*editor
= NULL
;
3112 if ( m_editor
&& this != m_defGridAttr
)
3114 // use the cells editor if it has one
3118 else // no non default cell editor
3120 // get default editor for the data type
3123 // GetDefaultEditorForCell() will do IncRef() for us
3124 editor
= grid
->GetDefaultEditorForCell(row
, col
);
3127 if ( editor
== NULL
)
3129 if ( (m_defGridAttr
!= NULL
) && (m_defGridAttr
!= this) )
3131 // if we still don't have one then use the grid default
3132 // (no need for IncRef() here neither)
3133 editor
= m_defGridAttr
->GetEditor(NULL
, 0, 0);
3135 else // default grid attr
3137 // use m_editor which we had decided not to use initially
3145 // we're supposed to always find something
3146 wxASSERT_MSG(editor
, wxT("Missing default cell editor"));
3151 // ----------------------------------------------------------------------------
3152 // wxGridCellAttrData
3153 // ----------------------------------------------------------------------------
3155 void wxGridCellAttrData::SetAttr(wxGridCellAttr
*attr
, int row
, int col
)
3157 // Note: contrary to wxGridRowOrColAttrData::SetAttr, we must not
3158 // touch attribute's reference counting explicitly, since this
3159 // is managed by class wxGridCellWithAttr
3160 int n
= FindIndex(row
, col
);
3161 if ( n
== wxNOT_FOUND
)
3165 // add the attribute
3166 m_attrs
.Add(new wxGridCellWithAttr(row
, col
, attr
));
3168 //else: nothing to do
3170 else // we already have an attribute for this cell
3174 // change the attribute
3175 m_attrs
[(size_t)n
].ChangeAttr(attr
);
3179 // remove this attribute
3180 m_attrs
.RemoveAt((size_t)n
);
3185 wxGridCellAttr
*wxGridCellAttrData::GetAttr(int row
, int col
) const
3187 wxGridCellAttr
*attr
= NULL
;
3189 int n
= FindIndex(row
, col
);
3190 if ( n
!= wxNOT_FOUND
)
3192 attr
= m_attrs
[(size_t)n
].attr
;
3199 void wxGridCellAttrData::UpdateAttrRows( size_t pos
, int numRows
)
3201 size_t count
= m_attrs
.GetCount();
3202 for ( size_t n
= 0; n
< count
; n
++ )
3204 wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3205 wxCoord row
= coords
.GetRow();
3206 if ((size_t)row
>= pos
)
3210 // If rows inserted, include row counter where necessary
3211 coords
.SetRow(row
+ numRows
);
3213 else if (numRows
< 0)
3215 // If rows deleted ...
3216 if ((size_t)row
>= pos
- numRows
)
3218 // ...either decrement row counter (if row still exists)...
3219 coords
.SetRow(row
+ numRows
);
3223 // ...or remove the attribute
3224 m_attrs
.RemoveAt(n
);
3233 void wxGridCellAttrData::UpdateAttrCols( size_t pos
, int numCols
)
3235 size_t count
= m_attrs
.GetCount();
3236 for ( size_t n
= 0; n
< count
; n
++ )
3238 wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3239 wxCoord col
= coords
.GetCol();
3240 if ( (size_t)col
>= pos
)
3244 // If rows inserted, include row counter where necessary
3245 coords
.SetCol(col
+ numCols
);
3247 else if (numCols
< 0)
3249 // If rows deleted ...
3250 if ((size_t)col
>= pos
- numCols
)
3252 // ...either decrement row counter (if row still exists)...
3253 coords
.SetCol(col
+ numCols
);
3257 // ...or remove the attribute
3258 m_attrs
.RemoveAt(n
);
3267 int wxGridCellAttrData::FindIndex(int row
, int col
) const
3269 size_t count
= m_attrs
.GetCount();
3270 for ( size_t n
= 0; n
< count
; n
++ )
3272 const wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3273 if ( (coords
.GetRow() == row
) && (coords
.GetCol() == col
) )
3282 // ----------------------------------------------------------------------------
3283 // wxGridRowOrColAttrData
3284 // ----------------------------------------------------------------------------
3286 wxGridRowOrColAttrData::~wxGridRowOrColAttrData()
3288 size_t count
= m_attrs
.GetCount();
3289 for ( size_t n
= 0; n
< count
; n
++ )
3291 m_attrs
[n
]->DecRef();
3295 wxGridCellAttr
*wxGridRowOrColAttrData::GetAttr(int rowOrCol
) const
3297 wxGridCellAttr
*attr
= NULL
;
3299 int n
= m_rowsOrCols
.Index(rowOrCol
);
3300 if ( n
!= wxNOT_FOUND
)
3302 attr
= m_attrs
[(size_t)n
];
3309 void wxGridRowOrColAttrData::SetAttr(wxGridCellAttr
*attr
, int rowOrCol
)
3311 int i
= m_rowsOrCols
.Index(rowOrCol
);
3312 if ( i
== wxNOT_FOUND
)
3316 // add the attribute - no need to do anything to reference count
3317 // since we take ownership of the attribute.
3318 m_rowsOrCols
.Add(rowOrCol
);
3321 // nothing to remove
3325 size_t n
= (size_t)i
;
3326 if ( m_attrs
[n
] == attr
)
3331 // change the attribute, handling reference count manually,
3332 // taking ownership of the new attribute.
3333 m_attrs
[n
]->DecRef();
3338 // remove this attribute, handling reference count manually
3339 m_attrs
[n
]->DecRef();
3340 m_rowsOrCols
.RemoveAt(n
);
3341 m_attrs
.RemoveAt(n
);
3346 void wxGridRowOrColAttrData::UpdateAttrRowsOrCols( size_t pos
, int numRowsOrCols
)
3348 size_t count
= m_attrs
.GetCount();
3349 for ( size_t n
= 0; n
< count
; n
++ )
3351 int & rowOrCol
= m_rowsOrCols
[n
];
3352 if ( (size_t)rowOrCol
>= pos
)
3354 if ( numRowsOrCols
> 0 )
3356 // If rows inserted, include row counter where necessary
3357 rowOrCol
+= numRowsOrCols
;
3359 else if ( numRowsOrCols
< 0)
3361 // If rows deleted, either decrement row counter (if row still exists)
3362 if ((size_t)rowOrCol
>= pos
- numRowsOrCols
)
3363 rowOrCol
+= numRowsOrCols
;
3366 m_rowsOrCols
.RemoveAt(n
);
3367 m_attrs
[n
]->DecRef();
3368 m_attrs
.RemoveAt(n
);
3377 // ----------------------------------------------------------------------------
3378 // wxGridCellAttrProvider
3379 // ----------------------------------------------------------------------------
3381 wxGridCellAttrProvider::wxGridCellAttrProvider()
3386 wxGridCellAttrProvider::~wxGridCellAttrProvider()
3391 void wxGridCellAttrProvider::InitData()
3393 m_data
= new wxGridCellAttrProviderData
;
3396 wxGridCellAttr
*wxGridCellAttrProvider::GetAttr(int row
, int col
,
3397 wxGridCellAttr::wxAttrKind kind
) const
3399 wxGridCellAttr
*attr
= NULL
;
3404 case (wxGridCellAttr::Any
):
3405 // Get cached merge attributes.
3406 // Currently not used as no cache implemented as not mutable
3407 // attr = m_data->m_mergeAttr.GetAttr(row, col);
3410 // Basically implement old version.
3411 // Also check merge cache, so we don't have to re-merge every time..
3412 wxGridCellAttr
*attrcell
= m_data
->m_cellAttrs
.GetAttr(row
, col
);
3413 wxGridCellAttr
*attrrow
= m_data
->m_rowAttrs
.GetAttr(row
);
3414 wxGridCellAttr
*attrcol
= m_data
->m_colAttrs
.GetAttr(col
);
3416 if ((attrcell
!= attrrow
) && (attrrow
!= attrcol
) && (attrcell
!= attrcol
))
3418 // Two or more are non NULL
3419 attr
= new wxGridCellAttr
;
3420 attr
->SetKind(wxGridCellAttr::Merged
);
3422 // Order is important..
3425 attr
->MergeWith(attrcell
);
3430 attr
->MergeWith(attrcol
);
3435 attr
->MergeWith(attrrow
);
3439 // store merge attr if cache implemented
3441 //m_data->m_mergeAttr.SetAttr(attr, row, col);
3445 // one or none is non null return it or null.
3464 case (wxGridCellAttr::Cell
):
3465 attr
= m_data
->m_cellAttrs
.GetAttr(row
, col
);
3468 case (wxGridCellAttr::Col
):
3469 attr
= m_data
->m_colAttrs
.GetAttr(col
);
3472 case (wxGridCellAttr::Row
):
3473 attr
= m_data
->m_rowAttrs
.GetAttr(row
);
3478 // (wxGridCellAttr::Default):
3479 // (wxGridCellAttr::Merged):
3487 void wxGridCellAttrProvider::SetAttr(wxGridCellAttr
*attr
,
3493 m_data
->m_cellAttrs
.SetAttr(attr
, row
, col
);
3496 void wxGridCellAttrProvider::SetRowAttr(wxGridCellAttr
*attr
, int row
)
3501 m_data
->m_rowAttrs
.SetAttr(attr
, row
);
3504 void wxGridCellAttrProvider::SetColAttr(wxGridCellAttr
*attr
, int col
)
3509 m_data
->m_colAttrs
.SetAttr(attr
, col
);
3512 void wxGridCellAttrProvider::UpdateAttrRows( size_t pos
, int numRows
)
3516 m_data
->m_cellAttrs
.UpdateAttrRows( pos
, numRows
);
3518 m_data
->m_rowAttrs
.UpdateAttrRowsOrCols( pos
, numRows
);
3522 void wxGridCellAttrProvider::UpdateAttrCols( size_t pos
, int numCols
)
3526 m_data
->m_cellAttrs
.UpdateAttrCols( pos
, numCols
);
3528 m_data
->m_colAttrs
.UpdateAttrRowsOrCols( pos
, numCols
);
3532 // ----------------------------------------------------------------------------
3533 // wxGridTypeRegistry
3534 // ----------------------------------------------------------------------------
3536 wxGridTypeRegistry::~wxGridTypeRegistry()
3538 size_t count
= m_typeinfo
.GetCount();
3539 for ( size_t i
= 0; i
< count
; i
++ )
3540 delete m_typeinfo
[i
];
3543 void wxGridTypeRegistry::RegisterDataType(const wxString
& typeName
,
3544 wxGridCellRenderer
* renderer
,
3545 wxGridCellEditor
* editor
)
3547 wxGridDataTypeInfo
* info
= new wxGridDataTypeInfo(typeName
, renderer
, editor
);
3549 // is it already registered?
3550 int loc
= FindRegisteredDataType(typeName
);
3551 if ( loc
!= wxNOT_FOUND
)
3553 delete m_typeinfo
[loc
];
3554 m_typeinfo
[loc
] = info
;
3558 m_typeinfo
.Add(info
);
3562 int wxGridTypeRegistry::FindRegisteredDataType(const wxString
& typeName
)
3564 size_t count
= m_typeinfo
.GetCount();
3565 for ( size_t i
= 0; i
< count
; i
++ )
3567 if ( typeName
== m_typeinfo
[i
]->m_typeName
)
3576 int wxGridTypeRegistry::FindDataType(const wxString
& typeName
)
3578 int index
= FindRegisteredDataType(typeName
);
3579 if ( index
== wxNOT_FOUND
)
3581 // check whether this is one of the standard ones, in which case
3582 // register it "on the fly"
3584 if ( typeName
== wxGRID_VALUE_STRING
)
3586 RegisterDataType(wxGRID_VALUE_STRING
,
3587 new wxGridCellStringRenderer
,
3588 new wxGridCellTextEditor
);
3591 #endif // wxUSE_TEXTCTRL
3593 if ( typeName
== wxGRID_VALUE_BOOL
)
3595 RegisterDataType(wxGRID_VALUE_BOOL
,
3596 new wxGridCellBoolRenderer
,
3597 new wxGridCellBoolEditor
);
3600 #endif // wxUSE_CHECKBOX
3602 if ( typeName
== wxGRID_VALUE_NUMBER
)
3604 RegisterDataType(wxGRID_VALUE_NUMBER
,
3605 new wxGridCellNumberRenderer
,
3606 new wxGridCellNumberEditor
);
3608 else if ( typeName
== wxGRID_VALUE_FLOAT
)
3610 RegisterDataType(wxGRID_VALUE_FLOAT
,
3611 new wxGridCellFloatRenderer
,
3612 new wxGridCellFloatEditor
);
3615 #endif // wxUSE_TEXTCTRL
3617 if ( typeName
== wxGRID_VALUE_CHOICE
)
3619 RegisterDataType(wxGRID_VALUE_CHOICE
,
3620 new wxGridCellStringRenderer
,
3621 new wxGridCellChoiceEditor
);
3624 #endif // wxUSE_COMBOBOX
3629 // we get here only if just added the entry for this type, so return
3631 index
= m_typeinfo
.GetCount() - 1;
3637 int wxGridTypeRegistry::FindOrCloneDataType(const wxString
& typeName
)
3639 int index
= FindDataType(typeName
);
3640 if ( index
== wxNOT_FOUND
)
3642 // the first part of the typename is the "real" type, anything after ':'
3643 // are the parameters for the renderer
3644 index
= FindDataType(typeName
.BeforeFirst(_T(':')));
3645 if ( index
== wxNOT_FOUND
)
3650 wxGridCellRenderer
*renderer
= GetRenderer(index
);
3651 wxGridCellRenderer
*rendererOld
= renderer
;
3652 renderer
= renderer
->Clone();
3653 rendererOld
->DecRef();
3655 wxGridCellEditor
*editor
= GetEditor(index
);
3656 wxGridCellEditor
*editorOld
= editor
;
3657 editor
= editor
->Clone();
3658 editorOld
->DecRef();
3660 // do it even if there are no parameters to reset them to defaults
3661 wxString params
= typeName
.AfterFirst(_T(':'));
3662 renderer
->SetParameters(params
);
3663 editor
->SetParameters(params
);
3665 // register the new typename
3666 RegisterDataType(typeName
, renderer
, editor
);
3668 // we just registered it, it's the last one
3669 index
= m_typeinfo
.GetCount() - 1;
3675 wxGridCellRenderer
* wxGridTypeRegistry::GetRenderer(int index
)
3677 wxGridCellRenderer
* renderer
= m_typeinfo
[index
]->m_renderer
;
3684 wxGridCellEditor
* wxGridTypeRegistry::GetEditor(int index
)
3686 wxGridCellEditor
* editor
= m_typeinfo
[index
]->m_editor
;
3693 // ----------------------------------------------------------------------------
3695 // ----------------------------------------------------------------------------
3697 IMPLEMENT_ABSTRACT_CLASS( wxGridTableBase
, wxObject
)
3699 wxGridTableBase::wxGridTableBase()
3702 m_attrProvider
= NULL
;
3705 wxGridTableBase::~wxGridTableBase()
3707 delete m_attrProvider
;
3710 void wxGridTableBase::SetAttrProvider(wxGridCellAttrProvider
*attrProvider
)
3712 delete m_attrProvider
;
3713 m_attrProvider
= attrProvider
;
3716 bool wxGridTableBase::CanHaveAttributes()
3718 if ( ! GetAttrProvider() )
3720 // use the default attr provider by default
3721 SetAttrProvider(new wxGridCellAttrProvider
);
3727 wxGridCellAttr
*wxGridTableBase::GetAttr(int row
, int col
, wxGridCellAttr::wxAttrKind kind
)
3729 if ( m_attrProvider
)
3730 return m_attrProvider
->GetAttr(row
, col
, kind
);
3735 void wxGridTableBase::SetAttr(wxGridCellAttr
* attr
, int row
, int col
)
3737 if ( m_attrProvider
)
3740 attr
->SetKind(wxGridCellAttr::Cell
);
3741 m_attrProvider
->SetAttr(attr
, row
, col
);
3745 // as we take ownership of the pointer and don't store it, we must
3751 void wxGridTableBase::SetRowAttr(wxGridCellAttr
*attr
, int row
)
3753 if ( m_attrProvider
)
3755 attr
->SetKind(wxGridCellAttr::Row
);
3756 m_attrProvider
->SetRowAttr(attr
, row
);
3760 // as we take ownership of the pointer and don't store it, we must
3766 void wxGridTableBase::SetColAttr(wxGridCellAttr
*attr
, int col
)
3768 if ( m_attrProvider
)
3770 attr
->SetKind(wxGridCellAttr::Col
);
3771 m_attrProvider
->SetColAttr(attr
, col
);
3775 // as we take ownership of the pointer and don't store it, we must
3781 bool wxGridTableBase::InsertRows( size_t WXUNUSED(pos
),
3782 size_t WXUNUSED(numRows
) )
3784 wxFAIL_MSG( wxT("Called grid table class function InsertRows\nbut your derived table class does not override this function") );
3789 bool wxGridTableBase::AppendRows( size_t WXUNUSED(numRows
) )
3791 wxFAIL_MSG( wxT("Called grid table class function AppendRows\nbut your derived table class does not override this function"));
3796 bool wxGridTableBase::DeleteRows( size_t WXUNUSED(pos
),
3797 size_t WXUNUSED(numRows
) )
3799 wxFAIL_MSG( wxT("Called grid table class function DeleteRows\nbut your derived table class does not override this function"));
3804 bool wxGridTableBase::InsertCols( size_t WXUNUSED(pos
),
3805 size_t WXUNUSED(numCols
) )
3807 wxFAIL_MSG( wxT("Called grid table class function InsertCols\nbut your derived table class does not override this function"));
3812 bool wxGridTableBase::AppendCols( size_t WXUNUSED(numCols
) )
3814 wxFAIL_MSG(wxT("Called grid table class function AppendCols\nbut your derived table class does not override this function"));
3819 bool wxGridTableBase::DeleteCols( size_t WXUNUSED(pos
),
3820 size_t WXUNUSED(numCols
) )
3822 wxFAIL_MSG( wxT("Called grid table class function DeleteCols\nbut your derived table class does not override this function"));
3827 wxString
wxGridTableBase::GetRowLabelValue( int row
)
3831 // RD: Starting the rows at zero confuses users,
3832 // no matter how much it makes sense to us geeks.
3838 wxString
wxGridTableBase::GetColLabelValue( int col
)
3840 // default col labels are:
3841 // cols 0 to 25 : A-Z
3842 // cols 26 to 675 : AA-ZZ
3847 for ( n
= 1; ; n
++ )
3849 s
+= (wxChar
) (_T('A') + (wxChar
)(col
% 26));
3855 // reverse the string...
3857 for ( i
= 0; i
< n
; i
++ )
3865 wxString
wxGridTableBase::GetTypeName( int WXUNUSED(row
), int WXUNUSED(col
) )
3867 return wxGRID_VALUE_STRING
;
3870 bool wxGridTableBase::CanGetValueAs( int WXUNUSED(row
), int WXUNUSED(col
),
3871 const wxString
& typeName
)
3873 return typeName
== wxGRID_VALUE_STRING
;
3876 bool wxGridTableBase::CanSetValueAs( int row
, int col
, const wxString
& typeName
)
3878 return CanGetValueAs(row
, col
, typeName
);
3881 long wxGridTableBase::GetValueAsLong( int WXUNUSED(row
), int WXUNUSED(col
) )
3886 double wxGridTableBase::GetValueAsDouble( int WXUNUSED(row
), int WXUNUSED(col
) )
3891 bool wxGridTableBase::GetValueAsBool( int WXUNUSED(row
), int WXUNUSED(col
) )
3896 void wxGridTableBase::SetValueAsLong( int WXUNUSED(row
), int WXUNUSED(col
),
3897 long WXUNUSED(value
) )
3901 void wxGridTableBase::SetValueAsDouble( int WXUNUSED(row
), int WXUNUSED(col
),
3902 double WXUNUSED(value
) )
3906 void wxGridTableBase::SetValueAsBool( int WXUNUSED(row
), int WXUNUSED(col
),
3907 bool WXUNUSED(value
) )
3911 void* wxGridTableBase::GetValueAsCustom( int WXUNUSED(row
), int WXUNUSED(col
),
3912 const wxString
& WXUNUSED(typeName
) )
3917 void wxGridTableBase::SetValueAsCustom( int WXUNUSED(row
), int WXUNUSED(col
),
3918 const wxString
& WXUNUSED(typeName
),
3919 void* WXUNUSED(value
) )
3923 //////////////////////////////////////////////////////////////////////
3925 // Message class for the grid table to send requests and notifications
3929 wxGridTableMessage::wxGridTableMessage()
3937 wxGridTableMessage::wxGridTableMessage( wxGridTableBase
*table
, int id
,
3938 int commandInt1
, int commandInt2
)
3942 m_comInt1
= commandInt1
;
3943 m_comInt2
= commandInt2
;
3946 //////////////////////////////////////////////////////////////////////
3948 // A basic grid table for string data. An object of this class will
3949 // created by wxGrid if you don't specify an alternative table class.
3952 WX_DEFINE_OBJARRAY(wxGridStringArray
)
3954 IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable
, wxGridTableBase
)
3956 wxGridStringTable::wxGridStringTable()
3961 wxGridStringTable::wxGridStringTable( int numRows
, int numCols
)
3964 m_data
.Alloc( numRows
);
3967 sa
.Alloc( numCols
);
3968 sa
.Add( wxEmptyString
, numCols
);
3970 m_data
.Add( sa
, numRows
);
3973 wxGridStringTable::~wxGridStringTable()
3977 int wxGridStringTable::GetNumberRows()
3979 return m_data
.GetCount();
3982 int wxGridStringTable::GetNumberCols()
3984 if ( m_data
.GetCount() > 0 )
3985 return m_data
[0].GetCount();
3990 wxString
wxGridStringTable::GetValue( int row
, int col
)
3992 wxCHECK_MSG( (row
< GetNumberRows()) && (col
< GetNumberCols()),
3994 _T("invalid row or column index in wxGridStringTable") );
3996 return m_data
[row
][col
];
3999 void wxGridStringTable::SetValue( int row
, int col
, const wxString
& value
)
4001 wxCHECK_RET( (row
< GetNumberRows()) && (col
< GetNumberCols()),
4002 _T("invalid row or column index in wxGridStringTable") );
4004 m_data
[row
][col
] = value
;
4007 void wxGridStringTable::Clear()
4010 int numRows
, numCols
;
4012 numRows
= m_data
.GetCount();
4015 numCols
= m_data
[0].GetCount();
4017 for ( row
= 0; row
< numRows
; row
++ )
4019 for ( col
= 0; col
< numCols
; col
++ )
4021 m_data
[row
][col
] = wxEmptyString
;
4027 bool wxGridStringTable::InsertRows( size_t pos
, size_t numRows
)
4029 size_t curNumRows
= m_data
.GetCount();
4030 size_t curNumCols
= ( curNumRows
> 0 ? m_data
[0].GetCount() :
4031 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4033 if ( pos
>= curNumRows
)
4035 return AppendRows( numRows
);
4039 sa
.Alloc( curNumCols
);
4040 sa
.Add( wxEmptyString
, curNumCols
);
4041 m_data
.Insert( sa
, pos
, numRows
);
4045 wxGridTableMessage
msg( this,
4046 wxGRIDTABLE_NOTIFY_ROWS_INSERTED
,
4050 GetView()->ProcessTableMessage( msg
);
4056 bool wxGridStringTable::AppendRows( size_t numRows
)
4058 size_t curNumRows
= m_data
.GetCount();
4059 size_t curNumCols
= ( curNumRows
> 0
4060 ? m_data
[0].GetCount()
4061 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4064 if ( curNumCols
> 0 )
4066 sa
.Alloc( curNumCols
);
4067 sa
.Add( wxEmptyString
, curNumCols
);
4070 m_data
.Add( sa
, numRows
);
4074 wxGridTableMessage
msg( this,
4075 wxGRIDTABLE_NOTIFY_ROWS_APPENDED
,
4078 GetView()->ProcessTableMessage( msg
);
4084 bool wxGridStringTable::DeleteRows( size_t pos
, size_t numRows
)
4086 size_t curNumRows
= m_data
.GetCount();
4088 if ( pos
>= curNumRows
)
4090 wxFAIL_MSG( wxString::Format
4092 wxT("Called wxGridStringTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
4094 (unsigned long)numRows
,
4095 (unsigned long)curNumRows
4101 if ( numRows
> curNumRows
- pos
)
4103 numRows
= curNumRows
- pos
;
4106 if ( numRows
>= curNumRows
)
4112 m_data
.RemoveAt( pos
, numRows
);
4117 wxGridTableMessage
msg( this,
4118 wxGRIDTABLE_NOTIFY_ROWS_DELETED
,
4122 GetView()->ProcessTableMessage( msg
);
4128 bool wxGridStringTable::InsertCols( size_t pos
, size_t numCols
)
4132 size_t curNumRows
= m_data
.GetCount();
4133 size_t curNumCols
= ( curNumRows
> 0
4134 ? m_data
[0].GetCount()
4135 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4137 if ( pos
>= curNumCols
)
4139 return AppendCols( numCols
);
4142 if ( !m_colLabels
.IsEmpty() )
4144 m_colLabels
.Insert( wxEmptyString
, pos
, numCols
);
4147 for ( i
= pos
; i
< pos
+ numCols
; i
++ )
4148 m_colLabels
[i
] = wxGridTableBase::GetColLabelValue( i
);
4151 for ( row
= 0; row
< curNumRows
; row
++ )
4153 for ( col
= pos
; col
< pos
+ numCols
; col
++ )
4155 m_data
[row
].Insert( wxEmptyString
, col
);
4161 wxGridTableMessage
msg( this,
4162 wxGRIDTABLE_NOTIFY_COLS_INSERTED
,
4166 GetView()->ProcessTableMessage( msg
);
4172 bool wxGridStringTable::AppendCols( size_t numCols
)
4176 size_t curNumRows
= m_data
.GetCount();
4178 for ( row
= 0; row
< curNumRows
; row
++ )
4180 m_data
[row
].Add( wxEmptyString
, numCols
);
4185 wxGridTableMessage
msg( this,
4186 wxGRIDTABLE_NOTIFY_COLS_APPENDED
,
4189 GetView()->ProcessTableMessage( msg
);
4195 bool wxGridStringTable::DeleteCols( size_t pos
, size_t numCols
)
4199 size_t curNumRows
= m_data
.GetCount();
4200 size_t curNumCols
= ( curNumRows
> 0 ? m_data
[0].GetCount() :
4201 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4203 if ( pos
>= curNumCols
)
4205 wxFAIL_MSG( wxString::Format
4207 wxT("Called wxGridStringTable::DeleteCols(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu cols"),
4209 (unsigned long)numCols
,
4210 (unsigned long)curNumCols
4217 colID
= GetView()->GetColAt( pos
);
4221 if ( numCols
> curNumCols
- colID
)
4223 numCols
= curNumCols
- colID
;
4226 if ( !m_colLabels
.IsEmpty() )
4228 // m_colLabels stores just as many elements as it needs, e.g. if only
4229 // the label of the first column had been set it would have only one
4230 // element and not numCols, so account for it
4231 int nToRm
= m_colLabels
.size() - colID
;
4233 m_colLabels
.RemoveAt( colID
, nToRm
);
4236 for ( row
= 0; row
< curNumRows
; row
++ )
4238 if ( numCols
>= curNumCols
)
4240 m_data
[row
].Clear();
4244 m_data
[row
].RemoveAt( colID
, numCols
);
4250 wxGridTableMessage
msg( this,
4251 wxGRIDTABLE_NOTIFY_COLS_DELETED
,
4255 GetView()->ProcessTableMessage( msg
);
4261 wxString
wxGridStringTable::GetRowLabelValue( int row
)
4263 if ( row
> (int)(m_rowLabels
.GetCount()) - 1 )
4265 // using default label
4267 return wxGridTableBase::GetRowLabelValue( row
);
4271 return m_rowLabels
[row
];
4275 wxString
wxGridStringTable::GetColLabelValue( int col
)
4277 if ( col
> (int)(m_colLabels
.GetCount()) - 1 )
4279 // using default label
4281 return wxGridTableBase::GetColLabelValue( col
);
4285 return m_colLabels
[col
];
4289 void wxGridStringTable::SetRowLabelValue( int row
, const wxString
& value
)
4291 if ( row
> (int)(m_rowLabels
.GetCount()) - 1 )
4293 int n
= m_rowLabels
.GetCount();
4296 for ( i
= n
; i
<= row
; i
++ )
4298 m_rowLabels
.Add( wxGridTableBase::GetRowLabelValue(i
) );
4302 m_rowLabels
[row
] = value
;
4305 void wxGridStringTable::SetColLabelValue( int col
, const wxString
& value
)
4307 if ( col
> (int)(m_colLabels
.GetCount()) - 1 )
4309 int n
= m_colLabels
.GetCount();
4312 for ( i
= n
; i
<= col
; i
++ )
4314 m_colLabels
.Add( wxGridTableBase::GetColLabelValue(i
) );
4318 m_colLabels
[col
] = value
;
4322 //////////////////////////////////////////////////////////////////////
4323 //////////////////////////////////////////////////////////////////////
4325 BEGIN_EVENT_TABLE(wxGridSubwindow
, wxWindow
)
4326 EVT_MOUSE_CAPTURE_LOST(wxGridSubwindow::OnMouseCaptureLost
)
4329 void wxGridSubwindow::OnMouseCaptureLost(wxMouseCaptureLostEvent
& WXUNUSED(event
))
4331 m_owner
->CancelMouseCapture();
4334 BEGIN_EVENT_TABLE( wxGridRowLabelWindow
, wxGridSubwindow
)
4335 EVT_PAINT( wxGridRowLabelWindow::OnPaint
)
4336 EVT_MOUSEWHEEL( wxGridRowLabelWindow::OnMouseWheel
)
4337 EVT_MOUSE_EVENTS( wxGridRowLabelWindow::OnMouseEvent
)
4340 void wxGridRowLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4344 // NO - don't do this because it will set both the x and y origin
4345 // coords to match the parent scrolled window and we just want to
4346 // set the y coord - MB
4348 // m_owner->PrepareDC( dc );
4351 m_owner
->CalcUnscrolledPosition( 0, 0, &x
, &y
);
4352 wxPoint pt
= dc
.GetDeviceOrigin();
4353 dc
.SetDeviceOrigin( pt
.x
, pt
.y
-y
);
4355 wxArrayInt rows
= m_owner
->CalcRowLabelsExposed( GetUpdateRegion() );
4356 m_owner
->DrawRowLabels( dc
, rows
);
4359 void wxGridRowLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4361 m_owner
->ProcessRowLabelMouseEvent( event
);
4364 void wxGridRowLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4366 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4370 //////////////////////////////////////////////////////////////////////
4372 BEGIN_EVENT_TABLE( wxGridColLabelWindow
, wxGridSubwindow
)
4373 EVT_PAINT( wxGridColLabelWindow::OnPaint
)
4374 EVT_MOUSEWHEEL( wxGridColLabelWindow::OnMouseWheel
)
4375 EVT_MOUSE_EVENTS( wxGridColLabelWindow::OnMouseEvent
)
4378 void wxGridColLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4382 // NO - don't do this because it will set both the x and y origin
4383 // coords to match the parent scrolled window and we just want to
4384 // set the x coord - MB
4386 // m_owner->PrepareDC( dc );
4389 m_owner
->CalcUnscrolledPosition( 0, 0, &x
, &y
);
4390 wxPoint pt
= dc
.GetDeviceOrigin();
4391 if (GetLayoutDirection() == wxLayout_RightToLeft
)
4392 dc
.SetDeviceOrigin( pt
.x
+x
, pt
.y
);
4394 dc
.SetDeviceOrigin( pt
.x
-x
, pt
.y
);
4396 wxArrayInt cols
= m_owner
->CalcColLabelsExposed( GetUpdateRegion() );
4397 m_owner
->DrawColLabels( dc
, cols
);
4400 void wxGridColLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4402 m_owner
->ProcessColLabelMouseEvent( event
);
4405 void wxGridColLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4407 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4411 //////////////////////////////////////////////////////////////////////
4413 BEGIN_EVENT_TABLE( wxGridCornerLabelWindow
, wxGridSubwindow
)
4414 EVT_MOUSEWHEEL( wxGridCornerLabelWindow::OnMouseWheel
)
4415 EVT_MOUSE_EVENTS( wxGridCornerLabelWindow::OnMouseEvent
)
4416 EVT_PAINT( wxGridCornerLabelWindow::OnPaint
)
4419 void wxGridCornerLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4423 m_owner
->DrawCornerLabel(dc
);
4426 void wxGridCornerLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4428 m_owner
->ProcessCornerLabelMouseEvent( event
);
4431 void wxGridCornerLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4433 if (!m_owner
->GetEventHandler()->ProcessEvent(event
))
4437 //////////////////////////////////////////////////////////////////////
4439 BEGIN_EVENT_TABLE( wxGridWindow
, wxGridSubwindow
)
4440 EVT_PAINT( wxGridWindow::OnPaint
)
4441 EVT_MOUSEWHEEL( wxGridWindow::OnMouseWheel
)
4442 EVT_MOUSE_EVENTS( wxGridWindow::OnMouseEvent
)
4443 EVT_KEY_DOWN( wxGridWindow::OnKeyDown
)
4444 EVT_KEY_UP( wxGridWindow::OnKeyUp
)
4445 EVT_CHAR( wxGridWindow::OnChar
)
4446 EVT_SET_FOCUS( wxGridWindow::OnFocus
)
4447 EVT_KILL_FOCUS( wxGridWindow::OnFocus
)
4448 EVT_ERASE_BACKGROUND( wxGridWindow::OnEraseBackground
)
4451 void wxGridWindow::OnPaint( wxPaintEvent
&WXUNUSED(event
) )
4453 wxPaintDC
dc( this );
4454 m_owner
->PrepareDC( dc
);
4455 wxRegion reg
= GetUpdateRegion();
4456 wxGridCellCoordsArray dirtyCells
= m_owner
->CalcCellsExposed( reg
);
4457 m_owner
->DrawGridCellArea( dc
, dirtyCells
);
4459 m_owner
->DrawGridSpace( dc
);
4461 m_owner
->DrawAllGridLines( dc
, reg
);
4463 m_owner
->DrawHighlight( dc
, dirtyCells
);
4466 void wxGridWindow::ScrollWindow( int dx
, int dy
, const wxRect
*rect
)
4468 wxWindow::ScrollWindow( dx
, dy
, rect
);
4469 m_owner
->GetGridRowLabelWindow()->ScrollWindow( 0, dy
, rect
);
4470 m_owner
->GetGridColLabelWindow()->ScrollWindow( dx
, 0, rect
);
4473 void wxGridWindow::OnMouseEvent( wxMouseEvent
& event
)
4475 if (event
.ButtonDown(wxMOUSE_BTN_LEFT
) && FindFocus() != this)
4478 m_owner
->ProcessGridCellMouseEvent( event
);
4481 void wxGridWindow::OnMouseWheel( wxMouseEvent
& event
)
4483 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4487 // This seems to be required for wxMotif/wxGTK otherwise the mouse
4488 // cursor must be in the cell edit control to get key events
4490 void wxGridWindow::OnKeyDown( wxKeyEvent
& event
)
4492 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4496 void wxGridWindow::OnKeyUp( wxKeyEvent
& event
)
4498 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4502 void wxGridWindow::OnChar( wxKeyEvent
& event
)
4504 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4508 void wxGridWindow::OnEraseBackground( wxEraseEvent
& WXUNUSED(event
) )
4512 void wxGridWindow::OnFocus(wxFocusEvent
& event
)
4514 // and if we have any selection, it has to be repainted, because it
4515 // uses different colour when the grid is not focused:
4516 if ( m_owner
->IsSelection() )
4522 // NB: Note that this code is in "else" branch only because the other
4523 // branch refreshes everything and so there's no point in calling
4524 // Refresh() again, *not* because it should only be done if
4525 // !IsSelection(). If the above code is ever optimized to refresh
4526 // only selected area, this needs to be moved out of the "else"
4527 // branch so that it's always executed.
4529 // current cell cursor {dis,re}appears on focus change:
4530 const wxGridCellCoords
cursorCoords(m_owner
->GetGridCursorRow(),
4531 m_owner
->GetGridCursorCol());
4532 const wxRect cursor
=
4533 m_owner
->BlockToDeviceRect(cursorCoords
, cursorCoords
);
4534 Refresh(true, &cursor
);
4537 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4541 #define internalXToCol(x) XToCol(x, true)
4542 #define internalYToRow(y) YToRow(y, true)
4544 /////////////////////////////////////////////////////////////////////
4546 #if wxUSE_EXTENDED_RTTI
4547 WX_DEFINE_FLAGS( wxGridStyle
)
4549 wxBEGIN_FLAGS( wxGridStyle
)
4550 // new style border flags, we put them first to
4551 // use them for streaming out
4552 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
4553 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
4554 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
4555 wxFLAGS_MEMBER(wxBORDER_RAISED
)
4556 wxFLAGS_MEMBER(wxBORDER_STATIC
)
4557 wxFLAGS_MEMBER(wxBORDER_NONE
)
4559 // old style border flags
4560 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
4561 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
4562 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
4563 wxFLAGS_MEMBER(wxRAISED_BORDER
)
4564 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
4565 wxFLAGS_MEMBER(wxBORDER
)
4567 // standard window styles
4568 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
4569 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
4570 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
4571 wxFLAGS_MEMBER(wxWANTS_CHARS
)
4572 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
4573 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
4574 wxFLAGS_MEMBER(wxVSCROLL
)
4575 wxFLAGS_MEMBER(wxHSCROLL
)
4577 wxEND_FLAGS( wxGridStyle
)
4579 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid
, wxScrolledWindow
,"wx/grid.h")
4581 wxBEGIN_PROPERTIES_TABLE(wxGrid
)
4582 wxHIDE_PROPERTY( Children
)
4583 wxPROPERTY_FLAGS( WindowStyle
, wxGridStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
4584 wxEND_PROPERTIES_TABLE()
4586 wxBEGIN_HANDLERS_TABLE(wxGrid
)
4587 wxEND_HANDLERS_TABLE()
4589 wxCONSTRUCTOR_5( wxGrid
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
)
4592 TODO : Expose more information of a list's layout, etc. via appropriate objects (e.g., NotebookPageInfo)
4595 IMPLEMENT_DYNAMIC_CLASS( wxGrid
, wxScrolledWindow
)
4598 BEGIN_EVENT_TABLE( wxGrid
, wxScrolledWindow
)
4599 EVT_PAINT( wxGrid::OnPaint
)
4600 EVT_SIZE( wxGrid::OnSize
)
4601 EVT_KEY_DOWN( wxGrid::OnKeyDown
)
4602 EVT_KEY_UP( wxGrid::OnKeyUp
)
4603 EVT_CHAR ( wxGrid::OnChar
)
4604 EVT_ERASE_BACKGROUND( wxGrid::OnEraseBackground
)
4607 bool wxGrid::Create(wxWindow
*parent
, wxWindowID id
,
4608 const wxPoint
& pos
, const wxSize
& size
,
4609 long style
, const wxString
& name
)
4611 if (!wxScrolledWindow::Create(parent
, id
, pos
, size
,
4612 style
| wxWANTS_CHARS
, name
))
4615 m_colMinWidths
= wxLongToLongHashMap(GRID_HASH_SIZE
);
4616 m_rowMinHeights
= wxLongToLongHashMap(GRID_HASH_SIZE
);
4619 SetInitialSize(size
);
4620 SetScrollRate(m_scrollLineX
, m_scrollLineY
);
4629 m_winCapture
->ReleaseMouse();
4631 // Ensure that the editor control is destroyed before the grid is,
4632 // otherwise we crash later when the editor tries to do something with the
4633 // half destroyed grid
4634 HideCellEditControl();
4636 // Must do this or ~wxScrollHelper will pop the wrong event handler
4637 SetTargetWindow(this);
4639 wxSafeDecRef(m_defaultCellAttr
);
4641 #ifdef DEBUG_ATTR_CACHE
4642 size_t total
= gs_nAttrCacheHits
+ gs_nAttrCacheMisses
;
4643 wxPrintf(_T("wxGrid attribute cache statistics: "
4644 "total: %u, hits: %u (%u%%)\n"),
4645 total
, gs_nAttrCacheHits
,
4646 total
? (gs_nAttrCacheHits
*100) / total
: 0);
4649 // if we own the table, just delete it, otherwise at least don't leave it
4650 // with dangling view pointer
4653 else if ( m_table
&& m_table
->GetView() == this )
4654 m_table
->SetView(NULL
);
4656 delete m_typeRegistry
;
4661 // ----- internal init and update functions
4664 // NOTE: If using the default visual attributes works everywhere then this can
4665 // be removed as well as the #else cases below.
4666 #define _USE_VISATTR 0
4668 void wxGrid::Create()
4670 // create the type registry
4671 m_typeRegistry
= new wxGridTypeRegistry
;
4673 m_cellEditCtrlEnabled
= false;
4675 m_defaultCellAttr
= new wxGridCellAttr();
4677 // Set default cell attributes
4678 m_defaultCellAttr
->SetDefAttr(m_defaultCellAttr
);
4679 m_defaultCellAttr
->SetKind(wxGridCellAttr::Default
);
4680 m_defaultCellAttr
->SetFont(GetFont());
4681 m_defaultCellAttr
->SetAlignment(wxALIGN_LEFT
, wxALIGN_TOP
);
4682 m_defaultCellAttr
->SetRenderer(new wxGridCellStringRenderer
);
4683 m_defaultCellAttr
->SetEditor(new wxGridCellTextEditor
);
4686 wxVisualAttributes gva
= wxListBox::GetClassDefaultAttributes();
4687 wxVisualAttributes lva
= wxPanel::GetClassDefaultAttributes();
4689 m_defaultCellAttr
->SetTextColour(gva
.colFg
);
4690 m_defaultCellAttr
->SetBackgroundColour(gva
.colBg
);
4693 m_defaultCellAttr
->SetTextColour(
4694 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
4695 m_defaultCellAttr
->SetBackgroundColour(
4696 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
4701 m_currentCellCoords
= wxGridNoCellCoords
;
4703 // subwindow components that make up the wxGrid
4704 m_rowLabelWin
= new wxGridRowLabelWindow(this);
4705 CreateColumnWindow();
4706 m_cornerLabelWin
= new wxGridCornerLabelWindow(this);
4707 m_gridWin
= new wxGridWindow( this );
4709 SetTargetWindow( m_gridWin
);
4712 wxColour gfg
= gva
.colFg
;
4713 wxColour gbg
= gva
.colBg
;
4714 wxColour lfg
= lva
.colFg
;
4715 wxColour lbg
= lva
.colBg
;
4717 wxColour gfg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT
);
4718 wxColour gbg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW
);
4719 wxColour lfg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT
);
4720 wxColour lbg
= wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE
);
4723 m_cornerLabelWin
->SetOwnForegroundColour(lfg
);
4724 m_cornerLabelWin
->SetOwnBackgroundColour(lbg
);
4725 m_rowLabelWin
->SetOwnForegroundColour(lfg
);
4726 m_rowLabelWin
->SetOwnBackgroundColour(lbg
);
4727 m_colWindow
->SetOwnForegroundColour(lfg
);
4728 m_colWindow
->SetOwnBackgroundColour(lbg
);
4730 m_gridWin
->SetOwnForegroundColour(gfg
);
4731 m_gridWin
->SetOwnBackgroundColour(gbg
);
4733 m_labelBackgroundColour
= m_rowLabelWin
->GetBackgroundColour();
4734 m_labelTextColour
= m_rowLabelWin
->GetForegroundColour();
4736 // now that we have the grid window, use its font to compute the default
4738 m_defaultRowHeight
= m_gridWin
->GetCharHeight();
4739 #if defined(__WXMOTIF__) || defined(__WXGTK__) // see also text ctrl sizing in ShowCellEditControl()
4740 m_defaultRowHeight
+= 8;
4742 m_defaultRowHeight
+= 4;
4747 void wxGrid::CreateColumnWindow()
4749 if ( m_useNativeHeader
)
4751 m_colWindow
= new wxGridHeaderCtrl(this);
4752 m_colLabelHeight
= m_colWindow
->GetBestSize().y
;
4754 else // draw labels ourselves
4756 m_colWindow
= new wxGridColLabelWindow(this);
4757 m_colLabelHeight
= WXGRID_DEFAULT_COL_LABEL_HEIGHT
;
4761 bool wxGrid::CreateGrid( int numRows
, int numCols
,
4762 wxGridSelectionModes selmode
)
4764 wxCHECK_MSG( !m_created
,
4766 wxT("wxGrid::CreateGrid or wxGrid::SetTable called more than once") );
4768 return SetTable(new wxGridStringTable(numRows
, numCols
), true, selmode
);
4771 void wxGrid::SetSelectionMode(wxGridSelectionModes selmode
)
4773 wxCHECK_RET( m_created
,
4774 wxT("Called wxGrid::SetSelectionMode() before calling CreateGrid()") );
4776 m_selection
->SetSelectionMode( selmode
);
4779 wxGrid::wxGridSelectionModes
wxGrid::GetSelectionMode() const
4781 wxCHECK_MSG( m_created
, wxGridSelectCells
,
4782 wxT("Called wxGrid::GetSelectionMode() before calling CreateGrid()") );
4784 return m_selection
->GetSelectionMode();
4788 wxGrid::SetTable(wxGridTableBase
*table
,
4790 wxGrid::wxGridSelectionModes selmode
)
4792 bool checkSelection
= false;
4795 // stop all processing
4800 m_table
->SetView(0);
4812 checkSelection
= true;
4814 // kill row and column size arrays
4815 m_colWidths
.Empty();
4816 m_colRights
.Empty();
4817 m_rowHeights
.Empty();
4818 m_rowBottoms
.Empty();
4823 m_numRows
= table
->GetNumberRows();
4824 m_numCols
= table
->GetNumberCols();
4826 if ( m_useNativeHeader
)
4827 GetGridColHeader()->SetColumnCount(m_numCols
);
4830 m_table
->SetView( this );
4831 m_ownTable
= takeOwnership
;
4832 m_selection
= new wxGridSelection( this, selmode
);
4835 // If the newly set table is smaller than the
4836 // original one current cell and selection regions
4837 // might be invalid,
4838 m_selectedBlockCorner
= wxGridNoCellCoords
;
4839 m_currentCellCoords
=
4840 wxGridCellCoords(wxMin(m_numRows
, m_currentCellCoords
.GetRow()),
4841 wxMin(m_numCols
, m_currentCellCoords
.GetCol()));
4842 if (m_selectedBlockTopLeft
.GetRow() >= m_numRows
||
4843 m_selectedBlockTopLeft
.GetCol() >= m_numCols
)
4845 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
4846 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
4849 m_selectedBlockBottomRight
=
4850 wxGridCellCoords(wxMin(m_numRows
,
4851 m_selectedBlockBottomRight
.GetRow()),
4853 m_selectedBlockBottomRight
.GetCol()));
4867 m_cornerLabelWin
= NULL
;
4868 m_rowLabelWin
= NULL
;
4876 m_defaultCellAttr
= NULL
;
4877 m_typeRegistry
= NULL
;
4878 m_winCapture
= NULL
;
4880 m_rowLabelWidth
= WXGRID_DEFAULT_ROW_LABEL_WIDTH
;
4881 m_colLabelHeight
= WXGRID_DEFAULT_COL_LABEL_HEIGHT
;
4884 m_attrCache
.row
= -1;
4885 m_attrCache
.col
= -1;
4886 m_attrCache
.attr
= NULL
;
4888 m_labelFont
= GetFont();
4889 m_labelFont
.SetWeight( wxBOLD
);
4891 m_rowLabelHorizAlign
= wxALIGN_CENTRE
;
4892 m_rowLabelVertAlign
= wxALIGN_CENTRE
;
4894 m_colLabelHorizAlign
= wxALIGN_CENTRE
;
4895 m_colLabelVertAlign
= wxALIGN_CENTRE
;
4896 m_colLabelTextOrientation
= wxHORIZONTAL
;
4898 m_defaultColWidth
= WXGRID_DEFAULT_COL_WIDTH
;
4899 m_defaultRowHeight
= 0; // this will be initialized after creation
4901 m_minAcceptableColWidth
= WXGRID_MIN_COL_WIDTH
;
4902 m_minAcceptableRowHeight
= WXGRID_MIN_ROW_HEIGHT
;
4904 m_gridLineColour
= wxColour( 192,192,192 );
4905 m_gridLinesEnabled
= true;
4906 m_gridLinesClipHorz
=
4907 m_gridLinesClipVert
= true;
4908 m_cellHighlightColour
= *wxBLACK
;
4909 m_cellHighlightPenWidth
= 2;
4910 m_cellHighlightROPenWidth
= 1;
4912 m_canDragColMove
= false;
4914 m_cursorMode
= WXGRID_CURSOR_SELECT_CELL
;
4915 m_winCapture
= NULL
;
4916 m_canDragRowSize
= true;
4917 m_canDragColSize
= true;
4918 m_canDragGridSize
= true;
4919 m_canDragCell
= false;
4921 m_dragRowOrCol
= -1;
4922 m_isDragging
= false;
4923 m_startDragPos
= wxDefaultPosition
;
4925 m_sortCol
= wxNOT_FOUND
;
4926 m_sortIsAscending
= true;
4929 m_nativeColumnLabels
= false;
4931 m_waitForSlowClick
= false;
4933 m_rowResizeCursor
= wxCursor( wxCURSOR_SIZENS
);
4934 m_colResizeCursor
= wxCursor( wxCURSOR_SIZEWE
);
4936 m_currentCellCoords
= wxGridNoCellCoords
;
4938 m_selectedBlockTopLeft
=
4939 m_selectedBlockBottomRight
=
4940 m_selectedBlockCorner
= wxGridNoCellCoords
;
4942 m_selectionBackground
= wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
);
4943 m_selectionForeground
= wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
);
4945 m_editable
= true; // default for whole grid
4947 m_inOnKeyDown
= false;
4953 m_scrollLineX
= GRID_SCROLL_LINE_X
;
4954 m_scrollLineY
= GRID_SCROLL_LINE_Y
;
4957 // ----------------------------------------------------------------------------
4958 // the idea is to call these functions only when necessary because they create
4959 // quite big arrays which eat memory mostly unnecessary - in particular, if
4960 // default widths/heights are used for all rows/columns, we may not use these
4963 // with some extra code, it should be possible to only store the widths/heights
4964 // different from default ones (resulting in space savings for huge grids) but
4965 // this is not done currently
4966 // ----------------------------------------------------------------------------
4968 void wxGrid::InitRowHeights()
4970 m_rowHeights
.Empty();
4971 m_rowBottoms
.Empty();
4973 m_rowHeights
.Alloc( m_numRows
);
4974 m_rowBottoms
.Alloc( m_numRows
);
4976 m_rowHeights
.Add( m_defaultRowHeight
, m_numRows
);
4979 for ( int i
= 0; i
< m_numRows
; i
++ )
4981 rowBottom
+= m_defaultRowHeight
;
4982 m_rowBottoms
.Add( rowBottom
);
4986 void wxGrid::InitColWidths()
4988 m_colWidths
.Empty();
4989 m_colRights
.Empty();
4991 m_colWidths
.Alloc( m_numCols
);
4992 m_colRights
.Alloc( m_numCols
);
4994 m_colWidths
.Add( m_defaultColWidth
, m_numCols
);
4996 for ( int i
= 0; i
< m_numCols
; i
++ )
4998 int colRight
= ( GetColPos( i
) + 1 ) * m_defaultColWidth
;
4999 m_colRights
.Add( colRight
);
5003 int wxGrid::GetColWidth(int col
) const
5005 return m_colWidths
.IsEmpty() ? m_defaultColWidth
: m_colWidths
[col
];
5008 int wxGrid::GetColLeft(int col
) const
5010 return m_colRights
.IsEmpty() ? GetColPos( col
) * m_defaultColWidth
5011 : m_colRights
[col
] - m_colWidths
[col
];
5014 int wxGrid::GetColRight(int col
) const
5016 return m_colRights
.IsEmpty() ? (GetColPos( col
) + 1) * m_defaultColWidth
5020 int wxGrid::GetRowHeight(int row
) const
5022 return m_rowHeights
.IsEmpty() ? m_defaultRowHeight
: m_rowHeights
[row
];
5025 int wxGrid::GetRowTop(int row
) const
5027 return m_rowBottoms
.IsEmpty() ? row
* m_defaultRowHeight
5028 : m_rowBottoms
[row
] - m_rowHeights
[row
];
5031 int wxGrid::GetRowBottom(int row
) const
5033 return m_rowBottoms
.IsEmpty() ? (row
+ 1) * m_defaultRowHeight
5034 : m_rowBottoms
[row
];
5037 void wxGrid::CalcDimensions()
5039 // compute the size of the scrollable area
5040 int w
= m_numCols
> 0 ? GetColRight(GetColAt(m_numCols
- 1)) : 0;
5041 int h
= m_numRows
> 0 ? GetRowBottom(m_numRows
- 1) : 0;
5046 // take into account editor if shown
5047 if ( IsCellEditControlShown() )
5050 int r
= m_currentCellCoords
.GetRow();
5051 int c
= m_currentCellCoords
.GetCol();
5052 int x
= GetColLeft(c
);
5053 int y
= GetRowTop(r
);
5055 // how big is the editor
5056 wxGridCellAttr
* attr
= GetCellAttr(r
, c
);
5057 wxGridCellEditor
* editor
= attr
->GetEditor(this, r
, c
);
5058 editor
->GetControl()->GetSize(&w2
, &h2
);
5069 // preserve (more or less) the previous position
5071 GetViewStart( &x
, &y
);
5073 // ensure the position is valid for the new scroll ranges
5075 x
= wxMax( w
- 1, 0 );
5077 y
= wxMax( h
- 1, 0 );
5079 // update the virtual size and refresh the scrollbars to reflect it
5080 m_gridWin
->SetVirtualSize(w
, h
);
5084 // if our OnSize() hadn't been called (it would if we have scrollbars), we
5085 // still must reposition the children
5089 wxSize
wxGrid::GetSizeAvailableForScrollTarget(const wxSize
& size
)
5091 wxSize
sizeGridWin(size
);
5092 sizeGridWin
.x
-= m_rowLabelWidth
;
5093 sizeGridWin
.y
-= m_colLabelHeight
;
5098 void wxGrid::CalcWindowSizes()
5100 // escape if the window is has not been fully created yet
5102 if ( m_cornerLabelWin
== NULL
)
5106 GetClientSize( &cw
, &ch
);
5108 // the grid may be too small to have enough space for the labels yet, don't
5109 // size the windows to negative sizes in this case
5110 int gw
= cw
- m_rowLabelWidth
;
5111 int gh
= ch
- m_colLabelHeight
;
5117 if ( m_cornerLabelWin
&& m_cornerLabelWin
->IsShown() )
5118 m_cornerLabelWin
->SetSize( 0, 0, m_rowLabelWidth
, m_colLabelHeight
);
5120 if ( m_colWindow
&& m_colWindow
->IsShown() )
5121 m_colWindow
->SetSize( m_rowLabelWidth
, 0, gw
, m_colLabelHeight
);
5123 if ( m_rowLabelWin
&& m_rowLabelWin
->IsShown() )
5124 m_rowLabelWin
->SetSize( 0, m_colLabelHeight
, m_rowLabelWidth
, gh
);
5126 if ( m_gridWin
&& m_gridWin
->IsShown() )
5127 m_gridWin
->SetSize( m_rowLabelWidth
, m_colLabelHeight
, gw
, gh
);
5130 // this is called when the grid table sends a message
5131 // to indicate that it has been redimensioned
5133 bool wxGrid::Redimension( wxGridTableMessage
& msg
)
5136 bool result
= false;
5138 // Clear the attribute cache as the attribute might refer to a different
5139 // cell than stored in the cache after adding/removing rows/columns.
5142 // By the same reasoning, the editor should be dismissed if columns are
5143 // added or removed. And for consistency, it should IMHO always be
5144 // removed, not only if the cell "underneath" it actually changes.
5145 // For now, I intentionally do not save the editor's content as the
5146 // cell it might want to save that stuff to might no longer exist.
5147 HideCellEditControl();
5149 switch ( msg
.GetId() )
5151 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED
:
5153 size_t pos
= msg
.GetCommandInt();
5154 int numRows
= msg
.GetCommandInt2();
5156 m_numRows
+= numRows
;
5158 if ( !m_rowHeights
.IsEmpty() )
5160 m_rowHeights
.Insert( m_defaultRowHeight
, pos
, numRows
);
5161 m_rowBottoms
.Insert( 0, pos
, numRows
);
5165 bottom
= m_rowBottoms
[pos
- 1];
5167 for ( i
= pos
; i
< m_numRows
; i
++ )
5169 bottom
+= m_rowHeights
[i
];
5170 m_rowBottoms
[i
] = bottom
;
5174 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5176 // if we have just inserted cols into an empty grid the current
5177 // cell will be undefined...
5179 SetCurrentCell( 0, 0 );
5183 m_selection
->UpdateRows( pos
, numRows
);
5184 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5186 attrProvider
->UpdateAttrRows( pos
, numRows
);
5188 if ( !GetBatchCount() )
5191 m_rowLabelWin
->Refresh();
5197 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED
:
5199 int numRows
= msg
.GetCommandInt();
5200 int oldNumRows
= m_numRows
;
5201 m_numRows
+= numRows
;
5203 if ( !m_rowHeights
.IsEmpty() )
5205 m_rowHeights
.Add( m_defaultRowHeight
, numRows
);
5206 m_rowBottoms
.Add( 0, numRows
);
5209 if ( oldNumRows
> 0 )
5210 bottom
= m_rowBottoms
[oldNumRows
- 1];
5212 for ( i
= oldNumRows
; i
< m_numRows
; i
++ )
5214 bottom
+= m_rowHeights
[i
];
5215 m_rowBottoms
[i
] = bottom
;
5219 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5221 // if we have just inserted cols into an empty grid the current
5222 // cell will be undefined...
5224 SetCurrentCell( 0, 0 );
5227 if ( !GetBatchCount() )
5230 m_rowLabelWin
->Refresh();
5236 case wxGRIDTABLE_NOTIFY_ROWS_DELETED
:
5238 size_t pos
= msg
.GetCommandInt();
5239 int numRows
= msg
.GetCommandInt2();
5240 m_numRows
-= numRows
;
5242 if ( !m_rowHeights
.IsEmpty() )
5244 m_rowHeights
.RemoveAt( pos
, numRows
);
5245 m_rowBottoms
.RemoveAt( pos
, numRows
);
5248 for ( i
= 0; i
< m_numRows
; i
++ )
5250 h
+= m_rowHeights
[i
];
5251 m_rowBottoms
[i
] = h
;
5257 m_currentCellCoords
= wxGridNoCellCoords
;
5261 if ( m_currentCellCoords
.GetRow() >= m_numRows
)
5262 m_currentCellCoords
.Set( 0, 0 );
5266 m_selection
->UpdateRows( pos
, -((int)numRows
) );
5267 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5270 attrProvider
->UpdateAttrRows( pos
, -((int)numRows
) );
5272 // ifdef'd out following patch from Paul Gammans
5274 // No need to touch column attributes, unless we
5275 // removed _all_ rows, in this case, we remove
5276 // all column attributes.
5277 // I hate to do this here, but the
5278 // needed data is not available inside UpdateAttrRows.
5279 if ( !GetNumberRows() )
5280 attrProvider
->UpdateAttrCols( 0, -GetNumberCols() );
5284 if ( !GetBatchCount() )
5287 m_rowLabelWin
->Refresh();
5293 case wxGRIDTABLE_NOTIFY_COLS_INSERTED
:
5295 size_t pos
= msg
.GetCommandInt();
5296 int numCols
= msg
.GetCommandInt2();
5297 m_numCols
+= numCols
;
5299 if ( m_useNativeHeader
)
5300 GetGridColHeader()->SetColumnCount(m_numCols
);
5302 if ( !m_colAt
.IsEmpty() )
5304 //Shift the column IDs
5306 for ( i
= 0; i
< m_numCols
- numCols
; i
++ )
5308 if ( m_colAt
[i
] >= (int)pos
)
5309 m_colAt
[i
] += numCols
;
5312 m_colAt
.Insert( pos
, pos
, numCols
);
5314 //Set the new columns' positions
5315 for ( i
= pos
+ 1; i
< (int)pos
+ numCols
; i
++ )
5321 if ( !m_colWidths
.IsEmpty() )
5323 m_colWidths
.Insert( m_defaultColWidth
, pos
, numCols
);
5324 m_colRights
.Insert( 0, pos
, numCols
);
5328 right
= m_colRights
[GetColAt( pos
- 1 )];
5331 for ( colPos
= pos
; colPos
< m_numCols
; colPos
++ )
5333 i
= GetColAt( colPos
);
5335 right
+= m_colWidths
[i
];
5336 m_colRights
[i
] = right
;
5340 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5342 // if we have just inserted cols into an empty grid the current
5343 // cell will be undefined...
5345 SetCurrentCell( 0, 0 );
5349 m_selection
->UpdateCols( pos
, numCols
);
5350 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5352 attrProvider
->UpdateAttrCols( pos
, numCols
);
5353 if ( !GetBatchCount() )
5356 m_colWindow
->Refresh();
5362 case wxGRIDTABLE_NOTIFY_COLS_APPENDED
:
5364 int numCols
= msg
.GetCommandInt();
5365 int oldNumCols
= m_numCols
;
5366 m_numCols
+= numCols
;
5367 if ( m_useNativeHeader
)
5368 GetGridColHeader()->SetColumnCount(m_numCols
);
5370 if ( !m_colAt
.IsEmpty() )
5372 m_colAt
.Add( 0, numCols
);
5374 //Set the new columns' positions
5376 for ( i
= oldNumCols
; i
< m_numCols
; i
++ )
5382 if ( !m_colWidths
.IsEmpty() )
5384 m_colWidths
.Add( m_defaultColWidth
, numCols
);
5385 m_colRights
.Add( 0, numCols
);
5388 if ( oldNumCols
> 0 )
5389 right
= m_colRights
[GetColAt( oldNumCols
- 1 )];
5392 for ( colPos
= oldNumCols
; colPos
< m_numCols
; colPos
++ )
5394 i
= GetColAt( colPos
);
5396 right
+= m_colWidths
[i
];
5397 m_colRights
[i
] = right
;
5401 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5403 // if we have just inserted cols into an empty grid the current
5404 // cell will be undefined...
5406 SetCurrentCell( 0, 0 );
5408 if ( !GetBatchCount() )
5411 m_colWindow
->Refresh();
5417 case wxGRIDTABLE_NOTIFY_COLS_DELETED
:
5419 size_t pos
= msg
.GetCommandInt();
5420 int numCols
= msg
.GetCommandInt2();
5421 m_numCols
-= numCols
;
5422 if ( m_useNativeHeader
)
5423 GetGridColHeader()->SetColumnCount(m_numCols
);
5425 if ( !m_colAt
.IsEmpty() )
5427 int colID
= GetColAt( pos
);
5429 m_colAt
.RemoveAt( pos
, numCols
);
5431 //Shift the column IDs
5433 for ( colPos
= 0; colPos
< m_numCols
; colPos
++ )
5435 if ( m_colAt
[colPos
] > colID
)
5436 m_colAt
[colPos
] -= numCols
;
5440 if ( !m_colWidths
.IsEmpty() )
5442 m_colWidths
.RemoveAt( pos
, numCols
);
5443 m_colRights
.RemoveAt( pos
, numCols
);
5447 for ( colPos
= 0; colPos
< m_numCols
; colPos
++ )
5449 i
= GetColAt( colPos
);
5451 w
+= m_colWidths
[i
];
5458 m_currentCellCoords
= wxGridNoCellCoords
;
5462 if ( m_currentCellCoords
.GetCol() >= m_numCols
)
5463 m_currentCellCoords
.Set( 0, 0 );
5467 m_selection
->UpdateCols( pos
, -((int)numCols
) );
5468 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5471 attrProvider
->UpdateAttrCols( pos
, -((int)numCols
) );
5473 // ifdef'd out following patch from Paul Gammans
5475 // No need to touch row attributes, unless we
5476 // removed _all_ columns, in this case, we remove
5477 // all row attributes.
5478 // I hate to do this here, but the
5479 // needed data is not available inside UpdateAttrCols.
5480 if ( !GetNumberCols() )
5481 attrProvider
->UpdateAttrRows( 0, -GetNumberRows() );
5485 if ( !GetBatchCount() )
5488 m_colWindow
->Refresh();
5495 if (result
&& !GetBatchCount() )
5496 m_gridWin
->Refresh();
5501 wxArrayInt
wxGrid::CalcRowLabelsExposed( const wxRegion
& reg
) const
5503 wxRegionIterator
iter( reg
);
5506 wxArrayInt rowlabels
;
5513 // TODO: remove this when we can...
5514 // There is a bug in wxMotif that gives garbage update
5515 // rectangles if you jump-scroll a long way by clicking the
5516 // scrollbar with middle button. This is a work-around
5518 #if defined(__WXMOTIF__)
5520 m_gridWin
->GetClientSize( &cw
, &ch
);
5521 if ( r
.GetTop() > ch
)
5523 r
.SetBottom( wxMin( r
.GetBottom(), ch
) );
5526 // logical bounds of update region
5529 CalcUnscrolledPosition( 0, r
.GetTop(), &dummy
, &top
);
5530 CalcUnscrolledPosition( 0, r
.GetBottom(), &dummy
, &bottom
);
5532 // find the row labels within these bounds
5535 for ( row
= internalYToRow(top
); row
< m_numRows
; row
++ )
5537 if ( GetRowBottom(row
) < top
)
5540 if ( GetRowTop(row
) > bottom
)
5543 rowlabels
.Add( row
);
5552 wxArrayInt
wxGrid::CalcColLabelsExposed( const wxRegion
& reg
) const
5554 wxRegionIterator
iter( reg
);
5557 wxArrayInt colLabels
;
5564 // TODO: remove this when we can...
5565 // There is a bug in wxMotif that gives garbage update
5566 // rectangles if you jump-scroll a long way by clicking the
5567 // scrollbar with middle button. This is a work-around
5569 #if defined(__WXMOTIF__)
5571 m_gridWin
->GetClientSize( &cw
, &ch
);
5572 if ( r
.GetLeft() > cw
)
5574 r
.SetRight( wxMin( r
.GetRight(), cw
) );
5577 // logical bounds of update region
5580 CalcUnscrolledPosition( r
.GetLeft(), 0, &left
, &dummy
);
5581 CalcUnscrolledPosition( r
.GetRight(), 0, &right
, &dummy
);
5583 // find the cells within these bounds
5587 for ( colPos
= GetColPos( internalXToCol(left
) ); colPos
< m_numCols
; colPos
++ )
5589 col
= GetColAt( colPos
);
5591 if ( GetColRight(col
) < left
)
5594 if ( GetColLeft(col
) > right
)
5597 colLabels
.Add( col
);
5606 wxGridCellCoordsArray
wxGrid::CalcCellsExposed( const wxRegion
& reg
) const
5608 wxRegionIterator
iter( reg
);
5611 wxGridCellCoordsArray cellsExposed
;
5613 int left
, top
, right
, bottom
;
5618 // TODO: remove this when we can...
5619 // There is a bug in wxMotif that gives garbage update
5620 // rectangles if you jump-scroll a long way by clicking the
5621 // scrollbar with middle button. This is a work-around
5623 #if defined(__WXMOTIF__)
5625 m_gridWin
->GetClientSize( &cw
, &ch
);
5626 if ( r
.GetTop() > ch
) r
.SetTop( 0 );
5627 if ( r
.GetLeft() > cw
) r
.SetLeft( 0 );
5628 r
.SetRight( wxMin( r
.GetRight(), cw
) );
5629 r
.SetBottom( wxMin( r
.GetBottom(), ch
) );
5632 // logical bounds of update region
5634 CalcUnscrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
5635 CalcUnscrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
5637 // find the cells within these bounds
5639 for ( int row
= internalYToRow(top
); row
< m_numRows
; row
++ )
5641 if ( GetRowBottom(row
) <= top
)
5644 if ( GetRowTop(row
) > bottom
)
5647 // add all dirty cells in this row: notice that the columns which
5648 // are dirty don't depend on the row so we compute them only once
5649 // for the first dirty row and then reuse for all the next ones
5652 // do determine the dirty columns
5653 for ( int pos
= XToPos(left
); pos
<= XToPos(right
); pos
++ )
5654 cols
.push_back(GetColAt(pos
));
5656 // if there are no dirty columns at all, nothing to do
5661 const size_t count
= cols
.size();
5662 for ( size_t n
= 0; n
< count
; n
++ )
5663 cellsExposed
.Add(wxGridCellCoords(row
, cols
[n
]));
5669 return cellsExposed
;
5673 void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent
& event
)
5676 wxPoint
pos( event
.GetPosition() );
5677 CalcUnscrolledPosition( pos
.x
, pos
.y
, &x
, &y
);
5679 if ( event
.Dragging() )
5683 m_isDragging
= true;
5684 m_rowLabelWin
->CaptureMouse();
5687 if ( event
.LeftIsDown() )
5689 switch ( m_cursorMode
)
5691 case WXGRID_CURSOR_RESIZE_ROW
:
5693 int cw
, ch
, left
, dummy
;
5694 m_gridWin
->GetClientSize( &cw
, &ch
);
5695 CalcUnscrolledPosition( 0, 0, &left
, &dummy
);
5697 wxClientDC
dc( m_gridWin
);
5700 GetRowTop(m_dragRowOrCol
) +
5701 GetRowMinimalHeight(m_dragRowOrCol
) );
5702 dc
.SetLogicalFunction(wxINVERT
);
5703 if ( m_dragLastPos
>= 0 )
5705 dc
.DrawLine( left
, m_dragLastPos
, left
+cw
, m_dragLastPos
);
5707 dc
.DrawLine( left
, y
, left
+cw
, y
);
5712 case WXGRID_CURSOR_SELECT_ROW
:
5714 if ( (row
= YToRow( y
)) >= 0 )
5717 m_selection
->SelectRow(row
, event
);
5722 // default label to suppress warnings about "enumeration value
5723 // 'xxx' not handled in switch
5731 if ( m_isDragging
&& (event
.Entering() || event
.Leaving()) )
5736 if (m_rowLabelWin
->HasCapture())
5737 m_rowLabelWin
->ReleaseMouse();
5738 m_isDragging
= false;
5741 // ------------ Entering or leaving the window
5743 if ( event
.Entering() || event
.Leaving() )
5745 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
);
5748 // ------------ Left button pressed
5750 else if ( event
.LeftDown() )
5752 // don't send a label click event for a hit on the
5753 // edge of the row label - this is probably the user
5754 // wanting to resize the row
5756 if ( YToEdgeOfRow(y
) < 0 )
5760 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, row
, -1, event
) )
5762 if ( !event
.ShiftDown() && !event
.CmdDown() )
5766 if ( event
.ShiftDown() )
5768 m_selection
->SelectBlock
5770 m_currentCellCoords
.GetRow(), 0,
5771 row
, GetNumberCols() - 1,
5777 m_selection
->SelectRow(row
, event
);
5781 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW
, m_rowLabelWin
);
5786 // starting to drag-resize a row
5787 if ( CanDragRowSize() )
5788 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, m_rowLabelWin
);
5792 // ------------ Left double click
5794 else if (event
.LeftDClick() )
5796 row
= YToEdgeOfRow(y
);
5801 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, row
, -1, event
) )
5803 // no default action at the moment
5808 // adjust row height depending on label text
5809 AutoSizeRowLabelSize( row
);
5811 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
5816 // ------------ Left button released
5818 else if ( event
.LeftUp() )
5820 if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
)
5822 DoEndDragResizeRow();
5824 // Note: we are ending the event *after* doing
5825 // default processing in this case
5827 SendEvent( wxEVT_GRID_ROW_SIZE
, m_dragRowOrCol
, -1, event
);
5830 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
);
5834 // ------------ Right button down
5836 else if ( event
.RightDown() )
5840 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, row
, -1, event
) )
5842 // no default action at the moment
5846 // ------------ Right double click
5848 else if ( event
.RightDClick() )
5852 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, row
, -1, event
) )
5854 // no default action at the moment
5858 // ------------ No buttons down and mouse moving
5860 else if ( event
.Moving() )
5862 m_dragRowOrCol
= YToEdgeOfRow( y
);
5863 if ( m_dragRowOrCol
>= 0 )
5865 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
5867 // don't capture the mouse yet
5868 if ( CanDragRowSize() )
5869 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, m_rowLabelWin
, false);
5872 else if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
5874 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
, false);
5879 void wxGrid::UpdateColumnSortingIndicator(int col
)
5881 wxCHECK_RET( col
!= wxNOT_FOUND
, "invalid column index" );
5883 if ( m_useNativeHeader
)
5884 GetGridColHeader()->UpdateColumn(col
);
5885 else if ( m_nativeColumnLabels
)
5886 m_colWindow
->Refresh();
5887 //else: sorting indicator display not yet implemented in grid version
5890 void wxGrid::SetSortingColumn(int col
, bool ascending
)
5892 if ( col
== m_sortCol
)
5894 // we are already using this column for sorting (or not sorting at all)
5895 // but we might still change the sorting order, check for it
5896 if ( m_sortCol
!= wxNOT_FOUND
&& ascending
!= m_sortIsAscending
)
5898 m_sortIsAscending
= ascending
;
5900 UpdateColumnSortingIndicator(m_sortCol
);
5903 else // we're changing the column used for sorting
5905 const int sortColOld
= m_sortCol
;
5907 // change it before updating the column as we want GetSortingColumn()
5908 // to return the correct new value
5911 if ( sortColOld
!= wxNOT_FOUND
)
5912 UpdateColumnSortingIndicator(sortColOld
);
5914 if ( m_sortCol
!= wxNOT_FOUND
)
5916 m_sortIsAscending
= ascending
;
5917 UpdateColumnSortingIndicator(m_sortCol
);
5922 void wxGrid::DoColHeaderClick(int col
)
5924 // we consider that the grid was resorted if this event is processed and
5926 if ( SendEvent(wxEVT_GRID_COL_SORT
, -1, col
) == 1 )
5928 SetSortingColumn(col
, IsSortingBy(col
) ? !m_sortIsAscending
: true);
5933 void wxGrid::DoStartResizeCol(int col
)
5935 m_dragRowOrCol
= col
;
5937 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol
));
5940 void wxGrid::DoUpdateResizeCol(int x
)
5942 int cw
, ch
, dummy
, top
;
5943 m_gridWin
->GetClientSize( &cw
, &ch
);
5944 CalcUnscrolledPosition( 0, 0, &dummy
, &top
);
5946 wxClientDC
dc( m_gridWin
);
5949 x
= wxMax( x
, GetColLeft(m_dragRowOrCol
) + GetColMinimalWidth(m_dragRowOrCol
));
5950 dc
.SetLogicalFunction(wxINVERT
);
5951 if ( m_dragLastPos
>= 0 )
5953 dc
.DrawLine( m_dragLastPos
, top
, m_dragLastPos
, top
+ ch
);
5955 dc
.DrawLine( x
, top
, x
, top
+ ch
);
5959 void wxGrid::DoUpdateResizeColWidth(int w
)
5961 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol
) + w
);
5964 void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent
& event
)
5967 wxPoint
pos( event
.GetPosition() );
5968 CalcUnscrolledPosition( pos
.x
, pos
.y
, &x
, &y
);
5970 int col
= XToCol(x
);
5971 if ( event
.Dragging() )
5975 m_isDragging
= true;
5976 GetColLabelWindow()->CaptureMouse();
5978 if ( m_cursorMode
== WXGRID_CURSOR_MOVE_COL
&& col
!= -1 )
5979 DoStartMoveCol(col
);
5982 if ( event
.LeftIsDown() )
5984 switch ( m_cursorMode
)
5986 case WXGRID_CURSOR_RESIZE_COL
:
5987 DoUpdateResizeCol(x
);
5990 case WXGRID_CURSOR_SELECT_COL
:
5995 m_selection
->SelectCol(col
, event
);
6000 case WXGRID_CURSOR_MOVE_COL
:
6002 int posNew
= XToPos(x
);
6003 int colNew
= GetColAt(posNew
);
6005 // determine the position of the drop marker
6007 if ( x
>= GetColLeft(colNew
) + (GetColWidth(colNew
) / 2) )
6008 markerX
= GetColRight(colNew
);
6010 markerX
= GetColLeft(colNew
);
6012 if ( markerX
!= m_dragLastPos
)
6014 wxClientDC
dc( GetColLabelWindow() );
6018 GetColLabelWindow()->GetClientSize( &cw
, &ch
);
6022 //Clean up the last indicator
6023 if ( m_dragLastPos
>= 0 )
6025 wxPen
pen( GetColLabelWindow()->GetBackgroundColour(), 2 );
6027 dc
.DrawLine( m_dragLastPos
+ 1, 0, m_dragLastPos
+ 1, ch
);
6028 dc
.SetPen(wxNullPen
);
6030 if ( XToCol( m_dragLastPos
) != -1 )
6031 DrawColLabel( dc
, XToCol( m_dragLastPos
) );
6034 const wxColour
*color
;
6035 //Moving to the same place? Don't draw a marker
6036 if ( colNew
== m_dragRowOrCol
)
6037 color
= wxLIGHT_GREY
;
6042 wxPen
pen( *color
, 2 );
6045 dc
.DrawLine( markerX
, 0, markerX
, ch
);
6047 dc
.SetPen(wxNullPen
);
6049 m_dragLastPos
= markerX
- 1;
6054 // default label to suppress warnings about "enumeration value
6055 // 'xxx' not handled in switch
6063 if ( m_isDragging
&& (event
.Entering() || event
.Leaving()) )
6068 if (GetColLabelWindow()->HasCapture())
6069 GetColLabelWindow()->ReleaseMouse();
6070 m_isDragging
= false;
6073 // ------------ Entering or leaving the window
6075 if ( event
.Entering() || event
.Leaving() )
6077 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6080 // ------------ Left button pressed
6082 else if ( event
.LeftDown() )
6084 // don't send a label click event for a hit on the
6085 // edge of the col label - this is probably the user
6086 // wanting to resize the col
6088 if ( XToEdgeOfCol(x
) < 0 )
6091 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, -1, col
, event
) )
6093 if ( m_canDragColMove
)
6095 //Show button as pressed
6096 wxClientDC
dc( GetColLabelWindow() );
6097 int colLeft
= GetColLeft( col
);
6098 int colRight
= GetColRight( col
) - 1;
6099 dc
.SetPen( wxPen( GetColLabelWindow()->GetBackgroundColour(), 1 ) );
6100 dc
.DrawLine( colLeft
, 1, colLeft
, m_colLabelHeight
-1 );
6101 dc
.DrawLine( colLeft
, 1, colRight
, 1 );
6103 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL
, GetColLabelWindow());
6107 if ( !event
.ShiftDown() && !event
.CmdDown() )
6111 if ( event
.ShiftDown() )
6113 m_selection
->SelectBlock
6115 0, m_currentCellCoords
.GetCol(),
6116 GetNumberRows() - 1, col
,
6122 m_selection
->SelectCol(col
, event
);
6126 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL
, GetColLabelWindow());
6132 // starting to drag-resize a col
6134 if ( CanDragColSize() )
6135 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, GetColLabelWindow());
6139 // ------------ Left double click
6141 if ( event
.LeftDClick() )
6143 const int colEdge
= XToEdgeOfCol(x
);
6144 if ( colEdge
== -1 )
6147 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, -1, col
, event
) )
6149 // no default action at the moment
6154 // adjust column width depending on label text
6155 AutoSizeColLabelSize( colEdge
);
6157 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6162 // ------------ Left button released
6164 else if ( event
.LeftUp() )
6166 switch ( m_cursorMode
)
6168 case WXGRID_CURSOR_RESIZE_COL
:
6169 DoEndDragResizeCol();
6172 case WXGRID_CURSOR_MOVE_COL
:
6173 if ( m_dragLastPos
== -1 || col
== m_dragRowOrCol
)
6175 // the column didn't actually move anywhere
6177 DoColHeaderClick(col
);
6178 m_colWindow
->Refresh(); // "unpress" the column
6182 DoEndMoveCol(XToPos(x
));
6186 case WXGRID_CURSOR_SELECT_COL
:
6187 case WXGRID_CURSOR_SELECT_CELL
:
6188 case WXGRID_CURSOR_RESIZE_ROW
:
6189 case WXGRID_CURSOR_SELECT_ROW
:
6191 DoColHeaderClick(col
);
6195 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6199 // ------------ Right button down
6201 else if ( event
.RightDown() )
6204 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, -1, col
, event
) )
6206 // no default action at the moment
6210 // ------------ Right double click
6212 else if ( event
.RightDClick() )
6215 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, -1, col
, event
) )
6217 // no default action at the moment
6221 // ------------ No buttons down and mouse moving
6223 else if ( event
.Moving() )
6225 m_dragRowOrCol
= XToEdgeOfCol( x
);
6226 if ( m_dragRowOrCol
>= 0 )
6228 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6230 // don't capture the cursor yet
6231 if ( CanDragColSize() )
6232 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, GetColLabelWindow(), false);
6235 else if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
6237 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow(), false);
6242 void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent
& event
)
6244 if ( event
.LeftDown() )
6246 // indicate corner label by having both row and
6249 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, -1, -1, event
) )
6254 else if ( event
.LeftDClick() )
6256 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, -1, -1, event
);
6258 else if ( event
.RightDown() )
6260 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, -1, -1, event
) )
6262 // no default action at the moment
6265 else if ( event
.RightDClick() )
6267 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, -1, -1, event
) )
6269 // no default action at the moment
6274 void wxGrid::CancelMouseCapture()
6276 // cancel operation currently in progress, whatever it is
6279 m_isDragging
= false;
6280 m_startDragPos
= wxDefaultPosition
;
6282 m_cursorMode
= WXGRID_CURSOR_SELECT_CELL
;
6283 m_winCapture
->SetCursor( *wxSTANDARD_CURSOR
);
6284 m_winCapture
= NULL
;
6286 // remove traces of whatever we drew on screen
6291 void wxGrid::ChangeCursorMode(CursorMode mode
,
6296 static const wxChar
*cursorModes
[] =
6306 wxLogTrace(_T("grid"),
6307 _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
6308 win
== m_colWindow
? _T("colLabelWin")
6309 : win
? _T("rowLabelWin")
6311 cursorModes
[m_cursorMode
], cursorModes
[mode
]);
6314 if ( mode
== m_cursorMode
&&
6315 win
== m_winCapture
&&
6316 captureMouse
== (m_winCapture
!= NULL
))
6321 // by default use the grid itself
6327 m_winCapture
->ReleaseMouse();
6328 m_winCapture
= NULL
;
6331 m_cursorMode
= mode
;
6333 switch ( m_cursorMode
)
6335 case WXGRID_CURSOR_RESIZE_ROW
:
6336 win
->SetCursor( m_rowResizeCursor
);
6339 case WXGRID_CURSOR_RESIZE_COL
:
6340 win
->SetCursor( m_colResizeCursor
);
6343 case WXGRID_CURSOR_MOVE_COL
:
6344 win
->SetCursor( wxCursor(wxCURSOR_HAND
) );
6348 win
->SetCursor( *wxSTANDARD_CURSOR
);
6352 // we need to capture mouse when resizing
6353 bool resize
= m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
||
6354 m_cursorMode
== WXGRID_CURSOR_RESIZE_COL
;
6356 if ( captureMouse
&& resize
)
6358 win
->CaptureMouse();
6363 // ----------------------------------------------------------------------------
6364 // grid mouse event processing
6365 // ----------------------------------------------------------------------------
6368 wxGrid::DoGridCellDrag(wxMouseEvent
& event
,
6369 const wxGridCellCoords
& coords
,
6372 if ( coords
== wxGridNoCellCoords
)
6373 return; // we're outside any valid cell
6375 // Hide the edit control, so it won't interfere with drag-shrinking.
6376 if ( IsCellEditControlShown() )
6378 HideCellEditControl();
6379 SaveEditControlValue();
6382 switch ( event
.GetModifiers() )
6385 if ( m_selectedBlockCorner
== wxGridNoCellCoords
)
6386 m_selectedBlockCorner
= coords
;
6387 UpdateBlockBeingSelected(m_selectedBlockCorner
, coords
);
6391 if ( CanDragCell() )
6395 if ( m_selectedBlockCorner
== wxGridNoCellCoords
)
6396 m_selectedBlockCorner
= coords
;
6398 SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG
, coords
, event
);
6403 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
6407 // we don't handle the other key modifiers
6412 void wxGrid::DoGridLineDrag(wxMouseEvent
& event
, const wxGridOperations
& oper
)
6414 wxClientDC
dc(m_gridWin
);
6416 dc
.SetLogicalFunction(wxINVERT
);
6418 const wxRect
rectWin(CalcUnscrolledPosition(wxPoint(0, 0)),
6419 m_gridWin
->GetClientSize());
6421 // erase the previously drawn line, if any
6422 if ( m_dragLastPos
>= 0 )
6423 oper
.DrawParallelLineInRect(dc
, rectWin
, m_dragLastPos
);
6425 // we need the vertical position for rows and horizontal for columns here
6426 m_dragLastPos
= oper
.Dual().Select(CalcUnscrolledPosition(event
.GetPosition()));
6428 // don't allow resizing beneath the minimal size
6429 const int posMin
= oper
.GetLineStartPos(this, m_dragRowOrCol
) +
6430 oper
.GetMinimalLineSize(this, m_dragRowOrCol
);
6431 if ( m_dragLastPos
< posMin
)
6432 m_dragLastPos
= posMin
;
6434 // and draw it at the new position
6435 oper
.DrawParallelLineInRect(dc
, rectWin
, m_dragLastPos
);
6438 void wxGrid::DoGridDragEvent(wxMouseEvent
& event
, const wxGridCellCoords
& coords
)
6440 if ( !m_isDragging
)
6442 // Don't start doing anything until the mouse has been dragged far
6444 const wxPoint
& pt
= event
.GetPosition();
6445 if ( m_startDragPos
== wxDefaultPosition
)
6447 m_startDragPos
= pt
;
6451 if ( abs(m_startDragPos
.x
- pt
.x
) <= DRAG_SENSITIVITY
&&
6452 abs(m_startDragPos
.y
- pt
.y
) <= DRAG_SENSITIVITY
)
6456 const bool isFirstDrag
= !m_isDragging
;
6457 m_isDragging
= true;
6459 switch ( m_cursorMode
)
6461 case WXGRID_CURSOR_SELECT_CELL
:
6462 DoGridCellDrag(event
, coords
, isFirstDrag
);
6465 case WXGRID_CURSOR_RESIZE_ROW
:
6466 DoGridLineDrag(event
, wxGridRowOperations());
6469 case WXGRID_CURSOR_RESIZE_COL
:
6470 DoGridLineDrag(event
, wxGridColumnOperations());
6479 m_winCapture
= m_gridWin
;
6480 m_winCapture
->CaptureMouse();
6485 wxGrid::DoGridCellLeftDown(wxMouseEvent
& event
,
6486 const wxGridCellCoords
& coords
,
6489 if ( SendEvent(wxEVT_GRID_CELL_LEFT_CLICK
, coords
, event
) )
6491 // event handled by user code, no need to do anything here
6495 if ( !event
.CmdDown() )
6498 if ( event
.ShiftDown() )
6502 m_selection
->SelectBlock(m_currentCellCoords
, coords
, event
);
6503 m_selectedBlockCorner
= coords
;
6506 else if ( XToEdgeOfCol(pos
.x
) < 0 && YToEdgeOfRow(pos
.y
) < 0 )
6508 DisableCellEditControl();
6509 MakeCellVisible( coords
);
6511 if ( event
.CmdDown() )
6515 m_selection
->ToggleCellSelection(coords
, event
);
6518 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
6519 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
6520 m_selectedBlockCorner
= coords
;
6524 m_waitForSlowClick
= m_currentCellCoords
== coords
&&
6525 coords
!= wxGridNoCellCoords
;
6526 SetCurrentCell( coords
);
6532 wxGrid::DoGridCellLeftDClick(wxMouseEvent
& event
,
6533 const wxGridCellCoords
& coords
,
6536 if ( XToEdgeOfCol(pos
.x
) < 0 && YToEdgeOfRow(pos
.y
) < 0 )
6538 if ( !SendEvent(wxEVT_GRID_CELL_LEFT_DCLICK
, coords
, event
) )
6540 // we want double click to select a cell and start editing
6541 // (i.e. to behave in same way as sequence of two slow clicks):
6542 m_waitForSlowClick
= true;
6548 wxGrid::DoGridCellLeftUp(wxMouseEvent
& event
, const wxGridCellCoords
& coords
)
6550 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6554 m_winCapture
->ReleaseMouse();
6555 m_winCapture
= NULL
;
6558 if ( coords
== m_currentCellCoords
&& m_waitForSlowClick
&& CanEnableCellControl() )
6561 EnableCellEditControl();
6563 wxGridCellAttr
*attr
= GetCellAttr(coords
);
6564 wxGridCellEditor
*editor
= attr
->GetEditor(this, coords
.GetRow(), coords
.GetCol());
6565 editor
->StartingClick();
6569 m_waitForSlowClick
= false;
6571 else if ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
6572 m_selectedBlockBottomRight
!= wxGridNoCellCoords
)
6576 m_selection
->SelectBlock( m_selectedBlockTopLeft
,
6577 m_selectedBlockBottomRight
,
6581 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
6582 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
6584 // Show the edit control, if it has been hidden for
6586 ShowCellEditControl();
6589 else if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
)
6591 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6592 DoEndDragResizeRow();
6594 // Note: we are ending the event *after* doing
6595 // default processing in this case
6597 SendEvent( wxEVT_GRID_ROW_SIZE
, m_dragRowOrCol
, -1, event
);
6599 else if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_COL
)
6601 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6602 DoEndDragResizeCol();
6609 wxGrid::DoGridMouseMoveEvent(wxMouseEvent
& WXUNUSED(event
),
6610 const wxGridCellCoords
& coords
,
6613 if ( coords
.GetRow() < 0 || coords
.GetCol() < 0 )
6615 // out of grid cell area
6616 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6620 int dragRow
= YToEdgeOfRow( pos
.y
);
6621 int dragCol
= XToEdgeOfCol( pos
.x
);
6623 // Dragging on the corner of a cell to resize in both
6624 // directions is not implemented yet...
6626 if ( dragRow
>= 0 && dragCol
>= 0 )
6628 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6634 m_dragRowOrCol
= dragRow
;
6636 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6638 if ( CanDragRowSize() && CanDragGridSize() )
6639 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, NULL
, false);
6642 // When using the native header window we can only resize the columns by
6643 // dragging the dividers in it because we can't make it enter into the
6644 // column resizing mode programmatically
6645 else if ( dragCol
>= 0 && !m_useNativeHeader
)
6647 m_dragRowOrCol
= dragCol
;
6649 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6651 if ( CanDragColSize() && CanDragGridSize() )
6652 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, NULL
, false);
6655 else // Neither on a row or col edge
6657 if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
6659 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6664 void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent
& event
)
6666 const wxPoint pos
= CalcUnscrolledPosition(event
.GetPosition());
6668 // coordinates of the cell under mouse
6669 wxGridCellCoords coords
= XYToCell(pos
);
6671 int cell_rows
, cell_cols
;
6672 GetCellSize( coords
.GetRow(), coords
.GetCol(), &cell_rows
, &cell_cols
);
6673 if ( (cell_rows
< 0) || (cell_cols
< 0) )
6675 coords
.SetRow(coords
.GetRow() + cell_rows
);
6676 coords
.SetCol(coords
.GetCol() + cell_cols
);
6679 if ( event
.Dragging() )
6681 if ( event
.LeftIsDown() )
6682 DoGridDragEvent(event
, coords
);
6688 m_isDragging
= false;
6689 m_startDragPos
= wxDefaultPosition
;
6691 // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL
6692 // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under
6695 if ( event
.Entering() || event
.Leaving() )
6697 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6698 m_gridWin
->SetCursor( *wxSTANDARD_CURSOR
);
6702 // deal with various button presses
6703 if ( event
.IsButton() )
6705 if ( coords
!= wxGridNoCellCoords
)
6707 DisableCellEditControl();
6709 if ( event
.LeftDown() )
6710 DoGridCellLeftDown(event
, coords
, pos
);
6711 else if ( event
.LeftDClick() )
6712 DoGridCellLeftDClick(event
, coords
, pos
);
6713 else if ( event
.RightDown() )
6714 SendEvent(wxEVT_GRID_CELL_RIGHT_CLICK
, coords
, event
);
6715 else if ( event
.RightDClick() )
6716 SendEvent(wxEVT_GRID_CELL_RIGHT_DCLICK
, coords
, event
);
6719 // this one should be called even if we're not over any cell
6720 if ( event
.LeftUp() )
6722 DoGridCellLeftUp(event
, coords
);
6725 else if ( event
.Moving() )
6727 DoGridMouseMoveEvent(event
, coords
, pos
);
6729 else // unknown mouse event?
6735 void wxGrid::DoEndDragResizeLine(const wxGridOperations
& oper
)
6737 if ( m_dragLastPos
== -1 )
6740 const wxGridOperations
& doper
= oper
.Dual();
6742 const wxSize size
= m_gridWin
->GetClientSize();
6744 const wxPoint ptOrigin
= CalcUnscrolledPosition(wxPoint(0, 0));
6746 // erase the last line we drew
6747 wxClientDC
dc(m_gridWin
);
6749 dc
.SetLogicalFunction(wxINVERT
);
6751 const int posLineStart
= oper
.Select(ptOrigin
);
6752 const int posLineEnd
= oper
.Select(ptOrigin
) + oper
.Select(size
);
6754 oper
.DrawParallelLine(dc
, posLineStart
, posLineEnd
, m_dragLastPos
);
6756 // temporarily hide the edit control before resizing
6757 HideCellEditControl();
6758 SaveEditControlValue();
6760 // do resize the line
6761 const int lineStart
= oper
.GetLineStartPos(this, m_dragRowOrCol
);
6762 oper
.SetLineSize(this, m_dragRowOrCol
,
6763 wxMax(m_dragLastPos
- lineStart
,
6764 oper
.GetMinimalLineSize(this, m_dragRowOrCol
)));
6768 // refresh now if we're not frozen
6769 if ( !GetBatchCount() )
6771 // we need to refresh everything beyond the resized line in the header
6774 // get the position from which to refresh in the other direction
6775 wxRect
rect(CellToRect(oper
.MakeCoords(m_dragRowOrCol
, 0)));
6776 rect
.SetPosition(CalcScrolledPosition(rect
.GetPosition()));
6778 // we only need the ordinate (for rows) or abscissa (for columns) here,
6779 // and need to cover the entire window in the other direction
6780 oper
.Select(rect
) = 0;
6782 wxRect
rectHeader(rect
.GetPosition(),
6785 oper
.GetHeaderWindowSize(this),
6786 doper
.Select(size
) - doper
.Select(rect
)
6789 oper
.GetHeaderWindow(this)->Refresh(true, &rectHeader
);
6792 // also refresh the grid window: extend the rectangle
6795 oper
.SelectSize(rect
) = oper
.Select(size
);
6797 int subtractLines
= 0;
6798 const int lineStart
= oper
.PosToLine(this, posLineStart
);
6799 if ( lineStart
>= 0 )
6801 // ensure that if we have a multi-cell block we redraw all of
6802 // it by increasing the refresh area to cover it entirely if a
6803 // part of it is affected
6804 const int lineEnd
= oper
.PosToLine(this, posLineEnd
, true);
6805 for ( int line
= lineStart
; line
< lineEnd
; line
++ )
6807 int cellLines
= oper
.Select(
6808 GetCellSize(oper
.MakeCoords(m_dragRowOrCol
, line
)));
6809 if ( cellLines
< subtractLines
)
6810 subtractLines
= cellLines
;
6815 oper
.GetLineStartPos(this, m_dragRowOrCol
+ subtractLines
);
6816 startPos
= doper
.CalcScrolledPosition(this, startPos
);
6818 doper
.Select(rect
) = startPos
;
6819 doper
.SelectSize(rect
) = doper
.Select(size
) - startPos
;
6821 m_gridWin
->Refresh(false, &rect
);
6825 // show the edit control back again
6826 ShowCellEditControl();
6829 void wxGrid::DoEndDragResizeRow()
6831 DoEndDragResizeLine(wxGridRowOperations());
6834 void wxGrid::DoEndDragResizeCol(wxMouseEvent
*event
)
6836 DoEndDragResizeLine(wxGridColumnOperations());
6838 // Note: we are ending the event *after* doing
6839 // default processing in this case
6842 SendEvent( wxEVT_GRID_COL_SIZE
, -1, m_dragRowOrCol
, *event
);
6844 SendEvent( wxEVT_GRID_COL_SIZE
, -1, m_dragRowOrCol
);
6847 void wxGrid::DoStartMoveCol(int col
)
6849 m_dragRowOrCol
= col
;
6852 void wxGrid::DoEndMoveCol(int pos
)
6854 wxASSERT_MSG( m_dragRowOrCol
!= -1, "no matching DoStartMoveCol?" );
6856 if ( SendEvent(wxEVT_GRID_COL_MOVE
, -1, m_dragRowOrCol
) != -1 )
6857 SetColPos(m_dragRowOrCol
, pos
);
6858 //else: vetoed by user
6860 m_dragRowOrCol
= -1;
6863 void wxGrid::RefreshAfterColPosChange()
6865 // recalculate the column rights as the column positions have changed,
6866 // unless we calculate them dynamically because all columns widths are the
6867 // same and it's easy to do
6868 if ( !m_colWidths
.empty() )
6871 for ( int colPos
= 0; colPos
< m_numCols
; colPos
++ )
6873 int colID
= GetColAt( colPos
);
6875 colRight
+= m_colWidths
[colID
];
6876 m_colRights
[colID
] = colRight
;
6880 // and make the changes visible
6881 if ( m_useNativeHeader
)
6883 if ( m_colAt
.empty() )
6884 GetGridColHeader()->ResetColumnsOrder();
6886 GetGridColHeader()->SetColumnsOrder(m_colAt
);
6890 m_colWindow
->Refresh();
6892 m_gridWin
->Refresh();
6895 void wxGrid::SetColumnsOrder(const wxArrayInt
& order
)
6899 RefreshAfterColPosChange();
6902 void wxGrid::SetColPos(int idx
, int pos
)
6904 // we're going to need m_colAt now, initialize it if needed
6905 if ( m_colAt
.empty() )
6907 m_colAt
.reserve(m_numCols
);
6908 for ( int i
= 0; i
< m_numCols
; i
++ )
6909 m_colAt
.push_back(i
);
6912 wxHeaderCtrl::MoveColumnInOrderArray(m_colAt
, idx
, pos
);
6914 RefreshAfterColPosChange();
6917 void wxGrid::ResetColPos()
6921 RefreshAfterColPosChange();
6924 void wxGrid::EnableDragColMove( bool enable
)
6926 if ( m_canDragColMove
== enable
)
6929 if ( m_useNativeHeader
)
6931 // update all columns to make them [not] reorderable
6932 GetGridColHeader()->SetColumnCount(m_numCols
);
6935 m_canDragColMove
= enable
;
6937 // we use to call ResetColPos() from here if !enable but this doesn't seem
6938 // right as it would mean there would be no way to "freeze" the current
6939 // columns order by disabling moving them after putting them in the desired
6940 // order, whereas now you can always call ResetColPos() manually if needed
6945 // ------ interaction with data model
6947 bool wxGrid::ProcessTableMessage( wxGridTableMessage
& msg
)
6949 switch ( msg
.GetId() )
6951 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES
:
6952 return GetModelValues();
6954 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES
:
6955 return SetModelValues();
6957 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED
:
6958 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED
:
6959 case wxGRIDTABLE_NOTIFY_ROWS_DELETED
:
6960 case wxGRIDTABLE_NOTIFY_COLS_INSERTED
:
6961 case wxGRIDTABLE_NOTIFY_COLS_APPENDED
:
6962 case wxGRIDTABLE_NOTIFY_COLS_DELETED
:
6963 return Redimension( msg
);
6970 // The behaviour of this function depends on the grid table class
6971 // Clear() function. For the default wxGridStringTable class the
6972 // behaviour is to replace all cell contents with wxEmptyString but
6973 // not to change the number of rows or cols.
6975 void wxGrid::ClearGrid()
6979 if (IsCellEditControlEnabled())
6980 DisableCellEditControl();
6983 if (!GetBatchCount())
6984 m_gridWin
->Refresh();
6989 wxGrid::DoModifyLines(bool (wxGridTableBase::*funcModify
)(size_t, size_t),
6990 int pos
, int num
, bool WXUNUSED(updateLabels
) )
6992 wxCHECK_MSG( m_created
, false, "must finish creating the grid first" );
6997 if ( IsCellEditControlEnabled() )
6998 DisableCellEditControl();
7000 return (m_table
->*funcModify
)(pos
, num
);
7002 // the table will have sent the results of the insert row
7003 // operation to this view object as a grid table message
7007 wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend
)(size_t),
7008 int num
, bool WXUNUSED(updateLabels
))
7010 wxCHECK_MSG( m_created
, false, "must finish creating the grid first" );
7015 return (m_table
->*funcAppend
)(num
);
7019 // ----- event handlers
7022 // Generate a grid event based on a mouse event and return:
7023 // -1 if the event was vetoed
7024 // +1 if the event was processed (but not vetoed)
7025 // 0 if the event wasn't handled
7027 wxGrid::SendEvent(const wxEventType type
,
7029 wxMouseEvent
& mouseEv
)
7031 bool claimed
, vetoed
;
7033 if ( type
== wxEVT_GRID_ROW_SIZE
|| type
== wxEVT_GRID_COL_SIZE
)
7035 int rowOrCol
= (row
== -1 ? col
: row
);
7037 wxGridSizeEvent
gridEvt( GetId(),
7041 mouseEv
.GetX() + GetRowLabelSize(),
7042 mouseEv
.GetY() + GetColLabelSize(),
7045 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7046 vetoed
= !gridEvt
.IsAllowed();
7048 else if ( type
== wxEVT_GRID_RANGE_SELECT
)
7050 // Right now, it should _never_ end up here!
7051 wxGridRangeSelectEvent
gridEvt( GetId(),
7054 m_selectedBlockTopLeft
,
7055 m_selectedBlockBottomRight
,
7059 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7060 vetoed
= !gridEvt
.IsAllowed();
7062 else if ( type
== wxEVT_GRID_LABEL_LEFT_CLICK
||
7063 type
== wxEVT_GRID_LABEL_LEFT_DCLICK
||
7064 type
== wxEVT_GRID_LABEL_RIGHT_CLICK
||
7065 type
== wxEVT_GRID_LABEL_RIGHT_DCLICK
)
7067 wxPoint pos
= mouseEv
.GetPosition();
7069 if ( mouseEv
.GetEventObject() == GetGridRowLabelWindow() )
7070 pos
.y
+= GetColLabelSize();
7071 if ( mouseEv
.GetEventObject() == GetGridColLabelWindow() )
7072 pos
.x
+= GetRowLabelSize();
7074 wxGridEvent
gridEvt( GetId(),
7082 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7083 vetoed
= !gridEvt
.IsAllowed();
7087 wxGridEvent
gridEvt( GetId(),
7091 mouseEv
.GetX() + GetRowLabelSize(),
7092 mouseEv
.GetY() + GetColLabelSize(),
7095 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7096 vetoed
= !gridEvt
.IsAllowed();
7099 // A Veto'd event may not be `claimed' so test this first
7103 return claimed
? 1 : 0;
7106 // Generate a grid event of specified type, return value same as above
7108 int wxGrid::SendEvent(const wxEventType type
, int row
, int col
)
7110 bool claimed
, vetoed
;
7112 if ( type
== wxEVT_GRID_ROW_SIZE
|| type
== wxEVT_GRID_COL_SIZE
)
7114 int rowOrCol
= (row
== -1 ? col
: row
);
7116 wxGridSizeEvent
gridEvt( GetId(), type
, this, rowOrCol
);
7118 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7119 vetoed
= !gridEvt
.IsAllowed();
7123 wxGridEvent
gridEvt( GetId(), type
, this, row
, col
);
7125 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7126 vetoed
= !gridEvt
.IsAllowed();
7129 // A Veto'd event may not be `claimed' so test this first
7133 return claimed
? 1 : 0;
7136 void wxGrid::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
7138 // needed to prevent zillions of paint events on MSW
7142 void wxGrid::Refresh(bool eraseb
, const wxRect
* rect
)
7144 // Don't do anything if between Begin/EndBatch...
7145 // EndBatch() will do all this on the last nested one anyway.
7146 if ( m_created
&& !GetBatchCount() )
7148 // Refresh to get correct scrolled position:
7149 wxScrolledWindow::Refresh(eraseb
, rect
);
7153 int rect_x
, rect_y
, rectWidth
, rectHeight
;
7154 int width_label
, width_cell
, height_label
, height_cell
;
7157 // Copy rectangle can get scroll offsets..
7158 rect_x
= rect
->GetX();
7159 rect_y
= rect
->GetY();
7160 rectWidth
= rect
->GetWidth();
7161 rectHeight
= rect
->GetHeight();
7163 width_label
= m_rowLabelWidth
- rect_x
;
7164 if (width_label
> rectWidth
)
7165 width_label
= rectWidth
;
7167 height_label
= m_colLabelHeight
- rect_y
;
7168 if (height_label
> rectHeight
)
7169 height_label
= rectHeight
;
7171 if (rect_x
> m_rowLabelWidth
)
7173 x
= rect_x
- m_rowLabelWidth
;
7174 width_cell
= rectWidth
;
7179 width_cell
= rectWidth
- (m_rowLabelWidth
- rect_x
);
7182 if (rect_y
> m_colLabelHeight
)
7184 y
= rect_y
- m_colLabelHeight
;
7185 height_cell
= rectHeight
;
7190 height_cell
= rectHeight
- (m_colLabelHeight
- rect_y
);
7193 // Paint corner label part intersecting rect.
7194 if ( width_label
> 0 && height_label
> 0 )
7196 wxRect
anotherrect(rect_x
, rect_y
, width_label
, height_label
);
7197 m_cornerLabelWin
->Refresh(eraseb
, &anotherrect
);
7200 // Paint col labels part intersecting rect.
7201 if ( width_cell
> 0 && height_label
> 0 )
7203 wxRect
anotherrect(x
, rect_y
, width_cell
, height_label
);
7204 m_colWindow
->Refresh(eraseb
, &anotherrect
);
7207 // Paint row labels part intersecting rect.
7208 if ( width_label
> 0 && height_cell
> 0 )
7210 wxRect
anotherrect(rect_x
, y
, width_label
, height_cell
);
7211 m_rowLabelWin
->Refresh(eraseb
, &anotherrect
);
7214 // Paint cell area part intersecting rect.
7215 if ( width_cell
> 0 && height_cell
> 0 )
7217 wxRect
anotherrect(x
, y
, width_cell
, height_cell
);
7218 m_gridWin
->Refresh(eraseb
, &anotherrect
);
7223 m_cornerLabelWin
->Refresh(eraseb
, NULL
);
7224 m_colWindow
->Refresh(eraseb
, NULL
);
7225 m_rowLabelWin
->Refresh(eraseb
, NULL
);
7226 m_gridWin
->Refresh(eraseb
, NULL
);
7231 void wxGrid::OnSize(wxSizeEvent
& WXUNUSED(event
))
7233 if (m_targetWindow
!= this) // check whether initialisation has been done
7235 // reposition our children windows
7240 void wxGrid::OnKeyDown( wxKeyEvent
& event
)
7242 if ( m_inOnKeyDown
)
7244 // shouldn't be here - we are going round in circles...
7246 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
7249 m_inOnKeyDown
= true;
7251 // propagate the event up and see if it gets processed
7252 wxWindow
*parent
= GetParent();
7253 wxKeyEvent
keyEvt( event
);
7254 keyEvt
.SetEventObject( parent
);
7256 if ( !parent
->GetEventHandler()->ProcessEvent( keyEvt
) )
7258 if (GetLayoutDirection() == wxLayout_RightToLeft
)
7260 if (event
.GetKeyCode() == WXK_RIGHT
)
7261 event
.m_keyCode
= WXK_LEFT
;
7262 else if (event
.GetKeyCode() == WXK_LEFT
)
7263 event
.m_keyCode
= WXK_RIGHT
;
7266 // try local handlers
7267 switch ( event
.GetKeyCode() )
7270 if ( event
.ControlDown() )
7271 MoveCursorUpBlock( event
.ShiftDown() );
7273 MoveCursorUp( event
.ShiftDown() );
7277 if ( event
.ControlDown() )
7278 MoveCursorDownBlock( event
.ShiftDown() );
7280 MoveCursorDown( event
.ShiftDown() );
7284 if ( event
.ControlDown() )
7285 MoveCursorLeftBlock( event
.ShiftDown() );
7287 MoveCursorLeft( event
.ShiftDown() );
7291 if ( event
.ControlDown() )
7292 MoveCursorRightBlock( event
.ShiftDown() );
7294 MoveCursorRight( event
.ShiftDown() );
7298 case WXK_NUMPAD_ENTER
:
7299 if ( event
.ControlDown() )
7301 event
.Skip(); // to let the edit control have the return
7305 if ( GetGridCursorRow() < GetNumberRows()-1 )
7307 MoveCursorDown( event
.ShiftDown() );
7311 // at the bottom of a column
7312 DisableCellEditControl();
7322 if (event
.ShiftDown())
7324 if ( GetGridCursorCol() > 0 )
7326 MoveCursorLeft( false );
7331 DisableCellEditControl();
7336 if ( GetGridCursorCol() < GetNumberCols() - 1 )
7338 MoveCursorRight( false );
7343 DisableCellEditControl();
7349 if ( event
.ControlDown() )
7360 if ( event
.ControlDown() )
7362 GoToCell(m_numRows
- 1, m_numCols
- 1);
7379 // Ctrl-Space selects the current column, Shift-Space -- the
7380 // current row and Ctrl-Shift-Space -- everything
7381 switch ( m_selection
? event
.GetModifiers() : wxMOD_NONE
)
7384 m_selection
->SelectCol(m_currentCellCoords
.GetCol());
7388 m_selection
->SelectRow(m_currentCellCoords
.GetRow());
7391 case wxMOD_CONTROL
| wxMOD_SHIFT
:
7392 m_selection
->SelectBlock(0, 0,
7393 m_numRows
- 1, m_numCols
- 1);
7397 if ( !IsEditable() )
7399 MoveCursorRight(false);
7402 //else: fall through
7415 m_inOnKeyDown
= false;
7418 void wxGrid::OnKeyUp( wxKeyEvent
& event
)
7420 // try local handlers
7422 if ( event
.GetKeyCode() == WXK_SHIFT
)
7424 if ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
7425 m_selectedBlockBottomRight
!= wxGridNoCellCoords
)
7429 m_selection
->SelectBlock(
7430 m_selectedBlockTopLeft
,
7431 m_selectedBlockBottomRight
,
7436 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
7437 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
7438 m_selectedBlockCorner
= wxGridNoCellCoords
;
7442 void wxGrid::OnChar( wxKeyEvent
& event
)
7444 // is it possible to edit the current cell at all?
7445 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
7447 // yes, now check whether the cells editor accepts the key
7448 int row
= m_currentCellCoords
.GetRow();
7449 int col
= m_currentCellCoords
.GetCol();
7450 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
7451 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
7453 // <F2> is special and will always start editing, for
7454 // other keys - ask the editor itself
7455 if ( (event
.GetKeyCode() == WXK_F2
&& !event
.HasModifiers())
7456 || editor
->IsAcceptedKey(event
) )
7458 // ensure cell is visble
7459 MakeCellVisible(row
, col
);
7460 EnableCellEditControl();
7462 // a problem can arise if the cell is not completely
7463 // visible (even after calling MakeCellVisible the
7464 // control is not created and calling StartingKey will
7466 if ( event
.GetKeyCode() != WXK_F2
&& editor
->IsCreated() && m_cellEditCtrlEnabled
)
7467 editor
->StartingKey(event
);
7483 void wxGrid::OnEraseBackground(wxEraseEvent
&)
7487 bool wxGrid::SetCurrentCell( const wxGridCellCoords
& coords
)
7489 if ( SendEvent(wxEVT_GRID_SELECT_CELL
, coords
) == -1 )
7491 // the event has been vetoed - do nothing
7495 #if !defined(__WXMAC__)
7496 wxClientDC
dc( m_gridWin
);
7500 if ( m_currentCellCoords
!= wxGridNoCellCoords
)
7502 DisableCellEditControl();
7504 if ( IsVisible( m_currentCellCoords
, false ) )
7507 r
= BlockToDeviceRect( m_currentCellCoords
, m_currentCellCoords
);
7508 if ( !m_gridLinesEnabled
)
7516 wxGridCellCoordsArray cells
= CalcCellsExposed( r
);
7518 // Otherwise refresh redraws the highlight!
7519 m_currentCellCoords
= coords
;
7521 #if defined(__WXMAC__)
7522 m_gridWin
->Refresh(true /*, & r */);
7524 DrawGridCellArea( dc
, cells
);
7525 DrawAllGridLines( dc
, r
);
7530 m_currentCellCoords
= coords
;
7532 wxGridCellAttr
*attr
= GetCellAttr( coords
);
7533 #if !defined(__WXMAC__)
7534 DrawCellHighlight( dc
, attr
);
7542 wxGrid::UpdateBlockBeingSelected(int topRow
, int leftCol
,
7543 int bottomRow
, int rightCol
)
7547 switch ( m_selection
->GetSelectionMode() )
7550 wxFAIL_MSG( "unknown selection mode" );
7553 case wxGridSelectCells
:
7554 // arbitrary blocks selection allowed so just use the cell
7555 // coordinates as is
7558 case wxGridSelectRows
:
7559 // only full rows selection allowd, ensure that we do select
7562 rightCol
= GetNumberCols() - 1;
7565 case wxGridSelectColumns
:
7566 // same as above but for columns
7568 bottomRow
= GetNumberRows() - 1;
7571 case wxGridSelectRowsOrColumns
:
7572 // in this mode we can select only full rows or full columns so
7573 // it doesn't make sense to select blocks at all (and we can't
7574 // extend the block because there is no preferred direction, we
7575 // could only extend it to cover the entire grid but this is
7581 m_selectedBlockCorner
= wxGridCellCoords(bottomRow
, rightCol
);
7582 MakeCellVisible(m_selectedBlockCorner
);
7584 EnsureFirstLessThanSecond(topRow
, bottomRow
);
7585 EnsureFirstLessThanSecond(leftCol
, rightCol
);
7587 wxGridCellCoords updateTopLeft
= wxGridCellCoords(topRow
, leftCol
),
7588 updateBottomRight
= wxGridCellCoords(bottomRow
, rightCol
);
7590 // First the case that we selected a completely new area
7591 if ( m_selectedBlockTopLeft
== wxGridNoCellCoords
||
7592 m_selectedBlockBottomRight
== wxGridNoCellCoords
)
7595 rect
= BlockToDeviceRect( wxGridCellCoords ( topRow
, leftCol
),
7596 wxGridCellCoords ( bottomRow
, rightCol
) );
7597 m_gridWin
->Refresh( false, &rect
);
7600 // Now handle changing an existing selection area.
7601 else if ( m_selectedBlockTopLeft
!= updateTopLeft
||
7602 m_selectedBlockBottomRight
!= updateBottomRight
)
7604 // Compute two optimal update rectangles:
7605 // Either one rectangle is a real subset of the
7606 // other, or they are (almost) disjoint!
7608 bool need_refresh
[4];
7612 need_refresh
[3] = false;
7615 // Store intermediate values
7616 wxCoord oldLeft
= m_selectedBlockTopLeft
.GetCol();
7617 wxCoord oldTop
= m_selectedBlockTopLeft
.GetRow();
7618 wxCoord oldRight
= m_selectedBlockBottomRight
.GetCol();
7619 wxCoord oldBottom
= m_selectedBlockBottomRight
.GetRow();
7621 // Determine the outer/inner coordinates.
7622 EnsureFirstLessThanSecond(oldLeft
, leftCol
);
7623 EnsureFirstLessThanSecond(oldTop
, topRow
);
7624 EnsureFirstLessThanSecond(rightCol
, oldRight
);
7625 EnsureFirstLessThanSecond(bottomRow
, oldBottom
);
7627 // Now, either the stuff marked old is the outer
7628 // rectangle or we don't have a situation where one
7629 // is contained in the other.
7631 if ( oldLeft
< leftCol
)
7633 // Refresh the newly selected or deselected
7634 // area to the left of the old or new selection.
7635 need_refresh
[0] = true;
7636 rect
[0] = BlockToDeviceRect(
7637 wxGridCellCoords( oldTop
, oldLeft
),
7638 wxGridCellCoords( oldBottom
, leftCol
- 1 ) );
7641 if ( oldTop
< topRow
)
7643 // Refresh the newly selected or deselected
7644 // area above the old or new selection.
7645 need_refresh
[1] = true;
7646 rect
[1] = BlockToDeviceRect(
7647 wxGridCellCoords( oldTop
, leftCol
),
7648 wxGridCellCoords( topRow
- 1, rightCol
) );
7651 if ( oldRight
> rightCol
)
7653 // Refresh the newly selected or deselected
7654 // area to the right of the old or new selection.
7655 need_refresh
[2] = true;
7656 rect
[2] = BlockToDeviceRect(
7657 wxGridCellCoords( oldTop
, rightCol
+ 1 ),
7658 wxGridCellCoords( oldBottom
, oldRight
) );
7661 if ( oldBottom
> bottomRow
)
7663 // Refresh the newly selected or deselected
7664 // area below the old or new selection.
7665 need_refresh
[3] = true;
7666 rect
[3] = BlockToDeviceRect(
7667 wxGridCellCoords( bottomRow
+ 1, leftCol
),
7668 wxGridCellCoords( oldBottom
, rightCol
) );
7671 // various Refresh() calls
7672 for (i
= 0; i
< 4; i
++ )
7673 if ( need_refresh
[i
] && rect
[i
] != wxGridNoCellRect
)
7674 m_gridWin
->Refresh( false, &(rect
[i
]) );
7678 m_selectedBlockTopLeft
= updateTopLeft
;
7679 m_selectedBlockBottomRight
= updateBottomRight
;
7683 // ------ functions to get/send data (see also public functions)
7686 bool wxGrid::GetModelValues()
7688 // Hide the editor, so it won't hide a changed value.
7689 HideCellEditControl();
7693 // all we need to do is repaint the grid
7695 m_gridWin
->Refresh();
7702 bool wxGrid::SetModelValues()
7706 // Disable the editor, so it won't hide a changed value.
7707 // Do we also want to save the current value of the editor first?
7709 DisableCellEditControl();
7713 for ( row
= 0; row
< m_numRows
; row
++ )
7715 for ( col
= 0; col
< m_numCols
; col
++ )
7717 m_table
->SetValue( row
, col
, GetCellValue(row
, col
) );
7727 // Note - this function only draws cells that are in the list of
7728 // exposed cells (usually set from the update region by
7729 // CalcExposedCells)
7731 void wxGrid::DrawGridCellArea( wxDC
& dc
, const wxGridCellCoordsArray
& cells
)
7733 if ( !m_numRows
|| !m_numCols
)
7736 int i
, numCells
= cells
.GetCount();
7737 int row
, col
, cell_rows
, cell_cols
;
7738 wxGridCellCoordsArray redrawCells
;
7740 for ( i
= numCells
- 1; i
>= 0; i
-- )
7742 row
= cells
[i
].GetRow();
7743 col
= cells
[i
].GetCol();
7744 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
7746 // If this cell is part of a multicell block, find owner for repaint
7747 if ( cell_rows
<= 0 || cell_cols
<= 0 )
7749 wxGridCellCoords
cell( row
+ cell_rows
, col
+ cell_cols
);
7750 bool marked
= false;
7751 for ( int j
= 0; j
< numCells
; j
++ )
7753 if ( cell
== cells
[j
] )
7762 int count
= redrawCells
.GetCount();
7763 for (int j
= 0; j
< count
; j
++)
7765 if ( cell
== redrawCells
[j
] )
7773 redrawCells
.Add( cell
);
7776 // don't bother drawing this cell
7780 // If this cell is empty, find cell to left that might want to overflow
7781 if (m_table
&& m_table
->IsEmptyCell(row
, col
))
7783 for ( int l
= 0; l
< cell_rows
; l
++ )
7785 // find a cell in this row to leave already marked for repaint
7787 for (int k
= 0; k
< int(redrawCells
.GetCount()); k
++)
7788 if ((redrawCells
[k
].GetCol() < left
) &&
7789 (redrawCells
[k
].GetRow() == row
))
7791 left
= redrawCells
[k
].GetCol();
7795 left
= 0; // oh well
7797 for (int j
= col
- 1; j
>= left
; j
--)
7799 if (!m_table
->IsEmptyCell(row
+ l
, j
))
7801 if (GetCellOverflow(row
+ l
, j
))
7803 wxGridCellCoords
cell(row
+ l
, j
);
7804 bool marked
= false;
7806 for (int k
= 0; k
< numCells
; k
++)
7808 if ( cell
== cells
[k
] )
7817 int count
= redrawCells
.GetCount();
7818 for (int k
= 0; k
< count
; k
++)
7820 if ( cell
== redrawCells
[k
] )
7827 redrawCells
.Add( cell
);
7836 DrawCell( dc
, cells
[i
] );
7839 numCells
= redrawCells
.GetCount();
7841 for ( i
= numCells
- 1; i
>= 0; i
-- )
7843 DrawCell( dc
, redrawCells
[i
] );
7847 void wxGrid::DrawGridSpace( wxDC
& dc
)
7850 m_gridWin
->GetClientSize( &cw
, &ch
);
7853 CalcUnscrolledPosition( cw
, ch
, &right
, &bottom
);
7855 int rightCol
= m_numCols
> 0 ? GetColRight(GetColAt( m_numCols
- 1 )) : 0;
7856 int bottomRow
= m_numRows
> 0 ? GetRowBottom(m_numRows
- 1) : 0;
7858 if ( right
> rightCol
|| bottom
> bottomRow
)
7861 CalcUnscrolledPosition( 0, 0, &left
, &top
);
7863 dc
.SetBrush(GetDefaultCellBackgroundColour());
7864 dc
.SetPen( *wxTRANSPARENT_PEN
);
7866 if ( right
> rightCol
)
7868 dc
.DrawRectangle( rightCol
, top
, right
- rightCol
, ch
);
7871 if ( bottom
> bottomRow
)
7873 dc
.DrawRectangle( left
, bottomRow
, cw
, bottom
- bottomRow
);
7878 void wxGrid::DrawCell( wxDC
& dc
, const wxGridCellCoords
& coords
)
7880 int row
= coords
.GetRow();
7881 int col
= coords
.GetCol();
7883 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7886 // we draw the cell border ourselves
7887 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
7889 bool isCurrent
= coords
== m_currentCellCoords
;
7891 wxRect rect
= CellToRect( row
, col
);
7893 // if the editor is shown, we should use it and not the renderer
7894 // Note: However, only if it is really _shown_, i.e. not hidden!
7895 if ( isCurrent
&& IsCellEditControlShown() )
7897 // NB: this "#if..." is temporary and fixes a problem where the
7898 // edit control is erased by this code after being rendered.
7899 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
7900 // implicitly, causing this out-of order render.
7901 #if !defined(__WXMAC__)
7902 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
7903 editor
->PaintBackground(rect
, attr
);
7909 // but all the rest is drawn by the cell renderer and hence may be customized
7910 wxGridCellRenderer
*renderer
= attr
->GetRenderer(this, row
, col
);
7911 renderer
->Draw(*this, *attr
, dc
, rect
, row
, col
, IsInSelection(coords
));
7918 void wxGrid::DrawCellHighlight( wxDC
& dc
, const wxGridCellAttr
*attr
)
7920 // don't show highlight when the grid doesn't have focus
7924 int row
= m_currentCellCoords
.GetRow();
7925 int col
= m_currentCellCoords
.GetCol();
7927 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7930 wxRect rect
= CellToRect(row
, col
);
7932 // hmmm... what could we do here to show that the cell is disabled?
7933 // for now, I just draw a thinner border than for the other ones, but
7934 // it doesn't look really good
7936 int penWidth
= attr
->IsReadOnly() ? m_cellHighlightROPenWidth
: m_cellHighlightPenWidth
;
7940 // The center of the drawn line is where the position/width/height of
7941 // the rectangle is actually at (on wxMSW at least), so the
7942 // size of the rectangle is reduced to compensate for the thickness of
7943 // the line. If this is too strange on non-wxMSW platforms then
7944 // please #ifdef this appropriately.
7945 rect
.x
+= penWidth
/ 2;
7946 rect
.y
+= penWidth
/ 2;
7947 rect
.width
-= penWidth
- 1;
7948 rect
.height
-= penWidth
- 1;
7950 // Now draw the rectangle
7951 // use the cellHighlightColour if the cell is inside a selection, this
7952 // will ensure the cell is always visible.
7953 dc
.SetPen(wxPen(IsInSelection(row
,col
) ? m_selectionForeground
7954 : m_cellHighlightColour
,
7956 dc
.SetBrush(*wxTRANSPARENT_BRUSH
);
7957 dc
.DrawRectangle(rect
);
7961 wxPen
wxGrid::GetDefaultGridLinePen()
7963 return wxPen(GetGridLineColour());
7966 wxPen
wxGrid::GetRowGridLinePen(int WXUNUSED(row
))
7968 return GetDefaultGridLinePen();
7971 wxPen
wxGrid::GetColGridLinePen(int WXUNUSED(col
))
7973 return GetDefaultGridLinePen();
7976 void wxGrid::DrawCellBorder( wxDC
& dc
, const wxGridCellCoords
& coords
)
7978 int row
= coords
.GetRow();
7979 int col
= coords
.GetCol();
7980 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7984 wxRect rect
= CellToRect( row
, col
);
7986 // right hand border
7987 dc
.SetPen( GetColGridLinePen(col
) );
7988 dc
.DrawLine( rect
.x
+ rect
.width
, rect
.y
,
7989 rect
.x
+ rect
.width
, rect
.y
+ rect
.height
+ 1 );
7992 dc
.SetPen( GetRowGridLinePen(row
) );
7993 dc
.DrawLine( rect
.x
, rect
.y
+ rect
.height
,
7994 rect
.x
+ rect
.width
, rect
.y
+ rect
.height
);
7997 void wxGrid::DrawHighlight(wxDC
& dc
, const wxGridCellCoordsArray
& cells
)
7999 // This if block was previously in wxGrid::OnPaint but that doesn't
8000 // seem to get called under wxGTK - MB
8002 if ( m_currentCellCoords
== wxGridNoCellCoords
&&
8003 m_numRows
&& m_numCols
)
8005 m_currentCellCoords
.Set(0, 0);
8008 if ( IsCellEditControlShown() )
8010 // don't show highlight when the edit control is shown
8014 // if the active cell was repainted, repaint its highlight too because it
8015 // might have been damaged by the grid lines
8016 size_t count
= cells
.GetCount();
8017 for ( size_t n
= 0; n
< count
; n
++ )
8019 wxGridCellCoords cell
= cells
[n
];
8021 // If we are using attributes, then we may have just exposed another
8022 // cell in a partially-visible merged cluster of cells. If the "anchor"
8023 // (upper left) cell of this merged cluster is the cell indicated by
8024 // m_currentCellCoords, then we need to refresh the cell highlight even
8025 // though the "anchor" itself is not part of our update segment.
8026 if ( CanHaveAttributes() )
8030 GetCellSize(cell
.GetRow(), cell
.GetCol(), &rows
, &cols
);
8033 cell
.SetRow(cell
.GetRow() + rows
);
8036 cell
.SetCol(cell
.GetCol() + cols
);
8039 if ( cell
== m_currentCellCoords
)
8041 wxGridCellAttr
* attr
= GetCellAttr(m_currentCellCoords
);
8042 DrawCellHighlight(dc
, attr
);
8050 // This is used to redraw all grid lines e.g. when the grid line colour
8053 void wxGrid::DrawAllGridLines( wxDC
& dc
, const wxRegion
& WXUNUSED(reg
) )
8055 if ( !m_gridLinesEnabled
)
8058 int top
, bottom
, left
, right
;
8061 m_gridWin
->GetClientSize(&cw
, &ch
);
8062 CalcUnscrolledPosition( 0, 0, &left
, &top
);
8063 CalcUnscrolledPosition( cw
, ch
, &right
, &bottom
);
8065 // avoid drawing grid lines past the last row and col
8066 if ( m_gridLinesClipHorz
)
8071 const int lastColRight
= GetColRight(GetColAt(m_numCols
- 1));
8072 if ( right
> lastColRight
)
8073 right
= lastColRight
;
8076 if ( m_gridLinesClipVert
)
8081 const int lastRowBottom
= GetRowBottom(m_numRows
- 1);
8082 if ( bottom
> lastRowBottom
)
8083 bottom
= lastRowBottom
;
8086 // no gridlines inside multicells, clip them out
8087 int leftCol
= GetColPos( internalXToCol(left
) );
8088 int topRow
= internalYToRow(top
);
8089 int rightCol
= GetColPos( internalXToCol(right
) );
8090 int bottomRow
= internalYToRow(bottom
);
8092 wxRegion
clippedcells(0, 0, cw
, ch
);
8094 int cell_rows
, cell_cols
;
8097 for ( int j
= topRow
; j
<= bottomRow
; j
++ )
8099 for ( int colPos
= leftCol
; colPos
<= rightCol
; colPos
++ )
8101 int i
= GetColAt( colPos
);
8103 GetCellSize( j
, i
, &cell_rows
, &cell_cols
);
8104 if ((cell_rows
> 1) || (cell_cols
> 1))
8106 rect
= CellToRect(j
,i
);
8107 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8108 clippedcells
.Subtract(rect
);
8110 else if ((cell_rows
< 0) || (cell_cols
< 0))
8112 rect
= CellToRect(j
+ cell_rows
, i
+ cell_cols
);
8113 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8114 clippedcells
.Subtract(rect
);
8119 dc
.SetDeviceClippingRegion( clippedcells
);
8122 // horizontal grid lines
8123 for ( int i
= internalYToRow(top
); i
< m_numRows
; i
++ )
8125 int bot
= GetRowBottom(i
) - 1;
8132 dc
.SetPen( GetRowGridLinePen(i
) );
8133 dc
.DrawLine( left
, bot
, right
, bot
);
8137 // vertical grid lines
8138 for ( int colPos
= leftCol
; colPos
< m_numCols
; colPos
++ )
8140 int i
= GetColAt( colPos
);
8142 int colRight
= GetColRight(i
);
8144 if (GetLayoutDirection() != wxLayout_RightToLeft
)
8148 if ( colRight
> right
)
8151 if ( colRight
>= left
)
8153 dc
.SetPen( GetColGridLinePen(i
) );
8154 dc
.DrawLine( colRight
, top
, colRight
, bottom
);
8158 dc
.DestroyClippingRegion();
8161 void wxGrid::DrawRowLabels( wxDC
& dc
, const wxArrayInt
& rows
)
8166 const size_t numLabels
= rows
.GetCount();
8167 for ( size_t i
= 0; i
< numLabels
; i
++ )
8169 DrawRowLabel( dc
, rows
[i
] );
8173 void wxGrid::DrawRowLabel( wxDC
& dc
, int row
)
8175 if ( GetRowHeight(row
) <= 0 || m_rowLabelWidth
<= 0 )
8180 int rowTop
= GetRowTop(row
),
8181 rowBottom
= GetRowBottom(row
) - 1;
8183 dc
.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8184 dc
.DrawLine( m_rowLabelWidth
- 1, rowTop
, m_rowLabelWidth
- 1, rowBottom
);
8185 dc
.DrawLine( 0, rowTop
, 0, rowBottom
);
8186 dc
.DrawLine( 0, rowBottom
, m_rowLabelWidth
, rowBottom
);
8188 dc
.SetPen( *wxWHITE_PEN
);
8189 dc
.DrawLine( 1, rowTop
, 1, rowBottom
);
8190 dc
.DrawLine( 1, rowTop
, m_rowLabelWidth
- 1, rowTop
);
8192 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
8193 dc
.SetTextForeground( GetLabelTextColour() );
8194 dc
.SetFont( GetLabelFont() );
8197 GetRowLabelAlignment( &hAlign
, &vAlign
);
8200 rect
.SetY( GetRowTop(row
) + 2 );
8201 rect
.SetWidth( m_rowLabelWidth
- 4 );
8202 rect
.SetHeight( GetRowHeight(row
) - 4 );
8203 DrawTextRectangle( dc
, GetRowLabelValue( row
), rect
, hAlign
, vAlign
);
8206 void wxGrid::UseNativeColHeader(bool native
)
8208 if ( native
== m_useNativeHeader
)
8212 m_useNativeHeader
= native
;
8214 CreateColumnWindow();
8216 if ( m_useNativeHeader
)
8217 GetGridColHeader()->SetColumnCount(m_numCols
);
8221 void wxGrid::SetUseNativeColLabels( bool native
)
8223 wxASSERT_MSG( !m_useNativeHeader
,
8224 "doesn't make sense when using native header" );
8226 m_nativeColumnLabels
= native
;
8229 int height
= wxRendererNative::Get().GetHeaderButtonHeight( this );
8230 SetColLabelSize( height
);
8233 GetColLabelWindow()->Refresh();
8234 m_cornerLabelWin
->Refresh();
8237 void wxGrid::DrawColLabels( wxDC
& dc
,const wxArrayInt
& cols
)
8242 const size_t numLabels
= cols
.GetCount();
8243 for ( size_t i
= 0; i
< numLabels
; i
++ )
8245 DrawColLabel( dc
, cols
[i
] );
8249 void wxGrid::DrawCornerLabel(wxDC
& dc
)
8251 if ( m_nativeColumnLabels
)
8253 wxRect
rect(wxSize(m_rowLabelWidth
, m_colLabelHeight
));
8256 wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin
, dc
, rect
, 0);
8260 dc
.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8261 dc
.DrawLine( m_rowLabelWidth
- 1, m_colLabelHeight
- 1,
8262 m_rowLabelWidth
- 1, 0 );
8263 dc
.DrawLine( m_rowLabelWidth
- 1, m_colLabelHeight
- 1,
8264 0, m_colLabelHeight
- 1 );
8265 dc
.DrawLine( 0, 0, m_rowLabelWidth
, 0 );
8266 dc
.DrawLine( 0, 0, 0, m_colLabelHeight
);
8268 dc
.SetPen( *wxWHITE_PEN
);
8269 dc
.DrawLine( 1, 1, m_rowLabelWidth
- 1, 1 );
8270 dc
.DrawLine( 1, 1, 1, m_colLabelHeight
- 1 );
8274 void wxGrid::DrawColLabel(wxDC
& dc
, int col
)
8276 if ( GetColWidth(col
) <= 0 || m_colLabelHeight
<= 0 )
8279 int colLeft
= GetColLeft(col
);
8281 wxRect
rect(colLeft
, 0, GetColWidth(col
), m_colLabelHeight
);
8283 if ( m_nativeColumnLabels
)
8285 wxRendererNative::Get().DrawHeaderButton
8287 GetColLabelWindow(),
8292 ? IsSortOrderAscending()
8293 ? wxHDR_SORT_ICON_UP
8294 : wxHDR_SORT_ICON_DOWN
8295 : wxHDR_SORT_ICON_NONE
8300 int colRight
= GetColRight(col
) - 1;
8302 dc
.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8303 dc
.DrawLine( colRight
, 0,
8304 colRight
, m_colLabelHeight
- 1 );
8305 dc
.DrawLine( colLeft
, 0,
8307 dc
.DrawLine( colLeft
, m_colLabelHeight
- 1,
8308 colRight
+ 1, m_colLabelHeight
- 1 );
8310 dc
.SetPen( *wxWHITE_PEN
);
8311 dc
.DrawLine( colLeft
, 1, colLeft
, m_colLabelHeight
- 1 );
8312 dc
.DrawLine( colLeft
, 1, colRight
, 1 );
8315 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
8316 dc
.SetTextForeground( GetLabelTextColour() );
8317 dc
.SetFont( GetLabelFont() );
8320 GetColLabelAlignment( &hAlign
, &vAlign
);
8321 const int orient
= GetColLabelTextOrientation();
8324 DrawTextRectangle(dc
, GetColLabelValue(col
), rect
, hAlign
, vAlign
, orient
);
8327 // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which
8328 // we just have to add textOrientation support
8329 void wxGrid::DrawTextRectangle( wxDC
& dc
,
8330 const wxString
& value
,
8334 int textOrientation
)
8336 wxArrayString lines
;
8338 StringToLines( value
, lines
);
8340 DrawTextRectangle(dc
, lines
, rect
, horizAlign
, vertAlign
, textOrientation
);
8343 void wxGrid::DrawTextRectangle(wxDC
& dc
,
8344 const wxArrayString
& lines
,
8348 int textOrientation
)
8350 if ( lines
.empty() )
8353 wxDCClipper
clip(dc
, rect
);
8358 if ( textOrientation
== wxHORIZONTAL
)
8359 GetTextBoxSize( dc
, lines
, &textWidth
, &textHeight
);
8361 GetTextBoxSize( dc
, lines
, &textHeight
, &textWidth
);
8365 switch ( vertAlign
)
8367 case wxALIGN_BOTTOM
:
8368 if ( textOrientation
== wxHORIZONTAL
)
8369 y
= rect
.y
+ (rect
.height
- textHeight
- 1);
8371 x
= rect
.x
+ rect
.width
- textWidth
;
8374 case wxALIGN_CENTRE
:
8375 if ( textOrientation
== wxHORIZONTAL
)
8376 y
= rect
.y
+ ((rect
.height
- textHeight
) / 2);
8378 x
= rect
.x
+ ((rect
.width
- textWidth
) / 2);
8383 if ( textOrientation
== wxHORIZONTAL
)
8390 // Align each line of a multi-line label
8391 size_t nLines
= lines
.GetCount();
8392 for ( size_t l
= 0; l
< nLines
; l
++ )
8394 const wxString
& line
= lines
[l
];
8398 *(textOrientation
== wxHORIZONTAL
? &y
: &x
) += dc
.GetCharHeight();
8402 wxCoord lineWidth
= 0,
8404 dc
.GetTextExtent(line
, &lineWidth
, &lineHeight
);
8406 switch ( horizAlign
)
8409 if ( textOrientation
== wxHORIZONTAL
)
8410 x
= rect
.x
+ (rect
.width
- lineWidth
- 1);
8412 y
= rect
.y
+ lineWidth
+ 1;
8415 case wxALIGN_CENTRE
:
8416 if ( textOrientation
== wxHORIZONTAL
)
8417 x
= rect
.x
+ ((rect
.width
- lineWidth
) / 2);
8419 y
= rect
.y
+ rect
.height
- ((rect
.height
- lineWidth
) / 2);
8424 if ( textOrientation
== wxHORIZONTAL
)
8427 y
= rect
.y
+ rect
.height
- 1;
8431 if ( textOrientation
== wxHORIZONTAL
)
8433 dc
.DrawText( line
, x
, y
);
8438 dc
.DrawRotatedText( line
, x
, y
, 90.0 );
8444 // Split multi-line text up into an array of strings.
8445 // Any existing contents of the string array are preserved.
8447 // TODO: refactor wxTextFile::Read() and reuse the same code from here
8448 void wxGrid::StringToLines( const wxString
& value
, wxArrayString
& lines
) const
8452 wxString eol
= wxTextFile::GetEOL( wxTextFileType_Unix
);
8453 wxString tVal
= wxTextFile::Translate( value
, wxTextFileType_Unix
);
8455 while ( startPos
< (int)tVal
.length() )
8457 pos
= tVal
.Mid(startPos
).Find( eol
);
8462 else if ( pos
== 0 )
8464 lines
.Add( wxEmptyString
);
8468 lines
.Add( tVal
.Mid(startPos
, pos
) );
8471 startPos
+= pos
+ 1;
8474 if ( startPos
< (int)tVal
.length() )
8476 lines
.Add( tVal
.Mid( startPos
) );
8480 void wxGrid::GetTextBoxSize( const wxDC
& dc
,
8481 const wxArrayString
& lines
,
8482 long *width
, long *height
) const
8486 wxCoord lineW
= 0, lineH
= 0;
8489 for ( i
= 0; i
< lines
.GetCount(); i
++ )
8491 dc
.GetTextExtent( lines
[i
], &lineW
, &lineH
);
8492 w
= wxMax( w
, lineW
);
8501 // ------ Batch processing.
8503 void wxGrid::EndBatch()
8505 if ( m_batchCount
> 0 )
8508 if ( !m_batchCount
)
8511 m_rowLabelWin
->Refresh();
8512 m_colWindow
->Refresh();
8513 m_cornerLabelWin
->Refresh();
8514 m_gridWin
->Refresh();
8519 // Use this, rather than wxWindow::Refresh(), to force an immediate
8520 // repainting of the grid. Has no effect if you are already inside a
8521 // BeginBatch / EndBatch block.
8523 void wxGrid::ForceRefresh()
8529 bool wxGrid::Enable(bool enable
)
8531 if ( !wxScrolledWindow::Enable(enable
) )
8534 // redraw in the new state
8535 m_gridWin
->Refresh();
8541 // ------ Edit control functions
8544 void wxGrid::EnableEditing( bool edit
)
8546 if ( edit
!= m_editable
)
8549 EnableCellEditControl(edit
);
8554 void wxGrid::EnableCellEditControl( bool enable
)
8559 if ( enable
!= m_cellEditCtrlEnabled
)
8563 if ( SendEvent(wxEVT_GRID_EDITOR_SHOWN
) == -1 )
8566 // this should be checked by the caller!
8567 wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") );
8569 // do it before ShowCellEditControl()
8570 m_cellEditCtrlEnabled
= enable
;
8572 ShowCellEditControl();
8576 //FIXME:add veto support
8577 SendEvent(wxEVT_GRID_EDITOR_HIDDEN
);
8579 HideCellEditControl();
8580 SaveEditControlValue();
8582 // do it after HideCellEditControl()
8583 m_cellEditCtrlEnabled
= enable
;
8588 bool wxGrid::IsCurrentCellReadOnly() const
8591 wxGridCellAttr
* attr
= ((wxGrid
*)this)->GetCellAttr(m_currentCellCoords
);
8592 bool readonly
= attr
->IsReadOnly();
8598 bool wxGrid::CanEnableCellControl() const
8600 return m_editable
&& (m_currentCellCoords
!= wxGridNoCellCoords
) &&
8601 !IsCurrentCellReadOnly();
8604 bool wxGrid::IsCellEditControlEnabled() const
8606 // the cell edit control might be disable for all cells or just for the
8607 // current one if it's read only
8608 return m_cellEditCtrlEnabled
? !IsCurrentCellReadOnly() : false;
8611 bool wxGrid::IsCellEditControlShown() const
8613 bool isShown
= false;
8615 if ( m_cellEditCtrlEnabled
)
8617 int row
= m_currentCellCoords
.GetRow();
8618 int col
= m_currentCellCoords
.GetCol();
8619 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8620 wxGridCellEditor
* editor
= attr
->GetEditor((wxGrid
*) this, row
, col
);
8625 if ( editor
->IsCreated() )
8627 isShown
= editor
->GetControl()->IsShown();
8637 void wxGrid::ShowCellEditControl()
8639 if ( IsCellEditControlEnabled() )
8641 if ( !IsVisible( m_currentCellCoords
, false ) )
8643 m_cellEditCtrlEnabled
= false;
8648 wxRect rect
= CellToRect( m_currentCellCoords
);
8649 int row
= m_currentCellCoords
.GetRow();
8650 int col
= m_currentCellCoords
.GetCol();
8652 // if this is part of a multicell, find owner (topleft)
8653 int cell_rows
, cell_cols
;
8654 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
8655 if ( cell_rows
<= 0 || cell_cols
<= 0 )
8659 m_currentCellCoords
.SetRow( row
);
8660 m_currentCellCoords
.SetCol( col
);
8663 // erase the highlight and the cell contents because the editor
8664 // might not cover the entire cell
8665 wxClientDC
dc( m_gridWin
);
8667 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8668 dc
.SetBrush(wxBrush(attr
->GetBackgroundColour()));
8669 dc
.SetPen(*wxTRANSPARENT_PEN
);
8670 dc
.DrawRectangle(rect
);
8672 // convert to scrolled coords
8673 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8679 // cell is shifted by one pixel
8680 // However, don't allow x or y to become negative
8681 // since the SetSize() method interprets that as
8688 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
8689 if ( !editor
->IsCreated() )
8691 editor
->Create(m_gridWin
, wxID_ANY
,
8692 new wxGridCellEditorEvtHandler(this, editor
));
8694 wxGridEditorCreatedEvent
evt(GetId(),
8695 wxEVT_GRID_EDITOR_CREATED
,
8699 editor
->GetControl());
8700 GetEventHandler()->ProcessEvent(evt
);
8703 // resize editor to overflow into righthand cells if allowed
8704 int maxWidth
= rect
.width
;
8705 wxString value
= GetCellValue(row
, col
);
8706 if ( (value
!= wxEmptyString
) && (attr
->GetOverflow()) )
8709 GetTextExtent(value
, &maxWidth
, &y
, NULL
, NULL
, &attr
->GetFont());
8710 if (maxWidth
< rect
.width
)
8711 maxWidth
= rect
.width
;
8714 int client_right
= m_gridWin
->GetClientSize().GetWidth();
8715 if (rect
.x
+ maxWidth
> client_right
)
8716 maxWidth
= client_right
- rect
.x
;
8718 if ((maxWidth
> rect
.width
) && (col
< m_numCols
) && m_table
)
8720 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
8721 // may have changed earlier
8722 for (int i
= col
+ cell_cols
; i
< m_numCols
; i
++)
8725 GetCellSize( row
, i
, &c_rows
, &c_cols
);
8727 // looks weird going over a multicell
8728 if (m_table
->IsEmptyCell( row
, i
) &&
8729 (rect
.width
< maxWidth
) && (c_rows
== 1))
8731 rect
.width
+= GetColWidth( i
);
8737 if (rect
.GetRight() > client_right
)
8738 rect
.SetRight( client_right
- 1 );
8741 editor
->SetCellAttr( attr
);
8742 editor
->SetSize( rect
);
8744 editor
->GetControl()->Move(
8745 editor
->GetControl()->GetPosition().x
+ nXMove
,
8746 editor
->GetControl()->GetPosition().y
);
8747 editor
->Show( true, attr
);
8749 // recalc dimensions in case we need to
8750 // expand the scrolled window to account for editor
8753 editor
->BeginEdit(row
, col
, this);
8754 editor
->SetCellAttr(NULL
);
8762 void wxGrid::HideCellEditControl()
8764 if ( IsCellEditControlEnabled() )
8766 int row
= m_currentCellCoords
.GetRow();
8767 int col
= m_currentCellCoords
.GetCol();
8769 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
8770 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
8771 const bool editorHadFocus
= editor
->GetControl()->HasFocus();
8772 editor
->Show( false );
8776 // return the focus to the grid itself if the editor had it
8778 // note that we must not do this unconditionally to avoid stealing
8779 // focus from the window which just received it if we are hiding the
8780 // editor precisely because we lost focus
8781 if ( editorHadFocus
)
8782 m_gridWin
->SetFocus();
8784 // refresh whole row to the right
8785 wxRect
rect( CellToRect(row
, col
) );
8786 CalcScrolledPosition(rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8787 rect
.width
= m_gridWin
->GetClientSize().GetWidth() - rect
.x
;
8790 // ensure that the pixels under the focus ring get refreshed as well
8791 rect
.Inflate(10, 10);
8794 m_gridWin
->Refresh( false, &rect
);
8798 void wxGrid::SaveEditControlValue()
8800 if ( IsCellEditControlEnabled() )
8802 int row
= m_currentCellCoords
.GetRow();
8803 int col
= m_currentCellCoords
.GetCol();
8805 wxString oldval
= GetCellValue(row
, col
);
8807 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8808 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
8809 bool changed
= editor
->EndEdit(row
, col
, this);
8816 if ( SendEvent(wxEVT_GRID_CELL_CHANGE
) == -1 )
8818 // Event has been vetoed, set the data back.
8819 SetCellValue(row
, col
, oldval
);
8826 // ------ Grid location functions
8827 // Note that all of these functions work with the logical coordinates of
8828 // grid cells and labels so you will need to convert from device
8829 // coordinates for mouse events etc.
8832 wxGridCellCoords
wxGrid::XYToCell(int x
, int y
) const
8834 int row
= YToRow(y
);
8835 int col
= XToCol(x
);
8837 return row
== -1 || col
== -1 ? wxGridNoCellCoords
8838 : wxGridCellCoords(row
, col
);
8841 // compute row or column from some (unscrolled) coordinate value, using either
8842 // m_defaultRowHeight/m_defaultColWidth or binary search on array of
8843 // m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used
8845 int wxGrid::PosToLinePos(int coord
,
8847 const wxGridOperations
& oper
) const
8849 const int numLines
= oper
.GetNumberOfLines(this);
8852 return clipToMinMax
&& numLines
> 0 ? 0 : wxNOT_FOUND
;
8854 const int defaultLineSize
= oper
.GetDefaultLineSize(this);
8855 wxCHECK_MSG( defaultLineSize
, -1, "can't have 0 default line size" );
8857 int maxPos
= coord
/ defaultLineSize
,
8860 // check for the simplest case: if we have no explicit line sizes
8861 // configured, then we already know the line this position falls in
8862 const wxArrayInt
& lineEnds
= oper
.GetLineEnds(this);
8863 if ( lineEnds
.empty() )
8865 if ( maxPos
< numLines
)
8868 return clipToMinMax
? numLines
- 1 : -1;
8872 // adjust maxPos before starting the binary search
8873 if ( maxPos
>= numLines
)
8875 maxPos
= numLines
- 1;
8879 if ( coord
>= lineEnds
[oper
.GetLineAt(this, maxPos
)])
8882 const int minDist
= oper
.GetMinimalAcceptableLineSize(this);
8884 maxPos
= coord
/ minDist
;
8886 maxPos
= numLines
- 1;
8889 if ( maxPos
>= numLines
)
8890 maxPos
= numLines
- 1;
8893 // check if the position is beyond the last column
8894 const int lineAtMaxPos
= oper
.GetLineAt(this, maxPos
);
8895 if ( coord
>= lineEnds
[lineAtMaxPos
] )
8896 return clipToMinMax
? maxPos
: -1;
8898 // or before the first one
8899 const int lineAt0
= oper
.GetLineAt(this, 0);
8900 if ( coord
< lineEnds
[lineAt0
] )
8904 // finally do perform the binary search
8905 while ( minPos
< maxPos
)
8907 wxCHECK_MSG( lineEnds
[oper
.GetLineAt(this, minPos
)] <= coord
&&
8908 coord
< lineEnds
[oper
.GetLineAt(this, maxPos
)],
8910 "wxGrid: internal error in PosToLinePos()" );
8912 if ( coord
>= lineEnds
[oper
.GetLineAt(this, maxPos
- 1)] )
8917 const int median
= minPos
+ (maxPos
- minPos
+ 1) / 2;
8918 if ( coord
< lineEnds
[oper
.GetLineAt(this, median
)] )
8928 wxGrid::PosToLine(int coord
,
8930 const wxGridOperations
& oper
) const
8932 int pos
= PosToLinePos(coord
, clipToMinMax
, oper
);
8934 return pos
== wxNOT_FOUND
? wxNOT_FOUND
: oper
.GetLineAt(this, pos
);
8937 int wxGrid::YToRow(int y
, bool clipToMinMax
) const
8939 return PosToLine(y
, clipToMinMax
, wxGridRowOperations());
8942 int wxGrid::XToCol(int x
, bool clipToMinMax
) const
8944 return PosToLine(x
, clipToMinMax
, wxGridColumnOperations());
8947 int wxGrid::XToPos(int x
) const
8949 return PosToLinePos(x
, true /* clip */, wxGridColumnOperations());
8952 // return the row number that that the y coord is near the edge of, or -1 if
8953 // not near an edge.
8955 // coords can only possibly be near an edge if
8956 // (a) the row/column is large enough to still allow for an "inner" area
8957 // that is _not_ near the edge (i.e., if the height/width is smaller
8958 // than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be
8961 // (b) resizing rows/columns (the thing for which edge detection is
8962 // relevant at all) is enabled.
8964 int wxGrid::PosToEdgeOfLine(int pos
, const wxGridOperations
& oper
) const
8966 if ( !oper
.CanResizeLines(this) )
8969 const int line
= oper
.PosToLine(this, pos
, true);
8971 if ( oper
.GetLineSize(this, line
) > WXGRID_LABEL_EDGE_ZONE
)
8973 // We know that we are in this line, test whether we are close enough
8974 // to start or end border, respectively.
8975 if ( abs(oper
.GetLineEndPos(this, line
) - pos
) < WXGRID_LABEL_EDGE_ZONE
)
8977 else if ( line
> 0 &&
8978 pos
- oper
.GetLineStartPos(this,
8979 line
) < WXGRID_LABEL_EDGE_ZONE
)
8986 int wxGrid::YToEdgeOfRow(int y
) const
8988 return PosToEdgeOfLine(y
, wxGridRowOperations());
8991 int wxGrid::XToEdgeOfCol(int x
) const
8993 return PosToEdgeOfLine(x
, wxGridColumnOperations());
8996 wxRect
wxGrid::CellToRect( int row
, int col
) const
8998 wxRect
rect( -1, -1, -1, -1 );
9000 if ( row
>= 0 && row
< m_numRows
&&
9001 col
>= 0 && col
< m_numCols
)
9003 int i
, cell_rows
, cell_cols
;
9004 rect
.width
= rect
.height
= 0;
9005 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
9006 // if negative then find multicell owner
9011 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
9013 rect
.x
= GetColLeft(col
);
9014 rect
.y
= GetRowTop(row
);
9015 for (i
=col
; i
< col
+ cell_cols
; i
++)
9016 rect
.width
+= GetColWidth(i
);
9017 for (i
=row
; i
< row
+ cell_rows
; i
++)
9018 rect
.height
+= GetRowHeight(i
);
9021 // if grid lines are enabled, then the area of the cell is a bit smaller
9022 if (m_gridLinesEnabled
)
9031 bool wxGrid::IsVisible( int row
, int col
, bool wholeCellVisible
) const
9033 // get the cell rectangle in logical coords
9035 wxRect
r( CellToRect( row
, col
) );
9037 // convert to device coords
9039 int left
, top
, right
, bottom
;
9040 CalcScrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
9041 CalcScrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
9043 // check against the client area of the grid window
9045 m_gridWin
->GetClientSize( &cw
, &ch
);
9047 if ( wholeCellVisible
)
9049 // is the cell wholly visible ?
9050 return ( left
>= 0 && right
<= cw
&&
9051 top
>= 0 && bottom
<= ch
);
9055 // is the cell partly visible ?
9057 return ( ((left
>= 0 && left
< cw
) || (right
> 0 && right
<= cw
)) &&
9058 ((top
>= 0 && top
< ch
) || (bottom
> 0 && bottom
<= ch
)) );
9062 // make the specified cell location visible by doing a minimal amount
9065 void wxGrid::MakeCellVisible( int row
, int col
)
9068 int xpos
= -1, ypos
= -1;
9070 if ( row
>= 0 && row
< m_numRows
&&
9071 col
>= 0 && col
< m_numCols
)
9073 // get the cell rectangle in logical coords
9074 wxRect
r( CellToRect( row
, col
) );
9076 // convert to device coords
9077 int left
, top
, right
, bottom
;
9078 CalcScrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
9079 CalcScrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
9082 m_gridWin
->GetClientSize( &cw
, &ch
);
9088 else if ( bottom
> ch
)
9090 int h
= r
.GetHeight();
9092 for ( i
= row
- 1; i
>= 0; i
-- )
9094 int rowHeight
= GetRowHeight(i
);
9095 if ( h
+ rowHeight
> ch
)
9102 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
9103 // have rounding errors (this is important, because if we do,
9104 // we might not scroll at all and some cells won't be redrawn)
9106 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
9107 // so just add a full scroll unit...
9108 ypos
+= m_scrollLineY
;
9111 // special handling for wide cells - show always left part of the cell!
9112 // Otherwise, e.g. when stepping from row to row, it would jump between
9113 // left and right part of the cell on every step!
9115 if ( left
< 0 || (right
- left
) >= cw
)
9119 else if ( right
> cw
)
9121 // position the view so that the cell is on the right
9123 CalcUnscrolledPosition(0, 0, &x0
, &y0
);
9124 xpos
= x0
+ (right
- cw
);
9126 // see comment for ypos above
9127 xpos
+= m_scrollLineX
;
9130 if ( xpos
!= -1 || ypos
!= -1 )
9133 xpos
/= m_scrollLineX
;
9135 ypos
/= m_scrollLineY
;
9136 Scroll( xpos
, ypos
);
9143 // ------ Grid cursor movement functions
9147 wxGrid::DoMoveCursor(bool expandSelection
,
9148 const wxGridDirectionOperations
& diroper
)
9150 if ( m_currentCellCoords
== wxGridNoCellCoords
)
9153 if ( expandSelection
)
9155 wxGridCellCoords coords
= m_selectedBlockCorner
;
9156 if ( coords
== wxGridNoCellCoords
)
9157 coords
= m_currentCellCoords
;
9159 if ( diroper
.IsAtBoundary(coords
) )
9162 diroper
.Advance(coords
);
9164 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
9166 else // don't expand selection
9170 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9173 wxGridCellCoords coords
= m_currentCellCoords
;
9174 diroper
.Advance(coords
);
9182 bool wxGrid::MoveCursorUp(bool expandSelection
)
9184 return DoMoveCursor(expandSelection
,
9185 wxGridBackwardOperations(this, wxGridRowOperations()));
9188 bool wxGrid::MoveCursorDown(bool expandSelection
)
9190 return DoMoveCursor(expandSelection
,
9191 wxGridForwardOperations(this, wxGridRowOperations()));
9194 bool wxGrid::MoveCursorLeft(bool expandSelection
)
9196 return DoMoveCursor(expandSelection
,
9197 wxGridBackwardOperations(this, wxGridColumnOperations()));
9200 bool wxGrid::MoveCursorRight(bool expandSelection
)
9202 return DoMoveCursor(expandSelection
,
9203 wxGridForwardOperations(this, wxGridColumnOperations()));
9206 bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations
& diroper
)
9208 if ( m_currentCellCoords
== wxGridNoCellCoords
)
9211 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9214 const int oldRow
= m_currentCellCoords
.GetRow();
9215 int newRow
= diroper
.MoveByPixelDistance(oldRow
, m_gridWin
->GetClientSize().y
);
9216 if ( newRow
== oldRow
)
9218 wxGridCellCoords
coords(m_currentCellCoords
);
9219 diroper
.Advance(coords
);
9220 newRow
= coords
.GetRow();
9223 GoToCell(newRow
, m_currentCellCoords
.GetCol());
9228 bool wxGrid::MovePageUp()
9230 return DoMoveCursorByPage(
9231 wxGridBackwardOperations(this, wxGridRowOperations()));
9234 bool wxGrid::MovePageDown()
9236 return DoMoveCursorByPage(
9237 wxGridForwardOperations(this, wxGridRowOperations()));
9240 // helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
9241 // until we find a non-empty cell or reach the grid end
9243 wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords
& coords
,
9244 const wxGridDirectionOperations
& diroper
)
9246 while ( !diroper
.IsAtBoundary(coords
) )
9248 diroper
.Advance(coords
);
9249 if ( !m_table
->IsEmpty(coords
) )
9255 wxGrid::DoMoveCursorByBlock(bool expandSelection
,
9256 const wxGridDirectionOperations
& diroper
)
9258 if ( !m_table
|| m_currentCellCoords
== wxGridNoCellCoords
)
9261 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9264 wxGridCellCoords
coords(m_currentCellCoords
);
9265 if ( m_table
->IsEmpty(coords
) )
9267 // we are in an empty cell: find the next block of non-empty cells
9268 AdvanceToNextNonEmpty(coords
, diroper
);
9270 else // current cell is not empty
9272 diroper
.Advance(coords
);
9273 if ( m_table
->IsEmpty(coords
) )
9275 // we started at the end of a block, find the next one
9276 AdvanceToNextNonEmpty(coords
, diroper
);
9278 else // we're in a middle of a block
9280 // go to the end of it, i.e. find the last cell before the next
9282 while ( !diroper
.IsAtBoundary(coords
) )
9284 wxGridCellCoords
coordsNext(coords
);
9285 diroper
.Advance(coordsNext
);
9286 if ( m_table
->IsEmpty(coordsNext
) )
9289 coords
= coordsNext
;
9294 if ( expandSelection
)
9296 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
9307 bool wxGrid::MoveCursorUpBlock(bool expandSelection
)
9309 return DoMoveCursorByBlock(
9311 wxGridBackwardOperations(this, wxGridRowOperations())
9315 bool wxGrid::MoveCursorDownBlock( bool expandSelection
)
9317 return DoMoveCursorByBlock(
9319 wxGridForwardOperations(this, wxGridRowOperations())
9323 bool wxGrid::MoveCursorLeftBlock( bool expandSelection
)
9325 return DoMoveCursorByBlock(
9327 wxGridBackwardOperations(this, wxGridColumnOperations())
9331 bool wxGrid::MoveCursorRightBlock( bool expandSelection
)
9333 return DoMoveCursorByBlock(
9335 wxGridForwardOperations(this, wxGridColumnOperations())
9340 // ------ Label values and formatting
9343 void wxGrid::GetRowLabelAlignment( int *horiz
, int *vert
) const
9346 *horiz
= m_rowLabelHorizAlign
;
9348 *vert
= m_rowLabelVertAlign
;
9351 void wxGrid::GetColLabelAlignment( int *horiz
, int *vert
) const
9354 *horiz
= m_colLabelHorizAlign
;
9356 *vert
= m_colLabelVertAlign
;
9359 int wxGrid::GetColLabelTextOrientation() const
9361 return m_colLabelTextOrientation
;
9364 wxString
wxGrid::GetRowLabelValue( int row
) const
9368 return m_table
->GetRowLabelValue( row
);
9378 wxString
wxGrid::GetColLabelValue( int col
) const
9382 return m_table
->GetColLabelValue( col
);
9392 void wxGrid::SetRowLabelSize( int width
)
9394 wxASSERT( width
>= 0 || width
== wxGRID_AUTOSIZE
);
9396 if ( width
== wxGRID_AUTOSIZE
)
9398 width
= CalcColOrRowLabelAreaMinSize(wxGRID_ROW
);
9401 if ( width
!= m_rowLabelWidth
)
9405 m_rowLabelWin
->Show( false );
9406 m_cornerLabelWin
->Show( false );
9408 else if ( m_rowLabelWidth
== 0 )
9410 m_rowLabelWin
->Show( true );
9411 if ( m_colLabelHeight
> 0 )
9412 m_cornerLabelWin
->Show( true );
9415 m_rowLabelWidth
= width
;
9417 wxScrolledWindow::Refresh( true );
9421 void wxGrid::SetColLabelSize( int height
)
9423 wxASSERT( height
>=0 || height
== wxGRID_AUTOSIZE
);
9425 if ( height
== wxGRID_AUTOSIZE
)
9427 height
= CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN
);
9430 if ( height
!= m_colLabelHeight
)
9434 m_colWindow
->Show( false );
9435 m_cornerLabelWin
->Show( false );
9437 else if ( m_colLabelHeight
== 0 )
9439 m_colWindow
->Show( true );
9440 if ( m_rowLabelWidth
> 0 )
9441 m_cornerLabelWin
->Show( true );
9444 m_colLabelHeight
= height
;
9446 wxScrolledWindow::Refresh( true );
9450 void wxGrid::SetLabelBackgroundColour( const wxColour
& colour
)
9452 if ( m_labelBackgroundColour
!= colour
)
9454 m_labelBackgroundColour
= colour
;
9455 m_rowLabelWin
->SetBackgroundColour( colour
);
9456 m_colWindow
->SetBackgroundColour( colour
);
9457 m_cornerLabelWin
->SetBackgroundColour( colour
);
9459 if ( !GetBatchCount() )
9461 m_rowLabelWin
->Refresh();
9462 m_colWindow
->Refresh();
9463 m_cornerLabelWin
->Refresh();
9468 void wxGrid::SetLabelTextColour( const wxColour
& colour
)
9470 if ( m_labelTextColour
!= colour
)
9472 m_labelTextColour
= colour
;
9473 if ( !GetBatchCount() )
9475 m_rowLabelWin
->Refresh();
9476 m_colWindow
->Refresh();
9481 void wxGrid::SetLabelFont( const wxFont
& font
)
9484 if ( !GetBatchCount() )
9486 m_rowLabelWin
->Refresh();
9487 m_colWindow
->Refresh();
9491 void wxGrid::SetRowLabelAlignment( int horiz
, int vert
)
9493 // allow old (incorrect) defs to be used
9496 case wxLEFT
: horiz
= wxALIGN_LEFT
; break;
9497 case wxRIGHT
: horiz
= wxALIGN_RIGHT
; break;
9498 case wxCENTRE
: horiz
= wxALIGN_CENTRE
; break;
9503 case wxTOP
: vert
= wxALIGN_TOP
; break;
9504 case wxBOTTOM
: vert
= wxALIGN_BOTTOM
; break;
9505 case wxCENTRE
: vert
= wxALIGN_CENTRE
; break;
9508 if ( horiz
== wxALIGN_LEFT
|| horiz
== wxALIGN_CENTRE
|| horiz
== wxALIGN_RIGHT
)
9510 m_rowLabelHorizAlign
= horiz
;
9513 if ( vert
== wxALIGN_TOP
|| vert
== wxALIGN_CENTRE
|| vert
== wxALIGN_BOTTOM
)
9515 m_rowLabelVertAlign
= vert
;
9518 if ( !GetBatchCount() )
9520 m_rowLabelWin
->Refresh();
9524 void wxGrid::SetColLabelAlignment( int horiz
, int vert
)
9526 // allow old (incorrect) defs to be used
9529 case wxLEFT
: horiz
= wxALIGN_LEFT
; break;
9530 case wxRIGHT
: horiz
= wxALIGN_RIGHT
; break;
9531 case wxCENTRE
: horiz
= wxALIGN_CENTRE
; break;
9536 case wxTOP
: vert
= wxALIGN_TOP
; break;
9537 case wxBOTTOM
: vert
= wxALIGN_BOTTOM
; break;
9538 case wxCENTRE
: vert
= wxALIGN_CENTRE
; break;
9541 if ( horiz
== wxALIGN_LEFT
|| horiz
== wxALIGN_CENTRE
|| horiz
== wxALIGN_RIGHT
)
9543 m_colLabelHorizAlign
= horiz
;
9546 if ( vert
== wxALIGN_TOP
|| vert
== wxALIGN_CENTRE
|| vert
== wxALIGN_BOTTOM
)
9548 m_colLabelVertAlign
= vert
;
9551 if ( !GetBatchCount() )
9553 m_colWindow
->Refresh();
9557 // Note: under MSW, the default column label font must be changed because it
9558 // does not support vertical printing
9560 // Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
9561 // pGrid->SetLabelFont(font);
9562 // pGrid->SetColLabelTextOrientation(wxVERTICAL);
9564 void wxGrid::SetColLabelTextOrientation( int textOrientation
)
9566 if ( textOrientation
== wxHORIZONTAL
|| textOrientation
== wxVERTICAL
)
9567 m_colLabelTextOrientation
= textOrientation
;
9569 if ( !GetBatchCount() )
9570 m_colWindow
->Refresh();
9573 void wxGrid::SetRowLabelValue( int row
, const wxString
& s
)
9577 m_table
->SetRowLabelValue( row
, s
);
9578 if ( !GetBatchCount() )
9580 wxRect rect
= CellToRect( row
, 0 );
9581 if ( rect
.height
> 0 )
9583 CalcScrolledPosition(0, rect
.y
, &rect
.x
, &rect
.y
);
9585 rect
.width
= m_rowLabelWidth
;
9586 m_rowLabelWin
->Refresh( true, &rect
);
9592 void wxGrid::SetColLabelValue( int col
, const wxString
& s
)
9596 m_table
->SetColLabelValue( col
, s
);
9597 if ( !GetBatchCount() )
9599 if ( m_useNativeHeader
)
9601 GetGridColHeader()->UpdateColumn(col
);
9605 wxRect rect
= CellToRect( 0, col
);
9606 if ( rect
.width
> 0 )
9608 CalcScrolledPosition(rect
.x
, 0, &rect
.x
, &rect
.y
);
9610 rect
.height
= m_colLabelHeight
;
9611 GetColLabelWindow()->Refresh( true, &rect
);
9618 void wxGrid::SetGridLineColour( const wxColour
& colour
)
9620 if ( m_gridLineColour
!= colour
)
9622 m_gridLineColour
= colour
;
9624 if ( GridLinesEnabled() )
9629 void wxGrid::SetCellHighlightColour( const wxColour
& colour
)
9631 if ( m_cellHighlightColour
!= colour
)
9633 m_cellHighlightColour
= colour
;
9635 wxClientDC
dc( m_gridWin
);
9637 wxGridCellAttr
* attr
= GetCellAttr(m_currentCellCoords
);
9638 DrawCellHighlight(dc
, attr
);
9643 void wxGrid::SetCellHighlightPenWidth(int width
)
9645 if (m_cellHighlightPenWidth
!= width
)
9647 m_cellHighlightPenWidth
= width
;
9649 // Just redrawing the cell highlight is not enough since that won't
9650 // make any visible change if the the thickness is getting smaller.
9651 int row
= m_currentCellCoords
.GetRow();
9652 int col
= m_currentCellCoords
.GetCol();
9653 if ( row
== -1 || col
== -1 || GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
9656 wxRect rect
= CellToRect(row
, col
);
9657 m_gridWin
->Refresh(true, &rect
);
9661 void wxGrid::SetCellHighlightROPenWidth(int width
)
9663 if (m_cellHighlightROPenWidth
!= width
)
9665 m_cellHighlightROPenWidth
= width
;
9667 // Just redrawing the cell highlight is not enough since that won't
9668 // make any visible change if the the thickness is getting smaller.
9669 int row
= m_currentCellCoords
.GetRow();
9670 int col
= m_currentCellCoords
.GetCol();
9671 if ( row
== -1 || col
== -1 ||
9672 GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
9675 wxRect rect
= CellToRect(row
, col
);
9676 m_gridWin
->Refresh(true, &rect
);
9680 void wxGrid::RedrawGridLines()
9682 // the lines will be redrawn when the window is thawn
9683 if ( GetBatchCount() )
9686 if ( GridLinesEnabled() )
9688 wxClientDC
dc( m_gridWin
);
9690 DrawAllGridLines( dc
, wxRegion() );
9692 else // remove the grid lines
9694 m_gridWin
->Refresh();
9698 void wxGrid::EnableGridLines( bool enable
)
9700 if ( enable
!= m_gridLinesEnabled
)
9702 m_gridLinesEnabled
= enable
;
9708 void wxGrid::DoClipGridLines(bool& var
, bool clip
)
9714 if ( GridLinesEnabled() )
9719 int wxGrid::GetDefaultRowSize() const
9721 return m_defaultRowHeight
;
9724 int wxGrid::GetRowSize( int row
) const
9726 wxCHECK_MSG( row
>= 0 && row
< m_numRows
, 0, _T("invalid row index") );
9728 return GetRowHeight(row
);
9731 int wxGrid::GetDefaultColSize() const
9733 return m_defaultColWidth
;
9736 int wxGrid::GetColSize( int col
) const
9738 wxCHECK_MSG( col
>= 0 && col
< m_numCols
, 0, _T("invalid column index") );
9740 return GetColWidth(col
);
9743 // ============================================================================
9744 // access to the grid attributes: each of them has a default value in the grid
9745 // itself and may be overidden on a per-cell basis
9746 // ============================================================================
9748 // ----------------------------------------------------------------------------
9749 // setting default attributes
9750 // ----------------------------------------------------------------------------
9752 void wxGrid::SetDefaultCellBackgroundColour( const wxColour
& col
)
9754 m_defaultCellAttr
->SetBackgroundColour(col
);
9756 m_gridWin
->SetBackgroundColour(col
);
9760 void wxGrid::SetDefaultCellTextColour( const wxColour
& col
)
9762 m_defaultCellAttr
->SetTextColour(col
);
9765 void wxGrid::SetDefaultCellAlignment( int horiz
, int vert
)
9767 m_defaultCellAttr
->SetAlignment(horiz
, vert
);
9770 void wxGrid::SetDefaultCellOverflow( bool allow
)
9772 m_defaultCellAttr
->SetOverflow(allow
);
9775 void wxGrid::SetDefaultCellFont( const wxFont
& font
)
9777 m_defaultCellAttr
->SetFont(font
);
9780 // For editors and renderers the type registry takes precedence over the
9781 // default attr, so we need to register the new editor/renderer for the string
9782 // data type in order to make setting a default editor/renderer appear to
9785 void wxGrid::SetDefaultRenderer(wxGridCellRenderer
*renderer
)
9787 RegisterDataType(wxGRID_VALUE_STRING
,
9789 GetDefaultEditorForType(wxGRID_VALUE_STRING
));
9792 void wxGrid::SetDefaultEditor(wxGridCellEditor
*editor
)
9794 RegisterDataType(wxGRID_VALUE_STRING
,
9795 GetDefaultRendererForType(wxGRID_VALUE_STRING
),
9799 // ----------------------------------------------------------------------------
9800 // access to the default attributes
9801 // ----------------------------------------------------------------------------
9803 wxColour
wxGrid::GetDefaultCellBackgroundColour() const
9805 return m_defaultCellAttr
->GetBackgroundColour();
9808 wxColour
wxGrid::GetDefaultCellTextColour() const
9810 return m_defaultCellAttr
->GetTextColour();
9813 wxFont
wxGrid::GetDefaultCellFont() const
9815 return m_defaultCellAttr
->GetFont();
9818 void wxGrid::GetDefaultCellAlignment( int *horiz
, int *vert
) const
9820 m_defaultCellAttr
->GetAlignment(horiz
, vert
);
9823 bool wxGrid::GetDefaultCellOverflow() const
9825 return m_defaultCellAttr
->GetOverflow();
9828 wxGridCellRenderer
*wxGrid::GetDefaultRenderer() const
9830 return m_defaultCellAttr
->GetRenderer(NULL
, 0, 0);
9833 wxGridCellEditor
*wxGrid::GetDefaultEditor() const
9835 return m_defaultCellAttr
->GetEditor(NULL
, 0, 0);
9838 // ----------------------------------------------------------------------------
9839 // access to cell attributes
9840 // ----------------------------------------------------------------------------
9842 wxColour
wxGrid::GetCellBackgroundColour(int row
, int col
) const
9844 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9845 wxColour colour
= attr
->GetBackgroundColour();
9851 wxColour
wxGrid::GetCellTextColour( int row
, int col
) const
9853 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9854 wxColour colour
= attr
->GetTextColour();
9860 wxFont
wxGrid::GetCellFont( int row
, int col
) const
9862 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9863 wxFont font
= attr
->GetFont();
9869 void wxGrid::GetCellAlignment( int row
, int col
, int *horiz
, int *vert
) const
9871 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9872 attr
->GetAlignment(horiz
, vert
);
9876 bool wxGrid::GetCellOverflow( int row
, int col
) const
9878 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9879 bool allow
= attr
->GetOverflow();
9885 void wxGrid::GetCellSize( int row
, int col
, int *num_rows
, int *num_cols
) const
9887 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9888 attr
->GetSize( num_rows
, num_cols
);
9892 wxGridCellRenderer
* wxGrid::GetCellRenderer(int row
, int col
) const
9894 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9895 wxGridCellRenderer
* renderer
= attr
->GetRenderer(this, row
, col
);
9901 wxGridCellEditor
* wxGrid::GetCellEditor(int row
, int col
) const
9903 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9904 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
9910 bool wxGrid::IsReadOnly(int row
, int col
) const
9912 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9913 bool isReadOnly
= attr
->IsReadOnly();
9919 // ----------------------------------------------------------------------------
9920 // attribute support: cache, automatic provider creation, ...
9921 // ----------------------------------------------------------------------------
9923 bool wxGrid::CanHaveAttributes() const
9930 return m_table
->CanHaveAttributes();
9933 void wxGrid::ClearAttrCache()
9935 if ( m_attrCache
.row
!= -1 )
9937 wxGridCellAttr
*oldAttr
= m_attrCache
.attr
;
9938 m_attrCache
.attr
= NULL
;
9939 m_attrCache
.row
= -1;
9940 // wxSafeDecRec(...) might cause event processing that accesses
9941 // the cached attribute, if one exists (e.g. by deleting the
9942 // editor stored within the attribute). Therefore it is important
9943 // to invalidate the cache before calling wxSafeDecRef!
9944 wxSafeDecRef(oldAttr
);
9948 void wxGrid::CacheAttr(int row
, int col
, wxGridCellAttr
*attr
) const
9952 wxGrid
*self
= (wxGrid
*)this; // const_cast
9954 self
->ClearAttrCache();
9955 self
->m_attrCache
.row
= row
;
9956 self
->m_attrCache
.col
= col
;
9957 self
->m_attrCache
.attr
= attr
;
9962 bool wxGrid::LookupAttr(int row
, int col
, wxGridCellAttr
**attr
) const
9964 if ( row
== m_attrCache
.row
&& col
== m_attrCache
.col
)
9966 *attr
= m_attrCache
.attr
;
9967 wxSafeIncRef(m_attrCache
.attr
);
9969 #ifdef DEBUG_ATTR_CACHE
9970 gs_nAttrCacheHits
++;
9977 #ifdef DEBUG_ATTR_CACHE
9978 gs_nAttrCacheMisses
++;
9985 wxGridCellAttr
*wxGrid::GetCellAttr(int row
, int col
) const
9987 wxGridCellAttr
*attr
= NULL
;
9988 // Additional test to avoid looking at the cache e.g. for
9989 // wxNoCellCoords, as this will confuse memory management.
9992 if ( !LookupAttr(row
, col
, &attr
) )
9994 attr
= m_table
? m_table
->GetAttr(row
, col
, wxGridCellAttr::Any
)
9996 CacheAttr(row
, col
, attr
);
10002 attr
->SetDefAttr(m_defaultCellAttr
);
10006 attr
= m_defaultCellAttr
;
10013 wxGridCellAttr
*wxGrid::GetOrCreateCellAttr(int row
, int col
) const
10015 wxGridCellAttr
*attr
= NULL
;
10016 bool canHave
= ((wxGrid
*)this)->CanHaveAttributes();
10018 wxCHECK_MSG( canHave
, attr
, _T("Cell attributes not allowed"));
10019 wxCHECK_MSG( m_table
, attr
, _T("must have a table") );
10021 attr
= m_table
->GetAttr(row
, col
, wxGridCellAttr::Cell
);
10024 attr
= new wxGridCellAttr(m_defaultCellAttr
);
10026 // artificially inc the ref count to match DecRef() in caller
10028 m_table
->SetAttr(attr
, row
, col
);
10034 // ----------------------------------------------------------------------------
10035 // setting column attributes (wrappers around SetColAttr)
10036 // ----------------------------------------------------------------------------
10038 void wxGrid::SetColFormatBool(int col
)
10040 SetColFormatCustom(col
, wxGRID_VALUE_BOOL
);
10043 void wxGrid::SetColFormatNumber(int col
)
10045 SetColFormatCustom(col
, wxGRID_VALUE_NUMBER
);
10048 void wxGrid::SetColFormatFloat(int col
, int width
, int precision
)
10050 wxString typeName
= wxGRID_VALUE_FLOAT
;
10051 if ( (width
!= -1) || (precision
!= -1) )
10053 typeName
<< _T(':') << width
<< _T(',') << precision
;
10056 SetColFormatCustom(col
, typeName
);
10059 void wxGrid::SetColFormatCustom(int col
, const wxString
& typeName
)
10061 wxGridCellAttr
*attr
= m_table
->GetAttr(-1, col
, wxGridCellAttr::Col
);
10063 attr
= new wxGridCellAttr
;
10064 wxGridCellRenderer
*renderer
= GetDefaultRendererForType(typeName
);
10065 attr
->SetRenderer(renderer
);
10066 wxGridCellEditor
*editor
= GetDefaultEditorForType(typeName
);
10067 attr
->SetEditor(editor
);
10069 SetColAttr(col
, attr
);
10073 // ----------------------------------------------------------------------------
10074 // setting cell attributes: this is forwarded to the table
10075 // ----------------------------------------------------------------------------
10077 void wxGrid::SetAttr(int row
, int col
, wxGridCellAttr
*attr
)
10079 if ( CanHaveAttributes() )
10081 m_table
->SetAttr(attr
, row
, col
);
10086 wxSafeDecRef(attr
);
10090 void wxGrid::SetRowAttr(int row
, wxGridCellAttr
*attr
)
10092 if ( CanHaveAttributes() )
10094 m_table
->SetRowAttr(attr
, row
);
10099 wxSafeDecRef(attr
);
10103 void wxGrid::SetColAttr(int col
, wxGridCellAttr
*attr
)
10105 if ( CanHaveAttributes() )
10107 m_table
->SetColAttr(attr
, col
);
10112 wxSafeDecRef(attr
);
10116 void wxGrid::SetCellBackgroundColour( int row
, int col
, const wxColour
& colour
)
10118 if ( CanHaveAttributes() )
10120 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10121 attr
->SetBackgroundColour(colour
);
10126 void wxGrid::SetCellTextColour( int row
, int col
, const wxColour
& colour
)
10128 if ( CanHaveAttributes() )
10130 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10131 attr
->SetTextColour(colour
);
10136 void wxGrid::SetCellFont( int row
, int col
, const wxFont
& font
)
10138 if ( CanHaveAttributes() )
10140 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10141 attr
->SetFont(font
);
10146 void wxGrid::SetCellAlignment( int row
, int col
, int horiz
, int vert
)
10148 if ( CanHaveAttributes() )
10150 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10151 attr
->SetAlignment(horiz
, vert
);
10156 void wxGrid::SetCellOverflow( int row
, int col
, bool allow
)
10158 if ( CanHaveAttributes() )
10160 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10161 attr
->SetOverflow(allow
);
10166 void wxGrid::SetCellSize( int row
, int col
, int num_rows
, int num_cols
)
10168 if ( CanHaveAttributes() )
10170 int cell_rows
, cell_cols
;
10172 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10173 attr
->GetSize(&cell_rows
, &cell_cols
);
10174 attr
->SetSize(num_rows
, num_cols
);
10177 // Cannot set the size of a cell to 0 or negative values
10178 // While it is perfectly legal to do that, this function cannot
10179 // handle all the possibilies, do it by hand by getting the CellAttr.
10180 // You can only set the size of a cell to 1,1 or greater with this fn
10181 wxASSERT_MSG( !((cell_rows
< 1) || (cell_cols
< 1)),
10182 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
10183 wxASSERT_MSG( !((num_rows
< 1) || (num_cols
< 1)),
10184 wxT("wxGrid::SetCellSize setting cell size to < 1"));
10186 // if this was already a multicell then "turn off" the other cells first
10187 if ((cell_rows
> 1) || (cell_cols
> 1))
10190 for (j
=row
; j
< row
+ cell_rows
; j
++)
10192 for (i
=col
; i
< col
+ cell_cols
; i
++)
10194 if ((i
!= col
) || (j
!= row
))
10196 wxGridCellAttr
*attr_stub
= GetOrCreateCellAttr(j
, i
);
10197 attr_stub
->SetSize( 1, 1 );
10198 attr_stub
->DecRef();
10204 // mark the cells that will be covered by this cell to
10205 // negative or zero values to point back at this cell
10206 if (((num_rows
> 1) || (num_cols
> 1)) && (num_rows
>= 1) && (num_cols
>= 1))
10209 for (j
=row
; j
< row
+ num_rows
; j
++)
10211 for (i
=col
; i
< col
+ num_cols
; i
++)
10213 if ((i
!= col
) || (j
!= row
))
10215 wxGridCellAttr
*attr_stub
= GetOrCreateCellAttr(j
, i
);
10216 attr_stub
->SetSize( row
- j
, col
- i
);
10217 attr_stub
->DecRef();
10225 void wxGrid::SetCellRenderer(int row
, int col
, wxGridCellRenderer
*renderer
)
10227 if ( CanHaveAttributes() )
10229 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10230 attr
->SetRenderer(renderer
);
10235 void wxGrid::SetCellEditor(int row
, int col
, wxGridCellEditor
* editor
)
10237 if ( CanHaveAttributes() )
10239 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10240 attr
->SetEditor(editor
);
10245 void wxGrid::SetReadOnly(int row
, int col
, bool isReadOnly
)
10247 if ( CanHaveAttributes() )
10249 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10250 attr
->SetReadOnly(isReadOnly
);
10255 // ----------------------------------------------------------------------------
10256 // Data type registration
10257 // ----------------------------------------------------------------------------
10259 void wxGrid::RegisterDataType(const wxString
& typeName
,
10260 wxGridCellRenderer
* renderer
,
10261 wxGridCellEditor
* editor
)
10263 m_typeRegistry
->RegisterDataType(typeName
, renderer
, editor
);
10267 wxGridCellEditor
* wxGrid::GetDefaultEditorForCell(int row
, int col
) const
10269 wxString typeName
= m_table
->GetTypeName(row
, col
);
10270 return GetDefaultEditorForType(typeName
);
10273 wxGridCellRenderer
* wxGrid::GetDefaultRendererForCell(int row
, int col
) const
10275 wxString typeName
= m_table
->GetTypeName(row
, col
);
10276 return GetDefaultRendererForType(typeName
);
10279 wxGridCellEditor
* wxGrid::GetDefaultEditorForType(const wxString
& typeName
) const
10281 int index
= m_typeRegistry
->FindOrCloneDataType(typeName
);
10282 if ( index
== wxNOT_FOUND
)
10284 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName
.c_str()));
10289 return m_typeRegistry
->GetEditor(index
);
10292 wxGridCellRenderer
* wxGrid::GetDefaultRendererForType(const wxString
& typeName
) const
10294 int index
= m_typeRegistry
->FindOrCloneDataType(typeName
);
10295 if ( index
== wxNOT_FOUND
)
10297 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName
.c_str()));
10302 return m_typeRegistry
->GetRenderer(index
);
10305 // ----------------------------------------------------------------------------
10307 // ----------------------------------------------------------------------------
10309 void wxGrid::EnableDragRowSize( bool enable
)
10311 m_canDragRowSize
= enable
;
10314 void wxGrid::EnableDragColSize( bool enable
)
10316 m_canDragColSize
= enable
;
10319 void wxGrid::EnableDragGridSize( bool enable
)
10321 m_canDragGridSize
= enable
;
10324 void wxGrid::EnableDragCell( bool enable
)
10326 m_canDragCell
= enable
;
10329 void wxGrid::SetDefaultRowSize( int height
, bool resizeExistingRows
)
10331 m_defaultRowHeight
= wxMax( height
, m_minAcceptableRowHeight
);
10333 if ( resizeExistingRows
)
10335 // since we are resizing all rows to the default row size,
10336 // we can simply clear the row heights and row bottoms
10337 // arrays (which also allows us to take advantage of
10338 // some speed optimisations)
10339 m_rowHeights
.Empty();
10340 m_rowBottoms
.Empty();
10341 if ( !GetBatchCount() )
10346 void wxGrid::SetRowSize( int row
, int height
)
10348 wxCHECK_RET( row
>= 0 && row
< m_numRows
, _T("invalid row index") );
10350 // if < 0 then calculate new height from label
10354 wxArrayString lines
;
10355 wxClientDC
dc(m_rowLabelWin
);
10356 dc
.SetFont(GetLabelFont());
10357 StringToLines(GetRowLabelValue( row
), lines
);
10358 GetTextBoxSize( dc
, lines
, &w
, &h
);
10359 //check that it is not less than the minimal height
10360 height
= wxMax(h
, GetRowMinimalAcceptableHeight());
10363 // See comment in SetColSize
10364 if ( height
< GetRowMinimalAcceptableHeight())
10367 if ( m_rowHeights
.IsEmpty() )
10369 // need to really create the array
10373 int h
= wxMax( 0, height
);
10374 int diff
= h
- m_rowHeights
[row
];
10376 m_rowHeights
[row
] = h
;
10377 for ( int i
= row
; i
< m_numRows
; i
++ )
10379 m_rowBottoms
[i
] += diff
;
10382 if ( !GetBatchCount() )
10386 void wxGrid::SetDefaultColSize( int width
, bool resizeExistingCols
)
10388 // we dont allow zero default column width
10389 m_defaultColWidth
= wxMax( wxMax( width
, m_minAcceptableColWidth
), 1 );
10391 if ( resizeExistingCols
)
10393 // since we are resizing all columns to the default column size,
10394 // we can simply clear the col widths and col rights
10395 // arrays (which also allows us to take advantage of
10396 // some speed optimisations)
10397 m_colWidths
.Empty();
10398 m_colRights
.Empty();
10399 if ( !GetBatchCount() )
10404 void wxGrid::SetColSize( int col
, int width
)
10406 wxCHECK_RET( col
>= 0 && col
< m_numCols
, _T("invalid column index") );
10408 // if < 0 then calculate new width from label
10412 wxArrayString lines
;
10413 wxClientDC
dc(m_colWindow
);
10414 dc
.SetFont(GetLabelFont());
10415 StringToLines(GetColLabelValue(col
), lines
);
10416 if ( GetColLabelTextOrientation() == wxHORIZONTAL
)
10417 GetTextBoxSize( dc
, lines
, &w
, &h
);
10419 GetTextBoxSize( dc
, lines
, &h
, &w
);
10421 //check that it is not less than the minimal width
10422 width
= wxMax(width
, GetColMinimalAcceptableWidth());
10425 // we intentionally don't test whether the width is less than
10426 // GetColMinimalWidth() here but we do compare it with
10427 // GetColMinimalAcceptableWidth() as otherwise things currently break (see
10428 // #651) -- and we also always allow the width of 0 as it has the special
10429 // sense of hiding the column
10430 if ( width
> 0 && width
< GetColMinimalAcceptableWidth() )
10433 if ( m_colWidths
.IsEmpty() )
10435 // need to really create the array
10439 const int diff
= width
- m_colWidths
[col
];
10440 m_colWidths
[col
] = width
;
10441 if ( m_useNativeHeader
)
10442 GetGridColHeader()->UpdateColumn(col
);
10443 //else: will be refreshed when the header is redrawn
10445 for ( int colPos
= GetColPos(col
); colPos
< m_numCols
; colPos
++ )
10447 m_colRights
[GetColAt(colPos
)] += diff
;
10450 if ( !GetBatchCount() )
10457 void wxGrid::SetColMinimalWidth( int col
, int width
)
10459 if (width
> GetColMinimalAcceptableWidth())
10461 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)col
;
10462 m_colMinWidths
[key
] = width
;
10466 void wxGrid::SetRowMinimalHeight( int row
, int width
)
10468 if (width
> GetRowMinimalAcceptableHeight())
10470 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)row
;
10471 m_rowMinHeights
[key
] = width
;
10475 int wxGrid::GetColMinimalWidth(int col
) const
10477 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)col
;
10478 wxLongToLongHashMap::const_iterator it
= m_colMinWidths
.find(key
);
10480 return it
!= m_colMinWidths
.end() ? (int)it
->second
: m_minAcceptableColWidth
;
10483 int wxGrid::GetRowMinimalHeight(int row
) const
10485 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)row
;
10486 wxLongToLongHashMap::const_iterator it
= m_rowMinHeights
.find(key
);
10488 return it
!= m_rowMinHeights
.end() ? (int)it
->second
: m_minAcceptableRowHeight
;
10491 void wxGrid::SetColMinimalAcceptableWidth( int width
)
10493 // We do allow a width of 0 since this gives us
10494 // an easy way to temporarily hiding columns.
10496 m_minAcceptableColWidth
= width
;
10499 void wxGrid::SetRowMinimalAcceptableHeight( int height
)
10501 // We do allow a height of 0 since this gives us
10502 // an easy way to temporarily hiding rows.
10504 m_minAcceptableRowHeight
= height
;
10507 int wxGrid::GetColMinimalAcceptableWidth() const
10509 return m_minAcceptableColWidth
;
10512 int wxGrid::GetRowMinimalAcceptableHeight() const
10514 return m_minAcceptableRowHeight
;
10517 // ----------------------------------------------------------------------------
10519 // ----------------------------------------------------------------------------
10522 wxGrid::AutoSizeColOrRow(int colOrRow
, bool setAsMin
, wxGridDirection direction
)
10524 const bool column
= direction
== wxGRID_COLUMN
;
10526 wxClientDC
dc(m_gridWin
);
10528 // cancel editing of cell
10529 HideCellEditControl();
10530 SaveEditControlValue();
10532 // init both of them to avoid compiler warnings, even if we only need one
10540 wxCoord extent
, extentMax
= 0;
10541 int max
= column
? m_numRows
: m_numCols
;
10542 for ( int rowOrCol
= 0; rowOrCol
< max
; rowOrCol
++ )
10549 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
10550 wxGridCellRenderer
*renderer
= attr
->GetRenderer(this, row
, col
);
10553 wxSize size
= renderer
->GetBestSize(*this, *attr
, dc
, row
, col
);
10554 extent
= column
? size
.x
: size
.y
;
10555 if ( extent
> extentMax
)
10556 extentMax
= extent
;
10558 renderer
->DecRef();
10564 // now also compare with the column label extent
10566 dc
.SetFont( GetLabelFont() );
10570 dc
.GetMultiLineTextExtent( GetColLabelValue(col
), &w
, &h
);
10571 if ( GetColLabelTextOrientation() == wxVERTICAL
)
10575 dc
.GetMultiLineTextExtent( GetRowLabelValue(row
), &w
, &h
);
10577 extent
= column
? w
: h
;
10578 if ( extent
> extentMax
)
10579 extentMax
= extent
;
10583 // empty column - give default extent (notice that if extentMax is less
10584 // than default extent but != 0, it's OK)
10585 extentMax
= column
? m_defaultColWidth
: m_defaultRowHeight
;
10590 // leave some space around text
10598 // Ensure automatic width is not less than minimal width. See the
10599 // comment in SetColSize() for explanation of why this isn't done
10600 // in SetColSize().
10602 extentMax
= wxMax(extentMax
, GetColMinimalWidth(col
));
10604 SetColSize( col
, extentMax
);
10605 if ( !GetBatchCount() )
10607 if ( m_useNativeHeader
)
10609 GetGridColHeader()->UpdateColumn(col
);
10614 m_gridWin
->GetClientSize( &cw
, &ch
);
10615 wxRect
rect ( CellToRect( 0, col
) );
10617 CalcScrolledPosition(rect
.x
, 0, &rect
.x
, &dummy
);
10618 rect
.width
= cw
- rect
.x
;
10619 rect
.height
= m_colLabelHeight
;
10620 GetColLabelWindow()->Refresh( true, &rect
);
10626 // Ensure automatic width is not less than minimal height. See the
10627 // comment in SetColSize() for explanation of why this isn't done
10628 // in SetRowSize().
10630 extentMax
= wxMax(extentMax
, GetRowMinimalHeight(row
));
10632 SetRowSize(row
, extentMax
);
10633 if ( !GetBatchCount() )
10636 m_gridWin
->GetClientSize( &cw
, &ch
);
10637 wxRect
rect( CellToRect( row
, 0 ) );
10639 CalcScrolledPosition(0, rect
.y
, &dummy
, &rect
.y
);
10640 rect
.width
= m_rowLabelWidth
;
10641 rect
.height
= ch
- rect
.y
;
10642 m_rowLabelWin
->Refresh( true, &rect
);
10649 SetColMinimalWidth(col
, extentMax
);
10651 SetRowMinimalHeight(row
, extentMax
);
10655 wxCoord
wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction
)
10657 // calculate size for the rows or columns?
10658 const bool calcRows
= direction
== wxGRID_ROW
;
10660 wxClientDC
dc(calcRows
? GetGridRowLabelWindow()
10661 : GetGridColLabelWindow());
10662 dc
.SetFont(GetLabelFont());
10664 // which dimension should we take into account for calculations?
10666 // for columns, the text can be only horizontal so it's easy but for rows
10667 // we also have to take into account the text orientation
10669 useWidth
= calcRows
|| (GetColLabelTextOrientation() == wxVERTICAL
);
10671 wxArrayString lines
;
10672 wxCoord extentMax
= 0;
10674 const int numRowsOrCols
= calcRows
? m_numRows
: m_numCols
;
10675 for ( int rowOrCol
= 0; rowOrCol
< numRowsOrCols
; rowOrCol
++ )
10679 wxString label
= calcRows
? GetRowLabelValue(rowOrCol
)
10680 : GetColLabelValue(rowOrCol
);
10681 StringToLines(label
, lines
);
10684 GetTextBoxSize(dc
, lines
, &w
, &h
);
10686 const wxCoord extent
= useWidth
? w
: h
;
10687 if ( extent
> extentMax
)
10688 extentMax
= extent
;
10693 // empty column - give default extent (notice that if extentMax is less
10694 // than default extent but != 0, it's OK)
10695 extentMax
= calcRows
? GetDefaultRowLabelSize()
10696 : GetDefaultColLabelSize();
10699 // leave some space around text (taken from AutoSizeColOrRow)
10708 int wxGrid::SetOrCalcColumnSizes(bool calcOnly
, bool setAsMin
)
10710 int width
= m_rowLabelWidth
;
10712 wxGridUpdateLocker locker
;
10714 locker
.Create(this);
10716 for ( int col
= 0; col
< m_numCols
; col
++ )
10719 AutoSizeColumn(col
, setAsMin
);
10721 width
+= GetColWidth(col
);
10727 int wxGrid::SetOrCalcRowSizes(bool calcOnly
, bool setAsMin
)
10729 int height
= m_colLabelHeight
;
10731 wxGridUpdateLocker locker
;
10733 locker
.Create(this);
10735 for ( int row
= 0; row
< m_numRows
; row
++ )
10738 AutoSizeRow(row
, setAsMin
);
10740 height
+= GetRowHeight(row
);
10746 void wxGrid::AutoSize()
10748 wxGridUpdateLocker
locker(this);
10750 wxSize
size(SetOrCalcColumnSizes(false) - m_rowLabelWidth
+ m_extraWidth
,
10751 SetOrCalcRowSizes(false) - m_colLabelHeight
+ m_extraHeight
);
10753 // we know that we're not going to have scrollbars so disable them now to
10754 // avoid trouble in SetClientSize() which can otherwise set the correct
10755 // client size but also leave space for (not needed any more) scrollbars
10756 SetScrollbars(0, 0, 0, 0, 0, 0, true);
10758 // restore the scroll rate parameters overwritten by SetScrollbars()
10759 SetScrollRate(m_scrollLineX
, m_scrollLineY
);
10761 SetClientSize(size
.x
+ m_rowLabelWidth
, size
.y
+ m_colLabelHeight
);
10764 void wxGrid::AutoSizeRowLabelSize( int row
)
10766 // Hide the edit control, so it
10767 // won't interfere with drag-shrinking.
10768 if ( IsCellEditControlShown() )
10770 HideCellEditControl();
10771 SaveEditControlValue();
10774 // autosize row height depending on label text
10775 SetRowSize(row
, -1);
10779 void wxGrid::AutoSizeColLabelSize( int col
)
10781 // Hide the edit control, so it
10782 // won't interfere with drag-shrinking.
10783 if ( IsCellEditControlShown() )
10785 HideCellEditControl();
10786 SaveEditControlValue();
10789 // autosize column width depending on label text
10790 SetColSize(col
, -1);
10794 wxSize
wxGrid::DoGetBestSize() const
10796 wxGrid
*self
= (wxGrid
*)this; // const_cast
10798 // we do the same as in AutoSize() here with the exception that we don't
10799 // change the column/row sizes, only calculate them
10800 wxSize
size(self
->SetOrCalcColumnSizes(true) - m_rowLabelWidth
+ m_extraWidth
,
10801 self
->SetOrCalcRowSizes(true) - m_colLabelHeight
+ m_extraHeight
);
10803 // NOTE: This size should be cached, but first we need to add calls to
10804 // InvalidateBestSize everywhere that could change the results of this
10806 // CacheBestSize(size);
10808 return wxSize(size
.x
+ m_rowLabelWidth
, size
.y
+ m_colLabelHeight
)
10809 + GetWindowBorderSize();
10817 wxPen
& wxGrid::GetDividerPen() const
10822 // ----------------------------------------------------------------------------
10823 // cell value accessor functions
10824 // ----------------------------------------------------------------------------
10826 void wxGrid::SetCellValue( int row
, int col
, const wxString
& s
)
10830 m_table
->SetValue( row
, col
, s
);
10831 if ( !GetBatchCount() )
10834 wxRect
rect( CellToRect( row
, col
) );
10836 rect
.width
= m_gridWin
->GetClientSize().GetWidth();
10837 CalcScrolledPosition(0, rect
.y
, &dummy
, &rect
.y
);
10838 m_gridWin
->Refresh( false, &rect
);
10841 if ( m_currentCellCoords
.GetRow() == row
&&
10842 m_currentCellCoords
.GetCol() == col
&&
10843 IsCellEditControlShown())
10844 // Note: If we are using IsCellEditControlEnabled,
10845 // this interacts badly with calling SetCellValue from
10846 // an EVT_GRID_CELL_CHANGE handler.
10848 HideCellEditControl();
10849 ShowCellEditControl(); // will reread data from table
10854 // ----------------------------------------------------------------------------
10855 // block, row and column selection
10856 // ----------------------------------------------------------------------------
10858 void wxGrid::SelectRow( int row
, bool addToSelected
)
10860 if ( !m_selection
)
10863 if ( !addToSelected
)
10866 m_selection
->SelectRow(row
);
10869 void wxGrid::SelectCol( int col
, bool addToSelected
)
10871 if ( !m_selection
)
10874 if ( !addToSelected
)
10877 m_selection
->SelectCol(col
);
10880 void wxGrid::SelectBlock(int topRow
, int leftCol
, int bottomRow
, int rightCol
,
10881 bool addToSelected
)
10883 if ( !m_selection
)
10886 if ( !addToSelected
)
10889 m_selection
->SelectBlock(topRow
, leftCol
, bottomRow
, rightCol
);
10892 void wxGrid::SelectAll()
10894 if ( m_numRows
> 0 && m_numCols
> 0 )
10897 m_selection
->SelectBlock( 0, 0, m_numRows
- 1, m_numCols
- 1 );
10901 // ----------------------------------------------------------------------------
10902 // cell, row and col deselection
10903 // ----------------------------------------------------------------------------
10905 void wxGrid::DeselectLine(int line
, const wxGridOperations
& oper
)
10907 if ( !m_selection
)
10910 const wxGridSelectionModes mode
= m_selection
->GetSelectionMode();
10911 if ( mode
== oper
.GetSelectionMode() )
10913 const wxGridCellCoords
c(oper
.MakeCoords(line
, 0));
10914 if ( m_selection
->IsInSelection(c
) )
10915 m_selection
->ToggleCellSelection(c
);
10917 else if ( mode
!= oper
.Dual().GetSelectionMode() )
10919 const int nOther
= oper
.Dual().GetNumberOfLines(this);
10920 for ( int i
= 0; i
< nOther
; i
++ )
10922 const wxGridCellCoords
c(oper
.MakeCoords(line
, i
));
10923 if ( m_selection
->IsInSelection(c
) )
10924 m_selection
->ToggleCellSelection(c
);
10927 //else: can only select orthogonal lines so no lines in this direction
10928 // could have been selected anyhow
10931 void wxGrid::DeselectRow(int row
)
10933 DeselectLine(row
, wxGridRowOperations());
10936 void wxGrid::DeselectCol(int col
)
10938 DeselectLine(col
, wxGridColumnOperations());
10941 void wxGrid::DeselectCell( int row
, int col
)
10943 if ( m_selection
&& m_selection
->IsInSelection(row
, col
) )
10944 m_selection
->ToggleCellSelection(row
, col
);
10947 bool wxGrid::IsSelection() const
10949 return ( m_selection
&& (m_selection
->IsSelection() ||
10950 ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
10951 m_selectedBlockBottomRight
!= wxGridNoCellCoords
) ) );
10954 bool wxGrid::IsInSelection( int row
, int col
) const
10956 return ( m_selection
&& (m_selection
->IsInSelection( row
, col
) ||
10957 ( row
>= m_selectedBlockTopLeft
.GetRow() &&
10958 col
>= m_selectedBlockTopLeft
.GetCol() &&
10959 row
<= m_selectedBlockBottomRight
.GetRow() &&
10960 col
<= m_selectedBlockBottomRight
.GetCol() )) );
10963 wxGridCellCoordsArray
wxGrid::GetSelectedCells() const
10967 wxGridCellCoordsArray a
;
10971 return m_selection
->m_cellSelection
;
10974 wxGridCellCoordsArray
wxGrid::GetSelectionBlockTopLeft() const
10978 wxGridCellCoordsArray a
;
10982 return m_selection
->m_blockSelectionTopLeft
;
10985 wxGridCellCoordsArray
wxGrid::GetSelectionBlockBottomRight() const
10989 wxGridCellCoordsArray a
;
10993 return m_selection
->m_blockSelectionBottomRight
;
10996 wxArrayInt
wxGrid::GetSelectedRows() const
11004 return m_selection
->m_rowSelection
;
11007 wxArrayInt
wxGrid::GetSelectedCols() const
11015 return m_selection
->m_colSelection
;
11018 void wxGrid::ClearSelection()
11020 wxRect r1
= BlockToDeviceRect(m_selectedBlockTopLeft
,
11021 m_selectedBlockBottomRight
);
11022 wxRect r2
= BlockToDeviceRect(m_currentCellCoords
,
11023 m_selectedBlockCorner
);
11025 m_selectedBlockTopLeft
=
11026 m_selectedBlockBottomRight
=
11027 m_selectedBlockCorner
= wxGridNoCellCoords
;
11029 Refresh( false, &r1
);
11030 Refresh( false, &r2
);
11033 m_selection
->ClearSelection();
11036 // This function returns the rectangle that encloses the given block
11037 // in device coords clipped to the client size of the grid window.
11039 wxRect
wxGrid::BlockToDeviceRect( const wxGridCellCoords
& topLeft
,
11040 const wxGridCellCoords
& bottomRight
) const
11043 wxRect tempCellRect
= CellToRect(topLeft
);
11044 if ( tempCellRect
!= wxGridNoCellRect
)
11046 resultRect
= tempCellRect
;
11050 resultRect
= wxRect(0, 0, 0, 0);
11053 tempCellRect
= CellToRect(bottomRight
);
11054 if ( tempCellRect
!= wxGridNoCellRect
)
11056 resultRect
+= tempCellRect
;
11060 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
11061 return wxGridNoCellRect
;
11064 // Ensure that left/right and top/bottom pairs are in order.
11065 int left
= resultRect
.GetLeft();
11066 int top
= resultRect
.GetTop();
11067 int right
= resultRect
.GetRight();
11068 int bottom
= resultRect
.GetBottom();
11070 int leftCol
= topLeft
.GetCol();
11071 int topRow
= topLeft
.GetRow();
11072 int rightCol
= bottomRight
.GetCol();
11073 int bottomRow
= bottomRight
.GetRow();
11082 leftCol
= rightCol
;
11093 topRow
= bottomRow
;
11097 // The following loop is ONLY necessary to detect and handle merged cells.
11099 m_gridWin
->GetClientSize( &cw
, &ch
);
11101 // Get the origin coordinates: notice that they will be negative if the
11102 // grid is scrolled downwards/to the right.
11103 int gridOriginX
= 0;
11104 int gridOriginY
= 0;
11105 CalcScrolledPosition(gridOriginX
, gridOriginY
, &gridOriginX
, &gridOriginY
);
11107 int onScreenLeftmostCol
= internalXToCol(-gridOriginX
);
11108 int onScreenUppermostRow
= internalYToRow(-gridOriginY
);
11110 int onScreenRightmostCol
= internalXToCol(-gridOriginX
+ cw
);
11111 int onScreenBottommostRow
= internalYToRow(-gridOriginY
+ ch
);
11113 // Bound our loop so that we only examine the portion of the selected block
11114 // that is shown on screen. Therefore, we compare the Top-Left block values
11115 // to the Top-Left screen values, and the Bottom-Right block values to the
11116 // Bottom-Right screen values, choosing appropriately.
11117 const int visibleTopRow
= wxMax(topRow
, onScreenUppermostRow
);
11118 const int visibleBottomRow
= wxMin(bottomRow
, onScreenBottommostRow
);
11119 const int visibleLeftCol
= wxMax(leftCol
, onScreenLeftmostCol
);
11120 const int visibleRightCol
= wxMin(rightCol
, onScreenRightmostCol
);
11122 for ( int j
= visibleTopRow
; j
<= visibleBottomRow
; j
++ )
11124 for ( int i
= visibleLeftCol
; i
<= visibleRightCol
; i
++ )
11126 if ( (j
== visibleTopRow
) || (j
== visibleBottomRow
) ||
11127 (i
== visibleLeftCol
) || (i
== visibleRightCol
) )
11129 tempCellRect
= CellToRect( j
, i
);
11131 if (tempCellRect
.x
< left
)
11132 left
= tempCellRect
.x
;
11133 if (tempCellRect
.y
< top
)
11134 top
= tempCellRect
.y
;
11135 if (tempCellRect
.x
+ tempCellRect
.width
> right
)
11136 right
= tempCellRect
.x
+ tempCellRect
.width
;
11137 if (tempCellRect
.y
+ tempCellRect
.height
> bottom
)
11138 bottom
= tempCellRect
.y
+ tempCellRect
.height
;
11142 i
= visibleRightCol
; // jump over inner cells.
11147 // Convert to scrolled coords
11148 CalcScrolledPosition( left
, top
, &left
, &top
);
11149 CalcScrolledPosition( right
, bottom
, &right
, &bottom
);
11151 if (right
< 0 || bottom
< 0 || left
> cw
|| top
> ch
)
11152 return wxRect(0,0,0,0);
11154 resultRect
.SetLeft( wxMax(0, left
) );
11155 resultRect
.SetTop( wxMax(0, top
) );
11156 resultRect
.SetRight( wxMin(cw
, right
) );
11157 resultRect
.SetBottom( wxMin(ch
, bottom
) );
11162 // ----------------------------------------------------------------------------
11164 // ----------------------------------------------------------------------------
11166 #if wxUSE_DRAG_AND_DROP
11168 // this allow setting drop target directly on wxGrid
11169 void wxGrid::SetDropTarget(wxDropTarget
*dropTarget
)
11171 GetGridWindow()->SetDropTarget(dropTarget
);
11174 #endif // wxUSE_DRAG_AND_DROP
11176 // ----------------------------------------------------------------------------
11177 // grid event classes
11178 // ----------------------------------------------------------------------------
11180 IMPLEMENT_DYNAMIC_CLASS( wxGridEvent
, wxNotifyEvent
)
11182 wxGridEvent::wxGridEvent( int id
, wxEventType type
, wxObject
* obj
,
11183 int row
, int col
, int x
, int y
, bool sel
,
11184 bool control
, bool shift
, bool alt
, bool meta
)
11185 : wxNotifyEvent( type
, id
),
11186 wxKeyboardState(control
, shift
, alt
, meta
)
11188 Init(row
, col
, x
, y
, sel
);
11190 SetEventObject(obj
);
11193 IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent
, wxNotifyEvent
)
11195 wxGridSizeEvent::wxGridSizeEvent( int id
, wxEventType type
, wxObject
* obj
,
11196 int rowOrCol
, int x
, int y
,
11197 bool control
, bool shift
, bool alt
, bool meta
)
11198 : wxNotifyEvent( type
, id
),
11199 wxKeyboardState(control
, shift
, alt
, meta
)
11201 Init(rowOrCol
, x
, y
);
11203 SetEventObject(obj
);
11207 IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent
, wxNotifyEvent
)
11209 wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id
, wxEventType type
, wxObject
* obj
,
11210 const wxGridCellCoords
& topLeft
,
11211 const wxGridCellCoords
& bottomRight
,
11212 bool sel
, bool control
,
11213 bool shift
, bool alt
, bool meta
)
11214 : wxNotifyEvent( type
, id
),
11215 wxKeyboardState(control
, shift
, alt
, meta
)
11217 Init(topLeft
, bottomRight
, sel
);
11219 SetEventObject(obj
);
11223 IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent
, wxCommandEvent
)
11225 wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id
, wxEventType type
,
11226 wxObject
* obj
, int row
,
11227 int col
, wxControl
* ctrl
)
11228 : wxCommandEvent(type
, id
)
11230 SetEventObject(obj
);
11236 #endif // wxUSE_GRID