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