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