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