]> git.saurik.com Git - wxWidgets.git/blob - src/generic/grid.cpp
more attempts to fix CppUnit::assertEquals for VC6 without breaking everything else
[wxWidgets.git] / src / generic / grid.cpp
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
6 // Created: 1/08/1999
7 // RCS-ID: $Id$
8 // Copyright: (c) Michael Bedward (mbedward@ozemail.com.au)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 TODO:
14
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.
19 */
20
21 // For compilers that support precompilation, includes "wx/wx.h".
22 #include "wx/wxprec.h"
23
24 #ifdef __BORLANDC__
25 #pragma hdrstop
26 #endif
27
28 #if wxUSE_GRID
29
30 #include "wx/grid.h"
31
32 #ifndef WX_PRECOMP
33 #include "wx/utils.h"
34 #include "wx/dcclient.h"
35 #include "wx/settings.h"
36 #include "wx/log.h"
37 #include "wx/textctrl.h"
38 #include "wx/checkbox.h"
39 #include "wx/combobox.h"
40 #include "wx/valtext.h"
41 #include "wx/intl.h"
42 #include "wx/math.h"
43 #include "wx/listbox.h"
44 #endif
45
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"
51
52 #include "wx/generic/gridsel.h"
53
54 const char wxGridNameStr[] = "grid";
55
56 #if defined(__WXMOTIF__)
57 #define WXUNUSED_MOTIF(identifier) WXUNUSED(identifier)
58 #else
59 #define WXUNUSED_MOTIF(identifier) identifier
60 #endif
61
62 #if defined(__WXGTK__)
63 #define WXUNUSED_GTK(identifier) WXUNUSED(identifier)
64 #else
65 #define WXUNUSED_GTK(identifier) identifier
66 #endif
67
68 // Required for wxIs... functions
69 #include <ctype.h>
70
71 // ----------------------------------------------------------------------------
72 // array classes
73 // ----------------------------------------------------------------------------
74
75 WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridCellAttr *, wxArrayAttrs,
76 class WXDLLIMPEXP_ADV);
77
78 struct wxGridCellWithAttr
79 {
80 wxGridCellWithAttr(int row, int col, wxGridCellAttr *attr_)
81 : coords(row, col), attr(attr_)
82 {
83 wxASSERT( attr );
84 }
85
86 wxGridCellWithAttr(const wxGridCellWithAttr& other)
87 : coords(other.coords),
88 attr(other.attr)
89 {
90 attr->IncRef();
91 }
92
93 wxGridCellWithAttr& operator=(const wxGridCellWithAttr& other)
94 {
95 coords = other.coords;
96 if (attr != other.attr)
97 {
98 attr->DecRef();
99 attr = other.attr;
100 attr->IncRef();
101 }
102 return *this;
103 }
104
105 void ChangeAttr(wxGridCellAttr* new_attr)
106 {
107 if (attr != new_attr)
108 {
109 // "Delete" (i.e. DecRef) the old attribute.
110 attr->DecRef();
111 attr = new_attr;
112 // Take ownership of the new attribute, i.e. no IncRef.
113 }
114 }
115
116 ~wxGridCellWithAttr()
117 {
118 attr->DecRef();
119 }
120
121 wxGridCellCoords coords;
122 wxGridCellAttr *attr;
123 };
124
125 WX_DECLARE_OBJARRAY_WITH_DECL(wxGridCellWithAttr, wxGridCellWithAttrArray,
126 class WXDLLIMPEXP_ADV);
127
128 #include "wx/arrimpl.cpp"
129
130 WX_DEFINE_OBJARRAY(wxGridCellCoordsArray)
131 WX_DEFINE_OBJARRAY(wxGridCellWithAttrArray)
132
133 // ----------------------------------------------------------------------------
134 // events
135 // ----------------------------------------------------------------------------
136
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_CHANGING)
152 DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_CHANGED)
153 DEFINE_EVENT_TYPE(wxEVT_GRID_SELECT_CELL)
154 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_SHOWN)
155 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_HIDDEN)
156 DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_CREATED)
157
158 // ----------------------------------------------------------------------------
159 // private classes
160 // ----------------------------------------------------------------------------
161
162 // header column providing access to the column information stored in wxGrid
163 // via wxHeaderColumn interface
164 class wxGridHeaderColumn : public wxHeaderColumn
165 {
166 public:
167 wxGridHeaderColumn(wxGrid *grid, int col)
168 : m_grid(grid),
169 m_col(col)
170 {
171 }
172
173 virtual wxString GetTitle() const { return m_grid->GetColLabelValue(m_col); }
174 virtual wxBitmap GetBitmap() const { return wxNullBitmap; }
175 virtual int GetWidth() const { return m_grid->GetColSize(m_col); }
176 virtual int GetMinWidth() const { return 0; }
177 virtual wxAlignment GetAlignment() const
178 {
179 int horz,
180 vert;
181 m_grid->GetColLabelAlignment(&horz, &vert);
182
183 return static_cast<wxAlignment>(horz);
184 }
185
186 virtual int GetFlags() const
187 {
188 // we can't know in advance whether we can sort by this column or not
189 // with wxGrid API so suppose we can by default
190 int flags = wxCOL_SORTABLE;
191 if ( m_grid->CanDragColSize() )
192 flags |= wxCOL_RESIZABLE;
193 if ( m_grid->CanDragColMove() )
194 flags |= wxCOL_REORDERABLE;
195 if ( GetWidth() == 0 )
196 flags |= wxCOL_HIDDEN;
197
198 return flags;
199 }
200
201 virtual bool IsSortKey() const
202 {
203 return m_grid->IsSortingBy(m_col);
204 }
205
206 virtual bool IsSortOrderAscending() const
207 {
208 return m_grid->IsSortOrderAscending();
209 }
210
211 private:
212 // these really should be const but are not because the column needs to be
213 // assignable to be used in a wxVector (in STL build, in non-STL build we
214 // avoid the need for this)
215 wxGrid *m_grid;
216 int m_col;
217 };
218
219 // header control retreiving column information from the grid
220 class wxGridHeaderCtrl : public wxHeaderCtrl
221 {
222 public:
223 wxGridHeaderCtrl(wxGrid *owner)
224 : wxHeaderCtrl(owner,
225 wxID_ANY,
226 wxDefaultPosition,
227 wxDefaultSize,
228 wxHD_ALLOW_HIDE |
229 (owner->CanDragColMove() ? wxHD_ALLOW_REORDER : 0))
230 {
231 }
232
233 protected:
234 virtual const wxHeaderColumn& GetColumn(unsigned int idx) const
235 {
236 return m_columns[idx];
237 }
238
239 private:
240 wxGrid *GetOwner() const { return static_cast<wxGrid *>(GetParent()); }
241
242 // override the base class method to update our m_columns array
243 virtual void OnColumnCountChanging(unsigned int count)
244 {
245 const unsigned countOld = m_columns.size();
246 if ( count < countOld )
247 {
248 // just discard the columns which don't exist any more (notice that
249 // we can't use resize() here as it would require the vector
250 // value_type, i.e. wxGridHeaderColumn to be default constructible,
251 // which it is not)
252 m_columns.erase(m_columns.begin() + count, m_columns.end());
253 }
254 else // new columns added
255 {
256 // add columns for the new elements
257 for ( unsigned n = countOld; n < count; n++ )
258 m_columns.push_back(wxGridHeaderColumn(GetOwner(), n));
259 }
260 }
261
262 // override to implement column auto sizing
263 virtual bool UpdateColumnWidthToFit(unsigned int idx, int widthTitle)
264 {
265 // TODO: currently grid doesn't support computing the column best width
266 // from its contents so we just use the best label width as is
267 GetOwner()->SetColSize(idx, widthTitle);
268
269 return true;
270 }
271
272 // overridden to react to the actions using the columns popup menu
273 virtual void UpdateColumnVisibility(unsigned int idx, bool show)
274 {
275 GetOwner()->SetColSize(idx, show ? wxGRID_AUTOSIZE : 0);
276
277 // as this is done by the user we should notify the main program about
278 // it
279 GetOwner()->SendEvent(wxEVT_GRID_COL_SIZE, -1, idx);
280 }
281
282 // overridden to react to the columns order changes in the customization
283 // dialog
284 virtual void UpdateColumnsOrder(const wxArrayInt& order)
285 {
286 GetOwner()->SetColumnsOrder(order);
287 }
288
289
290 // event handlers forwarding wxHeaderCtrl events to wxGrid
291 void OnClick(wxHeaderCtrlEvent& event)
292 {
293 GetOwner()->DoColHeaderClick(event.GetColumn());
294 }
295
296 void OnBeginResize(wxHeaderCtrlEvent& event)
297 {
298 GetOwner()->DoStartResizeCol(event.GetColumn());
299
300 event.Skip();
301 }
302
303 void OnResizing(wxHeaderCtrlEvent& event)
304 {
305 GetOwner()->DoUpdateResizeColWidth(event.GetWidth());
306 }
307
308 void OnEndResize(wxHeaderCtrlEvent& event)
309 {
310 GetOwner()->DoEndDragResizeCol();
311
312 event.Skip();
313 }
314
315 void OnBeginReorder(wxHeaderCtrlEvent& event)
316 {
317 GetOwner()->DoStartMoveCol(event.GetColumn());
318 }
319
320 void OnEndReorder(wxHeaderCtrlEvent& event)
321 {
322 GetOwner()->DoEndMoveCol(event.GetNewOrder());
323 }
324
325 wxVector<wxGridHeaderColumn> m_columns;
326
327 DECLARE_EVENT_TABLE()
328 DECLARE_NO_COPY_CLASS(wxGridHeaderCtrl)
329 };
330
331 BEGIN_EVENT_TABLE(wxGridHeaderCtrl, wxHeaderCtrl)
332 EVT_HEADER_CLICK(wxID_ANY, wxGridHeaderCtrl::OnClick)
333
334 EVT_HEADER_BEGIN_RESIZE(wxID_ANY, wxGridHeaderCtrl::OnBeginResize)
335 EVT_HEADER_RESIZING(wxID_ANY, wxGridHeaderCtrl::OnResizing)
336 EVT_HEADER_END_RESIZE(wxID_ANY, wxGridHeaderCtrl::OnEndResize)
337
338 EVT_HEADER_BEGIN_REORDER(wxID_ANY, wxGridHeaderCtrl::OnBeginReorder)
339 EVT_HEADER_END_REORDER(wxID_ANY, wxGridHeaderCtrl::OnEndReorder)
340 END_EVENT_TABLE()
341
342 // common base class for various grid subwindows
343 class WXDLLIMPEXP_ADV wxGridSubwindow : public wxWindow
344 {
345 public:
346 wxGridSubwindow(wxGrid *owner,
347 int additionalStyle = 0,
348 const wxString& name = wxPanelNameStr)
349 : wxWindow(owner, wxID_ANY,
350 wxDefaultPosition, wxDefaultSize,
351 wxBORDER_NONE | additionalStyle,
352 name)
353 {
354 m_owner = owner;
355 }
356
357 virtual bool AcceptsFocus() const { return false; }
358
359 wxGrid *GetOwner() { return m_owner; }
360
361 protected:
362 void OnMouseCaptureLost(wxMouseCaptureLostEvent& event);
363
364 wxGrid *m_owner;
365
366 DECLARE_EVENT_TABLE()
367 DECLARE_NO_COPY_CLASS(wxGridSubwindow)
368 };
369
370 class WXDLLIMPEXP_ADV wxGridRowLabelWindow : public wxGridSubwindow
371 {
372 public:
373 wxGridRowLabelWindow(wxGrid *parent)
374 : wxGridSubwindow(parent)
375 {
376 }
377
378
379 private:
380 void OnPaint( wxPaintEvent& event );
381 void OnMouseEvent( wxMouseEvent& event );
382 void OnMouseWheel( wxMouseEvent& event );
383
384 DECLARE_EVENT_TABLE()
385 DECLARE_NO_COPY_CLASS(wxGridRowLabelWindow)
386 };
387
388
389 class WXDLLIMPEXP_ADV wxGridColLabelWindow : public wxGridSubwindow
390 {
391 public:
392 wxGridColLabelWindow(wxGrid *parent)
393 : wxGridSubwindow(parent)
394 {
395 }
396
397
398 private:
399 void OnPaint( wxPaintEvent& event );
400 void OnMouseEvent( wxMouseEvent& event );
401 void OnMouseWheel( wxMouseEvent& event );
402
403 DECLARE_EVENT_TABLE()
404 DECLARE_NO_COPY_CLASS(wxGridColLabelWindow)
405 };
406
407
408 class WXDLLIMPEXP_ADV wxGridCornerLabelWindow : public wxGridSubwindow
409 {
410 public:
411 wxGridCornerLabelWindow(wxGrid *parent)
412 : wxGridSubwindow(parent)
413 {
414 }
415
416 private:
417 void OnMouseEvent( wxMouseEvent& event );
418 void OnMouseWheel( wxMouseEvent& event );
419 void OnPaint( wxPaintEvent& event );
420
421 DECLARE_EVENT_TABLE()
422 DECLARE_NO_COPY_CLASS(wxGridCornerLabelWindow)
423 };
424
425 class WXDLLIMPEXP_ADV wxGridWindow : public wxGridSubwindow
426 {
427 public:
428 wxGridWindow(wxGrid *parent)
429 : wxGridSubwindow(parent,
430 wxWANTS_CHARS | wxCLIP_CHILDREN,
431 "GridWindow")
432 {
433 }
434
435
436 virtual void ScrollWindow( int dx, int dy, const wxRect *rect );
437
438 virtual bool AcceptsFocus() const { return true; }
439
440 private:
441 void OnPaint( wxPaintEvent &event );
442 void OnMouseWheel( wxMouseEvent& event );
443 void OnMouseEvent( wxMouseEvent& event );
444 void OnKeyDown( wxKeyEvent& );
445 void OnKeyUp( wxKeyEvent& );
446 void OnChar( wxKeyEvent& );
447 void OnEraseBackground( wxEraseEvent& );
448 void OnFocus( wxFocusEvent& );
449
450 DECLARE_EVENT_TABLE()
451 DECLARE_NO_COPY_CLASS(wxGridWindow)
452 };
453
454
455 class wxGridCellEditorEvtHandler : public wxEvtHandler
456 {
457 public:
458 wxGridCellEditorEvtHandler(wxGrid* grid, wxGridCellEditor* editor)
459 : m_grid(grid),
460 m_editor(editor),
461 m_inSetFocus(false)
462 {
463 }
464
465 void OnKillFocus(wxFocusEvent& event);
466 void OnKeyDown(wxKeyEvent& event);
467 void OnChar(wxKeyEvent& event);
468
469 void SetInSetFocus(bool inSetFocus) { m_inSetFocus = inSetFocus; }
470
471 private:
472 wxGrid *m_grid;
473 wxGridCellEditor *m_editor;
474
475 // Work around the fact that a focus kill event can be sent to
476 // a combobox within a set focus event.
477 bool m_inSetFocus;
478
479 DECLARE_EVENT_TABLE()
480 DECLARE_DYNAMIC_CLASS(wxGridCellEditorEvtHandler)
481 DECLARE_NO_COPY_CLASS(wxGridCellEditorEvtHandler)
482 };
483
484
485 IMPLEMENT_ABSTRACT_CLASS(wxGridCellEditorEvtHandler, wxEvtHandler)
486
487 BEGIN_EVENT_TABLE( wxGridCellEditorEvtHandler, wxEvtHandler )
488 EVT_KILL_FOCUS( wxGridCellEditorEvtHandler::OnKillFocus )
489 EVT_KEY_DOWN( wxGridCellEditorEvtHandler::OnKeyDown )
490 EVT_CHAR( wxGridCellEditorEvtHandler::OnChar )
491 END_EVENT_TABLE()
492
493
494 // ----------------------------------------------------------------------------
495 // the internal data representation used by wxGridCellAttrProvider
496 // ----------------------------------------------------------------------------
497
498 // this class stores attributes set for cells
499 class WXDLLIMPEXP_ADV wxGridCellAttrData
500 {
501 public:
502 void SetAttr(wxGridCellAttr *attr, int row, int col);
503 wxGridCellAttr *GetAttr(int row, int col) const;
504 void UpdateAttrRows( size_t pos, int numRows );
505 void UpdateAttrCols( size_t pos, int numCols );
506
507 private:
508 // searches for the attr for given cell, returns wxNOT_FOUND if not found
509 int FindIndex(int row, int col) const;
510
511 wxGridCellWithAttrArray m_attrs;
512 };
513
514 // this class stores attributes set for rows or columns
515 class WXDLLIMPEXP_ADV wxGridRowOrColAttrData
516 {
517 public:
518 // empty ctor to suppress warnings
519 wxGridRowOrColAttrData() {}
520 ~wxGridRowOrColAttrData();
521
522 void SetAttr(wxGridCellAttr *attr, int rowOrCol);
523 wxGridCellAttr *GetAttr(int rowOrCol) const;
524 void UpdateAttrRowsOrCols( size_t pos, int numRowsOrCols );
525
526 private:
527 wxArrayInt m_rowsOrCols;
528 wxArrayAttrs m_attrs;
529 };
530
531 // NB: this is just a wrapper around 3 objects: one which stores cell
532 // attributes, and 2 others for row/col ones
533 class WXDLLIMPEXP_ADV wxGridCellAttrProviderData
534 {
535 public:
536 wxGridCellAttrData m_cellAttrs;
537 wxGridRowOrColAttrData m_rowAttrs,
538 m_colAttrs;
539 };
540
541
542 // ----------------------------------------------------------------------------
543 // data structures used for the data type registry
544 // ----------------------------------------------------------------------------
545
546 struct wxGridDataTypeInfo
547 {
548 wxGridDataTypeInfo(const wxString& typeName,
549 wxGridCellRenderer* renderer,
550 wxGridCellEditor* editor)
551 : m_typeName(typeName), m_renderer(renderer), m_editor(editor)
552 {}
553
554 ~wxGridDataTypeInfo()
555 {
556 wxSafeDecRef(m_renderer);
557 wxSafeDecRef(m_editor);
558 }
559
560 wxString m_typeName;
561 wxGridCellRenderer* m_renderer;
562 wxGridCellEditor* m_editor;
563
564 DECLARE_NO_COPY_CLASS(wxGridDataTypeInfo)
565 };
566
567
568 WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridDataTypeInfo*, wxGridDataTypeInfoArray,
569 class WXDLLIMPEXP_ADV);
570
571
572 class WXDLLIMPEXP_ADV wxGridTypeRegistry
573 {
574 public:
575 wxGridTypeRegistry() {}
576 ~wxGridTypeRegistry();
577
578 void RegisterDataType(const wxString& typeName,
579 wxGridCellRenderer* renderer,
580 wxGridCellEditor* editor);
581
582 // find one of already registered data types
583 int FindRegisteredDataType(const wxString& typeName);
584
585 // try to FindRegisteredDataType(), if this fails and typeName is one of
586 // standard typenames, register it and return its index
587 int FindDataType(const wxString& typeName);
588
589 // try to FindDataType(), if it fails see if it is not one of already
590 // registered data types with some params in which case clone the
591 // registered data type and set params for it
592 int FindOrCloneDataType(const wxString& typeName);
593
594 wxGridCellRenderer* GetRenderer(int index);
595 wxGridCellEditor* GetEditor(int index);
596
597 private:
598 wxGridDataTypeInfoArray m_typeinfo;
599 };
600
601 // ----------------------------------------------------------------------------
602 // operations classes abstracting the difference between operating on rows and
603 // columns
604 // ----------------------------------------------------------------------------
605
606 // This class allows to write a function only once because by using its methods
607 // it will apply to both columns and rows.
608 //
609 // This is an abstract interface definition, the two concrete implementations
610 // below should be used when working with rows and columns respectively.
611 class wxGridOperations
612 {
613 public:
614 // Returns the operations in the other direction, i.e. wxGridRowOperations
615 // if this object is a wxGridColumnOperations and vice versa.
616 virtual wxGridOperations& Dual() const = 0;
617
618 // Return the number of rows or columns.
619 virtual int GetNumberOfLines(const wxGrid *grid) const = 0;
620
621 // Return the selection mode which allows selecting rows or columns.
622 virtual wxGrid::wxGridSelectionModes GetSelectionMode() const = 0;
623
624 // Make a wxGridCellCoords from the given components: thisDir is row or
625 // column and otherDir is column or row
626 virtual wxGridCellCoords MakeCoords(int thisDir, int otherDir) const = 0;
627
628 // Calculate the scrolled position of the given abscissa or ordinate.
629 virtual int CalcScrolledPosition(wxGrid *grid, int pos) const = 0;
630
631 // Selects the horizontal or vertical component from the given object.
632 virtual int Select(const wxGridCellCoords& coords) const = 0;
633 virtual int Select(const wxPoint& pt) const = 0;
634 virtual int Select(const wxSize& sz) const = 0;
635 virtual int Select(const wxRect& r) const = 0;
636 virtual int& Select(wxRect& r) const = 0;
637
638 // Returns width or height of the rectangle
639 virtual int& SelectSize(wxRect& r) const = 0;
640
641 // Make a wxSize such that Select() applied to it returns first component
642 virtual wxSize MakeSize(int first, int second) const = 0;
643
644 // Sets the row or column component of the given cell coordinates
645 virtual void Set(wxGridCellCoords& coords, int line) const = 0;
646
647
648 // Draws a line parallel to the row or column, i.e. horizontal or vertical:
649 // pos is the horizontal or vertical position of the line and start and end
650 // are the coordinates of the line extremities in the other direction
651 virtual void
652 DrawParallelLine(wxDC& dc, int start, int end, int pos) const = 0;
653
654 // Draw a horizontal or vertical line across the given rectangle
655 // (this is implemented in terms of above and uses Select() to extract
656 // start and end from the given rectangle)
657 void DrawParallelLineInRect(wxDC& dc, const wxRect& rect, int pos) const
658 {
659 const int posStart = Select(rect.GetPosition());
660 DrawParallelLine(dc, posStart, posStart + Select(rect.GetSize()), pos);
661 }
662
663
664 // Return the index of the row or column at the given pixel coordinate.
665 virtual int
666 PosToLine(const wxGrid *grid, int pos, bool clip = false) const = 0;
667
668 // Get the top/left position, in pixels, of the given row or column
669 virtual int GetLineStartPos(const wxGrid *grid, int line) const = 0;
670
671 // Get the bottom/right position, in pixels, of the given row or column
672 virtual int GetLineEndPos(const wxGrid *grid, int line) const = 0;
673
674 // Get the height/width of the given row/column
675 virtual int GetLineSize(const wxGrid *grid, int line) const = 0;
676
677 // Get wxGrid::m_rowBottoms/m_colRights array
678 virtual const wxArrayInt& GetLineEnds(const wxGrid *grid) const = 0;
679
680 // Get default height row height or column width
681 virtual int GetDefaultLineSize(const wxGrid *grid) const = 0;
682
683 // Return the minimal acceptable row height or column width
684 virtual int GetMinimalAcceptableLineSize(const wxGrid *grid) const = 0;
685
686 // Return the minimal row height or column width
687 virtual int GetMinimalLineSize(const wxGrid *grid, int line) const = 0;
688
689 // Set the row height or column width
690 virtual void SetLineSize(wxGrid *grid, int line, int size) const = 0;
691
692 // True if rows/columns can be resized by user
693 virtual bool CanResizeLines(const wxGrid *grid) const = 0;
694
695
696 // Return the index of the line at the given position
697 //
698 // NB: currently this is always identity for the rows as reordering is only
699 // implemented for the lines
700 virtual int GetLineAt(const wxGrid *grid, int line) const = 0;
701
702
703 // Get the row or column label window
704 virtual wxWindow *GetHeaderWindow(wxGrid *grid) const = 0;
705
706 // Get the width or height of the row or column label window
707 virtual int GetHeaderWindowSize(wxGrid *grid) const = 0;
708
709
710 // This class is never used polymorphically but give it a virtual dtor
711 // anyhow to suppress g++ complaints about it
712 virtual ~wxGridOperations() { }
713 };
714
715 class wxGridRowOperations : public wxGridOperations
716 {
717 public:
718 virtual wxGridOperations& Dual() const;
719
720 virtual int GetNumberOfLines(const wxGrid *grid) const
721 { return grid->GetNumberRows(); }
722
723 virtual wxGrid::wxGridSelectionModes GetSelectionMode() const
724 { return wxGrid::wxGridSelectRows; }
725
726 virtual wxGridCellCoords MakeCoords(int thisDir, int otherDir) const
727 { return wxGridCellCoords(thisDir, otherDir); }
728
729 virtual int CalcScrolledPosition(wxGrid *grid, int pos) const
730 { return grid->CalcScrolledPosition(wxPoint(pos, 0)).x; }
731
732 virtual int Select(const wxGridCellCoords& c) const { return c.GetRow(); }
733 virtual int Select(const wxPoint& pt) const { return pt.x; }
734 virtual int Select(const wxSize& sz) const { return sz.x; }
735 virtual int Select(const wxRect& r) const { return r.x; }
736 virtual int& Select(wxRect& r) const { return r.x; }
737 virtual int& SelectSize(wxRect& r) const { return r.width; }
738 virtual wxSize MakeSize(int first, int second) const
739 { return wxSize(first, second); }
740 virtual void Set(wxGridCellCoords& coords, int line) const
741 { coords.SetRow(line); }
742
743 virtual void DrawParallelLine(wxDC& dc, int start, int end, int pos) const
744 { dc.DrawLine(start, pos, end, pos); }
745
746 virtual int PosToLine(const wxGrid *grid, int pos, bool clip = false) const
747 { return grid->YToRow(pos, clip); }
748 virtual int GetLineStartPos(const wxGrid *grid, int line) const
749 { return grid->GetRowTop(line); }
750 virtual int GetLineEndPos(const wxGrid *grid, int line) const
751 { return grid->GetRowBottom(line); }
752 virtual int GetLineSize(const wxGrid *grid, int line) const
753 { return grid->GetRowHeight(line); }
754 virtual const wxArrayInt& GetLineEnds(const wxGrid *grid) const
755 { return grid->m_rowBottoms; }
756 virtual int GetDefaultLineSize(const wxGrid *grid) const
757 { return grid->GetDefaultRowSize(); }
758 virtual int GetMinimalAcceptableLineSize(const wxGrid *grid) const
759 { return grid->GetRowMinimalAcceptableHeight(); }
760 virtual int GetMinimalLineSize(const wxGrid *grid, int line) const
761 { return grid->GetRowMinimalHeight(line); }
762 virtual void SetLineSize(wxGrid *grid, int line, int size) const
763 { grid->SetRowSize(line, size); }
764 virtual bool CanResizeLines(const wxGrid *grid) const
765 { return grid->CanDragRowSize(); }
766
767 virtual int GetLineAt(const wxGrid * WXUNUSED(grid), int line) const
768 { return line; } // TODO: implement row reordering
769
770 virtual wxWindow *GetHeaderWindow(wxGrid *grid) const
771 { return grid->GetGridRowLabelWindow(); }
772 virtual int GetHeaderWindowSize(wxGrid *grid) const
773 { return grid->GetRowLabelSize(); }
774 };
775
776 class wxGridColumnOperations : public wxGridOperations
777 {
778 public:
779 virtual wxGridOperations& Dual() const;
780
781 virtual int GetNumberOfLines(const wxGrid *grid) const
782 { return grid->GetNumberCols(); }
783
784 virtual wxGrid::wxGridSelectionModes GetSelectionMode() const
785 { return wxGrid::wxGridSelectColumns; }
786
787 virtual wxGridCellCoords MakeCoords(int thisDir, int otherDir) const
788 { return wxGridCellCoords(otherDir, thisDir); }
789
790 virtual int CalcScrolledPosition(wxGrid *grid, int pos) const
791 { return grid->CalcScrolledPosition(wxPoint(0, pos)).y; }
792
793 virtual int Select(const wxGridCellCoords& c) const { return c.GetCol(); }
794 virtual int Select(const wxPoint& pt) const { return pt.y; }
795 virtual int Select(const wxSize& sz) const { return sz.y; }
796 virtual int Select(const wxRect& r) const { return r.y; }
797 virtual int& Select(wxRect& r) const { return r.y; }
798 virtual int& SelectSize(wxRect& r) const { return r.height; }
799 virtual wxSize MakeSize(int first, int second) const
800 { return wxSize(second, first); }
801 virtual void Set(wxGridCellCoords& coords, int line) const
802 { coords.SetCol(line); }
803
804 virtual void DrawParallelLine(wxDC& dc, int start, int end, int pos) const
805 { dc.DrawLine(pos, start, pos, end); }
806
807 virtual int PosToLine(const wxGrid *grid, int pos, bool clip = false) const
808 { return grid->XToCol(pos, clip); }
809 virtual int GetLineStartPos(const wxGrid *grid, int line) const
810 { return grid->GetColLeft(line); }
811 virtual int GetLineEndPos(const wxGrid *grid, int line) const
812 { return grid->GetColRight(line); }
813 virtual int GetLineSize(const wxGrid *grid, int line) const
814 { return grid->GetColWidth(line); }
815 virtual const wxArrayInt& GetLineEnds(const wxGrid *grid) const
816 { return grid->m_colRights; }
817 virtual int GetDefaultLineSize(const wxGrid *grid) const
818 { return grid->GetDefaultColSize(); }
819 virtual int GetMinimalAcceptableLineSize(const wxGrid *grid) const
820 { return grid->GetColMinimalAcceptableWidth(); }
821 virtual int GetMinimalLineSize(const wxGrid *grid, int line) const
822 { return grid->GetColMinimalWidth(line); }
823 virtual void SetLineSize(wxGrid *grid, int line, int size) const
824 { grid->SetColSize(line, size); }
825 virtual bool CanResizeLines(const wxGrid *grid) const
826 { return grid->CanDragColSize(); }
827
828 virtual int GetLineAt(const wxGrid *grid, int line) const
829 { return grid->GetColAt(line); }
830
831 virtual wxWindow *GetHeaderWindow(wxGrid *grid) const
832 { return grid->GetGridColLabelWindow(); }
833 virtual int GetHeaderWindowSize(wxGrid *grid) const
834 { return grid->GetColLabelSize(); }
835 };
836
837 wxGridOperations& wxGridRowOperations::Dual() const
838 {
839 static wxGridColumnOperations s_colOper;
840
841 return s_colOper;
842 }
843
844 wxGridOperations& wxGridColumnOperations::Dual() const
845 {
846 static wxGridRowOperations s_rowOper;
847
848 return s_rowOper;
849 }
850
851 // This class abstracts the difference between operations going forward
852 // (down/right) and backward (up/left) and allows to use the same code for
853 // functions which differ only in the direction of grid traversal
854 //
855 // Like wxGridOperations it's an ABC with two concrete subclasses below. Unlike
856 // it, this is a normal object and not just a function dispatch table and has a
857 // non-default ctor.
858 //
859 // Note: the explanation of this discrepancy is the existence of (very useful)
860 // Dual() method in wxGridOperations which forces us to make wxGridOperations a
861 // function dispatcher only.
862 class wxGridDirectionOperations
863 {
864 public:
865 // The oper parameter to ctor selects whether we work with rows or columns
866 wxGridDirectionOperations(wxGrid *grid, const wxGridOperations& oper)
867 : m_grid(grid),
868 m_oper(oper)
869 {
870 }
871
872 // Check if the component of this point in our direction is at the
873 // boundary, i.e. is the first/last row/column
874 virtual bool IsAtBoundary(const wxGridCellCoords& coords) const = 0;
875
876 // Increment the component of this point in our direction
877 virtual void Advance(wxGridCellCoords& coords) const = 0;
878
879 // Find the line at the given distance, in pixels, away from this one
880 // (this uses clipping, i.e. anything after the last line is counted as the
881 // last one and anything before the first one as 0)
882 virtual int MoveByPixelDistance(int line, int distance) const = 0;
883
884 // This class is never used polymorphically but give it a virtual dtor
885 // anyhow to suppress g++ complaints about it
886 virtual ~wxGridDirectionOperations() { }
887
888 protected:
889 wxGrid * const m_grid;
890 const wxGridOperations& m_oper;
891 };
892
893 class wxGridBackwardOperations : public wxGridDirectionOperations
894 {
895 public:
896 wxGridBackwardOperations(wxGrid *grid, const wxGridOperations& oper)
897 : wxGridDirectionOperations(grid, oper)
898 {
899 }
900
901 virtual bool IsAtBoundary(const wxGridCellCoords& coords) const
902 {
903 wxASSERT_MSG( m_oper.Select(coords) >= 0, "invalid row/column" );
904
905 return m_oper.Select(coords) == 0;
906 }
907
908 virtual void Advance(wxGridCellCoords& coords) const
909 {
910 wxASSERT( !IsAtBoundary(coords) );
911
912 m_oper.Set(coords, m_oper.Select(coords) - 1);
913 }
914
915 virtual int MoveByPixelDistance(int line, int distance) const
916 {
917 int pos = m_oper.GetLineStartPos(m_grid, line);
918 return m_oper.PosToLine(m_grid, pos - distance + 1, true);
919 }
920 };
921
922 class wxGridForwardOperations : public wxGridDirectionOperations
923 {
924 public:
925 wxGridForwardOperations(wxGrid *grid, const wxGridOperations& oper)
926 : wxGridDirectionOperations(grid, oper),
927 m_numLines(oper.GetNumberOfLines(grid))
928 {
929 }
930
931 virtual bool IsAtBoundary(const wxGridCellCoords& coords) const
932 {
933 wxASSERT_MSG( m_oper.Select(coords) < m_numLines, "invalid row/column" );
934
935 return m_oper.Select(coords) == m_numLines - 1;
936 }
937
938 virtual void Advance(wxGridCellCoords& coords) const
939 {
940 wxASSERT( !IsAtBoundary(coords) );
941
942 m_oper.Set(coords, m_oper.Select(coords) + 1);
943 }
944
945 virtual int MoveByPixelDistance(int line, int distance) const
946 {
947 int pos = m_oper.GetLineStartPos(m_grid, line);
948 return m_oper.PosToLine(m_grid, pos + distance, true);
949 }
950
951 private:
952 const int m_numLines;
953 };
954
955 // ----------------------------------------------------------------------------
956 // globals
957 // ----------------------------------------------------------------------------
958
959 //#define DEBUG_ATTR_CACHE
960 #ifdef DEBUG_ATTR_CACHE
961 static size_t gs_nAttrCacheHits = 0;
962 static size_t gs_nAttrCacheMisses = 0;
963 #endif
964
965 // ----------------------------------------------------------------------------
966 // constants
967 // ----------------------------------------------------------------------------
968
969 wxGridCellCoords wxGridNoCellCoords( -1, -1 );
970 wxRect wxGridNoCellRect( -1, -1, -1, -1 );
971
972 namespace
973 {
974
975 // scroll line size
976 const size_t GRID_SCROLL_LINE_X = 15;
977 const size_t GRID_SCROLL_LINE_Y = GRID_SCROLL_LINE_X;
978
979 // the size of hash tables used a bit everywhere (the max number of elements
980 // in these hash tables is the number of rows/columns)
981 const int GRID_HASH_SIZE = 100;
982
983 // the minimal distance in pixels the mouse needs to move to start a drag
984 // operation
985 const int DRAG_SENSITIVITY = 3;
986
987 } // anonymous namespace
988
989 // ----------------------------------------------------------------------------
990 // private helpers
991 // ----------------------------------------------------------------------------
992
993 namespace
994 {
995
996 // ensure that first is less or equal to second, swapping the values if
997 // necessary
998 void EnsureFirstLessThanSecond(int& first, int& second)
999 {
1000 if ( first > second )
1001 wxSwap(first, second);
1002 }
1003
1004 } // anonymous namespace
1005
1006 // ============================================================================
1007 // implementation
1008 // ============================================================================
1009
1010 // ----------------------------------------------------------------------------
1011 // wxGridCellEditor
1012 // ----------------------------------------------------------------------------
1013
1014 wxGridCellEditor::wxGridCellEditor()
1015 {
1016 m_control = NULL;
1017 m_attr = NULL;
1018 }
1019
1020 wxGridCellEditor::~wxGridCellEditor()
1021 {
1022 Destroy();
1023 }
1024
1025 void wxGridCellEditor::Create(wxWindow* WXUNUSED(parent),
1026 wxWindowID WXUNUSED(id),
1027 wxEvtHandler* evtHandler)
1028 {
1029 if ( evtHandler )
1030 m_control->PushEventHandler(evtHandler);
1031 }
1032
1033 void wxGridCellEditor::PaintBackground(const wxRect& rectCell,
1034 wxGridCellAttr *attr)
1035 {
1036 // erase the background because we might not fill the cell
1037 wxClientDC dc(m_control->GetParent());
1038 wxGridWindow* gridWindow = wxDynamicCast(m_control->GetParent(), wxGridWindow);
1039 if (gridWindow)
1040 gridWindow->GetOwner()->PrepareDC(dc);
1041
1042 dc.SetPen(*wxTRANSPARENT_PEN);
1043 dc.SetBrush(wxBrush(attr->GetBackgroundColour()));
1044 dc.DrawRectangle(rectCell);
1045
1046 // redraw the control we just painted over
1047 m_control->Refresh();
1048 }
1049
1050 void wxGridCellEditor::Destroy()
1051 {
1052 if (m_control)
1053 {
1054 m_control->PopEventHandler( true /* delete it*/ );
1055
1056 m_control->Destroy();
1057 m_control = NULL;
1058 }
1059 }
1060
1061 void wxGridCellEditor::Show(bool show, wxGridCellAttr *attr)
1062 {
1063 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
1064
1065 m_control->Show(show);
1066
1067 if ( show )
1068 {
1069 // set the colours/fonts if we have any
1070 if ( attr )
1071 {
1072 m_colFgOld = m_control->GetForegroundColour();
1073 m_control->SetForegroundColour(attr->GetTextColour());
1074
1075 m_colBgOld = m_control->GetBackgroundColour();
1076 m_control->SetBackgroundColour(attr->GetBackgroundColour());
1077
1078 // Workaround for GTK+1 font setting problem on some platforms
1079 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1080 m_fontOld = m_control->GetFont();
1081 m_control->SetFont(attr->GetFont());
1082 #endif
1083
1084 // can't do anything more in the base class version, the other
1085 // attributes may only be used by the derived classes
1086 }
1087 }
1088 else
1089 {
1090 // restore the standard colours fonts
1091 if ( m_colFgOld.Ok() )
1092 {
1093 m_control->SetForegroundColour(m_colFgOld);
1094 m_colFgOld = wxNullColour;
1095 }
1096
1097 if ( m_colBgOld.Ok() )
1098 {
1099 m_control->SetBackgroundColour(m_colBgOld);
1100 m_colBgOld = wxNullColour;
1101 }
1102
1103 // Workaround for GTK+1 font setting problem on some platforms
1104 #if !defined(__WXGTK__) || defined(__WXGTK20__)
1105 if ( m_fontOld.Ok() )
1106 {
1107 m_control->SetFont(m_fontOld);
1108 m_fontOld = wxNullFont;
1109 }
1110 #endif
1111 }
1112 }
1113
1114 void wxGridCellEditor::SetSize(const wxRect& rect)
1115 {
1116 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
1117
1118 m_control->SetSize(rect, wxSIZE_ALLOW_MINUS_ONE);
1119 }
1120
1121 void wxGridCellEditor::HandleReturn(wxKeyEvent& event)
1122 {
1123 event.Skip();
1124 }
1125
1126 bool wxGridCellEditor::IsAcceptedKey(wxKeyEvent& event)
1127 {
1128 bool ctrl = event.ControlDown();
1129 bool alt = event.AltDown();
1130
1131 #ifdef __WXMAC__
1132 // On the Mac the Alt key is more like shift and is used for entry of
1133 // valid characters, so check for Ctrl and Meta instead.
1134 alt = event.MetaDown();
1135 #endif
1136
1137 // Assume it's not a valid char if ctrl or alt is down, but if both are
1138 // down then it may be because of an AltGr key combination, so let them
1139 // through in that case.
1140 if ((ctrl || alt) && !(ctrl && alt))
1141 return false;
1142
1143 #if wxUSE_UNICODE
1144 // if the unicode key code is not really a unicode character (it may
1145 // be a function key or etc., the platforms appear to always give us a
1146 // small value in this case) then fallback to the ASCII key code but
1147 // don't do anything for function keys or etc.
1148 if ( event.GetUnicodeKey() > 127 && event.GetKeyCode() > 127 )
1149 return false;
1150 #else
1151 if ( event.GetKeyCode() > 255 )
1152 return false;
1153 #endif
1154
1155 return true;
1156 }
1157
1158 void wxGridCellEditor::StartingKey(wxKeyEvent& event)
1159 {
1160 event.Skip();
1161 }
1162
1163 void wxGridCellEditor::StartingClick()
1164 {
1165 }
1166
1167 #if wxUSE_TEXTCTRL
1168
1169 // ----------------------------------------------------------------------------
1170 // wxGridCellTextEditor
1171 // ----------------------------------------------------------------------------
1172
1173 wxGridCellTextEditor::wxGridCellTextEditor()
1174 {
1175 m_maxChars = 0;
1176 }
1177
1178 void wxGridCellTextEditor::Create(wxWindow* parent,
1179 wxWindowID id,
1180 wxEvtHandler* evtHandler)
1181 {
1182 DoCreate(parent, id, evtHandler);
1183 }
1184
1185 void wxGridCellTextEditor::DoCreate(wxWindow* parent,
1186 wxWindowID id,
1187 wxEvtHandler* evtHandler,
1188 long style)
1189 {
1190 style |= wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB | wxNO_BORDER;
1191
1192 m_control = new wxTextCtrl(parent, id, wxEmptyString,
1193 wxDefaultPosition, wxDefaultSize,
1194 style);
1195
1196 // set max length allowed in the textctrl, if the parameter was set
1197 if ( m_maxChars != 0 )
1198 {
1199 Text()->SetMaxLength(m_maxChars);
1200 }
1201
1202 wxGridCellEditor::Create(parent, id, evtHandler);
1203 }
1204
1205 void wxGridCellTextEditor::PaintBackground(const wxRect& WXUNUSED(rectCell),
1206 wxGridCellAttr * WXUNUSED(attr))
1207 {
1208 // as we fill the entire client area,
1209 // don't do anything here to minimize flicker
1210 }
1211
1212 void wxGridCellTextEditor::SetSize(const wxRect& rectOrig)
1213 {
1214 wxRect rect(rectOrig);
1215
1216 // Make the edit control large enough to allow for internal margins
1217 //
1218 // TODO: remove this if the text ctrl sizing is improved esp. for unix
1219 //
1220 #if defined(__WXGTK__)
1221 if (rect.x != 0)
1222 {
1223 rect.x += 1;
1224 rect.y += 1;
1225 rect.width -= 1;
1226 rect.height -= 1;
1227 }
1228 #elif defined(__WXMSW__)
1229 if ( rect.x == 0 )
1230 rect.x += 2;
1231 else
1232 rect.x += 3;
1233
1234 if ( rect.y == 0 )
1235 rect.y += 2;
1236 else
1237 rect.y += 3;
1238
1239 rect.width -= 2;
1240 rect.height -= 2;
1241 #else
1242 int extra_x = ( rect.x > 2 ) ? 2 : 1;
1243 int extra_y = ( rect.y > 2 ) ? 2 : 1;
1244
1245 #if defined(__WXMOTIF__)
1246 extra_x *= 2;
1247 extra_y *= 2;
1248 #endif
1249
1250 rect.SetLeft( wxMax(0, rect.x - extra_x) );
1251 rect.SetTop( wxMax(0, rect.y - extra_y) );
1252 rect.SetRight( rect.GetRight() + 2 * extra_x );
1253 rect.SetBottom( rect.GetBottom() + 2 * extra_y );
1254 #endif
1255
1256 wxGridCellEditor::SetSize(rect);
1257 }
1258
1259 void wxGridCellTextEditor::BeginEdit(int row, int col, wxGrid* grid)
1260 {
1261 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
1262
1263 m_value = grid->GetTable()->GetValue(row, col);
1264
1265 DoBeginEdit(m_value);
1266 }
1267
1268 void wxGridCellTextEditor::DoBeginEdit(const wxString& startValue)
1269 {
1270 Text()->SetValue(startValue);
1271 Text()->SetInsertionPointEnd();
1272 Text()->SetSelection(-1, -1);
1273 Text()->SetFocus();
1274 }
1275
1276 bool wxGridCellTextEditor::EndEdit(const wxString& WXUNUSED(oldval),
1277 wxString *newval)
1278 {
1279 wxCHECK_MSG( m_control, false,
1280 "wxGridCellTextEditor must be created first!" );
1281
1282 const wxString value = Text()->GetValue();
1283 if ( value == m_value )
1284 return false;
1285
1286 m_value = value;
1287
1288 if ( newval )
1289 *newval = m_value;
1290
1291 return true;
1292 }
1293
1294 void wxGridCellTextEditor::ApplyEdit(int row, int col, wxGrid* grid)
1295 {
1296 grid->GetTable()->SetValue(row, col, m_value);
1297 m_value.clear();
1298 }
1299
1300 void wxGridCellTextEditor::Reset()
1301 {
1302 wxASSERT_MSG( m_control, "wxGridCellTextEditor must be created first!" );
1303
1304 DoReset(m_value);
1305 }
1306
1307 void wxGridCellTextEditor::DoReset(const wxString& startValue)
1308 {
1309 Text()->SetValue(startValue);
1310 Text()->SetInsertionPointEnd();
1311 }
1312
1313 bool wxGridCellTextEditor::IsAcceptedKey(wxKeyEvent& event)
1314 {
1315 return wxGridCellEditor::IsAcceptedKey(event);
1316 }
1317
1318 void wxGridCellTextEditor::StartingKey(wxKeyEvent& event)
1319 {
1320 // Since this is now happening in the EVT_CHAR event EmulateKeyPress is no
1321 // longer an appropriate way to get the character into the text control.
1322 // Do it ourselves instead. We know that if we get this far that we have
1323 // a valid character, so not a whole lot of testing needs to be done.
1324
1325 wxTextCtrl* tc = Text();
1326 wxChar ch;
1327 long pos;
1328
1329 #if wxUSE_UNICODE
1330 ch = event.GetUnicodeKey();
1331 if (ch <= 127)
1332 ch = (wxChar)event.GetKeyCode();
1333 #else
1334 ch = (wxChar)event.GetKeyCode();
1335 #endif
1336
1337 switch (ch)
1338 {
1339 case WXK_DELETE:
1340 // delete the character at the cursor
1341 pos = tc->GetInsertionPoint();
1342 if (pos < tc->GetLastPosition())
1343 tc->Remove(pos, pos + 1);
1344 break;
1345
1346 case WXK_BACK:
1347 // delete the character before the cursor
1348 pos = tc->GetInsertionPoint();
1349 if (pos > 0)
1350 tc->Remove(pos - 1, pos);
1351 break;
1352
1353 default:
1354 tc->WriteText(ch);
1355 break;
1356 }
1357 }
1358
1359 void wxGridCellTextEditor::HandleReturn( wxKeyEvent&
1360 WXUNUSED_GTK(WXUNUSED_MOTIF(event)) )
1361 {
1362 #if defined(__WXMOTIF__) || defined(__WXGTK__)
1363 // wxMotif needs a little extra help...
1364 size_t pos = (size_t)( Text()->GetInsertionPoint() );
1365 wxString s( Text()->GetValue() );
1366 s = s.Left(pos) + wxT("\n") + s.Mid(pos);
1367 Text()->SetValue(s);
1368 Text()->SetInsertionPoint( pos );
1369 #else
1370 // the other ports can handle a Return key press
1371 //
1372 event.Skip();
1373 #endif
1374 }
1375
1376 void wxGridCellTextEditor::SetParameters(const wxString& params)
1377 {
1378 if ( !params )
1379 {
1380 // reset to default
1381 m_maxChars = 0;
1382 }
1383 else
1384 {
1385 long tmp;
1386 if ( params.ToLong(&tmp) )
1387 {
1388 m_maxChars = (size_t)tmp;
1389 }
1390 else
1391 {
1392 wxLogDebug( _T("Invalid wxGridCellTextEditor parameter string '%s' ignored"), params.c_str() );
1393 }
1394 }
1395 }
1396
1397 // return the value in the text control
1398 wxString wxGridCellTextEditor::GetValue() const
1399 {
1400 return Text()->GetValue();
1401 }
1402
1403 // ----------------------------------------------------------------------------
1404 // wxGridCellNumberEditor
1405 // ----------------------------------------------------------------------------
1406
1407 wxGridCellNumberEditor::wxGridCellNumberEditor(int min, int max)
1408 {
1409 m_min = min;
1410 m_max = max;
1411 }
1412
1413 void wxGridCellNumberEditor::Create(wxWindow* parent,
1414 wxWindowID id,
1415 wxEvtHandler* evtHandler)
1416 {
1417 #if wxUSE_SPINCTRL
1418 if ( HasRange() )
1419 {
1420 // create a spin ctrl
1421 m_control = new wxSpinCtrl(parent, wxID_ANY, wxEmptyString,
1422 wxDefaultPosition, wxDefaultSize,
1423 wxSP_ARROW_KEYS,
1424 m_min, m_max);
1425
1426 wxGridCellEditor::Create(parent, id, evtHandler);
1427 }
1428 else
1429 #endif
1430 {
1431 // just a text control
1432 wxGridCellTextEditor::Create(parent, id, evtHandler);
1433
1434 #if wxUSE_VALIDATORS
1435 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
1436 #endif
1437 }
1438 }
1439
1440 void wxGridCellNumberEditor::BeginEdit(int row, int col, wxGrid* grid)
1441 {
1442 // first get the value
1443 wxGridTableBase *table = grid->GetTable();
1444 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
1445 {
1446 m_value = table->GetValueAsLong(row, col);
1447 }
1448 else
1449 {
1450 m_value = 0;
1451 wxString sValue = table->GetValue(row, col);
1452 if (! sValue.ToLong(&m_value) && ! sValue.empty())
1453 {
1454 wxFAIL_MSG( _T("this cell doesn't have numeric value") );
1455 return;
1456 }
1457 }
1458
1459 #if wxUSE_SPINCTRL
1460 if ( HasRange() )
1461 {
1462 Spin()->SetValue((int)m_value);
1463 Spin()->SetFocus();
1464 }
1465 else
1466 #endif
1467 {
1468 DoBeginEdit(GetString());
1469 }
1470 }
1471
1472 bool wxGridCellNumberEditor::EndEdit(const wxString& oldval, wxString *newval)
1473 {
1474 long value = 0;
1475 wxString text;
1476
1477 #if wxUSE_SPINCTRL
1478 if ( HasRange() )
1479 {
1480 value = Spin()->GetValue();
1481 if ( value == m_value )
1482 return false;
1483
1484 text.Printf(wxT("%ld"), value);
1485 }
1486 else // using unconstrained input
1487 #endif // wxUSE_SPINCTRL
1488 {
1489 text = Text()->GetValue();
1490 if ( text.empty() )
1491 {
1492 if ( oldval.empty() )
1493 return false;
1494 }
1495 else // non-empty text now (maybe 0)
1496 {
1497 if ( !text.ToLong(&value) )
1498 return false;
1499
1500 // if value == m_value == 0 but old text was "" and new one is
1501 // "0" something still did change
1502 if ( value == m_value && (value || !oldval.empty()) )
1503 return false;
1504 }
1505 }
1506
1507 m_value = value;
1508
1509 if ( newval )
1510 *newval = text;
1511
1512 return true;
1513 }
1514
1515 void wxGridCellNumberEditor::ApplyEdit(int row, int col, wxGrid* grid)
1516 {
1517 wxGridTableBase * const table = grid->GetTable();
1518 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_NUMBER) )
1519 table->SetValueAsLong(row, col, m_value);
1520 else
1521 table->SetValue(row, col, wxString::Format("%ld", m_value));
1522 }
1523
1524 void wxGridCellNumberEditor::Reset()
1525 {
1526 #if wxUSE_SPINCTRL
1527 if ( HasRange() )
1528 {
1529 Spin()->SetValue((int)m_value);
1530 }
1531 else
1532 #endif
1533 {
1534 DoReset(GetString());
1535 }
1536 }
1537
1538 bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent& event)
1539 {
1540 if ( wxGridCellEditor::IsAcceptedKey(event) )
1541 {
1542 int keycode = event.GetKeyCode();
1543 if ( (keycode < 128) &&
1544 (wxIsdigit(keycode) || keycode == '+' || keycode == '-'))
1545 {
1546 return true;
1547 }
1548 }
1549
1550 return false;
1551 }
1552
1553 void wxGridCellNumberEditor::StartingKey(wxKeyEvent& event)
1554 {
1555 int keycode = event.GetKeyCode();
1556 if ( !HasRange() )
1557 {
1558 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-')
1559 {
1560 wxGridCellTextEditor::StartingKey(event);
1561
1562 // skip Skip() below
1563 return;
1564 }
1565 }
1566 #if wxUSE_SPINCTRL
1567 else
1568 {
1569 if ( wxIsdigit(keycode) )
1570 {
1571 wxSpinCtrl* spin = (wxSpinCtrl*)m_control;
1572 spin->SetValue(keycode - '0');
1573 spin->SetSelection(1,1);
1574 return;
1575 }
1576 }
1577 #endif
1578
1579 event.Skip();
1580 }
1581
1582 void wxGridCellNumberEditor::SetParameters(const wxString& params)
1583 {
1584 if ( !params )
1585 {
1586 // reset to default
1587 m_min =
1588 m_max = -1;
1589 }
1590 else
1591 {
1592 long tmp;
1593 if ( params.BeforeFirst(_T(',')).ToLong(&tmp) )
1594 {
1595 m_min = (int)tmp;
1596
1597 if ( params.AfterFirst(_T(',')).ToLong(&tmp) )
1598 {
1599 m_max = (int)tmp;
1600
1601 // skip the error message below
1602 return;
1603 }
1604 }
1605
1606 wxLogDebug(_T("Invalid wxGridCellNumberEditor parameter string '%s' ignored"), params.c_str());
1607 }
1608 }
1609
1610 // return the value in the spin control if it is there (the text control otherwise)
1611 wxString wxGridCellNumberEditor::GetValue() const
1612 {
1613 wxString s;
1614
1615 #if wxUSE_SPINCTRL
1616 if ( HasRange() )
1617 {
1618 long value = Spin()->GetValue();
1619 s.Printf(wxT("%ld"), value);
1620 }
1621 else
1622 #endif
1623 {
1624 s = Text()->GetValue();
1625 }
1626
1627 return s;
1628 }
1629
1630 // ----------------------------------------------------------------------------
1631 // wxGridCellFloatEditor
1632 // ----------------------------------------------------------------------------
1633
1634 wxGridCellFloatEditor::wxGridCellFloatEditor(int width, int precision)
1635 {
1636 m_width = width;
1637 m_precision = precision;
1638 }
1639
1640 void wxGridCellFloatEditor::Create(wxWindow* parent,
1641 wxWindowID id,
1642 wxEvtHandler* evtHandler)
1643 {
1644 wxGridCellTextEditor::Create(parent, id, evtHandler);
1645
1646 #if wxUSE_VALIDATORS
1647 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
1648 #endif
1649 }
1650
1651 void wxGridCellFloatEditor::BeginEdit(int row, int col, wxGrid* grid)
1652 {
1653 // first get the value
1654 wxGridTableBase * const table = grid->GetTable();
1655 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_FLOAT) )
1656 {
1657 m_value = table->GetValueAsDouble(row, col);
1658 }
1659 else
1660 {
1661 m_value = 0.0;
1662
1663 const wxString value = table->GetValue(row, col);
1664 if ( !value.empty() )
1665 {
1666 if ( !value.ToDouble(&m_value) )
1667 {
1668 wxFAIL_MSG( _T("this cell doesn't have float value") );
1669 return;
1670 }
1671 }
1672 }
1673
1674 DoBeginEdit(GetString());
1675 }
1676
1677 bool wxGridCellFloatEditor::EndEdit(const wxString& oldval, wxString *newval)
1678 {
1679 const wxString text(Text()->GetValue());
1680
1681 double value;
1682 if ( !text.empty() )
1683 {
1684 if ( !text.ToDouble(&value) )
1685 return false;
1686 }
1687 else // new value is empty string
1688 {
1689 if ( oldval.empty() )
1690 return false; // nothing changed
1691
1692 value = 0.;
1693 }
1694
1695 // the test for empty strings ensures that we don't skip the value setting
1696 // when "" is replaced by "0" or vice versa as "" numeric value is also 0.
1697 if ( wxIsSameDouble(value, m_value) && !text.empty() && !oldval.empty() )
1698 return false; // nothing changed
1699
1700 m_value = value;
1701
1702 if ( newval )
1703 *newval = text;
1704
1705 return true;
1706 }
1707
1708 void wxGridCellFloatEditor::ApplyEdit(int row, int col, wxGrid* grid)
1709 {
1710 wxGridTableBase * const table = grid->GetTable();
1711
1712 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_FLOAT) )
1713 table->SetValueAsDouble(row, col, m_value);
1714 else
1715 table->SetValue(row, col, Text()->GetValue());
1716 }
1717
1718 void wxGridCellFloatEditor::Reset()
1719 {
1720 DoReset(GetString());
1721 }
1722
1723 void wxGridCellFloatEditor::StartingKey(wxKeyEvent& event)
1724 {
1725 int keycode = event.GetKeyCode();
1726 char tmpbuf[2];
1727 tmpbuf[0] = (char) keycode;
1728 tmpbuf[1] = '\0';
1729 wxString strbuf(tmpbuf, *wxConvCurrent);
1730
1731 #if wxUSE_INTL
1732 bool is_decimal_point = ( strbuf ==
1733 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER) );
1734 #else
1735 bool is_decimal_point = ( strbuf == _T(".") );
1736 #endif
1737
1738 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-'
1739 || is_decimal_point )
1740 {
1741 wxGridCellTextEditor::StartingKey(event);
1742
1743 // skip Skip() below
1744 return;
1745 }
1746
1747 event.Skip();
1748 }
1749
1750 void wxGridCellFloatEditor::SetParameters(const wxString& params)
1751 {
1752 if ( !params )
1753 {
1754 // reset to default
1755 m_width =
1756 m_precision = -1;
1757 }
1758 else
1759 {
1760 long tmp;
1761 if ( params.BeforeFirst(_T(',')).ToLong(&tmp) )
1762 {
1763 m_width = (int)tmp;
1764
1765 if ( params.AfterFirst(_T(',')).ToLong(&tmp) )
1766 {
1767 m_precision = (int)tmp;
1768
1769 // skip the error message below
1770 return;
1771 }
1772 }
1773
1774 wxLogDebug(_T("Invalid wxGridCellFloatEditor parameter string '%s' ignored"), params.c_str());
1775 }
1776 }
1777
1778 wxString wxGridCellFloatEditor::GetString() const
1779 {
1780 wxString fmt;
1781 if ( m_precision == -1 && m_width != -1)
1782 {
1783 // default precision
1784 fmt.Printf(_T("%%%d.f"), m_width);
1785 }
1786 else if ( m_precision != -1 && m_width == -1)
1787 {
1788 // default width
1789 fmt.Printf(_T("%%.%df"), m_precision);
1790 }
1791 else if ( m_precision != -1 && m_width != -1 )
1792 {
1793 fmt.Printf(_T("%%%d.%df"), m_width, m_precision);
1794 }
1795 else
1796 {
1797 // default width/precision
1798 fmt = _T("%f");
1799 }
1800
1801 return wxString::Format(fmt, m_value);
1802 }
1803
1804 bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent& event)
1805 {
1806 if ( wxGridCellEditor::IsAcceptedKey(event) )
1807 {
1808 const int keycode = event.GetKeyCode();
1809 if ( isascii(keycode) )
1810 {
1811 char tmpbuf[2];
1812 tmpbuf[0] = (char) keycode;
1813 tmpbuf[1] = '\0';
1814 wxString strbuf(tmpbuf, *wxConvCurrent);
1815
1816 #if wxUSE_INTL
1817 const wxString decimalPoint =
1818 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER);
1819 #else
1820 const wxString decimalPoint(_T('.'));
1821 #endif
1822
1823 // accept digits, 'e' as in '1e+6', also '-', '+', and '.'
1824 if ( wxIsdigit(keycode) ||
1825 tolower(keycode) == 'e' ||
1826 keycode == decimalPoint ||
1827 keycode == '+' ||
1828 keycode == '-' )
1829 {
1830 return true;
1831 }
1832 }
1833 }
1834
1835 return false;
1836 }
1837
1838 #endif // wxUSE_TEXTCTRL
1839
1840 #if wxUSE_CHECKBOX
1841
1842 // ----------------------------------------------------------------------------
1843 // wxGridCellBoolEditor
1844 // ----------------------------------------------------------------------------
1845
1846 // the default values for GetValue()
1847 wxString wxGridCellBoolEditor::ms_stringValues[2] = { _T(""), _T("1") };
1848
1849 void wxGridCellBoolEditor::Create(wxWindow* parent,
1850 wxWindowID id,
1851 wxEvtHandler* evtHandler)
1852 {
1853 m_control = new wxCheckBox(parent, id, wxEmptyString,
1854 wxDefaultPosition, wxDefaultSize,
1855 wxNO_BORDER);
1856
1857 wxGridCellEditor::Create(parent, id, evtHandler);
1858 }
1859
1860 void wxGridCellBoolEditor::SetSize(const wxRect& r)
1861 {
1862 bool resize = false;
1863 wxSize size = m_control->GetSize();
1864 wxCoord minSize = wxMin(r.width, r.height);
1865
1866 // check if the checkbox is not too big/small for this cell
1867 wxSize sizeBest = m_control->GetBestSize();
1868 if ( !(size == sizeBest) )
1869 {
1870 // reset to default size if it had been made smaller
1871 size = sizeBest;
1872
1873 resize = true;
1874 }
1875
1876 if ( size.x >= minSize || size.y >= minSize )
1877 {
1878 // leave 1 pixel margin
1879 size.x = size.y = minSize - 2;
1880
1881 resize = true;
1882 }
1883
1884 if ( resize )
1885 {
1886 m_control->SetSize(size);
1887 }
1888
1889 // position it in the centre of the rectangle (TODO: support alignment?)
1890
1891 #if defined(__WXGTK__) || defined (__WXMOTIF__)
1892 // the checkbox without label still has some space to the right in wxGTK,
1893 // so shift it to the right
1894 size.x -= 8;
1895 #elif defined(__WXMSW__)
1896 // here too, but in other way
1897 size.x += 1;
1898 size.y -= 2;
1899 #endif
1900
1901 int hAlign = wxALIGN_CENTRE;
1902 int vAlign = wxALIGN_CENTRE;
1903 if (GetCellAttr())
1904 GetCellAttr()->GetAlignment(& hAlign, & vAlign);
1905
1906 int x = 0, y = 0;
1907 if (hAlign == wxALIGN_LEFT)
1908 {
1909 x = r.x + 2;
1910
1911 #ifdef __WXMSW__
1912 x += 2;
1913 #endif
1914
1915 y = r.y + r.height / 2 - size.y / 2;
1916 }
1917 else if (hAlign == wxALIGN_RIGHT)
1918 {
1919 x = r.x + r.width - size.x - 2;
1920 y = r.y + r.height / 2 - size.y / 2;
1921 }
1922 else if (hAlign == wxALIGN_CENTRE)
1923 {
1924 x = r.x + r.width / 2 - size.x / 2;
1925 y = r.y + r.height / 2 - size.y / 2;
1926 }
1927
1928 m_control->Move(x, y);
1929 }
1930
1931 void wxGridCellBoolEditor::Show(bool show, wxGridCellAttr *attr)
1932 {
1933 m_control->Show(show);
1934
1935 if ( show )
1936 {
1937 wxColour colBg = attr ? attr->GetBackgroundColour() : *wxLIGHT_GREY;
1938 CBox()->SetBackgroundColour(colBg);
1939 }
1940 }
1941
1942 void wxGridCellBoolEditor::BeginEdit(int row, int col, wxGrid* grid)
1943 {
1944 wxASSERT_MSG(m_control,
1945 wxT("The wxGridCellEditor must be created first!"));
1946
1947 if (grid->GetTable()->CanGetValueAs(row, col, wxGRID_VALUE_BOOL))
1948 {
1949 m_value = grid->GetTable()->GetValueAsBool(row, col);
1950 }
1951 else
1952 {
1953 wxString cellval( grid->GetTable()->GetValue(row, col) );
1954
1955 if ( cellval == ms_stringValues[false] )
1956 m_value = false;
1957 else if ( cellval == ms_stringValues[true] )
1958 m_value = true;
1959 else
1960 {
1961 // do not try to be smart here and convert it to true or false
1962 // because we'll still overwrite it with something different and
1963 // this risks to be very surprising for the user code, let them
1964 // know about it
1965 wxFAIL_MSG( _T("invalid value for a cell with bool editor!") );
1966 }
1967 }
1968
1969 CBox()->SetValue(m_value);
1970 CBox()->SetFocus();
1971 }
1972
1973 bool wxGridCellBoolEditor::EndEdit(const wxString& WXUNUSED(oldval),
1974 wxString *newval)
1975 {
1976 bool value = CBox()->GetValue();
1977 if ( value == m_value )
1978 return false;
1979
1980 m_value = value;
1981
1982 if ( newval )
1983 *newval = GetValue();
1984
1985 return true;
1986 }
1987
1988 void wxGridCellBoolEditor::ApplyEdit(int row, int col, wxGrid* grid)
1989 {
1990 wxGridTableBase * const table = grid->GetTable();
1991 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_BOOL) )
1992 table->SetValueAsBool(row, col, m_value);
1993 else
1994 table->SetValue(row, col, GetValue());
1995 }
1996
1997 void wxGridCellBoolEditor::Reset()
1998 {
1999 wxASSERT_MSG(m_control,
2000 wxT("The wxGridCellEditor must be created first!"));
2001
2002 CBox()->SetValue(m_value);
2003 }
2004
2005 void wxGridCellBoolEditor::StartingClick()
2006 {
2007 CBox()->SetValue(!CBox()->GetValue());
2008 }
2009
2010 bool wxGridCellBoolEditor::IsAcceptedKey(wxKeyEvent& event)
2011 {
2012 if ( wxGridCellEditor::IsAcceptedKey(event) )
2013 {
2014 int keycode = event.GetKeyCode();
2015 switch ( keycode )
2016 {
2017 case WXK_SPACE:
2018 case '+':
2019 case '-':
2020 return true;
2021 }
2022 }
2023
2024 return false;
2025 }
2026
2027 void wxGridCellBoolEditor::StartingKey(wxKeyEvent& event)
2028 {
2029 int keycode = event.GetKeyCode();
2030 switch ( keycode )
2031 {
2032 case WXK_SPACE:
2033 CBox()->SetValue(!CBox()->GetValue());
2034 break;
2035
2036 case '+':
2037 CBox()->SetValue(true);
2038 break;
2039
2040 case '-':
2041 CBox()->SetValue(false);
2042 break;
2043 }
2044 }
2045
2046 wxString wxGridCellBoolEditor::GetValue() const
2047 {
2048 return ms_stringValues[CBox()->GetValue()];
2049 }
2050
2051 /* static */ void
2052 wxGridCellBoolEditor::UseStringValues(const wxString& valueTrue,
2053 const wxString& valueFalse)
2054 {
2055 ms_stringValues[false] = valueFalse;
2056 ms_stringValues[true] = valueTrue;
2057 }
2058
2059 /* static */ bool
2060 wxGridCellBoolEditor::IsTrueValue(const wxString& value)
2061 {
2062 return value == ms_stringValues[true];
2063 }
2064
2065 #endif // wxUSE_CHECKBOX
2066
2067 #if wxUSE_COMBOBOX
2068
2069 // ----------------------------------------------------------------------------
2070 // wxGridCellChoiceEditor
2071 // ----------------------------------------------------------------------------
2072
2073 wxGridCellChoiceEditor::wxGridCellChoiceEditor(const wxArrayString& choices,
2074 bool allowOthers)
2075 : m_choices(choices),
2076 m_allowOthers(allowOthers) { }
2077
2078 wxGridCellChoiceEditor::wxGridCellChoiceEditor(size_t count,
2079 const wxString choices[],
2080 bool allowOthers)
2081 : m_allowOthers(allowOthers)
2082 {
2083 if ( count )
2084 {
2085 m_choices.Alloc(count);
2086 for ( size_t n = 0; n < count; n++ )
2087 {
2088 m_choices.Add(choices[n]);
2089 }
2090 }
2091 }
2092
2093 wxGridCellEditor *wxGridCellChoiceEditor::Clone() const
2094 {
2095 wxGridCellChoiceEditor *editor = new wxGridCellChoiceEditor;
2096 editor->m_allowOthers = m_allowOthers;
2097 editor->m_choices = m_choices;
2098
2099 return editor;
2100 }
2101
2102 void wxGridCellChoiceEditor::Create(wxWindow* parent,
2103 wxWindowID id,
2104 wxEvtHandler* evtHandler)
2105 {
2106 int style = wxTE_PROCESS_ENTER |
2107 wxTE_PROCESS_TAB |
2108 wxBORDER_NONE;
2109
2110 if ( !m_allowOthers )
2111 style |= wxCB_READONLY;
2112 m_control = new wxComboBox(parent, id, wxEmptyString,
2113 wxDefaultPosition, wxDefaultSize,
2114 m_choices,
2115 style);
2116
2117 wxGridCellEditor::Create(parent, id, evtHandler);
2118 }
2119
2120 void wxGridCellChoiceEditor::PaintBackground(const wxRect& rectCell,
2121 wxGridCellAttr * attr)
2122 {
2123 // as we fill the entire client area, don't do anything here to minimize
2124 // flicker
2125
2126 // TODO: It doesn't actually fill the client area since the height of a
2127 // combo always defaults to the standard. Until someone has time to
2128 // figure out the right rectangle to paint, just do it the normal way.
2129 wxGridCellEditor::PaintBackground(rectCell, attr);
2130 }
2131
2132 void wxGridCellChoiceEditor::BeginEdit(int row, int col, wxGrid* grid)
2133 {
2134 wxASSERT_MSG(m_control,
2135 wxT("The wxGridCellEditor must be created first!"));
2136
2137 wxGridCellEditorEvtHandler* evtHandler = NULL;
2138 if (m_control)
2139 evtHandler = wxDynamicCast(m_control->GetEventHandler(), wxGridCellEditorEvtHandler);
2140
2141 // Don't immediately end if we get a kill focus event within BeginEdit
2142 if (evtHandler)
2143 evtHandler->SetInSetFocus(true);
2144
2145 m_value = grid->GetTable()->GetValue(row, col);
2146
2147 Reset(); // this updates combo box to correspond to m_value
2148
2149 Combo()->SetFocus();
2150
2151 if (evtHandler)
2152 {
2153 // When dropping down the menu, a kill focus event
2154 // happens after this point, so we can't reset the flag yet.
2155 #if !defined(__WXGTK20__)
2156 evtHandler->SetInSetFocus(false);
2157 #endif
2158 }
2159 }
2160
2161 bool wxGridCellChoiceEditor::EndEdit(const wxString& WXUNUSED(oldval),
2162 wxString *newval)
2163 {
2164 const wxString value = Combo()->GetValue();
2165 if ( value == m_value )
2166 return false;
2167
2168 m_value = value;
2169
2170 if ( newval )
2171 *newval = value;
2172
2173 return true;
2174 }
2175
2176 void wxGridCellChoiceEditor::ApplyEdit(int row, int col, wxGrid* grid)
2177 {
2178 grid->GetTable()->SetValue(row, col, m_value);
2179 }
2180
2181 void wxGridCellChoiceEditor::Reset()
2182 {
2183 if (m_allowOthers)
2184 {
2185 Combo()->SetValue(m_value);
2186 Combo()->SetInsertionPointEnd();
2187 }
2188 else // the combobox is read-only
2189 {
2190 // find the right position, or default to the first if not found
2191 int pos = Combo()->FindString(m_value);
2192 if (pos == wxNOT_FOUND)
2193 pos = 0;
2194 Combo()->SetSelection(pos);
2195 }
2196 }
2197
2198 void wxGridCellChoiceEditor::SetParameters(const wxString& params)
2199 {
2200 if ( !params )
2201 {
2202 // what can we do?
2203 return;
2204 }
2205
2206 m_choices.Empty();
2207
2208 wxStringTokenizer tk(params, _T(','));
2209 while ( tk.HasMoreTokens() )
2210 {
2211 m_choices.Add(tk.GetNextToken());
2212 }
2213 }
2214
2215 // return the value in the text control
2216 wxString wxGridCellChoiceEditor::GetValue() const
2217 {
2218 return Combo()->GetValue();
2219 }
2220
2221 #endif // wxUSE_COMBOBOX
2222
2223 // ----------------------------------------------------------------------------
2224 // wxGridCellEditorEvtHandler
2225 // ----------------------------------------------------------------------------
2226
2227 void wxGridCellEditorEvtHandler::OnKillFocus(wxFocusEvent& event)
2228 {
2229 // Don't disable the cell if we're just starting to edit it
2230 if (m_inSetFocus)
2231 return;
2232
2233 // accept changes
2234 m_grid->DisableCellEditControl();
2235
2236 event.Skip();
2237 }
2238
2239 void wxGridCellEditorEvtHandler::OnKeyDown(wxKeyEvent& event)
2240 {
2241 switch ( event.GetKeyCode() )
2242 {
2243 case WXK_ESCAPE:
2244 m_editor->Reset();
2245 m_grid->DisableCellEditControl();
2246 break;
2247
2248 case WXK_TAB:
2249 m_grid->GetEventHandler()->ProcessEvent( event );
2250 break;
2251
2252 case WXK_RETURN:
2253 case WXK_NUMPAD_ENTER:
2254 if (!m_grid->GetEventHandler()->ProcessEvent(event))
2255 m_editor->HandleReturn(event);
2256 break;
2257
2258 default:
2259 event.Skip();
2260 break;
2261 }
2262 }
2263
2264 void wxGridCellEditorEvtHandler::OnChar(wxKeyEvent& event)
2265 {
2266 int row = m_grid->GetGridCursorRow();
2267 int col = m_grid->GetGridCursorCol();
2268 wxRect rect = m_grid->CellToRect( row, col );
2269 int cw, ch;
2270 m_grid->GetGridWindow()->GetClientSize( &cw, &ch );
2271
2272 // if cell width is smaller than grid client area, cell is wholly visible
2273 bool wholeCellVisible = (rect.GetWidth() < cw);
2274
2275 switch ( event.GetKeyCode() )
2276 {
2277 case WXK_ESCAPE:
2278 case WXK_TAB:
2279 case WXK_RETURN:
2280 case WXK_NUMPAD_ENTER:
2281 break;
2282
2283 case WXK_HOME:
2284 {
2285 if ( wholeCellVisible )
2286 {
2287 // no special processing needed...
2288 event.Skip();
2289 break;
2290 }
2291
2292 // do special processing for partly visible cell...
2293
2294 // get the widths of all cells previous to this one
2295 int colXPos = 0;
2296 for ( int i = 0; i < col; i++ )
2297 {
2298 colXPos += m_grid->GetColSize(i);
2299 }
2300
2301 int xUnit = 1, yUnit = 1;
2302 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
2303 if (col != 0)
2304 {
2305 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
2306 }
2307 else
2308 {
2309 m_grid->Scroll(colXPos / xUnit, m_grid->GetScrollPos(wxVERTICAL));
2310 }
2311 event.Skip();
2312 break;
2313 }
2314
2315 case WXK_END:
2316 {
2317 if ( wholeCellVisible )
2318 {
2319 // no special processing needed...
2320 event.Skip();
2321 break;
2322 }
2323
2324 // do special processing for partly visible cell...
2325
2326 int textWidth = 0;
2327 wxString value = m_grid->GetCellValue(row, col);
2328 if ( wxEmptyString != value )
2329 {
2330 // get width of cell CONTENTS (text)
2331 int y;
2332 wxFont font = m_grid->GetCellFont(row, col);
2333 m_grid->GetTextExtent(value, &textWidth, &y, NULL, NULL, &font);
2334
2335 // try to RIGHT align the text by scrolling
2336 int client_right = m_grid->GetGridWindow()->GetClientSize().GetWidth();
2337
2338 // (m_grid->GetScrollLineX()*2) is a factor for not scrolling to far,
2339 // otherwise the last part of the cell content might be hidden below the scroll bar
2340 // FIXME: maybe there is a more suitable correction?
2341 textWidth -= (client_right - (m_grid->GetScrollLineX() * 2));
2342 if ( textWidth < 0 )
2343 {
2344 textWidth = 0;
2345 }
2346 }
2347
2348 // get the widths of all cells previous to this one
2349 int colXPos = 0;
2350 for ( int i = 0; i < col; i++ )
2351 {
2352 colXPos += m_grid->GetColSize(i);
2353 }
2354
2355 // and add the (modified) text width of the cell contents
2356 // as we'd like to see the last part of the cell contents
2357 colXPos += textWidth;
2358
2359 int xUnit = 1, yUnit = 1;
2360 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
2361 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
2362 event.Skip();
2363 break;
2364 }
2365
2366 default:
2367 event.Skip();
2368 break;
2369 }
2370 }
2371
2372 // ----------------------------------------------------------------------------
2373 // wxGridCellWorker is an (almost) empty common base class for
2374 // wxGridCellRenderer and wxGridCellEditor managing ref counting
2375 // ----------------------------------------------------------------------------
2376
2377 void wxGridCellWorker::SetParameters(const wxString& WXUNUSED(params))
2378 {
2379 // nothing to do
2380 }
2381
2382 wxGridCellWorker::~wxGridCellWorker()
2383 {
2384 }
2385
2386 // ============================================================================
2387 // renderer classes
2388 // ============================================================================
2389
2390 // ----------------------------------------------------------------------------
2391 // wxGridCellRenderer
2392 // ----------------------------------------------------------------------------
2393
2394 void wxGridCellRenderer::Draw(wxGrid& grid,
2395 wxGridCellAttr& attr,
2396 wxDC& dc,
2397 const wxRect& rect,
2398 int WXUNUSED(row), int WXUNUSED(col),
2399 bool isSelected)
2400 {
2401 dc.SetBackgroundMode( wxBRUSHSTYLE_SOLID );
2402
2403 wxColour clr;
2404 if ( grid.IsEnabled() )
2405 {
2406 if ( isSelected )
2407 {
2408 if ( grid.HasFocus() )
2409 clr = grid.GetSelectionBackground();
2410 else
2411 clr = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW);
2412 }
2413 else
2414 {
2415 clr = attr.GetBackgroundColour();
2416 }
2417 }
2418 else // grey out fields if the grid is disabled
2419 {
2420 clr = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
2421 }
2422
2423 dc.SetBrush(clr);
2424 dc.SetPen( *wxTRANSPARENT_PEN );
2425 dc.DrawRectangle(rect);
2426 }
2427
2428 // ----------------------------------------------------------------------------
2429 // wxGridCellStringRenderer
2430 // ----------------------------------------------------------------------------
2431
2432 void wxGridCellStringRenderer::SetTextColoursAndFont(const wxGrid& grid,
2433 const wxGridCellAttr& attr,
2434 wxDC& dc,
2435 bool isSelected)
2436 {
2437 dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT );
2438
2439 // TODO some special colours for attr.IsReadOnly() case?
2440
2441 // different coloured text when the grid is disabled
2442 if ( grid.IsEnabled() )
2443 {
2444 if ( isSelected )
2445 {
2446 wxColour clr;
2447 if ( grid.HasFocus() )
2448 clr = grid.GetSelectionBackground();
2449 else
2450 clr = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW);
2451 dc.SetTextBackground( clr );
2452 dc.SetTextForeground( grid.GetSelectionForeground() );
2453 }
2454 else
2455 {
2456 dc.SetTextBackground( attr.GetBackgroundColour() );
2457 dc.SetTextForeground( attr.GetTextColour() );
2458 }
2459 }
2460 else
2461 {
2462 dc.SetTextBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
2463 dc.SetTextForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT));
2464 }
2465
2466 dc.SetFont( attr.GetFont() );
2467 }
2468
2469 wxSize wxGridCellStringRenderer::DoGetBestSize(const wxGridCellAttr& attr,
2470 wxDC& dc,
2471 const wxString& text)
2472 {
2473 wxCoord x = 0, y = 0, max_x = 0;
2474 dc.SetFont(attr.GetFont());
2475 wxStringTokenizer tk(text, _T('\n'));
2476 while ( tk.HasMoreTokens() )
2477 {
2478 dc.GetTextExtent(tk.GetNextToken(), &x, &y);
2479 max_x = wxMax(max_x, x);
2480 }
2481
2482 y *= 1 + text.Freq(wxT('\n')); // multiply by the number of lines.
2483
2484 return wxSize(max_x, y);
2485 }
2486
2487 wxSize wxGridCellStringRenderer::GetBestSize(wxGrid& grid,
2488 wxGridCellAttr& attr,
2489 wxDC& dc,
2490 int row, int col)
2491 {
2492 return DoGetBestSize(attr, dc, grid.GetCellValue(row, col));
2493 }
2494
2495 void wxGridCellStringRenderer::Draw(wxGrid& grid,
2496 wxGridCellAttr& attr,
2497 wxDC& dc,
2498 const wxRect& rectCell,
2499 int row, int col,
2500 bool isSelected)
2501 {
2502 wxRect rect = rectCell;
2503 rect.Inflate(-1);
2504
2505 // erase only this cells background, overflow cells should have been erased
2506 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
2507
2508 int hAlign, vAlign;
2509 attr.GetAlignment(&hAlign, &vAlign);
2510
2511 int overflowCols = 0;
2512
2513 if (attr.GetOverflow())
2514 {
2515 int cols = grid.GetNumberCols();
2516 int best_width = GetBestSize(grid,attr,dc,row,col).GetWidth();
2517 int cell_rows, cell_cols;
2518 attr.GetSize( &cell_rows, &cell_cols ); // shouldn't get here if <= 0
2519 if ((best_width > rectCell.width) && (col < cols) && grid.GetTable())
2520 {
2521 int i, c_cols, c_rows;
2522 for (i = col+cell_cols; i < cols; i++)
2523 {
2524 bool is_empty = true;
2525 for (int j=row; j < row + cell_rows; j++)
2526 {
2527 // check w/ anchor cell for multicell block
2528 grid.GetCellSize(j, i, &c_rows, &c_cols);
2529 if (c_rows > 0)
2530 c_rows = 0;
2531 if (!grid.GetTable()->IsEmptyCell(j + c_rows, i))
2532 {
2533 is_empty = false;
2534 break;
2535 }
2536 }
2537
2538 if (is_empty)
2539 {
2540 rect.width += grid.GetColSize(i);
2541 }
2542 else
2543 {
2544 i--;
2545 break;
2546 }
2547
2548 if (rect.width >= best_width)
2549 break;
2550 }
2551
2552 overflowCols = i - col - cell_cols + 1;
2553 if (overflowCols >= cols)
2554 overflowCols = cols - 1;
2555 }
2556
2557 if (overflowCols > 0) // redraw overflow cells w/ proper hilight
2558 {
2559 hAlign = wxALIGN_LEFT; // if oveflowed then it's left aligned
2560 wxRect clip = rect;
2561 clip.x += rectCell.width;
2562 // draw each overflow cell individually
2563 int col_end = col + cell_cols + overflowCols;
2564 if (col_end >= grid.GetNumberCols())
2565 col_end = grid.GetNumberCols() - 1;
2566 for (int i = col + cell_cols; i <= col_end; i++)
2567 {
2568 clip.width = grid.GetColSize(i) - 1;
2569 dc.DestroyClippingRegion();
2570 dc.SetClippingRegion(clip);
2571
2572 SetTextColoursAndFont(grid, attr, dc,
2573 grid.IsInSelection(row,i));
2574
2575 grid.DrawTextRectangle(dc, grid.GetCellValue(row, col),
2576 rect, hAlign, vAlign);
2577 clip.x += grid.GetColSize(i) - 1;
2578 }
2579
2580 rect = rectCell;
2581 rect.Inflate(-1);
2582 rect.width++;
2583 dc.DestroyClippingRegion();
2584 }
2585 }
2586
2587 // now we only have to draw the text
2588 SetTextColoursAndFont(grid, attr, dc, isSelected);
2589
2590 grid.DrawTextRectangle(dc, grid.GetCellValue(row, col),
2591 rect, hAlign, vAlign);
2592 }
2593
2594 // ----------------------------------------------------------------------------
2595 // wxGridCellNumberRenderer
2596 // ----------------------------------------------------------------------------
2597
2598 wxString wxGridCellNumberRenderer::GetString(const wxGrid& grid, int row, int col)
2599 {
2600 wxGridTableBase *table = grid.GetTable();
2601 wxString text;
2602 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
2603 {
2604 text.Printf(_T("%ld"), table->GetValueAsLong(row, col));
2605 }
2606 else
2607 {
2608 text = table->GetValue(row, col);
2609 }
2610
2611 return text;
2612 }
2613
2614 void wxGridCellNumberRenderer::Draw(wxGrid& grid,
2615 wxGridCellAttr& attr,
2616 wxDC& dc,
2617 const wxRect& rectCell,
2618 int row, int col,
2619 bool isSelected)
2620 {
2621 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
2622
2623 SetTextColoursAndFont(grid, attr, dc, isSelected);
2624
2625 // draw the text right aligned by default
2626 int hAlign, vAlign;
2627 attr.GetAlignment(&hAlign, &vAlign);
2628 hAlign = wxALIGN_RIGHT;
2629
2630 wxRect rect = rectCell;
2631 rect.Inflate(-1);
2632
2633 grid.DrawTextRectangle(dc, GetString(grid, row, col), rect, hAlign, vAlign);
2634 }
2635
2636 wxSize wxGridCellNumberRenderer::GetBestSize(wxGrid& grid,
2637 wxGridCellAttr& attr,
2638 wxDC& dc,
2639 int row, int col)
2640 {
2641 return DoGetBestSize(attr, dc, GetString(grid, row, col));
2642 }
2643
2644 // ----------------------------------------------------------------------------
2645 // wxGridCellFloatRenderer
2646 // ----------------------------------------------------------------------------
2647
2648 wxGridCellFloatRenderer::wxGridCellFloatRenderer(int width, int precision)
2649 {
2650 SetWidth(width);
2651 SetPrecision(precision);
2652 }
2653
2654 wxGridCellRenderer *wxGridCellFloatRenderer::Clone() const
2655 {
2656 wxGridCellFloatRenderer *renderer = new wxGridCellFloatRenderer;
2657 renderer->m_width = m_width;
2658 renderer->m_precision = m_precision;
2659 renderer->m_format = m_format;
2660
2661 return renderer;
2662 }
2663
2664 wxString wxGridCellFloatRenderer::GetString(const wxGrid& grid, int row, int col)
2665 {
2666 wxGridTableBase *table = grid.GetTable();
2667
2668 bool hasDouble;
2669 double val;
2670 wxString text;
2671 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_FLOAT) )
2672 {
2673 val = table->GetValueAsDouble(row, col);
2674 hasDouble = true;
2675 }
2676 else
2677 {
2678 text = table->GetValue(row, col);
2679 hasDouble = text.ToDouble(&val);
2680 }
2681
2682 if ( hasDouble )
2683 {
2684 if ( !m_format )
2685 {
2686 if ( m_width == -1 )
2687 {
2688 if ( m_precision == -1 )
2689 {
2690 // default width/precision
2691 m_format = _T("%f");
2692 }
2693 else
2694 {
2695 m_format.Printf(_T("%%.%df"), m_precision);
2696 }
2697 }
2698 else if ( m_precision == -1 )
2699 {
2700 // default precision
2701 m_format.Printf(_T("%%%d.f"), m_width);
2702 }
2703 else
2704 {
2705 m_format.Printf(_T("%%%d.%df"), m_width, m_precision);
2706 }
2707 }
2708
2709 text.Printf(m_format, val);
2710
2711 }
2712 //else: text already contains the string
2713
2714 return text;
2715 }
2716
2717 void wxGridCellFloatRenderer::Draw(wxGrid& grid,
2718 wxGridCellAttr& attr,
2719 wxDC& dc,
2720 const wxRect& rectCell,
2721 int row, int col,
2722 bool isSelected)
2723 {
2724 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
2725
2726 SetTextColoursAndFont(grid, attr, dc, isSelected);
2727
2728 // draw the text right aligned by default
2729 int hAlign, vAlign;
2730 attr.GetAlignment(&hAlign, &vAlign);
2731 hAlign = wxALIGN_RIGHT;
2732
2733 wxRect rect = rectCell;
2734 rect.Inflate(-1);
2735
2736 grid.DrawTextRectangle(dc, GetString(grid, row, col), rect, hAlign, vAlign);
2737 }
2738
2739 wxSize wxGridCellFloatRenderer::GetBestSize(wxGrid& grid,
2740 wxGridCellAttr& attr,
2741 wxDC& dc,
2742 int row, int col)
2743 {
2744 return DoGetBestSize(attr, dc, GetString(grid, row, col));
2745 }
2746
2747 void wxGridCellFloatRenderer::SetParameters(const wxString& params)
2748 {
2749 if ( !params )
2750 {
2751 // reset to defaults
2752 SetWidth(-1);
2753 SetPrecision(-1);
2754 }
2755 else
2756 {
2757 wxString tmp = params.BeforeFirst(_T(','));
2758 if ( !tmp.empty() )
2759 {
2760 long width;
2761 if ( tmp.ToLong(&width) )
2762 {
2763 SetWidth((int)width);
2764 }
2765 else
2766 {
2767 wxLogDebug(_T("Invalid wxGridCellFloatRenderer width parameter string '%s ignored"), params.c_str());
2768 }
2769 }
2770
2771 tmp = params.AfterFirst(_T(','));
2772 if ( !tmp.empty() )
2773 {
2774 long precision;
2775 if ( tmp.ToLong(&precision) )
2776 {
2777 SetPrecision((int)precision);
2778 }
2779 else
2780 {
2781 wxLogDebug(_T("Invalid wxGridCellFloatRenderer precision parameter string '%s ignored"), params.c_str());
2782 }
2783 }
2784 }
2785 }
2786
2787 // ----------------------------------------------------------------------------
2788 // wxGridCellBoolRenderer
2789 // ----------------------------------------------------------------------------
2790
2791 wxSize wxGridCellBoolRenderer::ms_sizeCheckMark;
2792
2793 // FIXME these checkbox size calculations are really ugly...
2794
2795 // between checkmark and box
2796 static const wxCoord wxGRID_CHECKMARK_MARGIN = 2;
2797
2798 wxSize wxGridCellBoolRenderer::GetBestSize(wxGrid& grid,
2799 wxGridCellAttr& WXUNUSED(attr),
2800 wxDC& WXUNUSED(dc),
2801 int WXUNUSED(row),
2802 int WXUNUSED(col))
2803 {
2804 // compute it only once (no locks for MT safeness in GUI thread...)
2805 if ( !ms_sizeCheckMark.x )
2806 {
2807 // get checkbox size
2808 wxCheckBox *checkbox = new wxCheckBox(&grid, wxID_ANY, wxEmptyString);
2809 wxSize size = checkbox->GetBestSize();
2810 wxCoord checkSize = size.y + 2 * wxGRID_CHECKMARK_MARGIN;
2811
2812 #if defined(__WXMOTIF__)
2813 checkSize -= size.y / 2;
2814 #endif
2815
2816 delete checkbox;
2817
2818 ms_sizeCheckMark.x = ms_sizeCheckMark.y = checkSize;
2819 }
2820
2821 return ms_sizeCheckMark;
2822 }
2823
2824 void wxGridCellBoolRenderer::Draw(wxGrid& grid,
2825 wxGridCellAttr& attr,
2826 wxDC& dc,
2827 const wxRect& rect,
2828 int row, int col,
2829 bool isSelected)
2830 {
2831 wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);
2832
2833 // draw a check mark in the centre (ignoring alignment - TODO)
2834 wxSize size = GetBestSize(grid, attr, dc, row, col);
2835
2836 // don't draw outside the cell
2837 wxCoord minSize = wxMin(rect.width, rect.height);
2838 if ( size.x >= minSize || size.y >= minSize )
2839 {
2840 // and even leave (at least) 1 pixel margin
2841 size.x = size.y = minSize;
2842 }
2843
2844 // draw a border around checkmark
2845 int vAlign, hAlign;
2846 attr.GetAlignment(&hAlign, &vAlign);
2847
2848 wxRect rectBorder;
2849 if (hAlign == wxALIGN_CENTRE)
2850 {
2851 rectBorder.x = rect.x + rect.width / 2 - size.x / 2;
2852 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2853 rectBorder.width = size.x;
2854 rectBorder.height = size.y;
2855 }
2856 else if (hAlign == wxALIGN_LEFT)
2857 {
2858 rectBorder.x = rect.x + 2;
2859 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2860 rectBorder.width = size.x;
2861 rectBorder.height = size.y;
2862 }
2863 else if (hAlign == wxALIGN_RIGHT)
2864 {
2865 rectBorder.x = rect.x + rect.width - size.x - 2;
2866 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2867 rectBorder.width = size.x;
2868 rectBorder.height = size.y;
2869 }
2870
2871 bool value;
2872 if ( grid.GetTable()->CanGetValueAs(row, col, wxGRID_VALUE_BOOL) )
2873 {
2874 value = grid.GetTable()->GetValueAsBool(row, col);
2875 }
2876 else
2877 {
2878 wxString cellval( grid.GetTable()->GetValue(row, col) );
2879 value = wxGridCellBoolEditor::IsTrueValue(cellval);
2880 }
2881
2882 int flags = 0;
2883 if (value)
2884 flags |= wxCONTROL_CHECKED;
2885
2886 wxRendererNative::Get().DrawCheckBox( &grid, dc, rectBorder, flags );
2887 }
2888
2889 // ----------------------------------------------------------------------------
2890 // wxGridCellAttr
2891 // ----------------------------------------------------------------------------
2892
2893 void wxGridCellAttr::Init(wxGridCellAttr *attrDefault)
2894 {
2895 m_nRef = 1;
2896
2897 m_isReadOnly = Unset;
2898
2899 m_renderer = NULL;
2900 m_editor = NULL;
2901
2902 m_attrkind = wxGridCellAttr::Cell;
2903
2904 m_sizeRows = m_sizeCols = 1;
2905 m_overflow = UnsetOverflow;
2906
2907 SetDefAttr(attrDefault);
2908 }
2909
2910 wxGridCellAttr *wxGridCellAttr::Clone() const
2911 {
2912 wxGridCellAttr *attr = new wxGridCellAttr(m_defGridAttr);
2913
2914 if ( HasTextColour() )
2915 attr->SetTextColour(GetTextColour());
2916 if ( HasBackgroundColour() )
2917 attr->SetBackgroundColour(GetBackgroundColour());
2918 if ( HasFont() )
2919 attr->SetFont(GetFont());
2920 if ( HasAlignment() )
2921 attr->SetAlignment(m_hAlign, m_vAlign);
2922
2923 attr->SetSize( m_sizeRows, m_sizeCols );
2924
2925 if ( m_renderer )
2926 {
2927 attr->SetRenderer(m_renderer);
2928 m_renderer->IncRef();
2929 }
2930 if ( m_editor )
2931 {
2932 attr->SetEditor(m_editor);
2933 m_editor->IncRef();
2934 }
2935
2936 if ( IsReadOnly() )
2937 attr->SetReadOnly();
2938
2939 attr->SetOverflow( m_overflow == Overflow );
2940 attr->SetKind( m_attrkind );
2941
2942 return attr;
2943 }
2944
2945 void wxGridCellAttr::MergeWith(wxGridCellAttr *mergefrom)
2946 {
2947 if ( !HasTextColour() && mergefrom->HasTextColour() )
2948 SetTextColour(mergefrom->GetTextColour());
2949 if ( !HasBackgroundColour() && mergefrom->HasBackgroundColour() )
2950 SetBackgroundColour(mergefrom->GetBackgroundColour());
2951 if ( !HasFont() && mergefrom->HasFont() )
2952 SetFont(mergefrom->GetFont());
2953 if ( !HasAlignment() && mergefrom->HasAlignment() )
2954 {
2955 int hAlign, vAlign;
2956 mergefrom->GetAlignment( &hAlign, &vAlign);
2957 SetAlignment(hAlign, vAlign);
2958 }
2959 if ( !HasSize() && mergefrom->HasSize() )
2960 mergefrom->GetSize( &m_sizeRows, &m_sizeCols );
2961
2962 // Directly access member functions as GetRender/Editor don't just return
2963 // m_renderer/m_editor
2964 //
2965 // Maybe add support for merge of Render and Editor?
2966 if (!HasRenderer() && mergefrom->HasRenderer() )
2967 {
2968 m_renderer = mergefrom->m_renderer;
2969 m_renderer->IncRef();
2970 }
2971 if ( !HasEditor() && mergefrom->HasEditor() )
2972 {
2973 m_editor = mergefrom->m_editor;
2974 m_editor->IncRef();
2975 }
2976 if ( !HasReadWriteMode() && mergefrom->HasReadWriteMode() )
2977 SetReadOnly(mergefrom->IsReadOnly());
2978
2979 if (!HasOverflowMode() && mergefrom->HasOverflowMode() )
2980 SetOverflow(mergefrom->GetOverflow());
2981
2982 SetDefAttr(mergefrom->m_defGridAttr);
2983 }
2984
2985 void wxGridCellAttr::SetSize(int num_rows, int num_cols)
2986 {
2987 // The size of a cell is normally 1,1
2988
2989 // If this cell is larger (2,2) then this is the top left cell
2990 // the other cells that will be covered (lower right cells) must be
2991 // set to negative or zero values such that
2992 // row + num_rows of the covered cell points to the larger cell (this cell)
2993 // same goes for the col + num_cols.
2994
2995 // Size of 0,0 is NOT valid, neither is <=0 and any positive value
2996
2997 wxASSERT_MSG( (!((num_rows > 0) && (num_cols <= 0)) ||
2998 !((num_rows <= 0) && (num_cols > 0)) ||
2999 !((num_rows == 0) && (num_cols == 0))),
3000 wxT("wxGridCellAttr::SetSize only takes two postive values or negative/zero values"));
3001
3002 m_sizeRows = num_rows;
3003 m_sizeCols = num_cols;
3004 }
3005
3006 const wxColour& wxGridCellAttr::GetTextColour() const
3007 {
3008 if (HasTextColour())
3009 {
3010 return m_colText;
3011 }
3012 else if (m_defGridAttr && m_defGridAttr != this)
3013 {
3014 return m_defGridAttr->GetTextColour();
3015 }
3016 else
3017 {
3018 wxFAIL_MSG(wxT("Missing default cell attribute"));
3019 return wxNullColour;
3020 }
3021 }
3022
3023 const wxColour& wxGridCellAttr::GetBackgroundColour() const
3024 {
3025 if (HasBackgroundColour())
3026 {
3027 return m_colBack;
3028 }
3029 else if (m_defGridAttr && m_defGridAttr != this)
3030 {
3031 return m_defGridAttr->GetBackgroundColour();
3032 }
3033 else
3034 {
3035 wxFAIL_MSG(wxT("Missing default cell attribute"));
3036 return wxNullColour;
3037 }
3038 }
3039
3040 const wxFont& wxGridCellAttr::GetFont() const
3041 {
3042 if (HasFont())
3043 {
3044 return m_font;
3045 }
3046 else if (m_defGridAttr && m_defGridAttr != this)
3047 {
3048 return m_defGridAttr->GetFont();
3049 }
3050 else
3051 {
3052 wxFAIL_MSG(wxT("Missing default cell attribute"));
3053 return wxNullFont;
3054 }
3055 }
3056
3057 void wxGridCellAttr::GetAlignment(int *hAlign, int *vAlign) const
3058 {
3059 if (HasAlignment())
3060 {
3061 if ( hAlign )
3062 *hAlign = m_hAlign;
3063 if ( vAlign )
3064 *vAlign = m_vAlign;
3065 }
3066 else if (m_defGridAttr && m_defGridAttr != this)
3067 {
3068 m_defGridAttr->GetAlignment(hAlign, vAlign);
3069 }
3070 else
3071 {
3072 wxFAIL_MSG(wxT("Missing default cell attribute"));
3073 }
3074 }
3075
3076 void wxGridCellAttr::GetSize( int *num_rows, int *num_cols ) const
3077 {
3078 if ( num_rows )
3079 *num_rows = m_sizeRows;
3080 if ( num_cols )
3081 *num_cols = m_sizeCols;
3082 }
3083
3084 // GetRenderer and GetEditor use a slightly different decision path about
3085 // which attribute to use. If a non-default attr object has one then it is
3086 // used, otherwise the default editor or renderer is fetched from the grid and
3087 // used. It should be the default for the data type of the cell. If it is
3088 // NULL (because the table has a type that the grid does not have in its
3089 // registry), then the grid's default editor or renderer is used.
3090
3091 wxGridCellRenderer* wxGridCellAttr::GetRenderer(const wxGrid* grid, int row, int col) const
3092 {
3093 wxGridCellRenderer *renderer = NULL;
3094
3095 if ( m_renderer && this != m_defGridAttr )
3096 {
3097 // use the cells renderer if it has one
3098 renderer = m_renderer;
3099 renderer->IncRef();
3100 }
3101 else // no non-default cell renderer
3102 {
3103 // get default renderer for the data type
3104 if ( grid )
3105 {
3106 // GetDefaultRendererForCell() will do IncRef() for us
3107 renderer = grid->GetDefaultRendererForCell(row, col);
3108 }
3109
3110 if ( renderer == NULL )
3111 {
3112 if ( (m_defGridAttr != NULL) && (m_defGridAttr != this) )
3113 {
3114 // if we still don't have one then use the grid default
3115 // (no need for IncRef() here neither)
3116 renderer = m_defGridAttr->GetRenderer(NULL, 0, 0);
3117 }
3118 else // default grid attr
3119 {
3120 // use m_renderer which we had decided not to use initially
3121 renderer = m_renderer;
3122 if ( renderer )
3123 renderer->IncRef();
3124 }
3125 }
3126 }
3127
3128 // we're supposed to always find something
3129 wxASSERT_MSG(renderer, wxT("Missing default cell renderer"));
3130
3131 return renderer;
3132 }
3133
3134 // same as above, except for s/renderer/editor/g
3135 wxGridCellEditor* wxGridCellAttr::GetEditor(const wxGrid* grid, int row, int col) const
3136 {
3137 wxGridCellEditor *editor = NULL;
3138
3139 if ( m_editor && this != m_defGridAttr )
3140 {
3141 // use the cells editor if it has one
3142 editor = m_editor;
3143 editor->IncRef();
3144 }
3145 else // no non default cell editor
3146 {
3147 // get default editor for the data type
3148 if ( grid )
3149 {
3150 // GetDefaultEditorForCell() will do IncRef() for us
3151 editor = grid->GetDefaultEditorForCell(row, col);
3152 }
3153
3154 if ( editor == NULL )
3155 {
3156 if ( (m_defGridAttr != NULL) && (m_defGridAttr != this) )
3157 {
3158 // if we still don't have one then use the grid default
3159 // (no need for IncRef() here neither)
3160 editor = m_defGridAttr->GetEditor(NULL, 0, 0);
3161 }
3162 else // default grid attr
3163 {
3164 // use m_editor which we had decided not to use initially
3165 editor = m_editor;
3166 if ( editor )
3167 editor->IncRef();
3168 }
3169 }
3170 }
3171
3172 // we're supposed to always find something
3173 wxASSERT_MSG(editor, wxT("Missing default cell editor"));
3174
3175 return editor;
3176 }
3177
3178 // ----------------------------------------------------------------------------
3179 // wxGridCellAttrData
3180 // ----------------------------------------------------------------------------
3181
3182 void wxGridCellAttrData::SetAttr(wxGridCellAttr *attr, int row, int col)
3183 {
3184 // Note: contrary to wxGridRowOrColAttrData::SetAttr, we must not
3185 // touch attribute's reference counting explicitly, since this
3186 // is managed by class wxGridCellWithAttr
3187 int n = FindIndex(row, col);
3188 if ( n == wxNOT_FOUND )
3189 {
3190 if ( attr )
3191 {
3192 // add the attribute
3193 m_attrs.Add(new wxGridCellWithAttr(row, col, attr));
3194 }
3195 //else: nothing to do
3196 }
3197 else // we already have an attribute for this cell
3198 {
3199 if ( attr )
3200 {
3201 // change the attribute
3202 m_attrs[(size_t)n].ChangeAttr(attr);
3203 }
3204 else
3205 {
3206 // remove this attribute
3207 m_attrs.RemoveAt((size_t)n);
3208 }
3209 }
3210 }
3211
3212 wxGridCellAttr *wxGridCellAttrData::GetAttr(int row, int col) const
3213 {
3214 wxGridCellAttr *attr = NULL;
3215
3216 int n = FindIndex(row, col);
3217 if ( n != wxNOT_FOUND )
3218 {
3219 attr = m_attrs[(size_t)n].attr;
3220 attr->IncRef();
3221 }
3222
3223 return attr;
3224 }
3225
3226 void wxGridCellAttrData::UpdateAttrRows( size_t pos, int numRows )
3227 {
3228 size_t count = m_attrs.GetCount();
3229 for ( size_t n = 0; n < count; n++ )
3230 {
3231 wxGridCellCoords& coords = m_attrs[n].coords;
3232 wxCoord row = coords.GetRow();
3233 if ((size_t)row >= pos)
3234 {
3235 if (numRows > 0)
3236 {
3237 // If rows inserted, include row counter where necessary
3238 coords.SetRow(row + numRows);
3239 }
3240 else if (numRows < 0)
3241 {
3242 // If rows deleted ...
3243 if ((size_t)row >= pos - numRows)
3244 {
3245 // ...either decrement row counter (if row still exists)...
3246 coords.SetRow(row + numRows);
3247 }
3248 else
3249 {
3250 // ...or remove the attribute
3251 m_attrs.RemoveAt(n);
3252 n--;
3253 count--;
3254 }
3255 }
3256 }
3257 }
3258 }
3259
3260 void wxGridCellAttrData::UpdateAttrCols( size_t pos, int numCols )
3261 {
3262 size_t count = m_attrs.GetCount();
3263 for ( size_t n = 0; n < count; n++ )
3264 {
3265 wxGridCellCoords& coords = m_attrs[n].coords;
3266 wxCoord col = coords.GetCol();
3267 if ( (size_t)col >= pos )
3268 {
3269 if ( numCols > 0 )
3270 {
3271 // If rows inserted, include row counter where necessary
3272 coords.SetCol(col + numCols);
3273 }
3274 else if (numCols < 0)
3275 {
3276 // If rows deleted ...
3277 if ((size_t)col >= pos - numCols)
3278 {
3279 // ...either decrement row counter (if row still exists)...
3280 coords.SetCol(col + numCols);
3281 }
3282 else
3283 {
3284 // ...or remove the attribute
3285 m_attrs.RemoveAt(n);
3286 n--;
3287 count--;
3288 }
3289 }
3290 }
3291 }
3292 }
3293
3294 int wxGridCellAttrData::FindIndex(int row, int col) const
3295 {
3296 size_t count = m_attrs.GetCount();
3297 for ( size_t n = 0; n < count; n++ )
3298 {
3299 const wxGridCellCoords& coords = m_attrs[n].coords;
3300 if ( (coords.GetRow() == row) && (coords.GetCol() == col) )
3301 {
3302 return n;
3303 }
3304 }
3305
3306 return wxNOT_FOUND;
3307 }
3308
3309 // ----------------------------------------------------------------------------
3310 // wxGridRowOrColAttrData
3311 // ----------------------------------------------------------------------------
3312
3313 wxGridRowOrColAttrData::~wxGridRowOrColAttrData()
3314 {
3315 size_t count = m_attrs.GetCount();
3316 for ( size_t n = 0; n < count; n++ )
3317 {
3318 m_attrs[n]->DecRef();
3319 }
3320 }
3321
3322 wxGridCellAttr *wxGridRowOrColAttrData::GetAttr(int rowOrCol) const
3323 {
3324 wxGridCellAttr *attr = NULL;
3325
3326 int n = m_rowsOrCols.Index(rowOrCol);
3327 if ( n != wxNOT_FOUND )
3328 {
3329 attr = m_attrs[(size_t)n];
3330 attr->IncRef();
3331 }
3332
3333 return attr;
3334 }
3335
3336 void wxGridRowOrColAttrData::SetAttr(wxGridCellAttr *attr, int rowOrCol)
3337 {
3338 int i = m_rowsOrCols.Index(rowOrCol);
3339 if ( i == wxNOT_FOUND )
3340 {
3341 if ( attr )
3342 {
3343 // add the attribute - no need to do anything to reference count
3344 // since we take ownership of the attribute.
3345 m_rowsOrCols.Add(rowOrCol);
3346 m_attrs.Add(attr);
3347 }
3348 // nothing to remove
3349 }
3350 else
3351 {
3352 size_t n = (size_t)i;
3353 if ( m_attrs[n] == attr )
3354 // nothing to do
3355 return;
3356 if ( attr )
3357 {
3358 // change the attribute, handling reference count manually,
3359 // taking ownership of the new attribute.
3360 m_attrs[n]->DecRef();
3361 m_attrs[n] = attr;
3362 }
3363 else
3364 {
3365 // remove this attribute, handling reference count manually
3366 m_attrs[n]->DecRef();
3367 m_rowsOrCols.RemoveAt(n);
3368 m_attrs.RemoveAt(n);
3369 }
3370 }
3371 }
3372
3373 void wxGridRowOrColAttrData::UpdateAttrRowsOrCols( size_t pos, int numRowsOrCols )
3374 {
3375 size_t count = m_attrs.GetCount();
3376 for ( size_t n = 0; n < count; n++ )
3377 {
3378 int & rowOrCol = m_rowsOrCols[n];
3379 if ( (size_t)rowOrCol >= pos )
3380 {
3381 if ( numRowsOrCols > 0 )
3382 {
3383 // If rows inserted, include row counter where necessary
3384 rowOrCol += numRowsOrCols;
3385 }
3386 else if ( numRowsOrCols < 0)
3387 {
3388 // If rows deleted, either decrement row counter (if row still exists)
3389 if ((size_t)rowOrCol >= pos - numRowsOrCols)
3390 rowOrCol += numRowsOrCols;
3391 else
3392 {
3393 m_rowsOrCols.RemoveAt(n);
3394 m_attrs[n]->DecRef();
3395 m_attrs.RemoveAt(n);
3396 n--;
3397 count--;
3398 }
3399 }
3400 }
3401 }
3402 }
3403
3404 // ----------------------------------------------------------------------------
3405 // wxGridCellAttrProvider
3406 // ----------------------------------------------------------------------------
3407
3408 wxGridCellAttrProvider::wxGridCellAttrProvider()
3409 {
3410 m_data = NULL;
3411 }
3412
3413 wxGridCellAttrProvider::~wxGridCellAttrProvider()
3414 {
3415 delete m_data;
3416 }
3417
3418 void wxGridCellAttrProvider::InitData()
3419 {
3420 m_data = new wxGridCellAttrProviderData;
3421 }
3422
3423 wxGridCellAttr *wxGridCellAttrProvider::GetAttr(int row, int col,
3424 wxGridCellAttr::wxAttrKind kind ) const
3425 {
3426 wxGridCellAttr *attr = NULL;
3427 if ( m_data )
3428 {
3429 switch (kind)
3430 {
3431 case (wxGridCellAttr::Any):
3432 // Get cached merge attributes.
3433 // Currently not used as no cache implemented as not mutable
3434 // attr = m_data->m_mergeAttr.GetAttr(row, col);
3435 if (!attr)
3436 {
3437 // Basically implement old version.
3438 // Also check merge cache, so we don't have to re-merge every time..
3439 wxGridCellAttr *attrcell = m_data->m_cellAttrs.GetAttr(row, col);
3440 wxGridCellAttr *attrrow = m_data->m_rowAttrs.GetAttr(row);
3441 wxGridCellAttr *attrcol = m_data->m_colAttrs.GetAttr(col);
3442
3443 if ((attrcell != attrrow) && (attrrow != attrcol) && (attrcell != attrcol))
3444 {
3445 // Two or more are non NULL
3446 attr = new wxGridCellAttr;
3447 attr->SetKind(wxGridCellAttr::Merged);
3448
3449 // Order is important..
3450 if (attrcell)
3451 {
3452 attr->MergeWith(attrcell);
3453 attrcell->DecRef();
3454 }
3455 if (attrcol)
3456 {
3457 attr->MergeWith(attrcol);
3458 attrcol->DecRef();
3459 }
3460 if (attrrow)
3461 {
3462 attr->MergeWith(attrrow);
3463 attrrow->DecRef();
3464 }
3465
3466 // store merge attr if cache implemented
3467 //attr->IncRef();
3468 //m_data->m_mergeAttr.SetAttr(attr, row, col);
3469 }
3470 else
3471 {
3472 // one or none is non null return it or null.
3473 if (attrrow)
3474 attr = attrrow;
3475 if (attrcol)
3476 {
3477 if (attr)
3478 attr->DecRef();
3479 attr = attrcol;
3480 }
3481 if (attrcell)
3482 {
3483 if (attr)
3484 attr->DecRef();
3485 attr = attrcell;
3486 }
3487 }
3488 }
3489 break;
3490
3491 case (wxGridCellAttr::Cell):
3492 attr = m_data->m_cellAttrs.GetAttr(row, col);
3493 break;
3494
3495 case (wxGridCellAttr::Col):
3496 attr = m_data->m_colAttrs.GetAttr(col);
3497 break;
3498
3499 case (wxGridCellAttr::Row):
3500 attr = m_data->m_rowAttrs.GetAttr(row);
3501 break;
3502
3503 default:
3504 // unused as yet...
3505 // (wxGridCellAttr::Default):
3506 // (wxGridCellAttr::Merged):
3507 break;
3508 }
3509 }
3510
3511 return attr;
3512 }
3513
3514 void wxGridCellAttrProvider::SetAttr(wxGridCellAttr *attr,
3515 int row, int col)
3516 {
3517 if ( !m_data )
3518 InitData();
3519
3520 m_data->m_cellAttrs.SetAttr(attr, row, col);
3521 }
3522
3523 void wxGridCellAttrProvider::SetRowAttr(wxGridCellAttr *attr, int row)
3524 {
3525 if ( !m_data )
3526 InitData();
3527
3528 m_data->m_rowAttrs.SetAttr(attr, row);
3529 }
3530
3531 void wxGridCellAttrProvider::SetColAttr(wxGridCellAttr *attr, int col)
3532 {
3533 if ( !m_data )
3534 InitData();
3535
3536 m_data->m_colAttrs.SetAttr(attr, col);
3537 }
3538
3539 void wxGridCellAttrProvider::UpdateAttrRows( size_t pos, int numRows )
3540 {
3541 if ( m_data )
3542 {
3543 m_data->m_cellAttrs.UpdateAttrRows( pos, numRows );
3544
3545 m_data->m_rowAttrs.UpdateAttrRowsOrCols( pos, numRows );
3546 }
3547 }
3548
3549 void wxGridCellAttrProvider::UpdateAttrCols( size_t pos, int numCols )
3550 {
3551 if ( m_data )
3552 {
3553 m_data->m_cellAttrs.UpdateAttrCols( pos, numCols );
3554
3555 m_data->m_colAttrs.UpdateAttrRowsOrCols( pos, numCols );
3556 }
3557 }
3558
3559 // ----------------------------------------------------------------------------
3560 // wxGridTypeRegistry
3561 // ----------------------------------------------------------------------------
3562
3563 wxGridTypeRegistry::~wxGridTypeRegistry()
3564 {
3565 size_t count = m_typeinfo.GetCount();
3566 for ( size_t i = 0; i < count; i++ )
3567 delete m_typeinfo[i];
3568 }
3569
3570 void wxGridTypeRegistry::RegisterDataType(const wxString& typeName,
3571 wxGridCellRenderer* renderer,
3572 wxGridCellEditor* editor)
3573 {
3574 wxGridDataTypeInfo* info = new wxGridDataTypeInfo(typeName, renderer, editor);
3575
3576 // is it already registered?
3577 int loc = FindRegisteredDataType(typeName);
3578 if ( loc != wxNOT_FOUND )
3579 {
3580 delete m_typeinfo[loc];
3581 m_typeinfo[loc] = info;
3582 }
3583 else
3584 {
3585 m_typeinfo.Add(info);
3586 }
3587 }
3588
3589 int wxGridTypeRegistry::FindRegisteredDataType(const wxString& typeName)
3590 {
3591 size_t count = m_typeinfo.GetCount();
3592 for ( size_t i = 0; i < count; i++ )
3593 {
3594 if ( typeName == m_typeinfo[i]->m_typeName )
3595 {
3596 return i;
3597 }
3598 }
3599
3600 return wxNOT_FOUND;
3601 }
3602
3603 int wxGridTypeRegistry::FindDataType(const wxString& typeName)
3604 {
3605 int index = FindRegisteredDataType(typeName);
3606 if ( index == wxNOT_FOUND )
3607 {
3608 // check whether this is one of the standard ones, in which case
3609 // register it "on the fly"
3610 #if wxUSE_TEXTCTRL
3611 if ( typeName == wxGRID_VALUE_STRING )
3612 {
3613 RegisterDataType(wxGRID_VALUE_STRING,
3614 new wxGridCellStringRenderer,
3615 new wxGridCellTextEditor);
3616 }
3617 else
3618 #endif // wxUSE_TEXTCTRL
3619 #if wxUSE_CHECKBOX
3620 if ( typeName == wxGRID_VALUE_BOOL )
3621 {
3622 RegisterDataType(wxGRID_VALUE_BOOL,
3623 new wxGridCellBoolRenderer,
3624 new wxGridCellBoolEditor);
3625 }
3626 else
3627 #endif // wxUSE_CHECKBOX
3628 #if wxUSE_TEXTCTRL
3629 if ( typeName == wxGRID_VALUE_NUMBER )
3630 {
3631 RegisterDataType(wxGRID_VALUE_NUMBER,
3632 new wxGridCellNumberRenderer,
3633 new wxGridCellNumberEditor);
3634 }
3635 else if ( typeName == wxGRID_VALUE_FLOAT )
3636 {
3637 RegisterDataType(wxGRID_VALUE_FLOAT,
3638 new wxGridCellFloatRenderer,
3639 new wxGridCellFloatEditor);
3640 }
3641 else
3642 #endif // wxUSE_TEXTCTRL
3643 #if wxUSE_COMBOBOX
3644 if ( typeName == wxGRID_VALUE_CHOICE )
3645 {
3646 RegisterDataType(wxGRID_VALUE_CHOICE,
3647 new wxGridCellStringRenderer,
3648 new wxGridCellChoiceEditor);
3649 }
3650 else
3651 #endif // wxUSE_COMBOBOX
3652 {
3653 return wxNOT_FOUND;
3654 }
3655
3656 // we get here only if just added the entry for this type, so return
3657 // the last index
3658 index = m_typeinfo.GetCount() - 1;
3659 }
3660
3661 return index;
3662 }
3663
3664 int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName)
3665 {
3666 int index = FindDataType(typeName);
3667 if ( index == wxNOT_FOUND )
3668 {
3669 // the first part of the typename is the "real" type, anything after ':'
3670 // are the parameters for the renderer
3671 index = FindDataType(typeName.BeforeFirst(_T(':')));
3672 if ( index == wxNOT_FOUND )
3673 {
3674 return wxNOT_FOUND;
3675 }
3676
3677 wxGridCellRenderer *renderer = GetRenderer(index);
3678 wxGridCellRenderer *rendererOld = renderer;
3679 renderer = renderer->Clone();
3680 rendererOld->DecRef();
3681
3682 wxGridCellEditor *editor = GetEditor(index);
3683 wxGridCellEditor *editorOld = editor;
3684 editor = editor->Clone();
3685 editorOld->DecRef();
3686
3687 // do it even if there are no parameters to reset them to defaults
3688 wxString params = typeName.AfterFirst(_T(':'));
3689 renderer->SetParameters(params);
3690 editor->SetParameters(params);
3691
3692 // register the new typename
3693 RegisterDataType(typeName, renderer, editor);
3694
3695 // we just registered it, it's the last one
3696 index = m_typeinfo.GetCount() - 1;
3697 }
3698
3699 return index;
3700 }
3701
3702 wxGridCellRenderer* wxGridTypeRegistry::GetRenderer(int index)
3703 {
3704 wxGridCellRenderer* renderer = m_typeinfo[index]->m_renderer;
3705 if (renderer)
3706 renderer->IncRef();
3707
3708 return renderer;
3709 }
3710
3711 wxGridCellEditor* wxGridTypeRegistry::GetEditor(int index)
3712 {
3713 wxGridCellEditor* editor = m_typeinfo[index]->m_editor;
3714 if (editor)
3715 editor->IncRef();
3716
3717 return editor;
3718 }
3719
3720 // ----------------------------------------------------------------------------
3721 // wxGridTableBase
3722 // ----------------------------------------------------------------------------
3723
3724 IMPLEMENT_ABSTRACT_CLASS( wxGridTableBase, wxObject )
3725
3726 wxGridTableBase::wxGridTableBase()
3727 {
3728 m_view = NULL;
3729 m_attrProvider = NULL;
3730 }
3731
3732 wxGridTableBase::~wxGridTableBase()
3733 {
3734 delete m_attrProvider;
3735 }
3736
3737 void wxGridTableBase::SetAttrProvider(wxGridCellAttrProvider *attrProvider)
3738 {
3739 delete m_attrProvider;
3740 m_attrProvider = attrProvider;
3741 }
3742
3743 bool wxGridTableBase::CanHaveAttributes()
3744 {
3745 if ( ! GetAttrProvider() )
3746 {
3747 // use the default attr provider by default
3748 SetAttrProvider(new wxGridCellAttrProvider);
3749 }
3750
3751 return true;
3752 }
3753
3754 wxGridCellAttr *wxGridTableBase::GetAttr(int row, int col, wxGridCellAttr::wxAttrKind kind)
3755 {
3756 if ( m_attrProvider )
3757 return m_attrProvider->GetAttr(row, col, kind);
3758 else
3759 return NULL;
3760 }
3761
3762 void wxGridTableBase::SetAttr(wxGridCellAttr* attr, int row, int col)
3763 {
3764 if ( m_attrProvider )
3765 {
3766 if ( attr )
3767 attr->SetKind(wxGridCellAttr::Cell);
3768 m_attrProvider->SetAttr(attr, row, col);
3769 }
3770 else
3771 {
3772 // as we take ownership of the pointer and don't store it, we must
3773 // free it now
3774 wxSafeDecRef(attr);
3775 }
3776 }
3777
3778 void wxGridTableBase::SetRowAttr(wxGridCellAttr *attr, int row)
3779 {
3780 if ( m_attrProvider )
3781 {
3782 attr->SetKind(wxGridCellAttr::Row);
3783 m_attrProvider->SetRowAttr(attr, row);
3784 }
3785 else
3786 {
3787 // as we take ownership of the pointer and don't store it, we must
3788 // free it now
3789 wxSafeDecRef(attr);
3790 }
3791 }
3792
3793 void wxGridTableBase::SetColAttr(wxGridCellAttr *attr, int col)
3794 {
3795 if ( m_attrProvider )
3796 {
3797 attr->SetKind(wxGridCellAttr::Col);
3798 m_attrProvider->SetColAttr(attr, col);
3799 }
3800 else
3801 {
3802 // as we take ownership of the pointer and don't store it, we must
3803 // free it now
3804 wxSafeDecRef(attr);
3805 }
3806 }
3807
3808 bool wxGridTableBase::InsertRows( size_t WXUNUSED(pos),
3809 size_t WXUNUSED(numRows) )
3810 {
3811 wxFAIL_MSG( wxT("Called grid table class function InsertRows\nbut your derived table class does not override this function") );
3812
3813 return false;
3814 }
3815
3816 bool wxGridTableBase::AppendRows( size_t WXUNUSED(numRows) )
3817 {
3818 wxFAIL_MSG( wxT("Called grid table class function AppendRows\nbut your derived table class does not override this function"));
3819
3820 return false;
3821 }
3822
3823 bool wxGridTableBase::DeleteRows( size_t WXUNUSED(pos),
3824 size_t WXUNUSED(numRows) )
3825 {
3826 wxFAIL_MSG( wxT("Called grid table class function DeleteRows\nbut your derived table class does not override this function"));
3827
3828 return false;
3829 }
3830
3831 bool wxGridTableBase::InsertCols( size_t WXUNUSED(pos),
3832 size_t WXUNUSED(numCols) )
3833 {
3834 wxFAIL_MSG( wxT("Called grid table class function InsertCols\nbut your derived table class does not override this function"));
3835
3836 return false;
3837 }
3838
3839 bool wxGridTableBase::AppendCols( size_t WXUNUSED(numCols) )
3840 {
3841 wxFAIL_MSG(wxT("Called grid table class function AppendCols\nbut your derived table class does not override this function"));
3842
3843 return false;
3844 }
3845
3846 bool wxGridTableBase::DeleteCols( size_t WXUNUSED(pos),
3847 size_t WXUNUSED(numCols) )
3848 {
3849 wxFAIL_MSG( wxT("Called grid table class function DeleteCols\nbut your derived table class does not override this function"));
3850
3851 return false;
3852 }
3853
3854 wxString wxGridTableBase::GetRowLabelValue( int row )
3855 {
3856 wxString s;
3857
3858 // RD: Starting the rows at zero confuses users,
3859 // no matter how much it makes sense to us geeks.
3860 s << row + 1;
3861
3862 return s;
3863 }
3864
3865 wxString wxGridTableBase::GetColLabelValue( int col )
3866 {
3867 // default col labels are:
3868 // cols 0 to 25 : A-Z
3869 // cols 26 to 675 : AA-ZZ
3870 // etc.
3871
3872 wxString s;
3873 unsigned int i, n;
3874 for ( n = 1; ; n++ )
3875 {
3876 s += (wxChar) (_T('A') + (wxChar)(col % 26));
3877 col = col / 26 - 1;
3878 if ( col < 0 )
3879 break;
3880 }
3881
3882 // reverse the string...
3883 wxString s2;
3884 for ( i = 0; i < n; i++ )
3885 {
3886 s2 += s[n - i - 1];
3887 }
3888
3889 return s2;
3890 }
3891
3892 wxString wxGridTableBase::GetTypeName( int WXUNUSED(row), int WXUNUSED(col) )
3893 {
3894 return wxGRID_VALUE_STRING;
3895 }
3896
3897 bool wxGridTableBase::CanGetValueAs( int WXUNUSED(row), int WXUNUSED(col),
3898 const wxString& typeName )
3899 {
3900 return typeName == wxGRID_VALUE_STRING;
3901 }
3902
3903 bool wxGridTableBase::CanSetValueAs( int row, int col, const wxString& typeName )
3904 {
3905 return CanGetValueAs(row, col, typeName);
3906 }
3907
3908 long wxGridTableBase::GetValueAsLong( int WXUNUSED(row), int WXUNUSED(col) )
3909 {
3910 return 0;
3911 }
3912
3913 double wxGridTableBase::GetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col) )
3914 {
3915 return 0.0;
3916 }
3917
3918 bool wxGridTableBase::GetValueAsBool( int WXUNUSED(row), int WXUNUSED(col) )
3919 {
3920 return false;
3921 }
3922
3923 void wxGridTableBase::SetValueAsLong( int WXUNUSED(row), int WXUNUSED(col),
3924 long WXUNUSED(value) )
3925 {
3926 }
3927
3928 void wxGridTableBase::SetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col),
3929 double WXUNUSED(value) )
3930 {
3931 }
3932
3933 void wxGridTableBase::SetValueAsBool( int WXUNUSED(row), int WXUNUSED(col),
3934 bool WXUNUSED(value) )
3935 {
3936 }
3937
3938 void* wxGridTableBase::GetValueAsCustom( int WXUNUSED(row), int WXUNUSED(col),
3939 const wxString& WXUNUSED(typeName) )
3940 {
3941 return NULL;
3942 }
3943
3944 void wxGridTableBase::SetValueAsCustom( int WXUNUSED(row), int WXUNUSED(col),
3945 const wxString& WXUNUSED(typeName),
3946 void* WXUNUSED(value) )
3947 {
3948 }
3949
3950 //////////////////////////////////////////////////////////////////////
3951 //
3952 // Message class for the grid table to send requests and notifications
3953 // to the grid view
3954 //
3955
3956 wxGridTableMessage::wxGridTableMessage()
3957 {
3958 m_table = NULL;
3959 m_id = -1;
3960 m_comInt1 = -1;
3961 m_comInt2 = -1;
3962 }
3963
3964 wxGridTableMessage::wxGridTableMessage( wxGridTableBase *table, int id,
3965 int commandInt1, int commandInt2 )
3966 {
3967 m_table = table;
3968 m_id = id;
3969 m_comInt1 = commandInt1;
3970 m_comInt2 = commandInt2;
3971 }
3972
3973 //////////////////////////////////////////////////////////////////////
3974 //
3975 // A basic grid table for string data. An object of this class will
3976 // created by wxGrid if you don't specify an alternative table class.
3977 //
3978
3979 WX_DEFINE_OBJARRAY(wxGridStringArray)
3980
3981 IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable, wxGridTableBase )
3982
3983 wxGridStringTable::wxGridStringTable()
3984 : wxGridTableBase()
3985 {
3986 }
3987
3988 wxGridStringTable::wxGridStringTable( int numRows, int numCols )
3989 : wxGridTableBase()
3990 {
3991 m_data.Alloc( numRows );
3992
3993 wxArrayString sa;
3994 sa.Alloc( numCols );
3995 sa.Add( wxEmptyString, numCols );
3996
3997 m_data.Add( sa, numRows );
3998 }
3999
4000 wxGridStringTable::~wxGridStringTable()
4001 {
4002 }
4003
4004 int wxGridStringTable::GetNumberRows()
4005 {
4006 return m_data.GetCount();
4007 }
4008
4009 int wxGridStringTable::GetNumberCols()
4010 {
4011 if ( m_data.GetCount() > 0 )
4012 return m_data[0].GetCount();
4013 else
4014 return 0;
4015 }
4016
4017 wxString wxGridStringTable::GetValue( int row, int col )
4018 {
4019 wxCHECK_MSG( (row < GetNumberRows()) && (col < GetNumberCols()),
4020 wxEmptyString,
4021 _T("invalid row or column index in wxGridStringTable") );
4022
4023 return m_data[row][col];
4024 }
4025
4026 void wxGridStringTable::SetValue( int row, int col, const wxString& value )
4027 {
4028 wxCHECK_RET( (row < GetNumberRows()) && (col < GetNumberCols()),
4029 _T("invalid row or column index in wxGridStringTable") );
4030
4031 m_data[row][col] = value;
4032 }
4033
4034 void wxGridStringTable::Clear()
4035 {
4036 int row, col;
4037 int numRows, numCols;
4038
4039 numRows = m_data.GetCount();
4040 if ( numRows > 0 )
4041 {
4042 numCols = m_data[0].GetCount();
4043
4044 for ( row = 0; row < numRows; row++ )
4045 {
4046 for ( col = 0; col < numCols; col++ )
4047 {
4048 m_data[row][col] = wxEmptyString;
4049 }
4050 }
4051 }
4052 }
4053
4054 bool wxGridStringTable::InsertRows( size_t pos, size_t numRows )
4055 {
4056 size_t curNumRows = m_data.GetCount();
4057 size_t curNumCols = ( curNumRows > 0 ? m_data[0].GetCount() :
4058 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4059
4060 if ( pos >= curNumRows )
4061 {
4062 return AppendRows( numRows );
4063 }
4064
4065 wxArrayString sa;
4066 sa.Alloc( curNumCols );
4067 sa.Add( wxEmptyString, curNumCols );
4068 m_data.Insert( sa, pos, numRows );
4069
4070 if ( GetView() )
4071 {
4072 wxGridTableMessage msg( this,
4073 wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
4074 pos,
4075 numRows );
4076
4077 GetView()->ProcessTableMessage( msg );
4078 }
4079
4080 return true;
4081 }
4082
4083 bool wxGridStringTable::AppendRows( size_t numRows )
4084 {
4085 size_t curNumRows = m_data.GetCount();
4086 size_t curNumCols = ( curNumRows > 0
4087 ? m_data[0].GetCount()
4088 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4089
4090 wxArrayString sa;
4091 if ( curNumCols > 0 )
4092 {
4093 sa.Alloc( curNumCols );
4094 sa.Add( wxEmptyString, curNumCols );
4095 }
4096
4097 m_data.Add( sa, numRows );
4098
4099 if ( GetView() )
4100 {
4101 wxGridTableMessage msg( this,
4102 wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
4103 numRows );
4104
4105 GetView()->ProcessTableMessage( msg );
4106 }
4107
4108 return true;
4109 }
4110
4111 bool wxGridStringTable::DeleteRows( size_t pos, size_t numRows )
4112 {
4113 size_t curNumRows = m_data.GetCount();
4114
4115 if ( pos >= curNumRows )
4116 {
4117 wxFAIL_MSG( wxString::Format
4118 (
4119 wxT("Called wxGridStringTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
4120 (unsigned long)pos,
4121 (unsigned long)numRows,
4122 (unsigned long)curNumRows
4123 ) );
4124
4125 return false;
4126 }
4127
4128 if ( numRows > curNumRows - pos )
4129 {
4130 numRows = curNumRows - pos;
4131 }
4132
4133 if ( numRows >= curNumRows )
4134 {
4135 m_data.Clear();
4136 }
4137 else
4138 {
4139 m_data.RemoveAt( pos, numRows );
4140 }
4141
4142 if ( GetView() )
4143 {
4144 wxGridTableMessage msg( this,
4145 wxGRIDTABLE_NOTIFY_ROWS_DELETED,
4146 pos,
4147 numRows );
4148
4149 GetView()->ProcessTableMessage( msg );
4150 }
4151
4152 return true;
4153 }
4154
4155 bool wxGridStringTable::InsertCols( size_t pos, size_t numCols )
4156 {
4157 size_t row, col;
4158
4159 size_t curNumRows = m_data.GetCount();
4160 size_t curNumCols = ( curNumRows > 0
4161 ? m_data[0].GetCount()
4162 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4163
4164 if ( pos >= curNumCols )
4165 {
4166 return AppendCols( numCols );
4167 }
4168
4169 if ( !m_colLabels.IsEmpty() )
4170 {
4171 m_colLabels.Insert( wxEmptyString, pos, numCols );
4172
4173 size_t i;
4174 for ( i = pos; i < pos + numCols; i++ )
4175 m_colLabels[i] = wxGridTableBase::GetColLabelValue( i );
4176 }
4177
4178 for ( row = 0; row < curNumRows; row++ )
4179 {
4180 for ( col = pos; col < pos + numCols; col++ )
4181 {
4182 m_data[row].Insert( wxEmptyString, col );
4183 }
4184 }
4185
4186 if ( GetView() )
4187 {
4188 wxGridTableMessage msg( this,
4189 wxGRIDTABLE_NOTIFY_COLS_INSERTED,
4190 pos,
4191 numCols );
4192
4193 GetView()->ProcessTableMessage( msg );
4194 }
4195
4196 return true;
4197 }
4198
4199 bool wxGridStringTable::AppendCols( size_t numCols )
4200 {
4201 size_t row;
4202
4203 size_t curNumRows = m_data.GetCount();
4204
4205 for ( row = 0; row < curNumRows; row++ )
4206 {
4207 m_data[row].Add( wxEmptyString, numCols );
4208 }
4209
4210 if ( GetView() )
4211 {
4212 wxGridTableMessage msg( this,
4213 wxGRIDTABLE_NOTIFY_COLS_APPENDED,
4214 numCols );
4215
4216 GetView()->ProcessTableMessage( msg );
4217 }
4218
4219 return true;
4220 }
4221
4222 bool wxGridStringTable::DeleteCols( size_t pos, size_t numCols )
4223 {
4224 size_t row;
4225
4226 size_t curNumRows = m_data.GetCount();
4227 size_t curNumCols = ( curNumRows > 0 ? m_data[0].GetCount() :
4228 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
4229
4230 if ( pos >= curNumCols )
4231 {
4232 wxFAIL_MSG( wxString::Format
4233 (
4234 wxT("Called wxGridStringTable::DeleteCols(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu cols"),
4235 (unsigned long)pos,
4236 (unsigned long)numCols,
4237 (unsigned long)curNumCols
4238 ) );
4239 return false;
4240 }
4241
4242 int colID;
4243 if ( GetView() )
4244 colID = GetView()->GetColAt( pos );
4245 else
4246 colID = pos;
4247
4248 if ( numCols > curNumCols - colID )
4249 {
4250 numCols = curNumCols - colID;
4251 }
4252
4253 if ( !m_colLabels.IsEmpty() )
4254 {
4255 // m_colLabels stores just as many elements as it needs, e.g. if only
4256 // the label of the first column had been set it would have only one
4257 // element and not numCols, so account for it
4258 int nToRm = m_colLabels.size() - colID;
4259 if ( nToRm > 0 )
4260 m_colLabels.RemoveAt( colID, nToRm );
4261 }
4262
4263 for ( row = 0; row < curNumRows; row++ )
4264 {
4265 if ( numCols >= curNumCols )
4266 {
4267 m_data[row].Clear();
4268 }
4269 else
4270 {
4271 m_data[row].RemoveAt( colID, numCols );
4272 }
4273 }
4274
4275 if ( GetView() )
4276 {
4277 wxGridTableMessage msg( this,
4278 wxGRIDTABLE_NOTIFY_COLS_DELETED,
4279 pos,
4280 numCols );
4281
4282 GetView()->ProcessTableMessage( msg );
4283 }
4284
4285 return true;
4286 }
4287
4288 wxString wxGridStringTable::GetRowLabelValue( int row )
4289 {
4290 if ( row > (int)(m_rowLabels.GetCount()) - 1 )
4291 {
4292 // using default label
4293 //
4294 return wxGridTableBase::GetRowLabelValue( row );
4295 }
4296 else
4297 {
4298 return m_rowLabels[row];
4299 }
4300 }
4301
4302 wxString wxGridStringTable::GetColLabelValue( int col )
4303 {
4304 if ( col > (int)(m_colLabels.GetCount()) - 1 )
4305 {
4306 // using default label
4307 //
4308 return wxGridTableBase::GetColLabelValue( col );
4309 }
4310 else
4311 {
4312 return m_colLabels[col];
4313 }
4314 }
4315
4316 void wxGridStringTable::SetRowLabelValue( int row, const wxString& value )
4317 {
4318 if ( row > (int)(m_rowLabels.GetCount()) - 1 )
4319 {
4320 int n = m_rowLabels.GetCount();
4321 int i;
4322
4323 for ( i = n; i <= row; i++ )
4324 {
4325 m_rowLabels.Add( wxGridTableBase::GetRowLabelValue(i) );
4326 }
4327 }
4328
4329 m_rowLabels[row] = value;
4330 }
4331
4332 void wxGridStringTable::SetColLabelValue( int col, const wxString& value )
4333 {
4334 if ( col > (int)(m_colLabels.GetCount()) - 1 )
4335 {
4336 int n = m_colLabels.GetCount();
4337 int i;
4338
4339 for ( i = n; i <= col; i++ )
4340 {
4341 m_colLabels.Add( wxGridTableBase::GetColLabelValue(i) );
4342 }
4343 }
4344
4345 m_colLabels[col] = value;
4346 }
4347
4348
4349 //////////////////////////////////////////////////////////////////////
4350 //////////////////////////////////////////////////////////////////////
4351
4352 BEGIN_EVENT_TABLE(wxGridSubwindow, wxWindow)
4353 EVT_MOUSE_CAPTURE_LOST(wxGridSubwindow::OnMouseCaptureLost)
4354 END_EVENT_TABLE()
4355
4356 void wxGridSubwindow::OnMouseCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
4357 {
4358 m_owner->CancelMouseCapture();
4359 }
4360
4361 BEGIN_EVENT_TABLE( wxGridRowLabelWindow, wxGridSubwindow )
4362 EVT_PAINT( wxGridRowLabelWindow::OnPaint )
4363 EVT_MOUSEWHEEL( wxGridRowLabelWindow::OnMouseWheel )
4364 EVT_MOUSE_EVENTS( wxGridRowLabelWindow::OnMouseEvent )
4365 END_EVENT_TABLE()
4366
4367 void wxGridRowLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
4368 {
4369 wxPaintDC dc(this);
4370
4371 // NO - don't do this because it will set both the x and y origin
4372 // coords to match the parent scrolled window and we just want to
4373 // set the y coord - MB
4374 //
4375 // m_owner->PrepareDC( dc );
4376
4377 int x, y;
4378 m_owner->CalcUnscrolledPosition( 0, 0, &x, &y );
4379 wxPoint pt = dc.GetDeviceOrigin();
4380 dc.SetDeviceOrigin( pt.x, pt.y-y );
4381
4382 wxArrayInt rows = m_owner->CalcRowLabelsExposed( GetUpdateRegion() );
4383 m_owner->DrawRowLabels( dc, rows );
4384 }
4385
4386 void wxGridRowLabelWindow::OnMouseEvent( wxMouseEvent& event )
4387 {
4388 m_owner->ProcessRowLabelMouseEvent( event );
4389 }
4390
4391 void wxGridRowLabelWindow::OnMouseWheel( wxMouseEvent& event )
4392 {
4393 if (!m_owner->GetEventHandler()->ProcessEvent( event ))
4394 event.Skip();
4395 }
4396
4397 //////////////////////////////////////////////////////////////////////
4398
4399 BEGIN_EVENT_TABLE( wxGridColLabelWindow, wxGridSubwindow )
4400 EVT_PAINT( wxGridColLabelWindow::OnPaint )
4401 EVT_MOUSEWHEEL( wxGridColLabelWindow::OnMouseWheel )
4402 EVT_MOUSE_EVENTS( wxGridColLabelWindow::OnMouseEvent )
4403 END_EVENT_TABLE()
4404
4405 void wxGridColLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
4406 {
4407 wxPaintDC dc(this);
4408
4409 // NO - don't do this because it will set both the x and y origin
4410 // coords to match the parent scrolled window and we just want to
4411 // set the x coord - MB
4412 //
4413 // m_owner->PrepareDC( dc );
4414
4415 int x, y;
4416 m_owner->CalcUnscrolledPosition( 0, 0, &x, &y );
4417 wxPoint pt = dc.GetDeviceOrigin();
4418 if (GetLayoutDirection() == wxLayout_RightToLeft)
4419 dc.SetDeviceOrigin( pt.x+x, pt.y );
4420 else
4421 dc.SetDeviceOrigin( pt.x-x, pt.y );
4422
4423 wxArrayInt cols = m_owner->CalcColLabelsExposed( GetUpdateRegion() );
4424 m_owner->DrawColLabels( dc, cols );
4425 }
4426
4427 void wxGridColLabelWindow::OnMouseEvent( wxMouseEvent& event )
4428 {
4429 m_owner->ProcessColLabelMouseEvent( event );
4430 }
4431
4432 void wxGridColLabelWindow::OnMouseWheel( wxMouseEvent& event )
4433 {
4434 if (!m_owner->GetEventHandler()->ProcessEvent( event ))
4435 event.Skip();
4436 }
4437
4438 //////////////////////////////////////////////////////////////////////
4439
4440 BEGIN_EVENT_TABLE( wxGridCornerLabelWindow, wxGridSubwindow )
4441 EVT_MOUSEWHEEL( wxGridCornerLabelWindow::OnMouseWheel )
4442 EVT_MOUSE_EVENTS( wxGridCornerLabelWindow::OnMouseEvent )
4443 EVT_PAINT( wxGridCornerLabelWindow::OnPaint )
4444 END_EVENT_TABLE()
4445
4446 void wxGridCornerLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
4447 {
4448 wxPaintDC dc(this);
4449
4450 m_owner->DrawCornerLabel(dc);
4451 }
4452
4453 void wxGridCornerLabelWindow::OnMouseEvent( wxMouseEvent& event )
4454 {
4455 m_owner->ProcessCornerLabelMouseEvent( event );
4456 }
4457
4458 void wxGridCornerLabelWindow::OnMouseWheel( wxMouseEvent& event )
4459 {
4460 if (!m_owner->GetEventHandler()->ProcessEvent(event))
4461 event.Skip();
4462 }
4463
4464 //////////////////////////////////////////////////////////////////////
4465
4466 BEGIN_EVENT_TABLE( wxGridWindow, wxGridSubwindow )
4467 EVT_PAINT( wxGridWindow::OnPaint )
4468 EVT_MOUSEWHEEL( wxGridWindow::OnMouseWheel )
4469 EVT_MOUSE_EVENTS( wxGridWindow::OnMouseEvent )
4470 EVT_KEY_DOWN( wxGridWindow::OnKeyDown )
4471 EVT_KEY_UP( wxGridWindow::OnKeyUp )
4472 EVT_CHAR( wxGridWindow::OnChar )
4473 EVT_SET_FOCUS( wxGridWindow::OnFocus )
4474 EVT_KILL_FOCUS( wxGridWindow::OnFocus )
4475 EVT_ERASE_BACKGROUND( wxGridWindow::OnEraseBackground )
4476 END_EVENT_TABLE()
4477
4478 void wxGridWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
4479 {
4480 wxPaintDC dc( this );
4481 m_owner->PrepareDC( dc );
4482 wxRegion reg = GetUpdateRegion();
4483 wxGridCellCoordsArray dirtyCells = m_owner->CalcCellsExposed( reg );
4484 m_owner->DrawGridCellArea( dc, dirtyCells );
4485
4486 m_owner->DrawGridSpace( dc );
4487
4488 m_owner->DrawAllGridLines( dc, reg );
4489
4490 m_owner->DrawHighlight( dc, dirtyCells );
4491 }
4492
4493 void wxGridWindow::ScrollWindow( int dx, int dy, const wxRect *rect )
4494 {
4495 wxWindow::ScrollWindow( dx, dy, rect );
4496 m_owner->GetGridRowLabelWindow()->ScrollWindow( 0, dy, rect );
4497 m_owner->GetGridColLabelWindow()->ScrollWindow( dx, 0, rect );
4498 }
4499
4500 void wxGridWindow::OnMouseEvent( wxMouseEvent& event )
4501 {
4502 if (event.ButtonDown(wxMOUSE_BTN_LEFT) && FindFocus() != this)
4503 SetFocus();
4504
4505 m_owner->ProcessGridCellMouseEvent( event );
4506 }
4507
4508 void wxGridWindow::OnMouseWheel( wxMouseEvent& event )
4509 {
4510 if (!m_owner->GetEventHandler()->ProcessEvent( event ))
4511 event.Skip();
4512 }
4513
4514 // This seems to be required for wxMotif/wxGTK otherwise the mouse
4515 // cursor must be in the cell edit control to get key events
4516 //
4517 void wxGridWindow::OnKeyDown( wxKeyEvent& event )
4518 {
4519 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4520 event.Skip();
4521 }
4522
4523 void wxGridWindow::OnKeyUp( wxKeyEvent& event )
4524 {
4525 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4526 event.Skip();
4527 }
4528
4529 void wxGridWindow::OnChar( wxKeyEvent& event )
4530 {
4531 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4532 event.Skip();
4533 }
4534
4535 void wxGridWindow::OnEraseBackground( wxEraseEvent& WXUNUSED(event) )
4536 {
4537 }
4538
4539 void wxGridWindow::OnFocus(wxFocusEvent& event)
4540 {
4541 // and if we have any selection, it has to be repainted, because it
4542 // uses different colour when the grid is not focused:
4543 if ( m_owner->IsSelection() )
4544 {
4545 Refresh();
4546 }
4547 else
4548 {
4549 // NB: Note that this code is in "else" branch only because the other
4550 // branch refreshes everything and so there's no point in calling
4551 // Refresh() again, *not* because it should only be done if
4552 // !IsSelection(). If the above code is ever optimized to refresh
4553 // only selected area, this needs to be moved out of the "else"
4554 // branch so that it's always executed.
4555
4556 // current cell cursor {dis,re}appears on focus change:
4557 const wxGridCellCoords cursorCoords(m_owner->GetGridCursorRow(),
4558 m_owner->GetGridCursorCol());
4559 const wxRect cursor =
4560 m_owner->BlockToDeviceRect(cursorCoords, cursorCoords);
4561 Refresh(true, &cursor);
4562 }
4563
4564 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4565 event.Skip();
4566 }
4567
4568 #define internalXToCol(x) XToCol(x, true)
4569 #define internalYToRow(y) YToRow(y, true)
4570
4571 /////////////////////////////////////////////////////////////////////
4572
4573 #if wxUSE_EXTENDED_RTTI
4574 WX_DEFINE_FLAGS( wxGridStyle )
4575
4576 wxBEGIN_FLAGS( wxGridStyle )
4577 // new style border flags, we put them first to
4578 // use them for streaming out
4579 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
4580 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
4581 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
4582 wxFLAGS_MEMBER(wxBORDER_RAISED)
4583 wxFLAGS_MEMBER(wxBORDER_STATIC)
4584 wxFLAGS_MEMBER(wxBORDER_NONE)
4585
4586 // old style border flags
4587 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
4588 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
4589 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
4590 wxFLAGS_MEMBER(wxRAISED_BORDER)
4591 wxFLAGS_MEMBER(wxSTATIC_BORDER)
4592 wxFLAGS_MEMBER(wxBORDER)
4593
4594 // standard window styles
4595 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
4596 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
4597 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
4598 wxFLAGS_MEMBER(wxWANTS_CHARS)
4599 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
4600 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB)
4601 wxFLAGS_MEMBER(wxVSCROLL)
4602 wxFLAGS_MEMBER(wxHSCROLL)
4603
4604 wxEND_FLAGS( wxGridStyle )
4605
4606 IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid, wxScrolledWindow,"wx/grid.h")
4607
4608 wxBEGIN_PROPERTIES_TABLE(wxGrid)
4609 wxHIDE_PROPERTY( Children )
4610 wxPROPERTY_FLAGS( WindowStyle , wxGridStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
4611 wxEND_PROPERTIES_TABLE()
4612
4613 wxBEGIN_HANDLERS_TABLE(wxGrid)
4614 wxEND_HANDLERS_TABLE()
4615
4616 wxCONSTRUCTOR_5( wxGrid , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
4617
4618 /*
4619 TODO : Expose more information of a list's layout, etc. via appropriate objects (e.g., NotebookPageInfo)
4620 */
4621 #else
4622 IMPLEMENT_DYNAMIC_CLASS( wxGrid, wxScrolledWindow )
4623 #endif
4624
4625 BEGIN_EVENT_TABLE( wxGrid, wxScrolledWindow )
4626 EVT_PAINT( wxGrid::OnPaint )
4627 EVT_SIZE( wxGrid::OnSize )
4628 EVT_KEY_DOWN( wxGrid::OnKeyDown )
4629 EVT_KEY_UP( wxGrid::OnKeyUp )
4630 EVT_CHAR ( wxGrid::OnChar )
4631 EVT_ERASE_BACKGROUND( wxGrid::OnEraseBackground )
4632 END_EVENT_TABLE()
4633
4634 bool wxGrid::Create(wxWindow *parent, wxWindowID id,
4635 const wxPoint& pos, const wxSize& size,
4636 long style, const wxString& name)
4637 {
4638 if (!wxScrolledWindow::Create(parent, id, pos, size,
4639 style | wxWANTS_CHARS, name))
4640 return false;
4641
4642 m_colMinWidths = wxLongToLongHashMap(GRID_HASH_SIZE);
4643 m_rowMinHeights = wxLongToLongHashMap(GRID_HASH_SIZE);
4644
4645 Create();
4646 SetInitialSize(size);
4647 SetScrollRate(m_scrollLineX, m_scrollLineY);
4648 CalcDimensions();
4649
4650 return true;
4651 }
4652
4653 wxGrid::~wxGrid()
4654 {
4655 if ( m_winCapture )
4656 m_winCapture->ReleaseMouse();
4657
4658 // Ensure that the editor control is destroyed before the grid is,
4659 // otherwise we crash later when the editor tries to do something with the
4660 // half destroyed grid
4661 HideCellEditControl();
4662
4663 // Must do this or ~wxScrollHelper will pop the wrong event handler
4664 SetTargetWindow(this);
4665 ClearAttrCache();
4666 wxSafeDecRef(m_defaultCellAttr);
4667
4668 #ifdef DEBUG_ATTR_CACHE
4669 size_t total = gs_nAttrCacheHits + gs_nAttrCacheMisses;
4670 wxPrintf(_T("wxGrid attribute cache statistics: "
4671 "total: %u, hits: %u (%u%%)\n"),
4672 total, gs_nAttrCacheHits,
4673 total ? (gs_nAttrCacheHits*100) / total : 0);
4674 #endif
4675
4676 // if we own the table, just delete it, otherwise at least don't leave it
4677 // with dangling view pointer
4678 if ( m_ownTable )
4679 delete m_table;
4680 else if ( m_table && m_table->GetView() == this )
4681 m_table->SetView(NULL);
4682
4683 delete m_typeRegistry;
4684 delete m_selection;
4685 }
4686
4687 //
4688 // ----- internal init and update functions
4689 //
4690
4691 // NOTE: If using the default visual attributes works everywhere then this can
4692 // be removed as well as the #else cases below.
4693 #define _USE_VISATTR 0
4694
4695 void wxGrid::Create()
4696 {
4697 // create the type registry
4698 m_typeRegistry = new wxGridTypeRegistry;
4699
4700 m_cellEditCtrlEnabled = false;
4701
4702 m_defaultCellAttr = new wxGridCellAttr();
4703
4704 // Set default cell attributes
4705 m_defaultCellAttr->SetDefAttr(m_defaultCellAttr);
4706 m_defaultCellAttr->SetKind(wxGridCellAttr::Default);
4707 m_defaultCellAttr->SetFont(GetFont());
4708 m_defaultCellAttr->SetAlignment(wxALIGN_LEFT, wxALIGN_TOP);
4709 m_defaultCellAttr->SetRenderer(new wxGridCellStringRenderer);
4710 m_defaultCellAttr->SetEditor(new wxGridCellTextEditor);
4711
4712 #if _USE_VISATTR
4713 wxVisualAttributes gva = wxListBox::GetClassDefaultAttributes();
4714 wxVisualAttributes lva = wxPanel::GetClassDefaultAttributes();
4715
4716 m_defaultCellAttr->SetTextColour(gva.colFg);
4717 m_defaultCellAttr->SetBackgroundColour(gva.colBg);
4718
4719 #else
4720 m_defaultCellAttr->SetTextColour(
4721 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
4722 m_defaultCellAttr->SetBackgroundColour(
4723 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
4724 #endif
4725
4726 m_numRows = 0;
4727 m_numCols = 0;
4728 m_currentCellCoords = wxGridNoCellCoords;
4729
4730 // subwindow components that make up the wxGrid
4731 m_rowLabelWin = new wxGridRowLabelWindow(this);
4732 CreateColumnWindow();
4733 m_cornerLabelWin = new wxGridCornerLabelWindow(this);
4734 m_gridWin = new wxGridWindow( this );
4735
4736 SetTargetWindow( m_gridWin );
4737
4738 #if _USE_VISATTR
4739 wxColour gfg = gva.colFg;
4740 wxColour gbg = gva.colBg;
4741 wxColour lfg = lva.colFg;
4742 wxColour lbg = lva.colBg;
4743 #else
4744 wxColour gfg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
4745 wxColour gbg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
4746 wxColour lfg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
4747 wxColour lbg = wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE );
4748 #endif
4749
4750 m_cornerLabelWin->SetOwnForegroundColour(lfg);
4751 m_cornerLabelWin->SetOwnBackgroundColour(lbg);
4752 m_rowLabelWin->SetOwnForegroundColour(lfg);
4753 m_rowLabelWin->SetOwnBackgroundColour(lbg);
4754 m_colWindow->SetOwnForegroundColour(lfg);
4755 m_colWindow->SetOwnBackgroundColour(lbg);
4756
4757 m_gridWin->SetOwnForegroundColour(gfg);
4758 m_gridWin->SetOwnBackgroundColour(gbg);
4759
4760 m_labelBackgroundColour = m_rowLabelWin->GetBackgroundColour();
4761 m_labelTextColour = m_rowLabelWin->GetForegroundColour();
4762
4763 // now that we have the grid window, use its font to compute the default
4764 // row height
4765 m_defaultRowHeight = m_gridWin->GetCharHeight();
4766 #if defined(__WXMOTIF__) || defined(__WXGTK__) // see also text ctrl sizing in ShowCellEditControl()
4767 m_defaultRowHeight += 8;
4768 #else
4769 m_defaultRowHeight += 4;
4770 #endif
4771
4772 }
4773
4774 void wxGrid::CreateColumnWindow()
4775 {
4776 if ( m_useNativeHeader )
4777 {
4778 m_colWindow = new wxGridHeaderCtrl(this);
4779 m_colLabelHeight = m_colWindow->GetBestSize().y;
4780 }
4781 else // draw labels ourselves
4782 {
4783 m_colWindow = new wxGridColLabelWindow(this);
4784 m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT;
4785 }
4786 }
4787
4788 bool wxGrid::CreateGrid( int numRows, int numCols,
4789 wxGridSelectionModes selmode )
4790 {
4791 wxCHECK_MSG( !m_created,
4792 false,
4793 wxT("wxGrid::CreateGrid or wxGrid::SetTable called more than once") );
4794
4795 return SetTable(new wxGridStringTable(numRows, numCols), true, selmode);
4796 }
4797
4798 void wxGrid::SetSelectionMode(wxGridSelectionModes selmode)
4799 {
4800 wxCHECK_RET( m_created,
4801 wxT("Called wxGrid::SetSelectionMode() before calling CreateGrid()") );
4802
4803 m_selection->SetSelectionMode( selmode );
4804 }
4805
4806 wxGrid::wxGridSelectionModes wxGrid::GetSelectionMode() const
4807 {
4808 wxCHECK_MSG( m_created, wxGridSelectCells,
4809 wxT("Called wxGrid::GetSelectionMode() before calling CreateGrid()") );
4810
4811 return m_selection->GetSelectionMode();
4812 }
4813
4814 bool
4815 wxGrid::SetTable(wxGridTableBase *table,
4816 bool takeOwnership,
4817 wxGrid::wxGridSelectionModes selmode )
4818 {
4819 bool checkSelection = false;
4820 if ( m_created )
4821 {
4822 // stop all processing
4823 m_created = false;
4824
4825 if (m_table)
4826 {
4827 m_table->SetView(0);
4828 if( m_ownTable )
4829 delete m_table;
4830 m_table = NULL;
4831 }
4832
4833 delete m_selection;
4834 m_selection = NULL;
4835
4836 m_ownTable = false;
4837 m_numRows = 0;
4838 m_numCols = 0;
4839 checkSelection = true;
4840
4841 // kill row and column size arrays
4842 m_colWidths.Empty();
4843 m_colRights.Empty();
4844 m_rowHeights.Empty();
4845 m_rowBottoms.Empty();
4846 }
4847
4848 if (table)
4849 {
4850 m_numRows = table->GetNumberRows();
4851 m_numCols = table->GetNumberCols();
4852
4853 if ( m_useNativeHeader )
4854 GetGridColHeader()->SetColumnCount(m_numCols);
4855
4856 m_table = table;
4857 m_table->SetView( this );
4858 m_ownTable = takeOwnership;
4859 m_selection = new wxGridSelection( this, selmode );
4860 if (checkSelection)
4861 {
4862 // If the newly set table is smaller than the
4863 // original one current cell and selection regions
4864 // might be invalid,
4865 m_selectedBlockCorner = wxGridNoCellCoords;
4866 m_currentCellCoords =
4867 wxGridCellCoords(wxMin(m_numRows, m_currentCellCoords.GetRow()),
4868 wxMin(m_numCols, m_currentCellCoords.GetCol()));
4869 if (m_selectedBlockTopLeft.GetRow() >= m_numRows ||
4870 m_selectedBlockTopLeft.GetCol() >= m_numCols)
4871 {
4872 m_selectedBlockTopLeft = wxGridNoCellCoords;
4873 m_selectedBlockBottomRight = wxGridNoCellCoords;
4874 }
4875 else
4876 m_selectedBlockBottomRight =
4877 wxGridCellCoords(wxMin(m_numRows,
4878 m_selectedBlockBottomRight.GetRow()),
4879 wxMin(m_numCols,
4880 m_selectedBlockBottomRight.GetCol()));
4881 }
4882 CalcDimensions();
4883
4884 m_created = true;
4885 }
4886
4887 return m_created;
4888 }
4889
4890 void wxGrid::Init()
4891 {
4892 m_created = false;
4893
4894 m_cornerLabelWin = NULL;
4895 m_rowLabelWin = NULL;
4896 m_colWindow = NULL;
4897 m_gridWin = NULL;
4898
4899 m_table = NULL;
4900 m_ownTable = false;
4901
4902 m_selection = NULL;
4903 m_defaultCellAttr = NULL;
4904 m_typeRegistry = NULL;
4905 m_winCapture = NULL;
4906
4907 m_rowLabelWidth = WXGRID_DEFAULT_ROW_LABEL_WIDTH;
4908 m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT;
4909
4910 // init attr cache
4911 m_attrCache.row = -1;
4912 m_attrCache.col = -1;
4913 m_attrCache.attr = NULL;
4914
4915 m_labelFont = GetFont();
4916 m_labelFont.SetWeight( wxBOLD );
4917
4918 m_rowLabelHorizAlign = wxALIGN_CENTRE;
4919 m_rowLabelVertAlign = wxALIGN_CENTRE;
4920
4921 m_colLabelHorizAlign = wxALIGN_CENTRE;
4922 m_colLabelVertAlign = wxALIGN_CENTRE;
4923 m_colLabelTextOrientation = wxHORIZONTAL;
4924
4925 m_defaultColWidth = WXGRID_DEFAULT_COL_WIDTH;
4926 m_defaultRowHeight = 0; // this will be initialized after creation
4927
4928 m_minAcceptableColWidth = WXGRID_MIN_COL_WIDTH;
4929 m_minAcceptableRowHeight = WXGRID_MIN_ROW_HEIGHT;
4930
4931 m_gridLineColour = wxColour( 192,192,192 );
4932 m_gridLinesEnabled = true;
4933 m_gridLinesClipHorz =
4934 m_gridLinesClipVert = true;
4935 m_cellHighlightColour = *wxBLACK;
4936 m_cellHighlightPenWidth = 2;
4937 m_cellHighlightROPenWidth = 1;
4938
4939 m_canDragColMove = false;
4940
4941 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
4942 m_winCapture = NULL;
4943 m_canDragRowSize = true;
4944 m_canDragColSize = true;
4945 m_canDragGridSize = true;
4946 m_canDragCell = false;
4947 m_dragLastPos = -1;
4948 m_dragRowOrCol = -1;
4949 m_isDragging = false;
4950 m_startDragPos = wxDefaultPosition;
4951
4952 m_sortCol = wxNOT_FOUND;
4953 m_sortIsAscending = true;
4954
4955 m_useNativeHeader =
4956 m_nativeColumnLabels = false;
4957
4958 m_waitForSlowClick = false;
4959
4960 m_rowResizeCursor = wxCursor( wxCURSOR_SIZENS );
4961 m_colResizeCursor = wxCursor( wxCURSOR_SIZEWE );
4962
4963 m_currentCellCoords = wxGridNoCellCoords;
4964
4965 m_selectedBlockTopLeft =
4966 m_selectedBlockBottomRight =
4967 m_selectedBlockCorner = wxGridNoCellCoords;
4968
4969 m_selectionBackground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
4970 m_selectionForeground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
4971
4972 m_editable = true; // default for whole grid
4973
4974 m_inOnKeyDown = false;
4975 m_batchCount = 0;
4976
4977 m_extraWidth =
4978 m_extraHeight = 0;
4979
4980 m_scrollLineX = GRID_SCROLL_LINE_X;
4981 m_scrollLineY = GRID_SCROLL_LINE_Y;
4982 }
4983
4984 // ----------------------------------------------------------------------------
4985 // the idea is to call these functions only when necessary because they create
4986 // quite big arrays which eat memory mostly unnecessary - in particular, if
4987 // default widths/heights are used for all rows/columns, we may not use these
4988 // arrays at all
4989 //
4990 // with some extra code, it should be possible to only store the widths/heights
4991 // different from default ones (resulting in space savings for huge grids) but
4992 // this is not done currently
4993 // ----------------------------------------------------------------------------
4994
4995 void wxGrid::InitRowHeights()
4996 {
4997 m_rowHeights.Empty();
4998 m_rowBottoms.Empty();
4999
5000 m_rowHeights.Alloc( m_numRows );
5001 m_rowBottoms.Alloc( m_numRows );
5002
5003 m_rowHeights.Add( m_defaultRowHeight, m_numRows );
5004
5005 int rowBottom = 0;
5006 for ( int i = 0; i < m_numRows; i++ )
5007 {
5008 rowBottom += m_defaultRowHeight;
5009 m_rowBottoms.Add( rowBottom );
5010 }
5011 }
5012
5013 void wxGrid::InitColWidths()
5014 {
5015 m_colWidths.Empty();
5016 m_colRights.Empty();
5017
5018 m_colWidths.Alloc( m_numCols );
5019 m_colRights.Alloc( m_numCols );
5020
5021 m_colWidths.Add( m_defaultColWidth, m_numCols );
5022
5023 for ( int i = 0; i < m_numCols; i++ )
5024 {
5025 int colRight = ( GetColPos( i ) + 1 ) * m_defaultColWidth;
5026 m_colRights.Add( colRight );
5027 }
5028 }
5029
5030 int wxGrid::GetColWidth(int col) const
5031 {
5032 return m_colWidths.IsEmpty() ? m_defaultColWidth : m_colWidths[col];
5033 }
5034
5035 int wxGrid::GetColLeft(int col) const
5036 {
5037 return m_colRights.IsEmpty() ? GetColPos( col ) * m_defaultColWidth
5038 : m_colRights[col] - m_colWidths[col];
5039 }
5040
5041 int wxGrid::GetColRight(int col) const
5042 {
5043 return m_colRights.IsEmpty() ? (GetColPos( col ) + 1) * m_defaultColWidth
5044 : m_colRights[col];
5045 }
5046
5047 int wxGrid::GetRowHeight(int row) const
5048 {
5049 return m_rowHeights.IsEmpty() ? m_defaultRowHeight : m_rowHeights[row];
5050 }
5051
5052 int wxGrid::GetRowTop(int row) const
5053 {
5054 return m_rowBottoms.IsEmpty() ? row * m_defaultRowHeight
5055 : m_rowBottoms[row] - m_rowHeights[row];
5056 }
5057
5058 int wxGrid::GetRowBottom(int row) const
5059 {
5060 return m_rowBottoms.IsEmpty() ? (row + 1) * m_defaultRowHeight
5061 : m_rowBottoms[row];
5062 }
5063
5064 void wxGrid::CalcDimensions()
5065 {
5066 // compute the size of the scrollable area
5067 int w = m_numCols > 0 ? GetColRight(GetColAt(m_numCols - 1)) : 0;
5068 int h = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
5069
5070 w += m_extraWidth;
5071 h += m_extraHeight;
5072
5073 // take into account editor if shown
5074 if ( IsCellEditControlShown() )
5075 {
5076 int w2, h2;
5077 int r = m_currentCellCoords.GetRow();
5078 int c = m_currentCellCoords.GetCol();
5079 int x = GetColLeft(c);
5080 int y = GetRowTop(r);
5081
5082 // how big is the editor
5083 wxGridCellAttr* attr = GetCellAttr(r, c);
5084 wxGridCellEditor* editor = attr->GetEditor(this, r, c);
5085 editor->GetControl()->GetSize(&w2, &h2);
5086 w2 += x;
5087 h2 += y;
5088 if ( w2 > w )
5089 w = w2;
5090 if ( h2 > h )
5091 h = h2;
5092 editor->DecRef();
5093 attr->DecRef();
5094 }
5095
5096 // preserve (more or less) the previous position
5097 int x, y;
5098 GetViewStart( &x, &y );
5099
5100 // ensure the position is valid for the new scroll ranges
5101 if ( x >= w )
5102 x = wxMax( w - 1, 0 );
5103 if ( y >= h )
5104 y = wxMax( h - 1, 0 );
5105
5106 // update the virtual size and refresh the scrollbars to reflect it
5107 m_gridWin->SetVirtualSize(w, h);
5108 Scroll(x, y);
5109 AdjustScrollbars();
5110
5111 // if our OnSize() hadn't been called (it would if we have scrollbars), we
5112 // still must reposition the children
5113 CalcWindowSizes();
5114 }
5115
5116 wxSize wxGrid::GetSizeAvailableForScrollTarget(const wxSize& size)
5117 {
5118 wxSize sizeGridWin(size);
5119 sizeGridWin.x -= m_rowLabelWidth;
5120 sizeGridWin.y -= m_colLabelHeight;
5121
5122 return sizeGridWin;
5123 }
5124
5125 void wxGrid::CalcWindowSizes()
5126 {
5127 // escape if the window is has not been fully created yet
5128
5129 if ( m_cornerLabelWin == NULL )
5130 return;
5131
5132 int cw, ch;
5133 GetClientSize( &cw, &ch );
5134
5135 // the grid may be too small to have enough space for the labels yet, don't
5136 // size the windows to negative sizes in this case
5137 int gw = cw - m_rowLabelWidth;
5138 int gh = ch - m_colLabelHeight;
5139 if (gw < 0)
5140 gw = 0;
5141 if (gh < 0)
5142 gh = 0;
5143
5144 if ( m_cornerLabelWin && m_cornerLabelWin->IsShown() )
5145 m_cornerLabelWin->SetSize( 0, 0, m_rowLabelWidth, m_colLabelHeight );
5146
5147 if ( m_colWindow && m_colWindow->IsShown() )
5148 m_colWindow->SetSize( m_rowLabelWidth, 0, gw, m_colLabelHeight );
5149
5150 if ( m_rowLabelWin && m_rowLabelWin->IsShown() )
5151 m_rowLabelWin->SetSize( 0, m_colLabelHeight, m_rowLabelWidth, gh );
5152
5153 if ( m_gridWin && m_gridWin->IsShown() )
5154 m_gridWin->SetSize( m_rowLabelWidth, m_colLabelHeight, gw, gh );
5155 }
5156
5157 // this is called when the grid table sends a message
5158 // to indicate that it has been redimensioned
5159 //
5160 bool wxGrid::Redimension( wxGridTableMessage& msg )
5161 {
5162 int i;
5163 bool result = false;
5164
5165 // Clear the attribute cache as the attribute might refer to a different
5166 // cell than stored in the cache after adding/removing rows/columns.
5167 ClearAttrCache();
5168
5169 // By the same reasoning, the editor should be dismissed if columns are
5170 // added or removed. And for consistency, it should IMHO always be
5171 // removed, not only if the cell "underneath" it actually changes.
5172 // For now, I intentionally do not save the editor's content as the
5173 // cell it might want to save that stuff to might no longer exist.
5174 HideCellEditControl();
5175
5176 switch ( msg.GetId() )
5177 {
5178 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
5179 {
5180 size_t pos = msg.GetCommandInt();
5181 int numRows = msg.GetCommandInt2();
5182
5183 m_numRows += numRows;
5184
5185 if ( !m_rowHeights.IsEmpty() )
5186 {
5187 m_rowHeights.Insert( m_defaultRowHeight, pos, numRows );
5188 m_rowBottoms.Insert( 0, pos, numRows );
5189
5190 int bottom = 0;
5191 if ( pos > 0 )
5192 bottom = m_rowBottoms[pos - 1];
5193
5194 for ( i = pos; i < m_numRows; i++ )
5195 {
5196 bottom += m_rowHeights[i];
5197 m_rowBottoms[i] = bottom;
5198 }
5199 }
5200
5201 if ( m_currentCellCoords == wxGridNoCellCoords )
5202 {
5203 // if we have just inserted cols into an empty grid the current
5204 // cell will be undefined...
5205 //
5206 SetCurrentCell( 0, 0 );
5207 }
5208
5209 if ( m_selection )
5210 m_selection->UpdateRows( pos, numRows );
5211 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
5212 if (attrProvider)
5213 attrProvider->UpdateAttrRows( pos, numRows );
5214
5215 if ( !GetBatchCount() )
5216 {
5217 CalcDimensions();
5218 m_rowLabelWin->Refresh();
5219 }
5220 }
5221 result = true;
5222 break;
5223
5224 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
5225 {
5226 int numRows = msg.GetCommandInt();
5227 int oldNumRows = m_numRows;
5228 m_numRows += numRows;
5229
5230 if ( !m_rowHeights.IsEmpty() )
5231 {
5232 m_rowHeights.Add( m_defaultRowHeight, numRows );
5233 m_rowBottoms.Add( 0, numRows );
5234
5235 int bottom = 0;
5236 if ( oldNumRows > 0 )
5237 bottom = m_rowBottoms[oldNumRows - 1];
5238
5239 for ( i = oldNumRows; i < m_numRows; i++ )
5240 {
5241 bottom += m_rowHeights[i];
5242 m_rowBottoms[i] = bottom;
5243 }
5244 }
5245
5246 if ( m_currentCellCoords == wxGridNoCellCoords )
5247 {
5248 // if we have just inserted cols into an empty grid the current
5249 // cell will be undefined...
5250 //
5251 SetCurrentCell( 0, 0 );
5252 }
5253
5254 if ( !GetBatchCount() )
5255 {
5256 CalcDimensions();
5257 m_rowLabelWin->Refresh();
5258 }
5259 }
5260 result = true;
5261 break;
5262
5263 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
5264 {
5265 size_t pos = msg.GetCommandInt();
5266 int numRows = msg.GetCommandInt2();
5267 m_numRows -= numRows;
5268
5269 if ( !m_rowHeights.IsEmpty() )
5270 {
5271 m_rowHeights.RemoveAt( pos, numRows );
5272 m_rowBottoms.RemoveAt( pos, numRows );
5273
5274 int h = 0;
5275 for ( i = 0; i < m_numRows; i++ )
5276 {
5277 h += m_rowHeights[i];
5278 m_rowBottoms[i] = h;
5279 }
5280 }
5281
5282 if ( !m_numRows )
5283 {
5284 m_currentCellCoords = wxGridNoCellCoords;
5285 }
5286 else
5287 {
5288 if ( m_currentCellCoords.GetRow() >= m_numRows )
5289 m_currentCellCoords.Set( 0, 0 );
5290 }
5291
5292 if ( m_selection )
5293 m_selection->UpdateRows( pos, -((int)numRows) );
5294 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
5295 if (attrProvider)
5296 {
5297 attrProvider->UpdateAttrRows( pos, -((int)numRows) );
5298
5299 // ifdef'd out following patch from Paul Gammans
5300 #if 0
5301 // No need to touch column attributes, unless we
5302 // removed _all_ rows, in this case, we remove
5303 // all column attributes.
5304 // I hate to do this here, but the
5305 // needed data is not available inside UpdateAttrRows.
5306 if ( !GetNumberRows() )
5307 attrProvider->UpdateAttrCols( 0, -GetNumberCols() );
5308 #endif
5309 }
5310
5311 if ( !GetBatchCount() )
5312 {
5313 CalcDimensions();
5314 m_rowLabelWin->Refresh();
5315 }
5316 }
5317 result = true;
5318 break;
5319
5320 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
5321 {
5322 size_t pos = msg.GetCommandInt();
5323 int numCols = msg.GetCommandInt2();
5324 m_numCols += numCols;
5325
5326 if ( m_useNativeHeader )
5327 GetGridColHeader()->SetColumnCount(m_numCols);
5328
5329 if ( !m_colAt.IsEmpty() )
5330 {
5331 //Shift the column IDs
5332 int i;
5333 for ( i = 0; i < m_numCols - numCols; i++ )
5334 {
5335 if ( m_colAt[i] >= (int)pos )
5336 m_colAt[i] += numCols;
5337 }
5338
5339 m_colAt.Insert( pos, pos, numCols );
5340
5341 //Set the new columns' positions
5342 for ( i = pos + 1; i < (int)pos + numCols; i++ )
5343 {
5344 m_colAt[i] = i;
5345 }
5346 }
5347
5348 if ( !m_colWidths.IsEmpty() )
5349 {
5350 m_colWidths.Insert( m_defaultColWidth, pos, numCols );
5351 m_colRights.Insert( 0, pos, numCols );
5352
5353 int right = 0;
5354 if ( pos > 0 )
5355 right = m_colRights[GetColAt( pos - 1 )];
5356
5357 int colPos;
5358 for ( colPos = pos; colPos < m_numCols; colPos++ )
5359 {
5360 i = GetColAt( colPos );
5361
5362 right += m_colWidths[i];
5363 m_colRights[i] = right;
5364 }
5365 }
5366
5367 if ( m_currentCellCoords == wxGridNoCellCoords )
5368 {
5369 // if we have just inserted cols into an empty grid the current
5370 // cell will be undefined...
5371 //
5372 SetCurrentCell( 0, 0 );
5373 }
5374
5375 if ( m_selection )
5376 m_selection->UpdateCols( pos, numCols );
5377 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
5378 if (attrProvider)
5379 attrProvider->UpdateAttrCols( pos, numCols );
5380 if ( !GetBatchCount() )
5381 {
5382 CalcDimensions();
5383 m_colWindow->Refresh();
5384 }
5385 }
5386 result = true;
5387 break;
5388
5389 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
5390 {
5391 int numCols = msg.GetCommandInt();
5392 int oldNumCols = m_numCols;
5393 m_numCols += numCols;
5394 if ( m_useNativeHeader )
5395 GetGridColHeader()->SetColumnCount(m_numCols);
5396
5397 if ( !m_colAt.IsEmpty() )
5398 {
5399 m_colAt.Add( 0, numCols );
5400
5401 //Set the new columns' positions
5402 int i;
5403 for ( i = oldNumCols; i < m_numCols; i++ )
5404 {
5405 m_colAt[i] = i;
5406 }
5407 }
5408
5409 if ( !m_colWidths.IsEmpty() )
5410 {
5411 m_colWidths.Add( m_defaultColWidth, numCols );
5412 m_colRights.Add( 0, numCols );
5413
5414 int right = 0;
5415 if ( oldNumCols > 0 )
5416 right = m_colRights[GetColAt( oldNumCols - 1 )];
5417
5418 int colPos;
5419 for ( colPos = oldNumCols; colPos < m_numCols; colPos++ )
5420 {
5421 i = GetColAt( colPos );
5422
5423 right += m_colWidths[i];
5424 m_colRights[i] = right;
5425 }
5426 }
5427
5428 if ( m_currentCellCoords == wxGridNoCellCoords )
5429 {
5430 // if we have just inserted cols into an empty grid the current
5431 // cell will be undefined...
5432 //
5433 SetCurrentCell( 0, 0 );
5434 }
5435 if ( !GetBatchCount() )
5436 {
5437 CalcDimensions();
5438 m_colWindow->Refresh();
5439 }
5440 }
5441 result = true;
5442 break;
5443
5444 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
5445 {
5446 size_t pos = msg.GetCommandInt();
5447 int numCols = msg.GetCommandInt2();
5448 m_numCols -= numCols;
5449 if ( m_useNativeHeader )
5450 GetGridColHeader()->SetColumnCount(m_numCols);
5451
5452 if ( !m_colAt.IsEmpty() )
5453 {
5454 int colID = GetColAt( pos );
5455
5456 m_colAt.RemoveAt( pos, numCols );
5457
5458 //Shift the column IDs
5459 int colPos;
5460 for ( colPos = 0; colPos < m_numCols; colPos++ )
5461 {
5462 if ( m_colAt[colPos] > colID )
5463 m_colAt[colPos] -= numCols;
5464 }
5465 }
5466
5467 if ( !m_colWidths.IsEmpty() )
5468 {
5469 m_colWidths.RemoveAt( pos, numCols );
5470 m_colRights.RemoveAt( pos, numCols );
5471
5472 int w = 0;
5473 int colPos;
5474 for ( colPos = 0; colPos < m_numCols; colPos++ )
5475 {
5476 i = GetColAt( colPos );
5477
5478 w += m_colWidths[i];
5479 m_colRights[i] = w;
5480 }
5481 }
5482
5483 if ( !m_numCols )
5484 {
5485 m_currentCellCoords = wxGridNoCellCoords;
5486 }
5487 else
5488 {
5489 if ( m_currentCellCoords.GetCol() >= m_numCols )
5490 m_currentCellCoords.Set( 0, 0 );
5491 }
5492
5493 if ( m_selection )
5494 m_selection->UpdateCols( pos, -((int)numCols) );
5495 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
5496 if (attrProvider)
5497 {
5498 attrProvider->UpdateAttrCols( pos, -((int)numCols) );
5499
5500 // ifdef'd out following patch from Paul Gammans
5501 #if 0
5502 // No need to touch row attributes, unless we
5503 // removed _all_ columns, in this case, we remove
5504 // all row attributes.
5505 // I hate to do this here, but the
5506 // needed data is not available inside UpdateAttrCols.
5507 if ( !GetNumberCols() )
5508 attrProvider->UpdateAttrRows( 0, -GetNumberRows() );
5509 #endif
5510 }
5511
5512 if ( !GetBatchCount() )
5513 {
5514 CalcDimensions();
5515 m_colWindow->Refresh();
5516 }
5517 }
5518 result = true;
5519 break;
5520 }
5521
5522 if (result && !GetBatchCount() )
5523 m_gridWin->Refresh();
5524
5525 return result;
5526 }
5527
5528 wxArrayInt wxGrid::CalcRowLabelsExposed( const wxRegion& reg ) const
5529 {
5530 wxRegionIterator iter( reg );
5531 wxRect r;
5532
5533 wxArrayInt rowlabels;
5534
5535 int top, bottom;
5536 while ( iter )
5537 {
5538 r = iter.GetRect();
5539
5540 // TODO: remove this when we can...
5541 // There is a bug in wxMotif that gives garbage update
5542 // rectangles if you jump-scroll a long way by clicking the
5543 // scrollbar with middle button. This is a work-around
5544 //
5545 #if defined(__WXMOTIF__)
5546 int cw, ch;
5547 m_gridWin->GetClientSize( &cw, &ch );
5548 if ( r.GetTop() > ch )
5549 r.SetTop( 0 );
5550 r.SetBottom( wxMin( r.GetBottom(), ch ) );
5551 #endif
5552
5553 // logical bounds of update region
5554 //
5555 int dummy;
5556 CalcUnscrolledPosition( 0, r.GetTop(), &dummy, &top );
5557 CalcUnscrolledPosition( 0, r.GetBottom(), &dummy, &bottom );
5558
5559 // find the row labels within these bounds
5560 //
5561 int row;
5562 for ( row = internalYToRow(top); row < m_numRows; row++ )
5563 {
5564 if ( GetRowBottom(row) < top )
5565 continue;
5566
5567 if ( GetRowTop(row) > bottom )
5568 break;
5569
5570 rowlabels.Add( row );
5571 }
5572
5573 ++iter;
5574 }
5575
5576 return rowlabels;
5577 }
5578
5579 wxArrayInt wxGrid::CalcColLabelsExposed( const wxRegion& reg ) const
5580 {
5581 wxRegionIterator iter( reg );
5582 wxRect r;
5583
5584 wxArrayInt colLabels;
5585
5586 int left, right;
5587 while ( iter )
5588 {
5589 r = iter.GetRect();
5590
5591 // TODO: remove this when we can...
5592 // There is a bug in wxMotif that gives garbage update
5593 // rectangles if you jump-scroll a long way by clicking the
5594 // scrollbar with middle button. This is a work-around
5595 //
5596 #if defined(__WXMOTIF__)
5597 int cw, ch;
5598 m_gridWin->GetClientSize( &cw, &ch );
5599 if ( r.GetLeft() > cw )
5600 r.SetLeft( 0 );
5601 r.SetRight( wxMin( r.GetRight(), cw ) );
5602 #endif
5603
5604 // logical bounds of update region
5605 //
5606 int dummy;
5607 CalcUnscrolledPosition( r.GetLeft(), 0, &left, &dummy );
5608 CalcUnscrolledPosition( r.GetRight(), 0, &right, &dummy );
5609
5610 // find the cells within these bounds
5611 //
5612 int col;
5613 int colPos;
5614 for ( colPos = GetColPos( internalXToCol(left) ); colPos < m_numCols; colPos++ )
5615 {
5616 col = GetColAt( colPos );
5617
5618 if ( GetColRight(col) < left )
5619 continue;
5620
5621 if ( GetColLeft(col) > right )
5622 break;
5623
5624 colLabels.Add( col );
5625 }
5626
5627 ++iter;
5628 }
5629
5630 return colLabels;
5631 }
5632
5633 wxGridCellCoordsArray wxGrid::CalcCellsExposed( const wxRegion& reg ) const
5634 {
5635 wxRegionIterator iter( reg );
5636 wxRect r;
5637
5638 wxGridCellCoordsArray cellsExposed;
5639
5640 int left, top, right, bottom;
5641 while ( iter )
5642 {
5643 r = iter.GetRect();
5644
5645 // TODO: remove this when we can...
5646 // There is a bug in wxMotif that gives garbage update
5647 // rectangles if you jump-scroll a long way by clicking the
5648 // scrollbar with middle button. This is a work-around
5649 //
5650 #if defined(__WXMOTIF__)
5651 int cw, ch;
5652 m_gridWin->GetClientSize( &cw, &ch );
5653 if ( r.GetTop() > ch ) r.SetTop( 0 );
5654 if ( r.GetLeft() > cw ) r.SetLeft( 0 );
5655 r.SetRight( wxMin( r.GetRight(), cw ) );
5656 r.SetBottom( wxMin( r.GetBottom(), ch ) );
5657 #endif
5658
5659 // logical bounds of update region
5660 //
5661 CalcUnscrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
5662 CalcUnscrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
5663
5664 // find the cells within these bounds
5665 wxArrayInt cols;
5666 for ( int row = internalYToRow(top); row < m_numRows; row++ )
5667 {
5668 if ( GetRowBottom(row) <= top )
5669 continue;
5670
5671 if ( GetRowTop(row) > bottom )
5672 break;
5673
5674 // add all dirty cells in this row: notice that the columns which
5675 // are dirty don't depend on the row so we compute them only once
5676 // for the first dirty row and then reuse for all the next ones
5677 if ( cols.empty() )
5678 {
5679 // do determine the dirty columns
5680 for ( int pos = XToPos(left); pos <= XToPos(right); pos++ )
5681 cols.push_back(GetColAt(pos));
5682
5683 // if there are no dirty columns at all, nothing to do
5684 if ( cols.empty() )
5685 break;
5686 }
5687
5688 const size_t count = cols.size();
5689 for ( size_t n = 0; n < count; n++ )
5690 cellsExposed.Add(wxGridCellCoords(row, cols[n]));
5691 }
5692
5693 ++iter;
5694 }
5695
5696 return cellsExposed;
5697 }
5698
5699
5700 void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event )
5701 {
5702 int x, y, row;
5703 wxPoint pos( event.GetPosition() );
5704 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5705
5706 if ( event.Dragging() )
5707 {
5708 if (!m_isDragging)
5709 {
5710 m_isDragging = true;
5711 m_rowLabelWin->CaptureMouse();
5712 }
5713
5714 if ( event.LeftIsDown() )
5715 {
5716 switch ( m_cursorMode )
5717 {
5718 case WXGRID_CURSOR_RESIZE_ROW:
5719 {
5720 int cw, ch, left, dummy;
5721 m_gridWin->GetClientSize( &cw, &ch );
5722 CalcUnscrolledPosition( 0, 0, &left, &dummy );
5723
5724 wxClientDC dc( m_gridWin );
5725 PrepareDC( dc );
5726 y = wxMax( y,
5727 GetRowTop(m_dragRowOrCol) +
5728 GetRowMinimalHeight(m_dragRowOrCol) );
5729 dc.SetLogicalFunction(wxINVERT);
5730 if ( m_dragLastPos >= 0 )
5731 {
5732 dc.DrawLine( left, m_dragLastPos, left+cw, m_dragLastPos );
5733 }
5734 dc.DrawLine( left, y, left+cw, y );
5735 m_dragLastPos = y;
5736 }
5737 break;
5738
5739 case WXGRID_CURSOR_SELECT_ROW:
5740 {
5741 if ( (row = YToRow( y )) >= 0 )
5742 {
5743 if ( m_selection )
5744 m_selection->SelectRow(row, event);
5745 }
5746 }
5747 break;
5748
5749 // default label to suppress warnings about "enumeration value
5750 // 'xxx' not handled in switch
5751 default:
5752 break;
5753 }
5754 }
5755 return;
5756 }
5757
5758 if ( m_isDragging && (event.Entering() || event.Leaving()) )
5759 return;
5760
5761 if (m_isDragging)
5762 {
5763 if (m_rowLabelWin->HasCapture())
5764 m_rowLabelWin->ReleaseMouse();
5765 m_isDragging = false;
5766 }
5767
5768 // ------------ Entering or leaving the window
5769 //
5770 if ( event.Entering() || event.Leaving() )
5771 {
5772 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5773 }
5774
5775 // ------------ Left button pressed
5776 //
5777 else if ( event.LeftDown() )
5778 {
5779 // don't send a label click event for a hit on the
5780 // edge of the row label - this is probably the user
5781 // wanting to resize the row
5782 //
5783 if ( YToEdgeOfRow(y) < 0 )
5784 {
5785 row = YToRow(y);
5786 if ( row >= 0 &&
5787 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, row, -1, event ) )
5788 {
5789 if ( !event.ShiftDown() && !event.CmdDown() )
5790 ClearSelection();
5791 if ( m_selection )
5792 {
5793 if ( event.ShiftDown() )
5794 {
5795 m_selection->SelectBlock
5796 (
5797 m_currentCellCoords.GetRow(), 0,
5798 row, GetNumberCols() - 1,
5799 event
5800 );
5801 }
5802 else
5803 {
5804 m_selection->SelectRow(row, event);
5805 }
5806 }
5807
5808 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW, m_rowLabelWin);
5809 }
5810 }
5811 else
5812 {
5813 // starting to drag-resize a row
5814 if ( CanDragRowSize() )
5815 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin);
5816 }
5817 }
5818
5819 // ------------ Left double click
5820 //
5821 else if (event.LeftDClick() )
5822 {
5823 row = YToEdgeOfRow(y);
5824 if ( row < 0 )
5825 {
5826 row = YToRow(y);
5827 if ( row >=0 &&
5828 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, row, -1, event ) )
5829 {
5830 // no default action at the moment
5831 }
5832 }
5833 else
5834 {
5835 // adjust row height depending on label text
5836 AutoSizeRowLabelSize( row );
5837
5838 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
5839 m_dragLastPos = -1;
5840 }
5841 }
5842
5843 // ------------ Left button released
5844 //
5845 else if ( event.LeftUp() )
5846 {
5847 if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
5848 {
5849 DoEndDragResizeRow();
5850
5851 // Note: we are ending the event *after* doing
5852 // default processing in this case
5853 //
5854 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
5855 }
5856
5857 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5858 m_dragLastPos = -1;
5859 }
5860
5861 // ------------ Right button down
5862 //
5863 else if ( event.RightDown() )
5864 {
5865 row = YToRow(y);
5866 if ( row >=0 &&
5867 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, row, -1, event ) )
5868 {
5869 // no default action at the moment
5870 }
5871 }
5872
5873 // ------------ Right double click
5874 //
5875 else if ( event.RightDClick() )
5876 {
5877 row = YToRow(y);
5878 if ( row >= 0 &&
5879 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, row, -1, event ) )
5880 {
5881 // no default action at the moment
5882 }
5883 }
5884
5885 // ------------ No buttons down and mouse moving
5886 //
5887 else if ( event.Moving() )
5888 {
5889 m_dragRowOrCol = YToEdgeOfRow( y );
5890 if ( m_dragRowOrCol >= 0 )
5891 {
5892 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
5893 {
5894 // don't capture the mouse yet
5895 if ( CanDragRowSize() )
5896 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin, false);
5897 }
5898 }
5899 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
5900 {
5901 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin, false);
5902 }
5903 }
5904 }
5905
5906 void wxGrid::UpdateColumnSortingIndicator(int col)
5907 {
5908 wxCHECK_RET( col != wxNOT_FOUND, "invalid column index" );
5909
5910 if ( m_useNativeHeader )
5911 GetGridColHeader()->UpdateColumn(col);
5912 else if ( m_nativeColumnLabels )
5913 m_colWindow->Refresh();
5914 //else: sorting indicator display not yet implemented in grid version
5915 }
5916
5917 void wxGrid::SetSortingColumn(int col, bool ascending)
5918 {
5919 if ( col == m_sortCol )
5920 {
5921 // we are already using this column for sorting (or not sorting at all)
5922 // but we might still change the sorting order, check for it
5923 if ( m_sortCol != wxNOT_FOUND && ascending != m_sortIsAscending )
5924 {
5925 m_sortIsAscending = ascending;
5926
5927 UpdateColumnSortingIndicator(m_sortCol);
5928 }
5929 }
5930 else // we're changing the column used for sorting
5931 {
5932 const int sortColOld = m_sortCol;
5933
5934 // change it before updating the column as we want GetSortingColumn()
5935 // to return the correct new value
5936 m_sortCol = col;
5937
5938 if ( sortColOld != wxNOT_FOUND )
5939 UpdateColumnSortingIndicator(sortColOld);
5940
5941 if ( m_sortCol != wxNOT_FOUND )
5942 {
5943 m_sortIsAscending = ascending;
5944 UpdateColumnSortingIndicator(m_sortCol);
5945 }
5946 }
5947 }
5948
5949 void wxGrid::DoColHeaderClick(int col)
5950 {
5951 // we consider that the grid was resorted if this event is processed and
5952 // not vetoed
5953 if ( SendEvent(wxEVT_GRID_COL_SORT, -1, col) == 1 )
5954 {
5955 SetSortingColumn(col, IsSortingBy(col) ? !m_sortIsAscending : true);
5956 Refresh();
5957 }
5958 }
5959
5960 void wxGrid::DoStartResizeCol(int col)
5961 {
5962 m_dragRowOrCol = col;
5963 m_dragLastPos = -1;
5964 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol));
5965 }
5966
5967 void wxGrid::DoUpdateResizeCol(int x)
5968 {
5969 int cw, ch, dummy, top;
5970 m_gridWin->GetClientSize( &cw, &ch );
5971 CalcUnscrolledPosition( 0, 0, &dummy, &top );
5972
5973 wxClientDC dc( m_gridWin );
5974 PrepareDC( dc );
5975
5976 x = wxMax( x, GetColLeft(m_dragRowOrCol) + GetColMinimalWidth(m_dragRowOrCol));
5977 dc.SetLogicalFunction(wxINVERT);
5978 if ( m_dragLastPos >= 0 )
5979 {
5980 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
5981 }
5982 dc.DrawLine( x, top, x, top + ch );
5983 m_dragLastPos = x;
5984 }
5985
5986 void wxGrid::DoUpdateResizeColWidth(int w)
5987 {
5988 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol) + w);
5989 }
5990
5991 void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event )
5992 {
5993 int x, y;
5994 wxPoint pos( event.GetPosition() );
5995 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5996
5997 int col = XToCol(x);
5998 if ( event.Dragging() )
5999 {
6000 if (!m_isDragging)
6001 {
6002 m_isDragging = true;
6003 GetColLabelWindow()->CaptureMouse();
6004
6005 if ( m_cursorMode == WXGRID_CURSOR_MOVE_COL && col != -1 )
6006 DoStartMoveCol(col);
6007 }
6008
6009 if ( event.LeftIsDown() )
6010 {
6011 switch ( m_cursorMode )
6012 {
6013 case WXGRID_CURSOR_RESIZE_COL:
6014 DoUpdateResizeCol(x);
6015 break;
6016
6017 case WXGRID_CURSOR_SELECT_COL:
6018 {
6019 if ( col != -1 )
6020 {
6021 if ( m_selection )
6022 m_selection->SelectCol(col, event);
6023 }
6024 }
6025 break;
6026
6027 case WXGRID_CURSOR_MOVE_COL:
6028 {
6029 int posNew = XToPos(x);
6030 int colNew = GetColAt(posNew);
6031
6032 // determine the position of the drop marker
6033 int markerX;
6034 if ( x >= GetColLeft(colNew) + (GetColWidth(colNew) / 2) )
6035 markerX = GetColRight(colNew);
6036 else
6037 markerX = GetColLeft(colNew);
6038
6039 if ( markerX != m_dragLastPos )
6040 {
6041 wxClientDC dc( GetColLabelWindow() );
6042 DoPrepareDC(dc);
6043
6044 int cw, ch;
6045 GetColLabelWindow()->GetClientSize( &cw, &ch );
6046
6047 markerX++;
6048
6049 //Clean up the last indicator
6050 if ( m_dragLastPos >= 0 )
6051 {
6052 wxPen pen( GetColLabelWindow()->GetBackgroundColour(), 2 );
6053 dc.SetPen(pen);
6054 dc.DrawLine( m_dragLastPos + 1, 0, m_dragLastPos + 1, ch );
6055 dc.SetPen(wxNullPen);
6056
6057 if ( XToCol( m_dragLastPos ) != -1 )
6058 DrawColLabel( dc, XToCol( m_dragLastPos ) );
6059 }
6060
6061 const wxColour *color;
6062 //Moving to the same place? Don't draw a marker
6063 if ( colNew == m_dragRowOrCol )
6064 color = wxLIGHT_GREY;
6065 else
6066 color = wxBLUE;
6067
6068 //Draw the marker
6069 wxPen pen( *color, 2 );
6070 dc.SetPen(pen);
6071
6072 dc.DrawLine( markerX, 0, markerX, ch );
6073
6074 dc.SetPen(wxNullPen);
6075
6076 m_dragLastPos = markerX - 1;
6077 }
6078 }
6079 break;
6080
6081 // default label to suppress warnings about "enumeration value
6082 // 'xxx' not handled in switch
6083 default:
6084 break;
6085 }
6086 }
6087 return;
6088 }
6089
6090 if ( m_isDragging && (event.Entering() || event.Leaving()) )
6091 return;
6092
6093 if (m_isDragging)
6094 {
6095 if (GetColLabelWindow()->HasCapture())
6096 GetColLabelWindow()->ReleaseMouse();
6097 m_isDragging = false;
6098 }
6099
6100 // ------------ Entering or leaving the window
6101 //
6102 if ( event.Entering() || event.Leaving() )
6103 {
6104 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6105 }
6106
6107 // ------------ Left button pressed
6108 //
6109 else if ( event.LeftDown() )
6110 {
6111 // don't send a label click event for a hit on the
6112 // edge of the col label - this is probably the user
6113 // wanting to resize the col
6114 //
6115 if ( XToEdgeOfCol(x) < 0 )
6116 {
6117 if ( col >= 0 &&
6118 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, col, event ) )
6119 {
6120 if ( m_canDragColMove )
6121 {
6122 //Show button as pressed
6123 wxClientDC dc( GetColLabelWindow() );
6124 int colLeft = GetColLeft( col );
6125 int colRight = GetColRight( col ) - 1;
6126 dc.SetPen( wxPen( GetColLabelWindow()->GetBackgroundColour(), 1 ) );
6127 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight-1 );
6128 dc.DrawLine( colLeft, 1, colRight, 1 );
6129
6130 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL, GetColLabelWindow());
6131 }
6132 else
6133 {
6134 if ( !event.ShiftDown() && !event.CmdDown() )
6135 ClearSelection();
6136 if ( m_selection )
6137 {
6138 if ( event.ShiftDown() )
6139 {
6140 m_selection->SelectBlock
6141 (
6142 0, m_currentCellCoords.GetCol(),
6143 GetNumberRows() - 1, col,
6144 event
6145 );
6146 }
6147 else
6148 {
6149 m_selection->SelectCol(col, event);
6150 }
6151 }
6152
6153 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL, GetColLabelWindow());
6154 }
6155 }
6156 }
6157 else
6158 {
6159 // starting to drag-resize a col
6160 //
6161 if ( CanDragColSize() )
6162 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow());
6163 }
6164 }
6165
6166 // ------------ Left double click
6167 //
6168 if ( event.LeftDClick() )
6169 {
6170 const int colEdge = XToEdgeOfCol(x);
6171 if ( colEdge == -1 )
6172 {
6173 if ( col >= 0 &&
6174 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, col, event ) )
6175 {
6176 // no default action at the moment
6177 }
6178 }
6179 else
6180 {
6181 // adjust column width depending on label text
6182 AutoSizeColLabelSize( colEdge );
6183
6184 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6185 m_dragLastPos = -1;
6186 }
6187 }
6188
6189 // ------------ Left button released
6190 //
6191 else if ( event.LeftUp() )
6192 {
6193 switch ( m_cursorMode )
6194 {
6195 case WXGRID_CURSOR_RESIZE_COL:
6196 DoEndDragResizeCol();
6197 break;
6198
6199 case WXGRID_CURSOR_MOVE_COL:
6200 if ( m_dragLastPos == -1 || col == m_dragRowOrCol )
6201 {
6202 // the column didn't actually move anywhere
6203 if ( col != -1 )
6204 DoColHeaderClick(col);
6205 m_colWindow->Refresh(); // "unpress" the column
6206 }
6207 else
6208 {
6209 DoEndMoveCol(XToPos(x));
6210 }
6211 break;
6212
6213 case WXGRID_CURSOR_SELECT_COL:
6214 case WXGRID_CURSOR_SELECT_CELL:
6215 case WXGRID_CURSOR_RESIZE_ROW:
6216 case WXGRID_CURSOR_SELECT_ROW:
6217 if ( col != -1 )
6218 DoColHeaderClick(col);
6219 break;
6220 }
6221
6222 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6223 m_dragLastPos = -1;
6224 }
6225
6226 // ------------ Right button down
6227 //
6228 else if ( event.RightDown() )
6229 {
6230 if ( col >= 0 &&
6231 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, col, event ) )
6232 {
6233 // no default action at the moment
6234 }
6235 }
6236
6237 // ------------ Right double click
6238 //
6239 else if ( event.RightDClick() )
6240 {
6241 if ( col >= 0 &&
6242 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, col, event ) )
6243 {
6244 // no default action at the moment
6245 }
6246 }
6247
6248 // ------------ No buttons down and mouse moving
6249 //
6250 else if ( event.Moving() )
6251 {
6252 m_dragRowOrCol = XToEdgeOfCol( x );
6253 if ( m_dragRowOrCol >= 0 )
6254 {
6255 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6256 {
6257 // don't capture the cursor yet
6258 if ( CanDragColSize() )
6259 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow(), false);
6260 }
6261 }
6262 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
6263 {
6264 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow(), false);
6265 }
6266 }
6267 }
6268
6269 void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent& event )
6270 {
6271 if ( event.LeftDown() )
6272 {
6273 // indicate corner label by having both row and
6274 // col args == -1
6275 //
6276 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, -1, event ) )
6277 {
6278 SelectAll();
6279 }
6280 }
6281 else if ( event.LeftDClick() )
6282 {
6283 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, -1, event );
6284 }
6285 else if ( event.RightDown() )
6286 {
6287 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, -1, event ) )
6288 {
6289 // no default action at the moment
6290 }
6291 }
6292 else if ( event.RightDClick() )
6293 {
6294 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, -1, event ) )
6295 {
6296 // no default action at the moment
6297 }
6298 }
6299 }
6300
6301 void wxGrid::CancelMouseCapture()
6302 {
6303 // cancel operation currently in progress, whatever it is
6304 if ( m_winCapture )
6305 {
6306 m_isDragging = false;
6307 m_startDragPos = wxDefaultPosition;
6308
6309 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
6310 m_winCapture->SetCursor( *wxSTANDARD_CURSOR );
6311 m_winCapture = NULL;
6312
6313 // remove traces of whatever we drew on screen
6314 Refresh();
6315 }
6316 }
6317
6318 void wxGrid::ChangeCursorMode(CursorMode mode,
6319 wxWindow *win,
6320 bool captureMouse)
6321 {
6322 #ifdef __WXDEBUG__
6323 static const wxChar *cursorModes[] =
6324 {
6325 _T("SELECT_CELL"),
6326 _T("RESIZE_ROW"),
6327 _T("RESIZE_COL"),
6328 _T("SELECT_ROW"),
6329 _T("SELECT_COL"),
6330 _T("MOVE_COL"),
6331 };
6332
6333 wxLogTrace(_T("grid"),
6334 _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
6335 win == m_colWindow ? _T("colLabelWin")
6336 : win ? _T("rowLabelWin")
6337 : _T("gridWin"),
6338 cursorModes[m_cursorMode], cursorModes[mode]);
6339 #endif
6340
6341 if ( mode == m_cursorMode &&
6342 win == m_winCapture &&
6343 captureMouse == (m_winCapture != NULL))
6344 return;
6345
6346 if ( !win )
6347 {
6348 // by default use the grid itself
6349 win = m_gridWin;
6350 }
6351
6352 if ( m_winCapture )
6353 {
6354 m_winCapture->ReleaseMouse();
6355 m_winCapture = NULL;
6356 }
6357
6358 m_cursorMode = mode;
6359
6360 switch ( m_cursorMode )
6361 {
6362 case WXGRID_CURSOR_RESIZE_ROW:
6363 win->SetCursor( m_rowResizeCursor );
6364 break;
6365
6366 case WXGRID_CURSOR_RESIZE_COL:
6367 win->SetCursor( m_colResizeCursor );
6368 break;
6369
6370 case WXGRID_CURSOR_MOVE_COL:
6371 win->SetCursor( wxCursor(wxCURSOR_HAND) );
6372 break;
6373
6374 default:
6375 win->SetCursor( *wxSTANDARD_CURSOR );
6376 break;
6377 }
6378
6379 // we need to capture mouse when resizing
6380 bool resize = m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ||
6381 m_cursorMode == WXGRID_CURSOR_RESIZE_COL;
6382
6383 if ( captureMouse && resize )
6384 {
6385 win->CaptureMouse();
6386 m_winCapture = win;
6387 }
6388 }
6389
6390 // ----------------------------------------------------------------------------
6391 // grid mouse event processing
6392 // ----------------------------------------------------------------------------
6393
6394 void
6395 wxGrid::DoGridCellDrag(wxMouseEvent& event,
6396 const wxGridCellCoords& coords,
6397 bool isFirstDrag)
6398 {
6399 if ( coords == wxGridNoCellCoords )
6400 return; // we're outside any valid cell
6401
6402 // Hide the edit control, so it won't interfere with drag-shrinking.
6403 if ( IsCellEditControlShown() )
6404 {
6405 HideCellEditControl();
6406 SaveEditControlValue();
6407 }
6408
6409 switch ( event.GetModifiers() )
6410 {
6411 case wxMOD_CMD:
6412 if ( m_selectedBlockCorner == wxGridNoCellCoords)
6413 m_selectedBlockCorner = coords;
6414 UpdateBlockBeingSelected(m_selectedBlockCorner, coords);
6415 break;
6416
6417 case wxMOD_NONE:
6418 if ( CanDragCell() )
6419 {
6420 if ( isFirstDrag )
6421 {
6422 if ( m_selectedBlockCorner == wxGridNoCellCoords)
6423 m_selectedBlockCorner = coords;
6424
6425 SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG, coords, event);
6426 return;
6427 }
6428 }
6429
6430 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6431 break;
6432
6433 default:
6434 // we don't handle the other key modifiers
6435 event.Skip();
6436 }
6437 }
6438
6439 void wxGrid::DoGridLineDrag(wxMouseEvent& event, const wxGridOperations& oper)
6440 {
6441 wxClientDC dc(m_gridWin);
6442 PrepareDC(dc);
6443 dc.SetLogicalFunction(wxINVERT);
6444
6445 const wxRect rectWin(CalcUnscrolledPosition(wxPoint(0, 0)),
6446 m_gridWin->GetClientSize());
6447
6448 // erase the previously drawn line, if any
6449 if ( m_dragLastPos >= 0 )
6450 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
6451
6452 // we need the vertical position for rows and horizontal for columns here
6453 m_dragLastPos = oper.Dual().Select(CalcUnscrolledPosition(event.GetPosition()));
6454
6455 // don't allow resizing beneath the minimal size
6456 const int posMin = oper.GetLineStartPos(this, m_dragRowOrCol) +
6457 oper.GetMinimalLineSize(this, m_dragRowOrCol);
6458 if ( m_dragLastPos < posMin )
6459 m_dragLastPos = posMin;
6460
6461 // and draw it at the new position
6462 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
6463 }
6464
6465 void wxGrid::DoGridDragEvent(wxMouseEvent& event, const wxGridCellCoords& coords)
6466 {
6467 if ( !m_isDragging )
6468 {
6469 // Don't start doing anything until the mouse has been dragged far
6470 // enough
6471 const wxPoint& pt = event.GetPosition();
6472 if ( m_startDragPos == wxDefaultPosition )
6473 {
6474 m_startDragPos = pt;
6475 return;
6476 }
6477
6478 if ( abs(m_startDragPos.x - pt.x) <= DRAG_SENSITIVITY &&
6479 abs(m_startDragPos.y - pt.y) <= DRAG_SENSITIVITY )
6480 return;
6481 }
6482
6483 const bool isFirstDrag = !m_isDragging;
6484 m_isDragging = true;
6485
6486 switch ( m_cursorMode )
6487 {
6488 case WXGRID_CURSOR_SELECT_CELL:
6489 DoGridCellDrag(event, coords, isFirstDrag);
6490 break;
6491
6492 case WXGRID_CURSOR_RESIZE_ROW:
6493 DoGridLineDrag(event, wxGridRowOperations());
6494 break;
6495
6496 case WXGRID_CURSOR_RESIZE_COL:
6497 DoGridLineDrag(event, wxGridColumnOperations());
6498 break;
6499
6500 default:
6501 event.Skip();
6502 }
6503
6504 if ( isFirstDrag )
6505 {
6506 m_winCapture = m_gridWin;
6507 m_winCapture->CaptureMouse();
6508 }
6509 }
6510
6511 void
6512 wxGrid::DoGridCellLeftDown(wxMouseEvent& event,
6513 const wxGridCellCoords& coords,
6514 const wxPoint& pos)
6515 {
6516 if ( SendEvent(wxEVT_GRID_CELL_LEFT_CLICK, coords, event) )
6517 {
6518 // event handled by user code, no need to do anything here
6519 return;
6520 }
6521
6522 if ( !event.CmdDown() )
6523 ClearSelection();
6524
6525 if ( event.ShiftDown() )
6526 {
6527 if ( m_selection )
6528 {
6529 m_selection->SelectBlock(m_currentCellCoords, coords, event);
6530 m_selectedBlockCorner = coords;
6531 }
6532 }
6533 else if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
6534 {
6535 DisableCellEditControl();
6536 MakeCellVisible( coords );
6537
6538 if ( event.CmdDown() )
6539 {
6540 if ( m_selection )
6541 {
6542 m_selection->ToggleCellSelection(coords, event);
6543 }
6544
6545 m_selectedBlockTopLeft = wxGridNoCellCoords;
6546 m_selectedBlockBottomRight = wxGridNoCellCoords;
6547 m_selectedBlockCorner = coords;
6548 }
6549 else
6550 {
6551 m_waitForSlowClick = m_currentCellCoords == coords &&
6552 coords != wxGridNoCellCoords;
6553 SetCurrentCell( coords );
6554 }
6555 }
6556 }
6557
6558 void
6559 wxGrid::DoGridCellLeftDClick(wxMouseEvent& event,
6560 const wxGridCellCoords& coords,
6561 const wxPoint& pos)
6562 {
6563 if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
6564 {
6565 if ( !SendEvent(wxEVT_GRID_CELL_LEFT_DCLICK, coords, event) )
6566 {
6567 // we want double click to select a cell and start editing
6568 // (i.e. to behave in same way as sequence of two slow clicks):
6569 m_waitForSlowClick = true;
6570 }
6571 }
6572 }
6573
6574 void
6575 wxGrid::DoGridCellLeftUp(wxMouseEvent& event, const wxGridCellCoords& coords)
6576 {
6577 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6578 {
6579 if (m_winCapture)
6580 {
6581 m_winCapture->ReleaseMouse();
6582 m_winCapture = NULL;
6583 }
6584
6585 if ( coords == m_currentCellCoords && m_waitForSlowClick && CanEnableCellControl() )
6586 {
6587 ClearSelection();
6588 EnableCellEditControl();
6589
6590 wxGridCellAttr *attr = GetCellAttr(coords);
6591 wxGridCellEditor *editor = attr->GetEditor(this, coords.GetRow(), coords.GetCol());
6592 editor->StartingClick();
6593 editor->DecRef();
6594 attr->DecRef();
6595
6596 m_waitForSlowClick = false;
6597 }
6598 else if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
6599 m_selectedBlockBottomRight != wxGridNoCellCoords )
6600 {
6601 if ( m_selection )
6602 {
6603 m_selection->SelectBlock( m_selectedBlockTopLeft,
6604 m_selectedBlockBottomRight,
6605 event );
6606 }
6607
6608 m_selectedBlockTopLeft = wxGridNoCellCoords;
6609 m_selectedBlockBottomRight = wxGridNoCellCoords;
6610
6611 // Show the edit control, if it has been hidden for
6612 // drag-shrinking.
6613 ShowCellEditControl();
6614 }
6615 }
6616 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
6617 {
6618 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6619 DoEndDragResizeRow();
6620
6621 // Note: we are ending the event *after* doing
6622 // default processing in this case
6623 //
6624 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
6625 }
6626 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL )
6627 {
6628 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6629 DoEndDragResizeCol();
6630 }
6631
6632 m_dragLastPos = -1;
6633 }
6634
6635 void
6636 wxGrid::DoGridMouseMoveEvent(wxMouseEvent& WXUNUSED(event),
6637 const wxGridCellCoords& coords,
6638 const wxPoint& pos)
6639 {
6640 if ( coords.GetRow() < 0 || coords.GetCol() < 0 )
6641 {
6642 // out of grid cell area
6643 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6644 return;
6645 }
6646
6647 int dragRow = YToEdgeOfRow( pos.y );
6648 int dragCol = XToEdgeOfCol( pos.x );
6649
6650 // Dragging on the corner of a cell to resize in both
6651 // directions is not implemented yet...
6652 //
6653 if ( dragRow >= 0 && dragCol >= 0 )
6654 {
6655 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6656 return;
6657 }
6658
6659 if ( dragRow >= 0 )
6660 {
6661 m_dragRowOrCol = dragRow;
6662
6663 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6664 {
6665 if ( CanDragRowSize() && CanDragGridSize() )
6666 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, NULL, false);
6667 }
6668 }
6669 // When using the native header window we can only resize the columns by
6670 // dragging the dividers in it because we can't make it enter into the
6671 // column resizing mode programmatically
6672 else if ( dragCol >= 0 && !m_useNativeHeader )
6673 {
6674 m_dragRowOrCol = dragCol;
6675
6676 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6677 {
6678 if ( CanDragColSize() && CanDragGridSize() )
6679 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, NULL, false);
6680 }
6681 }
6682 else // Neither on a row or col edge
6683 {
6684 if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
6685 {
6686 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6687 }
6688 }
6689 }
6690
6691 void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event)
6692 {
6693 const wxPoint pos = CalcUnscrolledPosition(event.GetPosition());
6694
6695 // coordinates of the cell under mouse
6696 wxGridCellCoords coords = XYToCell(pos);
6697
6698 int cell_rows, cell_cols;
6699 GetCellSize( coords.GetRow(), coords.GetCol(), &cell_rows, &cell_cols );
6700 if ( (cell_rows < 0) || (cell_cols < 0) )
6701 {
6702 coords.SetRow(coords.GetRow() + cell_rows);
6703 coords.SetCol(coords.GetCol() + cell_cols);
6704 }
6705
6706 if ( event.Dragging() )
6707 {
6708 if ( event.LeftIsDown() )
6709 DoGridDragEvent(event, coords);
6710 else
6711 event.Skip();
6712 return;
6713 }
6714
6715 m_isDragging = false;
6716 m_startDragPos = wxDefaultPosition;
6717
6718 // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL
6719 // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under
6720 // wxGTK
6721 #if 0
6722 if ( event.Entering() || event.Leaving() )
6723 {
6724 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6725 m_gridWin->SetCursor( *wxSTANDARD_CURSOR );
6726 }
6727 #endif // 0
6728
6729 // deal with various button presses
6730 if ( event.IsButton() )
6731 {
6732 if ( coords != wxGridNoCellCoords )
6733 {
6734 DisableCellEditControl();
6735
6736 if ( event.LeftDown() )
6737 DoGridCellLeftDown(event, coords, pos);
6738 else if ( event.LeftDClick() )
6739 DoGridCellLeftDClick(event, coords, pos);
6740 else if ( event.RightDown() )
6741 SendEvent(wxEVT_GRID_CELL_RIGHT_CLICK, coords, event);
6742 else if ( event.RightDClick() )
6743 SendEvent(wxEVT_GRID_CELL_RIGHT_DCLICK, coords, event);
6744 }
6745
6746 // this one should be called even if we're not over any cell
6747 if ( event.LeftUp() )
6748 {
6749 DoGridCellLeftUp(event, coords);
6750 }
6751 }
6752 else if ( event.Moving() )
6753 {
6754 DoGridMouseMoveEvent(event, coords, pos);
6755 }
6756 else // unknown mouse event?
6757 {
6758 event.Skip();
6759 }
6760 }
6761
6762 void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper)
6763 {
6764 if ( m_dragLastPos == -1 )
6765 return;
6766
6767 const wxGridOperations& doper = oper.Dual();
6768
6769 const wxSize size = m_gridWin->GetClientSize();
6770
6771 const wxPoint ptOrigin = CalcUnscrolledPosition(wxPoint(0, 0));
6772
6773 // erase the last line we drew
6774 wxClientDC dc(m_gridWin);
6775 PrepareDC(dc);
6776 dc.SetLogicalFunction(wxINVERT);
6777
6778 const int posLineStart = oper.Select(ptOrigin);
6779 const int posLineEnd = oper.Select(ptOrigin) + oper.Select(size);
6780
6781 oper.DrawParallelLine(dc, posLineStart, posLineEnd, m_dragLastPos);
6782
6783 // temporarily hide the edit control before resizing
6784 HideCellEditControl();
6785 SaveEditControlValue();
6786
6787 // do resize the line
6788 const int lineStart = oper.GetLineStartPos(this, m_dragRowOrCol);
6789 oper.SetLineSize(this, m_dragRowOrCol,
6790 wxMax(m_dragLastPos - lineStart,
6791 oper.GetMinimalLineSize(this, m_dragRowOrCol)));
6792
6793 m_dragLastPos = -1;
6794
6795 // refresh now if we're not frozen
6796 if ( !GetBatchCount() )
6797 {
6798 // we need to refresh everything beyond the resized line in the header
6799 // window
6800
6801 // get the position from which to refresh in the other direction
6802 wxRect rect(CellToRect(oper.MakeCoords(m_dragRowOrCol, 0)));
6803 rect.SetPosition(CalcScrolledPosition(rect.GetPosition()));
6804
6805 // we only need the ordinate (for rows) or abscissa (for columns) here,
6806 // and need to cover the entire window in the other direction
6807 oper.Select(rect) = 0;
6808
6809 wxRect rectHeader(rect.GetPosition(),
6810 oper.MakeSize
6811 (
6812 oper.GetHeaderWindowSize(this),
6813 doper.Select(size) - doper.Select(rect)
6814 ));
6815
6816 oper.GetHeaderWindow(this)->Refresh(true, &rectHeader);
6817
6818
6819 // also refresh the grid window: extend the rectangle
6820 if ( m_table )
6821 {
6822 oper.SelectSize(rect) = oper.Select(size);
6823
6824 int subtractLines = 0;
6825 const int lineStart = oper.PosToLine(this, posLineStart);
6826 if ( lineStart >= 0 )
6827 {
6828 // ensure that if we have a multi-cell block we redraw all of
6829 // it by increasing the refresh area to cover it entirely if a
6830 // part of it is affected
6831 const int lineEnd = oper.PosToLine(this, posLineEnd, true);
6832 for ( int line = lineStart; line < lineEnd; line++ )
6833 {
6834 int cellLines = oper.Select(
6835 GetCellSize(oper.MakeCoords(m_dragRowOrCol, line)));
6836 if ( cellLines < subtractLines )
6837 subtractLines = cellLines;
6838 }
6839 }
6840
6841 int startPos =
6842 oper.GetLineStartPos(this, m_dragRowOrCol + subtractLines);
6843 startPos = doper.CalcScrolledPosition(this, startPos);
6844
6845 doper.Select(rect) = startPos;
6846 doper.SelectSize(rect) = doper.Select(size) - startPos;
6847
6848 m_gridWin->Refresh(false, &rect);
6849 }
6850 }
6851
6852 // show the edit control back again
6853 ShowCellEditControl();
6854 }
6855
6856 void wxGrid::DoEndDragResizeRow()
6857 {
6858 DoEndDragResizeLine(wxGridRowOperations());
6859 }
6860
6861 void wxGrid::DoEndDragResizeCol(wxMouseEvent *event)
6862 {
6863 DoEndDragResizeLine(wxGridColumnOperations());
6864
6865 // Note: we are ending the event *after* doing
6866 // default processing in this case
6867 //
6868 if ( event )
6869 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, *event );
6870 else
6871 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol );
6872 }
6873
6874 void wxGrid::DoStartMoveCol(int col)
6875 {
6876 m_dragRowOrCol = col;
6877 }
6878
6879 void wxGrid::DoEndMoveCol(int pos)
6880 {
6881 wxASSERT_MSG( m_dragRowOrCol != -1, "no matching DoStartMoveCol?" );
6882
6883 if ( SendEvent(wxEVT_GRID_COL_MOVE, -1, m_dragRowOrCol) != -1 )
6884 SetColPos(m_dragRowOrCol, pos);
6885 //else: vetoed by user
6886
6887 m_dragRowOrCol = -1;
6888 }
6889
6890 void wxGrid::RefreshAfterColPosChange()
6891 {
6892 // recalculate the column rights as the column positions have changed,
6893 // unless we calculate them dynamically because all columns widths are the
6894 // same and it's easy to do
6895 if ( !m_colWidths.empty() )
6896 {
6897 int colRight = 0;
6898 for ( int colPos = 0; colPos < m_numCols; colPos++ )
6899 {
6900 int colID = GetColAt( colPos );
6901
6902 colRight += m_colWidths[colID];
6903 m_colRights[colID] = colRight;
6904 }
6905 }
6906
6907 // and make the changes visible
6908 if ( m_useNativeHeader )
6909 {
6910 if ( m_colAt.empty() )
6911 GetGridColHeader()->ResetColumnsOrder();
6912 else
6913 GetGridColHeader()->SetColumnsOrder(m_colAt);
6914 }
6915 else
6916 {
6917 m_colWindow->Refresh();
6918 }
6919 m_gridWin->Refresh();
6920 }
6921
6922 void wxGrid::SetColumnsOrder(const wxArrayInt& order)
6923 {
6924 m_colAt = order;
6925
6926 RefreshAfterColPosChange();
6927 }
6928
6929 void wxGrid::SetColPos(int idx, int pos)
6930 {
6931 // we're going to need m_colAt now, initialize it if needed
6932 if ( m_colAt.empty() )
6933 {
6934 m_colAt.reserve(m_numCols);
6935 for ( int i = 0; i < m_numCols; i++ )
6936 m_colAt.push_back(i);
6937 }
6938
6939 wxHeaderCtrl::MoveColumnInOrderArray(m_colAt, idx, pos);
6940
6941 RefreshAfterColPosChange();
6942 }
6943
6944 void wxGrid::ResetColPos()
6945 {
6946 m_colAt.clear();
6947
6948 RefreshAfterColPosChange();
6949 }
6950
6951 void wxGrid::EnableDragColMove( bool enable )
6952 {
6953 if ( m_canDragColMove == enable )
6954 return;
6955
6956 if ( m_useNativeHeader )
6957 {
6958 // update all columns to make them [not] reorderable
6959 GetGridColHeader()->SetColumnCount(m_numCols);
6960 }
6961
6962 m_canDragColMove = enable;
6963
6964 // we use to call ResetColPos() from here if !enable but this doesn't seem
6965 // right as it would mean there would be no way to "freeze" the current
6966 // columns order by disabling moving them after putting them in the desired
6967 // order, whereas now you can always call ResetColPos() manually if needed
6968 }
6969
6970
6971 //
6972 // ------ interaction with data model
6973 //
6974 bool wxGrid::ProcessTableMessage( wxGridTableMessage& msg )
6975 {
6976 switch ( msg.GetId() )
6977 {
6978 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES:
6979 return GetModelValues();
6980
6981 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES:
6982 return SetModelValues();
6983
6984 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
6985 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
6986 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
6987 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
6988 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
6989 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
6990 return Redimension( msg );
6991
6992 default:
6993 return false;
6994 }
6995 }
6996
6997 // The behaviour of this function depends on the grid table class
6998 // Clear() function. For the default wxGridStringTable class the
6999 // behaviour is to replace all cell contents with wxEmptyString but
7000 // not to change the number of rows or cols.
7001 //
7002 void wxGrid::ClearGrid()
7003 {
7004 if ( m_table )
7005 {
7006 if (IsCellEditControlEnabled())
7007 DisableCellEditControl();
7008
7009 m_table->Clear();
7010 if (!GetBatchCount())
7011 m_gridWin->Refresh();
7012 }
7013 }
7014
7015 bool
7016 wxGrid::DoModifyLines(bool (wxGridTableBase::*funcModify)(size_t, size_t),
7017 int pos, int num, bool WXUNUSED(updateLabels) )
7018 {
7019 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
7020
7021 if ( !m_table )
7022 return false;
7023
7024 if ( IsCellEditControlEnabled() )
7025 DisableCellEditControl();
7026
7027 return (m_table->*funcModify)(pos, num);
7028
7029 // the table will have sent the results of the insert row
7030 // operation to this view object as a grid table message
7031 }
7032
7033 bool
7034 wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend)(size_t),
7035 int num, bool WXUNUSED(updateLabels))
7036 {
7037 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
7038
7039 if ( !m_table )
7040 return false;
7041
7042 return (m_table->*funcAppend)(num);
7043 }
7044
7045 //
7046 // ----- event handlers
7047 //
7048
7049 // Generate a grid event based on a mouse event and return:
7050 // -1 if the event was vetoed
7051 // +1 if the event was processed (but not vetoed)
7052 // 0 if the event wasn't handled
7053 int
7054 wxGrid::SendEvent(const wxEventType type,
7055 int row, int col,
7056 wxMouseEvent& mouseEv)
7057 {
7058 bool claimed, vetoed;
7059
7060 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
7061 {
7062 int rowOrCol = (row == -1 ? col : row);
7063
7064 wxGridSizeEvent gridEvt( GetId(),
7065 type,
7066 this,
7067 rowOrCol,
7068 mouseEv.GetX() + GetRowLabelSize(),
7069 mouseEv.GetY() + GetColLabelSize(),
7070 mouseEv);
7071
7072 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7073 vetoed = !gridEvt.IsAllowed();
7074 }
7075 else if ( type == wxEVT_GRID_RANGE_SELECT )
7076 {
7077 // Right now, it should _never_ end up here!
7078 wxGridRangeSelectEvent gridEvt( GetId(),
7079 type,
7080 this,
7081 m_selectedBlockTopLeft,
7082 m_selectedBlockBottomRight,
7083 true,
7084 mouseEv);
7085
7086 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7087 vetoed = !gridEvt.IsAllowed();
7088 }
7089 else if ( type == wxEVT_GRID_LABEL_LEFT_CLICK ||
7090 type == wxEVT_GRID_LABEL_LEFT_DCLICK ||
7091 type == wxEVT_GRID_LABEL_RIGHT_CLICK ||
7092 type == wxEVT_GRID_LABEL_RIGHT_DCLICK )
7093 {
7094 wxPoint pos = mouseEv.GetPosition();
7095
7096 if ( mouseEv.GetEventObject() == GetGridRowLabelWindow() )
7097 pos.y += GetColLabelSize();
7098 if ( mouseEv.GetEventObject() == GetGridColLabelWindow() )
7099 pos.x += GetRowLabelSize();
7100
7101 wxGridEvent gridEvt( GetId(),
7102 type,
7103 this,
7104 row, col,
7105 pos.x,
7106 pos.y,
7107 false,
7108 mouseEv);
7109 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7110 vetoed = !gridEvt.IsAllowed();
7111 }
7112 else
7113 {
7114 wxGridEvent gridEvt( GetId(),
7115 type,
7116 this,
7117 row, col,
7118 mouseEv.GetX() + GetRowLabelSize(),
7119 mouseEv.GetY() + GetColLabelSize(),
7120 false,
7121 mouseEv);
7122 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7123 vetoed = !gridEvt.IsAllowed();
7124 }
7125
7126 // A Veto'd event may not be `claimed' so test this first
7127 if (vetoed)
7128 return -1;
7129
7130 return claimed ? 1 : 0;
7131 }
7132
7133 // Generate a grid event of specified type, return value same as above
7134 //
7135 int
7136 wxGrid::SendEvent(const wxEventType type, int row, int col, const wxString& s)
7137 {
7138 bool claimed, vetoed;
7139
7140 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
7141 {
7142 int rowOrCol = (row == -1 ? col : row);
7143
7144 wxGridSizeEvent gridEvt( GetId(), type, this, rowOrCol );
7145
7146 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7147 vetoed = !gridEvt.IsAllowed();
7148 }
7149 else
7150 {
7151 wxGridEvent gridEvt( GetId(), type, this, row, col );
7152 gridEvt.SetString(s);
7153
7154 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7155 vetoed = !gridEvt.IsAllowed();
7156 }
7157
7158 // A Veto'd event may not be `claimed' so test this first
7159 if (vetoed)
7160 return -1;
7161
7162 return claimed ? 1 : 0;
7163 }
7164
7165 void wxGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
7166 {
7167 // needed to prevent zillions of paint events on MSW
7168 wxPaintDC dc(this);
7169 }
7170
7171 void wxGrid::Refresh(bool eraseb, const wxRect* rect)
7172 {
7173 // Don't do anything if between Begin/EndBatch...
7174 // EndBatch() will do all this on the last nested one anyway.
7175 if ( m_created && !GetBatchCount() )
7176 {
7177 // Refresh to get correct scrolled position:
7178 wxScrolledWindow::Refresh(eraseb, rect);
7179
7180 if (rect)
7181 {
7182 int rect_x, rect_y, rectWidth, rectHeight;
7183 int width_label, width_cell, height_label, height_cell;
7184 int x, y;
7185
7186 // Copy rectangle can get scroll offsets..
7187 rect_x = rect->GetX();
7188 rect_y = rect->GetY();
7189 rectWidth = rect->GetWidth();
7190 rectHeight = rect->GetHeight();
7191
7192 width_label = m_rowLabelWidth - rect_x;
7193 if (width_label > rectWidth)
7194 width_label = rectWidth;
7195
7196 height_label = m_colLabelHeight - rect_y;
7197 if (height_label > rectHeight)
7198 height_label = rectHeight;
7199
7200 if (rect_x > m_rowLabelWidth)
7201 {
7202 x = rect_x - m_rowLabelWidth;
7203 width_cell = rectWidth;
7204 }
7205 else
7206 {
7207 x = 0;
7208 width_cell = rectWidth - (m_rowLabelWidth - rect_x);
7209 }
7210
7211 if (rect_y > m_colLabelHeight)
7212 {
7213 y = rect_y - m_colLabelHeight;
7214 height_cell = rectHeight;
7215 }
7216 else
7217 {
7218 y = 0;
7219 height_cell = rectHeight - (m_colLabelHeight - rect_y);
7220 }
7221
7222 // Paint corner label part intersecting rect.
7223 if ( width_label > 0 && height_label > 0 )
7224 {
7225 wxRect anotherrect(rect_x, rect_y, width_label, height_label);
7226 m_cornerLabelWin->Refresh(eraseb, &anotherrect);
7227 }
7228
7229 // Paint col labels part intersecting rect.
7230 if ( width_cell > 0 && height_label > 0 )
7231 {
7232 wxRect anotherrect(x, rect_y, width_cell, height_label);
7233 m_colWindow->Refresh(eraseb, &anotherrect);
7234 }
7235
7236 // Paint row labels part intersecting rect.
7237 if ( width_label > 0 && height_cell > 0 )
7238 {
7239 wxRect anotherrect(rect_x, y, width_label, height_cell);
7240 m_rowLabelWin->Refresh(eraseb, &anotherrect);
7241 }
7242
7243 // Paint cell area part intersecting rect.
7244 if ( width_cell > 0 && height_cell > 0 )
7245 {
7246 wxRect anotherrect(x, y, width_cell, height_cell);
7247 m_gridWin->Refresh(eraseb, &anotherrect);
7248 }
7249 }
7250 else
7251 {
7252 m_cornerLabelWin->Refresh(eraseb, NULL);
7253 m_colWindow->Refresh(eraseb, NULL);
7254 m_rowLabelWin->Refresh(eraseb, NULL);
7255 m_gridWin->Refresh(eraseb, NULL);
7256 }
7257 }
7258 }
7259
7260 void wxGrid::OnSize(wxSizeEvent& WXUNUSED(event))
7261 {
7262 if (m_targetWindow != this) // check whether initialisation has been done
7263 {
7264 // reposition our children windows
7265 CalcWindowSizes();
7266 }
7267 }
7268
7269 void wxGrid::OnKeyDown( wxKeyEvent& event )
7270 {
7271 if ( m_inOnKeyDown )
7272 {
7273 // shouldn't be here - we are going round in circles...
7274 //
7275 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
7276 }
7277
7278 m_inOnKeyDown = true;
7279
7280 // propagate the event up and see if it gets processed
7281 wxWindow *parent = GetParent();
7282 wxKeyEvent keyEvt( event );
7283 keyEvt.SetEventObject( parent );
7284
7285 if ( !parent->GetEventHandler()->ProcessEvent( keyEvt ) )
7286 {
7287 if (GetLayoutDirection() == wxLayout_RightToLeft)
7288 {
7289 if (event.GetKeyCode() == WXK_RIGHT)
7290 event.m_keyCode = WXK_LEFT;
7291 else if (event.GetKeyCode() == WXK_LEFT)
7292 event.m_keyCode = WXK_RIGHT;
7293 }
7294
7295 // try local handlers
7296 switch ( event.GetKeyCode() )
7297 {
7298 case WXK_UP:
7299 if ( event.ControlDown() )
7300 MoveCursorUpBlock( event.ShiftDown() );
7301 else
7302 MoveCursorUp( event.ShiftDown() );
7303 break;
7304
7305 case WXK_DOWN:
7306 if ( event.ControlDown() )
7307 MoveCursorDownBlock( event.ShiftDown() );
7308 else
7309 MoveCursorDown( event.ShiftDown() );
7310 break;
7311
7312 case WXK_LEFT:
7313 if ( event.ControlDown() )
7314 MoveCursorLeftBlock( event.ShiftDown() );
7315 else
7316 MoveCursorLeft( event.ShiftDown() );
7317 break;
7318
7319 case WXK_RIGHT:
7320 if ( event.ControlDown() )
7321 MoveCursorRightBlock( event.ShiftDown() );
7322 else
7323 MoveCursorRight( event.ShiftDown() );
7324 break;
7325
7326 case WXK_RETURN:
7327 case WXK_NUMPAD_ENTER:
7328 if ( event.ControlDown() )
7329 {
7330 event.Skip(); // to let the edit control have the return
7331 }
7332 else
7333 {
7334 if ( GetGridCursorRow() < GetNumberRows()-1 )
7335 {
7336 MoveCursorDown( event.ShiftDown() );
7337 }
7338 else
7339 {
7340 // at the bottom of a column
7341 DisableCellEditControl();
7342 }
7343 }
7344 break;
7345
7346 case WXK_ESCAPE:
7347 ClearSelection();
7348 break;
7349
7350 case WXK_TAB:
7351 if (event.ShiftDown())
7352 {
7353 if ( GetGridCursorCol() > 0 )
7354 {
7355 MoveCursorLeft( false );
7356 }
7357 else
7358 {
7359 // at left of grid
7360 DisableCellEditControl();
7361 }
7362 }
7363 else
7364 {
7365 if ( GetGridCursorCol() < GetNumberCols() - 1 )
7366 {
7367 MoveCursorRight( false );
7368 }
7369 else
7370 {
7371 // at right of grid
7372 DisableCellEditControl();
7373 }
7374 }
7375 break;
7376
7377 case WXK_HOME:
7378 if ( event.ControlDown() )
7379 {
7380 GoToCell(0, 0);
7381 }
7382 else
7383 {
7384 event.Skip();
7385 }
7386 break;
7387
7388 case WXK_END:
7389 if ( event.ControlDown() )
7390 {
7391 GoToCell(m_numRows - 1, m_numCols - 1);
7392 }
7393 else
7394 {
7395 event.Skip();
7396 }
7397 break;
7398
7399 case WXK_PAGEUP:
7400 MovePageUp();
7401 break;
7402
7403 case WXK_PAGEDOWN:
7404 MovePageDown();
7405 break;
7406
7407 case WXK_SPACE:
7408 // Ctrl-Space selects the current column, Shift-Space -- the
7409 // current row and Ctrl-Shift-Space -- everything
7410 switch ( m_selection ? event.GetModifiers() : wxMOD_NONE )
7411 {
7412 case wxMOD_CONTROL:
7413 m_selection->SelectCol(m_currentCellCoords.GetCol());
7414 break;
7415
7416 case wxMOD_SHIFT:
7417 m_selection->SelectRow(m_currentCellCoords.GetRow());
7418 break;
7419
7420 case wxMOD_CONTROL | wxMOD_SHIFT:
7421 m_selection->SelectBlock(0, 0,
7422 m_numRows - 1, m_numCols - 1);
7423 break;
7424
7425 case wxMOD_NONE:
7426 if ( !IsEditable() )
7427 {
7428 MoveCursorRight(false);
7429 break;
7430 }
7431 //else: fall through
7432
7433 default:
7434 event.Skip();
7435 }
7436 break;
7437
7438 default:
7439 event.Skip();
7440 break;
7441 }
7442 }
7443
7444 m_inOnKeyDown = false;
7445 }
7446
7447 void wxGrid::OnKeyUp( wxKeyEvent& event )
7448 {
7449 // try local handlers
7450 //
7451 if ( event.GetKeyCode() == WXK_SHIFT )
7452 {
7453 if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
7454 m_selectedBlockBottomRight != wxGridNoCellCoords )
7455 {
7456 if ( m_selection )
7457 {
7458 m_selection->SelectBlock(
7459 m_selectedBlockTopLeft,
7460 m_selectedBlockBottomRight,
7461 event);
7462 }
7463 }
7464
7465 m_selectedBlockTopLeft = wxGridNoCellCoords;
7466 m_selectedBlockBottomRight = wxGridNoCellCoords;
7467 m_selectedBlockCorner = wxGridNoCellCoords;
7468 }
7469 }
7470
7471 void wxGrid::OnChar( wxKeyEvent& event )
7472 {
7473 // is it possible to edit the current cell at all?
7474 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
7475 {
7476 // yes, now check whether the cells editor accepts the key
7477 int row = m_currentCellCoords.GetRow();
7478 int col = m_currentCellCoords.GetCol();
7479 wxGridCellAttr *attr = GetCellAttr(row, col);
7480 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7481
7482 // <F2> is special and will always start editing, for
7483 // other keys - ask the editor itself
7484 if ( (event.GetKeyCode() == WXK_F2 && !event.HasModifiers())
7485 || editor->IsAcceptedKey(event) )
7486 {
7487 // ensure cell is visble
7488 MakeCellVisible(row, col);
7489 EnableCellEditControl();
7490
7491 // a problem can arise if the cell is not completely
7492 // visible (even after calling MakeCellVisible the
7493 // control is not created and calling StartingKey will
7494 // crash the app
7495 if ( event.GetKeyCode() != WXK_F2 && editor->IsCreated() && m_cellEditCtrlEnabled )
7496 editor->StartingKey(event);
7497 }
7498 else
7499 {
7500 event.Skip();
7501 }
7502
7503 editor->DecRef();
7504 attr->DecRef();
7505 }
7506 else
7507 {
7508 event.Skip();
7509 }
7510 }
7511
7512 void wxGrid::OnEraseBackground(wxEraseEvent&)
7513 {
7514 }
7515
7516 bool wxGrid::SetCurrentCell( const wxGridCellCoords& coords )
7517 {
7518 if ( SendEvent(wxEVT_GRID_SELECT_CELL, coords) == -1 )
7519 {
7520 // the event has been vetoed - do nothing
7521 return false;
7522 }
7523
7524 #if !defined(__WXMAC__)
7525 wxClientDC dc( m_gridWin );
7526 PrepareDC( dc );
7527 #endif
7528
7529 if ( m_currentCellCoords != wxGridNoCellCoords )
7530 {
7531 DisableCellEditControl();
7532
7533 if ( IsVisible( m_currentCellCoords, false ) )
7534 {
7535 wxRect r;
7536 r = BlockToDeviceRect( m_currentCellCoords, m_currentCellCoords );
7537 if ( !m_gridLinesEnabled )
7538 {
7539 r.x--;
7540 r.y--;
7541 r.width++;
7542 r.height++;
7543 }
7544
7545 wxGridCellCoordsArray cells = CalcCellsExposed( r );
7546
7547 // Otherwise refresh redraws the highlight!
7548 m_currentCellCoords = coords;
7549
7550 #if defined(__WXMAC__)
7551 m_gridWin->Refresh(true /*, & r */);
7552 #else
7553 DrawGridCellArea( dc, cells );
7554 DrawAllGridLines( dc, r );
7555 #endif
7556 }
7557 }
7558
7559 m_currentCellCoords = coords;
7560
7561 wxGridCellAttr *attr = GetCellAttr( coords );
7562 #if !defined(__WXMAC__)
7563 DrawCellHighlight( dc, attr );
7564 #endif
7565 attr->DecRef();
7566
7567 return true;
7568 }
7569
7570 void
7571 wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol,
7572 int bottomRow, int rightCol)
7573 {
7574 if ( m_selection )
7575 {
7576 switch ( m_selection->GetSelectionMode() )
7577 {
7578 default:
7579 wxFAIL_MSG( "unknown selection mode" );
7580 // fall through
7581
7582 case wxGridSelectCells:
7583 // arbitrary blocks selection allowed so just use the cell
7584 // coordinates as is
7585 break;
7586
7587 case wxGridSelectRows:
7588 // only full rows selection allowd, ensure that we do select
7589 // full rows
7590 leftCol = 0;
7591 rightCol = GetNumberCols() - 1;
7592 break;
7593
7594 case wxGridSelectColumns:
7595 // same as above but for columns
7596 topRow = 0;
7597 bottomRow = GetNumberRows() - 1;
7598 break;
7599
7600 case wxGridSelectRowsOrColumns:
7601 // in this mode we can select only full rows or full columns so
7602 // it doesn't make sense to select blocks at all (and we can't
7603 // extend the block because there is no preferred direction, we
7604 // could only extend it to cover the entire grid but this is
7605 // not useful)
7606 return;
7607 }
7608 }
7609
7610 m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol);
7611 MakeCellVisible(m_selectedBlockCorner);
7612
7613 EnsureFirstLessThanSecond(topRow, bottomRow);
7614 EnsureFirstLessThanSecond(leftCol, rightCol);
7615
7616 wxGridCellCoords updateTopLeft = wxGridCellCoords(topRow, leftCol),
7617 updateBottomRight = wxGridCellCoords(bottomRow, rightCol);
7618
7619 // First the case that we selected a completely new area
7620 if ( m_selectedBlockTopLeft == wxGridNoCellCoords ||
7621 m_selectedBlockBottomRight == wxGridNoCellCoords )
7622 {
7623 wxRect rect;
7624 rect = BlockToDeviceRect( wxGridCellCoords ( topRow, leftCol ),
7625 wxGridCellCoords ( bottomRow, rightCol ) );
7626 m_gridWin->Refresh( false, &rect );
7627 }
7628
7629 // Now handle changing an existing selection area.
7630 else if ( m_selectedBlockTopLeft != updateTopLeft ||
7631 m_selectedBlockBottomRight != updateBottomRight )
7632 {
7633 // Compute two optimal update rectangles:
7634 // Either one rectangle is a real subset of the
7635 // other, or they are (almost) disjoint!
7636 wxRect rect[4];
7637 bool need_refresh[4];
7638 need_refresh[0] =
7639 need_refresh[1] =
7640 need_refresh[2] =
7641 need_refresh[3] = false;
7642 int i;
7643
7644 // Store intermediate values
7645 wxCoord oldLeft = m_selectedBlockTopLeft.GetCol();
7646 wxCoord oldTop = m_selectedBlockTopLeft.GetRow();
7647 wxCoord oldRight = m_selectedBlockBottomRight.GetCol();
7648 wxCoord oldBottom = m_selectedBlockBottomRight.GetRow();
7649
7650 // Determine the outer/inner coordinates.
7651 EnsureFirstLessThanSecond(oldLeft, leftCol);
7652 EnsureFirstLessThanSecond(oldTop, topRow);
7653 EnsureFirstLessThanSecond(rightCol, oldRight);
7654 EnsureFirstLessThanSecond(bottomRow, oldBottom);
7655
7656 // Now, either the stuff marked old is the outer
7657 // rectangle or we don't have a situation where one
7658 // is contained in the other.
7659
7660 if ( oldLeft < leftCol )
7661 {
7662 // Refresh the newly selected or deselected
7663 // area to the left of the old or new selection.
7664 need_refresh[0] = true;
7665 rect[0] = BlockToDeviceRect(
7666 wxGridCellCoords( oldTop, oldLeft ),
7667 wxGridCellCoords( oldBottom, leftCol - 1 ) );
7668 }
7669
7670 if ( oldTop < topRow )
7671 {
7672 // Refresh the newly selected or deselected
7673 // area above the old or new selection.
7674 need_refresh[1] = true;
7675 rect[1] = BlockToDeviceRect(
7676 wxGridCellCoords( oldTop, leftCol ),
7677 wxGridCellCoords( topRow - 1, rightCol ) );
7678 }
7679
7680 if ( oldRight > rightCol )
7681 {
7682 // Refresh the newly selected or deselected
7683 // area to the right of the old or new selection.
7684 need_refresh[2] = true;
7685 rect[2] = BlockToDeviceRect(
7686 wxGridCellCoords( oldTop, rightCol + 1 ),
7687 wxGridCellCoords( oldBottom, oldRight ) );
7688 }
7689
7690 if ( oldBottom > bottomRow )
7691 {
7692 // Refresh the newly selected or deselected
7693 // area below the old or new selection.
7694 need_refresh[3] = true;
7695 rect[3] = BlockToDeviceRect(
7696 wxGridCellCoords( bottomRow + 1, leftCol ),
7697 wxGridCellCoords( oldBottom, rightCol ) );
7698 }
7699
7700 // various Refresh() calls
7701 for (i = 0; i < 4; i++ )
7702 if ( need_refresh[i] && rect[i] != wxGridNoCellRect )
7703 m_gridWin->Refresh( false, &(rect[i]) );
7704 }
7705
7706 // change selection
7707 m_selectedBlockTopLeft = updateTopLeft;
7708 m_selectedBlockBottomRight = updateBottomRight;
7709 }
7710
7711 //
7712 // ------ functions to get/send data (see also public functions)
7713 //
7714
7715 bool wxGrid::GetModelValues()
7716 {
7717 // Hide the editor, so it won't hide a changed value.
7718 HideCellEditControl();
7719
7720 if ( m_table )
7721 {
7722 // all we need to do is repaint the grid
7723 //
7724 m_gridWin->Refresh();
7725 return true;
7726 }
7727
7728 return false;
7729 }
7730
7731 bool wxGrid::SetModelValues()
7732 {
7733 int row, col;
7734
7735 // Disable the editor, so it won't hide a changed value.
7736 // Do we also want to save the current value of the editor first?
7737 // I think so ...
7738 DisableCellEditControl();
7739
7740 if ( m_table )
7741 {
7742 for ( row = 0; row < m_numRows; row++ )
7743 {
7744 for ( col = 0; col < m_numCols; col++ )
7745 {
7746 m_table->SetValue( row, col, GetCellValue(row, col) );
7747 }
7748 }
7749
7750 return true;
7751 }
7752
7753 return false;
7754 }
7755
7756 // Note - this function only draws cells that are in the list of
7757 // exposed cells (usually set from the update region by
7758 // CalcExposedCells)
7759 //
7760 void wxGrid::DrawGridCellArea( wxDC& dc, const wxGridCellCoordsArray& cells )
7761 {
7762 if ( !m_numRows || !m_numCols )
7763 return;
7764
7765 int i, numCells = cells.GetCount();
7766 int row, col, cell_rows, cell_cols;
7767 wxGridCellCoordsArray redrawCells;
7768
7769 for ( i = numCells - 1; i >= 0; i-- )
7770 {
7771 row = cells[i].GetRow();
7772 col = cells[i].GetCol();
7773 GetCellSize( row, col, &cell_rows, &cell_cols );
7774
7775 // If this cell is part of a multicell block, find owner for repaint
7776 if ( cell_rows <= 0 || cell_cols <= 0 )
7777 {
7778 wxGridCellCoords cell( row + cell_rows, col + cell_cols );
7779 bool marked = false;
7780 for ( int j = 0; j < numCells; j++ )
7781 {
7782 if ( cell == cells[j] )
7783 {
7784 marked = true;
7785 break;
7786 }
7787 }
7788
7789 if (!marked)
7790 {
7791 int count = redrawCells.GetCount();
7792 for (int j = 0; j < count; j++)
7793 {
7794 if ( cell == redrawCells[j] )
7795 {
7796 marked = true;
7797 break;
7798 }
7799 }
7800
7801 if (!marked)
7802 redrawCells.Add( cell );
7803 }
7804
7805 // don't bother drawing this cell
7806 continue;
7807 }
7808
7809 // If this cell is empty, find cell to left that might want to overflow
7810 if (m_table && m_table->IsEmptyCell(row, col))
7811 {
7812 for ( int l = 0; l < cell_rows; l++ )
7813 {
7814 // find a cell in this row to leave already marked for repaint
7815 int left = col;
7816 for (int k = 0; k < int(redrawCells.GetCount()); k++)
7817 if ((redrawCells[k].GetCol() < left) &&
7818 (redrawCells[k].GetRow() == row))
7819 {
7820 left = redrawCells[k].GetCol();
7821 }
7822
7823 if (left == col)
7824 left = 0; // oh well
7825
7826 for (int j = col - 1; j >= left; j--)
7827 {
7828 if (!m_table->IsEmptyCell(row + l, j))
7829 {
7830 if (GetCellOverflow(row + l, j))
7831 {
7832 wxGridCellCoords cell(row + l, j);
7833 bool marked = false;
7834
7835 for (int k = 0; k < numCells; k++)
7836 {
7837 if ( cell == cells[k] )
7838 {
7839 marked = true;
7840 break;
7841 }
7842 }
7843
7844 if (!marked)
7845 {
7846 int count = redrawCells.GetCount();
7847 for (int k = 0; k < count; k++)
7848 {
7849 if ( cell == redrawCells[k] )
7850 {
7851 marked = true;
7852 break;
7853 }
7854 }
7855 if (!marked)
7856 redrawCells.Add( cell );
7857 }
7858 }
7859 break;
7860 }
7861 }
7862 }
7863 }
7864
7865 DrawCell( dc, cells[i] );
7866 }
7867
7868 numCells = redrawCells.GetCount();
7869
7870 for ( i = numCells - 1; i >= 0; i-- )
7871 {
7872 DrawCell( dc, redrawCells[i] );
7873 }
7874 }
7875
7876 void wxGrid::DrawGridSpace( wxDC& dc )
7877 {
7878 int cw, ch;
7879 m_gridWin->GetClientSize( &cw, &ch );
7880
7881 int right, bottom;
7882 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7883
7884 int rightCol = m_numCols > 0 ? GetColRight(GetColAt( m_numCols - 1 )) : 0;
7885 int bottomRow = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
7886
7887 if ( right > rightCol || bottom > bottomRow )
7888 {
7889 int left, top;
7890 CalcUnscrolledPosition( 0, 0, &left, &top );
7891
7892 dc.SetBrush(GetDefaultCellBackgroundColour());
7893 dc.SetPen( *wxTRANSPARENT_PEN );
7894
7895 if ( right > rightCol )
7896 {
7897 dc.DrawRectangle( rightCol, top, right - rightCol, ch );
7898 }
7899
7900 if ( bottom > bottomRow )
7901 {
7902 dc.DrawRectangle( left, bottomRow, cw, bottom - bottomRow );
7903 }
7904 }
7905 }
7906
7907 void wxGrid::DrawCell( wxDC& dc, const wxGridCellCoords& coords )
7908 {
7909 int row = coords.GetRow();
7910 int col = coords.GetCol();
7911
7912 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7913 return;
7914
7915 // we draw the cell border ourselves
7916 wxGridCellAttr* attr = GetCellAttr(row, col);
7917
7918 bool isCurrent = coords == m_currentCellCoords;
7919
7920 wxRect rect = CellToRect( row, col );
7921
7922 // if the editor is shown, we should use it and not the renderer
7923 // Note: However, only if it is really _shown_, i.e. not hidden!
7924 if ( isCurrent && IsCellEditControlShown() )
7925 {
7926 // NB: this "#if..." is temporary and fixes a problem where the
7927 // edit control is erased by this code after being rendered.
7928 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
7929 // implicitly, causing this out-of order render.
7930 #if !defined(__WXMAC__)
7931 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7932 editor->PaintBackground(rect, attr);
7933 editor->DecRef();
7934 #endif
7935 }
7936 else
7937 {
7938 // but all the rest is drawn by the cell renderer and hence may be customized
7939 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
7940 renderer->Draw(*this, *attr, dc, rect, row, col, IsInSelection(coords));
7941 renderer->DecRef();
7942 }
7943
7944 attr->DecRef();
7945 }
7946
7947 void wxGrid::DrawCellHighlight( wxDC& dc, const wxGridCellAttr *attr )
7948 {
7949 // don't show highlight when the grid doesn't have focus
7950 if ( !HasFocus() )
7951 return;
7952
7953 int row = m_currentCellCoords.GetRow();
7954 int col = m_currentCellCoords.GetCol();
7955
7956 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7957 return;
7958
7959 wxRect rect = CellToRect(row, col);
7960
7961 // hmmm... what could we do here to show that the cell is disabled?
7962 // for now, I just draw a thinner border than for the other ones, but
7963 // it doesn't look really good
7964
7965 int penWidth = attr->IsReadOnly() ? m_cellHighlightROPenWidth : m_cellHighlightPenWidth;
7966
7967 if (penWidth > 0)
7968 {
7969 // The center of the drawn line is where the position/width/height of
7970 // the rectangle is actually at (on wxMSW at least), so the
7971 // size of the rectangle is reduced to compensate for the thickness of
7972 // the line. If this is too strange on non-wxMSW platforms then
7973 // please #ifdef this appropriately.
7974 rect.x += penWidth / 2;
7975 rect.y += penWidth / 2;
7976 rect.width -= penWidth - 1;
7977 rect.height -= penWidth - 1;
7978
7979 // Now draw the rectangle
7980 // use the cellHighlightColour if the cell is inside a selection, this
7981 // will ensure the cell is always visible.
7982 dc.SetPen(wxPen(IsInSelection(row,col) ? m_selectionForeground
7983 : m_cellHighlightColour,
7984 penWidth));
7985 dc.SetBrush(*wxTRANSPARENT_BRUSH);
7986 dc.DrawRectangle(rect);
7987 }
7988 }
7989
7990 wxPen wxGrid::GetDefaultGridLinePen()
7991 {
7992 return wxPen(GetGridLineColour());
7993 }
7994
7995 wxPen wxGrid::GetRowGridLinePen(int WXUNUSED(row))
7996 {
7997 return GetDefaultGridLinePen();
7998 }
7999
8000 wxPen wxGrid::GetColGridLinePen(int WXUNUSED(col))
8001 {
8002 return GetDefaultGridLinePen();
8003 }
8004
8005 void wxGrid::DrawCellBorder( wxDC& dc, const wxGridCellCoords& coords )
8006 {
8007 int row = coords.GetRow();
8008 int col = coords.GetCol();
8009 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
8010 return;
8011
8012
8013 wxRect rect = CellToRect( row, col );
8014
8015 // right hand border
8016 dc.SetPen( GetColGridLinePen(col) );
8017 dc.DrawLine( rect.x + rect.width, rect.y,
8018 rect.x + rect.width, rect.y + rect.height + 1 );
8019
8020 // bottom border
8021 dc.SetPen( GetRowGridLinePen(row) );
8022 dc.DrawLine( rect.x, rect.y + rect.height,
8023 rect.x + rect.width, rect.y + rect.height);
8024 }
8025
8026 void wxGrid::DrawHighlight(wxDC& dc, const wxGridCellCoordsArray& cells)
8027 {
8028 // This if block was previously in wxGrid::OnPaint but that doesn't
8029 // seem to get called under wxGTK - MB
8030 //
8031 if ( m_currentCellCoords == wxGridNoCellCoords &&
8032 m_numRows && m_numCols )
8033 {
8034 m_currentCellCoords.Set(0, 0);
8035 }
8036
8037 if ( IsCellEditControlShown() )
8038 {
8039 // don't show highlight when the edit control is shown
8040 return;
8041 }
8042
8043 // if the active cell was repainted, repaint its highlight too because it
8044 // might have been damaged by the grid lines
8045 size_t count = cells.GetCount();
8046 for ( size_t n = 0; n < count; n++ )
8047 {
8048 wxGridCellCoords cell = cells[n];
8049
8050 // If we are using attributes, then we may have just exposed another
8051 // cell in a partially-visible merged cluster of cells. If the "anchor"
8052 // (upper left) cell of this merged cluster is the cell indicated by
8053 // m_currentCellCoords, then we need to refresh the cell highlight even
8054 // though the "anchor" itself is not part of our update segment.
8055 if ( CanHaveAttributes() )
8056 {
8057 int rows = 0,
8058 cols = 0;
8059 GetCellSize(cell.GetRow(), cell.GetCol(), &rows, &cols);
8060
8061 if ( rows < 0 )
8062 cell.SetRow(cell.GetRow() + rows);
8063
8064 if ( cols < 0 )
8065 cell.SetCol(cell.GetCol() + cols);
8066 }
8067
8068 if ( cell == m_currentCellCoords )
8069 {
8070 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
8071 DrawCellHighlight(dc, attr);
8072 attr->DecRef();
8073
8074 break;
8075 }
8076 }
8077 }
8078
8079 // This is used to redraw all grid lines e.g. when the grid line colour
8080 // has been changed
8081 //
8082 void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) )
8083 {
8084 if ( !m_gridLinesEnabled )
8085 return;
8086
8087 int top, bottom, left, right;
8088
8089 int cw, ch;
8090 m_gridWin->GetClientSize(&cw, &ch);
8091 CalcUnscrolledPosition( 0, 0, &left, &top );
8092 CalcUnscrolledPosition( cw, ch, &right, &bottom );
8093
8094 // avoid drawing grid lines past the last row and col
8095 if ( m_gridLinesClipHorz )
8096 {
8097 if ( !m_numCols )
8098 return;
8099
8100 const int lastColRight = GetColRight(GetColAt(m_numCols - 1));
8101 if ( right > lastColRight )
8102 right = lastColRight;
8103 }
8104
8105 if ( m_gridLinesClipVert )
8106 {
8107 if ( !m_numRows )
8108 return;
8109
8110 const int lastRowBottom = GetRowBottom(m_numRows - 1);
8111 if ( bottom > lastRowBottom )
8112 bottom = lastRowBottom;
8113 }
8114
8115 // no gridlines inside multicells, clip them out
8116 int leftCol = GetColPos( internalXToCol(left) );
8117 int topRow = internalYToRow(top);
8118 int rightCol = GetColPos( internalXToCol(right) );
8119 int bottomRow = internalYToRow(bottom);
8120
8121 wxRegion clippedcells(0, 0, cw, ch);
8122
8123 int cell_rows, cell_cols;
8124 wxRect rect;
8125
8126 for ( int j = topRow; j <= bottomRow; j++ )
8127 {
8128 for ( int colPos = leftCol; colPos <= rightCol; colPos++ )
8129 {
8130 int i = GetColAt( colPos );
8131
8132 GetCellSize( j, i, &cell_rows, &cell_cols );
8133 if ((cell_rows > 1) || (cell_cols > 1))
8134 {
8135 rect = CellToRect(j,i);
8136 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8137 clippedcells.Subtract(rect);
8138 }
8139 else if ((cell_rows < 0) || (cell_cols < 0))
8140 {
8141 rect = CellToRect(j + cell_rows, i + cell_cols);
8142 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8143 clippedcells.Subtract(rect);
8144 }
8145 }
8146 }
8147
8148 dc.SetDeviceClippingRegion( clippedcells );
8149
8150
8151 // horizontal grid lines
8152 for ( int i = internalYToRow(top); i < m_numRows; i++ )
8153 {
8154 int bot = GetRowBottom(i) - 1;
8155
8156 if ( bot > bottom )
8157 break;
8158
8159 if ( bot >= top )
8160 {
8161 dc.SetPen( GetRowGridLinePen(i) );
8162 dc.DrawLine( left, bot, right, bot );
8163 }
8164 }
8165
8166 // vertical grid lines
8167 for ( int colPos = leftCol; colPos < m_numCols; colPos++ )
8168 {
8169 int i = GetColAt( colPos );
8170
8171 int colRight = GetColRight(i);
8172 #ifdef __WXGTK__
8173 if (GetLayoutDirection() != wxLayout_RightToLeft)
8174 #endif
8175 colRight--;
8176
8177 if ( colRight > right )
8178 break;
8179
8180 if ( colRight >= left )
8181 {
8182 dc.SetPen( GetColGridLinePen(i) );
8183 dc.DrawLine( colRight, top, colRight, bottom );
8184 }
8185 }
8186
8187 dc.DestroyClippingRegion();
8188 }
8189
8190 void wxGrid::DrawRowLabels( wxDC& dc, const wxArrayInt& rows)
8191 {
8192 if ( !m_numRows )
8193 return;
8194
8195 const size_t numLabels = rows.GetCount();
8196 for ( size_t i = 0; i < numLabels; i++ )
8197 {
8198 DrawRowLabel( dc, rows[i] );
8199 }
8200 }
8201
8202 void wxGrid::DrawRowLabel( wxDC& dc, int row )
8203 {
8204 if ( GetRowHeight(row) <= 0 || m_rowLabelWidth <= 0 )
8205 return;
8206
8207 wxRect rect;
8208
8209 int rowTop = GetRowTop(row),
8210 rowBottom = GetRowBottom(row) - 1;
8211
8212 dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8213 dc.DrawLine( m_rowLabelWidth - 1, rowTop, m_rowLabelWidth - 1, rowBottom );
8214 dc.DrawLine( 0, rowTop, 0, rowBottom );
8215 dc.DrawLine( 0, rowBottom, m_rowLabelWidth, rowBottom );
8216
8217 dc.SetPen( *wxWHITE_PEN );
8218 dc.DrawLine( 1, rowTop, 1, rowBottom );
8219 dc.DrawLine( 1, rowTop, m_rowLabelWidth - 1, rowTop );
8220
8221 dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT );
8222 dc.SetTextForeground( GetLabelTextColour() );
8223 dc.SetFont( GetLabelFont() );
8224
8225 int hAlign, vAlign;
8226 GetRowLabelAlignment( &hAlign, &vAlign );
8227
8228 rect.SetX( 2 );
8229 rect.SetY( GetRowTop(row) + 2 );
8230 rect.SetWidth( m_rowLabelWidth - 4 );
8231 rect.SetHeight( GetRowHeight(row) - 4 );
8232 DrawTextRectangle( dc, GetRowLabelValue( row ), rect, hAlign, vAlign );
8233 }
8234
8235 void wxGrid::UseNativeColHeader(bool native)
8236 {
8237 if ( native == m_useNativeHeader )
8238 return;
8239
8240 delete m_colWindow;
8241 m_useNativeHeader = native;
8242
8243 CreateColumnWindow();
8244
8245 if ( m_useNativeHeader )
8246 GetGridColHeader()->SetColumnCount(m_numCols);
8247 CalcWindowSizes();
8248 }
8249
8250 void wxGrid::SetUseNativeColLabels( bool native )
8251 {
8252 wxASSERT_MSG( !m_useNativeHeader,
8253 "doesn't make sense when using native header" );
8254
8255 m_nativeColumnLabels = native;
8256 if (native)
8257 {
8258 int height = wxRendererNative::Get().GetHeaderButtonHeight( this );
8259 SetColLabelSize( height );
8260 }
8261
8262 GetColLabelWindow()->Refresh();
8263 m_cornerLabelWin->Refresh();
8264 }
8265
8266 void wxGrid::DrawColLabels( wxDC& dc,const wxArrayInt& cols )
8267 {
8268 if ( !m_numCols )
8269 return;
8270
8271 const size_t numLabels = cols.GetCount();
8272 for ( size_t i = 0; i < numLabels; i++ )
8273 {
8274 DrawColLabel( dc, cols[i] );
8275 }
8276 }
8277
8278 void wxGrid::DrawCornerLabel(wxDC& dc)
8279 {
8280 if ( m_nativeColumnLabels )
8281 {
8282 wxRect rect(wxSize(m_rowLabelWidth, m_colLabelHeight));
8283 rect.Deflate(1);
8284
8285 wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin, dc, rect, 0);
8286 }
8287 else
8288 {
8289 dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8290 dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1,
8291 m_rowLabelWidth - 1, 0 );
8292 dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1,
8293 0, m_colLabelHeight - 1 );
8294 dc.DrawLine( 0, 0, m_rowLabelWidth, 0 );
8295 dc.DrawLine( 0, 0, 0, m_colLabelHeight );
8296
8297 dc.SetPen( *wxWHITE_PEN );
8298 dc.DrawLine( 1, 1, m_rowLabelWidth - 1, 1 );
8299 dc.DrawLine( 1, 1, 1, m_colLabelHeight - 1 );
8300 }
8301 }
8302
8303 void wxGrid::DrawColLabel(wxDC& dc, int col)
8304 {
8305 if ( GetColWidth(col) <= 0 || m_colLabelHeight <= 0 )
8306 return;
8307
8308 int colLeft = GetColLeft(col);
8309
8310 wxRect rect(colLeft, 0, GetColWidth(col), m_colLabelHeight);
8311
8312 if ( m_nativeColumnLabels )
8313 {
8314 wxRendererNative::Get().DrawHeaderButton
8315 (
8316 GetColLabelWindow(),
8317 dc,
8318 rect,
8319 0,
8320 IsSortingBy(col)
8321 ? IsSortOrderAscending()
8322 ? wxHDR_SORT_ICON_UP
8323 : wxHDR_SORT_ICON_DOWN
8324 : wxHDR_SORT_ICON_NONE
8325 );
8326 }
8327 else
8328 {
8329 int colRight = GetColRight(col) - 1;
8330
8331 dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8332 dc.DrawLine( colRight, 0,
8333 colRight, m_colLabelHeight - 1 );
8334 dc.DrawLine( colLeft, 0,
8335 colRight, 0 );
8336 dc.DrawLine( colLeft, m_colLabelHeight - 1,
8337 colRight + 1, m_colLabelHeight - 1 );
8338
8339 dc.SetPen( *wxWHITE_PEN );
8340 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight - 1 );
8341 dc.DrawLine( colLeft, 1, colRight, 1 );
8342 }
8343
8344 dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT );
8345 dc.SetTextForeground( GetLabelTextColour() );
8346 dc.SetFont( GetLabelFont() );
8347
8348 int hAlign, vAlign;
8349 GetColLabelAlignment( &hAlign, &vAlign );
8350 const int orient = GetColLabelTextOrientation();
8351
8352 rect.Deflate(2);
8353 DrawTextRectangle(dc, GetColLabelValue(col), rect, hAlign, vAlign, orient);
8354 }
8355
8356 // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which
8357 // we just have to add textOrientation support
8358 void wxGrid::DrawTextRectangle( wxDC& dc,
8359 const wxString& value,
8360 const wxRect& rect,
8361 int horizAlign,
8362 int vertAlign,
8363 int textOrientation )
8364 {
8365 wxArrayString lines;
8366
8367 StringToLines( value, lines );
8368
8369 DrawTextRectangle(dc, lines, rect, horizAlign, vertAlign, textOrientation);
8370 }
8371
8372 void wxGrid::DrawTextRectangle(wxDC& dc,
8373 const wxArrayString& lines,
8374 const wxRect& rect,
8375 int horizAlign,
8376 int vertAlign,
8377 int textOrientation)
8378 {
8379 if ( lines.empty() )
8380 return;
8381
8382 wxDCClipper clip(dc, rect);
8383
8384 long textWidth,
8385 textHeight;
8386
8387 if ( textOrientation == wxHORIZONTAL )
8388 GetTextBoxSize( dc, lines, &textWidth, &textHeight );
8389 else
8390 GetTextBoxSize( dc, lines, &textHeight, &textWidth );
8391
8392 int x = 0,
8393 y = 0;
8394 switch ( vertAlign )
8395 {
8396 case wxALIGN_BOTTOM:
8397 if ( textOrientation == wxHORIZONTAL )
8398 y = rect.y + (rect.height - textHeight - 1);
8399 else
8400 x = rect.x + rect.width - textWidth;
8401 break;
8402
8403 case wxALIGN_CENTRE:
8404 if ( textOrientation == wxHORIZONTAL )
8405 y = rect.y + ((rect.height - textHeight) / 2);
8406 else
8407 x = rect.x + ((rect.width - textWidth) / 2);
8408 break;
8409
8410 case wxALIGN_TOP:
8411 default:
8412 if ( textOrientation == wxHORIZONTAL )
8413 y = rect.y + 1;
8414 else
8415 x = rect.x + 1;
8416 break;
8417 }
8418
8419 // Align each line of a multi-line label
8420 size_t nLines = lines.GetCount();
8421 for ( size_t l = 0; l < nLines; l++ )
8422 {
8423 const wxString& line = lines[l];
8424
8425 if ( line.empty() )
8426 {
8427 *(textOrientation == wxHORIZONTAL ? &y : &x) += dc.GetCharHeight();
8428 continue;
8429 }
8430
8431 wxCoord lineWidth = 0,
8432 lineHeight = 0;
8433 dc.GetTextExtent(line, &lineWidth, &lineHeight);
8434
8435 switch ( horizAlign )
8436 {
8437 case wxALIGN_RIGHT:
8438 if ( textOrientation == wxHORIZONTAL )
8439 x = rect.x + (rect.width - lineWidth - 1);
8440 else
8441 y = rect.y + lineWidth + 1;
8442 break;
8443
8444 case wxALIGN_CENTRE:
8445 if ( textOrientation == wxHORIZONTAL )
8446 x = rect.x + ((rect.width - lineWidth) / 2);
8447 else
8448 y = rect.y + rect.height - ((rect.height - lineWidth) / 2);
8449 break;
8450
8451 case wxALIGN_LEFT:
8452 default:
8453 if ( textOrientation == wxHORIZONTAL )
8454 x = rect.x + 1;
8455 else
8456 y = rect.y + rect.height - 1;
8457 break;
8458 }
8459
8460 if ( textOrientation == wxHORIZONTAL )
8461 {
8462 dc.DrawText( line, x, y );
8463 y += lineHeight;
8464 }
8465 else
8466 {
8467 dc.DrawRotatedText( line, x, y, 90.0 );
8468 x += lineHeight;
8469 }
8470 }
8471 }
8472
8473 // Split multi-line text up into an array of strings.
8474 // Any existing contents of the string array are preserved.
8475 //
8476 // TODO: refactor wxTextFile::Read() and reuse the same code from here
8477 void wxGrid::StringToLines( const wxString& value, wxArrayString& lines ) const
8478 {
8479 int startPos = 0;
8480 int pos;
8481 wxString eol = wxTextFile::GetEOL( wxTextFileType_Unix );
8482 wxString tVal = wxTextFile::Translate( value, wxTextFileType_Unix );
8483
8484 while ( startPos < (int)tVal.length() )
8485 {
8486 pos = tVal.Mid(startPos).Find( eol );
8487 if ( pos < 0 )
8488 {
8489 break;
8490 }
8491 else if ( pos == 0 )
8492 {
8493 lines.Add( wxEmptyString );
8494 }
8495 else
8496 {
8497 lines.Add( tVal.Mid(startPos, pos) );
8498 }
8499
8500 startPos += pos + 1;
8501 }
8502
8503 if ( startPos < (int)tVal.length() )
8504 {
8505 lines.Add( tVal.Mid( startPos ) );
8506 }
8507 }
8508
8509 void wxGrid::GetTextBoxSize( const wxDC& dc,
8510 const wxArrayString& lines,
8511 long *width, long *height ) const
8512 {
8513 wxCoord w = 0;
8514 wxCoord h = 0;
8515 wxCoord lineW = 0, lineH = 0;
8516
8517 size_t i;
8518 for ( i = 0; i < lines.GetCount(); i++ )
8519 {
8520 dc.GetTextExtent( lines[i], &lineW, &lineH );
8521 w = wxMax( w, lineW );
8522 h += lineH;
8523 }
8524
8525 *width = w;
8526 *height = h;
8527 }
8528
8529 //
8530 // ------ Batch processing.
8531 //
8532 void wxGrid::EndBatch()
8533 {
8534 if ( m_batchCount > 0 )
8535 {
8536 m_batchCount--;
8537 if ( !m_batchCount )
8538 {
8539 CalcDimensions();
8540 m_rowLabelWin->Refresh();
8541 m_colWindow->Refresh();
8542 m_cornerLabelWin->Refresh();
8543 m_gridWin->Refresh();
8544 }
8545 }
8546 }
8547
8548 // Use this, rather than wxWindow::Refresh(), to force an immediate
8549 // repainting of the grid. Has no effect if you are already inside a
8550 // BeginBatch / EndBatch block.
8551 //
8552 void wxGrid::ForceRefresh()
8553 {
8554 BeginBatch();
8555 EndBatch();
8556 }
8557
8558 bool wxGrid::Enable(bool enable)
8559 {
8560 if ( !wxScrolledWindow::Enable(enable) )
8561 return false;
8562
8563 // redraw in the new state
8564 m_gridWin->Refresh();
8565
8566 return true;
8567 }
8568
8569 //
8570 // ------ Edit control functions
8571 //
8572
8573 void wxGrid::EnableEditing( bool edit )
8574 {
8575 if ( edit != m_editable )
8576 {
8577 if (!edit)
8578 EnableCellEditControl(edit);
8579 m_editable = edit;
8580 }
8581 }
8582
8583 void wxGrid::EnableCellEditControl( bool enable )
8584 {
8585 if (! m_editable)
8586 return;
8587
8588 if ( enable != m_cellEditCtrlEnabled )
8589 {
8590 if ( enable )
8591 {
8592 if ( SendEvent(wxEVT_GRID_EDITOR_SHOWN) == -1 )
8593 return;
8594
8595 // this should be checked by the caller!
8596 wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") );
8597
8598 // do it before ShowCellEditControl()
8599 m_cellEditCtrlEnabled = enable;
8600
8601 ShowCellEditControl();
8602 }
8603 else
8604 {
8605 SendEvent(wxEVT_GRID_EDITOR_HIDDEN);
8606
8607 HideCellEditControl();
8608 SaveEditControlValue();
8609
8610 // do it after HideCellEditControl()
8611 m_cellEditCtrlEnabled = enable;
8612 }
8613 }
8614 }
8615
8616 bool wxGrid::IsCurrentCellReadOnly() const
8617 {
8618 // const_cast
8619 wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords);
8620 bool readonly = attr->IsReadOnly();
8621 attr->DecRef();
8622
8623 return readonly;
8624 }
8625
8626 bool wxGrid::CanEnableCellControl() const
8627 {
8628 return m_editable && (m_currentCellCoords != wxGridNoCellCoords) &&
8629 !IsCurrentCellReadOnly();
8630 }
8631
8632 bool wxGrid::IsCellEditControlEnabled() const
8633 {
8634 // the cell edit control might be disable for all cells or just for the
8635 // current one if it's read only
8636 return m_cellEditCtrlEnabled ? !IsCurrentCellReadOnly() : false;
8637 }
8638
8639 bool wxGrid::IsCellEditControlShown() const
8640 {
8641 bool isShown = false;
8642
8643 if ( m_cellEditCtrlEnabled )
8644 {
8645 int row = m_currentCellCoords.GetRow();
8646 int col = m_currentCellCoords.GetCol();
8647 wxGridCellAttr* attr = GetCellAttr(row, col);
8648 wxGridCellEditor* editor = attr->GetEditor((wxGrid*) this, row, col);
8649 attr->DecRef();
8650
8651 if ( editor )
8652 {
8653 if ( editor->IsCreated() )
8654 {
8655 isShown = editor->GetControl()->IsShown();
8656 }
8657
8658 editor->DecRef();
8659 }
8660 }
8661
8662 return isShown;
8663 }
8664
8665 void wxGrid::ShowCellEditControl()
8666 {
8667 if ( IsCellEditControlEnabled() )
8668 {
8669 if ( !IsVisible( m_currentCellCoords, false ) )
8670 {
8671 m_cellEditCtrlEnabled = false;
8672 return;
8673 }
8674 else
8675 {
8676 wxRect rect = CellToRect( m_currentCellCoords );
8677 int row = m_currentCellCoords.GetRow();
8678 int col = m_currentCellCoords.GetCol();
8679
8680 // if this is part of a multicell, find owner (topleft)
8681 int cell_rows, cell_cols;
8682 GetCellSize( row, col, &cell_rows, &cell_cols );
8683 if ( cell_rows <= 0 || cell_cols <= 0 )
8684 {
8685 row += cell_rows;
8686 col += cell_cols;
8687 m_currentCellCoords.SetRow( row );
8688 m_currentCellCoords.SetCol( col );
8689 }
8690
8691 // erase the highlight and the cell contents because the editor
8692 // might not cover the entire cell
8693 wxClientDC dc( m_gridWin );
8694 PrepareDC( dc );
8695 wxGridCellAttr* attr = GetCellAttr(row, col);
8696 dc.SetBrush(wxBrush(attr->GetBackgroundColour()));
8697 dc.SetPen(*wxTRANSPARENT_PEN);
8698 dc.DrawRectangle(rect);
8699
8700 // convert to scrolled coords
8701 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8702
8703 int nXMove = 0;
8704 if (rect.x < 0)
8705 nXMove = rect.x;
8706
8707 // cell is shifted by one pixel
8708 // However, don't allow x or y to become negative
8709 // since the SetSize() method interprets that as
8710 // "don't change."
8711 if (rect.x > 0)
8712 rect.x--;
8713 if (rect.y > 0)
8714 rect.y--;
8715
8716 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8717 if ( !editor->IsCreated() )
8718 {
8719 editor->Create(m_gridWin, wxID_ANY,
8720 new wxGridCellEditorEvtHandler(this, editor));
8721
8722 wxGridEditorCreatedEvent evt(GetId(),
8723 wxEVT_GRID_EDITOR_CREATED,
8724 this,
8725 row,
8726 col,
8727 editor->GetControl());
8728 GetEventHandler()->ProcessEvent(evt);
8729 }
8730
8731 // resize editor to overflow into righthand cells if allowed
8732 int maxWidth = rect.width;
8733 wxString value = GetCellValue(row, col);
8734 if ( (value != wxEmptyString) && (attr->GetOverflow()) )
8735 {
8736 int y;
8737 GetTextExtent(value, &maxWidth, &y, NULL, NULL, &attr->GetFont());
8738 if (maxWidth < rect.width)
8739 maxWidth = rect.width;
8740 }
8741
8742 int client_right = m_gridWin->GetClientSize().GetWidth();
8743 if (rect.x + maxWidth > client_right)
8744 maxWidth = client_right - rect.x;
8745
8746 if ((maxWidth > rect.width) && (col < m_numCols) && m_table)
8747 {
8748 GetCellSize( row, col, &cell_rows, &cell_cols );
8749 // may have changed earlier
8750 for (int i = col + cell_cols; i < m_numCols; i++)
8751 {
8752 int c_rows, c_cols;
8753 GetCellSize( row, i, &c_rows, &c_cols );
8754
8755 // looks weird going over a multicell
8756 if (m_table->IsEmptyCell( row, i ) &&
8757 (rect.width < maxWidth) && (c_rows == 1))
8758 {
8759 rect.width += GetColWidth( i );
8760 }
8761 else
8762 break;
8763 }
8764
8765 if (rect.GetRight() > client_right)
8766 rect.SetRight( client_right - 1 );
8767 }
8768
8769 editor->SetCellAttr( attr );
8770 editor->SetSize( rect );
8771 if (nXMove != 0)
8772 editor->GetControl()->Move(
8773 editor->GetControl()->GetPosition().x + nXMove,
8774 editor->GetControl()->GetPosition().y );
8775 editor->Show( true, attr );
8776
8777 // recalc dimensions in case we need to
8778 // expand the scrolled window to account for editor
8779 CalcDimensions();
8780
8781 editor->BeginEdit(row, col, this);
8782 editor->SetCellAttr(NULL);
8783
8784 editor->DecRef();
8785 attr->DecRef();
8786 }
8787 }
8788 }
8789
8790 void wxGrid::HideCellEditControl()
8791 {
8792 if ( IsCellEditControlEnabled() )
8793 {
8794 int row = m_currentCellCoords.GetRow();
8795 int col = m_currentCellCoords.GetCol();
8796
8797 wxGridCellAttr *attr = GetCellAttr(row, col);
8798 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
8799 const bool editorHadFocus = editor->GetControl()->HasFocus();
8800 editor->Show( false );
8801 editor->DecRef();
8802 attr->DecRef();
8803
8804 // return the focus to the grid itself if the editor had it
8805 //
8806 // note that we must not do this unconditionally to avoid stealing
8807 // focus from the window which just received it if we are hiding the
8808 // editor precisely because we lost focus
8809 if ( editorHadFocus )
8810 m_gridWin->SetFocus();
8811
8812 // refresh whole row to the right
8813 wxRect rect( CellToRect(row, col) );
8814 CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y );
8815 rect.width = m_gridWin->GetClientSize().GetWidth() - rect.x;
8816
8817 #ifdef __WXMAC__
8818 // ensure that the pixels under the focus ring get refreshed as well
8819 rect.Inflate(10, 10);
8820 #endif
8821
8822 m_gridWin->Refresh( false, &rect );
8823 }
8824 }
8825
8826 void wxGrid::SaveEditControlValue()
8827 {
8828 if ( IsCellEditControlEnabled() )
8829 {
8830 int row = m_currentCellCoords.GetRow();
8831 int col = m_currentCellCoords.GetCol();
8832
8833 wxString oldval = GetCellValue(row, col);
8834
8835 wxGridCellAttr* attr = GetCellAttr(row, col);
8836 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8837
8838 wxString newval;
8839 bool changed = editor->EndEdit(oldval, &newval);
8840
8841 if ( changed && SendEvent(wxEVT_GRID_CELL_CHANGING, newval) != -1 )
8842 {
8843 editor->ApplyEdit(row, col, this);
8844
8845 // for compatibility reasons dating back to wx 2.8 when this event
8846 // was called wxEVT_GRID_CELL_CHANGE and wxEVT_GRID_CELL_CHANGING
8847 // didn't exist we allow vetoing this one too
8848 if ( SendEvent(wxEVT_GRID_CELL_CHANGED, oldval) == -1 )
8849 {
8850 // Event has been vetoed, set the data back.
8851 SetCellValue(row, col, oldval);
8852 }
8853 }
8854
8855 editor->DecRef();
8856 attr->DecRef();
8857 }
8858 }
8859
8860 //
8861 // ------ Grid location functions
8862 // Note that all of these functions work with the logical coordinates of
8863 // grid cells and labels so you will need to convert from device
8864 // coordinates for mouse events etc.
8865 //
8866
8867 wxGridCellCoords wxGrid::XYToCell(int x, int y) const
8868 {
8869 int row = YToRow(y);
8870 int col = XToCol(x);
8871
8872 return row == -1 || col == -1 ? wxGridNoCellCoords
8873 : wxGridCellCoords(row, col);
8874 }
8875
8876 // compute row or column from some (unscrolled) coordinate value, using either
8877 // m_defaultRowHeight/m_defaultColWidth or binary search on array of
8878 // m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used
8879 // for large grids)
8880 int wxGrid::PosToLinePos(int coord,
8881 bool clipToMinMax,
8882 const wxGridOperations& oper) const
8883 {
8884 const int numLines = oper.GetNumberOfLines(this);
8885
8886 if ( coord < 0 )
8887 return clipToMinMax && numLines > 0 ? 0 : wxNOT_FOUND;
8888
8889 const int defaultLineSize = oper.GetDefaultLineSize(this);
8890 wxCHECK_MSG( defaultLineSize, -1, "can't have 0 default line size" );
8891
8892 int maxPos = coord / defaultLineSize,
8893 minPos = 0;
8894
8895 // check for the simplest case: if we have no explicit line sizes
8896 // configured, then we already know the line this position falls in
8897 const wxArrayInt& lineEnds = oper.GetLineEnds(this);
8898 if ( lineEnds.empty() )
8899 {
8900 if ( maxPos < numLines )
8901 return maxPos;
8902
8903 return clipToMinMax ? numLines - 1 : -1;
8904 }
8905
8906
8907 // adjust maxPos before starting the binary search
8908 if ( maxPos >= numLines )
8909 {
8910 maxPos = numLines - 1;
8911 }
8912 else
8913 {
8914 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos)])
8915 {
8916 minPos = maxPos;
8917 const int minDist = oper.GetMinimalAcceptableLineSize(this);
8918 if ( minDist )
8919 maxPos = coord / minDist;
8920 else
8921 maxPos = numLines - 1;
8922 }
8923
8924 if ( maxPos >= numLines )
8925 maxPos = numLines - 1;
8926 }
8927
8928 // check if the position is beyond the last column
8929 const int lineAtMaxPos = oper.GetLineAt(this, maxPos);
8930 if ( coord >= lineEnds[lineAtMaxPos] )
8931 return clipToMinMax ? maxPos : -1;
8932
8933 // or before the first one
8934 const int lineAt0 = oper.GetLineAt(this, 0);
8935 if ( coord < lineEnds[lineAt0] )
8936 return 0;
8937
8938
8939 // finally do perform the binary search
8940 while ( minPos < maxPos )
8941 {
8942 wxCHECK_MSG( lineEnds[oper.GetLineAt(this, minPos)] <= coord &&
8943 coord < lineEnds[oper.GetLineAt(this, maxPos)],
8944 -1,
8945 "wxGrid: internal error in PosToLinePos()" );
8946
8947 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos - 1)] )
8948 return maxPos;
8949 else
8950 maxPos--;
8951
8952 const int median = minPos + (maxPos - minPos + 1) / 2;
8953 if ( coord < lineEnds[oper.GetLineAt(this, median)] )
8954 maxPos = median;
8955 else
8956 minPos = median;
8957 }
8958
8959 return maxPos;
8960 }
8961
8962 int
8963 wxGrid::PosToLine(int coord,
8964 bool clipToMinMax,
8965 const wxGridOperations& oper) const
8966 {
8967 int pos = PosToLinePos(coord, clipToMinMax, oper);
8968
8969 return pos == wxNOT_FOUND ? wxNOT_FOUND : oper.GetLineAt(this, pos);
8970 }
8971
8972 int wxGrid::YToRow(int y, bool clipToMinMax) const
8973 {
8974 return PosToLine(y, clipToMinMax, wxGridRowOperations());
8975 }
8976
8977 int wxGrid::XToCol(int x, bool clipToMinMax) const
8978 {
8979 return PosToLine(x, clipToMinMax, wxGridColumnOperations());
8980 }
8981
8982 int wxGrid::XToPos(int x) const
8983 {
8984 return PosToLinePos(x, true /* clip */, wxGridColumnOperations());
8985 }
8986
8987 // return the row number that that the y coord is near the edge of, or -1 if
8988 // not near an edge.
8989 //
8990 // coords can only possibly be near an edge if
8991 // (a) the row/column is large enough to still allow for an "inner" area
8992 // that is _not_ near the edge (i.e., if the height/width is smaller
8993 // than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be
8994 // near the edge).
8995 // and
8996 // (b) resizing rows/columns (the thing for which edge detection is
8997 // relevant at all) is enabled.
8998 //
8999 int wxGrid::PosToEdgeOfLine(int pos, const wxGridOperations& oper) const
9000 {
9001 if ( !oper.CanResizeLines(this) )
9002 return -1;
9003
9004 const int line = oper.PosToLine(this, pos, true);
9005
9006 if ( oper.GetLineSize(this, line) > WXGRID_LABEL_EDGE_ZONE )
9007 {
9008 // We know that we are in this line, test whether we are close enough
9009 // to start or end border, respectively.
9010 if ( abs(oper.GetLineEndPos(this, line) - pos) < WXGRID_LABEL_EDGE_ZONE )
9011 return line;
9012 else if ( line > 0 &&
9013 pos - oper.GetLineStartPos(this,
9014 line) < WXGRID_LABEL_EDGE_ZONE )
9015 return line - 1;
9016 }
9017
9018 return -1;
9019 }
9020
9021 int wxGrid::YToEdgeOfRow(int y) const
9022 {
9023 return PosToEdgeOfLine(y, wxGridRowOperations());
9024 }
9025
9026 int wxGrid::XToEdgeOfCol(int x) const
9027 {
9028 return PosToEdgeOfLine(x, wxGridColumnOperations());
9029 }
9030
9031 wxRect wxGrid::CellToRect( int row, int col ) const
9032 {
9033 wxRect rect( -1, -1, -1, -1 );
9034
9035 if ( row >= 0 && row < m_numRows &&
9036 col >= 0 && col < m_numCols )
9037 {
9038 int i, cell_rows, cell_cols;
9039 rect.width = rect.height = 0;
9040 GetCellSize( row, col, &cell_rows, &cell_cols );
9041 // if negative then find multicell owner
9042 if (cell_rows < 0)
9043 row += cell_rows;
9044 if (cell_cols < 0)
9045 col += cell_cols;
9046 GetCellSize( row, col, &cell_rows, &cell_cols );
9047
9048 rect.x = GetColLeft(col);
9049 rect.y = GetRowTop(row);
9050 for (i=col; i < col + cell_cols; i++)
9051 rect.width += GetColWidth(i);
9052 for (i=row; i < row + cell_rows; i++)
9053 rect.height += GetRowHeight(i);
9054 }
9055
9056 // if grid lines are enabled, then the area of the cell is a bit smaller
9057 if (m_gridLinesEnabled)
9058 {
9059 rect.width -= 1;
9060 rect.height -= 1;
9061 }
9062
9063 return rect;
9064 }
9065
9066 bool wxGrid::IsVisible( int row, int col, bool wholeCellVisible ) const
9067 {
9068 // get the cell rectangle in logical coords
9069 //
9070 wxRect r( CellToRect( row, col ) );
9071
9072 // convert to device coords
9073 //
9074 int left, top, right, bottom;
9075 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
9076 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
9077
9078 // check against the client area of the grid window
9079 int cw, ch;
9080 m_gridWin->GetClientSize( &cw, &ch );
9081
9082 if ( wholeCellVisible )
9083 {
9084 // is the cell wholly visible ?
9085 return ( left >= 0 && right <= cw &&
9086 top >= 0 && bottom <= ch );
9087 }
9088 else
9089 {
9090 // is the cell partly visible ?
9091 //
9092 return ( ((left >= 0 && left < cw) || (right > 0 && right <= cw)) &&
9093 ((top >= 0 && top < ch) || (bottom > 0 && bottom <= ch)) );
9094 }
9095 }
9096
9097 // make the specified cell location visible by doing a minimal amount
9098 // of scrolling
9099 //
9100 void wxGrid::MakeCellVisible( int row, int col )
9101 {
9102 int i;
9103 int xpos = -1, ypos = -1;
9104
9105 if ( row >= 0 && row < m_numRows &&
9106 col >= 0 && col < m_numCols )
9107 {
9108 // get the cell rectangle in logical coords
9109 wxRect r( CellToRect( row, col ) );
9110
9111 // convert to device coords
9112 int left, top, right, bottom;
9113 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
9114 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
9115
9116 int cw, ch;
9117 m_gridWin->GetClientSize( &cw, &ch );
9118
9119 if ( top < 0 )
9120 {
9121 ypos = r.GetTop();
9122 }
9123 else if ( bottom > ch )
9124 {
9125 int h = r.GetHeight();
9126 ypos = r.GetTop();
9127 for ( i = row - 1; i >= 0; i-- )
9128 {
9129 int rowHeight = GetRowHeight(i);
9130 if ( h + rowHeight > ch )
9131 break;
9132
9133 h += rowHeight;
9134 ypos -= rowHeight;
9135 }
9136
9137 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
9138 // have rounding errors (this is important, because if we do,
9139 // we might not scroll at all and some cells won't be redrawn)
9140 //
9141 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
9142 // so just add a full scroll unit...
9143 ypos += m_scrollLineY;
9144 }
9145
9146 // special handling for wide cells - show always left part of the cell!
9147 // Otherwise, e.g. when stepping from row to row, it would jump between
9148 // left and right part of the cell on every step!
9149 // if ( left < 0 )
9150 if ( left < 0 || (right - left) >= cw )
9151 {
9152 xpos = r.GetLeft();
9153 }
9154 else if ( right > cw )
9155 {
9156 // position the view so that the cell is on the right
9157 int x0, y0;
9158 CalcUnscrolledPosition(0, 0, &x0, &y0);
9159 xpos = x0 + (right - cw);
9160
9161 // see comment for ypos above
9162 xpos += m_scrollLineX;
9163 }
9164
9165 if ( xpos != -1 || ypos != -1 )
9166 {
9167 if ( xpos != -1 )
9168 xpos /= m_scrollLineX;
9169 if ( ypos != -1 )
9170 ypos /= m_scrollLineY;
9171 Scroll( xpos, ypos );
9172 AdjustScrollbars();
9173 }
9174 }
9175 }
9176
9177 //
9178 // ------ Grid cursor movement functions
9179 //
9180
9181 bool
9182 wxGrid::DoMoveCursor(bool expandSelection,
9183 const wxGridDirectionOperations& diroper)
9184 {
9185 if ( m_currentCellCoords == wxGridNoCellCoords )
9186 return false;
9187
9188 if ( expandSelection )
9189 {
9190 wxGridCellCoords coords = m_selectedBlockCorner;
9191 if ( coords == wxGridNoCellCoords )
9192 coords = m_currentCellCoords;
9193
9194 if ( diroper.IsAtBoundary(coords) )
9195 return false;
9196
9197 diroper.Advance(coords);
9198
9199 UpdateBlockBeingSelected(m_currentCellCoords, coords);
9200 }
9201 else // don't expand selection
9202 {
9203 ClearSelection();
9204
9205 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9206 return false;
9207
9208 wxGridCellCoords coords = m_currentCellCoords;
9209 diroper.Advance(coords);
9210
9211 GoToCell(coords);
9212 }
9213
9214 return true;
9215 }
9216
9217 bool wxGrid::MoveCursorUp(bool expandSelection)
9218 {
9219 return DoMoveCursor(expandSelection,
9220 wxGridBackwardOperations(this, wxGridRowOperations()));
9221 }
9222
9223 bool wxGrid::MoveCursorDown(bool expandSelection)
9224 {
9225 return DoMoveCursor(expandSelection,
9226 wxGridForwardOperations(this, wxGridRowOperations()));
9227 }
9228
9229 bool wxGrid::MoveCursorLeft(bool expandSelection)
9230 {
9231 return DoMoveCursor(expandSelection,
9232 wxGridBackwardOperations(this, wxGridColumnOperations()));
9233 }
9234
9235 bool wxGrid::MoveCursorRight(bool expandSelection)
9236 {
9237 return DoMoveCursor(expandSelection,
9238 wxGridForwardOperations(this, wxGridColumnOperations()));
9239 }
9240
9241 bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations& diroper)
9242 {
9243 if ( m_currentCellCoords == wxGridNoCellCoords )
9244 return false;
9245
9246 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9247 return false;
9248
9249 const int oldRow = m_currentCellCoords.GetRow();
9250 int newRow = diroper.MoveByPixelDistance(oldRow, m_gridWin->GetClientSize().y);
9251 if ( newRow == oldRow )
9252 {
9253 wxGridCellCoords coords(m_currentCellCoords);
9254 diroper.Advance(coords);
9255 newRow = coords.GetRow();
9256 }
9257
9258 GoToCell(newRow, m_currentCellCoords.GetCol());
9259
9260 return true;
9261 }
9262
9263 bool wxGrid::MovePageUp()
9264 {
9265 return DoMoveCursorByPage(
9266 wxGridBackwardOperations(this, wxGridRowOperations()));
9267 }
9268
9269 bool wxGrid::MovePageDown()
9270 {
9271 return DoMoveCursorByPage(
9272 wxGridForwardOperations(this, wxGridRowOperations()));
9273 }
9274
9275 // helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
9276 // until we find a non-empty cell or reach the grid end
9277 void
9278 wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords& coords,
9279 const wxGridDirectionOperations& diroper)
9280 {
9281 while ( !diroper.IsAtBoundary(coords) )
9282 {
9283 diroper.Advance(coords);
9284 if ( !m_table->IsEmpty(coords) )
9285 break;
9286 }
9287 }
9288
9289 bool
9290 wxGrid::DoMoveCursorByBlock(bool expandSelection,
9291 const wxGridDirectionOperations& diroper)
9292 {
9293 if ( !m_table || m_currentCellCoords == wxGridNoCellCoords )
9294 return false;
9295
9296 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9297 return false;
9298
9299 wxGridCellCoords coords(m_currentCellCoords);
9300 if ( m_table->IsEmpty(coords) )
9301 {
9302 // we are in an empty cell: find the next block of non-empty cells
9303 AdvanceToNextNonEmpty(coords, diroper);
9304 }
9305 else // current cell is not empty
9306 {
9307 diroper.Advance(coords);
9308 if ( m_table->IsEmpty(coords) )
9309 {
9310 // we started at the end of a block, find the next one
9311 AdvanceToNextNonEmpty(coords, diroper);
9312 }
9313 else // we're in a middle of a block
9314 {
9315 // go to the end of it, i.e. find the last cell before the next
9316 // empty one
9317 while ( !diroper.IsAtBoundary(coords) )
9318 {
9319 wxGridCellCoords coordsNext(coords);
9320 diroper.Advance(coordsNext);
9321 if ( m_table->IsEmpty(coordsNext) )
9322 break;
9323
9324 coords = coordsNext;
9325 }
9326 }
9327 }
9328
9329 if ( expandSelection )
9330 {
9331 UpdateBlockBeingSelected(m_currentCellCoords, coords);
9332 }
9333 else
9334 {
9335 ClearSelection();
9336 GoToCell(coords);
9337 }
9338
9339 return true;
9340 }
9341
9342 bool wxGrid::MoveCursorUpBlock(bool expandSelection)
9343 {
9344 return DoMoveCursorByBlock(
9345 expandSelection,
9346 wxGridBackwardOperations(this, wxGridRowOperations())
9347 );
9348 }
9349
9350 bool wxGrid::MoveCursorDownBlock( bool expandSelection )
9351 {
9352 return DoMoveCursorByBlock(
9353 expandSelection,
9354 wxGridForwardOperations(this, wxGridRowOperations())
9355 );
9356 }
9357
9358 bool wxGrid::MoveCursorLeftBlock( bool expandSelection )
9359 {
9360 return DoMoveCursorByBlock(
9361 expandSelection,
9362 wxGridBackwardOperations(this, wxGridColumnOperations())
9363 );
9364 }
9365
9366 bool wxGrid::MoveCursorRightBlock( bool expandSelection )
9367 {
9368 return DoMoveCursorByBlock(
9369 expandSelection,
9370 wxGridForwardOperations(this, wxGridColumnOperations())
9371 );
9372 }
9373
9374 //
9375 // ------ Label values and formatting
9376 //
9377
9378 void wxGrid::GetRowLabelAlignment( int *horiz, int *vert ) const
9379 {
9380 if ( horiz )
9381 *horiz = m_rowLabelHorizAlign;
9382 if ( vert )
9383 *vert = m_rowLabelVertAlign;
9384 }
9385
9386 void wxGrid::GetColLabelAlignment( int *horiz, int *vert ) const
9387 {
9388 if ( horiz )
9389 *horiz = m_colLabelHorizAlign;
9390 if ( vert )
9391 *vert = m_colLabelVertAlign;
9392 }
9393
9394 int wxGrid::GetColLabelTextOrientation() const
9395 {
9396 return m_colLabelTextOrientation;
9397 }
9398
9399 wxString wxGrid::GetRowLabelValue( int row ) const
9400 {
9401 if ( m_table )
9402 {
9403 return m_table->GetRowLabelValue( row );
9404 }
9405 else
9406 {
9407 wxString s;
9408 s << row;
9409 return s;
9410 }
9411 }
9412
9413 wxString wxGrid::GetColLabelValue( int col ) const
9414 {
9415 if ( m_table )
9416 {
9417 return m_table->GetColLabelValue( col );
9418 }
9419 else
9420 {
9421 wxString s;
9422 s << col;
9423 return s;
9424 }
9425 }
9426
9427 void wxGrid::SetRowLabelSize( int width )
9428 {
9429 wxASSERT( width >= 0 || width == wxGRID_AUTOSIZE );
9430
9431 if ( width == wxGRID_AUTOSIZE )
9432 {
9433 width = CalcColOrRowLabelAreaMinSize(wxGRID_ROW);
9434 }
9435
9436 if ( width != m_rowLabelWidth )
9437 {
9438 if ( width == 0 )
9439 {
9440 m_rowLabelWin->Show( false );
9441 m_cornerLabelWin->Show( false );
9442 }
9443 else if ( m_rowLabelWidth == 0 )
9444 {
9445 m_rowLabelWin->Show( true );
9446 if ( m_colLabelHeight > 0 )
9447 m_cornerLabelWin->Show( true );
9448 }
9449
9450 m_rowLabelWidth = width;
9451 CalcWindowSizes();
9452 wxScrolledWindow::Refresh( true );
9453 }
9454 }
9455
9456 void wxGrid::SetColLabelSize( int height )
9457 {
9458 wxASSERT( height >=0 || height == wxGRID_AUTOSIZE );
9459
9460 if ( height == wxGRID_AUTOSIZE )
9461 {
9462 height = CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN);
9463 }
9464
9465 if ( height != m_colLabelHeight )
9466 {
9467 if ( height == 0 )
9468 {
9469 m_colWindow->Show( false );
9470 m_cornerLabelWin->Show( false );
9471 }
9472 else if ( m_colLabelHeight == 0 )
9473 {
9474 m_colWindow->Show( true );
9475 if ( m_rowLabelWidth > 0 )
9476 m_cornerLabelWin->Show( true );
9477 }
9478
9479 m_colLabelHeight = height;
9480 CalcWindowSizes();
9481 wxScrolledWindow::Refresh( true );
9482 }
9483 }
9484
9485 void wxGrid::SetLabelBackgroundColour( const wxColour& colour )
9486 {
9487 if ( m_labelBackgroundColour != colour )
9488 {
9489 m_labelBackgroundColour = colour;
9490 m_rowLabelWin->SetBackgroundColour( colour );
9491 m_colWindow->SetBackgroundColour( colour );
9492 m_cornerLabelWin->SetBackgroundColour( colour );
9493
9494 if ( !GetBatchCount() )
9495 {
9496 m_rowLabelWin->Refresh();
9497 m_colWindow->Refresh();
9498 m_cornerLabelWin->Refresh();
9499 }
9500 }
9501 }
9502
9503 void wxGrid::SetLabelTextColour( const wxColour& colour )
9504 {
9505 if ( m_labelTextColour != colour )
9506 {
9507 m_labelTextColour = colour;
9508 if ( !GetBatchCount() )
9509 {
9510 m_rowLabelWin->Refresh();
9511 m_colWindow->Refresh();
9512 }
9513 }
9514 }
9515
9516 void wxGrid::SetLabelFont( const wxFont& font )
9517 {
9518 m_labelFont = font;
9519 if ( !GetBatchCount() )
9520 {
9521 m_rowLabelWin->Refresh();
9522 m_colWindow->Refresh();
9523 }
9524 }
9525
9526 void wxGrid::SetRowLabelAlignment( int horiz, int vert )
9527 {
9528 // allow old (incorrect) defs to be used
9529 switch ( horiz )
9530 {
9531 case wxLEFT: horiz = wxALIGN_LEFT; break;
9532 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9533 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9534 }
9535
9536 switch ( vert )
9537 {
9538 case wxTOP: vert = wxALIGN_TOP; break;
9539 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9540 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9541 }
9542
9543 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9544 {
9545 m_rowLabelHorizAlign = horiz;
9546 }
9547
9548 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9549 {
9550 m_rowLabelVertAlign = vert;
9551 }
9552
9553 if ( !GetBatchCount() )
9554 {
9555 m_rowLabelWin->Refresh();
9556 }
9557 }
9558
9559 void wxGrid::SetColLabelAlignment( int horiz, int vert )
9560 {
9561 // allow old (incorrect) defs to be used
9562 switch ( horiz )
9563 {
9564 case wxLEFT: horiz = wxALIGN_LEFT; break;
9565 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9566 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9567 }
9568
9569 switch ( vert )
9570 {
9571 case wxTOP: vert = wxALIGN_TOP; break;
9572 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9573 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9574 }
9575
9576 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9577 {
9578 m_colLabelHorizAlign = horiz;
9579 }
9580
9581 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9582 {
9583 m_colLabelVertAlign = vert;
9584 }
9585
9586 if ( !GetBatchCount() )
9587 {
9588 m_colWindow->Refresh();
9589 }
9590 }
9591
9592 // Note: under MSW, the default column label font must be changed because it
9593 // does not support vertical printing
9594 //
9595 // Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
9596 // pGrid->SetLabelFont(font);
9597 // pGrid->SetColLabelTextOrientation(wxVERTICAL);
9598 //
9599 void wxGrid::SetColLabelTextOrientation( int textOrientation )
9600 {
9601 if ( textOrientation == wxHORIZONTAL || textOrientation == wxVERTICAL )
9602 m_colLabelTextOrientation = textOrientation;
9603
9604 if ( !GetBatchCount() )
9605 m_colWindow->Refresh();
9606 }
9607
9608 void wxGrid::SetRowLabelValue( int row, const wxString& s )
9609 {
9610 if ( m_table )
9611 {
9612 m_table->SetRowLabelValue( row, s );
9613 if ( !GetBatchCount() )
9614 {
9615 wxRect rect = CellToRect( row, 0 );
9616 if ( rect.height > 0 )
9617 {
9618 CalcScrolledPosition(0, rect.y, &rect.x, &rect.y);
9619 rect.x = 0;
9620 rect.width = m_rowLabelWidth;
9621 m_rowLabelWin->Refresh( true, &rect );
9622 }
9623 }
9624 }
9625 }
9626
9627 void wxGrid::SetColLabelValue( int col, const wxString& s )
9628 {
9629 if ( m_table )
9630 {
9631 m_table->SetColLabelValue( col, s );
9632 if ( !GetBatchCount() )
9633 {
9634 if ( m_useNativeHeader )
9635 {
9636 GetGridColHeader()->UpdateColumn(col);
9637 }
9638 else
9639 {
9640 wxRect rect = CellToRect( 0, col );
9641 if ( rect.width > 0 )
9642 {
9643 CalcScrolledPosition(rect.x, 0, &rect.x, &rect.y);
9644 rect.y = 0;
9645 rect.height = m_colLabelHeight;
9646 GetColLabelWindow()->Refresh( true, &rect );
9647 }
9648 }
9649 }
9650 }
9651 }
9652
9653 void wxGrid::SetGridLineColour( const wxColour& colour )
9654 {
9655 if ( m_gridLineColour != colour )
9656 {
9657 m_gridLineColour = colour;
9658
9659 if ( GridLinesEnabled() )
9660 RedrawGridLines();
9661 }
9662 }
9663
9664 void wxGrid::SetCellHighlightColour( const wxColour& colour )
9665 {
9666 if ( m_cellHighlightColour != colour )
9667 {
9668 m_cellHighlightColour = colour;
9669
9670 wxClientDC dc( m_gridWin );
9671 PrepareDC( dc );
9672 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
9673 DrawCellHighlight(dc, attr);
9674 attr->DecRef();
9675 }
9676 }
9677
9678 void wxGrid::SetCellHighlightPenWidth(int width)
9679 {
9680 if (m_cellHighlightPenWidth != width)
9681 {
9682 m_cellHighlightPenWidth = width;
9683
9684 // Just redrawing the cell highlight is not enough since that won't
9685 // make any visible change if the the thickness is getting smaller.
9686 int row = m_currentCellCoords.GetRow();
9687 int col = m_currentCellCoords.GetCol();
9688 if ( row == -1 || col == -1 || GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9689 return;
9690
9691 wxRect rect = CellToRect(row, col);
9692 m_gridWin->Refresh(true, &rect);
9693 }
9694 }
9695
9696 void wxGrid::SetCellHighlightROPenWidth(int width)
9697 {
9698 if (m_cellHighlightROPenWidth != width)
9699 {
9700 m_cellHighlightROPenWidth = width;
9701
9702 // Just redrawing the cell highlight is not enough since that won't
9703 // make any visible change if the the thickness is getting smaller.
9704 int row = m_currentCellCoords.GetRow();
9705 int col = m_currentCellCoords.GetCol();
9706 if ( row == -1 || col == -1 ||
9707 GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9708 return;
9709
9710 wxRect rect = CellToRect(row, col);
9711 m_gridWin->Refresh(true, &rect);
9712 }
9713 }
9714
9715 void wxGrid::RedrawGridLines()
9716 {
9717 // the lines will be redrawn when the window is thawn
9718 if ( GetBatchCount() )
9719 return;
9720
9721 if ( GridLinesEnabled() )
9722 {
9723 wxClientDC dc( m_gridWin );
9724 PrepareDC( dc );
9725 DrawAllGridLines( dc, wxRegion() );
9726 }
9727 else // remove the grid lines
9728 {
9729 m_gridWin->Refresh();
9730 }
9731 }
9732
9733 void wxGrid::EnableGridLines( bool enable )
9734 {
9735 if ( enable != m_gridLinesEnabled )
9736 {
9737 m_gridLinesEnabled = enable;
9738
9739 RedrawGridLines();
9740 }
9741 }
9742
9743 void wxGrid::DoClipGridLines(bool& var, bool clip)
9744 {
9745 if ( clip != var )
9746 {
9747 var = clip;
9748
9749 if ( GridLinesEnabled() )
9750 RedrawGridLines();
9751 }
9752 }
9753
9754 int wxGrid::GetDefaultRowSize() const
9755 {
9756 return m_defaultRowHeight;
9757 }
9758
9759 int wxGrid::GetRowSize( int row ) const
9760 {
9761 wxCHECK_MSG( row >= 0 && row < m_numRows, 0, _T("invalid row index") );
9762
9763 return GetRowHeight(row);
9764 }
9765
9766 int wxGrid::GetDefaultColSize() const
9767 {
9768 return m_defaultColWidth;
9769 }
9770
9771 int wxGrid::GetColSize( int col ) const
9772 {
9773 wxCHECK_MSG( col >= 0 && col < m_numCols, 0, _T("invalid column index") );
9774
9775 return GetColWidth(col);
9776 }
9777
9778 // ============================================================================
9779 // access to the grid attributes: each of them has a default value in the grid
9780 // itself and may be overidden on a per-cell basis
9781 // ============================================================================
9782
9783 // ----------------------------------------------------------------------------
9784 // setting default attributes
9785 // ----------------------------------------------------------------------------
9786
9787 void wxGrid::SetDefaultCellBackgroundColour( const wxColour& col )
9788 {
9789 m_defaultCellAttr->SetBackgroundColour(col);
9790 #ifdef __WXGTK__
9791 m_gridWin->SetBackgroundColour(col);
9792 #endif
9793 }
9794
9795 void wxGrid::SetDefaultCellTextColour( const wxColour& col )
9796 {
9797 m_defaultCellAttr->SetTextColour(col);
9798 }
9799
9800 void wxGrid::SetDefaultCellAlignment( int horiz, int vert )
9801 {
9802 m_defaultCellAttr->SetAlignment(horiz, vert);
9803 }
9804
9805 void wxGrid::SetDefaultCellOverflow( bool allow )
9806 {
9807 m_defaultCellAttr->SetOverflow(allow);
9808 }
9809
9810 void wxGrid::SetDefaultCellFont( const wxFont& font )
9811 {
9812 m_defaultCellAttr->SetFont(font);
9813 }
9814
9815 // For editors and renderers the type registry takes precedence over the
9816 // default attr, so we need to register the new editor/renderer for the string
9817 // data type in order to make setting a default editor/renderer appear to
9818 // work correctly.
9819
9820 void wxGrid::SetDefaultRenderer(wxGridCellRenderer *renderer)
9821 {
9822 RegisterDataType(wxGRID_VALUE_STRING,
9823 renderer,
9824 GetDefaultEditorForType(wxGRID_VALUE_STRING));
9825 }
9826
9827 void wxGrid::SetDefaultEditor(wxGridCellEditor *editor)
9828 {
9829 RegisterDataType(wxGRID_VALUE_STRING,
9830 GetDefaultRendererForType(wxGRID_VALUE_STRING),
9831 editor);
9832 }
9833
9834 // ----------------------------------------------------------------------------
9835 // access to the default attributes
9836 // ----------------------------------------------------------------------------
9837
9838 wxColour wxGrid::GetDefaultCellBackgroundColour() const
9839 {
9840 return m_defaultCellAttr->GetBackgroundColour();
9841 }
9842
9843 wxColour wxGrid::GetDefaultCellTextColour() const
9844 {
9845 return m_defaultCellAttr->GetTextColour();
9846 }
9847
9848 wxFont wxGrid::GetDefaultCellFont() const
9849 {
9850 return m_defaultCellAttr->GetFont();
9851 }
9852
9853 void wxGrid::GetDefaultCellAlignment( int *horiz, int *vert ) const
9854 {
9855 m_defaultCellAttr->GetAlignment(horiz, vert);
9856 }
9857
9858 bool wxGrid::GetDefaultCellOverflow() const
9859 {
9860 return m_defaultCellAttr->GetOverflow();
9861 }
9862
9863 wxGridCellRenderer *wxGrid::GetDefaultRenderer() const
9864 {
9865 return m_defaultCellAttr->GetRenderer(NULL, 0, 0);
9866 }
9867
9868 wxGridCellEditor *wxGrid::GetDefaultEditor() const
9869 {
9870 return m_defaultCellAttr->GetEditor(NULL, 0, 0);
9871 }
9872
9873 // ----------------------------------------------------------------------------
9874 // access to cell attributes
9875 // ----------------------------------------------------------------------------
9876
9877 wxColour wxGrid::GetCellBackgroundColour(int row, int col) const
9878 {
9879 wxGridCellAttr *attr = GetCellAttr(row, col);
9880 wxColour colour = attr->GetBackgroundColour();
9881 attr->DecRef();
9882
9883 return colour;
9884 }
9885
9886 wxColour wxGrid::GetCellTextColour( int row, int col ) const
9887 {
9888 wxGridCellAttr *attr = GetCellAttr(row, col);
9889 wxColour colour = attr->GetTextColour();
9890 attr->DecRef();
9891
9892 return colour;
9893 }
9894
9895 wxFont wxGrid::GetCellFont( int row, int col ) const
9896 {
9897 wxGridCellAttr *attr = GetCellAttr(row, col);
9898 wxFont font = attr->GetFont();
9899 attr->DecRef();
9900
9901 return font;
9902 }
9903
9904 void wxGrid::GetCellAlignment( int row, int col, int *horiz, int *vert ) const
9905 {
9906 wxGridCellAttr *attr = GetCellAttr(row, col);
9907 attr->GetAlignment(horiz, vert);
9908 attr->DecRef();
9909 }
9910
9911 bool wxGrid::GetCellOverflow( int row, int col ) const
9912 {
9913 wxGridCellAttr *attr = GetCellAttr(row, col);
9914 bool allow = attr->GetOverflow();
9915 attr->DecRef();
9916
9917 return allow;
9918 }
9919
9920 void wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const
9921 {
9922 wxGridCellAttr *attr = GetCellAttr(row, col);
9923 attr->GetSize( num_rows, num_cols );
9924 attr->DecRef();
9925 }
9926
9927 wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col) const
9928 {
9929 wxGridCellAttr* attr = GetCellAttr(row, col);
9930 wxGridCellRenderer* renderer = attr->GetRenderer(this, row, col);
9931 attr->DecRef();
9932
9933 return renderer;
9934 }
9935
9936 wxGridCellEditor* wxGrid::GetCellEditor(int row, int col) const
9937 {
9938 wxGridCellAttr* attr = GetCellAttr(row, col);
9939 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
9940 attr->DecRef();
9941
9942 return editor;
9943 }
9944
9945 bool wxGrid::IsReadOnly(int row, int col) const
9946 {
9947 wxGridCellAttr* attr = GetCellAttr(row, col);
9948 bool isReadOnly = attr->IsReadOnly();
9949 attr->DecRef();
9950
9951 return isReadOnly;
9952 }
9953
9954 // ----------------------------------------------------------------------------
9955 // attribute support: cache, automatic provider creation, ...
9956 // ----------------------------------------------------------------------------
9957
9958 bool wxGrid::CanHaveAttributes() const
9959 {
9960 if ( !m_table )
9961 {
9962 return false;
9963 }
9964
9965 return m_table->CanHaveAttributes();
9966 }
9967
9968 void wxGrid::ClearAttrCache()
9969 {
9970 if ( m_attrCache.row != -1 )
9971 {
9972 wxGridCellAttr *oldAttr = m_attrCache.attr;
9973 m_attrCache.attr = NULL;
9974 m_attrCache.row = -1;
9975 // wxSafeDecRec(...) might cause event processing that accesses
9976 // the cached attribute, if one exists (e.g. by deleting the
9977 // editor stored within the attribute). Therefore it is important
9978 // to invalidate the cache before calling wxSafeDecRef!
9979 wxSafeDecRef(oldAttr);
9980 }
9981 }
9982
9983 void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const
9984 {
9985 if ( attr != NULL )
9986 {
9987 wxGrid *self = (wxGrid *)this; // const_cast
9988
9989 self->ClearAttrCache();
9990 self->m_attrCache.row = row;
9991 self->m_attrCache.col = col;
9992 self->m_attrCache.attr = attr;
9993 wxSafeIncRef(attr);
9994 }
9995 }
9996
9997 bool wxGrid::LookupAttr(int row, int col, wxGridCellAttr **attr) const
9998 {
9999 if ( row == m_attrCache.row && col == m_attrCache.col )
10000 {
10001 *attr = m_attrCache.attr;
10002 wxSafeIncRef(m_attrCache.attr);
10003
10004 #ifdef DEBUG_ATTR_CACHE
10005 gs_nAttrCacheHits++;
10006 #endif
10007
10008 return true;
10009 }
10010 else
10011 {
10012 #ifdef DEBUG_ATTR_CACHE
10013 gs_nAttrCacheMisses++;
10014 #endif
10015
10016 return false;
10017 }
10018 }
10019
10020 wxGridCellAttr *wxGrid::GetCellAttr(int row, int col) const
10021 {
10022 wxGridCellAttr *attr = NULL;
10023 // Additional test to avoid looking at the cache e.g. for
10024 // wxNoCellCoords, as this will confuse memory management.
10025 if ( row >= 0 )
10026 {
10027 if ( !LookupAttr(row, col, &attr) )
10028 {
10029 attr = m_table ? m_table->GetAttr(row, col, wxGridCellAttr::Any)
10030 : NULL;
10031 CacheAttr(row, col, attr);
10032 }
10033 }
10034
10035 if (attr)
10036 {
10037 attr->SetDefAttr(m_defaultCellAttr);
10038 }
10039 else
10040 {
10041 attr = m_defaultCellAttr;
10042 attr->IncRef();
10043 }
10044
10045 return attr;
10046 }
10047
10048 wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const
10049 {
10050 wxGridCellAttr *attr = NULL;
10051 bool canHave = ((wxGrid*)this)->CanHaveAttributes();
10052
10053 wxCHECK_MSG( canHave, attr, _T("Cell attributes not allowed"));
10054 wxCHECK_MSG( m_table, attr, _T("must have a table") );
10055
10056 attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell);
10057 if ( !attr )
10058 {
10059 attr = new wxGridCellAttr(m_defaultCellAttr);
10060
10061 // artificially inc the ref count to match DecRef() in caller
10062 attr->IncRef();
10063 m_table->SetAttr(attr, row, col);
10064 }
10065
10066 return attr;
10067 }
10068
10069 // ----------------------------------------------------------------------------
10070 // setting column attributes (wrappers around SetColAttr)
10071 // ----------------------------------------------------------------------------
10072
10073 void wxGrid::SetColFormatBool(int col)
10074 {
10075 SetColFormatCustom(col, wxGRID_VALUE_BOOL);
10076 }
10077
10078 void wxGrid::SetColFormatNumber(int col)
10079 {
10080 SetColFormatCustom(col, wxGRID_VALUE_NUMBER);
10081 }
10082
10083 void wxGrid::SetColFormatFloat(int col, int width, int precision)
10084 {
10085 wxString typeName = wxGRID_VALUE_FLOAT;
10086 if ( (width != -1) || (precision != -1) )
10087 {
10088 typeName << _T(':') << width << _T(',') << precision;
10089 }
10090
10091 SetColFormatCustom(col, typeName);
10092 }
10093
10094 void wxGrid::SetColFormatCustom(int col, const wxString& typeName)
10095 {
10096 wxGridCellAttr *attr = m_table->GetAttr(-1, col, wxGridCellAttr::Col );
10097 if (!attr)
10098 attr = new wxGridCellAttr;
10099 wxGridCellRenderer *renderer = GetDefaultRendererForType(typeName);
10100 attr->SetRenderer(renderer);
10101 wxGridCellEditor *editor = GetDefaultEditorForType(typeName);
10102 attr->SetEditor(editor);
10103
10104 SetColAttr(col, attr);
10105
10106 }
10107
10108 // ----------------------------------------------------------------------------
10109 // setting cell attributes: this is forwarded to the table
10110 // ----------------------------------------------------------------------------
10111
10112 void wxGrid::SetAttr(int row, int col, wxGridCellAttr *attr)
10113 {
10114 if ( CanHaveAttributes() )
10115 {
10116 m_table->SetAttr(attr, row, col);
10117 ClearAttrCache();
10118 }
10119 else
10120 {
10121 wxSafeDecRef(attr);
10122 }
10123 }
10124
10125 void wxGrid::SetRowAttr(int row, wxGridCellAttr *attr)
10126 {
10127 if ( CanHaveAttributes() )
10128 {
10129 m_table->SetRowAttr(attr, row);
10130 ClearAttrCache();
10131 }
10132 else
10133 {
10134 wxSafeDecRef(attr);
10135 }
10136 }
10137
10138 void wxGrid::SetColAttr(int col, wxGridCellAttr *attr)
10139 {
10140 if ( CanHaveAttributes() )
10141 {
10142 m_table->SetColAttr(attr, col);
10143 ClearAttrCache();
10144 }
10145 else
10146 {
10147 wxSafeDecRef(attr);
10148 }
10149 }
10150
10151 void wxGrid::SetCellBackgroundColour( int row, int col, const wxColour& colour )
10152 {
10153 if ( CanHaveAttributes() )
10154 {
10155 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10156 attr->SetBackgroundColour(colour);
10157 attr->DecRef();
10158 }
10159 }
10160
10161 void wxGrid::SetCellTextColour( int row, int col, const wxColour& colour )
10162 {
10163 if ( CanHaveAttributes() )
10164 {
10165 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10166 attr->SetTextColour(colour);
10167 attr->DecRef();
10168 }
10169 }
10170
10171 void wxGrid::SetCellFont( int row, int col, const wxFont& font )
10172 {
10173 if ( CanHaveAttributes() )
10174 {
10175 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10176 attr->SetFont(font);
10177 attr->DecRef();
10178 }
10179 }
10180
10181 void wxGrid::SetCellAlignment( int row, int col, int horiz, int vert )
10182 {
10183 if ( CanHaveAttributes() )
10184 {
10185 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10186 attr->SetAlignment(horiz, vert);
10187 attr->DecRef();
10188 }
10189 }
10190
10191 void wxGrid::SetCellOverflow( int row, int col, bool allow )
10192 {
10193 if ( CanHaveAttributes() )
10194 {
10195 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10196 attr->SetOverflow(allow);
10197 attr->DecRef();
10198 }
10199 }
10200
10201 void wxGrid::SetCellSize( int row, int col, int num_rows, int num_cols )
10202 {
10203 if ( CanHaveAttributes() )
10204 {
10205 int cell_rows, cell_cols;
10206
10207 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10208 attr->GetSize(&cell_rows, &cell_cols);
10209 attr->SetSize(num_rows, num_cols);
10210 attr->DecRef();
10211
10212 // Cannot set the size of a cell to 0 or negative values
10213 // While it is perfectly legal to do that, this function cannot
10214 // handle all the possibilies, do it by hand by getting the CellAttr.
10215 // You can only set the size of a cell to 1,1 or greater with this fn
10216 wxASSERT_MSG( !((cell_rows < 1) || (cell_cols < 1)),
10217 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
10218 wxASSERT_MSG( !((num_rows < 1) || (num_cols < 1)),
10219 wxT("wxGrid::SetCellSize setting cell size to < 1"));
10220
10221 // if this was already a multicell then "turn off" the other cells first
10222 if ((cell_rows > 1) || (cell_cols > 1))
10223 {
10224 int i, j;
10225 for (j=row; j < row + cell_rows; j++)
10226 {
10227 for (i=col; i < col + cell_cols; i++)
10228 {
10229 if ((i != col) || (j != row))
10230 {
10231 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10232 attr_stub->SetSize( 1, 1 );
10233 attr_stub->DecRef();
10234 }
10235 }
10236 }
10237 }
10238
10239 // mark the cells that will be covered by this cell to
10240 // negative or zero values to point back at this cell
10241 if (((num_rows > 1) || (num_cols > 1)) && (num_rows >= 1) && (num_cols >= 1))
10242 {
10243 int i, j;
10244 for (j=row; j < row + num_rows; j++)
10245 {
10246 for (i=col; i < col + num_cols; i++)
10247 {
10248 if ((i != col) || (j != row))
10249 {
10250 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10251 attr_stub->SetSize( row - j, col - i );
10252 attr_stub->DecRef();
10253 }
10254 }
10255 }
10256 }
10257 }
10258 }
10259
10260 void wxGrid::SetCellRenderer(int row, int col, wxGridCellRenderer *renderer)
10261 {
10262 if ( CanHaveAttributes() )
10263 {
10264 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10265 attr->SetRenderer(renderer);
10266 attr->DecRef();
10267 }
10268 }
10269
10270 void wxGrid::SetCellEditor(int row, int col, wxGridCellEditor* editor)
10271 {
10272 if ( CanHaveAttributes() )
10273 {
10274 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10275 attr->SetEditor(editor);
10276 attr->DecRef();
10277 }
10278 }
10279
10280 void wxGrid::SetReadOnly(int row, int col, bool isReadOnly)
10281 {
10282 if ( CanHaveAttributes() )
10283 {
10284 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10285 attr->SetReadOnly(isReadOnly);
10286 attr->DecRef();
10287 }
10288 }
10289
10290 // ----------------------------------------------------------------------------
10291 // Data type registration
10292 // ----------------------------------------------------------------------------
10293
10294 void wxGrid::RegisterDataType(const wxString& typeName,
10295 wxGridCellRenderer* renderer,
10296 wxGridCellEditor* editor)
10297 {
10298 m_typeRegistry->RegisterDataType(typeName, renderer, editor);
10299 }
10300
10301
10302 wxGridCellEditor * wxGrid::GetDefaultEditorForCell(int row, int col) const
10303 {
10304 wxString typeName = m_table->GetTypeName(row, col);
10305 return GetDefaultEditorForType(typeName);
10306 }
10307
10308 wxGridCellRenderer * wxGrid::GetDefaultRendererForCell(int row, int col) const
10309 {
10310 wxString typeName = m_table->GetTypeName(row, col);
10311 return GetDefaultRendererForType(typeName);
10312 }
10313
10314 wxGridCellEditor * wxGrid::GetDefaultEditorForType(const wxString& typeName) const
10315 {
10316 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10317 if ( index == wxNOT_FOUND )
10318 {
10319 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
10320
10321 return NULL;
10322 }
10323
10324 return m_typeRegistry->GetEditor(index);
10325 }
10326
10327 wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) const
10328 {
10329 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10330 if ( index == wxNOT_FOUND )
10331 {
10332 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
10333
10334 return NULL;
10335 }
10336
10337 return m_typeRegistry->GetRenderer(index);
10338 }
10339
10340 // ----------------------------------------------------------------------------
10341 // row/col size
10342 // ----------------------------------------------------------------------------
10343
10344 void wxGrid::EnableDragRowSize( bool enable )
10345 {
10346 m_canDragRowSize = enable;
10347 }
10348
10349 void wxGrid::EnableDragColSize( bool enable )
10350 {
10351 m_canDragColSize = enable;
10352 }
10353
10354 void wxGrid::EnableDragGridSize( bool enable )
10355 {
10356 m_canDragGridSize = enable;
10357 }
10358
10359 void wxGrid::EnableDragCell( bool enable )
10360 {
10361 m_canDragCell = enable;
10362 }
10363
10364 void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows )
10365 {
10366 m_defaultRowHeight = wxMax( height, m_minAcceptableRowHeight );
10367
10368 if ( resizeExistingRows )
10369 {
10370 // since we are resizing all rows to the default row size,
10371 // we can simply clear the row heights and row bottoms
10372 // arrays (which also allows us to take advantage of
10373 // some speed optimisations)
10374 m_rowHeights.Empty();
10375 m_rowBottoms.Empty();
10376 if ( !GetBatchCount() )
10377 CalcDimensions();
10378 }
10379 }
10380
10381 void wxGrid::SetRowSize( int row, int height )
10382 {
10383 wxCHECK_RET( row >= 0 && row < m_numRows, _T("invalid row index") );
10384
10385 // if < 0 then calculate new height from label
10386 if ( height < 0 )
10387 {
10388 long w, h;
10389 wxArrayString lines;
10390 wxClientDC dc(m_rowLabelWin);
10391 dc.SetFont(GetLabelFont());
10392 StringToLines(GetRowLabelValue( row ), lines);
10393 GetTextBoxSize( dc, lines, &w, &h );
10394 //check that it is not less than the minimal height
10395 height = wxMax(h, GetRowMinimalAcceptableHeight());
10396 }
10397
10398 // See comment in SetColSize
10399 if ( height < GetRowMinimalAcceptableHeight())
10400 return;
10401
10402 if ( m_rowHeights.IsEmpty() )
10403 {
10404 // need to really create the array
10405 InitRowHeights();
10406 }
10407
10408 int h = wxMax( 0, height );
10409 int diff = h - m_rowHeights[row];
10410
10411 m_rowHeights[row] = h;
10412 for ( int i = row; i < m_numRows; i++ )
10413 {
10414 m_rowBottoms[i] += diff;
10415 }
10416
10417 if ( !GetBatchCount() )
10418 CalcDimensions();
10419 }
10420
10421 void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols )
10422 {
10423 // we dont allow zero default column width
10424 m_defaultColWidth = wxMax( wxMax( width, m_minAcceptableColWidth ), 1 );
10425
10426 if ( resizeExistingCols )
10427 {
10428 // since we are resizing all columns to the default column size,
10429 // we can simply clear the col widths and col rights
10430 // arrays (which also allows us to take advantage of
10431 // some speed optimisations)
10432 m_colWidths.Empty();
10433 m_colRights.Empty();
10434 if ( !GetBatchCount() )
10435 CalcDimensions();
10436 }
10437 }
10438
10439 void wxGrid::SetColSize( int col, int width )
10440 {
10441 wxCHECK_RET( col >= 0 && col < m_numCols, _T("invalid column index") );
10442
10443 // if < 0 then calculate new width from label
10444 if ( width < 0 )
10445 {
10446 long w, h;
10447 wxArrayString lines;
10448 wxClientDC dc(m_colWindow);
10449 dc.SetFont(GetLabelFont());
10450 StringToLines(GetColLabelValue(col), lines);
10451 if ( GetColLabelTextOrientation() == wxHORIZONTAL )
10452 GetTextBoxSize( dc, lines, &w, &h );
10453 else
10454 GetTextBoxSize( dc, lines, &h, &w );
10455 width = w + 6;
10456 //check that it is not less than the minimal width
10457 width = wxMax(width, GetColMinimalAcceptableWidth());
10458 }
10459
10460 // we intentionally don't test whether the width is less than
10461 // GetColMinimalWidth() here but we do compare it with
10462 // GetColMinimalAcceptableWidth() as otherwise things currently break (see
10463 // #651) -- and we also always allow the width of 0 as it has the special
10464 // sense of hiding the column
10465 if ( width > 0 && width < GetColMinimalAcceptableWidth() )
10466 return;
10467
10468 if ( m_colWidths.IsEmpty() )
10469 {
10470 // need to really create the array
10471 InitColWidths();
10472 }
10473
10474 const int diff = width - m_colWidths[col];
10475 m_colWidths[col] = width;
10476 if ( m_useNativeHeader )
10477 GetGridColHeader()->UpdateColumn(col);
10478 //else: will be refreshed when the header is redrawn
10479
10480 for ( int colPos = GetColPos(col); colPos < m_numCols; colPos++ )
10481 {
10482 m_colRights[GetColAt(colPos)] += diff;
10483 }
10484
10485 if ( !GetBatchCount() )
10486 {
10487 CalcDimensions();
10488 Refresh();
10489 }
10490 }
10491
10492 void wxGrid::SetColMinimalWidth( int col, int width )
10493 {
10494 if (width > GetColMinimalAcceptableWidth())
10495 {
10496 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10497 m_colMinWidths[key] = width;
10498 }
10499 }
10500
10501 void wxGrid::SetRowMinimalHeight( int row, int width )
10502 {
10503 if (width > GetRowMinimalAcceptableHeight())
10504 {
10505 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10506 m_rowMinHeights[key] = width;
10507 }
10508 }
10509
10510 int wxGrid::GetColMinimalWidth(int col) const
10511 {
10512 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10513 wxLongToLongHashMap::const_iterator it = m_colMinWidths.find(key);
10514
10515 return it != m_colMinWidths.end() ? (int)it->second : m_minAcceptableColWidth;
10516 }
10517
10518 int wxGrid::GetRowMinimalHeight(int row) const
10519 {
10520 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10521 wxLongToLongHashMap::const_iterator it = m_rowMinHeights.find(key);
10522
10523 return it != m_rowMinHeights.end() ? (int)it->second : m_minAcceptableRowHeight;
10524 }
10525
10526 void wxGrid::SetColMinimalAcceptableWidth( int width )
10527 {
10528 // We do allow a width of 0 since this gives us
10529 // an easy way to temporarily hiding columns.
10530 if ( width >= 0 )
10531 m_minAcceptableColWidth = width;
10532 }
10533
10534 void wxGrid::SetRowMinimalAcceptableHeight( int height )
10535 {
10536 // We do allow a height of 0 since this gives us
10537 // an easy way to temporarily hiding rows.
10538 if ( height >= 0 )
10539 m_minAcceptableRowHeight = height;
10540 }
10541
10542 int wxGrid::GetColMinimalAcceptableWidth() const
10543 {
10544 return m_minAcceptableColWidth;
10545 }
10546
10547 int wxGrid::GetRowMinimalAcceptableHeight() const
10548 {
10549 return m_minAcceptableRowHeight;
10550 }
10551
10552 // ----------------------------------------------------------------------------
10553 // auto sizing
10554 // ----------------------------------------------------------------------------
10555
10556 void
10557 wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction)
10558 {
10559 const bool column = direction == wxGRID_COLUMN;
10560
10561 wxClientDC dc(m_gridWin);
10562
10563 // cancel editing of cell
10564 HideCellEditControl();
10565 SaveEditControlValue();
10566
10567 // init both of them to avoid compiler warnings, even if we only need one
10568 int row = -1,
10569 col = -1;
10570 if ( column )
10571 col = colOrRow;
10572 else
10573 row = colOrRow;
10574
10575 wxCoord extent, extentMax = 0;
10576 int max = column ? m_numRows : m_numCols;
10577 for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ )
10578 {
10579 if ( column )
10580 row = rowOrCol;
10581 else
10582 col = rowOrCol;
10583
10584 wxGridCellAttr *attr = GetCellAttr(row, col);
10585 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
10586 if ( renderer )
10587 {
10588 wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col);
10589 extent = column ? size.x : size.y;
10590 if ( extent > extentMax )
10591 extentMax = extent;
10592
10593 renderer->DecRef();
10594 }
10595
10596 attr->DecRef();
10597 }
10598
10599 // now also compare with the column label extent
10600 wxCoord w, h;
10601 dc.SetFont( GetLabelFont() );
10602
10603 if ( column )
10604 {
10605 dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h );
10606 if ( GetColLabelTextOrientation() == wxVERTICAL )
10607 w = h;
10608 }
10609 else
10610 dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h );
10611
10612 extent = column ? w : h;
10613 if ( extent > extentMax )
10614 extentMax = extent;
10615
10616 if ( !extentMax )
10617 {
10618 // empty column - give default extent (notice that if extentMax is less
10619 // than default extent but != 0, it's OK)
10620 extentMax = column ? m_defaultColWidth : m_defaultRowHeight;
10621 }
10622 else
10623 {
10624 if ( column )
10625 // leave some space around text
10626 extentMax += 10;
10627 else
10628 extentMax += 6;
10629 }
10630
10631 if ( column )
10632 {
10633 // Ensure automatic width is not less than minimal width. See the
10634 // comment in SetColSize() for explanation of why this isn't done
10635 // in SetColSize().
10636 if ( !setAsMin )
10637 extentMax = wxMax(extentMax, GetColMinimalWidth(col));
10638
10639 SetColSize( col, extentMax );
10640 if ( !GetBatchCount() )
10641 {
10642 if ( m_useNativeHeader )
10643 {
10644 GetGridColHeader()->UpdateColumn(col);
10645 }
10646 else
10647 {
10648 int cw, ch, dummy;
10649 m_gridWin->GetClientSize( &cw, &ch );
10650 wxRect rect ( CellToRect( 0, col ) );
10651 rect.y = 0;
10652 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
10653 rect.width = cw - rect.x;
10654 rect.height = m_colLabelHeight;
10655 GetColLabelWindow()->Refresh( true, &rect );
10656 }
10657 }
10658 }
10659 else
10660 {
10661 // Ensure automatic width is not less than minimal height. See the
10662 // comment in SetColSize() for explanation of why this isn't done
10663 // in SetRowSize().
10664 if ( !setAsMin )
10665 extentMax = wxMax(extentMax, GetRowMinimalHeight(row));
10666
10667 SetRowSize(row, extentMax);
10668 if ( !GetBatchCount() )
10669 {
10670 int cw, ch, dummy;
10671 m_gridWin->GetClientSize( &cw, &ch );
10672 wxRect rect( CellToRect( row, 0 ) );
10673 rect.x = 0;
10674 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10675 rect.width = m_rowLabelWidth;
10676 rect.height = ch - rect.y;
10677 m_rowLabelWin->Refresh( true, &rect );
10678 }
10679 }
10680
10681 if ( setAsMin )
10682 {
10683 if ( column )
10684 SetColMinimalWidth(col, extentMax);
10685 else
10686 SetRowMinimalHeight(row, extentMax);
10687 }
10688 }
10689
10690 wxCoord wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction)
10691 {
10692 // calculate size for the rows or columns?
10693 const bool calcRows = direction == wxGRID_ROW;
10694
10695 wxClientDC dc(calcRows ? GetGridRowLabelWindow()
10696 : GetGridColLabelWindow());
10697 dc.SetFont(GetLabelFont());
10698
10699 // which dimension should we take into account for calculations?
10700 //
10701 // for columns, the text can be only horizontal so it's easy but for rows
10702 // we also have to take into account the text orientation
10703 const bool
10704 useWidth = calcRows || (GetColLabelTextOrientation() == wxVERTICAL);
10705
10706 wxArrayString lines;
10707 wxCoord extentMax = 0;
10708
10709 const int numRowsOrCols = calcRows ? m_numRows : m_numCols;
10710 for ( int rowOrCol = 0; rowOrCol < numRowsOrCols; rowOrCol++ )
10711 {
10712 lines.Clear();
10713
10714 wxString label = calcRows ? GetRowLabelValue(rowOrCol)
10715 : GetColLabelValue(rowOrCol);
10716 StringToLines(label, lines);
10717
10718 long w, h;
10719 GetTextBoxSize(dc, lines, &w, &h);
10720
10721 const wxCoord extent = useWidth ? w : h;
10722 if ( extent > extentMax )
10723 extentMax = extent;
10724 }
10725
10726 if ( !extentMax )
10727 {
10728 // empty column - give default extent (notice that if extentMax is less
10729 // than default extent but != 0, it's OK)
10730 extentMax = calcRows ? GetDefaultRowLabelSize()
10731 : GetDefaultColLabelSize();
10732 }
10733
10734 // leave some space around text (taken from AutoSizeColOrRow)
10735 if ( calcRows )
10736 extentMax += 10;
10737 else
10738 extentMax += 6;
10739
10740 return extentMax;
10741 }
10742
10743 int wxGrid::SetOrCalcColumnSizes(bool calcOnly, bool setAsMin)
10744 {
10745 int width = m_rowLabelWidth;
10746
10747 wxGridUpdateLocker locker;
10748 if(!calcOnly)
10749 locker.Create(this);
10750
10751 for ( int col = 0; col < m_numCols; col++ )
10752 {
10753 if ( !calcOnly )
10754 AutoSizeColumn(col, setAsMin);
10755
10756 width += GetColWidth(col);
10757 }
10758
10759 return width;
10760 }
10761
10762 int wxGrid::SetOrCalcRowSizes(bool calcOnly, bool setAsMin)
10763 {
10764 int height = m_colLabelHeight;
10765
10766 wxGridUpdateLocker locker;
10767 if(!calcOnly)
10768 locker.Create(this);
10769
10770 for ( int row = 0; row < m_numRows; row++ )
10771 {
10772 if ( !calcOnly )
10773 AutoSizeRow(row, setAsMin);
10774
10775 height += GetRowHeight(row);
10776 }
10777
10778 return height;
10779 }
10780
10781 void wxGrid::AutoSize()
10782 {
10783 wxGridUpdateLocker locker(this);
10784
10785 wxSize size(SetOrCalcColumnSizes(false) - m_rowLabelWidth + m_extraWidth,
10786 SetOrCalcRowSizes(false) - m_colLabelHeight + m_extraHeight);
10787
10788 // we know that we're not going to have scrollbars so disable them now to
10789 // avoid trouble in SetClientSize() which can otherwise set the correct
10790 // client size but also leave space for (not needed any more) scrollbars
10791 SetScrollbars(0, 0, 0, 0, 0, 0, true);
10792
10793 // restore the scroll rate parameters overwritten by SetScrollbars()
10794 SetScrollRate(m_scrollLineX, m_scrollLineY);
10795
10796 SetClientSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight);
10797 }
10798
10799 void wxGrid::AutoSizeRowLabelSize( int row )
10800 {
10801 // Hide the edit control, so it
10802 // won't interfere with drag-shrinking.
10803 if ( IsCellEditControlShown() )
10804 {
10805 HideCellEditControl();
10806 SaveEditControlValue();
10807 }
10808
10809 // autosize row height depending on label text
10810 SetRowSize(row, -1);
10811 ForceRefresh();
10812 }
10813
10814 void wxGrid::AutoSizeColLabelSize( int col )
10815 {
10816 // Hide the edit control, so it
10817 // won't interfere with drag-shrinking.
10818 if ( IsCellEditControlShown() )
10819 {
10820 HideCellEditControl();
10821 SaveEditControlValue();
10822 }
10823
10824 // autosize column width depending on label text
10825 SetColSize(col, -1);
10826 ForceRefresh();
10827 }
10828
10829 wxSize wxGrid::DoGetBestSize() const
10830 {
10831 wxGrid *self = (wxGrid *)this; // const_cast
10832
10833 // we do the same as in AutoSize() here with the exception that we don't
10834 // change the column/row sizes, only calculate them
10835 wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth,
10836 self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight);
10837
10838 // NOTE: This size should be cached, but first we need to add calls to
10839 // InvalidateBestSize everywhere that could change the results of this
10840 // calculation.
10841 // CacheBestSize(size);
10842
10843 return wxSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight)
10844 + GetWindowBorderSize();
10845 }
10846
10847 void wxGrid::Fit()
10848 {
10849 AutoSize();
10850 }
10851
10852 wxPen& wxGrid::GetDividerPen() const
10853 {
10854 return wxNullPen;
10855 }
10856
10857 // ----------------------------------------------------------------------------
10858 // cell value accessor functions
10859 // ----------------------------------------------------------------------------
10860
10861 void wxGrid::SetCellValue( int row, int col, const wxString& s )
10862 {
10863 if ( m_table )
10864 {
10865 m_table->SetValue( row, col, s );
10866 if ( !GetBatchCount() )
10867 {
10868 int dummy;
10869 wxRect rect( CellToRect( row, col ) );
10870 rect.x = 0;
10871 rect.width = m_gridWin->GetClientSize().GetWidth();
10872 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10873 m_gridWin->Refresh( false, &rect );
10874 }
10875
10876 if ( m_currentCellCoords.GetRow() == row &&
10877 m_currentCellCoords.GetCol() == col &&
10878 IsCellEditControlShown())
10879 // Note: If we are using IsCellEditControlEnabled,
10880 // this interacts badly with calling SetCellValue from
10881 // an EVT_GRID_CELL_CHANGE handler.
10882 {
10883 HideCellEditControl();
10884 ShowCellEditControl(); // will reread data from table
10885 }
10886 }
10887 }
10888
10889 // ----------------------------------------------------------------------------
10890 // block, row and column selection
10891 // ----------------------------------------------------------------------------
10892
10893 void wxGrid::SelectRow( int row, bool addToSelected )
10894 {
10895 if ( !m_selection )
10896 return;
10897
10898 if ( !addToSelected )
10899 ClearSelection();
10900
10901 m_selection->SelectRow(row);
10902 }
10903
10904 void wxGrid::SelectCol( int col, bool addToSelected )
10905 {
10906 if ( !m_selection )
10907 return;
10908
10909 if ( !addToSelected )
10910 ClearSelection();
10911
10912 m_selection->SelectCol(col);
10913 }
10914
10915 void wxGrid::SelectBlock(int topRow, int leftCol, int bottomRow, int rightCol,
10916 bool addToSelected)
10917 {
10918 if ( !m_selection )
10919 return;
10920
10921 if ( !addToSelected )
10922 ClearSelection();
10923
10924 m_selection->SelectBlock(topRow, leftCol, bottomRow, rightCol);
10925 }
10926
10927 void wxGrid::SelectAll()
10928 {
10929 if ( m_numRows > 0 && m_numCols > 0 )
10930 {
10931 if ( m_selection )
10932 m_selection->SelectBlock( 0, 0, m_numRows - 1, m_numCols - 1 );
10933 }
10934 }
10935
10936 // ----------------------------------------------------------------------------
10937 // cell, row and col deselection
10938 // ----------------------------------------------------------------------------
10939
10940 void wxGrid::DeselectLine(int line, const wxGridOperations& oper)
10941 {
10942 if ( !m_selection )
10943 return;
10944
10945 const wxGridSelectionModes mode = m_selection->GetSelectionMode();
10946 if ( mode == oper.GetSelectionMode() )
10947 {
10948 const wxGridCellCoords c(oper.MakeCoords(line, 0));
10949 if ( m_selection->IsInSelection(c) )
10950 m_selection->ToggleCellSelection(c);
10951 }
10952 else if ( mode != oper.Dual().GetSelectionMode() )
10953 {
10954 const int nOther = oper.Dual().GetNumberOfLines(this);
10955 for ( int i = 0; i < nOther; i++ )
10956 {
10957 const wxGridCellCoords c(oper.MakeCoords(line, i));
10958 if ( m_selection->IsInSelection(c) )
10959 m_selection->ToggleCellSelection(c);
10960 }
10961 }
10962 //else: can only select orthogonal lines so no lines in this direction
10963 // could have been selected anyhow
10964 }
10965
10966 void wxGrid::DeselectRow(int row)
10967 {
10968 DeselectLine(row, wxGridRowOperations());
10969 }
10970
10971 void wxGrid::DeselectCol(int col)
10972 {
10973 DeselectLine(col, wxGridColumnOperations());
10974 }
10975
10976 void wxGrid::DeselectCell( int row, int col )
10977 {
10978 if ( m_selection && m_selection->IsInSelection(row, col) )
10979 m_selection->ToggleCellSelection(row, col);
10980 }
10981
10982 bool wxGrid::IsSelection() const
10983 {
10984 return ( m_selection && (m_selection->IsSelection() ||
10985 ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
10986 m_selectedBlockBottomRight != wxGridNoCellCoords) ) );
10987 }
10988
10989 bool wxGrid::IsInSelection( int row, int col ) const
10990 {
10991 return ( m_selection && (m_selection->IsInSelection( row, col ) ||
10992 ( row >= m_selectedBlockTopLeft.GetRow() &&
10993 col >= m_selectedBlockTopLeft.GetCol() &&
10994 row <= m_selectedBlockBottomRight.GetRow() &&
10995 col <= m_selectedBlockBottomRight.GetCol() )) );
10996 }
10997
10998 wxGridCellCoordsArray wxGrid::GetSelectedCells() const
10999 {
11000 if (!m_selection)
11001 {
11002 wxGridCellCoordsArray a;
11003 return a;
11004 }
11005
11006 return m_selection->m_cellSelection;
11007 }
11008
11009 wxGridCellCoordsArray wxGrid::GetSelectionBlockTopLeft() const
11010 {
11011 if (!m_selection)
11012 {
11013 wxGridCellCoordsArray a;
11014 return a;
11015 }
11016
11017 return m_selection->m_blockSelectionTopLeft;
11018 }
11019
11020 wxGridCellCoordsArray wxGrid::GetSelectionBlockBottomRight() const
11021 {
11022 if (!m_selection)
11023 {
11024 wxGridCellCoordsArray a;
11025 return a;
11026 }
11027
11028 return m_selection->m_blockSelectionBottomRight;
11029 }
11030
11031 wxArrayInt wxGrid::GetSelectedRows() const
11032 {
11033 if (!m_selection)
11034 {
11035 wxArrayInt a;
11036 return a;
11037 }
11038
11039 return m_selection->m_rowSelection;
11040 }
11041
11042 wxArrayInt wxGrid::GetSelectedCols() const
11043 {
11044 if (!m_selection)
11045 {
11046 wxArrayInt a;
11047 return a;
11048 }
11049
11050 return m_selection->m_colSelection;
11051 }
11052
11053 void wxGrid::ClearSelection()
11054 {
11055 wxRect r1 = BlockToDeviceRect(m_selectedBlockTopLeft,
11056 m_selectedBlockBottomRight);
11057 wxRect r2 = BlockToDeviceRect(m_currentCellCoords,
11058 m_selectedBlockCorner);
11059
11060 m_selectedBlockTopLeft =
11061 m_selectedBlockBottomRight =
11062 m_selectedBlockCorner = wxGridNoCellCoords;
11063
11064 Refresh( false, &r1 );
11065 Refresh( false, &r2 );
11066
11067 if ( m_selection )
11068 m_selection->ClearSelection();
11069 }
11070
11071 // This function returns the rectangle that encloses the given block
11072 // in device coords clipped to the client size of the grid window.
11073 //
11074 wxRect wxGrid::BlockToDeviceRect( const wxGridCellCoords& topLeft,
11075 const wxGridCellCoords& bottomRight ) const
11076 {
11077 wxRect resultRect;
11078 wxRect tempCellRect = CellToRect(topLeft);
11079 if ( tempCellRect != wxGridNoCellRect )
11080 {
11081 resultRect = tempCellRect;
11082 }
11083 else
11084 {
11085 resultRect = wxRect(0, 0, 0, 0);
11086 }
11087
11088 tempCellRect = CellToRect(bottomRight);
11089 if ( tempCellRect != wxGridNoCellRect )
11090 {
11091 resultRect += tempCellRect;
11092 }
11093 else
11094 {
11095 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
11096 return wxGridNoCellRect;
11097 }
11098
11099 // Ensure that left/right and top/bottom pairs are in order.
11100 int left = resultRect.GetLeft();
11101 int top = resultRect.GetTop();
11102 int right = resultRect.GetRight();
11103 int bottom = resultRect.GetBottom();
11104
11105 int leftCol = topLeft.GetCol();
11106 int topRow = topLeft.GetRow();
11107 int rightCol = bottomRight.GetCol();
11108 int bottomRow = bottomRight.GetRow();
11109
11110 if (left > right)
11111 {
11112 int tmp = left;
11113 left = right;
11114 right = tmp;
11115
11116 tmp = leftCol;
11117 leftCol = rightCol;
11118 rightCol = tmp;
11119 }
11120
11121 if (top > bottom)
11122 {
11123 int tmp = top;
11124 top = bottom;
11125 bottom = tmp;
11126
11127 tmp = topRow;
11128 topRow = bottomRow;
11129 bottomRow = tmp;
11130 }
11131
11132 // The following loop is ONLY necessary to detect and handle merged cells.
11133 int cw, ch;
11134 m_gridWin->GetClientSize( &cw, &ch );
11135
11136 // Get the origin coordinates: notice that they will be negative if the
11137 // grid is scrolled downwards/to the right.
11138 int gridOriginX = 0;
11139 int gridOriginY = 0;
11140 CalcScrolledPosition(gridOriginX, gridOriginY, &gridOriginX, &gridOriginY);
11141
11142 int onScreenLeftmostCol = internalXToCol(-gridOriginX);
11143 int onScreenUppermostRow = internalYToRow(-gridOriginY);
11144
11145 int onScreenRightmostCol = internalXToCol(-gridOriginX + cw);
11146 int onScreenBottommostRow = internalYToRow(-gridOriginY + ch);
11147
11148 // Bound our loop so that we only examine the portion of the selected block
11149 // that is shown on screen. Therefore, we compare the Top-Left block values
11150 // to the Top-Left screen values, and the Bottom-Right block values to the
11151 // Bottom-Right screen values, choosing appropriately.
11152 const int visibleTopRow = wxMax(topRow, onScreenUppermostRow);
11153 const int visibleBottomRow = wxMin(bottomRow, onScreenBottommostRow);
11154 const int visibleLeftCol = wxMax(leftCol, onScreenLeftmostCol);
11155 const int visibleRightCol = wxMin(rightCol, onScreenRightmostCol);
11156
11157 for ( int j = visibleTopRow; j <= visibleBottomRow; j++ )
11158 {
11159 for ( int i = visibleLeftCol; i <= visibleRightCol; i++ )
11160 {
11161 if ( (j == visibleTopRow) || (j == visibleBottomRow) ||
11162 (i == visibleLeftCol) || (i == visibleRightCol) )
11163 {
11164 tempCellRect = CellToRect( j, i );
11165
11166 if (tempCellRect.x < left)
11167 left = tempCellRect.x;
11168 if (tempCellRect.y < top)
11169 top = tempCellRect.y;
11170 if (tempCellRect.x + tempCellRect.width > right)
11171 right = tempCellRect.x + tempCellRect.width;
11172 if (tempCellRect.y + tempCellRect.height > bottom)
11173 bottom = tempCellRect.y + tempCellRect.height;
11174 }
11175 else
11176 {
11177 i = visibleRightCol; // jump over inner cells.
11178 }
11179 }
11180 }
11181
11182 // Convert to scrolled coords
11183 CalcScrolledPosition( left, top, &left, &top );
11184 CalcScrolledPosition( right, bottom, &right, &bottom );
11185
11186 if (right < 0 || bottom < 0 || left > cw || top > ch)
11187 return wxRect(0,0,0,0);
11188
11189 resultRect.SetLeft( wxMax(0, left) );
11190 resultRect.SetTop( wxMax(0, top) );
11191 resultRect.SetRight( wxMin(cw, right) );
11192 resultRect.SetBottom( wxMin(ch, bottom) );
11193
11194 return resultRect;
11195 }
11196
11197 // ----------------------------------------------------------------------------
11198 // drop target
11199 // ----------------------------------------------------------------------------
11200
11201 #if wxUSE_DRAG_AND_DROP
11202
11203 // this allow setting drop target directly on wxGrid
11204 void wxGrid::SetDropTarget(wxDropTarget *dropTarget)
11205 {
11206 GetGridWindow()->SetDropTarget(dropTarget);
11207 }
11208
11209 #endif // wxUSE_DRAG_AND_DROP
11210
11211 // ----------------------------------------------------------------------------
11212 // grid event classes
11213 // ----------------------------------------------------------------------------
11214
11215 IMPLEMENT_DYNAMIC_CLASS( wxGridEvent, wxNotifyEvent )
11216
11217 wxGridEvent::wxGridEvent( int id, wxEventType type, wxObject* obj,
11218 int row, int col, int x, int y, bool sel,
11219 bool control, bool shift, bool alt, bool meta )
11220 : wxNotifyEvent( type, id ),
11221 wxKeyboardState(control, shift, alt, meta)
11222 {
11223 Init(row, col, x, y, sel);
11224
11225 SetEventObject(obj);
11226 }
11227
11228 IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent, wxNotifyEvent )
11229
11230 wxGridSizeEvent::wxGridSizeEvent( int id, wxEventType type, wxObject* obj,
11231 int rowOrCol, int x, int y,
11232 bool control, bool shift, bool alt, bool meta )
11233 : wxNotifyEvent( type, id ),
11234 wxKeyboardState(control, shift, alt, meta)
11235 {
11236 Init(rowOrCol, x, y);
11237
11238 SetEventObject(obj);
11239 }
11240
11241
11242 IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent, wxNotifyEvent )
11243
11244 wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id, wxEventType type, wxObject* obj,
11245 const wxGridCellCoords& topLeft,
11246 const wxGridCellCoords& bottomRight,
11247 bool sel, bool control,
11248 bool shift, bool alt, bool meta )
11249 : wxNotifyEvent( type, id ),
11250 wxKeyboardState(control, shift, alt, meta)
11251 {
11252 Init(topLeft, bottomRight, sel);
11253
11254 SetEventObject(obj);
11255 }
11256
11257
11258 IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent, wxCommandEvent)
11259
11260 wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id, wxEventType type,
11261 wxObject* obj, int row,
11262 int col, wxControl* ctrl)
11263 : wxCommandEvent(type, id)
11264 {
11265 SetEventObject(obj);
11266 m_row = row;
11267 m_col = col;
11268 m_ctrl = ctrl;
11269 }
11270
11271 #endif // wxUSE_GRID