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 wxHeaderColumn
& GetColumn(unsigned int idx
)
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 // event handlers forwarding wxHeaderCtrl events to wxGrid
282 void OnClick(wxHeaderCtrlEvent
& event
)
284 GetOwner()->DoColHeaderClick(event
.GetColumn());
287 void OnBeginResize(wxHeaderCtrlEvent
& event
)
289 GetOwner()->DoStartResizeCol(event
.GetColumn());
294 void OnResizing(wxHeaderCtrlEvent
& event
)
296 GetOwner()->DoUpdateResizeColWidth(event
.GetWidth());
299 void OnEndResize(wxHeaderCtrlEvent
& event
)
301 GetOwner()->DoEndDragResizeCol();
306 void OnBeginReorder(wxHeaderCtrlEvent
& event
)
308 GetOwner()->DoStartMoveCol(event
.GetColumn());
311 void OnEndReorder(wxHeaderCtrlEvent
& event
)
313 GetOwner()->DoEndMoveCol(event
.GetNewOrder());
316 wxVector
<wxGridHeaderColumn
> m_columns
;
318 DECLARE_EVENT_TABLE()
319 DECLARE_NO_COPY_CLASS(wxGridHeaderCtrl
)
322 BEGIN_EVENT_TABLE(wxGridHeaderCtrl
, wxHeaderCtrl
)
323 EVT_HEADER_CLICK(wxID_ANY
, wxGridHeaderCtrl::OnClick
)
325 EVT_HEADER_BEGIN_RESIZE(wxID_ANY
, wxGridHeaderCtrl::OnBeginResize
)
326 EVT_HEADER_RESIZING(wxID_ANY
, wxGridHeaderCtrl::OnResizing
)
327 EVT_HEADER_END_RESIZE(wxID_ANY
, wxGridHeaderCtrl::OnEndResize
)
329 EVT_HEADER_BEGIN_REORDER(wxID_ANY
, wxGridHeaderCtrl::OnBeginReorder
)
330 EVT_HEADER_END_REORDER(wxID_ANY
, wxGridHeaderCtrl::OnEndReorder
)
333 // common base class for various grid subwindows
334 class WXDLLIMPEXP_ADV wxGridSubwindow
: public wxWindow
337 wxGridSubwindow(wxGrid
*owner
,
338 int additionalStyle
= 0,
339 const wxString
& name
= wxPanelNameStr
)
340 : wxWindow(owner
, wxID_ANY
,
341 wxDefaultPosition
, wxDefaultSize
,
342 wxBORDER_NONE
| additionalStyle
,
348 virtual bool AcceptsFocus() const { return false; }
350 wxGrid
*GetOwner() { return m_owner
; }
353 void OnMouseCaptureLost(wxMouseCaptureLostEvent
& event
);
357 DECLARE_EVENT_TABLE()
358 DECLARE_NO_COPY_CLASS(wxGridSubwindow
)
361 class WXDLLIMPEXP_ADV wxGridRowLabelWindow
: public wxGridSubwindow
364 wxGridRowLabelWindow(wxGrid
*parent
)
365 : wxGridSubwindow(parent
)
371 void OnPaint( wxPaintEvent
& event
);
372 void OnMouseEvent( wxMouseEvent
& event
);
373 void OnMouseWheel( wxMouseEvent
& event
);
375 DECLARE_EVENT_TABLE()
376 DECLARE_NO_COPY_CLASS(wxGridRowLabelWindow
)
380 class WXDLLIMPEXP_ADV wxGridColLabelWindow
: public wxGridSubwindow
383 wxGridColLabelWindow(wxGrid
*parent
)
384 : wxGridSubwindow(parent
)
390 void OnPaint( wxPaintEvent
& event
);
391 void OnMouseEvent( wxMouseEvent
& event
);
392 void OnMouseWheel( wxMouseEvent
& event
);
394 DECLARE_EVENT_TABLE()
395 DECLARE_NO_COPY_CLASS(wxGridColLabelWindow
)
399 class WXDLLIMPEXP_ADV wxGridCornerLabelWindow
: public wxGridSubwindow
402 wxGridCornerLabelWindow(wxGrid
*parent
)
403 : wxGridSubwindow(parent
)
408 void OnMouseEvent( wxMouseEvent
& event
);
409 void OnMouseWheel( wxMouseEvent
& event
);
410 void OnPaint( wxPaintEvent
& event
);
412 DECLARE_EVENT_TABLE()
413 DECLARE_NO_COPY_CLASS(wxGridCornerLabelWindow
)
416 class WXDLLIMPEXP_ADV wxGridWindow
: public wxGridSubwindow
419 wxGridWindow(wxGrid
*parent
)
420 : wxGridSubwindow(parent
,
421 wxWANTS_CHARS
| wxCLIP_CHILDREN
,
427 virtual void ScrollWindow( int dx
, int dy
, const wxRect
*rect
);
429 virtual bool AcceptsFocus() const { return true; }
432 void OnPaint( wxPaintEvent
&event
);
433 void OnMouseWheel( wxMouseEvent
& event
);
434 void OnMouseEvent( wxMouseEvent
& event
);
435 void OnKeyDown( wxKeyEvent
& );
436 void OnKeyUp( wxKeyEvent
& );
437 void OnChar( wxKeyEvent
& );
438 void OnEraseBackground( wxEraseEvent
& );
439 void OnFocus( wxFocusEvent
& );
441 DECLARE_EVENT_TABLE()
442 DECLARE_NO_COPY_CLASS(wxGridWindow
)
446 class wxGridCellEditorEvtHandler
: public wxEvtHandler
449 wxGridCellEditorEvtHandler(wxGrid
* grid
, wxGridCellEditor
* editor
)
456 void OnKillFocus(wxFocusEvent
& event
);
457 void OnKeyDown(wxKeyEvent
& event
);
458 void OnChar(wxKeyEvent
& event
);
460 void SetInSetFocus(bool inSetFocus
) { m_inSetFocus
= inSetFocus
; }
464 wxGridCellEditor
*m_editor
;
466 // Work around the fact that a focus kill event can be sent to
467 // a combobox within a set focus event.
470 DECLARE_EVENT_TABLE()
471 DECLARE_DYNAMIC_CLASS(wxGridCellEditorEvtHandler
)
472 DECLARE_NO_COPY_CLASS(wxGridCellEditorEvtHandler
)
476 IMPLEMENT_ABSTRACT_CLASS(wxGridCellEditorEvtHandler
, wxEvtHandler
)
478 BEGIN_EVENT_TABLE( wxGridCellEditorEvtHandler
, wxEvtHandler
)
479 EVT_KILL_FOCUS( wxGridCellEditorEvtHandler::OnKillFocus
)
480 EVT_KEY_DOWN( wxGridCellEditorEvtHandler::OnKeyDown
)
481 EVT_CHAR( wxGridCellEditorEvtHandler::OnChar
)
485 // ----------------------------------------------------------------------------
486 // the internal data representation used by wxGridCellAttrProvider
487 // ----------------------------------------------------------------------------
489 // this class stores attributes set for cells
490 class WXDLLIMPEXP_ADV wxGridCellAttrData
493 void SetAttr(wxGridCellAttr
*attr
, int row
, int col
);
494 wxGridCellAttr
*GetAttr(int row
, int col
) const;
495 void UpdateAttrRows( size_t pos
, int numRows
);
496 void UpdateAttrCols( size_t pos
, int numCols
);
499 // searches for the attr for given cell, returns wxNOT_FOUND if not found
500 int FindIndex(int row
, int col
) const;
502 wxGridCellWithAttrArray m_attrs
;
505 // this class stores attributes set for rows or columns
506 class WXDLLIMPEXP_ADV wxGridRowOrColAttrData
509 // empty ctor to suppress warnings
510 wxGridRowOrColAttrData() {}
511 ~wxGridRowOrColAttrData();
513 void SetAttr(wxGridCellAttr
*attr
, int rowOrCol
);
514 wxGridCellAttr
*GetAttr(int rowOrCol
) const;
515 void UpdateAttrRowsOrCols( size_t pos
, int numRowsOrCols
);
518 wxArrayInt m_rowsOrCols
;
519 wxArrayAttrs m_attrs
;
522 // NB: this is just a wrapper around 3 objects: one which stores cell
523 // attributes, and 2 others for row/col ones
524 class WXDLLIMPEXP_ADV wxGridCellAttrProviderData
527 wxGridCellAttrData m_cellAttrs
;
528 wxGridRowOrColAttrData m_rowAttrs
,
533 // ----------------------------------------------------------------------------
534 // data structures used for the data type registry
535 // ----------------------------------------------------------------------------
537 struct wxGridDataTypeInfo
539 wxGridDataTypeInfo(const wxString
& typeName
,
540 wxGridCellRenderer
* renderer
,
541 wxGridCellEditor
* editor
)
542 : m_typeName(typeName
), m_renderer(renderer
), m_editor(editor
)
545 ~wxGridDataTypeInfo()
547 wxSafeDecRef(m_renderer
);
548 wxSafeDecRef(m_editor
);
552 wxGridCellRenderer
* m_renderer
;
553 wxGridCellEditor
* m_editor
;
555 DECLARE_NO_COPY_CLASS(wxGridDataTypeInfo
)
559 WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridDataTypeInfo
*, wxGridDataTypeInfoArray
,
560 class WXDLLIMPEXP_ADV
);
563 class WXDLLIMPEXP_ADV wxGridTypeRegistry
566 wxGridTypeRegistry() {}
567 ~wxGridTypeRegistry();
569 void RegisterDataType(const wxString
& typeName
,
570 wxGridCellRenderer
* renderer
,
571 wxGridCellEditor
* editor
);
573 // find one of already registered data types
574 int FindRegisteredDataType(const wxString
& typeName
);
576 // try to FindRegisteredDataType(), if this fails and typeName is one of
577 // standard typenames, register it and return its index
578 int FindDataType(const wxString
& typeName
);
580 // try to FindDataType(), if it fails see if it is not one of already
581 // registered data types with some params in which case clone the
582 // registered data type and set params for it
583 int FindOrCloneDataType(const wxString
& typeName
);
585 wxGridCellRenderer
* GetRenderer(int index
);
586 wxGridCellEditor
* GetEditor(int index
);
589 wxGridDataTypeInfoArray m_typeinfo
;
592 // ----------------------------------------------------------------------------
593 // operations classes abstracting the difference between operating on rows and
595 // ----------------------------------------------------------------------------
597 // This class allows to write a function only once because by using its methods
598 // it will apply to both columns and rows.
600 // This is an abstract interface definition, the two concrete implementations
601 // below should be used when working with rows and columns respectively.
602 class wxGridOperations
605 // Returns the operations in the other direction, i.e. wxGridRowOperations
606 // if this object is a wxGridColumnOperations and vice versa.
607 virtual wxGridOperations
& Dual() const = 0;
609 // Return the number of rows or columns.
610 virtual int GetNumberOfLines(const wxGrid
*grid
) const = 0;
612 // Return the selection mode which allows selecting rows or columns.
613 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const = 0;
615 // Make a wxGridCellCoords from the given components: thisDir is row or
616 // column and otherDir is column or row
617 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const = 0;
619 // Calculate the scrolled position of the given abscissa or ordinate.
620 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const = 0;
622 // Selects the horizontal or vertical component from the given object.
623 virtual int Select(const wxGridCellCoords
& coords
) const = 0;
624 virtual int Select(const wxPoint
& pt
) const = 0;
625 virtual int Select(const wxSize
& sz
) const = 0;
626 virtual int Select(const wxRect
& r
) const = 0;
627 virtual int& Select(wxRect
& r
) const = 0;
629 // Returns width or height of the rectangle
630 virtual int& SelectSize(wxRect
& r
) const = 0;
632 // Make a wxSize such that Select() applied to it returns first component
633 virtual wxSize
MakeSize(int first
, int second
) const = 0;
635 // Sets the row or column component of the given cell coordinates
636 virtual void Set(wxGridCellCoords
& coords
, int line
) const = 0;
639 // Draws a line parallel to the row or column, i.e. horizontal or vertical:
640 // pos is the horizontal or vertical position of the line and start and end
641 // are the coordinates of the line extremities in the other direction
643 DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const = 0;
645 // Draw a horizontal or vertical line across the given rectangle
646 // (this is implemented in terms of above and uses Select() to extract
647 // start and end from the given rectangle)
648 void DrawParallelLineInRect(wxDC
& dc
, const wxRect
& rect
, int pos
) const
650 const int posStart
= Select(rect
.GetPosition());
651 DrawParallelLine(dc
, posStart
, posStart
+ Select(rect
.GetSize()), pos
);
655 // Return the index of the row or column at the given pixel coordinate.
657 PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const = 0;
659 // Get the top/left position, in pixels, of the given row or column
660 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const = 0;
662 // Get the bottom/right position, in pixels, of the given row or column
663 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const = 0;
665 // Get the height/width of the given row/column
666 virtual int GetLineSize(const wxGrid
*grid
, int line
) const = 0;
668 // Get wxGrid::m_rowBottoms/m_colRights array
669 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const = 0;
671 // Get default height row height or column width
672 virtual int GetDefaultLineSize(const wxGrid
*grid
) const = 0;
674 // Return the minimal acceptable row height or column width
675 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const = 0;
677 // Return the minimal row height or column width
678 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const = 0;
680 // Set the row height or column width
681 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const = 0;
683 // True if rows/columns can be resized by user
684 virtual bool CanResizeLines(const wxGrid
*grid
) const = 0;
687 // Return the index of the line at the given position
689 // NB: currently this is always identity for the rows as reordering is only
690 // implemented for the lines
691 virtual int GetLineAt(const wxGrid
*grid
, int line
) const = 0;
694 // Get the row or column label window
695 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const = 0;
697 // Get the width or height of the row or column label window
698 virtual int GetHeaderWindowSize(wxGrid
*grid
) const = 0;
701 // This class is never used polymorphically but give it a virtual dtor
702 // anyhow to suppress g++ complaints about it
703 virtual ~wxGridOperations() { }
706 class wxGridRowOperations
: public wxGridOperations
709 virtual wxGridOperations
& Dual() const;
711 virtual int GetNumberOfLines(const wxGrid
*grid
) const
712 { return grid
->GetNumberRows(); }
714 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const
715 { return wxGrid::wxGridSelectRows
; }
717 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const
718 { return wxGridCellCoords(thisDir
, otherDir
); }
720 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const
721 { return grid
->CalcScrolledPosition(wxPoint(pos
, 0)).x
; }
723 virtual int Select(const wxGridCellCoords
& c
) const { return c
.GetRow(); }
724 virtual int Select(const wxPoint
& pt
) const { return pt
.x
; }
725 virtual int Select(const wxSize
& sz
) const { return sz
.x
; }
726 virtual int Select(const wxRect
& r
) const { return r
.x
; }
727 virtual int& Select(wxRect
& r
) const { return r
.x
; }
728 virtual int& SelectSize(wxRect
& r
) const { return r
.width
; }
729 virtual wxSize
MakeSize(int first
, int second
) const
730 { return wxSize(first
, second
); }
731 virtual void Set(wxGridCellCoords
& coords
, int line
) const
732 { coords
.SetRow(line
); }
734 virtual void DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const
735 { dc
.DrawLine(start
, pos
, end
, pos
); }
737 virtual int PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const
738 { return grid
->YToRow(pos
, clip
); }
739 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const
740 { return grid
->GetRowTop(line
); }
741 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const
742 { return grid
->GetRowBottom(line
); }
743 virtual int GetLineSize(const wxGrid
*grid
, int line
) const
744 { return grid
->GetRowHeight(line
); }
745 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const
746 { return grid
->m_rowBottoms
; }
747 virtual int GetDefaultLineSize(const wxGrid
*grid
) const
748 { return grid
->GetDefaultRowSize(); }
749 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const
750 { return grid
->GetRowMinimalAcceptableHeight(); }
751 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const
752 { return grid
->GetRowMinimalHeight(line
); }
753 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const
754 { grid
->SetRowSize(line
, size
); }
755 virtual bool CanResizeLines(const wxGrid
*grid
) const
756 { return grid
->CanDragRowSize(); }
758 virtual int GetLineAt(const wxGrid
* WXUNUSED(grid
), int line
) const
759 { return line
; } // TODO: implement row reordering
761 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const
762 { return grid
->GetGridRowLabelWindow(); }
763 virtual int GetHeaderWindowSize(wxGrid
*grid
) const
764 { return grid
->GetRowLabelSize(); }
767 class wxGridColumnOperations
: public wxGridOperations
770 virtual wxGridOperations
& Dual() const;
772 virtual int GetNumberOfLines(const wxGrid
*grid
) const
773 { return grid
->GetNumberCols(); }
775 virtual wxGrid::wxGridSelectionModes
GetSelectionMode() const
776 { return wxGrid::wxGridSelectColumns
; }
778 virtual wxGridCellCoords
MakeCoords(int thisDir
, int otherDir
) const
779 { return wxGridCellCoords(otherDir
, thisDir
); }
781 virtual int CalcScrolledPosition(wxGrid
*grid
, int pos
) const
782 { return grid
->CalcScrolledPosition(wxPoint(0, pos
)).y
; }
784 virtual int Select(const wxGridCellCoords
& c
) const { return c
.GetCol(); }
785 virtual int Select(const wxPoint
& pt
) const { return pt
.y
; }
786 virtual int Select(const wxSize
& sz
) const { return sz
.y
; }
787 virtual int Select(const wxRect
& r
) const { return r
.y
; }
788 virtual int& Select(wxRect
& r
) const { return r
.y
; }
789 virtual int& SelectSize(wxRect
& r
) const { return r
.height
; }
790 virtual wxSize
MakeSize(int first
, int second
) const
791 { return wxSize(second
, first
); }
792 virtual void Set(wxGridCellCoords
& coords
, int line
) const
793 { coords
.SetCol(line
); }
795 virtual void DrawParallelLine(wxDC
& dc
, int start
, int end
, int pos
) const
796 { dc
.DrawLine(pos
, start
, pos
, end
); }
798 virtual int PosToLine(const wxGrid
*grid
, int pos
, bool clip
= false) const
799 { return grid
->XToCol(pos
, clip
); }
800 virtual int GetLineStartPos(const wxGrid
*grid
, int line
) const
801 { return grid
->GetColLeft(line
); }
802 virtual int GetLineEndPos(const wxGrid
*grid
, int line
) const
803 { return grid
->GetColRight(line
); }
804 virtual int GetLineSize(const wxGrid
*grid
, int line
) const
805 { return grid
->GetColWidth(line
); }
806 virtual const wxArrayInt
& GetLineEnds(const wxGrid
*grid
) const
807 { return grid
->m_colRights
; }
808 virtual int GetDefaultLineSize(const wxGrid
*grid
) const
809 { return grid
->GetDefaultColSize(); }
810 virtual int GetMinimalAcceptableLineSize(const wxGrid
*grid
) const
811 { return grid
->GetColMinimalAcceptableWidth(); }
812 virtual int GetMinimalLineSize(const wxGrid
*grid
, int line
) const
813 { return grid
->GetColMinimalWidth(line
); }
814 virtual void SetLineSize(wxGrid
*grid
, int line
, int size
) const
815 { grid
->SetColSize(line
, size
); }
816 virtual bool CanResizeLines(const wxGrid
*grid
) const
817 { return grid
->CanDragColSize(); }
819 virtual int GetLineAt(const wxGrid
*grid
, int line
) const
820 { return grid
->GetColAt(line
); }
822 virtual wxWindow
*GetHeaderWindow(wxGrid
*grid
) const
823 { return grid
->GetGridColLabelWindow(); }
824 virtual int GetHeaderWindowSize(wxGrid
*grid
) const
825 { return grid
->GetColLabelSize(); }
828 wxGridOperations
& wxGridRowOperations::Dual() const
830 static wxGridColumnOperations s_colOper
;
835 wxGridOperations
& wxGridColumnOperations::Dual() const
837 static wxGridRowOperations s_rowOper
;
842 // This class abstracts the difference between operations going forward
843 // (down/right) and backward (up/left) and allows to use the same code for
844 // functions which differ only in the direction of grid traversal
846 // Like wxGridOperations it's an ABC with two concrete subclasses below. Unlike
847 // it, this is a normal object and not just a function dispatch table and has a
850 // Note: the explanation of this discrepancy is the existence of (very useful)
851 // Dual() method in wxGridOperations which forces us to make wxGridOperations a
852 // function dispatcher only.
853 class wxGridDirectionOperations
856 // The oper parameter to ctor selects whether we work with rows or columns
857 wxGridDirectionOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
863 // Check if the component of this point in our direction is at the
864 // boundary, i.e. is the first/last row/column
865 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const = 0;
867 // Increment the component of this point in our direction
868 virtual void Advance(wxGridCellCoords
& coords
) const = 0;
870 // Find the line at the given distance, in pixels, away from this one
871 // (this uses clipping, i.e. anything after the last line is counted as the
872 // last one and anything before the first one as 0)
873 virtual int MoveByPixelDistance(int line
, int distance
) const = 0;
875 // This class is never used polymorphically but give it a virtual dtor
876 // anyhow to suppress g++ complaints about it
877 virtual ~wxGridDirectionOperations() { }
880 wxGrid
* const m_grid
;
881 const wxGridOperations
& m_oper
;
884 class wxGridBackwardOperations
: public wxGridDirectionOperations
887 wxGridBackwardOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
888 : wxGridDirectionOperations(grid
, oper
)
892 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const
894 wxASSERT_MSG( m_oper
.Select(coords
) >= 0, "invalid row/column" );
896 return m_oper
.Select(coords
) == 0;
899 virtual void Advance(wxGridCellCoords
& coords
) const
901 wxASSERT( !IsAtBoundary(coords
) );
903 m_oper
.Set(coords
, m_oper
.Select(coords
) - 1);
906 virtual int MoveByPixelDistance(int line
, int distance
) const
908 int pos
= m_oper
.GetLineStartPos(m_grid
, line
);
909 return m_oper
.PosToLine(m_grid
, pos
- distance
+ 1, true);
913 class wxGridForwardOperations
: public wxGridDirectionOperations
916 wxGridForwardOperations(wxGrid
*grid
, const wxGridOperations
& oper
)
917 : wxGridDirectionOperations(grid
, oper
),
918 m_numLines(oper
.GetNumberOfLines(grid
))
922 virtual bool IsAtBoundary(const wxGridCellCoords
& coords
) const
924 wxASSERT_MSG( m_oper
.Select(coords
) < m_numLines
, "invalid row/column" );
926 return m_oper
.Select(coords
) == m_numLines
- 1;
929 virtual void Advance(wxGridCellCoords
& coords
) const
931 wxASSERT( !IsAtBoundary(coords
) );
933 m_oper
.Set(coords
, m_oper
.Select(coords
) + 1);
936 virtual int MoveByPixelDistance(int line
, int distance
) const
938 int pos
= m_oper
.GetLineStartPos(m_grid
, line
);
939 return m_oper
.PosToLine(m_grid
, pos
+ distance
, true);
943 const int m_numLines
;
946 // ----------------------------------------------------------------------------
948 // ----------------------------------------------------------------------------
950 //#define DEBUG_ATTR_CACHE
951 #ifdef DEBUG_ATTR_CACHE
952 static size_t gs_nAttrCacheHits
= 0;
953 static size_t gs_nAttrCacheMisses
= 0;
956 // ----------------------------------------------------------------------------
958 // ----------------------------------------------------------------------------
960 wxGridCellCoords
wxGridNoCellCoords( -1, -1 );
961 wxRect
wxGridNoCellRect( -1, -1, -1, -1 );
967 const size_t GRID_SCROLL_LINE_X
= 15;
968 const size_t GRID_SCROLL_LINE_Y
= GRID_SCROLL_LINE_X
;
970 // the size of hash tables used a bit everywhere (the max number of elements
971 // in these hash tables is the number of rows/columns)
972 const int GRID_HASH_SIZE
= 100;
974 // the minimal distance in pixels the mouse needs to move to start a drag
976 const int DRAG_SENSITIVITY
= 3;
978 } // anonymous namespace
980 // ----------------------------------------------------------------------------
982 // ----------------------------------------------------------------------------
987 // ensure that first is less or equal to second, swapping the values if
989 void EnsureFirstLessThanSecond(int& first
, int& second
)
991 if ( first
> second
)
992 wxSwap(first
, second
);
995 } // anonymous namespace
997 // ============================================================================
999 // ============================================================================
1001 // ----------------------------------------------------------------------------
1003 // ----------------------------------------------------------------------------
1005 wxGridCellEditor::wxGridCellEditor()
1011 wxGridCellEditor::~wxGridCellEditor()
1016 void wxGridCellEditor::Create(wxWindow
* WXUNUSED(parent
),
1017 wxWindowID
WXUNUSED(id
),
1018 wxEvtHandler
* evtHandler
)
1021 m_control
->PushEventHandler(evtHandler
);
1024 void wxGridCellEditor::PaintBackground(const wxRect
& rectCell
,
1025 wxGridCellAttr
*attr
)
1027 // erase the background because we might not fill the cell
1028 wxClientDC
dc(m_control
->GetParent());
1029 wxGridWindow
* gridWindow
= wxDynamicCast(m_control
->GetParent(), wxGridWindow
);
1031 gridWindow
->GetOwner()->PrepareDC(dc
);
1033 dc
.SetPen(*wxTRANSPARENT_PEN
);
1034 dc
.SetBrush(wxBrush(attr
->GetBackgroundColour()));
1035 dc
.DrawRectangle(rectCell
);
1037 // redraw the control we just painted over
1038 m_control
->Refresh();
1041 void wxGridCellEditor::Destroy()
1045 m_control
->PopEventHandler( true /* delete it*/ );
1047 m_control
->Destroy();
1052 void wxGridCellEditor::Show(bool show
, wxGridCellAttr
*attr
)
1054 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1056 m_control
->Show(show
);
1060 // set the colours/fonts if we have any
1063 m_colFgOld
= m_control
->GetForegroundColour();
1064 m_control
->SetForegroundColour(attr
->GetTextColour());
1066 m_colBgOld
= m_control
->GetBackgroundColour();
1067 m_control
->SetBackgroundColour(attr
->GetBackgroundColour());
1069 // Workaround for GTK+1 font setting problem on some platforms
1070 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1071 m_fontOld
= m_control
->GetFont();
1072 m_control
->SetFont(attr
->GetFont());
1075 // can't do anything more in the base class version, the other
1076 // attributes may only be used by the derived classes
1081 // restore the standard colours fonts
1082 if ( m_colFgOld
.Ok() )
1084 m_control
->SetForegroundColour(m_colFgOld
);
1085 m_colFgOld
= wxNullColour
;
1088 if ( m_colBgOld
.Ok() )
1090 m_control
->SetBackgroundColour(m_colBgOld
);
1091 m_colBgOld
= wxNullColour
;
1094 // Workaround for GTK+1 font setting problem on some platforms
1095 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1096 if ( m_fontOld
.Ok() )
1098 m_control
->SetFont(m_fontOld
);
1099 m_fontOld
= wxNullFont
;
1105 void wxGridCellEditor::SetSize(const wxRect
& rect
)
1107 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1109 m_control
->SetSize(rect
, wxSIZE_ALLOW_MINUS_ONE
);
1112 void wxGridCellEditor::HandleReturn(wxKeyEvent
& event
)
1117 bool wxGridCellEditor::IsAcceptedKey(wxKeyEvent
& event
)
1119 bool ctrl
= event
.ControlDown();
1120 bool alt
= event
.AltDown();
1123 // On the Mac the Alt key is more like shift and is used for entry of
1124 // valid characters, so check for Ctrl and Meta instead.
1125 alt
= event
.MetaDown();
1128 // Assume it's not a valid char if ctrl or alt is down, but if both are
1129 // down then it may be because of an AltGr key combination, so let them
1130 // through in that case.
1131 if ((ctrl
|| alt
) && !(ctrl
&& alt
))
1135 // if the unicode key code is not really a unicode character (it may
1136 // be a function key or etc., the platforms appear to always give us a
1137 // small value in this case) then fallback to the ASCII key code but
1138 // don't do anything for function keys or etc.
1139 if ( event
.GetUnicodeKey() > 127 && event
.GetKeyCode() > 127 )
1142 if ( event
.GetKeyCode() > 255 )
1149 void wxGridCellEditor::StartingKey(wxKeyEvent
& event
)
1154 void wxGridCellEditor::StartingClick()
1160 // ----------------------------------------------------------------------------
1161 // wxGridCellTextEditor
1162 // ----------------------------------------------------------------------------
1164 wxGridCellTextEditor::wxGridCellTextEditor()
1169 void wxGridCellTextEditor::Create(wxWindow
* parent
,
1171 wxEvtHandler
* evtHandler
)
1173 DoCreate(parent
, id
, evtHandler
);
1176 void wxGridCellTextEditor::DoCreate(wxWindow
* parent
,
1178 wxEvtHandler
* evtHandler
,
1181 style
|= wxTE_PROCESS_ENTER
| wxTE_PROCESS_TAB
| wxNO_BORDER
;
1183 m_control
= new wxTextCtrl(parent
, id
, wxEmptyString
,
1184 wxDefaultPosition
, wxDefaultSize
,
1187 // set max length allowed in the textctrl, if the parameter was set
1188 if ( m_maxChars
!= 0 )
1190 Text()->SetMaxLength(m_maxChars
);
1193 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1196 void wxGridCellTextEditor::PaintBackground(const wxRect
& WXUNUSED(rectCell
),
1197 wxGridCellAttr
* WXUNUSED(attr
))
1199 // as we fill the entire client area,
1200 // don't do anything here to minimize flicker
1203 void wxGridCellTextEditor::SetSize(const wxRect
& rectOrig
)
1205 wxRect
rect(rectOrig
);
1207 // Make the edit control large enough to allow for internal margins
1209 // TODO: remove this if the text ctrl sizing is improved esp. for unix
1211 #if defined(__WXGTK__)
1219 #elif defined(__WXMSW__)
1233 int extra_x
= ( rect
.x
> 2 ) ? 2 : 1;
1234 int extra_y
= ( rect
.y
> 2 ) ? 2 : 1;
1236 #if defined(__WXMOTIF__)
1241 rect
.SetLeft( wxMax(0, rect
.x
- extra_x
) );
1242 rect
.SetTop( wxMax(0, rect
.y
- extra_y
) );
1243 rect
.SetRight( rect
.GetRight() + 2 * extra_x
);
1244 rect
.SetBottom( rect
.GetBottom() + 2 * extra_y
);
1247 wxGridCellEditor::SetSize(rect
);
1250 void wxGridCellTextEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1252 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1254 m_startValue
= grid
->GetTable()->GetValue(row
, col
);
1256 DoBeginEdit(m_startValue
);
1259 void wxGridCellTextEditor::DoBeginEdit(const wxString
& startValue
)
1261 Text()->SetValue(startValue
);
1262 Text()->SetInsertionPointEnd();
1263 Text()->SetSelection(-1, -1);
1267 bool wxGridCellTextEditor::EndEdit(int row
, int col
, wxGrid
* grid
)
1269 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1271 bool changed
= false;
1272 wxString value
= Text()->GetValue();
1273 if (value
!= m_startValue
)
1277 grid
->GetTable()->SetValue(row
, col
, value
);
1279 m_startValue
= wxEmptyString
;
1281 // No point in setting the text of the hidden control
1282 //Text()->SetValue(m_startValue);
1287 void wxGridCellTextEditor::Reset()
1289 wxASSERT_MSG(m_control
, wxT("The wxGridCellEditor must be created first!"));
1291 DoReset(m_startValue
);
1294 void wxGridCellTextEditor::DoReset(const wxString
& startValue
)
1296 Text()->SetValue(startValue
);
1297 Text()->SetInsertionPointEnd();
1300 bool wxGridCellTextEditor::IsAcceptedKey(wxKeyEvent
& event
)
1302 return wxGridCellEditor::IsAcceptedKey(event
);
1305 void wxGridCellTextEditor::StartingKey(wxKeyEvent
& event
)
1307 // Since this is now happening in the EVT_CHAR event EmulateKeyPress is no
1308 // longer an appropriate way to get the character into the text control.
1309 // Do it ourselves instead. We know that if we get this far that we have
1310 // a valid character, so not a whole lot of testing needs to be done.
1312 wxTextCtrl
* tc
= Text();
1317 ch
= event
.GetUnicodeKey();
1319 ch
= (wxChar
)event
.GetKeyCode();
1321 ch
= (wxChar
)event
.GetKeyCode();
1327 // delete the character at the cursor
1328 pos
= tc
->GetInsertionPoint();
1329 if (pos
< tc
->GetLastPosition())
1330 tc
->Remove(pos
, pos
+ 1);
1334 // delete the character before the cursor
1335 pos
= tc
->GetInsertionPoint();
1337 tc
->Remove(pos
- 1, pos
);
1346 void wxGridCellTextEditor::HandleReturn( wxKeyEvent
&
1347 WXUNUSED_GTK(WXUNUSED_MOTIF(event
)) )
1349 #if defined(__WXMOTIF__) || defined(__WXGTK__)
1350 // wxMotif needs a little extra help...
1351 size_t pos
= (size_t)( Text()->GetInsertionPoint() );
1352 wxString
s( Text()->GetValue() );
1353 s
= s
.Left(pos
) + wxT("\n") + s
.Mid(pos
);
1354 Text()->SetValue(s
);
1355 Text()->SetInsertionPoint( pos
);
1357 // the other ports can handle a Return key press
1363 void wxGridCellTextEditor::SetParameters(const wxString
& params
)
1373 if ( params
.ToLong(&tmp
) )
1375 m_maxChars
= (size_t)tmp
;
1379 wxLogDebug( _T("Invalid wxGridCellTextEditor parameter string '%s' ignored"), params
.c_str() );
1384 // return the value in the text control
1385 wxString
wxGridCellTextEditor::GetValue() const
1387 return Text()->GetValue();
1390 // ----------------------------------------------------------------------------
1391 // wxGridCellNumberEditor
1392 // ----------------------------------------------------------------------------
1394 wxGridCellNumberEditor::wxGridCellNumberEditor(int min
, int max
)
1400 void wxGridCellNumberEditor::Create(wxWindow
* parent
,
1402 wxEvtHandler
* evtHandler
)
1407 // create a spin ctrl
1408 m_control
= new wxSpinCtrl(parent
, wxID_ANY
, wxEmptyString
,
1409 wxDefaultPosition
, wxDefaultSize
,
1413 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1418 // just a text control
1419 wxGridCellTextEditor::Create(parent
, id
, evtHandler
);
1421 #if wxUSE_VALIDATORS
1422 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC
));
1427 void wxGridCellNumberEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1429 // first get the value
1430 wxGridTableBase
*table
= grid
->GetTable();
1431 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
1433 m_valueOld
= table
->GetValueAsLong(row
, col
);
1438 wxString sValue
= table
->GetValue(row
, col
);
1439 if (! sValue
.ToLong(&m_valueOld
) && ! sValue
.empty())
1441 wxFAIL_MSG( _T("this cell doesn't have numeric value") );
1449 Spin()->SetValue((int)m_valueOld
);
1455 DoBeginEdit(GetString());
1459 bool wxGridCellNumberEditor::EndEdit(int row
, int col
,
1468 value
= Spin()->GetValue();
1469 if ( value
== m_valueOld
)
1472 text
.Printf(wxT("%ld"), value
);
1474 else // using unconstrained input
1475 #endif // wxUSE_SPINCTRL
1477 const wxString
textOld(grid
->GetCellValue(row
, col
));
1478 text
= Text()->GetValue();
1481 if ( textOld
.empty() )
1484 else // non-empty text now (maybe 0)
1486 if ( !text
.ToLong(&value
) )
1489 // if value == m_valueOld == 0 but old text was "" and new one is
1490 // "0" something still did change
1491 if ( value
== m_valueOld
&& (value
|| !textOld
.empty()) )
1496 wxGridTableBase
* const table
= grid
->GetTable();
1497 if ( table
->CanSetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
1498 table
->SetValueAsLong(row
, col
, value
);
1500 table
->SetValue(row
, col
, text
);
1505 void wxGridCellNumberEditor::Reset()
1510 Spin()->SetValue((int)m_valueOld
);
1515 DoReset(GetString());
1519 bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent
& event
)
1521 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1523 int keycode
= event
.GetKeyCode();
1524 if ( (keycode
< 128) &&
1525 (wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-'))
1534 void wxGridCellNumberEditor::StartingKey(wxKeyEvent
& event
)
1536 int keycode
= event
.GetKeyCode();
1539 if ( wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-')
1541 wxGridCellTextEditor::StartingKey(event
);
1543 // skip Skip() below
1550 if ( wxIsdigit(keycode
) )
1552 wxSpinCtrl
* spin
= (wxSpinCtrl
*)m_control
;
1553 spin
->SetValue(keycode
- '0');
1554 spin
->SetSelection(1,1);
1563 void wxGridCellNumberEditor::SetParameters(const wxString
& params
)
1574 if ( params
.BeforeFirst(_T(',')).ToLong(&tmp
) )
1578 if ( params
.AfterFirst(_T(',')).ToLong(&tmp
) )
1582 // skip the error message below
1587 wxLogDebug(_T("Invalid wxGridCellNumberEditor parameter string '%s' ignored"), params
.c_str());
1591 // return the value in the spin control if it is there (the text control otherwise)
1592 wxString
wxGridCellNumberEditor::GetValue() const
1599 long value
= Spin()->GetValue();
1600 s
.Printf(wxT("%ld"), value
);
1605 s
= Text()->GetValue();
1611 // ----------------------------------------------------------------------------
1612 // wxGridCellFloatEditor
1613 // ----------------------------------------------------------------------------
1615 wxGridCellFloatEditor::wxGridCellFloatEditor(int width
, int precision
)
1618 m_precision
= precision
;
1621 void wxGridCellFloatEditor::Create(wxWindow
* parent
,
1623 wxEvtHandler
* evtHandler
)
1625 wxGridCellTextEditor::Create(parent
, id
, evtHandler
);
1627 #if wxUSE_VALIDATORS
1628 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC
));
1632 void wxGridCellFloatEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1634 // first get the value
1635 wxGridTableBase
* const table
= grid
->GetTable();
1636 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
1638 m_valueOld
= table
->GetValueAsDouble(row
, col
);
1644 const wxString value
= table
->GetValue(row
, col
);
1645 if ( !value
.empty() )
1647 if ( !value
.ToDouble(&m_valueOld
) )
1649 wxFAIL_MSG( _T("this cell doesn't have float value") );
1655 DoBeginEdit(GetString());
1658 bool wxGridCellFloatEditor::EndEdit(int row
, int col
, wxGrid
* grid
)
1660 const wxString
text(Text()->GetValue()),
1661 textOld(grid
->GetCellValue(row
, col
));
1664 if ( !text
.empty() )
1666 if ( !text
.ToDouble(&value
) )
1669 else // new value is empty string
1671 if ( textOld
.empty() )
1672 return false; // nothing changed
1677 // the test for empty strings ensures that we don't skip the value setting
1678 // when "" is replaced by "0" or vice versa as "" numeric value is also 0.
1679 if ( wxIsSameDouble(value
, m_valueOld
) && !text
.empty() && !textOld
.empty() )
1680 return false; // nothing changed
1682 wxGridTableBase
* const table
= grid
->GetTable();
1684 if ( table
->CanSetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
1685 table
->SetValueAsDouble(row
, col
, value
);
1687 table
->SetValue(row
, col
, text
);
1692 void wxGridCellFloatEditor::Reset()
1694 DoReset(GetString());
1697 void wxGridCellFloatEditor::StartingKey(wxKeyEvent
& event
)
1699 int keycode
= event
.GetKeyCode();
1701 tmpbuf
[0] = (char) keycode
;
1703 wxString
strbuf(tmpbuf
, *wxConvCurrent
);
1706 bool is_decimal_point
= ( strbuf
==
1707 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT
, wxLOCALE_CAT_NUMBER
) );
1709 bool is_decimal_point
= ( strbuf
== _T(".") );
1712 if ( wxIsdigit(keycode
) || keycode
== '+' || keycode
== '-'
1713 || is_decimal_point
)
1715 wxGridCellTextEditor::StartingKey(event
);
1717 // skip Skip() below
1724 void wxGridCellFloatEditor::SetParameters(const wxString
& params
)
1735 if ( params
.BeforeFirst(_T(',')).ToLong(&tmp
) )
1739 if ( params
.AfterFirst(_T(',')).ToLong(&tmp
) )
1741 m_precision
= (int)tmp
;
1743 // skip the error message below
1748 wxLogDebug(_T("Invalid wxGridCellFloatEditor parameter string '%s' ignored"), params
.c_str());
1752 wxString
wxGridCellFloatEditor::GetString() const
1755 if ( m_precision
== -1 && m_width
!= -1)
1757 // default precision
1758 fmt
.Printf(_T("%%%d.f"), m_width
);
1760 else if ( m_precision
!= -1 && m_width
== -1)
1763 fmt
.Printf(_T("%%.%df"), m_precision
);
1765 else if ( m_precision
!= -1 && m_width
!= -1 )
1767 fmt
.Printf(_T("%%%d.%df"), m_width
, m_precision
);
1771 // default width/precision
1775 return wxString::Format(fmt
, m_valueOld
);
1778 bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent
& event
)
1780 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1782 const int keycode
= event
.GetKeyCode();
1783 if ( isascii(keycode
) )
1786 tmpbuf
[0] = (char) keycode
;
1788 wxString
strbuf(tmpbuf
, *wxConvCurrent
);
1791 const wxString decimalPoint
=
1792 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT
, wxLOCALE_CAT_NUMBER
);
1794 const wxString
decimalPoint(_T('.'));
1797 // accept digits, 'e' as in '1e+6', also '-', '+', and '.'
1798 if ( wxIsdigit(keycode
) ||
1799 tolower(keycode
) == 'e' ||
1800 keycode
== decimalPoint
||
1812 #endif // wxUSE_TEXTCTRL
1816 // ----------------------------------------------------------------------------
1817 // wxGridCellBoolEditor
1818 // ----------------------------------------------------------------------------
1820 // the default values for GetValue()
1821 wxString
wxGridCellBoolEditor::ms_stringValues
[2] = { _T(""), _T("1") };
1823 void wxGridCellBoolEditor::Create(wxWindow
* parent
,
1825 wxEvtHandler
* evtHandler
)
1827 m_control
= new wxCheckBox(parent
, id
, wxEmptyString
,
1828 wxDefaultPosition
, wxDefaultSize
,
1831 wxGridCellEditor::Create(parent
, id
, evtHandler
);
1834 void wxGridCellBoolEditor::SetSize(const wxRect
& r
)
1836 bool resize
= false;
1837 wxSize size
= m_control
->GetSize();
1838 wxCoord minSize
= wxMin(r
.width
, r
.height
);
1840 // check if the checkbox is not too big/small for this cell
1841 wxSize sizeBest
= m_control
->GetBestSize();
1842 if ( !(size
== sizeBest
) )
1844 // reset to default size if it had been made smaller
1850 if ( size
.x
>= minSize
|| size
.y
>= minSize
)
1852 // leave 1 pixel margin
1853 size
.x
= size
.y
= minSize
- 2;
1860 m_control
->SetSize(size
);
1863 // position it in the centre of the rectangle (TODO: support alignment?)
1865 #if defined(__WXGTK__) || defined (__WXMOTIF__)
1866 // the checkbox without label still has some space to the right in wxGTK,
1867 // so shift it to the right
1869 #elif defined(__WXMSW__)
1870 // here too, but in other way
1875 int hAlign
= wxALIGN_CENTRE
;
1876 int vAlign
= wxALIGN_CENTRE
;
1878 GetCellAttr()->GetAlignment(& hAlign
, & vAlign
);
1881 if (hAlign
== wxALIGN_LEFT
)
1889 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1891 else if (hAlign
== wxALIGN_RIGHT
)
1893 x
= r
.x
+ r
.width
- size
.x
- 2;
1894 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1896 else if (hAlign
== wxALIGN_CENTRE
)
1898 x
= r
.x
+ r
.width
/ 2 - size
.x
/ 2;
1899 y
= r
.y
+ r
.height
/ 2 - size
.y
/ 2;
1902 m_control
->Move(x
, y
);
1905 void wxGridCellBoolEditor::Show(bool show
, wxGridCellAttr
*attr
)
1907 m_control
->Show(show
);
1911 wxColour colBg
= attr
? attr
->GetBackgroundColour() : *wxLIGHT_GREY
;
1912 CBox()->SetBackgroundColour(colBg
);
1916 void wxGridCellBoolEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
1918 wxASSERT_MSG(m_control
,
1919 wxT("The wxGridCellEditor must be created first!"));
1921 if (grid
->GetTable()->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
))
1923 m_startValue
= grid
->GetTable()->GetValueAsBool(row
, col
);
1927 wxString
cellval( grid
->GetTable()->GetValue(row
, col
) );
1929 if ( cellval
== ms_stringValues
[false] )
1930 m_startValue
= false;
1931 else if ( cellval
== ms_stringValues
[true] )
1932 m_startValue
= true;
1935 // do not try to be smart here and convert it to true or false
1936 // because we'll still overwrite it with something different and
1937 // this risks to be very surprising for the user code, let them
1939 wxFAIL_MSG( _T("invalid value for a cell with bool editor!") );
1943 CBox()->SetValue(m_startValue
);
1947 bool wxGridCellBoolEditor::EndEdit(int row
, int col
,
1950 wxASSERT_MSG(m_control
,
1951 wxT("The wxGridCellEditor must be created first!"));
1953 bool changed
= false;
1954 bool value
= CBox()->GetValue();
1955 if ( value
!= m_startValue
)
1960 wxGridTableBase
* const table
= grid
->GetTable();
1961 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
) )
1962 table
->SetValueAsBool(row
, col
, value
);
1964 table
->SetValue(row
, col
, GetValue());
1970 void wxGridCellBoolEditor::Reset()
1972 wxASSERT_MSG(m_control
,
1973 wxT("The wxGridCellEditor must be created first!"));
1975 CBox()->SetValue(m_startValue
);
1978 void wxGridCellBoolEditor::StartingClick()
1980 CBox()->SetValue(!CBox()->GetValue());
1983 bool wxGridCellBoolEditor::IsAcceptedKey(wxKeyEvent
& event
)
1985 if ( wxGridCellEditor::IsAcceptedKey(event
) )
1987 int keycode
= event
.GetKeyCode();
2000 void wxGridCellBoolEditor::StartingKey(wxKeyEvent
& event
)
2002 int keycode
= event
.GetKeyCode();
2006 CBox()->SetValue(!CBox()->GetValue());
2010 CBox()->SetValue(true);
2014 CBox()->SetValue(false);
2019 wxString
wxGridCellBoolEditor::GetValue() const
2021 return ms_stringValues
[CBox()->GetValue()];
2025 wxGridCellBoolEditor::UseStringValues(const wxString
& valueTrue
,
2026 const wxString
& valueFalse
)
2028 ms_stringValues
[false] = valueFalse
;
2029 ms_stringValues
[true] = valueTrue
;
2033 wxGridCellBoolEditor::IsTrueValue(const wxString
& value
)
2035 return value
== ms_stringValues
[true];
2038 #endif // wxUSE_CHECKBOX
2042 // ----------------------------------------------------------------------------
2043 // wxGridCellChoiceEditor
2044 // ----------------------------------------------------------------------------
2046 wxGridCellChoiceEditor::wxGridCellChoiceEditor(const wxArrayString
& choices
,
2048 : m_choices(choices
),
2049 m_allowOthers(allowOthers
) { }
2051 wxGridCellChoiceEditor::wxGridCellChoiceEditor(size_t count
,
2052 const wxString choices
[],
2054 : m_allowOthers(allowOthers
)
2058 m_choices
.Alloc(count
);
2059 for ( size_t n
= 0; n
< count
; n
++ )
2061 m_choices
.Add(choices
[n
]);
2066 wxGridCellEditor
*wxGridCellChoiceEditor::Clone() const
2068 wxGridCellChoiceEditor
*editor
= new wxGridCellChoiceEditor
;
2069 editor
->m_allowOthers
= m_allowOthers
;
2070 editor
->m_choices
= m_choices
;
2075 void wxGridCellChoiceEditor::Create(wxWindow
* parent
,
2077 wxEvtHandler
* evtHandler
)
2079 int style
= wxTE_PROCESS_ENTER
|
2083 if ( !m_allowOthers
)
2084 style
|= wxCB_READONLY
;
2085 m_control
= new wxComboBox(parent
, id
, wxEmptyString
,
2086 wxDefaultPosition
, wxDefaultSize
,
2090 wxGridCellEditor::Create(parent
, id
, evtHandler
);
2093 void wxGridCellChoiceEditor::PaintBackground(const wxRect
& rectCell
,
2094 wxGridCellAttr
* attr
)
2096 // as we fill the entire client area, don't do anything here to minimize
2099 // TODO: It doesn't actually fill the client area since the height of a
2100 // combo always defaults to the standard. Until someone has time to
2101 // figure out the right rectangle to paint, just do it the normal way.
2102 wxGridCellEditor::PaintBackground(rectCell
, attr
);
2105 void wxGridCellChoiceEditor::BeginEdit(int row
, int col
, wxGrid
* grid
)
2107 wxASSERT_MSG(m_control
,
2108 wxT("The wxGridCellEditor must be created first!"));
2110 wxGridCellEditorEvtHandler
* evtHandler
= NULL
;
2112 evtHandler
= wxDynamicCast(m_control
->GetEventHandler(), wxGridCellEditorEvtHandler
);
2114 // Don't immediately end if we get a kill focus event within BeginEdit
2116 evtHandler
->SetInSetFocus(true);
2118 m_startValue
= grid
->GetTable()->GetValue(row
, col
);
2120 Reset(); // this updates combo box to correspond to m_startValue
2122 Combo()->SetFocus();
2126 // When dropping down the menu, a kill focus event
2127 // happens after this point, so we can't reset the flag yet.
2128 #if !defined(__WXGTK20__)
2129 evtHandler
->SetInSetFocus(false);
2134 bool wxGridCellChoiceEditor::EndEdit(int row
, int col
,
2137 wxString value
= Combo()->GetValue();
2138 if ( value
== m_startValue
)
2141 grid
->GetTable()->SetValue(row
, col
, value
);
2146 void wxGridCellChoiceEditor::Reset()
2150 Combo()->SetValue(m_startValue
);
2151 Combo()->SetInsertionPointEnd();
2153 else // the combobox is read-only
2155 // find the right position, or default to the first if not found
2156 int pos
= Combo()->FindString(m_startValue
);
2157 if (pos
== wxNOT_FOUND
)
2159 Combo()->SetSelection(pos
);
2163 void wxGridCellChoiceEditor::SetParameters(const wxString
& params
)
2173 wxStringTokenizer
tk(params
, _T(','));
2174 while ( tk
.HasMoreTokens() )
2176 m_choices
.Add(tk
.GetNextToken());
2180 // return the value in the text control
2181 wxString
wxGridCellChoiceEditor::GetValue() const
2183 return Combo()->GetValue();
2186 #endif // wxUSE_COMBOBOX
2188 // ----------------------------------------------------------------------------
2189 // wxGridCellEditorEvtHandler
2190 // ----------------------------------------------------------------------------
2192 void wxGridCellEditorEvtHandler::OnKillFocus(wxFocusEvent
& event
)
2194 // Don't disable the cell if we're just starting to edit it
2199 m_grid
->DisableCellEditControl();
2204 void wxGridCellEditorEvtHandler::OnKeyDown(wxKeyEvent
& event
)
2206 switch ( event
.GetKeyCode() )
2210 m_grid
->DisableCellEditControl();
2214 m_grid
->GetEventHandler()->ProcessEvent( event
);
2218 case WXK_NUMPAD_ENTER
:
2219 if (!m_grid
->GetEventHandler()->ProcessEvent(event
))
2220 m_editor
->HandleReturn(event
);
2229 void wxGridCellEditorEvtHandler::OnChar(wxKeyEvent
& event
)
2231 int row
= m_grid
->GetGridCursorRow();
2232 int col
= m_grid
->GetGridCursorCol();
2233 wxRect rect
= m_grid
->CellToRect( row
, col
);
2235 m_grid
->GetGridWindow()->GetClientSize( &cw
, &ch
);
2237 // if cell width is smaller than grid client area, cell is wholly visible
2238 bool wholeCellVisible
= (rect
.GetWidth() < cw
);
2240 switch ( event
.GetKeyCode() )
2245 case WXK_NUMPAD_ENTER
:
2250 if ( wholeCellVisible
)
2252 // no special processing needed...
2257 // do special processing for partly visible cell...
2259 // get the widths of all cells previous to this one
2261 for ( int i
= 0; i
< col
; i
++ )
2263 colXPos
+= m_grid
->GetColSize(i
);
2266 int xUnit
= 1, yUnit
= 1;
2267 m_grid
->GetScrollPixelsPerUnit(&xUnit
, &yUnit
);
2270 m_grid
->Scroll(colXPos
/ xUnit
- 1, m_grid
->GetScrollPos(wxVERTICAL
));
2274 m_grid
->Scroll(colXPos
/ xUnit
, m_grid
->GetScrollPos(wxVERTICAL
));
2282 if ( wholeCellVisible
)
2284 // no special processing needed...
2289 // do special processing for partly visible cell...
2292 wxString value
= m_grid
->GetCellValue(row
, col
);
2293 if ( wxEmptyString
!= value
)
2295 // get width of cell CONTENTS (text)
2297 wxFont font
= m_grid
->GetCellFont(row
, col
);
2298 m_grid
->GetTextExtent(value
, &textWidth
, &y
, NULL
, NULL
, &font
);
2300 // try to RIGHT align the text by scrolling
2301 int client_right
= m_grid
->GetGridWindow()->GetClientSize().GetWidth();
2303 // (m_grid->GetScrollLineX()*2) is a factor for not scrolling to far,
2304 // otherwise the last part of the cell content might be hidden below the scroll bar
2305 // FIXME: maybe there is a more suitable correction?
2306 textWidth
-= (client_right
- (m_grid
->GetScrollLineX() * 2));
2307 if ( textWidth
< 0 )
2313 // get the widths of all cells previous to this one
2315 for ( int i
= 0; i
< col
; i
++ )
2317 colXPos
+= m_grid
->GetColSize(i
);
2320 // and add the (modified) text width of the cell contents
2321 // as we'd like to see the last part of the cell contents
2322 colXPos
+= textWidth
;
2324 int xUnit
= 1, yUnit
= 1;
2325 m_grid
->GetScrollPixelsPerUnit(&xUnit
, &yUnit
);
2326 m_grid
->Scroll(colXPos
/ xUnit
- 1, m_grid
->GetScrollPos(wxVERTICAL
));
2337 // ----------------------------------------------------------------------------
2338 // wxGridCellWorker is an (almost) empty common base class for
2339 // wxGridCellRenderer and wxGridCellEditor managing ref counting
2340 // ----------------------------------------------------------------------------
2342 void wxGridCellWorker::SetParameters(const wxString
& WXUNUSED(params
))
2347 wxGridCellWorker::~wxGridCellWorker()
2351 // ============================================================================
2353 // ============================================================================
2355 // ----------------------------------------------------------------------------
2356 // wxGridCellRenderer
2357 // ----------------------------------------------------------------------------
2359 void wxGridCellRenderer::Draw(wxGrid
& grid
,
2360 wxGridCellAttr
& attr
,
2363 int WXUNUSED(row
), int WXUNUSED(col
),
2366 dc
.SetBackgroundMode( wxBRUSHSTYLE_SOLID
);
2369 if ( grid
.IsEnabled() )
2373 if ( grid
.HasFocus() )
2374 clr
= grid
.GetSelectionBackground();
2376 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW
);
2380 clr
= attr
.GetBackgroundColour();
2383 else // grey out fields if the grid is disabled
2385 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE
);
2389 dc
.SetPen( *wxTRANSPARENT_PEN
);
2390 dc
.DrawRectangle(rect
);
2393 // ----------------------------------------------------------------------------
2394 // wxGridCellStringRenderer
2395 // ----------------------------------------------------------------------------
2397 void wxGridCellStringRenderer::SetTextColoursAndFont(const wxGrid
& grid
,
2398 const wxGridCellAttr
& attr
,
2402 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
2404 // TODO some special colours for attr.IsReadOnly() case?
2406 // different coloured text when the grid is disabled
2407 if ( grid
.IsEnabled() )
2412 if ( grid
.HasFocus() )
2413 clr
= grid
.GetSelectionBackground();
2415 clr
= wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW
);
2416 dc
.SetTextBackground( clr
);
2417 dc
.SetTextForeground( grid
.GetSelectionForeground() );
2421 dc
.SetTextBackground( attr
.GetBackgroundColour() );
2422 dc
.SetTextForeground( attr
.GetTextColour() );
2427 dc
.SetTextBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE
));
2428 dc
.SetTextForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT
));
2431 dc
.SetFont( attr
.GetFont() );
2434 wxSize
wxGridCellStringRenderer::DoGetBestSize(const wxGridCellAttr
& attr
,
2436 const wxString
& text
)
2438 wxCoord x
= 0, y
= 0, max_x
= 0;
2439 dc
.SetFont(attr
.GetFont());
2440 wxStringTokenizer
tk(text
, _T('\n'));
2441 while ( tk
.HasMoreTokens() )
2443 dc
.GetTextExtent(tk
.GetNextToken(), &x
, &y
);
2444 max_x
= wxMax(max_x
, x
);
2447 y
*= 1 + text
.Freq(wxT('\n')); // multiply by the number of lines.
2449 return wxSize(max_x
, y
);
2452 wxSize
wxGridCellStringRenderer::GetBestSize(wxGrid
& grid
,
2453 wxGridCellAttr
& attr
,
2457 return DoGetBestSize(attr
, dc
, grid
.GetCellValue(row
, col
));
2460 void wxGridCellStringRenderer::Draw(wxGrid
& grid
,
2461 wxGridCellAttr
& attr
,
2463 const wxRect
& rectCell
,
2467 wxRect rect
= rectCell
;
2470 // erase only this cells background, overflow cells should have been erased
2471 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2474 attr
.GetAlignment(&hAlign
, &vAlign
);
2476 int overflowCols
= 0;
2478 if (attr
.GetOverflow())
2480 int cols
= grid
.GetNumberCols();
2481 int best_width
= GetBestSize(grid
,attr
,dc
,row
,col
).GetWidth();
2482 int cell_rows
, cell_cols
;
2483 attr
.GetSize( &cell_rows
, &cell_cols
); // shouldn't get here if <= 0
2484 if ((best_width
> rectCell
.width
) && (col
< cols
) && grid
.GetTable())
2486 int i
, c_cols
, c_rows
;
2487 for (i
= col
+cell_cols
; i
< cols
; i
++)
2489 bool is_empty
= true;
2490 for (int j
=row
; j
< row
+ cell_rows
; j
++)
2492 // check w/ anchor cell for multicell block
2493 grid
.GetCellSize(j
, i
, &c_rows
, &c_cols
);
2496 if (!grid
.GetTable()->IsEmptyCell(j
+ c_rows
, i
))
2505 rect
.width
+= grid
.GetColSize(i
);
2513 if (rect
.width
>= best_width
)
2517 overflowCols
= i
- col
- cell_cols
+ 1;
2518 if (overflowCols
>= cols
)
2519 overflowCols
= cols
- 1;
2522 if (overflowCols
> 0) // redraw overflow cells w/ proper hilight
2524 hAlign
= wxALIGN_LEFT
; // if oveflowed then it's left aligned
2526 clip
.x
+= rectCell
.width
;
2527 // draw each overflow cell individually
2528 int col_end
= col
+ cell_cols
+ overflowCols
;
2529 if (col_end
>= grid
.GetNumberCols())
2530 col_end
= grid
.GetNumberCols() - 1;
2531 for (int i
= col
+ cell_cols
; i
<= col_end
; i
++)
2533 clip
.width
= grid
.GetColSize(i
) - 1;
2534 dc
.DestroyClippingRegion();
2535 dc
.SetClippingRegion(clip
);
2537 SetTextColoursAndFont(grid
, attr
, dc
,
2538 grid
.IsInSelection(row
,i
));
2540 grid
.DrawTextRectangle(dc
, grid
.GetCellValue(row
, col
),
2541 rect
, hAlign
, vAlign
);
2542 clip
.x
+= grid
.GetColSize(i
) - 1;
2548 dc
.DestroyClippingRegion();
2552 // now we only have to draw the text
2553 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2555 grid
.DrawTextRectangle(dc
, grid
.GetCellValue(row
, col
),
2556 rect
, hAlign
, vAlign
);
2559 // ----------------------------------------------------------------------------
2560 // wxGridCellNumberRenderer
2561 // ----------------------------------------------------------------------------
2563 wxString
wxGridCellNumberRenderer::GetString(const wxGrid
& grid
, int row
, int col
)
2565 wxGridTableBase
*table
= grid
.GetTable();
2567 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_NUMBER
) )
2569 text
.Printf(_T("%ld"), table
->GetValueAsLong(row
, col
));
2573 text
= table
->GetValue(row
, col
);
2579 void wxGridCellNumberRenderer::Draw(wxGrid
& grid
,
2580 wxGridCellAttr
& attr
,
2582 const wxRect
& rectCell
,
2586 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2588 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2590 // draw the text right aligned by default
2592 attr
.GetAlignment(&hAlign
, &vAlign
);
2593 hAlign
= wxALIGN_RIGHT
;
2595 wxRect rect
= rectCell
;
2598 grid
.DrawTextRectangle(dc
, GetString(grid
, row
, col
), rect
, hAlign
, vAlign
);
2601 wxSize
wxGridCellNumberRenderer::GetBestSize(wxGrid
& grid
,
2602 wxGridCellAttr
& attr
,
2606 return DoGetBestSize(attr
, dc
, GetString(grid
, row
, col
));
2609 // ----------------------------------------------------------------------------
2610 // wxGridCellFloatRenderer
2611 // ----------------------------------------------------------------------------
2613 wxGridCellFloatRenderer::wxGridCellFloatRenderer(int width
, int precision
)
2616 SetPrecision(precision
);
2619 wxGridCellRenderer
*wxGridCellFloatRenderer::Clone() const
2621 wxGridCellFloatRenderer
*renderer
= new wxGridCellFloatRenderer
;
2622 renderer
->m_width
= m_width
;
2623 renderer
->m_precision
= m_precision
;
2624 renderer
->m_format
= m_format
;
2629 wxString
wxGridCellFloatRenderer::GetString(const wxGrid
& grid
, int row
, int col
)
2631 wxGridTableBase
*table
= grid
.GetTable();
2636 if ( table
->CanGetValueAs(row
, col
, wxGRID_VALUE_FLOAT
) )
2638 val
= table
->GetValueAsDouble(row
, col
);
2643 text
= table
->GetValue(row
, col
);
2644 hasDouble
= text
.ToDouble(&val
);
2651 if ( m_width
== -1 )
2653 if ( m_precision
== -1 )
2655 // default width/precision
2656 m_format
= _T("%f");
2660 m_format
.Printf(_T("%%.%df"), m_precision
);
2663 else if ( m_precision
== -1 )
2665 // default precision
2666 m_format
.Printf(_T("%%%d.f"), m_width
);
2670 m_format
.Printf(_T("%%%d.%df"), m_width
, m_precision
);
2674 text
.Printf(m_format
, val
);
2677 //else: text already contains the string
2682 void wxGridCellFloatRenderer::Draw(wxGrid
& grid
,
2683 wxGridCellAttr
& attr
,
2685 const wxRect
& rectCell
,
2689 wxGridCellRenderer::Draw(grid
, attr
, dc
, rectCell
, row
, col
, isSelected
);
2691 SetTextColoursAndFont(grid
, attr
, dc
, isSelected
);
2693 // draw the text right aligned by default
2695 attr
.GetAlignment(&hAlign
, &vAlign
);
2696 hAlign
= wxALIGN_RIGHT
;
2698 wxRect rect
= rectCell
;
2701 grid
.DrawTextRectangle(dc
, GetString(grid
, row
, col
), rect
, hAlign
, vAlign
);
2704 wxSize
wxGridCellFloatRenderer::GetBestSize(wxGrid
& grid
,
2705 wxGridCellAttr
& attr
,
2709 return DoGetBestSize(attr
, dc
, GetString(grid
, row
, col
));
2712 void wxGridCellFloatRenderer::SetParameters(const wxString
& params
)
2716 // reset to defaults
2722 wxString tmp
= params
.BeforeFirst(_T(','));
2726 if ( tmp
.ToLong(&width
) )
2728 SetWidth((int)width
);
2732 wxLogDebug(_T("Invalid wxGridCellFloatRenderer width parameter string '%s ignored"), params
.c_str());
2736 tmp
= params
.AfterFirst(_T(','));
2740 if ( tmp
.ToLong(&precision
) )
2742 SetPrecision((int)precision
);
2746 wxLogDebug(_T("Invalid wxGridCellFloatRenderer precision parameter string '%s ignored"), params
.c_str());
2752 // ----------------------------------------------------------------------------
2753 // wxGridCellBoolRenderer
2754 // ----------------------------------------------------------------------------
2756 wxSize
wxGridCellBoolRenderer::ms_sizeCheckMark
;
2758 // FIXME these checkbox size calculations are really ugly...
2760 // between checkmark and box
2761 static const wxCoord wxGRID_CHECKMARK_MARGIN
= 2;
2763 wxSize
wxGridCellBoolRenderer::GetBestSize(wxGrid
& grid
,
2764 wxGridCellAttr
& WXUNUSED(attr
),
2769 // compute it only once (no locks for MT safeness in GUI thread...)
2770 if ( !ms_sizeCheckMark
.x
)
2772 // get checkbox size
2773 wxCheckBox
*checkbox
= new wxCheckBox(&grid
, wxID_ANY
, wxEmptyString
);
2774 wxSize size
= checkbox
->GetBestSize();
2775 wxCoord checkSize
= size
.y
+ 2 * wxGRID_CHECKMARK_MARGIN
;
2777 #if defined(__WXMOTIF__)
2778 checkSize
-= size
.y
/ 2;
2783 ms_sizeCheckMark
.x
= ms_sizeCheckMark
.y
= checkSize
;
2786 return ms_sizeCheckMark
;
2789 void wxGridCellBoolRenderer::Draw(wxGrid
& grid
,
2790 wxGridCellAttr
& attr
,
2796 wxGridCellRenderer::Draw(grid
, attr
, dc
, rect
, row
, col
, isSelected
);
2798 // draw a check mark in the centre (ignoring alignment - TODO)
2799 wxSize size
= GetBestSize(grid
, attr
, dc
, row
, col
);
2801 // don't draw outside the cell
2802 wxCoord minSize
= wxMin(rect
.width
, rect
.height
);
2803 if ( size
.x
>= minSize
|| size
.y
>= minSize
)
2805 // and even leave (at least) 1 pixel margin
2806 size
.x
= size
.y
= minSize
;
2809 // draw a border around checkmark
2811 attr
.GetAlignment(&hAlign
, &vAlign
);
2814 if (hAlign
== wxALIGN_CENTRE
)
2816 rectBorder
.x
= rect
.x
+ rect
.width
/ 2 - size
.x
/ 2;
2817 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2818 rectBorder
.width
= size
.x
;
2819 rectBorder
.height
= size
.y
;
2821 else if (hAlign
== wxALIGN_LEFT
)
2823 rectBorder
.x
= rect
.x
+ 2;
2824 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2825 rectBorder
.width
= size
.x
;
2826 rectBorder
.height
= size
.y
;
2828 else if (hAlign
== wxALIGN_RIGHT
)
2830 rectBorder
.x
= rect
.x
+ rect
.width
- size
.x
- 2;
2831 rectBorder
.y
= rect
.y
+ rect
.height
/ 2 - size
.y
/ 2;
2832 rectBorder
.width
= size
.x
;
2833 rectBorder
.height
= size
.y
;
2837 if ( grid
.GetTable()->CanGetValueAs(row
, col
, wxGRID_VALUE_BOOL
) )
2839 value
= grid
.GetTable()->GetValueAsBool(row
, col
);
2843 wxString
cellval( grid
.GetTable()->GetValue(row
, col
) );
2844 value
= wxGridCellBoolEditor::IsTrueValue(cellval
);
2849 flags
|= wxCONTROL_CHECKED
;
2851 wxRendererNative::Get().DrawCheckBox( &grid
, dc
, rectBorder
, flags
);
2854 // ----------------------------------------------------------------------------
2856 // ----------------------------------------------------------------------------
2858 void wxGridCellAttr::Init(wxGridCellAttr
*attrDefault
)
2862 m_isReadOnly
= Unset
;
2867 m_attrkind
= wxGridCellAttr::Cell
;
2869 m_sizeRows
= m_sizeCols
= 1;
2870 m_overflow
= UnsetOverflow
;
2872 SetDefAttr(attrDefault
);
2875 wxGridCellAttr
*wxGridCellAttr::Clone() const
2877 wxGridCellAttr
*attr
= new wxGridCellAttr(m_defGridAttr
);
2879 if ( HasTextColour() )
2880 attr
->SetTextColour(GetTextColour());
2881 if ( HasBackgroundColour() )
2882 attr
->SetBackgroundColour(GetBackgroundColour());
2884 attr
->SetFont(GetFont());
2885 if ( HasAlignment() )
2886 attr
->SetAlignment(m_hAlign
, m_vAlign
);
2888 attr
->SetSize( m_sizeRows
, m_sizeCols
);
2892 attr
->SetRenderer(m_renderer
);
2893 m_renderer
->IncRef();
2897 attr
->SetEditor(m_editor
);
2902 attr
->SetReadOnly();
2904 attr
->SetOverflow( m_overflow
== Overflow
);
2905 attr
->SetKind( m_attrkind
);
2910 void wxGridCellAttr::MergeWith(wxGridCellAttr
*mergefrom
)
2912 if ( !HasTextColour() && mergefrom
->HasTextColour() )
2913 SetTextColour(mergefrom
->GetTextColour());
2914 if ( !HasBackgroundColour() && mergefrom
->HasBackgroundColour() )
2915 SetBackgroundColour(mergefrom
->GetBackgroundColour());
2916 if ( !HasFont() && mergefrom
->HasFont() )
2917 SetFont(mergefrom
->GetFont());
2918 if ( !HasAlignment() && mergefrom
->HasAlignment() )
2921 mergefrom
->GetAlignment( &hAlign
, &vAlign
);
2922 SetAlignment(hAlign
, vAlign
);
2924 if ( !HasSize() && mergefrom
->HasSize() )
2925 mergefrom
->GetSize( &m_sizeRows
, &m_sizeCols
);
2927 // Directly access member functions as GetRender/Editor don't just return
2928 // m_renderer/m_editor
2930 // Maybe add support for merge of Render and Editor?
2931 if (!HasRenderer() && mergefrom
->HasRenderer() )
2933 m_renderer
= mergefrom
->m_renderer
;
2934 m_renderer
->IncRef();
2936 if ( !HasEditor() && mergefrom
->HasEditor() )
2938 m_editor
= mergefrom
->m_editor
;
2941 if ( !HasReadWriteMode() && mergefrom
->HasReadWriteMode() )
2942 SetReadOnly(mergefrom
->IsReadOnly());
2944 if (!HasOverflowMode() && mergefrom
->HasOverflowMode() )
2945 SetOverflow(mergefrom
->GetOverflow());
2947 SetDefAttr(mergefrom
->m_defGridAttr
);
2950 void wxGridCellAttr::SetSize(int num_rows
, int num_cols
)
2952 // The size of a cell is normally 1,1
2954 // If this cell is larger (2,2) then this is the top left cell
2955 // the other cells that will be covered (lower right cells) must be
2956 // set to negative or zero values such that
2957 // row + num_rows of the covered cell points to the larger cell (this cell)
2958 // same goes for the col + num_cols.
2960 // Size of 0,0 is NOT valid, neither is <=0 and any positive value
2962 wxASSERT_MSG( (!((num_rows
> 0) && (num_cols
<= 0)) ||
2963 !((num_rows
<= 0) && (num_cols
> 0)) ||
2964 !((num_rows
== 0) && (num_cols
== 0))),
2965 wxT("wxGridCellAttr::SetSize only takes two postive values or negative/zero values"));
2967 m_sizeRows
= num_rows
;
2968 m_sizeCols
= num_cols
;
2971 const wxColour
& wxGridCellAttr::GetTextColour() const
2973 if (HasTextColour())
2977 else if (m_defGridAttr
&& m_defGridAttr
!= this)
2979 return m_defGridAttr
->GetTextColour();
2983 wxFAIL_MSG(wxT("Missing default cell attribute"));
2984 return wxNullColour
;
2988 const wxColour
& wxGridCellAttr::GetBackgroundColour() const
2990 if (HasBackgroundColour())
2994 else if (m_defGridAttr
&& m_defGridAttr
!= this)
2996 return m_defGridAttr
->GetBackgroundColour();
3000 wxFAIL_MSG(wxT("Missing default cell attribute"));
3001 return wxNullColour
;
3005 const wxFont
& wxGridCellAttr::GetFont() const
3011 else if (m_defGridAttr
&& m_defGridAttr
!= this)
3013 return m_defGridAttr
->GetFont();
3017 wxFAIL_MSG(wxT("Missing default cell attribute"));
3022 void wxGridCellAttr::GetAlignment(int *hAlign
, int *vAlign
) const
3031 else if (m_defGridAttr
&& m_defGridAttr
!= this)
3033 m_defGridAttr
->GetAlignment(hAlign
, vAlign
);
3037 wxFAIL_MSG(wxT("Missing default cell attribute"));
3041 void wxGridCellAttr::GetSize( int *num_rows
, int *num_cols
) const
3044 *num_rows
= m_sizeRows
;
3046 *num_cols
= m_sizeCols
;
3049 // GetRenderer and GetEditor use a slightly different decision path about
3050 // which attribute to use. If a non-default attr object has one then it is
3051 // used, otherwise the default editor or renderer is fetched from the grid and
3052 // used. It should be the default for the data type of the cell. If it is
3053 // NULL (because the table has a type that the grid does not have in its
3054 // registry), then the grid's default editor or renderer is used.
3056 wxGridCellRenderer
* wxGridCellAttr::GetRenderer(const wxGrid
* grid
, int row
, int col
) const
3058 wxGridCellRenderer
*renderer
= NULL
;
3060 if ( m_renderer
&& this != m_defGridAttr
)
3062 // use the cells renderer if it has one
3063 renderer
= m_renderer
;
3066 else // no non-default cell renderer
3068 // get default renderer for the data type
3071 // GetDefaultRendererForCell() will do IncRef() for us
3072 renderer
= grid
->GetDefaultRendererForCell(row
, col
);
3075 if ( renderer
== NULL
)
3077 if ( (m_defGridAttr
!= NULL
) && (m_defGridAttr
!= this) )
3079 // if we still don't have one then use the grid default
3080 // (no need for IncRef() here neither)
3081 renderer
= m_defGridAttr
->GetRenderer(NULL
, 0, 0);
3083 else // default grid attr
3085 // use m_renderer which we had decided not to use initially
3086 renderer
= m_renderer
;
3093 // we're supposed to always find something
3094 wxASSERT_MSG(renderer
, wxT("Missing default cell renderer"));
3099 // same as above, except for s/renderer/editor/g
3100 wxGridCellEditor
* wxGridCellAttr::GetEditor(const wxGrid
* grid
, int row
, int col
) const
3102 wxGridCellEditor
*editor
= NULL
;
3104 if ( m_editor
&& this != m_defGridAttr
)
3106 // use the cells editor if it has one
3110 else // no non default cell editor
3112 // get default editor for the data type
3115 // GetDefaultEditorForCell() will do IncRef() for us
3116 editor
= grid
->GetDefaultEditorForCell(row
, col
);
3119 if ( editor
== NULL
)
3121 if ( (m_defGridAttr
!= NULL
) && (m_defGridAttr
!= this) )
3123 // if we still don't have one then use the grid default
3124 // (no need for IncRef() here neither)
3125 editor
= m_defGridAttr
->GetEditor(NULL
, 0, 0);
3127 else // default grid attr
3129 // use m_editor which we had decided not to use initially
3137 // we're supposed to always find something
3138 wxASSERT_MSG(editor
, wxT("Missing default cell editor"));
3143 // ----------------------------------------------------------------------------
3144 // wxGridCellAttrData
3145 // ----------------------------------------------------------------------------
3147 void wxGridCellAttrData::SetAttr(wxGridCellAttr
*attr
, int row
, int col
)
3149 // Note: contrary to wxGridRowOrColAttrData::SetAttr, we must not
3150 // touch attribute's reference counting explicitly, since this
3151 // is managed by class wxGridCellWithAttr
3152 int n
= FindIndex(row
, col
);
3153 if ( n
== wxNOT_FOUND
)
3157 // add the attribute
3158 m_attrs
.Add(new wxGridCellWithAttr(row
, col
, attr
));
3160 //else: nothing to do
3162 else // we already have an attribute for this cell
3166 // change the attribute
3167 m_attrs
[(size_t)n
].ChangeAttr(attr
);
3171 // remove this attribute
3172 m_attrs
.RemoveAt((size_t)n
);
3177 wxGridCellAttr
*wxGridCellAttrData::GetAttr(int row
, int col
) const
3179 wxGridCellAttr
*attr
= NULL
;
3181 int n
= FindIndex(row
, col
);
3182 if ( n
!= wxNOT_FOUND
)
3184 attr
= m_attrs
[(size_t)n
].attr
;
3191 void wxGridCellAttrData::UpdateAttrRows( size_t pos
, int numRows
)
3193 size_t count
= m_attrs
.GetCount();
3194 for ( size_t n
= 0; n
< count
; n
++ )
3196 wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3197 wxCoord row
= coords
.GetRow();
3198 if ((size_t)row
>= pos
)
3202 // If rows inserted, include row counter where necessary
3203 coords
.SetRow(row
+ numRows
);
3205 else if (numRows
< 0)
3207 // If rows deleted ...
3208 if ((size_t)row
>= pos
- numRows
)
3210 // ...either decrement row counter (if row still exists)...
3211 coords
.SetRow(row
+ numRows
);
3215 // ...or remove the attribute
3216 m_attrs
.RemoveAt(n
);
3225 void wxGridCellAttrData::UpdateAttrCols( size_t pos
, int numCols
)
3227 size_t count
= m_attrs
.GetCount();
3228 for ( size_t n
= 0; n
< count
; n
++ )
3230 wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3231 wxCoord col
= coords
.GetCol();
3232 if ( (size_t)col
>= pos
)
3236 // If rows inserted, include row counter where necessary
3237 coords
.SetCol(col
+ numCols
);
3239 else if (numCols
< 0)
3241 // If rows deleted ...
3242 if ((size_t)col
>= pos
- numCols
)
3244 // ...either decrement row counter (if row still exists)...
3245 coords
.SetCol(col
+ numCols
);
3249 // ...or remove the attribute
3250 m_attrs
.RemoveAt(n
);
3259 int wxGridCellAttrData::FindIndex(int row
, int col
) const
3261 size_t count
= m_attrs
.GetCount();
3262 for ( size_t n
= 0; n
< count
; n
++ )
3264 const wxGridCellCoords
& coords
= m_attrs
[n
].coords
;
3265 if ( (coords
.GetRow() == row
) && (coords
.GetCol() == col
) )
3274 // ----------------------------------------------------------------------------
3275 // wxGridRowOrColAttrData
3276 // ----------------------------------------------------------------------------
3278 wxGridRowOrColAttrData::~wxGridRowOrColAttrData()
3280 size_t count
= m_attrs
.GetCount();
3281 for ( size_t n
= 0; n
< count
; n
++ )
3283 m_attrs
[n
]->DecRef();
3287 wxGridCellAttr
*wxGridRowOrColAttrData::GetAttr(int rowOrCol
) const
3289 wxGridCellAttr
*attr
= NULL
;
3291 int n
= m_rowsOrCols
.Index(rowOrCol
);
3292 if ( n
!= wxNOT_FOUND
)
3294 attr
= m_attrs
[(size_t)n
];
3301 void wxGridRowOrColAttrData::SetAttr(wxGridCellAttr
*attr
, int rowOrCol
)
3303 int i
= m_rowsOrCols
.Index(rowOrCol
);
3304 if ( i
== wxNOT_FOUND
)
3308 // add the attribute - no need to do anything to reference count
3309 // since we take ownership of the attribute.
3310 m_rowsOrCols
.Add(rowOrCol
);
3313 // nothing to remove
3317 size_t n
= (size_t)i
;
3318 if ( m_attrs
[n
] == attr
)
3323 // change the attribute, handling reference count manually,
3324 // taking ownership of the new attribute.
3325 m_attrs
[n
]->DecRef();
3330 // remove this attribute, handling reference count manually
3331 m_attrs
[n
]->DecRef();
3332 m_rowsOrCols
.RemoveAt(n
);
3333 m_attrs
.RemoveAt(n
);
3338 void wxGridRowOrColAttrData::UpdateAttrRowsOrCols( size_t pos
, int numRowsOrCols
)
3340 size_t count
= m_attrs
.GetCount();
3341 for ( size_t n
= 0; n
< count
; n
++ )
3343 int & rowOrCol
= m_rowsOrCols
[n
];
3344 if ( (size_t)rowOrCol
>= pos
)
3346 if ( numRowsOrCols
> 0 )
3348 // If rows inserted, include row counter where necessary
3349 rowOrCol
+= numRowsOrCols
;
3351 else if ( numRowsOrCols
< 0)
3353 // If rows deleted, either decrement row counter (if row still exists)
3354 if ((size_t)rowOrCol
>= pos
- numRowsOrCols
)
3355 rowOrCol
+= numRowsOrCols
;
3358 m_rowsOrCols
.RemoveAt(n
);
3359 m_attrs
[n
]->DecRef();
3360 m_attrs
.RemoveAt(n
);
3369 // ----------------------------------------------------------------------------
3370 // wxGridCellAttrProvider
3371 // ----------------------------------------------------------------------------
3373 wxGridCellAttrProvider::wxGridCellAttrProvider()
3378 wxGridCellAttrProvider::~wxGridCellAttrProvider()
3383 void wxGridCellAttrProvider::InitData()
3385 m_data
= new wxGridCellAttrProviderData
;
3388 wxGridCellAttr
*wxGridCellAttrProvider::GetAttr(int row
, int col
,
3389 wxGridCellAttr::wxAttrKind kind
) const
3391 wxGridCellAttr
*attr
= NULL
;
3396 case (wxGridCellAttr::Any
):
3397 // Get cached merge attributes.
3398 // Currently not used as no cache implemented as not mutable
3399 // attr = m_data->m_mergeAttr.GetAttr(row, col);
3402 // Basically implement old version.
3403 // Also check merge cache, so we don't have to re-merge every time..
3404 wxGridCellAttr
*attrcell
= m_data
->m_cellAttrs
.GetAttr(row
, col
);
3405 wxGridCellAttr
*attrrow
= m_data
->m_rowAttrs
.GetAttr(row
);
3406 wxGridCellAttr
*attrcol
= m_data
->m_colAttrs
.GetAttr(col
);
3408 if ((attrcell
!= attrrow
) && (attrrow
!= attrcol
) && (attrcell
!= attrcol
))
3410 // Two or more are non NULL
3411 attr
= new wxGridCellAttr
;
3412 attr
->SetKind(wxGridCellAttr::Merged
);
3414 // Order is important..
3417 attr
->MergeWith(attrcell
);
3422 attr
->MergeWith(attrcol
);
3427 attr
->MergeWith(attrrow
);
3431 // store merge attr if cache implemented
3433 //m_data->m_mergeAttr.SetAttr(attr, row, col);
3437 // one or none is non null return it or null.
3456 case (wxGridCellAttr::Cell
):
3457 attr
= m_data
->m_cellAttrs
.GetAttr(row
, col
);
3460 case (wxGridCellAttr::Col
):
3461 attr
= m_data
->m_colAttrs
.GetAttr(col
);
3464 case (wxGridCellAttr::Row
):
3465 attr
= m_data
->m_rowAttrs
.GetAttr(row
);
3470 // (wxGridCellAttr::Default):
3471 // (wxGridCellAttr::Merged):
3479 void wxGridCellAttrProvider::SetAttr(wxGridCellAttr
*attr
,
3485 m_data
->m_cellAttrs
.SetAttr(attr
, row
, col
);
3488 void wxGridCellAttrProvider::SetRowAttr(wxGridCellAttr
*attr
, int row
)
3493 m_data
->m_rowAttrs
.SetAttr(attr
, row
);
3496 void wxGridCellAttrProvider::SetColAttr(wxGridCellAttr
*attr
, int col
)
3501 m_data
->m_colAttrs
.SetAttr(attr
, col
);
3504 void wxGridCellAttrProvider::UpdateAttrRows( size_t pos
, int numRows
)
3508 m_data
->m_cellAttrs
.UpdateAttrRows( pos
, numRows
);
3510 m_data
->m_rowAttrs
.UpdateAttrRowsOrCols( pos
, numRows
);
3514 void wxGridCellAttrProvider::UpdateAttrCols( size_t pos
, int numCols
)
3518 m_data
->m_cellAttrs
.UpdateAttrCols( pos
, numCols
);
3520 m_data
->m_colAttrs
.UpdateAttrRowsOrCols( pos
, numCols
);
3524 // ----------------------------------------------------------------------------
3525 // wxGridTypeRegistry
3526 // ----------------------------------------------------------------------------
3528 wxGridTypeRegistry::~wxGridTypeRegistry()
3530 size_t count
= m_typeinfo
.GetCount();
3531 for ( size_t i
= 0; i
< count
; i
++ )
3532 delete m_typeinfo
[i
];
3535 void wxGridTypeRegistry::RegisterDataType(const wxString
& typeName
,
3536 wxGridCellRenderer
* renderer
,
3537 wxGridCellEditor
* editor
)
3539 wxGridDataTypeInfo
* info
= new wxGridDataTypeInfo(typeName
, renderer
, editor
);
3541 // is it already registered?
3542 int loc
= FindRegisteredDataType(typeName
);
3543 if ( loc
!= wxNOT_FOUND
)
3545 delete m_typeinfo
[loc
];
3546 m_typeinfo
[loc
] = info
;
3550 m_typeinfo
.Add(info
);
3554 int wxGridTypeRegistry::FindRegisteredDataType(const wxString
& typeName
)
3556 size_t count
= m_typeinfo
.GetCount();
3557 for ( size_t i
= 0; i
< count
; i
++ )
3559 if ( typeName
== m_typeinfo
[i
]->m_typeName
)
3568 int wxGridTypeRegistry::FindDataType(const wxString
& typeName
)
3570 int index
= FindRegisteredDataType(typeName
);
3571 if ( index
== wxNOT_FOUND
)
3573 // check whether this is one of the standard ones, in which case
3574 // register it "on the fly"
3576 if ( typeName
== wxGRID_VALUE_STRING
)
3578 RegisterDataType(wxGRID_VALUE_STRING
,
3579 new wxGridCellStringRenderer
,
3580 new wxGridCellTextEditor
);
3583 #endif // wxUSE_TEXTCTRL
3585 if ( typeName
== wxGRID_VALUE_BOOL
)
3587 RegisterDataType(wxGRID_VALUE_BOOL
,
3588 new wxGridCellBoolRenderer
,
3589 new wxGridCellBoolEditor
);
3592 #endif // wxUSE_CHECKBOX
3594 if ( typeName
== wxGRID_VALUE_NUMBER
)
3596 RegisterDataType(wxGRID_VALUE_NUMBER
,
3597 new wxGridCellNumberRenderer
,
3598 new wxGridCellNumberEditor
);
3600 else if ( typeName
== wxGRID_VALUE_FLOAT
)
3602 RegisterDataType(wxGRID_VALUE_FLOAT
,
3603 new wxGridCellFloatRenderer
,
3604 new wxGridCellFloatEditor
);
3607 #endif // wxUSE_TEXTCTRL
3609 if ( typeName
== wxGRID_VALUE_CHOICE
)
3611 RegisterDataType(wxGRID_VALUE_CHOICE
,
3612 new wxGridCellStringRenderer
,
3613 new wxGridCellChoiceEditor
);
3616 #endif // wxUSE_COMBOBOX
3621 // we get here only if just added the entry for this type, so return
3623 index
= m_typeinfo
.GetCount() - 1;
3629 int wxGridTypeRegistry::FindOrCloneDataType(const wxString
& typeName
)
3631 int index
= FindDataType(typeName
);
3632 if ( index
== wxNOT_FOUND
)
3634 // the first part of the typename is the "real" type, anything after ':'
3635 // are the parameters for the renderer
3636 index
= FindDataType(typeName
.BeforeFirst(_T(':')));
3637 if ( index
== wxNOT_FOUND
)
3642 wxGridCellRenderer
*renderer
= GetRenderer(index
);
3643 wxGridCellRenderer
*rendererOld
= renderer
;
3644 renderer
= renderer
->Clone();
3645 rendererOld
->DecRef();
3647 wxGridCellEditor
*editor
= GetEditor(index
);
3648 wxGridCellEditor
*editorOld
= editor
;
3649 editor
= editor
->Clone();
3650 editorOld
->DecRef();
3652 // do it even if there are no parameters to reset them to defaults
3653 wxString params
= typeName
.AfterFirst(_T(':'));
3654 renderer
->SetParameters(params
);
3655 editor
->SetParameters(params
);
3657 // register the new typename
3658 RegisterDataType(typeName
, renderer
, editor
);
3660 // we just registered it, it's the last one
3661 index
= m_typeinfo
.GetCount() - 1;
3667 wxGridCellRenderer
* wxGridTypeRegistry::GetRenderer(int index
)
3669 wxGridCellRenderer
* renderer
= m_typeinfo
[index
]->m_renderer
;
3676 wxGridCellEditor
* wxGridTypeRegistry::GetEditor(int index
)
3678 wxGridCellEditor
* editor
= m_typeinfo
[index
]->m_editor
;
3685 // ----------------------------------------------------------------------------
3687 // ----------------------------------------------------------------------------
3689 IMPLEMENT_ABSTRACT_CLASS( wxGridTableBase
, wxObject
)
3691 wxGridTableBase::wxGridTableBase()
3694 m_attrProvider
= NULL
;
3697 wxGridTableBase::~wxGridTableBase()
3699 delete m_attrProvider
;
3702 void wxGridTableBase::SetAttrProvider(wxGridCellAttrProvider
*attrProvider
)
3704 delete m_attrProvider
;
3705 m_attrProvider
= attrProvider
;
3708 bool wxGridTableBase::CanHaveAttributes()
3710 if ( ! GetAttrProvider() )
3712 // use the default attr provider by default
3713 SetAttrProvider(new wxGridCellAttrProvider
);
3719 wxGridCellAttr
*wxGridTableBase::GetAttr(int row
, int col
, wxGridCellAttr::wxAttrKind kind
)
3721 if ( m_attrProvider
)
3722 return m_attrProvider
->GetAttr(row
, col
, kind
);
3727 void wxGridTableBase::SetAttr(wxGridCellAttr
* attr
, int row
, int col
)
3729 if ( m_attrProvider
)
3732 attr
->SetKind(wxGridCellAttr::Cell
);
3733 m_attrProvider
->SetAttr(attr
, row
, col
);
3737 // as we take ownership of the pointer and don't store it, we must
3743 void wxGridTableBase::SetRowAttr(wxGridCellAttr
*attr
, int row
)
3745 if ( m_attrProvider
)
3747 attr
->SetKind(wxGridCellAttr::Row
);
3748 m_attrProvider
->SetRowAttr(attr
, row
);
3752 // as we take ownership of the pointer and don't store it, we must
3758 void wxGridTableBase::SetColAttr(wxGridCellAttr
*attr
, int col
)
3760 if ( m_attrProvider
)
3762 attr
->SetKind(wxGridCellAttr::Col
);
3763 m_attrProvider
->SetColAttr(attr
, col
);
3767 // as we take ownership of the pointer and don't store it, we must
3773 bool wxGridTableBase::InsertRows( size_t WXUNUSED(pos
),
3774 size_t WXUNUSED(numRows
) )
3776 wxFAIL_MSG( wxT("Called grid table class function InsertRows\nbut your derived table class does not override this function") );
3781 bool wxGridTableBase::AppendRows( size_t WXUNUSED(numRows
) )
3783 wxFAIL_MSG( wxT("Called grid table class function AppendRows\nbut your derived table class does not override this function"));
3788 bool wxGridTableBase::DeleteRows( size_t WXUNUSED(pos
),
3789 size_t WXUNUSED(numRows
) )
3791 wxFAIL_MSG( wxT("Called grid table class function DeleteRows\nbut your derived table class does not override this function"));
3796 bool wxGridTableBase::InsertCols( size_t WXUNUSED(pos
),
3797 size_t WXUNUSED(numCols
) )
3799 wxFAIL_MSG( wxT("Called grid table class function InsertCols\nbut your derived table class does not override this function"));
3804 bool wxGridTableBase::AppendCols( size_t WXUNUSED(numCols
) )
3806 wxFAIL_MSG(wxT("Called grid table class function AppendCols\nbut your derived table class does not override this function"));
3811 bool wxGridTableBase::DeleteCols( size_t WXUNUSED(pos
),
3812 size_t WXUNUSED(numCols
) )
3814 wxFAIL_MSG( wxT("Called grid table class function DeleteCols\nbut your derived table class does not override this function"));
3819 wxString
wxGridTableBase::GetRowLabelValue( int row
)
3823 // RD: Starting the rows at zero confuses users,
3824 // no matter how much it makes sense to us geeks.
3830 wxString
wxGridTableBase::GetColLabelValue( int col
)
3832 // default col labels are:
3833 // cols 0 to 25 : A-Z
3834 // cols 26 to 675 : AA-ZZ
3839 for ( n
= 1; ; n
++ )
3841 s
+= (wxChar
) (_T('A') + (wxChar
)(col
% 26));
3847 // reverse the string...
3849 for ( i
= 0; i
< n
; i
++ )
3857 wxString
wxGridTableBase::GetTypeName( int WXUNUSED(row
), int WXUNUSED(col
) )
3859 return wxGRID_VALUE_STRING
;
3862 bool wxGridTableBase::CanGetValueAs( int WXUNUSED(row
), int WXUNUSED(col
),
3863 const wxString
& typeName
)
3865 return typeName
== wxGRID_VALUE_STRING
;
3868 bool wxGridTableBase::CanSetValueAs( int row
, int col
, const wxString
& typeName
)
3870 return CanGetValueAs(row
, col
, typeName
);
3873 long wxGridTableBase::GetValueAsLong( int WXUNUSED(row
), int WXUNUSED(col
) )
3878 double wxGridTableBase::GetValueAsDouble( int WXUNUSED(row
), int WXUNUSED(col
) )
3883 bool wxGridTableBase::GetValueAsBool( int WXUNUSED(row
), int WXUNUSED(col
) )
3888 void wxGridTableBase::SetValueAsLong( int WXUNUSED(row
), int WXUNUSED(col
),
3889 long WXUNUSED(value
) )
3893 void wxGridTableBase::SetValueAsDouble( int WXUNUSED(row
), int WXUNUSED(col
),
3894 double WXUNUSED(value
) )
3898 void wxGridTableBase::SetValueAsBool( int WXUNUSED(row
), int WXUNUSED(col
),
3899 bool WXUNUSED(value
) )
3903 void* wxGridTableBase::GetValueAsCustom( int WXUNUSED(row
), int WXUNUSED(col
),
3904 const wxString
& WXUNUSED(typeName
) )
3909 void wxGridTableBase::SetValueAsCustom( int WXUNUSED(row
), int WXUNUSED(col
),
3910 const wxString
& WXUNUSED(typeName
),
3911 void* WXUNUSED(value
) )
3915 //////////////////////////////////////////////////////////////////////
3917 // Message class for the grid table to send requests and notifications
3921 wxGridTableMessage::wxGridTableMessage()
3929 wxGridTableMessage::wxGridTableMessage( wxGridTableBase
*table
, int id
,
3930 int commandInt1
, int commandInt2
)
3934 m_comInt1
= commandInt1
;
3935 m_comInt2
= commandInt2
;
3938 //////////////////////////////////////////////////////////////////////
3940 // A basic grid table for string data. An object of this class will
3941 // created by wxGrid if you don't specify an alternative table class.
3944 WX_DEFINE_OBJARRAY(wxGridStringArray
)
3946 IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable
, wxGridTableBase
)
3948 wxGridStringTable::wxGridStringTable()
3953 wxGridStringTable::wxGridStringTable( int numRows
, int numCols
)
3956 m_data
.Alloc( numRows
);
3959 sa
.Alloc( numCols
);
3960 sa
.Add( wxEmptyString
, numCols
);
3962 m_data
.Add( sa
, numRows
);
3965 wxGridStringTable::~wxGridStringTable()
3969 int wxGridStringTable::GetNumberRows()
3971 return m_data
.GetCount();
3974 int wxGridStringTable::GetNumberCols()
3976 if ( m_data
.GetCount() > 0 )
3977 return m_data
[0].GetCount();
3982 wxString
wxGridStringTable::GetValue( int row
, int col
)
3984 wxCHECK_MSG( (row
< GetNumberRows()) && (col
< GetNumberCols()),
3986 _T("invalid row or column index in wxGridStringTable") );
3988 return m_data
[row
][col
];
3991 void wxGridStringTable::SetValue( int row
, int col
, const wxString
& value
)
3993 wxCHECK_RET( (row
< GetNumberRows()) && (col
< GetNumberCols()),
3994 _T("invalid row or column index in wxGridStringTable") );
3996 m_data
[row
][col
] = value
;
3999 void wxGridStringTable::Clear()
4002 int numRows
, numCols
;
4004 numRows
= m_data
.GetCount();
4007 numCols
= m_data
[0].GetCount();
4009 for ( row
= 0; row
< numRows
; row
++ )
4011 for ( col
= 0; col
< numCols
; col
++ )
4013 m_data
[row
][col
] = wxEmptyString
;
4019 bool wxGridStringTable::InsertRows( size_t pos
, size_t numRows
)
4021 size_t curNumRows
= m_data
.GetCount();
4022 size_t curNumCols
= ( curNumRows
> 0 ? m_data
[0].GetCount() :
4023 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4025 if ( pos
>= curNumRows
)
4027 return AppendRows( numRows
);
4031 sa
.Alloc( curNumCols
);
4032 sa
.Add( wxEmptyString
, curNumCols
);
4033 m_data
.Insert( sa
, pos
, numRows
);
4037 wxGridTableMessage
msg( this,
4038 wxGRIDTABLE_NOTIFY_ROWS_INSERTED
,
4042 GetView()->ProcessTableMessage( msg
);
4048 bool wxGridStringTable::AppendRows( size_t numRows
)
4050 size_t curNumRows
= m_data
.GetCount();
4051 size_t curNumCols
= ( curNumRows
> 0
4052 ? m_data
[0].GetCount()
4053 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4056 if ( curNumCols
> 0 )
4058 sa
.Alloc( curNumCols
);
4059 sa
.Add( wxEmptyString
, curNumCols
);
4062 m_data
.Add( sa
, numRows
);
4066 wxGridTableMessage
msg( this,
4067 wxGRIDTABLE_NOTIFY_ROWS_APPENDED
,
4070 GetView()->ProcessTableMessage( msg
);
4076 bool wxGridStringTable::DeleteRows( size_t pos
, size_t numRows
)
4078 size_t curNumRows
= m_data
.GetCount();
4080 if ( pos
>= curNumRows
)
4082 wxFAIL_MSG( wxString::Format
4084 wxT("Called wxGridStringTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
4086 (unsigned long)numRows
,
4087 (unsigned long)curNumRows
4093 if ( numRows
> curNumRows
- pos
)
4095 numRows
= curNumRows
- pos
;
4098 if ( numRows
>= curNumRows
)
4104 m_data
.RemoveAt( pos
, numRows
);
4109 wxGridTableMessage
msg( this,
4110 wxGRIDTABLE_NOTIFY_ROWS_DELETED
,
4114 GetView()->ProcessTableMessage( msg
);
4120 bool wxGridStringTable::InsertCols( size_t pos
, size_t numCols
)
4124 size_t curNumRows
= m_data
.GetCount();
4125 size_t curNumCols
= ( curNumRows
> 0
4126 ? m_data
[0].GetCount()
4127 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4129 if ( pos
>= curNumCols
)
4131 return AppendCols( numCols
);
4134 if ( !m_colLabels
.IsEmpty() )
4136 m_colLabels
.Insert( wxEmptyString
, pos
, numCols
);
4139 for ( i
= pos
; i
< pos
+ numCols
; i
++ )
4140 m_colLabels
[i
] = wxGridTableBase::GetColLabelValue( i
);
4143 for ( row
= 0; row
< curNumRows
; row
++ )
4145 for ( col
= pos
; col
< pos
+ numCols
; col
++ )
4147 m_data
[row
].Insert( wxEmptyString
, col
);
4153 wxGridTableMessage
msg( this,
4154 wxGRIDTABLE_NOTIFY_COLS_INSERTED
,
4158 GetView()->ProcessTableMessage( msg
);
4164 bool wxGridStringTable::AppendCols( size_t numCols
)
4168 size_t curNumRows
= m_data
.GetCount();
4170 for ( row
= 0; row
< curNumRows
; row
++ )
4172 m_data
[row
].Add( wxEmptyString
, numCols
);
4177 wxGridTableMessage
msg( this,
4178 wxGRIDTABLE_NOTIFY_COLS_APPENDED
,
4181 GetView()->ProcessTableMessage( msg
);
4187 bool wxGridStringTable::DeleteCols( size_t pos
, size_t numCols
)
4191 size_t curNumRows
= m_data
.GetCount();
4192 size_t curNumCols
= ( curNumRows
> 0 ? m_data
[0].GetCount() :
4193 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4195 if ( pos
>= curNumCols
)
4197 wxFAIL_MSG( wxString::Format
4199 wxT("Called wxGridStringTable::DeleteCols(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu cols"),
4201 (unsigned long)numCols
,
4202 (unsigned long)curNumCols
4209 colID
= GetView()->GetColAt( pos
);
4213 if ( numCols
> curNumCols
- colID
)
4215 numCols
= curNumCols
- colID
;
4218 if ( !m_colLabels
.IsEmpty() )
4220 // m_colLabels stores just as many elements as it needs, e.g. if only
4221 // the label of the first column had been set it would have only one
4222 // element and not numCols, so account for it
4223 int nToRm
= m_colLabels
.size() - colID
;
4225 m_colLabels
.RemoveAt( colID
, nToRm
);
4228 for ( row
= 0; row
< curNumRows
; row
++ )
4230 if ( numCols
>= curNumCols
)
4232 m_data
[row
].Clear();
4236 m_data
[row
].RemoveAt( colID
, numCols
);
4242 wxGridTableMessage
msg( this,
4243 wxGRIDTABLE_NOTIFY_COLS_DELETED
,
4247 GetView()->ProcessTableMessage( msg
);
4253 wxString
wxGridStringTable::GetRowLabelValue( int row
)
4255 if ( row
> (int)(m_rowLabels
.GetCount()) - 1 )
4257 // using default label
4259 return wxGridTableBase::GetRowLabelValue( row
);
4263 return m_rowLabels
[row
];
4267 wxString
wxGridStringTable::GetColLabelValue( int col
)
4269 if ( col
> (int)(m_colLabels
.GetCount()) - 1 )
4271 // using default label
4273 return wxGridTableBase::GetColLabelValue( col
);
4277 return m_colLabels
[col
];
4281 void wxGridStringTable::SetRowLabelValue( int row
, const wxString
& value
)
4283 if ( row
> (int)(m_rowLabels
.GetCount()) - 1 )
4285 int n
= m_rowLabels
.GetCount();
4288 for ( i
= n
; i
<= row
; i
++ )
4290 m_rowLabels
.Add( wxGridTableBase::GetRowLabelValue(i
) );
4294 m_rowLabels
[row
] = value
;
4297 void wxGridStringTable::SetColLabelValue( int col
, const wxString
& value
)
4299 if ( col
> (int)(m_colLabels
.GetCount()) - 1 )
4301 int n
= m_colLabels
.GetCount();
4304 for ( i
= n
; i
<= col
; i
++ )
4306 m_colLabels
.Add( wxGridTableBase::GetColLabelValue(i
) );
4310 m_colLabels
[col
] = value
;
4314 //////////////////////////////////////////////////////////////////////
4315 //////////////////////////////////////////////////////////////////////
4317 BEGIN_EVENT_TABLE(wxGridSubwindow
, wxWindow
)
4318 EVT_MOUSE_CAPTURE_LOST(wxGridSubwindow::OnMouseCaptureLost
)
4321 void wxGridSubwindow::OnMouseCaptureLost(wxMouseCaptureLostEvent
& WXUNUSED(event
))
4323 m_owner
->CancelMouseCapture();
4326 BEGIN_EVENT_TABLE( wxGridRowLabelWindow
, wxGridSubwindow
)
4327 EVT_PAINT( wxGridRowLabelWindow::OnPaint
)
4328 EVT_MOUSEWHEEL( wxGridRowLabelWindow::OnMouseWheel
)
4329 EVT_MOUSE_EVENTS( wxGridRowLabelWindow::OnMouseEvent
)
4332 void wxGridRowLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4336 // NO - don't do this because it will set both the x and y origin
4337 // coords to match the parent scrolled window and we just want to
4338 // set the y coord - MB
4340 // m_owner->PrepareDC( dc );
4343 m_owner
->CalcUnscrolledPosition( 0, 0, &x
, &y
);
4344 wxPoint pt
= dc
.GetDeviceOrigin();
4345 dc
.SetDeviceOrigin( pt
.x
, pt
.y
-y
);
4347 wxArrayInt rows
= m_owner
->CalcRowLabelsExposed( GetUpdateRegion() );
4348 m_owner
->DrawRowLabels( dc
, rows
);
4351 void wxGridRowLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4353 m_owner
->ProcessRowLabelMouseEvent( event
);
4356 void wxGridRowLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4358 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4362 //////////////////////////////////////////////////////////////////////
4364 BEGIN_EVENT_TABLE( wxGridColLabelWindow
, wxGridSubwindow
)
4365 EVT_PAINT( wxGridColLabelWindow::OnPaint
)
4366 EVT_MOUSEWHEEL( wxGridColLabelWindow::OnMouseWheel
)
4367 EVT_MOUSE_EVENTS( wxGridColLabelWindow::OnMouseEvent
)
4370 void wxGridColLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4374 // NO - don't do this because it will set both the x and y origin
4375 // coords to match the parent scrolled window and we just want to
4376 // set the x coord - MB
4378 // m_owner->PrepareDC( dc );
4381 m_owner
->CalcUnscrolledPosition( 0, 0, &x
, &y
);
4382 wxPoint pt
= dc
.GetDeviceOrigin();
4383 if (GetLayoutDirection() == wxLayout_RightToLeft
)
4384 dc
.SetDeviceOrigin( pt
.x
+x
, pt
.y
);
4386 dc
.SetDeviceOrigin( pt
.x
-x
, pt
.y
);
4388 wxArrayInt cols
= m_owner
->CalcColLabelsExposed( GetUpdateRegion() );
4389 m_owner
->DrawColLabels( dc
, cols
);
4392 void wxGridColLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4394 m_owner
->ProcessColLabelMouseEvent( event
);
4397 void wxGridColLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4399 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4403 //////////////////////////////////////////////////////////////////////
4405 BEGIN_EVENT_TABLE( wxGridCornerLabelWindow
, wxGridSubwindow
)
4406 EVT_MOUSEWHEEL( wxGridCornerLabelWindow::OnMouseWheel
)
4407 EVT_MOUSE_EVENTS( wxGridCornerLabelWindow::OnMouseEvent
)
4408 EVT_PAINT( wxGridCornerLabelWindow::OnPaint
)
4411 void wxGridCornerLabelWindow::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
4415 m_owner
->DrawCornerLabel(dc
);
4418 void wxGridCornerLabelWindow::OnMouseEvent( wxMouseEvent
& event
)
4420 m_owner
->ProcessCornerLabelMouseEvent( event
);
4423 void wxGridCornerLabelWindow::OnMouseWheel( wxMouseEvent
& event
)
4425 if (!m_owner
->GetEventHandler()->ProcessEvent(event
))
4429 //////////////////////////////////////////////////////////////////////
4431 BEGIN_EVENT_TABLE( wxGridWindow
, wxGridSubwindow
)
4432 EVT_PAINT( wxGridWindow::OnPaint
)
4433 EVT_MOUSEWHEEL( wxGridWindow::OnMouseWheel
)
4434 EVT_MOUSE_EVENTS( wxGridWindow::OnMouseEvent
)
4435 EVT_KEY_DOWN( wxGridWindow::OnKeyDown
)
4436 EVT_KEY_UP( wxGridWindow::OnKeyUp
)
4437 EVT_CHAR( wxGridWindow::OnChar
)
4438 EVT_SET_FOCUS( wxGridWindow::OnFocus
)
4439 EVT_KILL_FOCUS( wxGridWindow::OnFocus
)
4440 EVT_ERASE_BACKGROUND( wxGridWindow::OnEraseBackground
)
4443 void wxGridWindow::OnPaint( wxPaintEvent
&WXUNUSED(event
) )
4445 wxPaintDC
dc( this );
4446 m_owner
->PrepareDC( dc
);
4447 wxRegion reg
= GetUpdateRegion();
4448 wxGridCellCoordsArray dirtyCells
= m_owner
->CalcCellsExposed( reg
);
4449 m_owner
->DrawGridCellArea( dc
, dirtyCells
);
4451 m_owner
->DrawGridSpace( dc
);
4453 m_owner
->DrawAllGridLines( dc
, reg
);
4455 m_owner
->DrawHighlight( dc
, dirtyCells
);
4458 void wxGridWindow::ScrollWindow( int dx
, int dy
, const wxRect
*rect
)
4460 wxWindow::ScrollWindow( dx
, dy
, rect
);
4461 m_owner
->GetGridRowLabelWindow()->ScrollWindow( 0, dy
, rect
);
4462 m_owner
->GetGridColLabelWindow()->ScrollWindow( dx
, 0, rect
);
4465 void wxGridWindow::OnMouseEvent( wxMouseEvent
& event
)
4467 if (event
.ButtonDown(wxMOUSE_BTN_LEFT
) && FindFocus() != this)
4470 m_owner
->ProcessGridCellMouseEvent( event
);
4473 void wxGridWindow::OnMouseWheel( wxMouseEvent
& event
)
4475 if (!m_owner
->GetEventHandler()->ProcessEvent( event
))
4479 // This seems to be required for wxMotif/wxGTK otherwise the mouse
4480 // cursor must be in the cell edit control to get key events
4482 void wxGridWindow::OnKeyDown( wxKeyEvent
& event
)
4484 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4488 void wxGridWindow::OnKeyUp( wxKeyEvent
& event
)
4490 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4494 void wxGridWindow::OnChar( wxKeyEvent
& event
)
4496 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4500 void wxGridWindow::OnEraseBackground( wxEraseEvent
& WXUNUSED(event
) )
4504 void wxGridWindow::OnFocus(wxFocusEvent
& event
)
4506 // and if we have any selection, it has to be repainted, because it
4507 // uses different colour when the grid is not focused:
4508 if ( m_owner
->IsSelection() )
4514 // NB: Note that this code is in "else" branch only because the other
4515 // branch refreshes everything and so there's no point in calling
4516 // Refresh() again, *not* because it should only be done if
4517 // !IsSelection(). If the above code is ever optimized to refresh
4518 // only selected area, this needs to be moved out of the "else"
4519 // branch so that it's always executed.
4521 // current cell cursor {dis,re}appears on focus change:
4522 const wxGridCellCoords
cursorCoords(m_owner
->GetGridCursorRow(),
4523 m_owner
->GetGridCursorCol());
4524 const wxRect cursor
=
4525 m_owner
->BlockToDeviceRect(cursorCoords
, cursorCoords
);
4526 Refresh(true, &cursor
);
4529 if ( !m_owner
->GetEventHandler()->ProcessEvent( event
) )
4533 #define internalXToCol(x) XToCol(x, true)
4534 #define internalYToRow(y) YToRow(y, true)
4536 /////////////////////////////////////////////////////////////////////
4538 #if wxUSE_EXTENDED_RTTI
4539 WX_DEFINE_FLAGS( wxGridStyle
)
4541 wxBEGIN_FLAGS( wxGridStyle
)
4542 // new style border flags, we put them first to
4543 // use them for streaming out
4544 wxFLAGS_MEMBER(wxBORDER_SIMPLE
)
4545 wxFLAGS_MEMBER(wxBORDER_SUNKEN
)
4546 wxFLAGS_MEMBER(wxBORDER_DOUBLE
)
4547 wxFLAGS_MEMBER(wxBORDER_RAISED
)
4548 wxFLAGS_MEMBER(wxBORDER_STATIC
)
4549 wxFLAGS_MEMBER(wxBORDER_NONE
)
4551 // old style border flags
4552 wxFLAGS_MEMBER(wxSIMPLE_BORDER
)
4553 wxFLAGS_MEMBER(wxSUNKEN_BORDER
)
4554 wxFLAGS_MEMBER(wxDOUBLE_BORDER
)
4555 wxFLAGS_MEMBER(wxRAISED_BORDER
)
4556 wxFLAGS_MEMBER(wxSTATIC_BORDER
)
4557 wxFLAGS_MEMBER(wxBORDER
)
4559 // standard window styles
4560 wxFLAGS_MEMBER(wxTAB_TRAVERSAL
)
4561 wxFLAGS_MEMBER(wxCLIP_CHILDREN
)
4562 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW
)
4563 wxFLAGS_MEMBER(wxWANTS_CHARS
)
4564 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE
)
4565 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB
)
4566 wxFLAGS_MEMBER(wxVSCROLL
)
4567 wxFLAGS_MEMBER(wxHSCROLL
)
4569 wxEND_FLAGS( wxGridStyle
)
4571 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid
, wxScrolledWindow
,"wx/grid.h")
4573 wxBEGIN_PROPERTIES_TABLE(wxGrid
)
4574 wxHIDE_PROPERTY( Children
)
4575 wxPROPERTY_FLAGS( WindowStyle
, wxGridStyle
, long , SetWindowStyleFlag
, GetWindowStyleFlag
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
4576 wxEND_PROPERTIES_TABLE()
4578 wxBEGIN_HANDLERS_TABLE(wxGrid
)
4579 wxEND_HANDLERS_TABLE()
4581 wxCONSTRUCTOR_5( wxGrid
, wxWindow
* , Parent
, wxWindowID
, Id
, wxPoint
, Position
, wxSize
, Size
, long , WindowStyle
)
4584 TODO : Expose more information of a list's layout, etc. via appropriate objects (e.g., NotebookPageInfo)
4587 IMPLEMENT_DYNAMIC_CLASS( wxGrid
, wxScrolledWindow
)
4590 BEGIN_EVENT_TABLE( wxGrid
, wxScrolledWindow
)
4591 EVT_PAINT( wxGrid::OnPaint
)
4592 EVT_SIZE( wxGrid::OnSize
)
4593 EVT_KEY_DOWN( wxGrid::OnKeyDown
)
4594 EVT_KEY_UP( wxGrid::OnKeyUp
)
4595 EVT_CHAR ( wxGrid::OnChar
)
4596 EVT_ERASE_BACKGROUND( wxGrid::OnEraseBackground
)
4599 bool wxGrid::Create(wxWindow
*parent
, wxWindowID id
,
4600 const wxPoint
& pos
, const wxSize
& size
,
4601 long style
, const wxString
& name
)
4603 if (!wxScrolledWindow::Create(parent
, id
, pos
, size
,
4604 style
| wxWANTS_CHARS
, name
))
4607 m_colMinWidths
= wxLongToLongHashMap(GRID_HASH_SIZE
);
4608 m_rowMinHeights
= wxLongToLongHashMap(GRID_HASH_SIZE
);
4611 SetInitialSize(size
);
4612 SetScrollRate(m_scrollLineX
, m_scrollLineY
);
4621 m_winCapture
->ReleaseMouse();
4623 // Ensure that the editor control is destroyed before the grid is,
4624 // otherwise we crash later when the editor tries to do something with the
4625 // half destroyed grid
4626 HideCellEditControl();
4628 // Must do this or ~wxScrollHelper will pop the wrong event handler
4629 SetTargetWindow(this);
4631 wxSafeDecRef(m_defaultCellAttr
);
4633 #ifdef DEBUG_ATTR_CACHE
4634 size_t total
= gs_nAttrCacheHits
+ gs_nAttrCacheMisses
;
4635 wxPrintf(_T("wxGrid attribute cache statistics: "
4636 "total: %u, hits: %u (%u%%)\n"),
4637 total
, gs_nAttrCacheHits
,
4638 total
? (gs_nAttrCacheHits
*100) / total
: 0);
4641 // if we own the table, just delete it, otherwise at least don't leave it
4642 // with dangling view pointer
4645 else if ( m_table
&& m_table
->GetView() == this )
4646 m_table
->SetView(NULL
);
4648 delete m_typeRegistry
;
4653 // ----- internal init and update functions
4656 // NOTE: If using the default visual attributes works everywhere then this can
4657 // be removed as well as the #else cases below.
4658 #define _USE_VISATTR 0
4660 void wxGrid::Create()
4662 // create the type registry
4663 m_typeRegistry
= new wxGridTypeRegistry
;
4665 m_cellEditCtrlEnabled
= false;
4667 m_defaultCellAttr
= new wxGridCellAttr();
4669 // Set default cell attributes
4670 m_defaultCellAttr
->SetDefAttr(m_defaultCellAttr
);
4671 m_defaultCellAttr
->SetKind(wxGridCellAttr::Default
);
4672 m_defaultCellAttr
->SetFont(GetFont());
4673 m_defaultCellAttr
->SetAlignment(wxALIGN_LEFT
, wxALIGN_TOP
);
4674 m_defaultCellAttr
->SetRenderer(new wxGridCellStringRenderer
);
4675 m_defaultCellAttr
->SetEditor(new wxGridCellTextEditor
);
4678 wxVisualAttributes gva
= wxListBox::GetClassDefaultAttributes();
4679 wxVisualAttributes lva
= wxPanel::GetClassDefaultAttributes();
4681 m_defaultCellAttr
->SetTextColour(gva
.colFg
);
4682 m_defaultCellAttr
->SetBackgroundColour(gva
.colBg
);
4685 m_defaultCellAttr
->SetTextColour(
4686 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
));
4687 m_defaultCellAttr
->SetBackgroundColour(
4688 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
4693 m_currentCellCoords
= wxGridNoCellCoords
;
4695 // subwindow components that make up the wxGrid
4696 m_rowLabelWin
= new wxGridRowLabelWindow(this);
4697 CreateColumnWindow();
4698 m_cornerLabelWin
= new wxGridCornerLabelWindow(this);
4699 m_gridWin
= new wxGridWindow( this );
4701 SetTargetWindow( m_gridWin
);
4704 wxColour gfg
= gva
.colFg
;
4705 wxColour gbg
= gva
.colBg
;
4706 wxColour lfg
= lva
.colFg
;
4707 wxColour lbg
= lva
.colBg
;
4709 wxColour gfg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT
);
4710 wxColour gbg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW
);
4711 wxColour lfg
= wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT
);
4712 wxColour lbg
= wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE
);
4715 m_cornerLabelWin
->SetOwnForegroundColour(lfg
);
4716 m_cornerLabelWin
->SetOwnBackgroundColour(lbg
);
4717 m_rowLabelWin
->SetOwnForegroundColour(lfg
);
4718 m_rowLabelWin
->SetOwnBackgroundColour(lbg
);
4719 m_colWindow
->SetOwnForegroundColour(lfg
);
4720 m_colWindow
->SetOwnBackgroundColour(lbg
);
4722 m_gridWin
->SetOwnForegroundColour(gfg
);
4723 m_gridWin
->SetOwnBackgroundColour(gbg
);
4725 m_labelBackgroundColour
= m_rowLabelWin
->GetBackgroundColour();
4726 m_labelTextColour
= m_rowLabelWin
->GetForegroundColour();
4728 // now that we have the grid window, use its font to compute the default
4730 m_defaultRowHeight
= m_gridWin
->GetCharHeight();
4731 #if defined(__WXMOTIF__) || defined(__WXGTK__) // see also text ctrl sizing in ShowCellEditControl()
4732 m_defaultRowHeight
+= 8;
4734 m_defaultRowHeight
+= 4;
4739 void wxGrid::CreateColumnWindow()
4741 if ( m_useNativeHeader
)
4743 m_colWindow
= new wxGridHeaderCtrl(this);
4744 m_colLabelHeight
= m_colWindow
->GetBestSize().y
;
4746 else // draw labels ourselves
4748 m_colWindow
= new wxGridColLabelWindow(this);
4749 m_colLabelHeight
= WXGRID_DEFAULT_COL_LABEL_HEIGHT
;
4753 bool wxGrid::CreateGrid( int numRows
, int numCols
,
4754 wxGridSelectionModes selmode
)
4756 wxCHECK_MSG( !m_created
,
4758 wxT("wxGrid::CreateGrid or wxGrid::SetTable called more than once") );
4760 return SetTable(new wxGridStringTable(numRows
, numCols
), true, selmode
);
4763 void wxGrid::SetSelectionMode(wxGridSelectionModes selmode
)
4765 wxCHECK_RET( m_created
,
4766 wxT("Called wxGrid::SetSelectionMode() before calling CreateGrid()") );
4768 m_selection
->SetSelectionMode( selmode
);
4771 wxGrid::wxGridSelectionModes
wxGrid::GetSelectionMode() const
4773 wxCHECK_MSG( m_created
, wxGridSelectCells
,
4774 wxT("Called wxGrid::GetSelectionMode() before calling CreateGrid()") );
4776 return m_selection
->GetSelectionMode();
4780 wxGrid::SetTable(wxGridTableBase
*table
,
4782 wxGrid::wxGridSelectionModes selmode
)
4784 bool checkSelection
= false;
4787 // stop all processing
4792 m_table
->SetView(0);
4804 checkSelection
= true;
4806 // kill row and column size arrays
4807 m_colWidths
.Empty();
4808 m_colRights
.Empty();
4809 m_rowHeights
.Empty();
4810 m_rowBottoms
.Empty();
4815 m_numRows
= table
->GetNumberRows();
4816 m_numCols
= table
->GetNumberCols();
4818 if ( m_useNativeHeader
)
4819 GetGridColHeader()->SetColumnCount(m_numCols
);
4822 m_table
->SetView( this );
4823 m_ownTable
= takeOwnership
;
4824 m_selection
= new wxGridSelection( this, selmode
);
4827 // If the newly set table is smaller than the
4828 // original one current cell and selection regions
4829 // might be invalid,
4830 m_selectedBlockCorner
= wxGridNoCellCoords
;
4831 m_currentCellCoords
=
4832 wxGridCellCoords(wxMin(m_numRows
, m_currentCellCoords
.GetRow()),
4833 wxMin(m_numCols
, m_currentCellCoords
.GetCol()));
4834 if (m_selectedBlockTopLeft
.GetRow() >= m_numRows
||
4835 m_selectedBlockTopLeft
.GetCol() >= m_numCols
)
4837 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
4838 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
4841 m_selectedBlockBottomRight
=
4842 wxGridCellCoords(wxMin(m_numRows
,
4843 m_selectedBlockBottomRight
.GetRow()),
4845 m_selectedBlockBottomRight
.GetCol()));
4859 m_cornerLabelWin
= NULL
;
4860 m_rowLabelWin
= NULL
;
4868 m_defaultCellAttr
= NULL
;
4869 m_typeRegistry
= NULL
;
4870 m_winCapture
= NULL
;
4872 m_rowLabelWidth
= WXGRID_DEFAULT_ROW_LABEL_WIDTH
;
4873 m_colLabelHeight
= WXGRID_DEFAULT_COL_LABEL_HEIGHT
;
4876 m_attrCache
.row
= -1;
4877 m_attrCache
.col
= -1;
4878 m_attrCache
.attr
= NULL
;
4880 m_labelFont
= GetFont();
4881 m_labelFont
.SetWeight( wxBOLD
);
4883 m_rowLabelHorizAlign
= wxALIGN_CENTRE
;
4884 m_rowLabelVertAlign
= wxALIGN_CENTRE
;
4886 m_colLabelHorizAlign
= wxALIGN_CENTRE
;
4887 m_colLabelVertAlign
= wxALIGN_CENTRE
;
4888 m_colLabelTextOrientation
= wxHORIZONTAL
;
4890 m_defaultColWidth
= WXGRID_DEFAULT_COL_WIDTH
;
4891 m_defaultRowHeight
= 0; // this will be initialized after creation
4893 m_minAcceptableColWidth
= WXGRID_MIN_COL_WIDTH
;
4894 m_minAcceptableRowHeight
= WXGRID_MIN_ROW_HEIGHT
;
4896 m_gridLineColour
= wxColour( 192,192,192 );
4897 m_gridLinesEnabled
= true;
4898 m_gridLinesClipHorz
=
4899 m_gridLinesClipVert
= true;
4900 m_cellHighlightColour
= *wxBLACK
;
4901 m_cellHighlightPenWidth
= 2;
4902 m_cellHighlightROPenWidth
= 1;
4904 m_canDragColMove
= false;
4906 m_cursorMode
= WXGRID_CURSOR_SELECT_CELL
;
4907 m_winCapture
= NULL
;
4908 m_canDragRowSize
= true;
4909 m_canDragColSize
= true;
4910 m_canDragGridSize
= true;
4911 m_canDragCell
= false;
4913 m_dragRowOrCol
= -1;
4914 m_isDragging
= false;
4915 m_startDragPos
= wxDefaultPosition
;
4917 m_sortCol
= wxNOT_FOUND
;
4918 m_sortIsAscending
= true;
4921 m_nativeColumnLabels
= false;
4923 m_waitForSlowClick
= false;
4925 m_rowResizeCursor
= wxCursor( wxCURSOR_SIZENS
);
4926 m_colResizeCursor
= wxCursor( wxCURSOR_SIZEWE
);
4928 m_currentCellCoords
= wxGridNoCellCoords
;
4930 m_selectedBlockTopLeft
=
4931 m_selectedBlockBottomRight
=
4932 m_selectedBlockCorner
= wxGridNoCellCoords
;
4934 m_selectionBackground
= wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT
);
4935 m_selectionForeground
= wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT
);
4937 m_editable
= true; // default for whole grid
4939 m_inOnKeyDown
= false;
4945 m_scrollLineX
= GRID_SCROLL_LINE_X
;
4946 m_scrollLineY
= GRID_SCROLL_LINE_Y
;
4949 // ----------------------------------------------------------------------------
4950 // the idea is to call these functions only when necessary because they create
4951 // quite big arrays which eat memory mostly unnecessary - in particular, if
4952 // default widths/heights are used for all rows/columns, we may not use these
4955 // with some extra code, it should be possible to only store the widths/heights
4956 // different from default ones (resulting in space savings for huge grids) but
4957 // this is not done currently
4958 // ----------------------------------------------------------------------------
4960 void wxGrid::InitRowHeights()
4962 m_rowHeights
.Empty();
4963 m_rowBottoms
.Empty();
4965 m_rowHeights
.Alloc( m_numRows
);
4966 m_rowBottoms
.Alloc( m_numRows
);
4968 m_rowHeights
.Add( m_defaultRowHeight
, m_numRows
);
4971 for ( int i
= 0; i
< m_numRows
; i
++ )
4973 rowBottom
+= m_defaultRowHeight
;
4974 m_rowBottoms
.Add( rowBottom
);
4978 void wxGrid::InitColWidths()
4980 m_colWidths
.Empty();
4981 m_colRights
.Empty();
4983 m_colWidths
.Alloc( m_numCols
);
4984 m_colRights
.Alloc( m_numCols
);
4986 m_colWidths
.Add( m_defaultColWidth
, m_numCols
);
4988 for ( int i
= 0; i
< m_numCols
; i
++ )
4990 int colRight
= ( GetColPos( i
) + 1 ) * m_defaultColWidth
;
4991 m_colRights
.Add( colRight
);
4995 int wxGrid::GetColWidth(int col
) const
4997 return m_colWidths
.IsEmpty() ? m_defaultColWidth
: m_colWidths
[col
];
5000 int wxGrid::GetColLeft(int col
) const
5002 return m_colRights
.IsEmpty() ? GetColPos( col
) * m_defaultColWidth
5003 : m_colRights
[col
] - m_colWidths
[col
];
5006 int wxGrid::GetColRight(int col
) const
5008 return m_colRights
.IsEmpty() ? (GetColPos( col
) + 1) * m_defaultColWidth
5012 int wxGrid::GetRowHeight(int row
) const
5014 return m_rowHeights
.IsEmpty() ? m_defaultRowHeight
: m_rowHeights
[row
];
5017 int wxGrid::GetRowTop(int row
) const
5019 return m_rowBottoms
.IsEmpty() ? row
* m_defaultRowHeight
5020 : m_rowBottoms
[row
] - m_rowHeights
[row
];
5023 int wxGrid::GetRowBottom(int row
) const
5025 return m_rowBottoms
.IsEmpty() ? (row
+ 1) * m_defaultRowHeight
5026 : m_rowBottoms
[row
];
5029 void wxGrid::CalcDimensions()
5031 // compute the size of the scrollable area
5032 int w
= m_numCols
> 0 ? GetColRight(GetColAt(m_numCols
- 1)) : 0;
5033 int h
= m_numRows
> 0 ? GetRowBottom(m_numRows
- 1) : 0;
5038 // take into account editor if shown
5039 if ( IsCellEditControlShown() )
5042 int r
= m_currentCellCoords
.GetRow();
5043 int c
= m_currentCellCoords
.GetCol();
5044 int x
= GetColLeft(c
);
5045 int y
= GetRowTop(r
);
5047 // how big is the editor
5048 wxGridCellAttr
* attr
= GetCellAttr(r
, c
);
5049 wxGridCellEditor
* editor
= attr
->GetEditor(this, r
, c
);
5050 editor
->GetControl()->GetSize(&w2
, &h2
);
5061 // preserve (more or less) the previous position
5063 GetViewStart( &x
, &y
);
5065 // ensure the position is valid for the new scroll ranges
5067 x
= wxMax( w
- 1, 0 );
5069 y
= wxMax( h
- 1, 0 );
5071 // update the virtual size and refresh the scrollbars to reflect it
5072 m_gridWin
->SetVirtualSize(w
, h
);
5076 // if our OnSize() hadn't been called (it would if we have scrollbars), we
5077 // still must reposition the children
5081 wxSize
wxGrid::GetSizeAvailableForScrollTarget(const wxSize
& size
)
5083 wxSize
sizeGridWin(size
);
5084 sizeGridWin
.x
-= m_rowLabelWidth
;
5085 sizeGridWin
.y
-= m_colLabelHeight
;
5090 void wxGrid::CalcWindowSizes()
5092 // escape if the window is has not been fully created yet
5094 if ( m_cornerLabelWin
== NULL
)
5098 GetClientSize( &cw
, &ch
);
5100 // the grid may be too small to have enough space for the labels yet, don't
5101 // size the windows to negative sizes in this case
5102 int gw
= cw
- m_rowLabelWidth
;
5103 int gh
= ch
- m_colLabelHeight
;
5109 if ( m_cornerLabelWin
&& m_cornerLabelWin
->IsShown() )
5110 m_cornerLabelWin
->SetSize( 0, 0, m_rowLabelWidth
, m_colLabelHeight
);
5112 if ( m_colWindow
&& m_colWindow
->IsShown() )
5113 m_colWindow
->SetSize( m_rowLabelWidth
, 0, gw
, m_colLabelHeight
);
5115 if ( m_rowLabelWin
&& m_rowLabelWin
->IsShown() )
5116 m_rowLabelWin
->SetSize( 0, m_colLabelHeight
, m_rowLabelWidth
, gh
);
5118 if ( m_gridWin
&& m_gridWin
->IsShown() )
5119 m_gridWin
->SetSize( m_rowLabelWidth
, m_colLabelHeight
, gw
, gh
);
5122 // this is called when the grid table sends a message
5123 // to indicate that it has been redimensioned
5125 bool wxGrid::Redimension( wxGridTableMessage
& msg
)
5128 bool result
= false;
5130 // Clear the attribute cache as the attribute might refer to a different
5131 // cell than stored in the cache after adding/removing rows/columns.
5134 // By the same reasoning, the editor should be dismissed if columns are
5135 // added or removed. And for consistency, it should IMHO always be
5136 // removed, not only if the cell "underneath" it actually changes.
5137 // For now, I intentionally do not save the editor's content as the
5138 // cell it might want to save that stuff to might no longer exist.
5139 HideCellEditControl();
5141 switch ( msg
.GetId() )
5143 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED
:
5145 size_t pos
= msg
.GetCommandInt();
5146 int numRows
= msg
.GetCommandInt2();
5148 m_numRows
+= numRows
;
5150 if ( !m_rowHeights
.IsEmpty() )
5152 m_rowHeights
.Insert( m_defaultRowHeight
, pos
, numRows
);
5153 m_rowBottoms
.Insert( 0, pos
, numRows
);
5157 bottom
= m_rowBottoms
[pos
- 1];
5159 for ( i
= pos
; i
< m_numRows
; i
++ )
5161 bottom
+= m_rowHeights
[i
];
5162 m_rowBottoms
[i
] = bottom
;
5166 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5168 // if we have just inserted cols into an empty grid the current
5169 // cell will be undefined...
5171 SetCurrentCell( 0, 0 );
5175 m_selection
->UpdateRows( pos
, numRows
);
5176 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5178 attrProvider
->UpdateAttrRows( pos
, numRows
);
5180 if ( !GetBatchCount() )
5183 m_rowLabelWin
->Refresh();
5189 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED
:
5191 int numRows
= msg
.GetCommandInt();
5192 int oldNumRows
= m_numRows
;
5193 m_numRows
+= numRows
;
5195 if ( !m_rowHeights
.IsEmpty() )
5197 m_rowHeights
.Add( m_defaultRowHeight
, numRows
);
5198 m_rowBottoms
.Add( 0, numRows
);
5201 if ( oldNumRows
> 0 )
5202 bottom
= m_rowBottoms
[oldNumRows
- 1];
5204 for ( i
= oldNumRows
; i
< m_numRows
; i
++ )
5206 bottom
+= m_rowHeights
[i
];
5207 m_rowBottoms
[i
] = bottom
;
5211 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5213 // if we have just inserted cols into an empty grid the current
5214 // cell will be undefined...
5216 SetCurrentCell( 0, 0 );
5219 if ( !GetBatchCount() )
5222 m_rowLabelWin
->Refresh();
5228 case wxGRIDTABLE_NOTIFY_ROWS_DELETED
:
5230 size_t pos
= msg
.GetCommandInt();
5231 int numRows
= msg
.GetCommandInt2();
5232 m_numRows
-= numRows
;
5234 if ( !m_rowHeights
.IsEmpty() )
5236 m_rowHeights
.RemoveAt( pos
, numRows
);
5237 m_rowBottoms
.RemoveAt( pos
, numRows
);
5240 for ( i
= 0; i
< m_numRows
; i
++ )
5242 h
+= m_rowHeights
[i
];
5243 m_rowBottoms
[i
] = h
;
5249 m_currentCellCoords
= wxGridNoCellCoords
;
5253 if ( m_currentCellCoords
.GetRow() >= m_numRows
)
5254 m_currentCellCoords
.Set( 0, 0 );
5258 m_selection
->UpdateRows( pos
, -((int)numRows
) );
5259 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5262 attrProvider
->UpdateAttrRows( pos
, -((int)numRows
) );
5264 // ifdef'd out following patch from Paul Gammans
5266 // No need to touch column attributes, unless we
5267 // removed _all_ rows, in this case, we remove
5268 // all column attributes.
5269 // I hate to do this here, but the
5270 // needed data is not available inside UpdateAttrRows.
5271 if ( !GetNumberRows() )
5272 attrProvider
->UpdateAttrCols( 0, -GetNumberCols() );
5276 if ( !GetBatchCount() )
5279 m_rowLabelWin
->Refresh();
5285 case wxGRIDTABLE_NOTIFY_COLS_INSERTED
:
5287 size_t pos
= msg
.GetCommandInt();
5288 int numCols
= msg
.GetCommandInt2();
5289 m_numCols
+= numCols
;
5291 if ( m_useNativeHeader
)
5292 GetGridColHeader()->SetColumnCount(m_numCols
);
5294 if ( !m_colAt
.IsEmpty() )
5296 //Shift the column IDs
5298 for ( i
= 0; i
< m_numCols
- numCols
; i
++ )
5300 if ( m_colAt
[i
] >= (int)pos
)
5301 m_colAt
[i
] += numCols
;
5304 m_colAt
.Insert( pos
, pos
, numCols
);
5306 //Set the new columns' positions
5307 for ( i
= pos
+ 1; i
< (int)pos
+ numCols
; i
++ )
5313 if ( !m_colWidths
.IsEmpty() )
5315 m_colWidths
.Insert( m_defaultColWidth
, pos
, numCols
);
5316 m_colRights
.Insert( 0, pos
, numCols
);
5320 right
= m_colRights
[GetColAt( pos
- 1 )];
5323 for ( colPos
= pos
; colPos
< m_numCols
; colPos
++ )
5325 i
= GetColAt( colPos
);
5327 right
+= m_colWidths
[i
];
5328 m_colRights
[i
] = right
;
5332 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5334 // if we have just inserted cols into an empty grid the current
5335 // cell will be undefined...
5337 SetCurrentCell( 0, 0 );
5341 m_selection
->UpdateCols( pos
, numCols
);
5342 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5344 attrProvider
->UpdateAttrCols( pos
, numCols
);
5345 if ( !GetBatchCount() )
5348 m_colWindow
->Refresh();
5354 case wxGRIDTABLE_NOTIFY_COLS_APPENDED
:
5356 int numCols
= msg
.GetCommandInt();
5357 int oldNumCols
= m_numCols
;
5358 m_numCols
+= numCols
;
5359 if ( m_useNativeHeader
)
5360 GetGridColHeader()->SetColumnCount(m_numCols
);
5362 if ( !m_colAt
.IsEmpty() )
5364 m_colAt
.Add( 0, numCols
);
5366 //Set the new columns' positions
5368 for ( i
= oldNumCols
; i
< m_numCols
; i
++ )
5374 if ( !m_colWidths
.IsEmpty() )
5376 m_colWidths
.Add( m_defaultColWidth
, numCols
);
5377 m_colRights
.Add( 0, numCols
);
5380 if ( oldNumCols
> 0 )
5381 right
= m_colRights
[GetColAt( oldNumCols
- 1 )];
5384 for ( colPos
= oldNumCols
; colPos
< m_numCols
; colPos
++ )
5386 i
= GetColAt( colPos
);
5388 right
+= m_colWidths
[i
];
5389 m_colRights
[i
] = right
;
5393 if ( m_currentCellCoords
== wxGridNoCellCoords
)
5395 // if we have just inserted cols into an empty grid the current
5396 // cell will be undefined...
5398 SetCurrentCell( 0, 0 );
5400 if ( !GetBatchCount() )
5403 m_colWindow
->Refresh();
5409 case wxGRIDTABLE_NOTIFY_COLS_DELETED
:
5411 size_t pos
= msg
.GetCommandInt();
5412 int numCols
= msg
.GetCommandInt2();
5413 m_numCols
-= numCols
;
5414 if ( m_useNativeHeader
)
5415 GetGridColHeader()->SetColumnCount(m_numCols
);
5417 if ( !m_colAt
.IsEmpty() )
5419 int colID
= GetColAt( pos
);
5421 m_colAt
.RemoveAt( pos
, numCols
);
5423 //Shift the column IDs
5425 for ( colPos
= 0; colPos
< m_numCols
; colPos
++ )
5427 if ( m_colAt
[colPos
] > colID
)
5428 m_colAt
[colPos
] -= numCols
;
5432 if ( !m_colWidths
.IsEmpty() )
5434 m_colWidths
.RemoveAt( pos
, numCols
);
5435 m_colRights
.RemoveAt( pos
, numCols
);
5439 for ( colPos
= 0; colPos
< m_numCols
; colPos
++ )
5441 i
= GetColAt( colPos
);
5443 w
+= m_colWidths
[i
];
5450 m_currentCellCoords
= wxGridNoCellCoords
;
5454 if ( m_currentCellCoords
.GetCol() >= m_numCols
)
5455 m_currentCellCoords
.Set( 0, 0 );
5459 m_selection
->UpdateCols( pos
, -((int)numCols
) );
5460 wxGridCellAttrProvider
* attrProvider
= m_table
->GetAttrProvider();
5463 attrProvider
->UpdateAttrCols( pos
, -((int)numCols
) );
5465 // ifdef'd out following patch from Paul Gammans
5467 // No need to touch row attributes, unless we
5468 // removed _all_ columns, in this case, we remove
5469 // all row attributes.
5470 // I hate to do this here, but the
5471 // needed data is not available inside UpdateAttrCols.
5472 if ( !GetNumberCols() )
5473 attrProvider
->UpdateAttrRows( 0, -GetNumberRows() );
5477 if ( !GetBatchCount() )
5480 m_colWindow
->Refresh();
5487 if (result
&& !GetBatchCount() )
5488 m_gridWin
->Refresh();
5493 wxArrayInt
wxGrid::CalcRowLabelsExposed( const wxRegion
& reg
) const
5495 wxRegionIterator
iter( reg
);
5498 wxArrayInt rowlabels
;
5505 // TODO: remove this when we can...
5506 // There is a bug in wxMotif that gives garbage update
5507 // rectangles if you jump-scroll a long way by clicking the
5508 // scrollbar with middle button. This is a work-around
5510 #if defined(__WXMOTIF__)
5512 m_gridWin
->GetClientSize( &cw
, &ch
);
5513 if ( r
.GetTop() > ch
)
5515 r
.SetBottom( wxMin( r
.GetBottom(), ch
) );
5518 // logical bounds of update region
5521 CalcUnscrolledPosition( 0, r
.GetTop(), &dummy
, &top
);
5522 CalcUnscrolledPosition( 0, r
.GetBottom(), &dummy
, &bottom
);
5524 // find the row labels within these bounds
5527 for ( row
= internalYToRow(top
); row
< m_numRows
; row
++ )
5529 if ( GetRowBottom(row
) < top
)
5532 if ( GetRowTop(row
) > bottom
)
5535 rowlabels
.Add( row
);
5544 wxArrayInt
wxGrid::CalcColLabelsExposed( const wxRegion
& reg
) const
5546 wxRegionIterator
iter( reg
);
5549 wxArrayInt colLabels
;
5556 // TODO: remove this when we can...
5557 // There is a bug in wxMotif that gives garbage update
5558 // rectangles if you jump-scroll a long way by clicking the
5559 // scrollbar with middle button. This is a work-around
5561 #if defined(__WXMOTIF__)
5563 m_gridWin
->GetClientSize( &cw
, &ch
);
5564 if ( r
.GetLeft() > cw
)
5566 r
.SetRight( wxMin( r
.GetRight(), cw
) );
5569 // logical bounds of update region
5572 CalcUnscrolledPosition( r
.GetLeft(), 0, &left
, &dummy
);
5573 CalcUnscrolledPosition( r
.GetRight(), 0, &right
, &dummy
);
5575 // find the cells within these bounds
5579 for ( colPos
= GetColPos( internalXToCol(left
) ); colPos
< m_numCols
; colPos
++ )
5581 col
= GetColAt( colPos
);
5583 if ( GetColRight(col
) < left
)
5586 if ( GetColLeft(col
) > right
)
5589 colLabels
.Add( col
);
5598 wxGridCellCoordsArray
wxGrid::CalcCellsExposed( const wxRegion
& reg
) const
5600 wxRegionIterator
iter( reg
);
5603 wxGridCellCoordsArray cellsExposed
;
5605 int left
, top
, right
, bottom
;
5610 // TODO: remove this when we can...
5611 // There is a bug in wxMotif that gives garbage update
5612 // rectangles if you jump-scroll a long way by clicking the
5613 // scrollbar with middle button. This is a work-around
5615 #if defined(__WXMOTIF__)
5617 m_gridWin
->GetClientSize( &cw
, &ch
);
5618 if ( r
.GetTop() > ch
) r
.SetTop( 0 );
5619 if ( r
.GetLeft() > cw
) r
.SetLeft( 0 );
5620 r
.SetRight( wxMin( r
.GetRight(), cw
) );
5621 r
.SetBottom( wxMin( r
.GetBottom(), ch
) );
5624 // logical bounds of update region
5626 CalcUnscrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
5627 CalcUnscrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
5629 // find the cells within these bounds
5631 for ( int row
= internalYToRow(top
); row
< m_numRows
; row
++ )
5633 if ( GetRowBottom(row
) <= top
)
5636 if ( GetRowTop(row
) > bottom
)
5639 // add all dirty cells in this row: notice that the columns which
5640 // are dirty don't depend on the row so we compute them only once
5641 // for the first dirty row and then reuse for all the next ones
5644 // do determine the dirty columns
5645 for ( int pos
= XToPos(left
); pos
<= XToPos(right
); pos
++ )
5646 cols
.push_back(GetColAt(pos
));
5648 // if there are no dirty columns at all, nothing to do
5653 const size_t count
= cols
.size();
5654 for ( size_t n
= 0; n
< count
; n
++ )
5655 cellsExposed
.Add(wxGridCellCoords(row
, cols
[n
]));
5661 return cellsExposed
;
5665 void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent
& event
)
5668 wxPoint
pos( event
.GetPosition() );
5669 CalcUnscrolledPosition( pos
.x
, pos
.y
, &x
, &y
);
5671 if ( event
.Dragging() )
5675 m_isDragging
= true;
5676 m_rowLabelWin
->CaptureMouse();
5679 if ( event
.LeftIsDown() )
5681 switch ( m_cursorMode
)
5683 case WXGRID_CURSOR_RESIZE_ROW
:
5685 int cw
, ch
, left
, dummy
;
5686 m_gridWin
->GetClientSize( &cw
, &ch
);
5687 CalcUnscrolledPosition( 0, 0, &left
, &dummy
);
5689 wxClientDC
dc( m_gridWin
);
5692 GetRowTop(m_dragRowOrCol
) +
5693 GetRowMinimalHeight(m_dragRowOrCol
) );
5694 dc
.SetLogicalFunction(wxINVERT
);
5695 if ( m_dragLastPos
>= 0 )
5697 dc
.DrawLine( left
, m_dragLastPos
, left
+cw
, m_dragLastPos
);
5699 dc
.DrawLine( left
, y
, left
+cw
, y
);
5704 case WXGRID_CURSOR_SELECT_ROW
:
5706 if ( (row
= YToRow( y
)) >= 0 )
5709 m_selection
->SelectRow(row
, event
);
5714 // default label to suppress warnings about "enumeration value
5715 // 'xxx' not handled in switch
5723 if ( m_isDragging
&& (event
.Entering() || event
.Leaving()) )
5728 if (m_rowLabelWin
->HasCapture())
5729 m_rowLabelWin
->ReleaseMouse();
5730 m_isDragging
= false;
5733 // ------------ Entering or leaving the window
5735 if ( event
.Entering() || event
.Leaving() )
5737 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
);
5740 // ------------ Left button pressed
5742 else if ( event
.LeftDown() )
5744 // don't send a label click event for a hit on the
5745 // edge of the row label - this is probably the user
5746 // wanting to resize the row
5748 if ( YToEdgeOfRow(y
) < 0 )
5752 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, row
, -1, event
) )
5754 if ( !event
.ShiftDown() && !event
.CmdDown() )
5758 if ( event
.ShiftDown() )
5760 m_selection
->SelectBlock
5762 m_currentCellCoords
.GetRow(), 0,
5763 row
, GetNumberCols() - 1,
5769 m_selection
->SelectRow(row
, event
);
5773 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW
, m_rowLabelWin
);
5778 // starting to drag-resize a row
5779 if ( CanDragRowSize() )
5780 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, m_rowLabelWin
);
5784 // ------------ Left double click
5786 else if (event
.LeftDClick() )
5788 row
= YToEdgeOfRow(y
);
5793 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, row
, -1, event
) )
5795 // no default action at the moment
5800 // adjust row height depending on label text
5801 AutoSizeRowLabelSize( row
);
5803 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
5808 // ------------ Left button released
5810 else if ( event
.LeftUp() )
5812 if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
)
5814 DoEndDragResizeRow();
5816 // Note: we are ending the event *after* doing
5817 // default processing in this case
5819 SendEvent( wxEVT_GRID_ROW_SIZE
, m_dragRowOrCol
, -1, event
);
5822 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
);
5826 // ------------ Right button down
5828 else if ( event
.RightDown() )
5832 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, row
, -1, event
) )
5834 // no default action at the moment
5838 // ------------ Right double click
5840 else if ( event
.RightDClick() )
5844 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, row
, -1, event
) )
5846 // no default action at the moment
5850 // ------------ No buttons down and mouse moving
5852 else if ( event
.Moving() )
5854 m_dragRowOrCol
= YToEdgeOfRow( y
);
5855 if ( m_dragRowOrCol
>= 0 )
5857 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
5859 // don't capture the mouse yet
5860 if ( CanDragRowSize() )
5861 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, m_rowLabelWin
, false);
5864 else if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
5866 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, m_rowLabelWin
, false);
5871 void wxGrid::UpdateColumnSortingIndicator(int col
)
5873 wxCHECK_RET( col
!= wxNOT_FOUND
, "invalid column index" );
5875 if ( m_useNativeHeader
)
5876 GetGridColHeader()->UpdateColumn(col
);
5877 else if ( m_nativeColumnLabels
)
5878 m_colWindow
->Refresh();
5879 //else: sorting indicator display not yet implemented in grid version
5882 void wxGrid::SetSortingColumn(int col
, bool ascending
)
5884 if ( col
== m_sortCol
)
5886 // we are already using this column for sorting (or not sorting at all)
5887 // but we might still change the sorting order, check for it
5888 if ( m_sortCol
!= wxNOT_FOUND
&& ascending
!= m_sortIsAscending
)
5890 m_sortIsAscending
= ascending
;
5892 UpdateColumnSortingIndicator(m_sortCol
);
5895 else // we're changing the column used for sorting
5897 const int sortColOld
= m_sortCol
;
5899 // change it before updating the column as we want GetSortingColumn()
5900 // to return the correct new value
5903 if ( sortColOld
!= wxNOT_FOUND
)
5904 UpdateColumnSortingIndicator(sortColOld
);
5906 if ( m_sortCol
!= wxNOT_FOUND
)
5908 m_sortIsAscending
= ascending
;
5909 UpdateColumnSortingIndicator(m_sortCol
);
5914 void wxGrid::DoColHeaderClick(int col
)
5916 // we consider that the grid was resorted if this event is processed and
5918 if ( SendEvent(wxEVT_GRID_COL_SORT
, -1, col
) == 1 )
5920 SetSortingColumn(col
, IsSortingBy(col
) ? !m_sortIsAscending
: true);
5925 void wxGrid::DoStartResizeCol(int col
)
5927 m_dragRowOrCol
= col
;
5929 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol
));
5932 void wxGrid::DoUpdateResizeCol(int x
)
5934 int cw
, ch
, dummy
, top
;
5935 m_gridWin
->GetClientSize( &cw
, &ch
);
5936 CalcUnscrolledPosition( 0, 0, &dummy
, &top
);
5938 wxClientDC
dc( m_gridWin
);
5941 x
= wxMax( x
, GetColLeft(m_dragRowOrCol
) + GetColMinimalWidth(m_dragRowOrCol
));
5942 dc
.SetLogicalFunction(wxINVERT
);
5943 if ( m_dragLastPos
>= 0 )
5945 dc
.DrawLine( m_dragLastPos
, top
, m_dragLastPos
, top
+ ch
);
5947 dc
.DrawLine( x
, top
, x
, top
+ ch
);
5951 void wxGrid::DoUpdateResizeColWidth(int w
)
5953 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol
) + w
);
5956 void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent
& event
)
5959 wxPoint
pos( event
.GetPosition() );
5960 CalcUnscrolledPosition( pos
.x
, pos
.y
, &x
, &y
);
5962 int col
= XToCol(x
);
5963 if ( event
.Dragging() )
5967 m_isDragging
= true;
5968 GetColLabelWindow()->CaptureMouse();
5970 if ( m_cursorMode
== WXGRID_CURSOR_MOVE_COL
&& col
!= -1 )
5971 DoStartMoveCol(col
);
5974 if ( event
.LeftIsDown() )
5976 switch ( m_cursorMode
)
5978 case WXGRID_CURSOR_RESIZE_COL
:
5979 DoUpdateResizeCol(x
);
5982 case WXGRID_CURSOR_SELECT_COL
:
5987 m_selection
->SelectCol(col
, event
);
5992 case WXGRID_CURSOR_MOVE_COL
:
5994 int posNew
= XToPos(x
);
5995 int colNew
= GetColAt(posNew
);
5997 // determine the position of the drop marker
5999 if ( x
>= GetColLeft(colNew
) + (GetColWidth(colNew
) / 2) )
6000 markerX
= GetColRight(colNew
);
6002 markerX
= GetColLeft(colNew
);
6004 if ( markerX
!= m_dragLastPos
)
6006 wxClientDC
dc( GetColLabelWindow() );
6010 GetColLabelWindow()->GetClientSize( &cw
, &ch
);
6014 //Clean up the last indicator
6015 if ( m_dragLastPos
>= 0 )
6017 wxPen
pen( GetColLabelWindow()->GetBackgroundColour(), 2 );
6019 dc
.DrawLine( m_dragLastPos
+ 1, 0, m_dragLastPos
+ 1, ch
);
6020 dc
.SetPen(wxNullPen
);
6022 if ( XToCol( m_dragLastPos
) != -1 )
6023 DrawColLabel( dc
, XToCol( m_dragLastPos
) );
6026 const wxColour
*color
;
6027 //Moving to the same place? Don't draw a marker
6028 if ( colNew
== m_dragRowOrCol
)
6029 color
= wxLIGHT_GREY
;
6034 wxPen
pen( *color
, 2 );
6037 dc
.DrawLine( markerX
, 0, markerX
, ch
);
6039 dc
.SetPen(wxNullPen
);
6041 m_dragLastPos
= markerX
- 1;
6046 // default label to suppress warnings about "enumeration value
6047 // 'xxx' not handled in switch
6055 if ( m_isDragging
&& (event
.Entering() || event
.Leaving()) )
6060 if (GetColLabelWindow()->HasCapture())
6061 GetColLabelWindow()->ReleaseMouse();
6062 m_isDragging
= false;
6065 // ------------ Entering or leaving the window
6067 if ( event
.Entering() || event
.Leaving() )
6069 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6072 // ------------ Left button pressed
6074 else if ( event
.LeftDown() )
6076 // don't send a label click event for a hit on the
6077 // edge of the col label - this is probably the user
6078 // wanting to resize the col
6080 if ( XToEdgeOfCol(x
) < 0 )
6083 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, -1, col
, event
) )
6085 if ( m_canDragColMove
)
6087 //Show button as pressed
6088 wxClientDC
dc( GetColLabelWindow() );
6089 int colLeft
= GetColLeft( col
);
6090 int colRight
= GetColRight( col
) - 1;
6091 dc
.SetPen( wxPen( GetColLabelWindow()->GetBackgroundColour(), 1 ) );
6092 dc
.DrawLine( colLeft
, 1, colLeft
, m_colLabelHeight
-1 );
6093 dc
.DrawLine( colLeft
, 1, colRight
, 1 );
6095 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL
, GetColLabelWindow());
6099 if ( !event
.ShiftDown() && !event
.CmdDown() )
6103 if ( event
.ShiftDown() )
6105 m_selection
->SelectBlock
6107 0, m_currentCellCoords
.GetCol(),
6108 GetNumberRows() - 1, col
,
6114 m_selection
->SelectCol(col
, event
);
6118 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL
, GetColLabelWindow());
6124 // starting to drag-resize a col
6126 if ( CanDragColSize() )
6127 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, GetColLabelWindow());
6131 // ------------ Left double click
6133 if ( event
.LeftDClick() )
6135 const int colEdge
= XToEdgeOfCol(x
);
6136 if ( colEdge
== -1 )
6139 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, -1, col
, event
) )
6141 // no default action at the moment
6146 // adjust column width depending on label text
6147 AutoSizeColLabelSize( colEdge
);
6149 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6154 // ------------ Left button released
6156 else if ( event
.LeftUp() )
6158 switch ( m_cursorMode
)
6160 case WXGRID_CURSOR_RESIZE_COL
:
6161 DoEndDragResizeCol();
6164 case WXGRID_CURSOR_MOVE_COL
:
6165 if ( m_dragLastPos
== -1 || col
== m_dragRowOrCol
)
6167 // the column didn't actually move anywhere
6169 DoColHeaderClick(col
);
6170 m_colWindow
->Refresh(); // "unpress" the column
6174 DoEndMoveCol(XToPos(x
));
6178 case WXGRID_CURSOR_SELECT_COL
:
6179 case WXGRID_CURSOR_SELECT_CELL
:
6180 case WXGRID_CURSOR_RESIZE_ROW
:
6181 case WXGRID_CURSOR_SELECT_ROW
:
6183 DoColHeaderClick(col
);
6187 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow());
6191 // ------------ Right button down
6193 else if ( event
.RightDown() )
6196 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, -1, col
, event
) )
6198 // no default action at the moment
6202 // ------------ Right double click
6204 else if ( event
.RightDClick() )
6207 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, -1, col
, event
) )
6209 // no default action at the moment
6213 // ------------ No buttons down and mouse moving
6215 else if ( event
.Moving() )
6217 m_dragRowOrCol
= XToEdgeOfCol( x
);
6218 if ( m_dragRowOrCol
>= 0 )
6220 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6222 // don't capture the cursor yet
6223 if ( CanDragColSize() )
6224 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, GetColLabelWindow(), false);
6227 else if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
6229 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
, GetColLabelWindow(), false);
6234 void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent
& event
)
6236 if ( event
.LeftDown() )
6238 // indicate corner label by having both row and
6241 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK
, -1, -1, event
) )
6246 else if ( event
.LeftDClick() )
6248 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK
, -1, -1, event
);
6250 else if ( event
.RightDown() )
6252 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK
, -1, -1, event
) )
6254 // no default action at the moment
6257 else if ( event
.RightDClick() )
6259 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK
, -1, -1, event
) )
6261 // no default action at the moment
6266 void wxGrid::CancelMouseCapture()
6268 // cancel operation currently in progress, whatever it is
6271 m_isDragging
= false;
6272 m_startDragPos
= wxDefaultPosition
;
6274 m_cursorMode
= WXGRID_CURSOR_SELECT_CELL
;
6275 m_winCapture
->SetCursor( *wxSTANDARD_CURSOR
);
6276 m_winCapture
= NULL
;
6278 // remove traces of whatever we drew on screen
6283 void wxGrid::ChangeCursorMode(CursorMode mode
,
6288 static const wxChar
*cursorModes
[] =
6298 wxLogTrace(_T("grid"),
6299 _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
6300 win
== m_colWindow
? _T("colLabelWin")
6301 : win
? _T("rowLabelWin")
6303 cursorModes
[m_cursorMode
], cursorModes
[mode
]);
6306 if ( mode
== m_cursorMode
&&
6307 win
== m_winCapture
&&
6308 captureMouse
== (m_winCapture
!= NULL
))
6313 // by default use the grid itself
6319 m_winCapture
->ReleaseMouse();
6320 m_winCapture
= NULL
;
6323 m_cursorMode
= mode
;
6325 switch ( m_cursorMode
)
6327 case WXGRID_CURSOR_RESIZE_ROW
:
6328 win
->SetCursor( m_rowResizeCursor
);
6331 case WXGRID_CURSOR_RESIZE_COL
:
6332 win
->SetCursor( m_colResizeCursor
);
6335 case WXGRID_CURSOR_MOVE_COL
:
6336 win
->SetCursor( wxCursor(wxCURSOR_HAND
) );
6340 win
->SetCursor( *wxSTANDARD_CURSOR
);
6344 // we need to capture mouse when resizing
6345 bool resize
= m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
||
6346 m_cursorMode
== WXGRID_CURSOR_RESIZE_COL
;
6348 if ( captureMouse
&& resize
)
6350 win
->CaptureMouse();
6355 // ----------------------------------------------------------------------------
6356 // grid mouse event processing
6357 // ----------------------------------------------------------------------------
6360 wxGrid::DoGridCellDrag(wxMouseEvent
& event
,
6361 const wxGridCellCoords
& coords
,
6364 if ( coords
== wxGridNoCellCoords
)
6365 return; // we're outside any valid cell
6367 // Hide the edit control, so it won't interfere with drag-shrinking.
6368 if ( IsCellEditControlShown() )
6370 HideCellEditControl();
6371 SaveEditControlValue();
6374 switch ( event
.GetModifiers() )
6377 if ( m_selectedBlockCorner
== wxGridNoCellCoords
)
6378 m_selectedBlockCorner
= coords
;
6379 UpdateBlockBeingSelected(m_selectedBlockCorner
, coords
);
6383 if ( CanDragCell() )
6387 if ( m_selectedBlockCorner
== wxGridNoCellCoords
)
6388 m_selectedBlockCorner
= coords
;
6390 SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG
, coords
, event
);
6395 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
6399 // we don't handle the other key modifiers
6404 void wxGrid::DoGridLineDrag(wxMouseEvent
& event
, const wxGridOperations
& oper
)
6406 wxClientDC
dc(m_gridWin
);
6408 dc
.SetLogicalFunction(wxINVERT
);
6410 const wxRect
rectWin(CalcUnscrolledPosition(wxPoint(0, 0)),
6411 m_gridWin
->GetClientSize());
6413 // erase the previously drawn line, if any
6414 if ( m_dragLastPos
>= 0 )
6415 oper
.DrawParallelLineInRect(dc
, rectWin
, m_dragLastPos
);
6417 // we need the vertical position for rows and horizontal for columns here
6418 m_dragLastPos
= oper
.Dual().Select(CalcUnscrolledPosition(event
.GetPosition()));
6420 // don't allow resizing beneath the minimal size
6421 const int posMin
= oper
.GetLineStartPos(this, m_dragRowOrCol
) +
6422 oper
.GetMinimalLineSize(this, m_dragRowOrCol
);
6423 if ( m_dragLastPos
< posMin
)
6424 m_dragLastPos
= posMin
;
6426 // and draw it at the new position
6427 oper
.DrawParallelLineInRect(dc
, rectWin
, m_dragLastPos
);
6430 void wxGrid::DoGridDragEvent(wxMouseEvent
& event
, const wxGridCellCoords
& coords
)
6432 if ( !m_isDragging
)
6434 // Don't start doing anything until the mouse has been dragged far
6436 const wxPoint
& pt
= event
.GetPosition();
6437 if ( m_startDragPos
== wxDefaultPosition
)
6439 m_startDragPos
= pt
;
6443 if ( abs(m_startDragPos
.x
- pt
.x
) <= DRAG_SENSITIVITY
&&
6444 abs(m_startDragPos
.y
- pt
.y
) <= DRAG_SENSITIVITY
)
6448 const bool isFirstDrag
= !m_isDragging
;
6449 m_isDragging
= true;
6451 switch ( m_cursorMode
)
6453 case WXGRID_CURSOR_SELECT_CELL
:
6454 DoGridCellDrag(event
, coords
, isFirstDrag
);
6457 case WXGRID_CURSOR_RESIZE_ROW
:
6458 DoGridLineDrag(event
, wxGridRowOperations());
6461 case WXGRID_CURSOR_RESIZE_COL
:
6462 DoGridLineDrag(event
, wxGridColumnOperations());
6471 m_winCapture
= m_gridWin
;
6472 m_winCapture
->CaptureMouse();
6477 wxGrid::DoGridCellLeftDown(wxMouseEvent
& event
,
6478 const wxGridCellCoords
& coords
,
6481 if ( SendEvent(wxEVT_GRID_CELL_LEFT_CLICK
, coords
, event
) )
6483 // event handled by user code, no need to do anything here
6487 if ( !event
.CmdDown() )
6490 if ( event
.ShiftDown() )
6494 m_selection
->SelectBlock(m_currentCellCoords
, coords
, event
);
6495 m_selectedBlockCorner
= coords
;
6498 else if ( XToEdgeOfCol(pos
.x
) < 0 && YToEdgeOfRow(pos
.y
) < 0 )
6500 DisableCellEditControl();
6501 MakeCellVisible( coords
);
6503 if ( event
.CmdDown() )
6507 m_selection
->ToggleCellSelection(coords
, event
);
6510 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
6511 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
6512 m_selectedBlockCorner
= coords
;
6516 m_waitForSlowClick
= m_currentCellCoords
== coords
&&
6517 coords
!= wxGridNoCellCoords
;
6518 SetCurrentCell( coords
);
6524 wxGrid::DoGridCellLeftDClick(wxMouseEvent
& event
,
6525 const wxGridCellCoords
& coords
,
6528 if ( XToEdgeOfCol(pos
.x
) < 0 && YToEdgeOfRow(pos
.y
) < 0 )
6530 if ( !SendEvent(wxEVT_GRID_CELL_LEFT_DCLICK
, coords
, event
) )
6532 // we want double click to select a cell and start editing
6533 // (i.e. to behave in same way as sequence of two slow clicks):
6534 m_waitForSlowClick
= true;
6540 wxGrid::DoGridCellLeftUp(wxMouseEvent
& event
, const wxGridCellCoords
& coords
)
6542 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6546 m_winCapture
->ReleaseMouse();
6547 m_winCapture
= NULL
;
6550 if ( coords
== m_currentCellCoords
&& m_waitForSlowClick
&& CanEnableCellControl() )
6553 EnableCellEditControl();
6555 wxGridCellAttr
*attr
= GetCellAttr(coords
);
6556 wxGridCellEditor
*editor
= attr
->GetEditor(this, coords
.GetRow(), coords
.GetCol());
6557 editor
->StartingClick();
6561 m_waitForSlowClick
= false;
6563 else if ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
6564 m_selectedBlockBottomRight
!= wxGridNoCellCoords
)
6568 m_selection
->SelectBlock( m_selectedBlockTopLeft
,
6569 m_selectedBlockBottomRight
,
6573 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
6574 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
6576 // Show the edit control, if it has been hidden for
6578 ShowCellEditControl();
6581 else if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_ROW
)
6583 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6584 DoEndDragResizeRow();
6586 // Note: we are ending the event *after* doing
6587 // default processing in this case
6589 SendEvent( wxEVT_GRID_ROW_SIZE
, m_dragRowOrCol
, -1, event
);
6591 else if ( m_cursorMode
== WXGRID_CURSOR_RESIZE_COL
)
6593 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6594 DoEndDragResizeCol();
6601 wxGrid::DoGridMouseMoveEvent(wxMouseEvent
& WXUNUSED(event
),
6602 const wxGridCellCoords
& coords
,
6605 if ( coords
.GetRow() < 0 || coords
.GetCol() < 0 )
6607 // out of grid cell area
6608 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6612 int dragRow
= YToEdgeOfRow( pos
.y
);
6613 int dragCol
= XToEdgeOfCol( pos
.x
);
6615 // Dragging on the corner of a cell to resize in both
6616 // directions is not implemented yet...
6618 if ( dragRow
>= 0 && dragCol
>= 0 )
6620 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6626 m_dragRowOrCol
= dragRow
;
6628 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6630 if ( CanDragRowSize() && CanDragGridSize() )
6631 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW
, NULL
, false);
6634 // When using the native header window we can only resize the columns by
6635 // dragging the dividers in it because we can't make it enter into the
6636 // column resizing mode programmatically
6637 else if ( dragCol
>= 0 && !m_useNativeHeader
)
6639 m_dragRowOrCol
= dragCol
;
6641 if ( m_cursorMode
== WXGRID_CURSOR_SELECT_CELL
)
6643 if ( CanDragColSize() && CanDragGridSize() )
6644 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL
, NULL
, false);
6647 else // Neither on a row or col edge
6649 if ( m_cursorMode
!= WXGRID_CURSOR_SELECT_CELL
)
6651 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6656 void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent
& event
)
6658 const wxPoint pos
= CalcUnscrolledPosition(event
.GetPosition());
6660 // coordinates of the cell under mouse
6661 wxGridCellCoords coords
= XYToCell(pos
);
6663 int cell_rows
, cell_cols
;
6664 GetCellSize( coords
.GetRow(), coords
.GetCol(), &cell_rows
, &cell_cols
);
6665 if ( (cell_rows
< 0) || (cell_cols
< 0) )
6667 coords
.SetRow(coords
.GetRow() + cell_rows
);
6668 coords
.SetCol(coords
.GetCol() + cell_cols
);
6671 if ( event
.Dragging() )
6673 if ( event
.LeftIsDown() )
6674 DoGridDragEvent(event
, coords
);
6680 m_isDragging
= false;
6681 m_startDragPos
= wxDefaultPosition
;
6683 // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL
6684 // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under
6687 if ( event
.Entering() || event
.Leaving() )
6689 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL
);
6690 m_gridWin
->SetCursor( *wxSTANDARD_CURSOR
);
6694 // deal with various button presses
6695 if ( event
.IsButton() )
6697 if ( coords
!= wxGridNoCellCoords
)
6699 DisableCellEditControl();
6701 if ( event
.LeftDown() )
6702 DoGridCellLeftDown(event
, coords
, pos
);
6703 else if ( event
.LeftDClick() )
6704 DoGridCellLeftDClick(event
, coords
, pos
);
6705 else if ( event
.RightDown() )
6706 SendEvent(wxEVT_GRID_CELL_RIGHT_CLICK
, coords
, event
);
6707 else if ( event
.RightDClick() )
6708 SendEvent(wxEVT_GRID_CELL_RIGHT_DCLICK
, coords
, event
);
6711 // this one should be called even if we're not over any cell
6712 if ( event
.LeftUp() )
6714 DoGridCellLeftUp(event
, coords
);
6717 else if ( event
.Moving() )
6719 DoGridMouseMoveEvent(event
, coords
, pos
);
6721 else // unknown mouse event?
6727 void wxGrid::DoEndDragResizeLine(const wxGridOperations
& oper
)
6729 if ( m_dragLastPos
== -1 )
6732 const wxGridOperations
& doper
= oper
.Dual();
6734 const wxSize size
= m_gridWin
->GetClientSize();
6736 const wxPoint ptOrigin
= CalcUnscrolledPosition(wxPoint(0, 0));
6738 // erase the last line we drew
6739 wxClientDC
dc(m_gridWin
);
6741 dc
.SetLogicalFunction(wxINVERT
);
6743 const int posLineStart
= oper
.Select(ptOrigin
);
6744 const int posLineEnd
= oper
.Select(ptOrigin
) + oper
.Select(size
);
6746 oper
.DrawParallelLine(dc
, posLineStart
, posLineEnd
, m_dragLastPos
);
6748 // temporarily hide the edit control before resizing
6749 HideCellEditControl();
6750 SaveEditControlValue();
6752 // do resize the line
6753 const int lineStart
= oper
.GetLineStartPos(this, m_dragRowOrCol
);
6754 oper
.SetLineSize(this, m_dragRowOrCol
,
6755 wxMax(m_dragLastPos
- lineStart
,
6756 oper
.GetMinimalLineSize(this, m_dragRowOrCol
)));
6760 // refresh now if we're not frozen
6761 if ( !GetBatchCount() )
6763 // we need to refresh everything beyond the resized line in the header
6766 // get the position from which to refresh in the other direction
6767 wxRect
rect(CellToRect(oper
.MakeCoords(m_dragRowOrCol
, 0)));
6768 rect
.SetPosition(CalcScrolledPosition(rect
.GetPosition()));
6770 // we only need the ordinate (for rows) or abscissa (for columns) here,
6771 // and need to cover the entire window in the other direction
6772 oper
.Select(rect
) = 0;
6774 wxRect
rectHeader(rect
.GetPosition(),
6777 oper
.GetHeaderWindowSize(this),
6778 doper
.Select(size
) - doper
.Select(rect
)
6781 oper
.GetHeaderWindow(this)->Refresh(true, &rectHeader
);
6784 // also refresh the grid window: extend the rectangle
6787 oper
.SelectSize(rect
) = oper
.Select(size
);
6789 int subtractLines
= 0;
6790 const int lineStart
= oper
.PosToLine(this, posLineStart
);
6791 if ( lineStart
>= 0 )
6793 // ensure that if we have a multi-cell block we redraw all of
6794 // it by increasing the refresh area to cover it entirely if a
6795 // part of it is affected
6796 const int lineEnd
= oper
.PosToLine(this, posLineEnd
, true);
6797 for ( int line
= lineStart
; line
< lineEnd
; line
++ )
6799 int cellLines
= oper
.Select(
6800 GetCellSize(oper
.MakeCoords(m_dragRowOrCol
, line
)));
6801 if ( cellLines
< subtractLines
)
6802 subtractLines
= cellLines
;
6807 oper
.GetLineStartPos(this, m_dragRowOrCol
+ subtractLines
);
6808 startPos
= doper
.CalcScrolledPosition(this, startPos
);
6810 doper
.Select(rect
) = startPos
;
6811 doper
.SelectSize(rect
) = doper
.Select(size
) - startPos
;
6813 m_gridWin
->Refresh(false, &rect
);
6817 // show the edit control back again
6818 ShowCellEditControl();
6821 void wxGrid::DoEndDragResizeRow()
6823 DoEndDragResizeLine(wxGridRowOperations());
6826 void wxGrid::DoEndDragResizeCol(wxMouseEvent
*event
)
6828 DoEndDragResizeLine(wxGridColumnOperations());
6830 // Note: we are ending the event *after* doing
6831 // default processing in this case
6834 SendEvent( wxEVT_GRID_COL_SIZE
, -1, m_dragRowOrCol
, *event
);
6836 SendEvent( wxEVT_GRID_COL_SIZE
, -1, m_dragRowOrCol
);
6839 void wxGrid::DoStartMoveCol(int col
)
6841 m_dragRowOrCol
= col
;
6844 void wxGrid::DoEndMoveCol(int pos
)
6846 wxASSERT_MSG( m_dragRowOrCol
!= -1, "no matching DoStartMoveCol?" );
6848 if ( SendEvent(wxEVT_GRID_COL_MOVE
, -1, m_dragRowOrCol
) != -1 )
6849 SetColPos(m_dragRowOrCol
, pos
);
6850 //else: vetoed by user
6852 m_dragRowOrCol
= -1;
6855 void wxGrid::RefreshAfterColPosChange()
6857 // recalculate the column rights as the column positions have changed,
6858 // unless we calculate them dynamically because all columns widths are the
6859 // same and it's easy to do
6860 if ( !m_colWidths
.empty() )
6863 for ( int colPos
= 0; colPos
< m_numCols
; colPos
++ )
6865 int colID
= GetColAt( colPos
);
6867 colRight
+= m_colWidths
[colID
];
6868 m_colRights
[colID
] = colRight
;
6872 // and make the changes visible
6873 if ( m_useNativeHeader
)
6875 if ( m_colAt
.empty() )
6876 GetGridColHeader()->ResetColumnsOrder();
6878 GetGridColHeader()->SetColumnsOrder(m_colAt
);
6882 m_colWindow
->Refresh();
6884 m_gridWin
->Refresh();
6887 void wxGrid::SetColumnsOrder(const wxArrayInt
& order
)
6891 RefreshAfterColPosChange();
6894 void wxGrid::SetColPos(int idx
, int pos
)
6896 // we're going to need m_colAt now, initialize it if needed
6897 if ( m_colAt
.empty() )
6899 m_colAt
.reserve(m_numCols
);
6900 for ( int i
= 0; i
< m_numCols
; i
++ )
6901 m_colAt
.push_back(i
);
6904 wxHeaderCtrl::MoveColumnInOrderArray(m_colAt
, idx
, pos
);
6906 RefreshAfterColPosChange();
6909 void wxGrid::ResetColPos()
6913 RefreshAfterColPosChange();
6916 void wxGrid::EnableDragColMove( bool enable
)
6918 if ( m_canDragColMove
== enable
)
6921 if ( m_useNativeHeader
)
6923 // update all columns to make them [not] reorderable
6924 GetGridColHeader()->SetColumnCount(m_numCols
);
6927 m_canDragColMove
= enable
;
6929 // we use to call ResetColPos() from here if !enable but this doesn't seem
6930 // right as it would mean there would be no way to "freeze" the current
6931 // columns order by disabling moving them after putting them in the desired
6932 // order, whereas now you can always call ResetColPos() manually if needed
6937 // ------ interaction with data model
6939 bool wxGrid::ProcessTableMessage( wxGridTableMessage
& msg
)
6941 switch ( msg
.GetId() )
6943 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES
:
6944 return GetModelValues();
6946 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES
:
6947 return SetModelValues();
6949 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED
:
6950 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED
:
6951 case wxGRIDTABLE_NOTIFY_ROWS_DELETED
:
6952 case wxGRIDTABLE_NOTIFY_COLS_INSERTED
:
6953 case wxGRIDTABLE_NOTIFY_COLS_APPENDED
:
6954 case wxGRIDTABLE_NOTIFY_COLS_DELETED
:
6955 return Redimension( msg
);
6962 // The behaviour of this function depends on the grid table class
6963 // Clear() function. For the default wxGridStringTable class the
6964 // behaviour is to replace all cell contents with wxEmptyString but
6965 // not to change the number of rows or cols.
6967 void wxGrid::ClearGrid()
6971 if (IsCellEditControlEnabled())
6972 DisableCellEditControl();
6975 if (!GetBatchCount())
6976 m_gridWin
->Refresh();
6981 wxGrid::DoModifyLines(bool (wxGridTableBase::*funcModify
)(size_t, size_t),
6982 int pos
, int num
, bool WXUNUSED(updateLabels
) )
6984 wxCHECK_MSG( m_created
, false, "must finish creating the grid first" );
6989 if ( IsCellEditControlEnabled() )
6990 DisableCellEditControl();
6992 return (m_table
->*funcModify
)(pos
, num
);
6994 // the table will have sent the results of the insert row
6995 // operation to this view object as a grid table message
6999 wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend
)(size_t),
7000 int num
, bool WXUNUSED(updateLabels
))
7002 wxCHECK_MSG( m_created
, false, "must finish creating the grid first" );
7007 return (m_table
->*funcAppend
)(num
);
7011 // ----- event handlers
7014 // Generate a grid event based on a mouse event and return:
7015 // -1 if the event was vetoed
7016 // +1 if the event was processed (but not vetoed)
7017 // 0 if the event wasn't handled
7019 wxGrid::SendEvent(const wxEventType type
,
7021 wxMouseEvent
& mouseEv
)
7023 bool claimed
, vetoed
;
7025 if ( type
== wxEVT_GRID_ROW_SIZE
|| type
== wxEVT_GRID_COL_SIZE
)
7027 int rowOrCol
= (row
== -1 ? col
: row
);
7029 wxGridSizeEvent
gridEvt( GetId(),
7033 mouseEv
.GetX() + GetRowLabelSize(),
7034 mouseEv
.GetY() + GetColLabelSize(),
7037 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7038 vetoed
= !gridEvt
.IsAllowed();
7040 else if ( type
== wxEVT_GRID_RANGE_SELECT
)
7042 // Right now, it should _never_ end up here!
7043 wxGridRangeSelectEvent
gridEvt( GetId(),
7046 m_selectedBlockTopLeft
,
7047 m_selectedBlockBottomRight
,
7051 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7052 vetoed
= !gridEvt
.IsAllowed();
7054 else if ( type
== wxEVT_GRID_LABEL_LEFT_CLICK
||
7055 type
== wxEVT_GRID_LABEL_LEFT_DCLICK
||
7056 type
== wxEVT_GRID_LABEL_RIGHT_CLICK
||
7057 type
== wxEVT_GRID_LABEL_RIGHT_DCLICK
)
7059 wxPoint pos
= mouseEv
.GetPosition();
7061 if ( mouseEv
.GetEventObject() == GetGridRowLabelWindow() )
7062 pos
.y
+= GetColLabelSize();
7063 if ( mouseEv
.GetEventObject() == GetGridColLabelWindow() )
7064 pos
.x
+= GetRowLabelSize();
7066 wxGridEvent
gridEvt( GetId(),
7074 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7075 vetoed
= !gridEvt
.IsAllowed();
7079 wxGridEvent
gridEvt( GetId(),
7083 mouseEv
.GetX() + GetRowLabelSize(),
7084 mouseEv
.GetY() + GetColLabelSize(),
7087 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7088 vetoed
= !gridEvt
.IsAllowed();
7091 // A Veto'd event may not be `claimed' so test this first
7095 return claimed
? 1 : 0;
7098 // Generate a grid event of specified type, return value same as above
7100 int wxGrid::SendEvent(const wxEventType type
, int row
, int col
)
7102 bool claimed
, vetoed
;
7104 if ( type
== wxEVT_GRID_ROW_SIZE
|| type
== wxEVT_GRID_COL_SIZE
)
7106 int rowOrCol
= (row
== -1 ? col
: row
);
7108 wxGridSizeEvent
gridEvt( GetId(), type
, this, rowOrCol
);
7110 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7111 vetoed
= !gridEvt
.IsAllowed();
7115 wxGridEvent
gridEvt( GetId(), type
, this, row
, col
);
7117 claimed
= GetEventHandler()->ProcessEvent(gridEvt
);
7118 vetoed
= !gridEvt
.IsAllowed();
7121 // A Veto'd event may not be `claimed' so test this first
7125 return claimed
? 1 : 0;
7128 void wxGrid::OnPaint( wxPaintEvent
& WXUNUSED(event
) )
7130 // needed to prevent zillions of paint events on MSW
7134 void wxGrid::Refresh(bool eraseb
, const wxRect
* rect
)
7136 // Don't do anything if between Begin/EndBatch...
7137 // EndBatch() will do all this on the last nested one anyway.
7138 if ( m_created
&& !GetBatchCount() )
7140 // Refresh to get correct scrolled position:
7141 wxScrolledWindow::Refresh(eraseb
, rect
);
7145 int rect_x
, rect_y
, rectWidth
, rectHeight
;
7146 int width_label
, width_cell
, height_label
, height_cell
;
7149 // Copy rectangle can get scroll offsets..
7150 rect_x
= rect
->GetX();
7151 rect_y
= rect
->GetY();
7152 rectWidth
= rect
->GetWidth();
7153 rectHeight
= rect
->GetHeight();
7155 width_label
= m_rowLabelWidth
- rect_x
;
7156 if (width_label
> rectWidth
)
7157 width_label
= rectWidth
;
7159 height_label
= m_colLabelHeight
- rect_y
;
7160 if (height_label
> rectHeight
)
7161 height_label
= rectHeight
;
7163 if (rect_x
> m_rowLabelWidth
)
7165 x
= rect_x
- m_rowLabelWidth
;
7166 width_cell
= rectWidth
;
7171 width_cell
= rectWidth
- (m_rowLabelWidth
- rect_x
);
7174 if (rect_y
> m_colLabelHeight
)
7176 y
= rect_y
- m_colLabelHeight
;
7177 height_cell
= rectHeight
;
7182 height_cell
= rectHeight
- (m_colLabelHeight
- rect_y
);
7185 // Paint corner label part intersecting rect.
7186 if ( width_label
> 0 && height_label
> 0 )
7188 wxRect
anotherrect(rect_x
, rect_y
, width_label
, height_label
);
7189 m_cornerLabelWin
->Refresh(eraseb
, &anotherrect
);
7192 // Paint col labels part intersecting rect.
7193 if ( width_cell
> 0 && height_label
> 0 )
7195 wxRect
anotherrect(x
, rect_y
, width_cell
, height_label
);
7196 m_colWindow
->Refresh(eraseb
, &anotherrect
);
7199 // Paint row labels part intersecting rect.
7200 if ( width_label
> 0 && height_cell
> 0 )
7202 wxRect
anotherrect(rect_x
, y
, width_label
, height_cell
);
7203 m_rowLabelWin
->Refresh(eraseb
, &anotherrect
);
7206 // Paint cell area part intersecting rect.
7207 if ( width_cell
> 0 && height_cell
> 0 )
7209 wxRect
anotherrect(x
, y
, width_cell
, height_cell
);
7210 m_gridWin
->Refresh(eraseb
, &anotherrect
);
7215 m_cornerLabelWin
->Refresh(eraseb
, NULL
);
7216 m_colWindow
->Refresh(eraseb
, NULL
);
7217 m_rowLabelWin
->Refresh(eraseb
, NULL
);
7218 m_gridWin
->Refresh(eraseb
, NULL
);
7223 void wxGrid::OnSize(wxSizeEvent
& WXUNUSED(event
))
7225 if (m_targetWindow
!= this) // check whether initialisation has been done
7227 // reposition our children windows
7232 void wxGrid::OnKeyDown( wxKeyEvent
& event
)
7234 if ( m_inOnKeyDown
)
7236 // shouldn't be here - we are going round in circles...
7238 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
7241 m_inOnKeyDown
= true;
7243 // propagate the event up and see if it gets processed
7244 wxWindow
*parent
= GetParent();
7245 wxKeyEvent
keyEvt( event
);
7246 keyEvt
.SetEventObject( parent
);
7248 if ( !parent
->GetEventHandler()->ProcessEvent( keyEvt
) )
7250 if (GetLayoutDirection() == wxLayout_RightToLeft
)
7252 if (event
.GetKeyCode() == WXK_RIGHT
)
7253 event
.m_keyCode
= WXK_LEFT
;
7254 else if (event
.GetKeyCode() == WXK_LEFT
)
7255 event
.m_keyCode
= WXK_RIGHT
;
7258 // try local handlers
7259 switch ( event
.GetKeyCode() )
7262 if ( event
.ControlDown() )
7263 MoveCursorUpBlock( event
.ShiftDown() );
7265 MoveCursorUp( event
.ShiftDown() );
7269 if ( event
.ControlDown() )
7270 MoveCursorDownBlock( event
.ShiftDown() );
7272 MoveCursorDown( event
.ShiftDown() );
7276 if ( event
.ControlDown() )
7277 MoveCursorLeftBlock( event
.ShiftDown() );
7279 MoveCursorLeft( event
.ShiftDown() );
7283 if ( event
.ControlDown() )
7284 MoveCursorRightBlock( event
.ShiftDown() );
7286 MoveCursorRight( event
.ShiftDown() );
7290 case WXK_NUMPAD_ENTER
:
7291 if ( event
.ControlDown() )
7293 event
.Skip(); // to let the edit control have the return
7297 if ( GetGridCursorRow() < GetNumberRows()-1 )
7299 MoveCursorDown( event
.ShiftDown() );
7303 // at the bottom of a column
7304 DisableCellEditControl();
7314 if (event
.ShiftDown())
7316 if ( GetGridCursorCol() > 0 )
7318 MoveCursorLeft( false );
7323 DisableCellEditControl();
7328 if ( GetGridCursorCol() < GetNumberCols() - 1 )
7330 MoveCursorRight( false );
7335 DisableCellEditControl();
7341 if ( event
.ControlDown() )
7352 if ( event
.ControlDown() )
7354 GoToCell(m_numRows
- 1, m_numCols
- 1);
7371 // Ctrl-Space selects the current column, Shift-Space -- the
7372 // current row and Ctrl-Shift-Space -- everything
7373 switch ( m_selection
? event
.GetModifiers() : wxMOD_NONE
)
7376 m_selection
->SelectCol(m_currentCellCoords
.GetCol());
7380 m_selection
->SelectRow(m_currentCellCoords
.GetRow());
7383 case wxMOD_CONTROL
| wxMOD_SHIFT
:
7384 m_selection
->SelectBlock(0, 0,
7385 m_numRows
- 1, m_numCols
- 1);
7389 if ( !IsEditable() )
7391 MoveCursorRight(false);
7394 //else: fall through
7407 m_inOnKeyDown
= false;
7410 void wxGrid::OnKeyUp( wxKeyEvent
& event
)
7412 // try local handlers
7414 if ( event
.GetKeyCode() == WXK_SHIFT
)
7416 if ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
7417 m_selectedBlockBottomRight
!= wxGridNoCellCoords
)
7421 m_selection
->SelectBlock(
7422 m_selectedBlockTopLeft
,
7423 m_selectedBlockBottomRight
,
7428 m_selectedBlockTopLeft
= wxGridNoCellCoords
;
7429 m_selectedBlockBottomRight
= wxGridNoCellCoords
;
7430 m_selectedBlockCorner
= wxGridNoCellCoords
;
7434 void wxGrid::OnChar( wxKeyEvent
& event
)
7436 // is it possible to edit the current cell at all?
7437 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
7439 // yes, now check whether the cells editor accepts the key
7440 int row
= m_currentCellCoords
.GetRow();
7441 int col
= m_currentCellCoords
.GetCol();
7442 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
7443 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
7445 // <F2> is special and will always start editing, for
7446 // other keys - ask the editor itself
7447 if ( (event
.GetKeyCode() == WXK_F2
&& !event
.HasModifiers())
7448 || editor
->IsAcceptedKey(event
) )
7450 // ensure cell is visble
7451 MakeCellVisible(row
, col
);
7452 EnableCellEditControl();
7454 // a problem can arise if the cell is not completely
7455 // visible (even after calling MakeCellVisible the
7456 // control is not created and calling StartingKey will
7458 if ( event
.GetKeyCode() != WXK_F2
&& editor
->IsCreated() && m_cellEditCtrlEnabled
)
7459 editor
->StartingKey(event
);
7475 void wxGrid::OnEraseBackground(wxEraseEvent
&)
7479 bool wxGrid::SetCurrentCell( const wxGridCellCoords
& coords
)
7481 if ( SendEvent(wxEVT_GRID_SELECT_CELL
, coords
) == -1 )
7483 // the event has been vetoed - do nothing
7487 #if !defined(__WXMAC__)
7488 wxClientDC
dc( m_gridWin
);
7492 if ( m_currentCellCoords
!= wxGridNoCellCoords
)
7494 DisableCellEditControl();
7496 if ( IsVisible( m_currentCellCoords
, false ) )
7499 r
= BlockToDeviceRect( m_currentCellCoords
, m_currentCellCoords
);
7500 if ( !m_gridLinesEnabled
)
7508 wxGridCellCoordsArray cells
= CalcCellsExposed( r
);
7510 // Otherwise refresh redraws the highlight!
7511 m_currentCellCoords
= coords
;
7513 #if defined(__WXMAC__)
7514 m_gridWin
->Refresh(true /*, & r */);
7516 DrawGridCellArea( dc
, cells
);
7517 DrawAllGridLines( dc
, r
);
7522 m_currentCellCoords
= coords
;
7524 wxGridCellAttr
*attr
= GetCellAttr( coords
);
7525 #if !defined(__WXMAC__)
7526 DrawCellHighlight( dc
, attr
);
7534 wxGrid::UpdateBlockBeingSelected(int topRow
, int leftCol
,
7535 int bottomRow
, int rightCol
)
7539 switch ( m_selection
->GetSelectionMode() )
7542 wxFAIL_MSG( "unknown selection mode" );
7545 case wxGridSelectCells
:
7546 // arbitrary blocks selection allowed so just use the cell
7547 // coordinates as is
7550 case wxGridSelectRows
:
7551 // only full rows selection allowd, ensure that we do select
7554 rightCol
= GetNumberCols() - 1;
7557 case wxGridSelectColumns
:
7558 // same as above but for columns
7560 bottomRow
= GetNumberRows() - 1;
7563 case wxGridSelectRowsOrColumns
:
7564 // in this mode we can select only full rows or full columns so
7565 // it doesn't make sense to select blocks at all (and we can't
7566 // extend the block because there is no preferred direction, we
7567 // could only extend it to cover the entire grid but this is
7573 m_selectedBlockCorner
= wxGridCellCoords(bottomRow
, rightCol
);
7574 MakeCellVisible(m_selectedBlockCorner
);
7576 EnsureFirstLessThanSecond(topRow
, bottomRow
);
7577 EnsureFirstLessThanSecond(leftCol
, rightCol
);
7579 wxGridCellCoords updateTopLeft
= wxGridCellCoords(topRow
, leftCol
),
7580 updateBottomRight
= wxGridCellCoords(bottomRow
, rightCol
);
7582 // First the case that we selected a completely new area
7583 if ( m_selectedBlockTopLeft
== wxGridNoCellCoords
||
7584 m_selectedBlockBottomRight
== wxGridNoCellCoords
)
7587 rect
= BlockToDeviceRect( wxGridCellCoords ( topRow
, leftCol
),
7588 wxGridCellCoords ( bottomRow
, rightCol
) );
7589 m_gridWin
->Refresh( false, &rect
);
7592 // Now handle changing an existing selection area.
7593 else if ( m_selectedBlockTopLeft
!= updateTopLeft
||
7594 m_selectedBlockBottomRight
!= updateBottomRight
)
7596 // Compute two optimal update rectangles:
7597 // Either one rectangle is a real subset of the
7598 // other, or they are (almost) disjoint!
7600 bool need_refresh
[4];
7604 need_refresh
[3] = false;
7607 // Store intermediate values
7608 wxCoord oldLeft
= m_selectedBlockTopLeft
.GetCol();
7609 wxCoord oldTop
= m_selectedBlockTopLeft
.GetRow();
7610 wxCoord oldRight
= m_selectedBlockBottomRight
.GetCol();
7611 wxCoord oldBottom
= m_selectedBlockBottomRight
.GetRow();
7613 // Determine the outer/inner coordinates.
7614 EnsureFirstLessThanSecond(oldLeft
, leftCol
);
7615 EnsureFirstLessThanSecond(oldTop
, topRow
);
7616 EnsureFirstLessThanSecond(rightCol
, oldRight
);
7617 EnsureFirstLessThanSecond(bottomRow
, oldBottom
);
7619 // Now, either the stuff marked old is the outer
7620 // rectangle or we don't have a situation where one
7621 // is contained in the other.
7623 if ( oldLeft
< leftCol
)
7625 // Refresh the newly selected or deselected
7626 // area to the left of the old or new selection.
7627 need_refresh
[0] = true;
7628 rect
[0] = BlockToDeviceRect(
7629 wxGridCellCoords( oldTop
, oldLeft
),
7630 wxGridCellCoords( oldBottom
, leftCol
- 1 ) );
7633 if ( oldTop
< topRow
)
7635 // Refresh the newly selected or deselected
7636 // area above the old or new selection.
7637 need_refresh
[1] = true;
7638 rect
[1] = BlockToDeviceRect(
7639 wxGridCellCoords( oldTop
, leftCol
),
7640 wxGridCellCoords( topRow
- 1, rightCol
) );
7643 if ( oldRight
> rightCol
)
7645 // Refresh the newly selected or deselected
7646 // area to the right of the old or new selection.
7647 need_refresh
[2] = true;
7648 rect
[2] = BlockToDeviceRect(
7649 wxGridCellCoords( oldTop
, rightCol
+ 1 ),
7650 wxGridCellCoords( oldBottom
, oldRight
) );
7653 if ( oldBottom
> bottomRow
)
7655 // Refresh the newly selected or deselected
7656 // area below the old or new selection.
7657 need_refresh
[3] = true;
7658 rect
[3] = BlockToDeviceRect(
7659 wxGridCellCoords( bottomRow
+ 1, leftCol
),
7660 wxGridCellCoords( oldBottom
, rightCol
) );
7663 // various Refresh() calls
7664 for (i
= 0; i
< 4; i
++ )
7665 if ( need_refresh
[i
] && rect
[i
] != wxGridNoCellRect
)
7666 m_gridWin
->Refresh( false, &(rect
[i
]) );
7670 m_selectedBlockTopLeft
= updateTopLeft
;
7671 m_selectedBlockBottomRight
= updateBottomRight
;
7675 // ------ functions to get/send data (see also public functions)
7678 bool wxGrid::GetModelValues()
7680 // Hide the editor, so it won't hide a changed value.
7681 HideCellEditControl();
7685 // all we need to do is repaint the grid
7687 m_gridWin
->Refresh();
7694 bool wxGrid::SetModelValues()
7698 // Disable the editor, so it won't hide a changed value.
7699 // Do we also want to save the current value of the editor first?
7701 DisableCellEditControl();
7705 for ( row
= 0; row
< m_numRows
; row
++ )
7707 for ( col
= 0; col
< m_numCols
; col
++ )
7709 m_table
->SetValue( row
, col
, GetCellValue(row
, col
) );
7719 // Note - this function only draws cells that are in the list of
7720 // exposed cells (usually set from the update region by
7721 // CalcExposedCells)
7723 void wxGrid::DrawGridCellArea( wxDC
& dc
, const wxGridCellCoordsArray
& cells
)
7725 if ( !m_numRows
|| !m_numCols
)
7728 int i
, numCells
= cells
.GetCount();
7729 int row
, col
, cell_rows
, cell_cols
;
7730 wxGridCellCoordsArray redrawCells
;
7732 for ( i
= numCells
- 1; i
>= 0; i
-- )
7734 row
= cells
[i
].GetRow();
7735 col
= cells
[i
].GetCol();
7736 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
7738 // If this cell is part of a multicell block, find owner for repaint
7739 if ( cell_rows
<= 0 || cell_cols
<= 0 )
7741 wxGridCellCoords
cell( row
+ cell_rows
, col
+ cell_cols
);
7742 bool marked
= false;
7743 for ( int j
= 0; j
< numCells
; j
++ )
7745 if ( cell
== cells
[j
] )
7754 int count
= redrawCells
.GetCount();
7755 for (int j
= 0; j
< count
; j
++)
7757 if ( cell
== redrawCells
[j
] )
7765 redrawCells
.Add( cell
);
7768 // don't bother drawing this cell
7772 // If this cell is empty, find cell to left that might want to overflow
7773 if (m_table
&& m_table
->IsEmptyCell(row
, col
))
7775 for ( int l
= 0; l
< cell_rows
; l
++ )
7777 // find a cell in this row to leave already marked for repaint
7779 for (int k
= 0; k
< int(redrawCells
.GetCount()); k
++)
7780 if ((redrawCells
[k
].GetCol() < left
) &&
7781 (redrawCells
[k
].GetRow() == row
))
7783 left
= redrawCells
[k
].GetCol();
7787 left
= 0; // oh well
7789 for (int j
= col
- 1; j
>= left
; j
--)
7791 if (!m_table
->IsEmptyCell(row
+ l
, j
))
7793 if (GetCellOverflow(row
+ l
, j
))
7795 wxGridCellCoords
cell(row
+ l
, j
);
7796 bool marked
= false;
7798 for (int k
= 0; k
< numCells
; k
++)
7800 if ( cell
== cells
[k
] )
7809 int count
= redrawCells
.GetCount();
7810 for (int k
= 0; k
< count
; k
++)
7812 if ( cell
== redrawCells
[k
] )
7819 redrawCells
.Add( cell
);
7828 DrawCell( dc
, cells
[i
] );
7831 numCells
= redrawCells
.GetCount();
7833 for ( i
= numCells
- 1; i
>= 0; i
-- )
7835 DrawCell( dc
, redrawCells
[i
] );
7839 void wxGrid::DrawGridSpace( wxDC
& dc
)
7842 m_gridWin
->GetClientSize( &cw
, &ch
);
7845 CalcUnscrolledPosition( cw
, ch
, &right
, &bottom
);
7847 int rightCol
= m_numCols
> 0 ? GetColRight(GetColAt( m_numCols
- 1 )) : 0;
7848 int bottomRow
= m_numRows
> 0 ? GetRowBottom(m_numRows
- 1) : 0;
7850 if ( right
> rightCol
|| bottom
> bottomRow
)
7853 CalcUnscrolledPosition( 0, 0, &left
, &top
);
7855 dc
.SetBrush(GetDefaultCellBackgroundColour());
7856 dc
.SetPen( *wxTRANSPARENT_PEN
);
7858 if ( right
> rightCol
)
7860 dc
.DrawRectangle( rightCol
, top
, right
- rightCol
, ch
);
7863 if ( bottom
> bottomRow
)
7865 dc
.DrawRectangle( left
, bottomRow
, cw
, bottom
- bottomRow
);
7870 void wxGrid::DrawCell( wxDC
& dc
, const wxGridCellCoords
& coords
)
7872 int row
= coords
.GetRow();
7873 int col
= coords
.GetCol();
7875 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7878 // we draw the cell border ourselves
7879 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
7881 bool isCurrent
= coords
== m_currentCellCoords
;
7883 wxRect rect
= CellToRect( row
, col
);
7885 // if the editor is shown, we should use it and not the renderer
7886 // Note: However, only if it is really _shown_, i.e. not hidden!
7887 if ( isCurrent
&& IsCellEditControlShown() )
7889 // NB: this "#if..." is temporary and fixes a problem where the
7890 // edit control is erased by this code after being rendered.
7891 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
7892 // implicitly, causing this out-of order render.
7893 #if !defined(__WXMAC__)
7894 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
7895 editor
->PaintBackground(rect
, attr
);
7901 // but all the rest is drawn by the cell renderer and hence may be customized
7902 wxGridCellRenderer
*renderer
= attr
->GetRenderer(this, row
, col
);
7903 renderer
->Draw(*this, *attr
, dc
, rect
, row
, col
, IsInSelection(coords
));
7910 void wxGrid::DrawCellHighlight( wxDC
& dc
, const wxGridCellAttr
*attr
)
7912 // don't show highlight when the grid doesn't have focus
7916 int row
= m_currentCellCoords
.GetRow();
7917 int col
= m_currentCellCoords
.GetCol();
7919 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7922 wxRect rect
= CellToRect(row
, col
);
7924 // hmmm... what could we do here to show that the cell is disabled?
7925 // for now, I just draw a thinner border than for the other ones, but
7926 // it doesn't look really good
7928 int penWidth
= attr
->IsReadOnly() ? m_cellHighlightROPenWidth
: m_cellHighlightPenWidth
;
7932 // The center of the drawn line is where the position/width/height of
7933 // the rectangle is actually at (on wxMSW at least), so the
7934 // size of the rectangle is reduced to compensate for the thickness of
7935 // the line. If this is too strange on non-wxMSW platforms then
7936 // please #ifdef this appropriately.
7937 rect
.x
+= penWidth
/ 2;
7938 rect
.y
+= penWidth
/ 2;
7939 rect
.width
-= penWidth
- 1;
7940 rect
.height
-= penWidth
- 1;
7942 // Now draw the rectangle
7943 // use the cellHighlightColour if the cell is inside a selection, this
7944 // will ensure the cell is always visible.
7945 dc
.SetPen(wxPen(IsInSelection(row
,col
) ? m_selectionForeground
7946 : m_cellHighlightColour
,
7948 dc
.SetBrush(*wxTRANSPARENT_BRUSH
);
7949 dc
.DrawRectangle(rect
);
7953 wxPen
wxGrid::GetDefaultGridLinePen()
7955 return wxPen(GetGridLineColour());
7958 wxPen
wxGrid::GetRowGridLinePen(int WXUNUSED(row
))
7960 return GetDefaultGridLinePen();
7963 wxPen
wxGrid::GetColGridLinePen(int WXUNUSED(col
))
7965 return GetDefaultGridLinePen();
7968 void wxGrid::DrawCellBorder( wxDC
& dc
, const wxGridCellCoords
& coords
)
7970 int row
= coords
.GetRow();
7971 int col
= coords
.GetCol();
7972 if ( GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
7976 wxRect rect
= CellToRect( row
, col
);
7978 // right hand border
7979 dc
.SetPen( GetColGridLinePen(col
) );
7980 dc
.DrawLine( rect
.x
+ rect
.width
, rect
.y
,
7981 rect
.x
+ rect
.width
, rect
.y
+ rect
.height
+ 1 );
7984 dc
.SetPen( GetRowGridLinePen(row
) );
7985 dc
.DrawLine( rect
.x
, rect
.y
+ rect
.height
,
7986 rect
.x
+ rect
.width
, rect
.y
+ rect
.height
);
7989 void wxGrid::DrawHighlight(wxDC
& dc
, const wxGridCellCoordsArray
& cells
)
7991 // This if block was previously in wxGrid::OnPaint but that doesn't
7992 // seem to get called under wxGTK - MB
7994 if ( m_currentCellCoords
== wxGridNoCellCoords
&&
7995 m_numRows
&& m_numCols
)
7997 m_currentCellCoords
.Set(0, 0);
8000 if ( IsCellEditControlShown() )
8002 // don't show highlight when the edit control is shown
8006 // if the active cell was repainted, repaint its highlight too because it
8007 // might have been damaged by the grid lines
8008 size_t count
= cells
.GetCount();
8009 for ( size_t n
= 0; n
< count
; n
++ )
8011 wxGridCellCoords cell
= cells
[n
];
8013 // If we are using attributes, then we may have just exposed another
8014 // cell in a partially-visible merged cluster of cells. If the "anchor"
8015 // (upper left) cell of this merged cluster is the cell indicated by
8016 // m_currentCellCoords, then we need to refresh the cell highlight even
8017 // though the "anchor" itself is not part of our update segment.
8018 if ( CanHaveAttributes() )
8022 GetCellSize(cell
.GetRow(), cell
.GetCol(), &rows
, &cols
);
8025 cell
.SetRow(cell
.GetRow() + rows
);
8028 cell
.SetCol(cell
.GetCol() + cols
);
8031 if ( cell
== m_currentCellCoords
)
8033 wxGridCellAttr
* attr
= GetCellAttr(m_currentCellCoords
);
8034 DrawCellHighlight(dc
, attr
);
8042 // This is used to redraw all grid lines e.g. when the grid line colour
8045 void wxGrid::DrawAllGridLines( wxDC
& dc
, const wxRegion
& WXUNUSED(reg
) )
8047 if ( !m_gridLinesEnabled
)
8050 int top
, bottom
, left
, right
;
8053 m_gridWin
->GetClientSize(&cw
, &ch
);
8054 CalcUnscrolledPosition( 0, 0, &left
, &top
);
8055 CalcUnscrolledPosition( cw
, ch
, &right
, &bottom
);
8057 // avoid drawing grid lines past the last row and col
8058 if ( m_gridLinesClipHorz
)
8063 const int lastColRight
= GetColRight(GetColAt(m_numCols
- 1));
8064 if ( right
> lastColRight
)
8065 right
= lastColRight
;
8068 if ( m_gridLinesClipVert
)
8073 const int lastRowBottom
= GetRowBottom(m_numRows
- 1);
8074 if ( bottom
> lastRowBottom
)
8075 bottom
= lastRowBottom
;
8078 // no gridlines inside multicells, clip them out
8079 int leftCol
= GetColPos( internalXToCol(left
) );
8080 int topRow
= internalYToRow(top
);
8081 int rightCol
= GetColPos( internalXToCol(right
) );
8082 int bottomRow
= internalYToRow(bottom
);
8084 wxRegion
clippedcells(0, 0, cw
, ch
);
8086 int cell_rows
, cell_cols
;
8089 for ( int j
= topRow
; j
<= bottomRow
; j
++ )
8091 for ( int colPos
= leftCol
; colPos
<= rightCol
; colPos
++ )
8093 int i
= GetColAt( colPos
);
8095 GetCellSize( j
, i
, &cell_rows
, &cell_cols
);
8096 if ((cell_rows
> 1) || (cell_cols
> 1))
8098 rect
= CellToRect(j
,i
);
8099 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8100 clippedcells
.Subtract(rect
);
8102 else if ((cell_rows
< 0) || (cell_cols
< 0))
8104 rect
= CellToRect(j
+ cell_rows
, i
+ cell_cols
);
8105 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8106 clippedcells
.Subtract(rect
);
8111 dc
.SetDeviceClippingRegion( clippedcells
);
8114 // horizontal grid lines
8115 for ( int i
= internalYToRow(top
); i
< m_numRows
; i
++ )
8117 int bot
= GetRowBottom(i
) - 1;
8124 dc
.SetPen( GetRowGridLinePen(i
) );
8125 dc
.DrawLine( left
, bot
, right
, bot
);
8129 // vertical grid lines
8130 for ( int colPos
= leftCol
; colPos
< m_numCols
; colPos
++ )
8132 int i
= GetColAt( colPos
);
8134 int colRight
= GetColRight(i
);
8136 if (GetLayoutDirection() != wxLayout_RightToLeft
)
8140 if ( colRight
> right
)
8143 if ( colRight
>= left
)
8145 dc
.SetPen( GetColGridLinePen(i
) );
8146 dc
.DrawLine( colRight
, top
, colRight
, bottom
);
8150 dc
.DestroyClippingRegion();
8153 void wxGrid::DrawRowLabels( wxDC
& dc
, const wxArrayInt
& rows
)
8158 const size_t numLabels
= rows
.GetCount();
8159 for ( size_t i
= 0; i
< numLabels
; i
++ )
8161 DrawRowLabel( dc
, rows
[i
] );
8165 void wxGrid::DrawRowLabel( wxDC
& dc
, int row
)
8167 if ( GetRowHeight(row
) <= 0 || m_rowLabelWidth
<= 0 )
8172 int rowTop
= GetRowTop(row
),
8173 rowBottom
= GetRowBottom(row
) - 1;
8175 dc
.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8176 dc
.DrawLine( m_rowLabelWidth
- 1, rowTop
, m_rowLabelWidth
- 1, rowBottom
);
8177 dc
.DrawLine( 0, rowTop
, 0, rowBottom
);
8178 dc
.DrawLine( 0, rowBottom
, m_rowLabelWidth
, rowBottom
);
8180 dc
.SetPen( *wxWHITE_PEN
);
8181 dc
.DrawLine( 1, rowTop
, 1, rowBottom
);
8182 dc
.DrawLine( 1, rowTop
, m_rowLabelWidth
- 1, rowTop
);
8184 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
8185 dc
.SetTextForeground( GetLabelTextColour() );
8186 dc
.SetFont( GetLabelFont() );
8189 GetRowLabelAlignment( &hAlign
, &vAlign
);
8192 rect
.SetY( GetRowTop(row
) + 2 );
8193 rect
.SetWidth( m_rowLabelWidth
- 4 );
8194 rect
.SetHeight( GetRowHeight(row
) - 4 );
8195 DrawTextRectangle( dc
, GetRowLabelValue( row
), rect
, hAlign
, vAlign
);
8198 void wxGrid::UseNativeColHeader(bool native
)
8200 if ( native
== m_useNativeHeader
)
8204 m_useNativeHeader
= native
;
8206 CreateColumnWindow();
8208 if ( m_useNativeHeader
)
8209 GetGridColHeader()->SetColumnCount(m_numCols
);
8213 void wxGrid::SetUseNativeColLabels( bool native
)
8215 wxASSERT_MSG( !m_useNativeHeader
,
8216 "doesn't make sense when using native header" );
8218 m_nativeColumnLabels
= native
;
8221 int height
= wxRendererNative::Get().GetHeaderButtonHeight( this );
8222 SetColLabelSize( height
);
8225 GetColLabelWindow()->Refresh();
8226 m_cornerLabelWin
->Refresh();
8229 void wxGrid::DrawColLabels( wxDC
& dc
,const wxArrayInt
& cols
)
8234 const size_t numLabels
= cols
.GetCount();
8235 for ( size_t i
= 0; i
< numLabels
; i
++ )
8237 DrawColLabel( dc
, cols
[i
] );
8241 void wxGrid::DrawCornerLabel(wxDC
& dc
)
8243 if ( m_nativeColumnLabels
)
8245 wxRect
rect(wxSize(m_rowLabelWidth
, m_colLabelHeight
));
8248 wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin
, dc
, rect
, 0);
8252 dc
.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8253 dc
.DrawLine( m_rowLabelWidth
- 1, m_colLabelHeight
- 1,
8254 m_rowLabelWidth
- 1, 0 );
8255 dc
.DrawLine( m_rowLabelWidth
- 1, m_colLabelHeight
- 1,
8256 0, m_colLabelHeight
- 1 );
8257 dc
.DrawLine( 0, 0, m_rowLabelWidth
, 0 );
8258 dc
.DrawLine( 0, 0, 0, m_colLabelHeight
);
8260 dc
.SetPen( *wxWHITE_PEN
);
8261 dc
.DrawLine( 1, 1, m_rowLabelWidth
- 1, 1 );
8262 dc
.DrawLine( 1, 1, 1, m_colLabelHeight
- 1 );
8266 void wxGrid::DrawColLabel(wxDC
& dc
, int col
)
8268 if ( GetColWidth(col
) <= 0 || m_colLabelHeight
<= 0 )
8271 int colLeft
= GetColLeft(col
);
8273 wxRect
rect(colLeft
, 0, GetColWidth(col
), m_colLabelHeight
);
8275 if ( m_nativeColumnLabels
)
8277 wxRendererNative::Get().DrawHeaderButton
8279 GetColLabelWindow(),
8284 ? IsSortOrderAscending()
8285 ? wxHDR_SORT_ICON_UP
8286 : wxHDR_SORT_ICON_DOWN
8287 : wxHDR_SORT_ICON_NONE
8292 int colRight
= GetColRight(col
) - 1;
8294 dc
.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW
)));
8295 dc
.DrawLine( colRight
, 0,
8296 colRight
, m_colLabelHeight
- 1 );
8297 dc
.DrawLine( colLeft
, 0,
8299 dc
.DrawLine( colLeft
, m_colLabelHeight
- 1,
8300 colRight
+ 1, m_colLabelHeight
- 1 );
8302 dc
.SetPen( *wxWHITE_PEN
);
8303 dc
.DrawLine( colLeft
, 1, colLeft
, m_colLabelHeight
- 1 );
8304 dc
.DrawLine( colLeft
, 1, colRight
, 1 );
8307 dc
.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT
);
8308 dc
.SetTextForeground( GetLabelTextColour() );
8309 dc
.SetFont( GetLabelFont() );
8312 GetColLabelAlignment( &hAlign
, &vAlign
);
8313 const int orient
= GetColLabelTextOrientation();
8316 DrawTextRectangle(dc
, GetColLabelValue(col
), rect
, hAlign
, vAlign
, orient
);
8319 // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which
8320 // we just have to add textOrientation support
8321 void wxGrid::DrawTextRectangle( wxDC
& dc
,
8322 const wxString
& value
,
8326 int textOrientation
)
8328 wxArrayString lines
;
8330 StringToLines( value
, lines
);
8332 DrawTextRectangle(dc
, lines
, rect
, horizAlign
, vertAlign
, textOrientation
);
8335 void wxGrid::DrawTextRectangle(wxDC
& dc
,
8336 const wxArrayString
& lines
,
8340 int textOrientation
)
8342 if ( lines
.empty() )
8345 wxDCClipper
clip(dc
, rect
);
8350 if ( textOrientation
== wxHORIZONTAL
)
8351 GetTextBoxSize( dc
, lines
, &textWidth
, &textHeight
);
8353 GetTextBoxSize( dc
, lines
, &textHeight
, &textWidth
);
8357 switch ( vertAlign
)
8359 case wxALIGN_BOTTOM
:
8360 if ( textOrientation
== wxHORIZONTAL
)
8361 y
= rect
.y
+ (rect
.height
- textHeight
- 1);
8363 x
= rect
.x
+ rect
.width
- textWidth
;
8366 case wxALIGN_CENTRE
:
8367 if ( textOrientation
== wxHORIZONTAL
)
8368 y
= rect
.y
+ ((rect
.height
- textHeight
) / 2);
8370 x
= rect
.x
+ ((rect
.width
- textWidth
) / 2);
8375 if ( textOrientation
== wxHORIZONTAL
)
8382 // Align each line of a multi-line label
8383 size_t nLines
= lines
.GetCount();
8384 for ( size_t l
= 0; l
< nLines
; l
++ )
8386 const wxString
& line
= lines
[l
];
8390 *(textOrientation
== wxHORIZONTAL
? &y
: &x
) += dc
.GetCharHeight();
8394 wxCoord lineWidth
= 0,
8396 dc
.GetTextExtent(line
, &lineWidth
, &lineHeight
);
8398 switch ( horizAlign
)
8401 if ( textOrientation
== wxHORIZONTAL
)
8402 x
= rect
.x
+ (rect
.width
- lineWidth
- 1);
8404 y
= rect
.y
+ lineWidth
+ 1;
8407 case wxALIGN_CENTRE
:
8408 if ( textOrientation
== wxHORIZONTAL
)
8409 x
= rect
.x
+ ((rect
.width
- lineWidth
) / 2);
8411 y
= rect
.y
+ rect
.height
- ((rect
.height
- lineWidth
) / 2);
8416 if ( textOrientation
== wxHORIZONTAL
)
8419 y
= rect
.y
+ rect
.height
- 1;
8423 if ( textOrientation
== wxHORIZONTAL
)
8425 dc
.DrawText( line
, x
, y
);
8430 dc
.DrawRotatedText( line
, x
, y
, 90.0 );
8436 // Split multi-line text up into an array of strings.
8437 // Any existing contents of the string array are preserved.
8439 // TODO: refactor wxTextFile::Read() and reuse the same code from here
8440 void wxGrid::StringToLines( const wxString
& value
, wxArrayString
& lines
) const
8444 wxString eol
= wxTextFile::GetEOL( wxTextFileType_Unix
);
8445 wxString tVal
= wxTextFile::Translate( value
, wxTextFileType_Unix
);
8447 while ( startPos
< (int)tVal
.length() )
8449 pos
= tVal
.Mid(startPos
).Find( eol
);
8454 else if ( pos
== 0 )
8456 lines
.Add( wxEmptyString
);
8460 lines
.Add( tVal
.Mid(startPos
, pos
) );
8463 startPos
+= pos
+ 1;
8466 if ( startPos
< (int)tVal
.length() )
8468 lines
.Add( tVal
.Mid( startPos
) );
8472 void wxGrid::GetTextBoxSize( const wxDC
& dc
,
8473 const wxArrayString
& lines
,
8474 long *width
, long *height
) const
8478 wxCoord lineW
= 0, lineH
= 0;
8481 for ( i
= 0; i
< lines
.GetCount(); i
++ )
8483 dc
.GetTextExtent( lines
[i
], &lineW
, &lineH
);
8484 w
= wxMax( w
, lineW
);
8493 // ------ Batch processing.
8495 void wxGrid::EndBatch()
8497 if ( m_batchCount
> 0 )
8500 if ( !m_batchCount
)
8503 m_rowLabelWin
->Refresh();
8504 m_colWindow
->Refresh();
8505 m_cornerLabelWin
->Refresh();
8506 m_gridWin
->Refresh();
8511 // Use this, rather than wxWindow::Refresh(), to force an immediate
8512 // repainting of the grid. Has no effect if you are already inside a
8513 // BeginBatch / EndBatch block.
8515 void wxGrid::ForceRefresh()
8521 bool wxGrid::Enable(bool enable
)
8523 if ( !wxScrolledWindow::Enable(enable
) )
8526 // redraw in the new state
8527 m_gridWin
->Refresh();
8533 // ------ Edit control functions
8536 void wxGrid::EnableEditing( bool edit
)
8538 if ( edit
!= m_editable
)
8541 EnableCellEditControl(edit
);
8546 void wxGrid::EnableCellEditControl( bool enable
)
8551 if ( enable
!= m_cellEditCtrlEnabled
)
8555 if ( SendEvent(wxEVT_GRID_EDITOR_SHOWN
) == -1 )
8558 // this should be checked by the caller!
8559 wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") );
8561 // do it before ShowCellEditControl()
8562 m_cellEditCtrlEnabled
= enable
;
8564 ShowCellEditControl();
8568 //FIXME:add veto support
8569 SendEvent(wxEVT_GRID_EDITOR_HIDDEN
);
8571 HideCellEditControl();
8572 SaveEditControlValue();
8574 // do it after HideCellEditControl()
8575 m_cellEditCtrlEnabled
= enable
;
8580 bool wxGrid::IsCurrentCellReadOnly() const
8583 wxGridCellAttr
* attr
= ((wxGrid
*)this)->GetCellAttr(m_currentCellCoords
);
8584 bool readonly
= attr
->IsReadOnly();
8590 bool wxGrid::CanEnableCellControl() const
8592 return m_editable
&& (m_currentCellCoords
!= wxGridNoCellCoords
) &&
8593 !IsCurrentCellReadOnly();
8596 bool wxGrid::IsCellEditControlEnabled() const
8598 // the cell edit control might be disable for all cells or just for the
8599 // current one if it's read only
8600 return m_cellEditCtrlEnabled
? !IsCurrentCellReadOnly() : false;
8603 bool wxGrid::IsCellEditControlShown() const
8605 bool isShown
= false;
8607 if ( m_cellEditCtrlEnabled
)
8609 int row
= m_currentCellCoords
.GetRow();
8610 int col
= m_currentCellCoords
.GetCol();
8611 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8612 wxGridCellEditor
* editor
= attr
->GetEditor((wxGrid
*) this, row
, col
);
8617 if ( editor
->IsCreated() )
8619 isShown
= editor
->GetControl()->IsShown();
8629 void wxGrid::ShowCellEditControl()
8631 if ( IsCellEditControlEnabled() )
8633 if ( !IsVisible( m_currentCellCoords
, false ) )
8635 m_cellEditCtrlEnabled
= false;
8640 wxRect rect
= CellToRect( m_currentCellCoords
);
8641 int row
= m_currentCellCoords
.GetRow();
8642 int col
= m_currentCellCoords
.GetCol();
8644 // if this is part of a multicell, find owner (topleft)
8645 int cell_rows
, cell_cols
;
8646 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
8647 if ( cell_rows
<= 0 || cell_cols
<= 0 )
8651 m_currentCellCoords
.SetRow( row
);
8652 m_currentCellCoords
.SetCol( col
);
8655 // erase the highlight and the cell contents because the editor
8656 // might not cover the entire cell
8657 wxClientDC
dc( m_gridWin
);
8659 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8660 dc
.SetBrush(wxBrush(attr
->GetBackgroundColour()));
8661 dc
.SetPen(*wxTRANSPARENT_PEN
);
8662 dc
.DrawRectangle(rect
);
8664 // convert to scrolled coords
8665 CalcScrolledPosition( rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8671 // cell is shifted by one pixel
8672 // However, don't allow x or y to become negative
8673 // since the SetSize() method interprets that as
8680 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
8681 if ( !editor
->IsCreated() )
8683 editor
->Create(m_gridWin
, wxID_ANY
,
8684 new wxGridCellEditorEvtHandler(this, editor
));
8686 wxGridEditorCreatedEvent
evt(GetId(),
8687 wxEVT_GRID_EDITOR_CREATED
,
8691 editor
->GetControl());
8692 GetEventHandler()->ProcessEvent(evt
);
8695 // resize editor to overflow into righthand cells if allowed
8696 int maxWidth
= rect
.width
;
8697 wxString value
= GetCellValue(row
, col
);
8698 if ( (value
!= wxEmptyString
) && (attr
->GetOverflow()) )
8701 GetTextExtent(value
, &maxWidth
, &y
, NULL
, NULL
, &attr
->GetFont());
8702 if (maxWidth
< rect
.width
)
8703 maxWidth
= rect
.width
;
8706 int client_right
= m_gridWin
->GetClientSize().GetWidth();
8707 if (rect
.x
+ maxWidth
> client_right
)
8708 maxWidth
= client_right
- rect
.x
;
8710 if ((maxWidth
> rect
.width
) && (col
< m_numCols
) && m_table
)
8712 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
8713 // may have changed earlier
8714 for (int i
= col
+ cell_cols
; i
< m_numCols
; i
++)
8717 GetCellSize( row
, i
, &c_rows
, &c_cols
);
8719 // looks weird going over a multicell
8720 if (m_table
->IsEmptyCell( row
, i
) &&
8721 (rect
.width
< maxWidth
) && (c_rows
== 1))
8723 rect
.width
+= GetColWidth( i
);
8729 if (rect
.GetRight() > client_right
)
8730 rect
.SetRight( client_right
- 1 );
8733 editor
->SetCellAttr( attr
);
8734 editor
->SetSize( rect
);
8736 editor
->GetControl()->Move(
8737 editor
->GetControl()->GetPosition().x
+ nXMove
,
8738 editor
->GetControl()->GetPosition().y
);
8739 editor
->Show( true, attr
);
8741 // recalc dimensions in case we need to
8742 // expand the scrolled window to account for editor
8745 editor
->BeginEdit(row
, col
, this);
8746 editor
->SetCellAttr(NULL
);
8754 void wxGrid::HideCellEditControl()
8756 if ( IsCellEditControlEnabled() )
8758 int row
= m_currentCellCoords
.GetRow();
8759 int col
= m_currentCellCoords
.GetCol();
8761 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
8762 wxGridCellEditor
*editor
= attr
->GetEditor(this, row
, col
);
8763 const bool editorHadFocus
= editor
->GetControl()->HasFocus();
8764 editor
->Show( false );
8768 // return the focus to the grid itself if the editor had it
8770 // note that we must not do this unconditionally to avoid stealing
8771 // focus from the window which just received it if we are hiding the
8772 // editor precisely because we lost focus
8773 if ( editorHadFocus
)
8774 m_gridWin
->SetFocus();
8776 // refresh whole row to the right
8777 wxRect
rect( CellToRect(row
, col
) );
8778 CalcScrolledPosition(rect
.x
, rect
.y
, &rect
.x
, &rect
.y
);
8779 rect
.width
= m_gridWin
->GetClientSize().GetWidth() - rect
.x
;
8782 // ensure that the pixels under the focus ring get refreshed as well
8783 rect
.Inflate(10, 10);
8786 m_gridWin
->Refresh( false, &rect
);
8790 void wxGrid::SaveEditControlValue()
8792 if ( IsCellEditControlEnabled() )
8794 int row
= m_currentCellCoords
.GetRow();
8795 int col
= m_currentCellCoords
.GetCol();
8797 wxString oldval
= GetCellValue(row
, col
);
8799 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
8800 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
8801 bool changed
= editor
->EndEdit(row
, col
, this);
8808 if ( SendEvent(wxEVT_GRID_CELL_CHANGE
) == -1 )
8810 // Event has been vetoed, set the data back.
8811 SetCellValue(row
, col
, oldval
);
8818 // ------ Grid location functions
8819 // Note that all of these functions work with the logical coordinates of
8820 // grid cells and labels so you will need to convert from device
8821 // coordinates for mouse events etc.
8824 wxGridCellCoords
wxGrid::XYToCell(int x
, int y
) const
8826 int row
= YToRow(y
);
8827 int col
= XToCol(x
);
8829 return row
== -1 || col
== -1 ? wxGridNoCellCoords
8830 : wxGridCellCoords(row
, col
);
8833 // compute row or column from some (unscrolled) coordinate value, using either
8834 // m_defaultRowHeight/m_defaultColWidth or binary search on array of
8835 // m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used
8837 int wxGrid::PosToLinePos(int coord
,
8839 const wxGridOperations
& oper
) const
8841 const int numLines
= oper
.GetNumberOfLines(this);
8844 return clipToMinMax
&& numLines
> 0 ? 0 : wxNOT_FOUND
;
8846 const int defaultLineSize
= oper
.GetDefaultLineSize(this);
8847 wxCHECK_MSG( defaultLineSize
, -1, "can't have 0 default line size" );
8849 int maxPos
= coord
/ defaultLineSize
,
8852 // check for the simplest case: if we have no explicit line sizes
8853 // configured, then we already know the line this position falls in
8854 const wxArrayInt
& lineEnds
= oper
.GetLineEnds(this);
8855 if ( lineEnds
.empty() )
8857 if ( maxPos
< numLines
)
8860 return clipToMinMax
? numLines
- 1 : -1;
8864 // adjust maxPos before starting the binary search
8865 if ( maxPos
>= numLines
)
8867 maxPos
= numLines
- 1;
8871 if ( coord
>= lineEnds
[oper
.GetLineAt(this, maxPos
)])
8874 const int minDist
= oper
.GetMinimalAcceptableLineSize(this);
8876 maxPos
= coord
/ minDist
;
8878 maxPos
= numLines
- 1;
8881 if ( maxPos
>= numLines
)
8882 maxPos
= numLines
- 1;
8885 // check if the position is beyond the last column
8886 const int lineAtMaxPos
= oper
.GetLineAt(this, maxPos
);
8887 if ( coord
>= lineEnds
[lineAtMaxPos
] )
8888 return clipToMinMax
? maxPos
: -1;
8890 // or before the first one
8891 const int lineAt0
= oper
.GetLineAt(this, 0);
8892 if ( coord
< lineEnds
[lineAt0
] )
8896 // finally do perform the binary search
8897 while ( minPos
< maxPos
)
8899 wxCHECK_MSG( lineEnds
[oper
.GetLineAt(this, minPos
)] <= coord
&&
8900 coord
< lineEnds
[oper
.GetLineAt(this, maxPos
)],
8902 "wxGrid: internal error in PosToLinePos()" );
8904 if ( coord
>= lineEnds
[oper
.GetLineAt(this, maxPos
- 1)] )
8909 const int median
= minPos
+ (maxPos
- minPos
+ 1) / 2;
8910 if ( coord
< lineEnds
[oper
.GetLineAt(this, median
)] )
8920 wxGrid::PosToLine(int coord
,
8922 const wxGridOperations
& oper
) const
8924 int pos
= PosToLinePos(coord
, clipToMinMax
, oper
);
8926 return pos
== wxNOT_FOUND
? wxNOT_FOUND
: oper
.GetLineAt(this, pos
);
8929 int wxGrid::YToRow(int y
, bool clipToMinMax
) const
8931 return PosToLine(y
, clipToMinMax
, wxGridRowOperations());
8934 int wxGrid::XToCol(int x
, bool clipToMinMax
) const
8936 return PosToLine(x
, clipToMinMax
, wxGridColumnOperations());
8939 int wxGrid::XToPos(int x
) const
8941 return PosToLinePos(x
, true /* clip */, wxGridColumnOperations());
8944 // return the row number that that the y coord is near the edge of, or -1 if
8945 // not near an edge.
8947 // coords can only possibly be near an edge if
8948 // (a) the row/column is large enough to still allow for an "inner" area
8949 // that is _not_ near the edge (i.e., if the height/width is smaller
8950 // than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be
8953 // (b) resizing rows/columns (the thing for which edge detection is
8954 // relevant at all) is enabled.
8956 int wxGrid::PosToEdgeOfLine(int pos
, const wxGridOperations
& oper
) const
8958 if ( !oper
.CanResizeLines(this) )
8961 const int line
= oper
.PosToLine(this, pos
, true);
8963 if ( oper
.GetLineSize(this, line
) > WXGRID_LABEL_EDGE_ZONE
)
8965 // We know that we are in this line, test whether we are close enough
8966 // to start or end border, respectively.
8967 if ( abs(oper
.GetLineEndPos(this, line
) - pos
) < WXGRID_LABEL_EDGE_ZONE
)
8969 else if ( line
> 0 &&
8970 pos
- oper
.GetLineStartPos(this,
8971 line
) < WXGRID_LABEL_EDGE_ZONE
)
8978 int wxGrid::YToEdgeOfRow(int y
) const
8980 return PosToEdgeOfLine(y
, wxGridRowOperations());
8983 int wxGrid::XToEdgeOfCol(int x
) const
8985 return PosToEdgeOfLine(x
, wxGridColumnOperations());
8988 wxRect
wxGrid::CellToRect( int row
, int col
) const
8990 wxRect
rect( -1, -1, -1, -1 );
8992 if ( row
>= 0 && row
< m_numRows
&&
8993 col
>= 0 && col
< m_numCols
)
8995 int i
, cell_rows
, cell_cols
;
8996 rect
.width
= rect
.height
= 0;
8997 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
8998 // if negative then find multicell owner
9003 GetCellSize( row
, col
, &cell_rows
, &cell_cols
);
9005 rect
.x
= GetColLeft(col
);
9006 rect
.y
= GetRowTop(row
);
9007 for (i
=col
; i
< col
+ cell_cols
; i
++)
9008 rect
.width
+= GetColWidth(i
);
9009 for (i
=row
; i
< row
+ cell_rows
; i
++)
9010 rect
.height
+= GetRowHeight(i
);
9013 // if grid lines are enabled, then the area of the cell is a bit smaller
9014 if (m_gridLinesEnabled
)
9023 bool wxGrid::IsVisible( int row
, int col
, bool wholeCellVisible
) const
9025 // get the cell rectangle in logical coords
9027 wxRect
r( CellToRect( row
, col
) );
9029 // convert to device coords
9031 int left
, top
, right
, bottom
;
9032 CalcScrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
9033 CalcScrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
9035 // check against the client area of the grid window
9037 m_gridWin
->GetClientSize( &cw
, &ch
);
9039 if ( wholeCellVisible
)
9041 // is the cell wholly visible ?
9042 return ( left
>= 0 && right
<= cw
&&
9043 top
>= 0 && bottom
<= ch
);
9047 // is the cell partly visible ?
9049 return ( ((left
>= 0 && left
< cw
) || (right
> 0 && right
<= cw
)) &&
9050 ((top
>= 0 && top
< ch
) || (bottom
> 0 && bottom
<= ch
)) );
9054 // make the specified cell location visible by doing a minimal amount
9057 void wxGrid::MakeCellVisible( int row
, int col
)
9060 int xpos
= -1, ypos
= -1;
9062 if ( row
>= 0 && row
< m_numRows
&&
9063 col
>= 0 && col
< m_numCols
)
9065 // get the cell rectangle in logical coords
9066 wxRect
r( CellToRect( row
, col
) );
9068 // convert to device coords
9069 int left
, top
, right
, bottom
;
9070 CalcScrolledPosition( r
.GetLeft(), r
.GetTop(), &left
, &top
);
9071 CalcScrolledPosition( r
.GetRight(), r
.GetBottom(), &right
, &bottom
);
9074 m_gridWin
->GetClientSize( &cw
, &ch
);
9080 else if ( bottom
> ch
)
9082 int h
= r
.GetHeight();
9084 for ( i
= row
- 1; i
>= 0; i
-- )
9086 int rowHeight
= GetRowHeight(i
);
9087 if ( h
+ rowHeight
> ch
)
9094 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
9095 // have rounding errors (this is important, because if we do,
9096 // we might not scroll at all and some cells won't be redrawn)
9098 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
9099 // so just add a full scroll unit...
9100 ypos
+= m_scrollLineY
;
9103 // special handling for wide cells - show always left part of the cell!
9104 // Otherwise, e.g. when stepping from row to row, it would jump between
9105 // left and right part of the cell on every step!
9107 if ( left
< 0 || (right
- left
) >= cw
)
9111 else if ( right
> cw
)
9113 // position the view so that the cell is on the right
9115 CalcUnscrolledPosition(0, 0, &x0
, &y0
);
9116 xpos
= x0
+ (right
- cw
);
9118 // see comment for ypos above
9119 xpos
+= m_scrollLineX
;
9122 if ( xpos
!= -1 || ypos
!= -1 )
9125 xpos
/= m_scrollLineX
;
9127 ypos
/= m_scrollLineY
;
9128 Scroll( xpos
, ypos
);
9135 // ------ Grid cursor movement functions
9139 wxGrid::DoMoveCursor(bool expandSelection
,
9140 const wxGridDirectionOperations
& diroper
)
9142 if ( m_currentCellCoords
== wxGridNoCellCoords
)
9145 if ( expandSelection
)
9147 wxGridCellCoords coords
= m_selectedBlockCorner
;
9148 if ( coords
== wxGridNoCellCoords
)
9149 coords
= m_currentCellCoords
;
9151 if ( diroper
.IsAtBoundary(coords
) )
9154 diroper
.Advance(coords
);
9156 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
9158 else // don't expand selection
9162 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9165 wxGridCellCoords coords
= m_currentCellCoords
;
9166 diroper
.Advance(coords
);
9174 bool wxGrid::MoveCursorUp(bool expandSelection
)
9176 return DoMoveCursor(expandSelection
,
9177 wxGridBackwardOperations(this, wxGridRowOperations()));
9180 bool wxGrid::MoveCursorDown(bool expandSelection
)
9182 return DoMoveCursor(expandSelection
,
9183 wxGridForwardOperations(this, wxGridRowOperations()));
9186 bool wxGrid::MoveCursorLeft(bool expandSelection
)
9188 return DoMoveCursor(expandSelection
,
9189 wxGridBackwardOperations(this, wxGridColumnOperations()));
9192 bool wxGrid::MoveCursorRight(bool expandSelection
)
9194 return DoMoveCursor(expandSelection
,
9195 wxGridForwardOperations(this, wxGridColumnOperations()));
9198 bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations
& diroper
)
9200 if ( m_currentCellCoords
== wxGridNoCellCoords
)
9203 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9206 const int oldRow
= m_currentCellCoords
.GetRow();
9207 int newRow
= diroper
.MoveByPixelDistance(oldRow
, m_gridWin
->GetClientSize().y
);
9208 if ( newRow
== oldRow
)
9210 wxGridCellCoords
coords(m_currentCellCoords
);
9211 diroper
.Advance(coords
);
9212 newRow
= coords
.GetRow();
9215 GoToCell(newRow
, m_currentCellCoords
.GetCol());
9220 bool wxGrid::MovePageUp()
9222 return DoMoveCursorByPage(
9223 wxGridBackwardOperations(this, wxGridRowOperations()));
9226 bool wxGrid::MovePageDown()
9228 return DoMoveCursorByPage(
9229 wxGridForwardOperations(this, wxGridRowOperations()));
9232 // helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
9233 // until we find a non-empty cell or reach the grid end
9235 wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords
& coords
,
9236 const wxGridDirectionOperations
& diroper
)
9238 while ( !diroper
.IsAtBoundary(coords
) )
9240 diroper
.Advance(coords
);
9241 if ( !m_table
->IsEmpty(coords
) )
9247 wxGrid::DoMoveCursorByBlock(bool expandSelection
,
9248 const wxGridDirectionOperations
& diroper
)
9250 if ( !m_table
|| m_currentCellCoords
== wxGridNoCellCoords
)
9253 if ( diroper
.IsAtBoundary(m_currentCellCoords
) )
9256 wxGridCellCoords
coords(m_currentCellCoords
);
9257 if ( m_table
->IsEmpty(coords
) )
9259 // we are in an empty cell: find the next block of non-empty cells
9260 AdvanceToNextNonEmpty(coords
, diroper
);
9262 else // current cell is not empty
9264 diroper
.Advance(coords
);
9265 if ( m_table
->IsEmpty(coords
) )
9267 // we started at the end of a block, find the next one
9268 AdvanceToNextNonEmpty(coords
, diroper
);
9270 else // we're in a middle of a block
9272 // go to the end of it, i.e. find the last cell before the next
9274 while ( !diroper
.IsAtBoundary(coords
) )
9276 wxGridCellCoords
coordsNext(coords
);
9277 diroper
.Advance(coordsNext
);
9278 if ( m_table
->IsEmpty(coordsNext
) )
9281 coords
= coordsNext
;
9286 if ( expandSelection
)
9288 UpdateBlockBeingSelected(m_currentCellCoords
, coords
);
9299 bool wxGrid::MoveCursorUpBlock(bool expandSelection
)
9301 return DoMoveCursorByBlock(
9303 wxGridBackwardOperations(this, wxGridRowOperations())
9307 bool wxGrid::MoveCursorDownBlock( bool expandSelection
)
9309 return DoMoveCursorByBlock(
9311 wxGridForwardOperations(this, wxGridRowOperations())
9315 bool wxGrid::MoveCursorLeftBlock( bool expandSelection
)
9317 return DoMoveCursorByBlock(
9319 wxGridBackwardOperations(this, wxGridColumnOperations())
9323 bool wxGrid::MoveCursorRightBlock( bool expandSelection
)
9325 return DoMoveCursorByBlock(
9327 wxGridForwardOperations(this, wxGridColumnOperations())
9332 // ------ Label values and formatting
9335 void wxGrid::GetRowLabelAlignment( int *horiz
, int *vert
) const
9338 *horiz
= m_rowLabelHorizAlign
;
9340 *vert
= m_rowLabelVertAlign
;
9343 void wxGrid::GetColLabelAlignment( int *horiz
, int *vert
) const
9346 *horiz
= m_colLabelHorizAlign
;
9348 *vert
= m_colLabelVertAlign
;
9351 int wxGrid::GetColLabelTextOrientation() const
9353 return m_colLabelTextOrientation
;
9356 wxString
wxGrid::GetRowLabelValue( int row
) const
9360 return m_table
->GetRowLabelValue( row
);
9370 wxString
wxGrid::GetColLabelValue( int col
) const
9374 return m_table
->GetColLabelValue( col
);
9384 void wxGrid::SetRowLabelSize( int width
)
9386 wxASSERT( width
>= 0 || width
== wxGRID_AUTOSIZE
);
9388 if ( width
== wxGRID_AUTOSIZE
)
9390 width
= CalcColOrRowLabelAreaMinSize(wxGRID_ROW
);
9393 if ( width
!= m_rowLabelWidth
)
9397 m_rowLabelWin
->Show( false );
9398 m_cornerLabelWin
->Show( false );
9400 else if ( m_rowLabelWidth
== 0 )
9402 m_rowLabelWin
->Show( true );
9403 if ( m_colLabelHeight
> 0 )
9404 m_cornerLabelWin
->Show( true );
9407 m_rowLabelWidth
= width
;
9409 wxScrolledWindow::Refresh( true );
9413 void wxGrid::SetColLabelSize( int height
)
9415 wxASSERT( height
>=0 || height
== wxGRID_AUTOSIZE
);
9417 if ( height
== wxGRID_AUTOSIZE
)
9419 height
= CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN
);
9422 if ( height
!= m_colLabelHeight
)
9426 m_colWindow
->Show( false );
9427 m_cornerLabelWin
->Show( false );
9429 else if ( m_colLabelHeight
== 0 )
9431 m_colWindow
->Show( true );
9432 if ( m_rowLabelWidth
> 0 )
9433 m_cornerLabelWin
->Show( true );
9436 m_colLabelHeight
= height
;
9438 wxScrolledWindow::Refresh( true );
9442 void wxGrid::SetLabelBackgroundColour( const wxColour
& colour
)
9444 if ( m_labelBackgroundColour
!= colour
)
9446 m_labelBackgroundColour
= colour
;
9447 m_rowLabelWin
->SetBackgroundColour( colour
);
9448 m_colWindow
->SetBackgroundColour( colour
);
9449 m_cornerLabelWin
->SetBackgroundColour( colour
);
9451 if ( !GetBatchCount() )
9453 m_rowLabelWin
->Refresh();
9454 m_colWindow
->Refresh();
9455 m_cornerLabelWin
->Refresh();
9460 void wxGrid::SetLabelTextColour( const wxColour
& colour
)
9462 if ( m_labelTextColour
!= colour
)
9464 m_labelTextColour
= colour
;
9465 if ( !GetBatchCount() )
9467 m_rowLabelWin
->Refresh();
9468 m_colWindow
->Refresh();
9473 void wxGrid::SetLabelFont( const wxFont
& font
)
9476 if ( !GetBatchCount() )
9478 m_rowLabelWin
->Refresh();
9479 m_colWindow
->Refresh();
9483 void wxGrid::SetRowLabelAlignment( int horiz
, int vert
)
9485 // allow old (incorrect) defs to be used
9488 case wxLEFT
: horiz
= wxALIGN_LEFT
; break;
9489 case wxRIGHT
: horiz
= wxALIGN_RIGHT
; break;
9490 case wxCENTRE
: horiz
= wxALIGN_CENTRE
; break;
9495 case wxTOP
: vert
= wxALIGN_TOP
; break;
9496 case wxBOTTOM
: vert
= wxALIGN_BOTTOM
; break;
9497 case wxCENTRE
: vert
= wxALIGN_CENTRE
; break;
9500 if ( horiz
== wxALIGN_LEFT
|| horiz
== wxALIGN_CENTRE
|| horiz
== wxALIGN_RIGHT
)
9502 m_rowLabelHorizAlign
= horiz
;
9505 if ( vert
== wxALIGN_TOP
|| vert
== wxALIGN_CENTRE
|| vert
== wxALIGN_BOTTOM
)
9507 m_rowLabelVertAlign
= vert
;
9510 if ( !GetBatchCount() )
9512 m_rowLabelWin
->Refresh();
9516 void wxGrid::SetColLabelAlignment( int horiz
, int vert
)
9518 // allow old (incorrect) defs to be used
9521 case wxLEFT
: horiz
= wxALIGN_LEFT
; break;
9522 case wxRIGHT
: horiz
= wxALIGN_RIGHT
; break;
9523 case wxCENTRE
: horiz
= wxALIGN_CENTRE
; break;
9528 case wxTOP
: vert
= wxALIGN_TOP
; break;
9529 case wxBOTTOM
: vert
= wxALIGN_BOTTOM
; break;
9530 case wxCENTRE
: vert
= wxALIGN_CENTRE
; break;
9533 if ( horiz
== wxALIGN_LEFT
|| horiz
== wxALIGN_CENTRE
|| horiz
== wxALIGN_RIGHT
)
9535 m_colLabelHorizAlign
= horiz
;
9538 if ( vert
== wxALIGN_TOP
|| vert
== wxALIGN_CENTRE
|| vert
== wxALIGN_BOTTOM
)
9540 m_colLabelVertAlign
= vert
;
9543 if ( !GetBatchCount() )
9545 m_colWindow
->Refresh();
9549 // Note: under MSW, the default column label font must be changed because it
9550 // does not support vertical printing
9552 // Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
9553 // pGrid->SetLabelFont(font);
9554 // pGrid->SetColLabelTextOrientation(wxVERTICAL);
9556 void wxGrid::SetColLabelTextOrientation( int textOrientation
)
9558 if ( textOrientation
== wxHORIZONTAL
|| textOrientation
== wxVERTICAL
)
9559 m_colLabelTextOrientation
= textOrientation
;
9561 if ( !GetBatchCount() )
9562 m_colWindow
->Refresh();
9565 void wxGrid::SetRowLabelValue( int row
, const wxString
& s
)
9569 m_table
->SetRowLabelValue( row
, s
);
9570 if ( !GetBatchCount() )
9572 wxRect rect
= CellToRect( row
, 0 );
9573 if ( rect
.height
> 0 )
9575 CalcScrolledPosition(0, rect
.y
, &rect
.x
, &rect
.y
);
9577 rect
.width
= m_rowLabelWidth
;
9578 m_rowLabelWin
->Refresh( true, &rect
);
9584 void wxGrid::SetColLabelValue( int col
, const wxString
& s
)
9588 m_table
->SetColLabelValue( col
, s
);
9589 if ( !GetBatchCount() )
9591 if ( m_useNativeHeader
)
9593 GetGridColHeader()->UpdateColumn(col
);
9597 wxRect rect
= CellToRect( 0, col
);
9598 if ( rect
.width
> 0 )
9600 CalcScrolledPosition(rect
.x
, 0, &rect
.x
, &rect
.y
);
9602 rect
.height
= m_colLabelHeight
;
9603 GetColLabelWindow()->Refresh( true, &rect
);
9610 void wxGrid::SetGridLineColour( const wxColour
& colour
)
9612 if ( m_gridLineColour
!= colour
)
9614 m_gridLineColour
= colour
;
9616 if ( GridLinesEnabled() )
9621 void wxGrid::SetCellHighlightColour( const wxColour
& colour
)
9623 if ( m_cellHighlightColour
!= colour
)
9625 m_cellHighlightColour
= colour
;
9627 wxClientDC
dc( m_gridWin
);
9629 wxGridCellAttr
* attr
= GetCellAttr(m_currentCellCoords
);
9630 DrawCellHighlight(dc
, attr
);
9635 void wxGrid::SetCellHighlightPenWidth(int width
)
9637 if (m_cellHighlightPenWidth
!= width
)
9639 m_cellHighlightPenWidth
= width
;
9641 // Just redrawing the cell highlight is not enough since that won't
9642 // make any visible change if the the thickness is getting smaller.
9643 int row
= m_currentCellCoords
.GetRow();
9644 int col
= m_currentCellCoords
.GetCol();
9645 if ( row
== -1 || col
== -1 || GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
9648 wxRect rect
= CellToRect(row
, col
);
9649 m_gridWin
->Refresh(true, &rect
);
9653 void wxGrid::SetCellHighlightROPenWidth(int width
)
9655 if (m_cellHighlightROPenWidth
!= width
)
9657 m_cellHighlightROPenWidth
= width
;
9659 // Just redrawing the cell highlight is not enough since that won't
9660 // make any visible change if the the thickness is getting smaller.
9661 int row
= m_currentCellCoords
.GetRow();
9662 int col
= m_currentCellCoords
.GetCol();
9663 if ( row
== -1 || col
== -1 ||
9664 GetColWidth(col
) <= 0 || GetRowHeight(row
) <= 0 )
9667 wxRect rect
= CellToRect(row
, col
);
9668 m_gridWin
->Refresh(true, &rect
);
9672 void wxGrid::RedrawGridLines()
9674 // the lines will be redrawn when the window is thawn
9675 if ( GetBatchCount() )
9678 if ( GridLinesEnabled() )
9680 wxClientDC
dc( m_gridWin
);
9682 DrawAllGridLines( dc
, wxRegion() );
9684 else // remove the grid lines
9686 m_gridWin
->Refresh();
9690 void wxGrid::EnableGridLines( bool enable
)
9692 if ( enable
!= m_gridLinesEnabled
)
9694 m_gridLinesEnabled
= enable
;
9700 void wxGrid::DoClipGridLines(bool& var
, bool clip
)
9706 if ( GridLinesEnabled() )
9711 int wxGrid::GetDefaultRowSize() const
9713 return m_defaultRowHeight
;
9716 int wxGrid::GetRowSize( int row
) const
9718 wxCHECK_MSG( row
>= 0 && row
< m_numRows
, 0, _T("invalid row index") );
9720 return GetRowHeight(row
);
9723 int wxGrid::GetDefaultColSize() const
9725 return m_defaultColWidth
;
9728 int wxGrid::GetColSize( int col
) const
9730 wxCHECK_MSG( col
>= 0 && col
< m_numCols
, 0, _T("invalid column index") );
9732 return GetColWidth(col
);
9735 // ============================================================================
9736 // access to the grid attributes: each of them has a default value in the grid
9737 // itself and may be overidden on a per-cell basis
9738 // ============================================================================
9740 // ----------------------------------------------------------------------------
9741 // setting default attributes
9742 // ----------------------------------------------------------------------------
9744 void wxGrid::SetDefaultCellBackgroundColour( const wxColour
& col
)
9746 m_defaultCellAttr
->SetBackgroundColour(col
);
9748 m_gridWin
->SetBackgroundColour(col
);
9752 void wxGrid::SetDefaultCellTextColour( const wxColour
& col
)
9754 m_defaultCellAttr
->SetTextColour(col
);
9757 void wxGrid::SetDefaultCellAlignment( int horiz
, int vert
)
9759 m_defaultCellAttr
->SetAlignment(horiz
, vert
);
9762 void wxGrid::SetDefaultCellOverflow( bool allow
)
9764 m_defaultCellAttr
->SetOverflow(allow
);
9767 void wxGrid::SetDefaultCellFont( const wxFont
& font
)
9769 m_defaultCellAttr
->SetFont(font
);
9772 // For editors and renderers the type registry takes precedence over the
9773 // default attr, so we need to register the new editor/renderer for the string
9774 // data type in order to make setting a default editor/renderer appear to
9777 void wxGrid::SetDefaultRenderer(wxGridCellRenderer
*renderer
)
9779 RegisterDataType(wxGRID_VALUE_STRING
,
9781 GetDefaultEditorForType(wxGRID_VALUE_STRING
));
9784 void wxGrid::SetDefaultEditor(wxGridCellEditor
*editor
)
9786 RegisterDataType(wxGRID_VALUE_STRING
,
9787 GetDefaultRendererForType(wxGRID_VALUE_STRING
),
9791 // ----------------------------------------------------------------------------
9792 // access to the default attributes
9793 // ----------------------------------------------------------------------------
9795 wxColour
wxGrid::GetDefaultCellBackgroundColour() const
9797 return m_defaultCellAttr
->GetBackgroundColour();
9800 wxColour
wxGrid::GetDefaultCellTextColour() const
9802 return m_defaultCellAttr
->GetTextColour();
9805 wxFont
wxGrid::GetDefaultCellFont() const
9807 return m_defaultCellAttr
->GetFont();
9810 void wxGrid::GetDefaultCellAlignment( int *horiz
, int *vert
) const
9812 m_defaultCellAttr
->GetAlignment(horiz
, vert
);
9815 bool wxGrid::GetDefaultCellOverflow() const
9817 return m_defaultCellAttr
->GetOverflow();
9820 wxGridCellRenderer
*wxGrid::GetDefaultRenderer() const
9822 return m_defaultCellAttr
->GetRenderer(NULL
, 0, 0);
9825 wxGridCellEditor
*wxGrid::GetDefaultEditor() const
9827 return m_defaultCellAttr
->GetEditor(NULL
, 0, 0);
9830 // ----------------------------------------------------------------------------
9831 // access to cell attributes
9832 // ----------------------------------------------------------------------------
9834 wxColour
wxGrid::GetCellBackgroundColour(int row
, int col
) const
9836 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9837 wxColour colour
= attr
->GetBackgroundColour();
9843 wxColour
wxGrid::GetCellTextColour( int row
, int col
) const
9845 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9846 wxColour colour
= attr
->GetTextColour();
9852 wxFont
wxGrid::GetCellFont( int row
, int col
) const
9854 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9855 wxFont font
= attr
->GetFont();
9861 void wxGrid::GetCellAlignment( int row
, int col
, int *horiz
, int *vert
) const
9863 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9864 attr
->GetAlignment(horiz
, vert
);
9868 bool wxGrid::GetCellOverflow( int row
, int col
) const
9870 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9871 bool allow
= attr
->GetOverflow();
9877 void wxGrid::GetCellSize( int row
, int col
, int *num_rows
, int *num_cols
) const
9879 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
9880 attr
->GetSize( num_rows
, num_cols
);
9884 wxGridCellRenderer
* wxGrid::GetCellRenderer(int row
, int col
) const
9886 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9887 wxGridCellRenderer
* renderer
= attr
->GetRenderer(this, row
, col
);
9893 wxGridCellEditor
* wxGrid::GetCellEditor(int row
, int col
) const
9895 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9896 wxGridCellEditor
* editor
= attr
->GetEditor(this, row
, col
);
9902 bool wxGrid::IsReadOnly(int row
, int col
) const
9904 wxGridCellAttr
* attr
= GetCellAttr(row
, col
);
9905 bool isReadOnly
= attr
->IsReadOnly();
9911 // ----------------------------------------------------------------------------
9912 // attribute support: cache, automatic provider creation, ...
9913 // ----------------------------------------------------------------------------
9915 bool wxGrid::CanHaveAttributes() const
9922 return m_table
->CanHaveAttributes();
9925 void wxGrid::ClearAttrCache()
9927 if ( m_attrCache
.row
!= -1 )
9929 wxGridCellAttr
*oldAttr
= m_attrCache
.attr
;
9930 m_attrCache
.attr
= NULL
;
9931 m_attrCache
.row
= -1;
9932 // wxSafeDecRec(...) might cause event processing that accesses
9933 // the cached attribute, if one exists (e.g. by deleting the
9934 // editor stored within the attribute). Therefore it is important
9935 // to invalidate the cache before calling wxSafeDecRef!
9936 wxSafeDecRef(oldAttr
);
9940 void wxGrid::CacheAttr(int row
, int col
, wxGridCellAttr
*attr
) const
9944 wxGrid
*self
= (wxGrid
*)this; // const_cast
9946 self
->ClearAttrCache();
9947 self
->m_attrCache
.row
= row
;
9948 self
->m_attrCache
.col
= col
;
9949 self
->m_attrCache
.attr
= attr
;
9954 bool wxGrid::LookupAttr(int row
, int col
, wxGridCellAttr
**attr
) const
9956 if ( row
== m_attrCache
.row
&& col
== m_attrCache
.col
)
9958 *attr
= m_attrCache
.attr
;
9959 wxSafeIncRef(m_attrCache
.attr
);
9961 #ifdef DEBUG_ATTR_CACHE
9962 gs_nAttrCacheHits
++;
9969 #ifdef DEBUG_ATTR_CACHE
9970 gs_nAttrCacheMisses
++;
9977 wxGridCellAttr
*wxGrid::GetCellAttr(int row
, int col
) const
9979 wxGridCellAttr
*attr
= NULL
;
9980 // Additional test to avoid looking at the cache e.g. for
9981 // wxNoCellCoords, as this will confuse memory management.
9984 if ( !LookupAttr(row
, col
, &attr
) )
9986 attr
= m_table
? m_table
->GetAttr(row
, col
, wxGridCellAttr::Any
)
9988 CacheAttr(row
, col
, attr
);
9994 attr
->SetDefAttr(m_defaultCellAttr
);
9998 attr
= m_defaultCellAttr
;
10005 wxGridCellAttr
*wxGrid::GetOrCreateCellAttr(int row
, int col
) const
10007 wxGridCellAttr
*attr
= NULL
;
10008 bool canHave
= ((wxGrid
*)this)->CanHaveAttributes();
10010 wxCHECK_MSG( canHave
, attr
, _T("Cell attributes not allowed"));
10011 wxCHECK_MSG( m_table
, attr
, _T("must have a table") );
10013 attr
= m_table
->GetAttr(row
, col
, wxGridCellAttr::Cell
);
10016 attr
= new wxGridCellAttr(m_defaultCellAttr
);
10018 // artificially inc the ref count to match DecRef() in caller
10020 m_table
->SetAttr(attr
, row
, col
);
10026 // ----------------------------------------------------------------------------
10027 // setting column attributes (wrappers around SetColAttr)
10028 // ----------------------------------------------------------------------------
10030 void wxGrid::SetColFormatBool(int col
)
10032 SetColFormatCustom(col
, wxGRID_VALUE_BOOL
);
10035 void wxGrid::SetColFormatNumber(int col
)
10037 SetColFormatCustom(col
, wxGRID_VALUE_NUMBER
);
10040 void wxGrid::SetColFormatFloat(int col
, int width
, int precision
)
10042 wxString typeName
= wxGRID_VALUE_FLOAT
;
10043 if ( (width
!= -1) || (precision
!= -1) )
10045 typeName
<< _T(':') << width
<< _T(',') << precision
;
10048 SetColFormatCustom(col
, typeName
);
10051 void wxGrid::SetColFormatCustom(int col
, const wxString
& typeName
)
10053 wxGridCellAttr
*attr
= m_table
->GetAttr(-1, col
, wxGridCellAttr::Col
);
10055 attr
= new wxGridCellAttr
;
10056 wxGridCellRenderer
*renderer
= GetDefaultRendererForType(typeName
);
10057 attr
->SetRenderer(renderer
);
10058 wxGridCellEditor
*editor
= GetDefaultEditorForType(typeName
);
10059 attr
->SetEditor(editor
);
10061 SetColAttr(col
, attr
);
10065 // ----------------------------------------------------------------------------
10066 // setting cell attributes: this is forwarded to the table
10067 // ----------------------------------------------------------------------------
10069 void wxGrid::SetAttr(int row
, int col
, wxGridCellAttr
*attr
)
10071 if ( CanHaveAttributes() )
10073 m_table
->SetAttr(attr
, row
, col
);
10078 wxSafeDecRef(attr
);
10082 void wxGrid::SetRowAttr(int row
, wxGridCellAttr
*attr
)
10084 if ( CanHaveAttributes() )
10086 m_table
->SetRowAttr(attr
, row
);
10091 wxSafeDecRef(attr
);
10095 void wxGrid::SetColAttr(int col
, wxGridCellAttr
*attr
)
10097 if ( CanHaveAttributes() )
10099 m_table
->SetColAttr(attr
, col
);
10104 wxSafeDecRef(attr
);
10108 void wxGrid::SetCellBackgroundColour( int row
, int col
, const wxColour
& colour
)
10110 if ( CanHaveAttributes() )
10112 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10113 attr
->SetBackgroundColour(colour
);
10118 void wxGrid::SetCellTextColour( int row
, int col
, const wxColour
& colour
)
10120 if ( CanHaveAttributes() )
10122 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10123 attr
->SetTextColour(colour
);
10128 void wxGrid::SetCellFont( int row
, int col
, const wxFont
& font
)
10130 if ( CanHaveAttributes() )
10132 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10133 attr
->SetFont(font
);
10138 void wxGrid::SetCellAlignment( int row
, int col
, int horiz
, int vert
)
10140 if ( CanHaveAttributes() )
10142 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10143 attr
->SetAlignment(horiz
, vert
);
10148 void wxGrid::SetCellOverflow( int row
, int col
, bool allow
)
10150 if ( CanHaveAttributes() )
10152 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10153 attr
->SetOverflow(allow
);
10158 void wxGrid::SetCellSize( int row
, int col
, int num_rows
, int num_cols
)
10160 if ( CanHaveAttributes() )
10162 int cell_rows
, cell_cols
;
10164 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10165 attr
->GetSize(&cell_rows
, &cell_cols
);
10166 attr
->SetSize(num_rows
, num_cols
);
10169 // Cannot set the size of a cell to 0 or negative values
10170 // While it is perfectly legal to do that, this function cannot
10171 // handle all the possibilies, do it by hand by getting the CellAttr.
10172 // You can only set the size of a cell to 1,1 or greater with this fn
10173 wxASSERT_MSG( !((cell_rows
< 1) || (cell_cols
< 1)),
10174 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
10175 wxASSERT_MSG( !((num_rows
< 1) || (num_cols
< 1)),
10176 wxT("wxGrid::SetCellSize setting cell size to < 1"));
10178 // if this was already a multicell then "turn off" the other cells first
10179 if ((cell_rows
> 1) || (cell_cols
> 1))
10182 for (j
=row
; j
< row
+ cell_rows
; j
++)
10184 for (i
=col
; i
< col
+ cell_cols
; i
++)
10186 if ((i
!= col
) || (j
!= row
))
10188 wxGridCellAttr
*attr_stub
= GetOrCreateCellAttr(j
, i
);
10189 attr_stub
->SetSize( 1, 1 );
10190 attr_stub
->DecRef();
10196 // mark the cells that will be covered by this cell to
10197 // negative or zero values to point back at this cell
10198 if (((num_rows
> 1) || (num_cols
> 1)) && (num_rows
>= 1) && (num_cols
>= 1))
10201 for (j
=row
; j
< row
+ num_rows
; j
++)
10203 for (i
=col
; i
< col
+ num_cols
; i
++)
10205 if ((i
!= col
) || (j
!= row
))
10207 wxGridCellAttr
*attr_stub
= GetOrCreateCellAttr(j
, i
);
10208 attr_stub
->SetSize( row
- j
, col
- i
);
10209 attr_stub
->DecRef();
10217 void wxGrid::SetCellRenderer(int row
, int col
, wxGridCellRenderer
*renderer
)
10219 if ( CanHaveAttributes() )
10221 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10222 attr
->SetRenderer(renderer
);
10227 void wxGrid::SetCellEditor(int row
, int col
, wxGridCellEditor
* editor
)
10229 if ( CanHaveAttributes() )
10231 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10232 attr
->SetEditor(editor
);
10237 void wxGrid::SetReadOnly(int row
, int col
, bool isReadOnly
)
10239 if ( CanHaveAttributes() )
10241 wxGridCellAttr
*attr
= GetOrCreateCellAttr(row
, col
);
10242 attr
->SetReadOnly(isReadOnly
);
10247 // ----------------------------------------------------------------------------
10248 // Data type registration
10249 // ----------------------------------------------------------------------------
10251 void wxGrid::RegisterDataType(const wxString
& typeName
,
10252 wxGridCellRenderer
* renderer
,
10253 wxGridCellEditor
* editor
)
10255 m_typeRegistry
->RegisterDataType(typeName
, renderer
, editor
);
10259 wxGridCellEditor
* wxGrid::GetDefaultEditorForCell(int row
, int col
) const
10261 wxString typeName
= m_table
->GetTypeName(row
, col
);
10262 return GetDefaultEditorForType(typeName
);
10265 wxGridCellRenderer
* wxGrid::GetDefaultRendererForCell(int row
, int col
) const
10267 wxString typeName
= m_table
->GetTypeName(row
, col
);
10268 return GetDefaultRendererForType(typeName
);
10271 wxGridCellEditor
* wxGrid::GetDefaultEditorForType(const wxString
& typeName
) const
10273 int index
= m_typeRegistry
->FindOrCloneDataType(typeName
);
10274 if ( index
== wxNOT_FOUND
)
10276 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName
.c_str()));
10281 return m_typeRegistry
->GetEditor(index
);
10284 wxGridCellRenderer
* wxGrid::GetDefaultRendererForType(const wxString
& typeName
) const
10286 int index
= m_typeRegistry
->FindOrCloneDataType(typeName
);
10287 if ( index
== wxNOT_FOUND
)
10289 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName
.c_str()));
10294 return m_typeRegistry
->GetRenderer(index
);
10297 // ----------------------------------------------------------------------------
10299 // ----------------------------------------------------------------------------
10301 void wxGrid::EnableDragRowSize( bool enable
)
10303 m_canDragRowSize
= enable
;
10306 void wxGrid::EnableDragColSize( bool enable
)
10308 m_canDragColSize
= enable
;
10311 void wxGrid::EnableDragGridSize( bool enable
)
10313 m_canDragGridSize
= enable
;
10316 void wxGrid::EnableDragCell( bool enable
)
10318 m_canDragCell
= enable
;
10321 void wxGrid::SetDefaultRowSize( int height
, bool resizeExistingRows
)
10323 m_defaultRowHeight
= wxMax( height
, m_minAcceptableRowHeight
);
10325 if ( resizeExistingRows
)
10327 // since we are resizing all rows to the default row size,
10328 // we can simply clear the row heights and row bottoms
10329 // arrays (which also allows us to take advantage of
10330 // some speed optimisations)
10331 m_rowHeights
.Empty();
10332 m_rowBottoms
.Empty();
10333 if ( !GetBatchCount() )
10338 void wxGrid::SetRowSize( int row
, int height
)
10340 wxCHECK_RET( row
>= 0 && row
< m_numRows
, _T("invalid row index") );
10342 // if < 0 then calculate new height from label
10346 wxArrayString lines
;
10347 wxClientDC
dc(m_rowLabelWin
);
10348 dc
.SetFont(GetLabelFont());
10349 StringToLines(GetRowLabelValue( row
), lines
);
10350 GetTextBoxSize( dc
, lines
, &w
, &h
);
10351 //check that it is not less than the minimal height
10352 height
= wxMax(h
, GetRowMinimalAcceptableHeight());
10355 // See comment in SetColSize
10356 if ( height
< GetRowMinimalAcceptableHeight())
10359 if ( m_rowHeights
.IsEmpty() )
10361 // need to really create the array
10365 int h
= wxMax( 0, height
);
10366 int diff
= h
- m_rowHeights
[row
];
10368 m_rowHeights
[row
] = h
;
10369 for ( int i
= row
; i
< m_numRows
; i
++ )
10371 m_rowBottoms
[i
] += diff
;
10374 if ( !GetBatchCount() )
10378 void wxGrid::SetDefaultColSize( int width
, bool resizeExistingCols
)
10380 // we dont allow zero default column width
10381 m_defaultColWidth
= wxMax( wxMax( width
, m_minAcceptableColWidth
), 1 );
10383 if ( resizeExistingCols
)
10385 // since we are resizing all columns to the default column size,
10386 // we can simply clear the col widths and col rights
10387 // arrays (which also allows us to take advantage of
10388 // some speed optimisations)
10389 m_colWidths
.Empty();
10390 m_colRights
.Empty();
10391 if ( !GetBatchCount() )
10396 void wxGrid::SetColSize( int col
, int width
)
10398 wxCHECK_RET( col
>= 0 && col
< m_numCols
, _T("invalid column index") );
10400 // if < 0 then calculate new width from label
10404 wxArrayString lines
;
10405 wxClientDC
dc(m_colWindow
);
10406 dc
.SetFont(GetLabelFont());
10407 StringToLines(GetColLabelValue(col
), lines
);
10408 if ( GetColLabelTextOrientation() == wxHORIZONTAL
)
10409 GetTextBoxSize( dc
, lines
, &w
, &h
);
10411 GetTextBoxSize( dc
, lines
, &h
, &w
);
10413 //check that it is not less than the minimal width
10414 width
= wxMax(width
, GetColMinimalAcceptableWidth());
10417 // we intentionally don't test whether the width is less than
10418 // GetColMinimalWidth() here but we do compare it with
10419 // GetColMinimalAcceptableWidth() as otherwise things currently break (see
10420 // #651) -- and we also always allow the width of 0 as it has the special
10421 // sense of hiding the column
10422 if ( width
> 0 && width
< GetColMinimalAcceptableWidth() )
10425 if ( m_colWidths
.IsEmpty() )
10427 // need to really create the array
10431 const int diff
= width
- m_colWidths
[col
];
10432 m_colWidths
[col
] = width
;
10433 if ( m_useNativeHeader
)
10434 GetGridColHeader()->UpdateColumn(col
);
10435 //else: will be refreshed when the header is redrawn
10437 for ( int colPos
= GetColPos(col
); colPos
< m_numCols
; colPos
++ )
10439 m_colRights
[GetColAt(colPos
)] += diff
;
10442 if ( !GetBatchCount() )
10449 void wxGrid::SetColMinimalWidth( int col
, int width
)
10451 if (width
> GetColMinimalAcceptableWidth())
10453 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)col
;
10454 m_colMinWidths
[key
] = width
;
10458 void wxGrid::SetRowMinimalHeight( int row
, int width
)
10460 if (width
> GetRowMinimalAcceptableHeight())
10462 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)row
;
10463 m_rowMinHeights
[key
] = width
;
10467 int wxGrid::GetColMinimalWidth(int col
) const
10469 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)col
;
10470 wxLongToLongHashMap::const_iterator it
= m_colMinWidths
.find(key
);
10472 return it
!= m_colMinWidths
.end() ? (int)it
->second
: m_minAcceptableColWidth
;
10475 int wxGrid::GetRowMinimalHeight(int row
) const
10477 wxLongToLongHashMap::key_type key
= (wxLongToLongHashMap::key_type
)row
;
10478 wxLongToLongHashMap::const_iterator it
= m_rowMinHeights
.find(key
);
10480 return it
!= m_rowMinHeights
.end() ? (int)it
->second
: m_minAcceptableRowHeight
;
10483 void wxGrid::SetColMinimalAcceptableWidth( int width
)
10485 // We do allow a width of 0 since this gives us
10486 // an easy way to temporarily hiding columns.
10488 m_minAcceptableColWidth
= width
;
10491 void wxGrid::SetRowMinimalAcceptableHeight( int height
)
10493 // We do allow a height of 0 since this gives us
10494 // an easy way to temporarily hiding rows.
10496 m_minAcceptableRowHeight
= height
;
10499 int wxGrid::GetColMinimalAcceptableWidth() const
10501 return m_minAcceptableColWidth
;
10504 int wxGrid::GetRowMinimalAcceptableHeight() const
10506 return m_minAcceptableRowHeight
;
10509 // ----------------------------------------------------------------------------
10511 // ----------------------------------------------------------------------------
10514 wxGrid::AutoSizeColOrRow(int colOrRow
, bool setAsMin
, wxGridDirection direction
)
10516 const bool column
= direction
== wxGRID_COLUMN
;
10518 wxClientDC
dc(m_gridWin
);
10520 // cancel editing of cell
10521 HideCellEditControl();
10522 SaveEditControlValue();
10524 // init both of them to avoid compiler warnings, even if we only need one
10532 wxCoord extent
, extentMax
= 0;
10533 int max
= column
? m_numRows
: m_numCols
;
10534 for ( int rowOrCol
= 0; rowOrCol
< max
; rowOrCol
++ )
10541 wxGridCellAttr
*attr
= GetCellAttr(row
, col
);
10542 wxGridCellRenderer
*renderer
= attr
->GetRenderer(this, row
, col
);
10545 wxSize size
= renderer
->GetBestSize(*this, *attr
, dc
, row
, col
);
10546 extent
= column
? size
.x
: size
.y
;
10547 if ( extent
> extentMax
)
10548 extentMax
= extent
;
10550 renderer
->DecRef();
10556 // now also compare with the column label extent
10558 dc
.SetFont( GetLabelFont() );
10562 dc
.GetMultiLineTextExtent( GetColLabelValue(col
), &w
, &h
);
10563 if ( GetColLabelTextOrientation() == wxVERTICAL
)
10567 dc
.GetMultiLineTextExtent( GetRowLabelValue(row
), &w
, &h
);
10569 extent
= column
? w
: h
;
10570 if ( extent
> extentMax
)
10571 extentMax
= extent
;
10575 // empty column - give default extent (notice that if extentMax is less
10576 // than default extent but != 0, it's OK)
10577 extentMax
= column
? m_defaultColWidth
: m_defaultRowHeight
;
10582 // leave some space around text
10590 // Ensure automatic width is not less than minimal width. See the
10591 // comment in SetColSize() for explanation of why this isn't done
10592 // in SetColSize().
10594 extentMax
= wxMax(extentMax
, GetColMinimalWidth(col
));
10596 SetColSize( col
, extentMax
);
10597 if ( !GetBatchCount() )
10599 if ( m_useNativeHeader
)
10601 GetGridColHeader()->UpdateColumn(col
);
10606 m_gridWin
->GetClientSize( &cw
, &ch
);
10607 wxRect
rect ( CellToRect( 0, col
) );
10609 CalcScrolledPosition(rect
.x
, 0, &rect
.x
, &dummy
);
10610 rect
.width
= cw
- rect
.x
;
10611 rect
.height
= m_colLabelHeight
;
10612 GetColLabelWindow()->Refresh( true, &rect
);
10618 // Ensure automatic width is not less than minimal height. See the
10619 // comment in SetColSize() for explanation of why this isn't done
10620 // in SetRowSize().
10622 extentMax
= wxMax(extentMax
, GetRowMinimalHeight(row
));
10624 SetRowSize(row
, extentMax
);
10625 if ( !GetBatchCount() )
10628 m_gridWin
->GetClientSize( &cw
, &ch
);
10629 wxRect
rect( CellToRect( row
, 0 ) );
10631 CalcScrolledPosition(0, rect
.y
, &dummy
, &rect
.y
);
10632 rect
.width
= m_rowLabelWidth
;
10633 rect
.height
= ch
- rect
.y
;
10634 m_rowLabelWin
->Refresh( true, &rect
);
10641 SetColMinimalWidth(col
, extentMax
);
10643 SetRowMinimalHeight(row
, extentMax
);
10647 wxCoord
wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction
)
10649 // calculate size for the rows or columns?
10650 const bool calcRows
= direction
== wxGRID_ROW
;
10652 wxClientDC
dc(calcRows
? GetGridRowLabelWindow()
10653 : GetGridColLabelWindow());
10654 dc
.SetFont(GetLabelFont());
10656 // which dimension should we take into account for calculations?
10658 // for columns, the text can be only horizontal so it's easy but for rows
10659 // we also have to take into account the text orientation
10661 useWidth
= calcRows
|| (GetColLabelTextOrientation() == wxVERTICAL
);
10663 wxArrayString lines
;
10664 wxCoord extentMax
= 0;
10666 const int numRowsOrCols
= calcRows
? m_numRows
: m_numCols
;
10667 for ( int rowOrCol
= 0; rowOrCol
< numRowsOrCols
; rowOrCol
++ )
10671 wxString label
= calcRows
? GetRowLabelValue(rowOrCol
)
10672 : GetColLabelValue(rowOrCol
);
10673 StringToLines(label
, lines
);
10676 GetTextBoxSize(dc
, lines
, &w
, &h
);
10678 const wxCoord extent
= useWidth
? w
: h
;
10679 if ( extent
> extentMax
)
10680 extentMax
= extent
;
10685 // empty column - give default extent (notice that if extentMax is less
10686 // than default extent but != 0, it's OK)
10687 extentMax
= calcRows
? GetDefaultRowLabelSize()
10688 : GetDefaultColLabelSize();
10691 // leave some space around text (taken from AutoSizeColOrRow)
10700 int wxGrid::SetOrCalcColumnSizes(bool calcOnly
, bool setAsMin
)
10702 int width
= m_rowLabelWidth
;
10704 wxGridUpdateLocker locker
;
10706 locker
.Create(this);
10708 for ( int col
= 0; col
< m_numCols
; col
++ )
10711 AutoSizeColumn(col
, setAsMin
);
10713 width
+= GetColWidth(col
);
10719 int wxGrid::SetOrCalcRowSizes(bool calcOnly
, bool setAsMin
)
10721 int height
= m_colLabelHeight
;
10723 wxGridUpdateLocker locker
;
10725 locker
.Create(this);
10727 for ( int row
= 0; row
< m_numRows
; row
++ )
10730 AutoSizeRow(row
, setAsMin
);
10732 height
+= GetRowHeight(row
);
10738 void wxGrid::AutoSize()
10740 wxGridUpdateLocker
locker(this);
10742 wxSize
size(SetOrCalcColumnSizes(false) - m_rowLabelWidth
+ m_extraWidth
,
10743 SetOrCalcRowSizes(false) - m_colLabelHeight
+ m_extraHeight
);
10745 // we know that we're not going to have scrollbars so disable them now to
10746 // avoid trouble in SetClientSize() which can otherwise set the correct
10747 // client size but also leave space for (not needed any more) scrollbars
10748 SetScrollbars(0, 0, 0, 0, 0, 0, true);
10750 // restore the scroll rate parameters overwritten by SetScrollbars()
10751 SetScrollRate(m_scrollLineX
, m_scrollLineY
);
10753 SetClientSize(size
.x
+ m_rowLabelWidth
, size
.y
+ m_colLabelHeight
);
10756 void wxGrid::AutoSizeRowLabelSize( int row
)
10758 // Hide the edit control, so it
10759 // won't interfere with drag-shrinking.
10760 if ( IsCellEditControlShown() )
10762 HideCellEditControl();
10763 SaveEditControlValue();
10766 // autosize row height depending on label text
10767 SetRowSize(row
, -1);
10771 void wxGrid::AutoSizeColLabelSize( int col
)
10773 // Hide the edit control, so it
10774 // won't interfere with drag-shrinking.
10775 if ( IsCellEditControlShown() )
10777 HideCellEditControl();
10778 SaveEditControlValue();
10781 // autosize column width depending on label text
10782 SetColSize(col
, -1);
10786 wxSize
wxGrid::DoGetBestSize() const
10788 wxGrid
*self
= (wxGrid
*)this; // const_cast
10790 // we do the same as in AutoSize() here with the exception that we don't
10791 // change the column/row sizes, only calculate them
10792 wxSize
size(self
->SetOrCalcColumnSizes(true) - m_rowLabelWidth
+ m_extraWidth
,
10793 self
->SetOrCalcRowSizes(true) - m_colLabelHeight
+ m_extraHeight
);
10795 // NOTE: This size should be cached, but first we need to add calls to
10796 // InvalidateBestSize everywhere that could change the results of this
10798 // CacheBestSize(size);
10800 return wxSize(size
.x
+ m_rowLabelWidth
, size
.y
+ m_colLabelHeight
)
10801 + GetWindowBorderSize();
10809 wxPen
& wxGrid::GetDividerPen() const
10814 // ----------------------------------------------------------------------------
10815 // cell value accessor functions
10816 // ----------------------------------------------------------------------------
10818 void wxGrid::SetCellValue( int row
, int col
, const wxString
& s
)
10822 m_table
->SetValue( row
, col
, s
);
10823 if ( !GetBatchCount() )
10826 wxRect
rect( CellToRect( row
, col
) );
10828 rect
.width
= m_gridWin
->GetClientSize().GetWidth();
10829 CalcScrolledPosition(0, rect
.y
, &dummy
, &rect
.y
);
10830 m_gridWin
->Refresh( false, &rect
);
10833 if ( m_currentCellCoords
.GetRow() == row
&&
10834 m_currentCellCoords
.GetCol() == col
&&
10835 IsCellEditControlShown())
10836 // Note: If we are using IsCellEditControlEnabled,
10837 // this interacts badly with calling SetCellValue from
10838 // an EVT_GRID_CELL_CHANGE handler.
10840 HideCellEditControl();
10841 ShowCellEditControl(); // will reread data from table
10846 // ----------------------------------------------------------------------------
10847 // block, row and column selection
10848 // ----------------------------------------------------------------------------
10850 void wxGrid::SelectRow( int row
, bool addToSelected
)
10852 if ( !m_selection
)
10855 if ( !addToSelected
)
10858 m_selection
->SelectRow(row
);
10861 void wxGrid::SelectCol( int col
, bool addToSelected
)
10863 if ( !m_selection
)
10866 if ( !addToSelected
)
10869 m_selection
->SelectCol(col
);
10872 void wxGrid::SelectBlock(int topRow
, int leftCol
, int bottomRow
, int rightCol
,
10873 bool addToSelected
)
10875 if ( !m_selection
)
10878 if ( !addToSelected
)
10881 m_selection
->SelectBlock(topRow
, leftCol
, bottomRow
, rightCol
);
10884 void wxGrid::SelectAll()
10886 if ( m_numRows
> 0 && m_numCols
> 0 )
10889 m_selection
->SelectBlock( 0, 0, m_numRows
- 1, m_numCols
- 1 );
10893 // ----------------------------------------------------------------------------
10894 // cell, row and col deselection
10895 // ----------------------------------------------------------------------------
10897 void wxGrid::DeselectLine(int line
, const wxGridOperations
& oper
)
10899 if ( !m_selection
)
10902 const wxGridSelectionModes mode
= m_selection
->GetSelectionMode();
10903 if ( mode
== oper
.GetSelectionMode() )
10905 const wxGridCellCoords
c(oper
.MakeCoords(line
, 0));
10906 if ( m_selection
->IsInSelection(c
) )
10907 m_selection
->ToggleCellSelection(c
);
10909 else if ( mode
!= oper
.Dual().GetSelectionMode() )
10911 const int nOther
= oper
.Dual().GetNumberOfLines(this);
10912 for ( int i
= 0; i
< nOther
; i
++ )
10914 const wxGridCellCoords
c(oper
.MakeCoords(line
, i
));
10915 if ( m_selection
->IsInSelection(c
) )
10916 m_selection
->ToggleCellSelection(c
);
10919 //else: can only select orthogonal lines so no lines in this direction
10920 // could have been selected anyhow
10923 void wxGrid::DeselectRow(int row
)
10925 DeselectLine(row
, wxGridRowOperations());
10928 void wxGrid::DeselectCol(int col
)
10930 DeselectLine(col
, wxGridColumnOperations());
10933 void wxGrid::DeselectCell( int row
, int col
)
10935 if ( m_selection
&& m_selection
->IsInSelection(row
, col
) )
10936 m_selection
->ToggleCellSelection(row
, col
);
10939 bool wxGrid::IsSelection() const
10941 return ( m_selection
&& (m_selection
->IsSelection() ||
10942 ( m_selectedBlockTopLeft
!= wxGridNoCellCoords
&&
10943 m_selectedBlockBottomRight
!= wxGridNoCellCoords
) ) );
10946 bool wxGrid::IsInSelection( int row
, int col
) const
10948 return ( m_selection
&& (m_selection
->IsInSelection( row
, col
) ||
10949 ( row
>= m_selectedBlockTopLeft
.GetRow() &&
10950 col
>= m_selectedBlockTopLeft
.GetCol() &&
10951 row
<= m_selectedBlockBottomRight
.GetRow() &&
10952 col
<= m_selectedBlockBottomRight
.GetCol() )) );
10955 wxGridCellCoordsArray
wxGrid::GetSelectedCells() const
10959 wxGridCellCoordsArray a
;
10963 return m_selection
->m_cellSelection
;
10966 wxGridCellCoordsArray
wxGrid::GetSelectionBlockTopLeft() const
10970 wxGridCellCoordsArray a
;
10974 return m_selection
->m_blockSelectionTopLeft
;
10977 wxGridCellCoordsArray
wxGrid::GetSelectionBlockBottomRight() const
10981 wxGridCellCoordsArray a
;
10985 return m_selection
->m_blockSelectionBottomRight
;
10988 wxArrayInt
wxGrid::GetSelectedRows() const
10996 return m_selection
->m_rowSelection
;
10999 wxArrayInt
wxGrid::GetSelectedCols() const
11007 return m_selection
->m_colSelection
;
11010 void wxGrid::ClearSelection()
11012 wxRect r1
= BlockToDeviceRect(m_selectedBlockTopLeft
,
11013 m_selectedBlockBottomRight
);
11014 wxRect r2
= BlockToDeviceRect(m_currentCellCoords
,
11015 m_selectedBlockCorner
);
11017 m_selectedBlockTopLeft
=
11018 m_selectedBlockBottomRight
=
11019 m_selectedBlockCorner
= wxGridNoCellCoords
;
11021 Refresh( false, &r1
);
11022 Refresh( false, &r2
);
11025 m_selection
->ClearSelection();
11028 // This function returns the rectangle that encloses the given block
11029 // in device coords clipped to the client size of the grid window.
11031 wxRect
wxGrid::BlockToDeviceRect( const wxGridCellCoords
& topLeft
,
11032 const wxGridCellCoords
& bottomRight
) const
11035 wxRect tempCellRect
= CellToRect(topLeft
);
11036 if ( tempCellRect
!= wxGridNoCellRect
)
11038 resultRect
= tempCellRect
;
11042 resultRect
= wxRect(0, 0, 0, 0);
11045 tempCellRect
= CellToRect(bottomRight
);
11046 if ( tempCellRect
!= wxGridNoCellRect
)
11048 resultRect
+= tempCellRect
;
11052 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
11053 return wxGridNoCellRect
;
11056 // Ensure that left/right and top/bottom pairs are in order.
11057 int left
= resultRect
.GetLeft();
11058 int top
= resultRect
.GetTop();
11059 int right
= resultRect
.GetRight();
11060 int bottom
= resultRect
.GetBottom();
11062 int leftCol
= topLeft
.GetCol();
11063 int topRow
= topLeft
.GetRow();
11064 int rightCol
= bottomRight
.GetCol();
11065 int bottomRow
= bottomRight
.GetRow();
11074 leftCol
= rightCol
;
11085 topRow
= bottomRow
;
11089 // The following loop is ONLY necessary to detect and handle merged cells.
11091 m_gridWin
->GetClientSize( &cw
, &ch
);
11093 // Get the origin coordinates: notice that they will be negative if the
11094 // grid is scrolled downwards/to the right.
11095 int gridOriginX
= 0;
11096 int gridOriginY
= 0;
11097 CalcScrolledPosition(gridOriginX
, gridOriginY
, &gridOriginX
, &gridOriginY
);
11099 int onScreenLeftmostCol
= internalXToCol(-gridOriginX
);
11100 int onScreenUppermostRow
= internalYToRow(-gridOriginY
);
11102 int onScreenRightmostCol
= internalXToCol(-gridOriginX
+ cw
);
11103 int onScreenBottommostRow
= internalYToRow(-gridOriginY
+ ch
);
11105 // Bound our loop so that we only examine the portion of the selected block
11106 // that is shown on screen. Therefore, we compare the Top-Left block values
11107 // to the Top-Left screen values, and the Bottom-Right block values to the
11108 // Bottom-Right screen values, choosing appropriately.
11109 const int visibleTopRow
= wxMax(topRow
, onScreenUppermostRow
);
11110 const int visibleBottomRow
= wxMin(bottomRow
, onScreenBottommostRow
);
11111 const int visibleLeftCol
= wxMax(leftCol
, onScreenLeftmostCol
);
11112 const int visibleRightCol
= wxMin(rightCol
, onScreenRightmostCol
);
11114 for ( int j
= visibleTopRow
; j
<= visibleBottomRow
; j
++ )
11116 for ( int i
= visibleLeftCol
; i
<= visibleRightCol
; i
++ )
11118 if ( (j
== visibleTopRow
) || (j
== visibleBottomRow
) ||
11119 (i
== visibleLeftCol
) || (i
== visibleRightCol
) )
11121 tempCellRect
= CellToRect( j
, i
);
11123 if (tempCellRect
.x
< left
)
11124 left
= tempCellRect
.x
;
11125 if (tempCellRect
.y
< top
)
11126 top
= tempCellRect
.y
;
11127 if (tempCellRect
.x
+ tempCellRect
.width
> right
)
11128 right
= tempCellRect
.x
+ tempCellRect
.width
;
11129 if (tempCellRect
.y
+ tempCellRect
.height
> bottom
)
11130 bottom
= tempCellRect
.y
+ tempCellRect
.height
;
11134 i
= visibleRightCol
; // jump over inner cells.
11139 // Convert to scrolled coords
11140 CalcScrolledPosition( left
, top
, &left
, &top
);
11141 CalcScrolledPosition( right
, bottom
, &right
, &bottom
);
11143 if (right
< 0 || bottom
< 0 || left
> cw
|| top
> ch
)
11144 return wxRect(0,0,0,0);
11146 resultRect
.SetLeft( wxMax(0, left
) );
11147 resultRect
.SetTop( wxMax(0, top
) );
11148 resultRect
.SetRight( wxMin(cw
, right
) );
11149 resultRect
.SetBottom( wxMin(ch
, bottom
) );
11154 // ----------------------------------------------------------------------------
11156 // ----------------------------------------------------------------------------
11158 #if wxUSE_DRAG_AND_DROP
11160 // this allow setting drop target directly on wxGrid
11161 void wxGrid::SetDropTarget(wxDropTarget
*dropTarget
)
11163 GetGridWindow()->SetDropTarget(dropTarget
);
11166 #endif // wxUSE_DRAG_AND_DROP
11168 // ----------------------------------------------------------------------------
11169 // grid event classes
11170 // ----------------------------------------------------------------------------
11172 IMPLEMENT_DYNAMIC_CLASS( wxGridEvent
, wxNotifyEvent
)
11174 wxGridEvent::wxGridEvent( int id
, wxEventType type
, wxObject
* obj
,
11175 int row
, int col
, int x
, int y
, bool sel
,
11176 bool control
, bool shift
, bool alt
, bool meta
)
11177 : wxNotifyEvent( type
, id
),
11178 wxKeyboardState(control
, shift
, alt
, meta
)
11180 Init(row
, col
, x
, y
, sel
);
11182 SetEventObject(obj
);
11185 IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent
, wxNotifyEvent
)
11187 wxGridSizeEvent::wxGridSizeEvent( int id
, wxEventType type
, wxObject
* obj
,
11188 int rowOrCol
, int x
, int y
,
11189 bool control
, bool shift
, bool alt
, bool meta
)
11190 : wxNotifyEvent( type
, id
),
11191 wxKeyboardState(control
, shift
, alt
, meta
)
11193 Init(rowOrCol
, x
, y
);
11195 SetEventObject(obj
);
11199 IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent
, wxNotifyEvent
)
11201 wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id
, wxEventType type
, wxObject
* obj
,
11202 const wxGridCellCoords
& topLeft
,
11203 const wxGridCellCoords
& bottomRight
,
11204 bool sel
, bool control
,
11205 bool shift
, bool alt
, bool meta
)
11206 : wxNotifyEvent( type
, id
),
11207 wxKeyboardState(control
, shift
, alt
, meta
)
11209 Init(topLeft
, bottomRight
, sel
);
11211 SetEventObject(obj
);
11215 IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent
, wxCommandEvent
)
11217 wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id
, wxEventType type
,
11218 wxObject
* obj
, int row
,
11219 int col
, wxControl
* ctrl
)
11220 : wxCommandEvent(type
, id
)
11222 SetEventObject(obj
);
11228 #endif // wxUSE_GRID