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