fix compuation of dirty cells when the columns are reordered, this didn't work at...
[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 index of 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 wxArrayInt cols;
5606 for ( int row = internalYToRow(top); row < m_numRows; row++ )
5607 {
5608 if ( GetRowBottom(row) <= top )
5609 continue;
5610
5611 if ( GetRowTop(row) > bottom )
5612 break;
5613
5614 // add all dirty cells in this row: notice that the columns which
5615 // are dirty don't depend on the row so we compute them only once
5616 // for the first dirty row and then reuse for all the next ones
5617 if ( cols.empty() )
5618 {
5619 // do determine the dirty columns
5620 for ( int pos = XToPos(left); pos <= XToPos(right); pos++ )
5621 cols.push_back(GetColAt(pos));
5622
5623 // if there are no dirty columns at all, nothing to do
5624 if ( cols.empty() )
5625 break;
5626 }
5627
5628 const size_t count = cols.size();
5629 for ( size_t n = 0; n < count; n++ )
5630 cellsExposed.Add(wxGridCellCoords(row, cols[n]));
5631 }
5632
5633 ++iter;
5634 }
5635
5636 return cellsExposed;
5637 }
5638
5639
5640 void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event )
5641 {
5642 int x, y, row;
5643 wxPoint pos( event.GetPosition() );
5644 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5645
5646 if ( event.Dragging() )
5647 {
5648 if (!m_isDragging)
5649 {
5650 m_isDragging = true;
5651 m_rowLabelWin->CaptureMouse();
5652 }
5653
5654 if ( event.LeftIsDown() )
5655 {
5656 switch ( m_cursorMode )
5657 {
5658 case WXGRID_CURSOR_RESIZE_ROW:
5659 {
5660 int cw, ch, left, dummy;
5661 m_gridWin->GetClientSize( &cw, &ch );
5662 CalcUnscrolledPosition( 0, 0, &left, &dummy );
5663
5664 wxClientDC dc( m_gridWin );
5665 PrepareDC( dc );
5666 y = wxMax( y,
5667 GetRowTop(m_dragRowOrCol) +
5668 GetRowMinimalHeight(m_dragRowOrCol) );
5669 dc.SetLogicalFunction(wxINVERT);
5670 if ( m_dragLastPos >= 0 )
5671 {
5672 dc.DrawLine( left, m_dragLastPos, left+cw, m_dragLastPos );
5673 }
5674 dc.DrawLine( left, y, left+cw, y );
5675 m_dragLastPos = y;
5676 }
5677 break;
5678
5679 case WXGRID_CURSOR_SELECT_ROW:
5680 {
5681 if ( (row = YToRow( y )) >= 0 )
5682 {
5683 if ( m_selection )
5684 m_selection->SelectRow(row, event);
5685 }
5686 }
5687 break;
5688
5689 // default label to suppress warnings about "enumeration value
5690 // 'xxx' not handled in switch
5691 default:
5692 break;
5693 }
5694 }
5695 return;
5696 }
5697
5698 if ( m_isDragging && (event.Entering() || event.Leaving()) )
5699 return;
5700
5701 if (m_isDragging)
5702 {
5703 if (m_rowLabelWin->HasCapture())
5704 m_rowLabelWin->ReleaseMouse();
5705 m_isDragging = false;
5706 }
5707
5708 // ------------ Entering or leaving the window
5709 //
5710 if ( event.Entering() || event.Leaving() )
5711 {
5712 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5713 }
5714
5715 // ------------ Left button pressed
5716 //
5717 else if ( event.LeftDown() )
5718 {
5719 // don't send a label click event for a hit on the
5720 // edge of the row label - this is probably the user
5721 // wanting to resize the row
5722 //
5723 if ( YToEdgeOfRow(y) < 0 )
5724 {
5725 row = YToRow(y);
5726 if ( row >= 0 &&
5727 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, row, -1, event ) )
5728 {
5729 if ( !event.ShiftDown() && !event.CmdDown() )
5730 ClearSelection();
5731 if ( m_selection )
5732 {
5733 if ( event.ShiftDown() )
5734 {
5735 m_selection->SelectBlock
5736 (
5737 m_currentCellCoords.GetRow(), 0,
5738 row, GetNumberCols() - 1,
5739 event
5740 );
5741 }
5742 else
5743 {
5744 m_selection->SelectRow(row, event);
5745 }
5746 }
5747
5748 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW, m_rowLabelWin);
5749 }
5750 }
5751 else
5752 {
5753 // starting to drag-resize a row
5754 if ( CanDragRowSize() )
5755 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin);
5756 }
5757 }
5758
5759 // ------------ Left double click
5760 //
5761 else if (event.LeftDClick() )
5762 {
5763 row = YToEdgeOfRow(y);
5764 if ( row < 0 )
5765 {
5766 row = YToRow(y);
5767 if ( row >=0 &&
5768 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, row, -1, event ) )
5769 {
5770 // no default action at the moment
5771 }
5772 }
5773 else
5774 {
5775 // adjust row height depending on label text
5776 AutoSizeRowLabelSize( row );
5777
5778 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
5779 m_dragLastPos = -1;
5780 }
5781 }
5782
5783 // ------------ Left button released
5784 //
5785 else if ( event.LeftUp() )
5786 {
5787 if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
5788 {
5789 DoEndDragResizeRow();
5790
5791 // Note: we are ending the event *after* doing
5792 // default processing in this case
5793 //
5794 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
5795 }
5796
5797 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5798 m_dragLastPos = -1;
5799 }
5800
5801 // ------------ Right button down
5802 //
5803 else if ( event.RightDown() )
5804 {
5805 row = YToRow(y);
5806 if ( row >=0 &&
5807 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, row, -1, event ) )
5808 {
5809 // no default action at the moment
5810 }
5811 }
5812
5813 // ------------ Right double click
5814 //
5815 else if ( event.RightDClick() )
5816 {
5817 row = YToRow(y);
5818 if ( row >= 0 &&
5819 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, row, -1, event ) )
5820 {
5821 // no default action at the moment
5822 }
5823 }
5824
5825 // ------------ No buttons down and mouse moving
5826 //
5827 else if ( event.Moving() )
5828 {
5829 m_dragRowOrCol = YToEdgeOfRow( y );
5830 if ( m_dragRowOrCol >= 0 )
5831 {
5832 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
5833 {
5834 // don't capture the mouse yet
5835 if ( CanDragRowSize() )
5836 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin, false);
5837 }
5838 }
5839 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
5840 {
5841 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin, false);
5842 }
5843 }
5844 }
5845
5846 void wxGrid::DoStartResizeCol(int col)
5847 {
5848 m_dragRowOrCol = col;
5849 m_dragLastPos = -1;
5850 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol));
5851 }
5852
5853 void wxGrid::DoUpdateResizeCol(int x)
5854 {
5855 int cw, ch, dummy, top;
5856 m_gridWin->GetClientSize( &cw, &ch );
5857 CalcUnscrolledPosition( 0, 0, &dummy, &top );
5858
5859 wxClientDC dc( m_gridWin );
5860 PrepareDC( dc );
5861
5862 x = wxMax( x, GetColLeft(m_dragRowOrCol) + GetColMinimalWidth(m_dragRowOrCol));
5863 dc.SetLogicalFunction(wxINVERT);
5864 if ( m_dragLastPos >= 0 )
5865 {
5866 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
5867 }
5868 dc.DrawLine( x, top, x, top + ch );
5869 m_dragLastPos = x;
5870 }
5871
5872 void wxGrid::DoUpdateResizeColWidth(int w)
5873 {
5874 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol) + w);
5875 }
5876
5877 void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event )
5878 {
5879 int x, y, col;
5880 wxPoint pos( event.GetPosition() );
5881 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5882
5883 if ( event.Dragging() )
5884 {
5885 if (!m_isDragging)
5886 {
5887 m_isDragging = true;
5888 GetColLabelWindow()->CaptureMouse();
5889
5890 if ( m_cursorMode == WXGRID_CURSOR_MOVE_COL )
5891 m_dragRowOrCol = XToCol( x );
5892 }
5893
5894 if ( event.LeftIsDown() )
5895 {
5896 switch ( m_cursorMode )
5897 {
5898 case WXGRID_CURSOR_RESIZE_COL:
5899 DoUpdateResizeCol(x);
5900 break;
5901
5902 case WXGRID_CURSOR_SELECT_COL:
5903 {
5904 if ( (col = XToCol( x )) >= 0 )
5905 {
5906 if ( m_selection )
5907 m_selection->SelectCol(col, event);
5908 }
5909 }
5910 break;
5911
5912 case WXGRID_CURSOR_MOVE_COL:
5913 {
5914 if ( x < 0 )
5915 m_moveToCol = GetColAt( 0 );
5916 else
5917 m_moveToCol = XToCol( x );
5918
5919 int markerX;
5920
5921 if ( m_moveToCol < 0 )
5922 markerX = GetColRight( GetColAt( m_numCols - 1 ) );
5923 else if ( x >= (GetColLeft( m_moveToCol ) + (GetColWidth(m_moveToCol) / 2)) )
5924 {
5925 m_moveToCol = GetColAt( GetColPos( m_moveToCol ) + 1 );
5926 if ( m_moveToCol < 0 )
5927 markerX = GetColRight( GetColAt( m_numCols - 1 ) );
5928 else
5929 markerX = GetColLeft( m_moveToCol );
5930 }
5931 else
5932 markerX = GetColLeft( m_moveToCol );
5933
5934 if ( markerX != m_dragLastPos )
5935 {
5936 wxClientDC dc( GetColLabelWindow() );
5937 DoPrepareDC(dc);
5938
5939 int cw, ch;
5940 GetColLabelWindow()->GetClientSize( &cw, &ch );
5941
5942 markerX++;
5943
5944 //Clean up the last indicator
5945 if ( m_dragLastPos >= 0 )
5946 {
5947 wxPen pen( GetColLabelWindow()->GetBackgroundColour(), 2 );
5948 dc.SetPen(pen);
5949 dc.DrawLine( m_dragLastPos + 1, 0, m_dragLastPos + 1, ch );
5950 dc.SetPen(wxNullPen);
5951
5952 if ( XToCol( m_dragLastPos ) != -1 )
5953 DrawColLabel( dc, XToCol( m_dragLastPos ) );
5954 }
5955
5956 const wxColour *color;
5957 //Moving to the same place? Don't draw a marker
5958 if ( (m_moveToCol == m_dragRowOrCol)
5959 || (GetColPos( m_moveToCol ) == GetColPos( m_dragRowOrCol ) + 1)
5960 || (m_moveToCol < 0 && m_dragRowOrCol == GetColAt( m_numCols - 1 )))
5961 color = wxLIGHT_GREY;
5962 else
5963 color = wxBLUE;
5964
5965 //Draw the marker
5966 wxPen pen( *color, 2 );
5967 dc.SetPen(pen);
5968
5969 dc.DrawLine( markerX, 0, markerX, ch );
5970
5971 dc.SetPen(wxNullPen);
5972
5973 m_dragLastPos = markerX - 1;
5974 }
5975 }
5976 break;
5977
5978 // default label to suppress warnings about "enumeration value
5979 // 'xxx' not handled in switch
5980 default:
5981 break;
5982 }
5983 }
5984 return;
5985 }
5986
5987 if ( m_isDragging && (event.Entering() || event.Leaving()) )
5988 return;
5989
5990 if (m_isDragging)
5991 {
5992 if (GetColLabelWindow()->HasCapture())
5993 GetColLabelWindow()->ReleaseMouse();
5994 m_isDragging = false;
5995 }
5996
5997 // ------------ Entering or leaving the window
5998 //
5999 if ( event.Entering() || event.Leaving() )
6000 {
6001 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6002 }
6003
6004 // ------------ Left button pressed
6005 //
6006 else if ( event.LeftDown() )
6007 {
6008 // don't send a label click event for a hit on the
6009 // edge of the col label - this is probably the user
6010 // wanting to resize the col
6011 //
6012 if ( XToEdgeOfCol(x) < 0 )
6013 {
6014 col = XToCol(x);
6015 if ( col >= 0 &&
6016 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, col, event ) )
6017 {
6018 if ( m_canDragColMove )
6019 {
6020 //Show button as pressed
6021 wxClientDC dc( GetColLabelWindow() );
6022 int colLeft = GetColLeft( col );
6023 int colRight = GetColRight( col ) - 1;
6024 dc.SetPen( wxPen( GetColLabelWindow()->GetBackgroundColour(), 1 ) );
6025 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight-1 );
6026 dc.DrawLine( colLeft, 1, colRight, 1 );
6027
6028 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL, GetColLabelWindow());
6029 }
6030 else
6031 {
6032 if ( !event.ShiftDown() && !event.CmdDown() )
6033 ClearSelection();
6034 if ( m_selection )
6035 {
6036 if ( event.ShiftDown() )
6037 {
6038 m_selection->SelectBlock
6039 (
6040 0, m_currentCellCoords.GetCol(),
6041 GetNumberRows() - 1, col,
6042 event
6043 );
6044 }
6045 else
6046 {
6047 m_selection->SelectCol(col, event);
6048 }
6049 }
6050
6051 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL, GetColLabelWindow());
6052 }
6053 }
6054 }
6055 else
6056 {
6057 // starting to drag-resize a col
6058 //
6059 if ( CanDragColSize() )
6060 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow());
6061 }
6062 }
6063
6064 // ------------ Left double click
6065 //
6066 if ( event.LeftDClick() )
6067 {
6068 col = XToEdgeOfCol(x);
6069 if ( col < 0 )
6070 {
6071 col = XToCol(x);
6072 if ( col >= 0 &&
6073 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, col, event ) )
6074 {
6075 // no default action at the moment
6076 }
6077 }
6078 else
6079 {
6080 // adjust column width depending on label text
6081 AutoSizeColLabelSize( col );
6082
6083 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6084 m_dragLastPos = -1;
6085 }
6086 }
6087
6088 // ------------ Left button released
6089 //
6090 else if ( event.LeftUp() )
6091 {
6092 switch ( m_cursorMode )
6093 {
6094 case WXGRID_CURSOR_RESIZE_COL:
6095 DoEndDragResizeCol();
6096 break;
6097
6098 case WXGRID_CURSOR_MOVE_COL:
6099 DoEndDragMoveCol();
6100
6101 SendEvent( wxEVT_GRID_COL_MOVE, -1, m_dragRowOrCol, event );
6102 break;
6103
6104 case WXGRID_CURSOR_SELECT_COL:
6105 case WXGRID_CURSOR_SELECT_CELL:
6106 case WXGRID_CURSOR_RESIZE_ROW:
6107 case WXGRID_CURSOR_SELECT_ROW:
6108 // nothing to do (?)
6109 break;
6110 }
6111
6112 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
6113 m_dragLastPos = -1;
6114 }
6115
6116 // ------------ Right button down
6117 //
6118 else if ( event.RightDown() )
6119 {
6120 col = XToCol(x);
6121 if ( col >= 0 &&
6122 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, col, event ) )
6123 {
6124 // no default action at the moment
6125 }
6126 }
6127
6128 // ------------ Right double click
6129 //
6130 else if ( event.RightDClick() )
6131 {
6132 col = XToCol(x);
6133 if ( col >= 0 &&
6134 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, col, event ) )
6135 {
6136 // no default action at the moment
6137 }
6138 }
6139
6140 // ------------ No buttons down and mouse moving
6141 //
6142 else if ( event.Moving() )
6143 {
6144 m_dragRowOrCol = XToEdgeOfCol( x );
6145 if ( m_dragRowOrCol >= 0 )
6146 {
6147 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6148 {
6149 // don't capture the cursor yet
6150 if ( CanDragColSize() )
6151 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow(), false);
6152 }
6153 }
6154 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
6155 {
6156 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow(), false);
6157 }
6158 }
6159 }
6160
6161 void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent& event )
6162 {
6163 if ( event.LeftDown() )
6164 {
6165 // indicate corner label by having both row and
6166 // col args == -1
6167 //
6168 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, -1, event ) )
6169 {
6170 SelectAll();
6171 }
6172 }
6173 else if ( event.LeftDClick() )
6174 {
6175 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, -1, event );
6176 }
6177 else if ( event.RightDown() )
6178 {
6179 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, -1, event ) )
6180 {
6181 // no default action at the moment
6182 }
6183 }
6184 else if ( event.RightDClick() )
6185 {
6186 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, -1, event ) )
6187 {
6188 // no default action at the moment
6189 }
6190 }
6191 }
6192
6193 void wxGrid::CancelMouseCapture()
6194 {
6195 // cancel operation currently in progress, whatever it is
6196 if ( m_winCapture )
6197 {
6198 m_isDragging = false;
6199 m_startDragPos = wxDefaultPosition;
6200
6201 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
6202 m_winCapture->SetCursor( *wxSTANDARD_CURSOR );
6203 m_winCapture = NULL;
6204
6205 // remove traces of whatever we drew on screen
6206 Refresh();
6207 }
6208 }
6209
6210 void wxGrid::ChangeCursorMode(CursorMode mode,
6211 wxWindow *win,
6212 bool captureMouse)
6213 {
6214 #ifdef __WXDEBUG__
6215 static const wxChar *cursorModes[] =
6216 {
6217 _T("SELECT_CELL"),
6218 _T("RESIZE_ROW"),
6219 _T("RESIZE_COL"),
6220 _T("SELECT_ROW"),
6221 _T("SELECT_COL"),
6222 _T("MOVE_COL"),
6223 };
6224
6225 wxLogTrace(_T("grid"),
6226 _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
6227 win == m_colWindow ? _T("colLabelWin")
6228 : win ? _T("rowLabelWin")
6229 : _T("gridWin"),
6230 cursorModes[m_cursorMode], cursorModes[mode]);
6231 #endif
6232
6233 if ( mode == m_cursorMode &&
6234 win == m_winCapture &&
6235 captureMouse == (m_winCapture != NULL))
6236 return;
6237
6238 if ( !win )
6239 {
6240 // by default use the grid itself
6241 win = m_gridWin;
6242 }
6243
6244 if ( m_winCapture )
6245 {
6246 m_winCapture->ReleaseMouse();
6247 m_winCapture = NULL;
6248 }
6249
6250 m_cursorMode = mode;
6251
6252 switch ( m_cursorMode )
6253 {
6254 case WXGRID_CURSOR_RESIZE_ROW:
6255 win->SetCursor( m_rowResizeCursor );
6256 break;
6257
6258 case WXGRID_CURSOR_RESIZE_COL:
6259 win->SetCursor( m_colResizeCursor );
6260 break;
6261
6262 case WXGRID_CURSOR_MOVE_COL:
6263 win->SetCursor( wxCursor(wxCURSOR_HAND) );
6264 break;
6265
6266 default:
6267 win->SetCursor( *wxSTANDARD_CURSOR );
6268 break;
6269 }
6270
6271 // we need to capture mouse when resizing
6272 bool resize = m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ||
6273 m_cursorMode == WXGRID_CURSOR_RESIZE_COL;
6274
6275 if ( captureMouse && resize )
6276 {
6277 win->CaptureMouse();
6278 m_winCapture = win;
6279 }
6280 }
6281
6282 // ----------------------------------------------------------------------------
6283 // grid mouse event processing
6284 // ----------------------------------------------------------------------------
6285
6286 void
6287 wxGrid::DoGridCellDrag(wxMouseEvent& event,
6288 const wxGridCellCoords& coords,
6289 bool isFirstDrag)
6290 {
6291 if ( coords == wxGridNoCellCoords )
6292 return; // we're outside any valid cell
6293
6294 // Hide the edit control, so it won't interfere with drag-shrinking.
6295 if ( IsCellEditControlShown() )
6296 {
6297 HideCellEditControl();
6298 SaveEditControlValue();
6299 }
6300
6301 switch ( event.GetModifiers() )
6302 {
6303 case wxMOD_CMD:
6304 if ( m_selectedBlockCorner == wxGridNoCellCoords)
6305 m_selectedBlockCorner = coords;
6306 UpdateBlockBeingSelected(m_selectedBlockCorner, coords);
6307 break;
6308
6309 case wxMOD_NONE:
6310 if ( CanDragCell() )
6311 {
6312 if ( isFirstDrag )
6313 {
6314 if ( m_selectedBlockCorner == wxGridNoCellCoords)
6315 m_selectedBlockCorner = coords;
6316
6317 SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG, coords, event);
6318 return;
6319 }
6320 }
6321
6322 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6323 break;
6324
6325 default:
6326 // we don't handle the other key modifiers
6327 event.Skip();
6328 }
6329 }
6330
6331 void wxGrid::DoGridLineDrag(wxMouseEvent& event, const wxGridOperations& oper)
6332 {
6333 wxClientDC dc(m_gridWin);
6334 PrepareDC(dc);
6335 dc.SetLogicalFunction(wxINVERT);
6336
6337 const wxRect rectWin(CalcUnscrolledPosition(wxPoint(0, 0)),
6338 m_gridWin->GetClientSize());
6339
6340 // erase the previously drawn line, if any
6341 if ( m_dragLastPos >= 0 )
6342 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
6343
6344 // we need the vertical position for rows and horizontal for columns here
6345 m_dragLastPos = oper.Dual().Select(CalcUnscrolledPosition(event.GetPosition()));
6346
6347 // don't allow resizing beneath the minimal size
6348 const int posMin = oper.GetLineStartPos(this, m_dragRowOrCol) +
6349 oper.GetMinimalLineSize(this, m_dragRowOrCol);
6350 if ( m_dragLastPos < posMin )
6351 m_dragLastPos = posMin;
6352
6353 // and draw it at the new position
6354 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
6355 }
6356
6357 void wxGrid::DoGridDragEvent(wxMouseEvent& event, const wxGridCellCoords& coords)
6358 {
6359 if ( !m_isDragging )
6360 {
6361 // Don't start doing anything until the mouse has been dragged far
6362 // enough
6363 const wxPoint& pt = event.GetPosition();
6364 if ( m_startDragPos == wxDefaultPosition )
6365 {
6366 m_startDragPos = pt;
6367 return;
6368 }
6369
6370 if ( abs(m_startDragPos.x - pt.x) <= DRAG_SENSITIVITY &&
6371 abs(m_startDragPos.y - pt.y) <= DRAG_SENSITIVITY )
6372 return;
6373 }
6374
6375 const bool isFirstDrag = !m_isDragging;
6376 m_isDragging = true;
6377
6378 switch ( m_cursorMode )
6379 {
6380 case WXGRID_CURSOR_SELECT_CELL:
6381 DoGridCellDrag(event, coords, isFirstDrag);
6382 break;
6383
6384 case WXGRID_CURSOR_RESIZE_ROW:
6385 DoGridLineDrag(event, wxGridRowOperations());
6386 break;
6387
6388 case WXGRID_CURSOR_RESIZE_COL:
6389 DoGridLineDrag(event, wxGridColumnOperations());
6390 break;
6391
6392 default:
6393 event.Skip();
6394 }
6395
6396 if ( isFirstDrag )
6397 {
6398 m_winCapture = m_gridWin;
6399 m_winCapture->CaptureMouse();
6400 }
6401 }
6402
6403 void
6404 wxGrid::DoGridCellLeftDown(wxMouseEvent& event,
6405 const wxGridCellCoords& coords,
6406 const wxPoint& pos)
6407 {
6408 if ( SendEvent(wxEVT_GRID_CELL_LEFT_CLICK, coords, event) )
6409 {
6410 // event handled by user code, no need to do anything here
6411 return;
6412 }
6413
6414 if ( !event.CmdDown() )
6415 ClearSelection();
6416
6417 if ( event.ShiftDown() )
6418 {
6419 if ( m_selection )
6420 {
6421 m_selection->SelectBlock(m_currentCellCoords, coords, event);
6422 m_selectedBlockCorner = coords;
6423 }
6424 }
6425 else if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
6426 {
6427 DisableCellEditControl();
6428 MakeCellVisible( coords );
6429
6430 if ( event.CmdDown() )
6431 {
6432 if ( m_selection )
6433 {
6434 m_selection->ToggleCellSelection(coords, event);
6435 }
6436
6437 m_selectedBlockTopLeft = wxGridNoCellCoords;
6438 m_selectedBlockBottomRight = wxGridNoCellCoords;
6439 m_selectedBlockCorner = coords;
6440 }
6441 else
6442 {
6443 m_waitForSlowClick = m_currentCellCoords == coords &&
6444 coords != wxGridNoCellCoords;
6445 SetCurrentCell( coords );
6446 }
6447 }
6448 }
6449
6450 void
6451 wxGrid::DoGridCellLeftDClick(wxMouseEvent& event,
6452 const wxGridCellCoords& coords,
6453 const wxPoint& pos)
6454 {
6455 if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
6456 {
6457 if ( !SendEvent(wxEVT_GRID_CELL_LEFT_DCLICK, coords, event) )
6458 {
6459 // we want double click to select a cell and start editing
6460 // (i.e. to behave in same way as sequence of two slow clicks):
6461 m_waitForSlowClick = true;
6462 }
6463 }
6464 }
6465
6466 void
6467 wxGrid::DoGridCellLeftUp(wxMouseEvent& event, const wxGridCellCoords& coords)
6468 {
6469 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6470 {
6471 if (m_winCapture)
6472 {
6473 m_winCapture->ReleaseMouse();
6474 m_winCapture = NULL;
6475 }
6476
6477 if ( coords == m_currentCellCoords && m_waitForSlowClick && CanEnableCellControl() )
6478 {
6479 ClearSelection();
6480 EnableCellEditControl();
6481
6482 wxGridCellAttr *attr = GetCellAttr(coords);
6483 wxGridCellEditor *editor = attr->GetEditor(this, coords.GetRow(), coords.GetCol());
6484 editor->StartingClick();
6485 editor->DecRef();
6486 attr->DecRef();
6487
6488 m_waitForSlowClick = false;
6489 }
6490 else if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
6491 m_selectedBlockBottomRight != wxGridNoCellCoords )
6492 {
6493 if ( m_selection )
6494 {
6495 m_selection->SelectBlock( m_selectedBlockTopLeft,
6496 m_selectedBlockBottomRight,
6497 event );
6498 }
6499
6500 m_selectedBlockTopLeft = wxGridNoCellCoords;
6501 m_selectedBlockBottomRight = wxGridNoCellCoords;
6502
6503 // Show the edit control, if it has been hidden for
6504 // drag-shrinking.
6505 ShowCellEditControl();
6506 }
6507 }
6508 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
6509 {
6510 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6511 DoEndDragResizeRow();
6512
6513 // Note: we are ending the event *after* doing
6514 // default processing in this case
6515 //
6516 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
6517 }
6518 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL )
6519 {
6520 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6521 DoEndDragResizeCol();
6522 }
6523
6524 m_dragLastPos = -1;
6525 }
6526
6527 void
6528 wxGrid::DoGridMouseMoveEvent(wxMouseEvent& WXUNUSED(event),
6529 const wxGridCellCoords& coords,
6530 const wxPoint& pos)
6531 {
6532 if ( coords.GetRow() < 0 || coords.GetCol() < 0 )
6533 {
6534 // out of grid cell area
6535 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6536 return;
6537 }
6538
6539 int dragRow = YToEdgeOfRow( pos.y );
6540 int dragCol = XToEdgeOfCol( pos.x );
6541
6542 // Dragging on the corner of a cell to resize in both
6543 // directions is not implemented yet...
6544 //
6545 if ( dragRow >= 0 && dragCol >= 0 )
6546 {
6547 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6548 return;
6549 }
6550
6551 if ( dragRow >= 0 )
6552 {
6553 m_dragRowOrCol = dragRow;
6554
6555 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6556 {
6557 if ( CanDragRowSize() && CanDragGridSize() )
6558 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, NULL, false);
6559 }
6560 }
6561 // When using the native header window we can only resize the columns by
6562 // dragging the dividers in it because we can't make it enter into the
6563 // column resizing mode programmatically
6564 else if ( dragCol >= 0 && !m_useNativeHeader )
6565 {
6566 m_dragRowOrCol = dragCol;
6567
6568 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6569 {
6570 if ( CanDragColSize() && CanDragGridSize() )
6571 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, NULL, false);
6572 }
6573 }
6574 else // Neither on a row or col edge
6575 {
6576 if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
6577 {
6578 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6579 }
6580 }
6581 }
6582
6583 void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event)
6584 {
6585 const wxPoint pos = CalcUnscrolledPosition(event.GetPosition());
6586
6587 // coordinates of the cell under mouse
6588 wxGridCellCoords coords = XYToCell(pos);
6589
6590 int cell_rows, cell_cols;
6591 GetCellSize( coords.GetRow(), coords.GetCol(), &cell_rows, &cell_cols );
6592 if ( (cell_rows < 0) || (cell_cols < 0) )
6593 {
6594 coords.SetRow(coords.GetRow() + cell_rows);
6595 coords.SetCol(coords.GetCol() + cell_cols);
6596 }
6597
6598 if ( event.Dragging() )
6599 {
6600 if ( event.LeftIsDown() )
6601 DoGridDragEvent(event, coords);
6602 else
6603 event.Skip();
6604 return;
6605 }
6606
6607 m_isDragging = false;
6608 m_startDragPos = wxDefaultPosition;
6609
6610 // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL
6611 // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under
6612 // wxGTK
6613 #if 0
6614 if ( event.Entering() || event.Leaving() )
6615 {
6616 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6617 m_gridWin->SetCursor( *wxSTANDARD_CURSOR );
6618 }
6619 #endif // 0
6620
6621 // deal with various button presses
6622 if ( event.IsButton() )
6623 {
6624 if ( coords != wxGridNoCellCoords )
6625 {
6626 DisableCellEditControl();
6627
6628 if ( event.LeftDown() )
6629 DoGridCellLeftDown(event, coords, pos);
6630 else if ( event.LeftDClick() )
6631 DoGridCellLeftDClick(event, coords, pos);
6632 else if ( event.RightDown() )
6633 SendEvent(wxEVT_GRID_CELL_RIGHT_CLICK, coords, event);
6634 else if ( event.RightDClick() )
6635 SendEvent(wxEVT_GRID_CELL_RIGHT_DCLICK, coords, event);
6636 }
6637
6638 // this one should be called even if we're not over any cell
6639 if ( event.LeftUp() )
6640 {
6641 DoGridCellLeftUp(event, coords);
6642 }
6643 }
6644 else if ( event.Moving() )
6645 {
6646 DoGridMouseMoveEvent(event, coords, pos);
6647 }
6648 else // unknown mouse event?
6649 {
6650 event.Skip();
6651 }
6652 }
6653
6654 void wxGrid::DoEndDragResizeLine(const wxGridOperations& oper)
6655 {
6656 if ( m_dragLastPos == -1 )
6657 return;
6658
6659 const wxGridOperations& doper = oper.Dual();
6660
6661 const wxSize size = m_gridWin->GetClientSize();
6662
6663 const wxPoint ptOrigin = CalcUnscrolledPosition(wxPoint(0, 0));
6664
6665 // erase the last line we drew
6666 wxClientDC dc(m_gridWin);
6667 PrepareDC(dc);
6668 dc.SetLogicalFunction(wxINVERT);
6669
6670 const int posLineStart = oper.Select(ptOrigin);
6671 const int posLineEnd = oper.Select(ptOrigin) + oper.Select(size);
6672
6673 oper.DrawParallelLine(dc, posLineStart, posLineEnd, m_dragLastPos);
6674
6675 // temporarily hide the edit control before resizing
6676 HideCellEditControl();
6677 SaveEditControlValue();
6678
6679 // do resize the line
6680 const int lineStart = oper.GetLineStartPos(this, m_dragRowOrCol);
6681 oper.SetLineSize(this, m_dragRowOrCol,
6682 wxMax(m_dragLastPos - lineStart,
6683 oper.GetMinimalLineSize(this, m_dragRowOrCol)));
6684
6685 m_dragLastPos = -1;
6686
6687 // refresh now if we're not frozen
6688 if ( !GetBatchCount() )
6689 {
6690 // we need to refresh everything beyond the resized line in the header
6691 // window
6692
6693 // get the position from which to refresh in the other direction
6694 wxRect rect(CellToRect(oper.MakeCoords(m_dragRowOrCol, 0)));
6695 rect.SetPosition(CalcScrolledPosition(rect.GetPosition()));
6696
6697 // we only need the ordinate (for rows) or abscissa (for columns) here,
6698 // and need to cover the entire window in the other direction
6699 oper.Select(rect) = 0;
6700
6701 wxRect rectHeader(rect.GetPosition(),
6702 oper.MakeSize
6703 (
6704 oper.GetHeaderWindowSize(this),
6705 doper.Select(size) - doper.Select(rect)
6706 ));
6707
6708 oper.GetHeaderWindow(this)->Refresh(true, &rectHeader);
6709
6710
6711 // also refresh the grid window: extend the rectangle
6712 if ( m_table )
6713 {
6714 oper.SelectSize(rect) = oper.Select(size);
6715
6716 int subtractLines = 0;
6717 const int lineStart = oper.PosToLine(this, posLineStart);
6718 if ( lineStart >= 0 )
6719 {
6720 // ensure that if we have a multi-cell block we redraw all of
6721 // it by increasing the refresh area to cover it entirely if a
6722 // part of it is affected
6723 const int lineEnd = oper.PosToLine(this, posLineEnd, true);
6724 for ( int line = lineStart; line < lineEnd; line++ )
6725 {
6726 int cellLines = oper.Select(
6727 GetCellSize(oper.MakeCoords(m_dragRowOrCol, line)));
6728 if ( cellLines < subtractLines )
6729 subtractLines = cellLines;
6730 }
6731 }
6732
6733 int startPos =
6734 oper.GetLineStartPos(this, m_dragRowOrCol + subtractLines);
6735 startPos = doper.CalcScrolledPosition(this, startPos);
6736
6737 doper.Select(rect) = startPos;
6738 doper.SelectSize(rect) = doper.Select(size) - startPos;
6739
6740 m_gridWin->Refresh(false, &rect);
6741 }
6742 }
6743
6744 // show the edit control back again
6745 ShowCellEditControl();
6746 }
6747
6748 void wxGrid::DoEndDragResizeRow()
6749 {
6750 DoEndDragResizeLine(wxGridRowOperations());
6751 }
6752
6753 void wxGrid::DoEndDragResizeCol(wxMouseEvent *event)
6754 {
6755 DoEndDragResizeLine(wxGridColumnOperations());
6756
6757 // Note: we are ending the event *after* doing
6758 // default processing in this case
6759 //
6760 if ( event )
6761 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, *event );
6762 else
6763 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol );
6764 }
6765
6766 void wxGrid::DoEndDragMoveCol()
6767 {
6768 //The user clicked on the column but didn't actually drag
6769 if ( m_dragLastPos < 0 )
6770 {
6771 m_colWindow->Refresh(); //Do this to "unpress" the column
6772 return;
6773 }
6774
6775 int newPos;
6776 if ( m_moveToCol == -1 )
6777 newPos = m_numCols - 1;
6778 else
6779 {
6780 newPos = GetColPos( m_moveToCol );
6781 if ( newPos > GetColPos( m_dragRowOrCol ) )
6782 newPos--;
6783 }
6784
6785 SetColPos( m_dragRowOrCol, newPos );
6786 }
6787
6788 void wxGrid::SetColPos(int idx, int pos)
6789 {
6790 // we're going to need m_colAt now, initialize it if needed
6791 if ( m_colAt.empty() )
6792 {
6793 m_colAt.reserve(m_numCols);
6794 for ( int i = 0; i < m_numCols; i++ )
6795 m_colAt.push_back(i);
6796 }
6797
6798 wxHeaderCtrl::MoveColumnInOrderArray(m_colAt, idx, pos);
6799
6800 // also recalculate the column rights
6801 if ( !m_colWidths.IsEmpty() )
6802 {
6803 int colRight = 0;
6804 int colPos;
6805 for ( colPos = 0; colPos < m_numCols; colPos++ )
6806 {
6807 int colID = GetColAt( colPos );
6808
6809 colRight += m_colWidths[colID];
6810 m_colRights[colID] = colRight;
6811 }
6812 }
6813
6814 // and make the changes visible
6815 if ( m_useNativeHeader )
6816 GetColHeader()->SetColumnsOrder(m_colAt);
6817 else
6818 m_colWindow->Refresh();
6819 m_gridWin->Refresh();
6820 }
6821
6822
6823
6824 void wxGrid::EnableDragColMove( bool enable )
6825 {
6826 if ( m_canDragColMove == enable )
6827 return;
6828
6829 m_canDragColMove = enable;
6830
6831 if ( !m_canDragColMove )
6832 {
6833 m_colAt.Clear();
6834
6835 //Recalculate the column rights
6836 if ( !m_colWidths.IsEmpty() )
6837 {
6838 int colRight = 0;
6839 int colPos;
6840 for ( colPos = 0; colPos < m_numCols; colPos++ )
6841 {
6842 colRight += m_colWidths[colPos];
6843 m_colRights[colPos] = colRight;
6844 }
6845 }
6846
6847 m_colWindow->Refresh();
6848 m_gridWin->Refresh();
6849 }
6850 }
6851
6852
6853 //
6854 // ------ interaction with data model
6855 //
6856 bool wxGrid::ProcessTableMessage( wxGridTableMessage& msg )
6857 {
6858 switch ( msg.GetId() )
6859 {
6860 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES:
6861 return GetModelValues();
6862
6863 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES:
6864 return SetModelValues();
6865
6866 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
6867 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
6868 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
6869 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
6870 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
6871 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
6872 return Redimension( msg );
6873
6874 default:
6875 return false;
6876 }
6877 }
6878
6879 // The behaviour of this function depends on the grid table class
6880 // Clear() function. For the default wxGridStringTable class the
6881 // behaviour is to replace all cell contents with wxEmptyString but
6882 // not to change the number of rows or cols.
6883 //
6884 void wxGrid::ClearGrid()
6885 {
6886 if ( m_table )
6887 {
6888 if (IsCellEditControlEnabled())
6889 DisableCellEditControl();
6890
6891 m_table->Clear();
6892 if (!GetBatchCount())
6893 m_gridWin->Refresh();
6894 }
6895 }
6896
6897 bool
6898 wxGrid::DoModifyLines(bool (wxGridTableBase::*funcModify)(size_t, size_t),
6899 int pos, int num, bool WXUNUSED(updateLabels) )
6900 {
6901 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
6902
6903 if ( !m_table )
6904 return false;
6905
6906 if ( IsCellEditControlEnabled() )
6907 DisableCellEditControl();
6908
6909 return (m_table->*funcModify)(pos, num);
6910
6911 // the table will have sent the results of the insert row
6912 // operation to this view object as a grid table message
6913 }
6914
6915 bool
6916 wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend)(size_t),
6917 int num, bool WXUNUSED(updateLabels))
6918 {
6919 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
6920
6921 if ( !m_table )
6922 return false;
6923
6924 return (m_table->*funcAppend)(num);
6925 }
6926
6927 //
6928 // ----- event handlers
6929 //
6930
6931 // Generate a grid event based on a mouse event and return:
6932 // -1 if the event was vetoed
6933 // +1 if the event was processed (but not vetoed)
6934 // 0 if the event wasn't handled
6935 int
6936 wxGrid::SendEvent(const wxEventType type,
6937 int row, int col,
6938 wxMouseEvent& mouseEv)
6939 {
6940 bool claimed, vetoed;
6941
6942 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
6943 {
6944 int rowOrCol = (row == -1 ? col : row);
6945
6946 wxGridSizeEvent gridEvt( GetId(),
6947 type,
6948 this,
6949 rowOrCol,
6950 mouseEv.GetX() + GetRowLabelSize(),
6951 mouseEv.GetY() + GetColLabelSize(),
6952 mouseEv);
6953
6954 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6955 vetoed = !gridEvt.IsAllowed();
6956 }
6957 else if ( type == wxEVT_GRID_RANGE_SELECT )
6958 {
6959 // Right now, it should _never_ end up here!
6960 wxGridRangeSelectEvent gridEvt( GetId(),
6961 type,
6962 this,
6963 m_selectedBlockTopLeft,
6964 m_selectedBlockBottomRight,
6965 true,
6966 mouseEv);
6967
6968 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6969 vetoed = !gridEvt.IsAllowed();
6970 }
6971 else if ( type == wxEVT_GRID_LABEL_LEFT_CLICK ||
6972 type == wxEVT_GRID_LABEL_LEFT_DCLICK ||
6973 type == wxEVT_GRID_LABEL_RIGHT_CLICK ||
6974 type == wxEVT_GRID_LABEL_RIGHT_DCLICK )
6975 {
6976 wxPoint pos = mouseEv.GetPosition();
6977
6978 if ( mouseEv.GetEventObject() == GetGridRowLabelWindow() )
6979 pos.y += GetColLabelSize();
6980 if ( mouseEv.GetEventObject() == GetGridColLabelWindow() )
6981 pos.x += GetRowLabelSize();
6982
6983 wxGridEvent gridEvt( GetId(),
6984 type,
6985 this,
6986 row, col,
6987 pos.x,
6988 pos.y,
6989 false,
6990 mouseEv);
6991 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6992 vetoed = !gridEvt.IsAllowed();
6993 }
6994 else
6995 {
6996 wxGridEvent gridEvt( GetId(),
6997 type,
6998 this,
6999 row, col,
7000 mouseEv.GetX() + GetRowLabelSize(),
7001 mouseEv.GetY() + GetColLabelSize(),
7002 false,
7003 mouseEv);
7004 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7005 vetoed = !gridEvt.IsAllowed();
7006 }
7007
7008 // A Veto'd event may not be `claimed' so test this first
7009 if (vetoed)
7010 return -1;
7011
7012 return claimed ? 1 : 0;
7013 }
7014
7015 // Generate a grid event of specified type, return value same as above
7016 //
7017 int wxGrid::SendEvent(const wxEventType type, int row, int col)
7018 {
7019 bool claimed, vetoed;
7020
7021 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
7022 {
7023 int rowOrCol = (row == -1 ? col : row);
7024
7025 wxGridSizeEvent gridEvt( GetId(), type, this, rowOrCol );
7026
7027 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7028 vetoed = !gridEvt.IsAllowed();
7029 }
7030 else
7031 {
7032 wxGridEvent gridEvt( GetId(), type, this, row, col );
7033
7034 claimed = GetEventHandler()->ProcessEvent(gridEvt);
7035 vetoed = !gridEvt.IsAllowed();
7036 }
7037
7038 // A Veto'd event may not be `claimed' so test this first
7039 if (vetoed)
7040 return -1;
7041
7042 return claimed ? 1 : 0;
7043 }
7044
7045 void wxGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
7046 {
7047 // needed to prevent zillions of paint events on MSW
7048 wxPaintDC dc(this);
7049 }
7050
7051 void wxGrid::Refresh(bool eraseb, const wxRect* rect)
7052 {
7053 // Don't do anything if between Begin/EndBatch...
7054 // EndBatch() will do all this on the last nested one anyway.
7055 if ( m_created && !GetBatchCount() )
7056 {
7057 // Refresh to get correct scrolled position:
7058 wxScrolledWindow::Refresh(eraseb, rect);
7059
7060 if (rect)
7061 {
7062 int rect_x, rect_y, rectWidth, rectHeight;
7063 int width_label, width_cell, height_label, height_cell;
7064 int x, y;
7065
7066 // Copy rectangle can get scroll offsets..
7067 rect_x = rect->GetX();
7068 rect_y = rect->GetY();
7069 rectWidth = rect->GetWidth();
7070 rectHeight = rect->GetHeight();
7071
7072 width_label = m_rowLabelWidth - rect_x;
7073 if (width_label > rectWidth)
7074 width_label = rectWidth;
7075
7076 height_label = m_colLabelHeight - rect_y;
7077 if (height_label > rectHeight)
7078 height_label = rectHeight;
7079
7080 if (rect_x > m_rowLabelWidth)
7081 {
7082 x = rect_x - m_rowLabelWidth;
7083 width_cell = rectWidth;
7084 }
7085 else
7086 {
7087 x = 0;
7088 width_cell = rectWidth - (m_rowLabelWidth - rect_x);
7089 }
7090
7091 if (rect_y > m_colLabelHeight)
7092 {
7093 y = rect_y - m_colLabelHeight;
7094 height_cell = rectHeight;
7095 }
7096 else
7097 {
7098 y = 0;
7099 height_cell = rectHeight - (m_colLabelHeight - rect_y);
7100 }
7101
7102 // Paint corner label part intersecting rect.
7103 if ( width_label > 0 && height_label > 0 )
7104 {
7105 wxRect anotherrect(rect_x, rect_y, width_label, height_label);
7106 m_cornerLabelWin->Refresh(eraseb, &anotherrect);
7107 }
7108
7109 // Paint col labels part intersecting rect.
7110 if ( width_cell > 0 && height_label > 0 )
7111 {
7112 wxRect anotherrect(x, rect_y, width_cell, height_label);
7113 m_colWindow->Refresh(eraseb, &anotherrect);
7114 }
7115
7116 // Paint row labels part intersecting rect.
7117 if ( width_label > 0 && height_cell > 0 )
7118 {
7119 wxRect anotherrect(rect_x, y, width_label, height_cell);
7120 m_rowLabelWin->Refresh(eraseb, &anotherrect);
7121 }
7122
7123 // Paint cell area part intersecting rect.
7124 if ( width_cell > 0 && height_cell > 0 )
7125 {
7126 wxRect anotherrect(x, y, width_cell, height_cell);
7127 m_gridWin->Refresh(eraseb, &anotherrect);
7128 }
7129 }
7130 else
7131 {
7132 m_cornerLabelWin->Refresh(eraseb, NULL);
7133 m_colWindow->Refresh(eraseb, NULL);
7134 m_rowLabelWin->Refresh(eraseb, NULL);
7135 m_gridWin->Refresh(eraseb, NULL);
7136 }
7137 }
7138 }
7139
7140 void wxGrid::OnSize(wxSizeEvent& WXUNUSED(event))
7141 {
7142 if (m_targetWindow != this) // check whether initialisation has been done
7143 {
7144 // reposition our children windows
7145 CalcWindowSizes();
7146 }
7147 }
7148
7149 void wxGrid::OnKeyDown( wxKeyEvent& event )
7150 {
7151 if ( m_inOnKeyDown )
7152 {
7153 // shouldn't be here - we are going round in circles...
7154 //
7155 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
7156 }
7157
7158 m_inOnKeyDown = true;
7159
7160 // propagate the event up and see if it gets processed
7161 wxWindow *parent = GetParent();
7162 wxKeyEvent keyEvt( event );
7163 keyEvt.SetEventObject( parent );
7164
7165 if ( !parent->GetEventHandler()->ProcessEvent( keyEvt ) )
7166 {
7167 if (GetLayoutDirection() == wxLayout_RightToLeft)
7168 {
7169 if (event.GetKeyCode() == WXK_RIGHT)
7170 event.m_keyCode = WXK_LEFT;
7171 else if (event.GetKeyCode() == WXK_LEFT)
7172 event.m_keyCode = WXK_RIGHT;
7173 }
7174
7175 // try local handlers
7176 switch ( event.GetKeyCode() )
7177 {
7178 case WXK_UP:
7179 if ( event.ControlDown() )
7180 MoveCursorUpBlock( event.ShiftDown() );
7181 else
7182 MoveCursorUp( event.ShiftDown() );
7183 break;
7184
7185 case WXK_DOWN:
7186 if ( event.ControlDown() )
7187 MoveCursorDownBlock( event.ShiftDown() );
7188 else
7189 MoveCursorDown( event.ShiftDown() );
7190 break;
7191
7192 case WXK_LEFT:
7193 if ( event.ControlDown() )
7194 MoveCursorLeftBlock( event.ShiftDown() );
7195 else
7196 MoveCursorLeft( event.ShiftDown() );
7197 break;
7198
7199 case WXK_RIGHT:
7200 if ( event.ControlDown() )
7201 MoveCursorRightBlock( event.ShiftDown() );
7202 else
7203 MoveCursorRight( event.ShiftDown() );
7204 break;
7205
7206 case WXK_RETURN:
7207 case WXK_NUMPAD_ENTER:
7208 if ( event.ControlDown() )
7209 {
7210 event.Skip(); // to let the edit control have the return
7211 }
7212 else
7213 {
7214 if ( GetGridCursorRow() < GetNumberRows()-1 )
7215 {
7216 MoveCursorDown( event.ShiftDown() );
7217 }
7218 else
7219 {
7220 // at the bottom of a column
7221 DisableCellEditControl();
7222 }
7223 }
7224 break;
7225
7226 case WXK_ESCAPE:
7227 ClearSelection();
7228 break;
7229
7230 case WXK_TAB:
7231 if (event.ShiftDown())
7232 {
7233 if ( GetGridCursorCol() > 0 )
7234 {
7235 MoveCursorLeft( false );
7236 }
7237 else
7238 {
7239 // at left of grid
7240 DisableCellEditControl();
7241 }
7242 }
7243 else
7244 {
7245 if ( GetGridCursorCol() < GetNumberCols() - 1 )
7246 {
7247 MoveCursorRight( false );
7248 }
7249 else
7250 {
7251 // at right of grid
7252 DisableCellEditControl();
7253 }
7254 }
7255 break;
7256
7257 case WXK_HOME:
7258 if ( event.ControlDown() )
7259 {
7260 GoToCell(0, 0);
7261 }
7262 else
7263 {
7264 event.Skip();
7265 }
7266 break;
7267
7268 case WXK_END:
7269 if ( event.ControlDown() )
7270 {
7271 GoToCell(m_numRows - 1, m_numCols - 1);
7272 }
7273 else
7274 {
7275 event.Skip();
7276 }
7277 break;
7278
7279 case WXK_PAGEUP:
7280 MovePageUp();
7281 break;
7282
7283 case WXK_PAGEDOWN:
7284 MovePageDown();
7285 break;
7286
7287 case WXK_SPACE:
7288 // Ctrl-Space selects the current column, Shift-Space -- the
7289 // current row and Ctrl-Shift-Space -- everything
7290 switch ( m_selection ? event.GetModifiers() : wxMOD_NONE )
7291 {
7292 case wxMOD_CONTROL:
7293 m_selection->SelectCol(m_currentCellCoords.GetCol());
7294 break;
7295
7296 case wxMOD_SHIFT:
7297 m_selection->SelectRow(m_currentCellCoords.GetRow());
7298 break;
7299
7300 case wxMOD_CONTROL | wxMOD_SHIFT:
7301 m_selection->SelectBlock(0, 0,
7302 m_numRows - 1, m_numCols - 1);
7303 break;
7304
7305 case wxMOD_NONE:
7306 if ( !IsEditable() )
7307 {
7308 MoveCursorRight(false);
7309 break;
7310 }
7311 //else: fall through
7312
7313 default:
7314 event.Skip();
7315 }
7316 break;
7317
7318 default:
7319 event.Skip();
7320 break;
7321 }
7322 }
7323
7324 m_inOnKeyDown = false;
7325 }
7326
7327 void wxGrid::OnKeyUp( wxKeyEvent& event )
7328 {
7329 // try local handlers
7330 //
7331 if ( event.GetKeyCode() == WXK_SHIFT )
7332 {
7333 if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
7334 m_selectedBlockBottomRight != wxGridNoCellCoords )
7335 {
7336 if ( m_selection )
7337 {
7338 m_selection->SelectBlock(
7339 m_selectedBlockTopLeft,
7340 m_selectedBlockBottomRight,
7341 event);
7342 }
7343 }
7344
7345 m_selectedBlockTopLeft = wxGridNoCellCoords;
7346 m_selectedBlockBottomRight = wxGridNoCellCoords;
7347 m_selectedBlockCorner = wxGridNoCellCoords;
7348 }
7349 }
7350
7351 void wxGrid::OnChar( wxKeyEvent& event )
7352 {
7353 // is it possible to edit the current cell at all?
7354 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
7355 {
7356 // yes, now check whether the cells editor accepts the key
7357 int row = m_currentCellCoords.GetRow();
7358 int col = m_currentCellCoords.GetCol();
7359 wxGridCellAttr *attr = GetCellAttr(row, col);
7360 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7361
7362 // <F2> is special and will always start editing, for
7363 // other keys - ask the editor itself
7364 if ( (event.GetKeyCode() == WXK_F2 && !event.HasModifiers())
7365 || editor->IsAcceptedKey(event) )
7366 {
7367 // ensure cell is visble
7368 MakeCellVisible(row, col);
7369 EnableCellEditControl();
7370
7371 // a problem can arise if the cell is not completely
7372 // visible (even after calling MakeCellVisible the
7373 // control is not created and calling StartingKey will
7374 // crash the app
7375 if ( event.GetKeyCode() != WXK_F2 && editor->IsCreated() && m_cellEditCtrlEnabled )
7376 editor->StartingKey(event);
7377 }
7378 else
7379 {
7380 event.Skip();
7381 }
7382
7383 editor->DecRef();
7384 attr->DecRef();
7385 }
7386 else
7387 {
7388 event.Skip();
7389 }
7390 }
7391
7392 void wxGrid::OnEraseBackground(wxEraseEvent&)
7393 {
7394 }
7395
7396 bool wxGrid::SetCurrentCell( const wxGridCellCoords& coords )
7397 {
7398 if ( SendEvent(wxEVT_GRID_SELECT_CELL, coords) == -1 )
7399 {
7400 // the event has been vetoed - do nothing
7401 return false;
7402 }
7403
7404 #if !defined(__WXMAC__)
7405 wxClientDC dc( m_gridWin );
7406 PrepareDC( dc );
7407 #endif
7408
7409 if ( m_currentCellCoords != wxGridNoCellCoords )
7410 {
7411 DisableCellEditControl();
7412
7413 if ( IsVisible( m_currentCellCoords, false ) )
7414 {
7415 wxRect r;
7416 r = BlockToDeviceRect( m_currentCellCoords, m_currentCellCoords );
7417 if ( !m_gridLinesEnabled )
7418 {
7419 r.x--;
7420 r.y--;
7421 r.width++;
7422 r.height++;
7423 }
7424
7425 wxGridCellCoordsArray cells = CalcCellsExposed( r );
7426
7427 // Otherwise refresh redraws the highlight!
7428 m_currentCellCoords = coords;
7429
7430 #if defined(__WXMAC__)
7431 m_gridWin->Refresh(true /*, & r */);
7432 #else
7433 DrawGridCellArea( dc, cells );
7434 DrawAllGridLines( dc, r );
7435 #endif
7436 }
7437 }
7438
7439 m_currentCellCoords = coords;
7440
7441 wxGridCellAttr *attr = GetCellAttr( coords );
7442 #if !defined(__WXMAC__)
7443 DrawCellHighlight( dc, attr );
7444 #endif
7445 attr->DecRef();
7446
7447 return true;
7448 }
7449
7450 void
7451 wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol,
7452 int bottomRow, int rightCol)
7453 {
7454 if ( m_selection )
7455 {
7456 switch ( m_selection->GetSelectionMode() )
7457 {
7458 default:
7459 wxFAIL_MSG( "unknown selection mode" );
7460 // fall through
7461
7462 case wxGridSelectCells:
7463 // arbitrary blocks selection allowed so just use the cell
7464 // coordinates as is
7465 break;
7466
7467 case wxGridSelectRows:
7468 // only full rows selection allowd, ensure that we do select
7469 // full rows
7470 leftCol = 0;
7471 rightCol = GetNumberCols() - 1;
7472 break;
7473
7474 case wxGridSelectColumns:
7475 // same as above but for columns
7476 topRow = 0;
7477 bottomRow = GetNumberRows() - 1;
7478 break;
7479
7480 case wxGridSelectRowsOrColumns:
7481 // in this mode we can select only full rows or full columns so
7482 // it doesn't make sense to select blocks at all (and we can't
7483 // extend the block because there is no preferred direction, we
7484 // could only extend it to cover the entire grid but this is
7485 // not useful)
7486 return;
7487 }
7488 }
7489
7490 m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol);
7491 MakeCellVisible(m_selectedBlockCorner);
7492
7493 EnsureFirstLessThanSecond(topRow, bottomRow);
7494 EnsureFirstLessThanSecond(leftCol, rightCol);
7495
7496 wxGridCellCoords updateTopLeft = wxGridCellCoords(topRow, leftCol),
7497 updateBottomRight = wxGridCellCoords(bottomRow, rightCol);
7498
7499 // First the case that we selected a completely new area
7500 if ( m_selectedBlockTopLeft == wxGridNoCellCoords ||
7501 m_selectedBlockBottomRight == wxGridNoCellCoords )
7502 {
7503 wxRect rect;
7504 rect = BlockToDeviceRect( wxGridCellCoords ( topRow, leftCol ),
7505 wxGridCellCoords ( bottomRow, rightCol ) );
7506 m_gridWin->Refresh( false, &rect );
7507 }
7508
7509 // Now handle changing an existing selection area.
7510 else if ( m_selectedBlockTopLeft != updateTopLeft ||
7511 m_selectedBlockBottomRight != updateBottomRight )
7512 {
7513 // Compute two optimal update rectangles:
7514 // Either one rectangle is a real subset of the
7515 // other, or they are (almost) disjoint!
7516 wxRect rect[4];
7517 bool need_refresh[4];
7518 need_refresh[0] =
7519 need_refresh[1] =
7520 need_refresh[2] =
7521 need_refresh[3] = false;
7522 int i;
7523
7524 // Store intermediate values
7525 wxCoord oldLeft = m_selectedBlockTopLeft.GetCol();
7526 wxCoord oldTop = m_selectedBlockTopLeft.GetRow();
7527 wxCoord oldRight = m_selectedBlockBottomRight.GetCol();
7528 wxCoord oldBottom = m_selectedBlockBottomRight.GetRow();
7529
7530 // Determine the outer/inner coordinates.
7531 EnsureFirstLessThanSecond(oldLeft, leftCol);
7532 EnsureFirstLessThanSecond(oldTop, topRow);
7533 EnsureFirstLessThanSecond(rightCol, oldRight);
7534 EnsureFirstLessThanSecond(bottomRow, oldBottom);
7535
7536 // Now, either the stuff marked old is the outer
7537 // rectangle or we don't have a situation where one
7538 // is contained in the other.
7539
7540 if ( oldLeft < leftCol )
7541 {
7542 // Refresh the newly selected or deselected
7543 // area to the left of the old or new selection.
7544 need_refresh[0] = true;
7545 rect[0] = BlockToDeviceRect(
7546 wxGridCellCoords( oldTop, oldLeft ),
7547 wxGridCellCoords( oldBottom, leftCol - 1 ) );
7548 }
7549
7550 if ( oldTop < topRow )
7551 {
7552 // Refresh the newly selected or deselected
7553 // area above the old or new selection.
7554 need_refresh[1] = true;
7555 rect[1] = BlockToDeviceRect(
7556 wxGridCellCoords( oldTop, leftCol ),
7557 wxGridCellCoords( topRow - 1, rightCol ) );
7558 }
7559
7560 if ( oldRight > rightCol )
7561 {
7562 // Refresh the newly selected or deselected
7563 // area to the right of the old or new selection.
7564 need_refresh[2] = true;
7565 rect[2] = BlockToDeviceRect(
7566 wxGridCellCoords( oldTop, rightCol + 1 ),
7567 wxGridCellCoords( oldBottom, oldRight ) );
7568 }
7569
7570 if ( oldBottom > bottomRow )
7571 {
7572 // Refresh the newly selected or deselected
7573 // area below the old or new selection.
7574 need_refresh[3] = true;
7575 rect[3] = BlockToDeviceRect(
7576 wxGridCellCoords( bottomRow + 1, leftCol ),
7577 wxGridCellCoords( oldBottom, rightCol ) );
7578 }
7579
7580 // various Refresh() calls
7581 for (i = 0; i < 4; i++ )
7582 if ( need_refresh[i] && rect[i] != wxGridNoCellRect )
7583 m_gridWin->Refresh( false, &(rect[i]) );
7584 }
7585
7586 // change selection
7587 m_selectedBlockTopLeft = updateTopLeft;
7588 m_selectedBlockBottomRight = updateBottomRight;
7589 }
7590
7591 //
7592 // ------ functions to get/send data (see also public functions)
7593 //
7594
7595 bool wxGrid::GetModelValues()
7596 {
7597 // Hide the editor, so it won't hide a changed value.
7598 HideCellEditControl();
7599
7600 if ( m_table )
7601 {
7602 // all we need to do is repaint the grid
7603 //
7604 m_gridWin->Refresh();
7605 return true;
7606 }
7607
7608 return false;
7609 }
7610
7611 bool wxGrid::SetModelValues()
7612 {
7613 int row, col;
7614
7615 // Disable the editor, so it won't hide a changed value.
7616 // Do we also want to save the current value of the editor first?
7617 // I think so ...
7618 DisableCellEditControl();
7619
7620 if ( m_table )
7621 {
7622 for ( row = 0; row < m_numRows; row++ )
7623 {
7624 for ( col = 0; col < m_numCols; col++ )
7625 {
7626 m_table->SetValue( row, col, GetCellValue(row, col) );
7627 }
7628 }
7629
7630 return true;
7631 }
7632
7633 return false;
7634 }
7635
7636 // Note - this function only draws cells that are in the list of
7637 // exposed cells (usually set from the update region by
7638 // CalcExposedCells)
7639 //
7640 void wxGrid::DrawGridCellArea( wxDC& dc, const wxGridCellCoordsArray& cells )
7641 {
7642 if ( !m_numRows || !m_numCols )
7643 return;
7644
7645 int i, numCells = cells.GetCount();
7646 int row, col, cell_rows, cell_cols;
7647 wxGridCellCoordsArray redrawCells;
7648
7649 for ( i = numCells - 1; i >= 0; i-- )
7650 {
7651 row = cells[i].GetRow();
7652 col = cells[i].GetCol();
7653 GetCellSize( row, col, &cell_rows, &cell_cols );
7654
7655 // If this cell is part of a multicell block, find owner for repaint
7656 if ( cell_rows <= 0 || cell_cols <= 0 )
7657 {
7658 wxGridCellCoords cell( row + cell_rows, col + cell_cols );
7659 bool marked = false;
7660 for ( int j = 0; j < numCells; j++ )
7661 {
7662 if ( cell == cells[j] )
7663 {
7664 marked = true;
7665 break;
7666 }
7667 }
7668
7669 if (!marked)
7670 {
7671 int count = redrawCells.GetCount();
7672 for (int j = 0; j < count; j++)
7673 {
7674 if ( cell == redrawCells[j] )
7675 {
7676 marked = true;
7677 break;
7678 }
7679 }
7680
7681 if (!marked)
7682 redrawCells.Add( cell );
7683 }
7684
7685 // don't bother drawing this cell
7686 continue;
7687 }
7688
7689 // If this cell is empty, find cell to left that might want to overflow
7690 if (m_table && m_table->IsEmptyCell(row, col))
7691 {
7692 for ( int l = 0; l < cell_rows; l++ )
7693 {
7694 // find a cell in this row to leave already marked for repaint
7695 int left = col;
7696 for (int k = 0; k < int(redrawCells.GetCount()); k++)
7697 if ((redrawCells[k].GetCol() < left) &&
7698 (redrawCells[k].GetRow() == row))
7699 {
7700 left = redrawCells[k].GetCol();
7701 }
7702
7703 if (left == col)
7704 left = 0; // oh well
7705
7706 for (int j = col - 1; j >= left; j--)
7707 {
7708 if (!m_table->IsEmptyCell(row + l, j))
7709 {
7710 if (GetCellOverflow(row + l, j))
7711 {
7712 wxGridCellCoords cell(row + l, j);
7713 bool marked = false;
7714
7715 for (int k = 0; k < numCells; k++)
7716 {
7717 if ( cell == cells[k] )
7718 {
7719 marked = true;
7720 break;
7721 }
7722 }
7723
7724 if (!marked)
7725 {
7726 int count = redrawCells.GetCount();
7727 for (int k = 0; k < count; k++)
7728 {
7729 if ( cell == redrawCells[k] )
7730 {
7731 marked = true;
7732 break;
7733 }
7734 }
7735 if (!marked)
7736 redrawCells.Add( cell );
7737 }
7738 }
7739 break;
7740 }
7741 }
7742 }
7743 }
7744
7745 DrawCell( dc, cells[i] );
7746 }
7747
7748 numCells = redrawCells.GetCount();
7749
7750 for ( i = numCells - 1; i >= 0; i-- )
7751 {
7752 DrawCell( dc, redrawCells[i] );
7753 }
7754 }
7755
7756 void wxGrid::DrawGridSpace( wxDC& dc )
7757 {
7758 int cw, ch;
7759 m_gridWin->GetClientSize( &cw, &ch );
7760
7761 int right, bottom;
7762 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7763
7764 int rightCol = m_numCols > 0 ? GetColRight(GetColAt( m_numCols - 1 )) : 0;
7765 int bottomRow = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
7766
7767 if ( right > rightCol || bottom > bottomRow )
7768 {
7769 int left, top;
7770 CalcUnscrolledPosition( 0, 0, &left, &top );
7771
7772 dc.SetBrush(GetDefaultCellBackgroundColour());
7773 dc.SetPen( *wxTRANSPARENT_PEN );
7774
7775 if ( right > rightCol )
7776 {
7777 dc.DrawRectangle( rightCol, top, right - rightCol, ch );
7778 }
7779
7780 if ( bottom > bottomRow )
7781 {
7782 dc.DrawRectangle( left, bottomRow, cw, bottom - bottomRow );
7783 }
7784 }
7785 }
7786
7787 void wxGrid::DrawCell( wxDC& dc, const wxGridCellCoords& coords )
7788 {
7789 int row = coords.GetRow();
7790 int col = coords.GetCol();
7791
7792 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7793 return;
7794
7795 // we draw the cell border ourselves
7796 wxGridCellAttr* attr = GetCellAttr(row, col);
7797
7798 bool isCurrent = coords == m_currentCellCoords;
7799
7800 wxRect rect = CellToRect( row, col );
7801
7802 // if the editor is shown, we should use it and not the renderer
7803 // Note: However, only if it is really _shown_, i.e. not hidden!
7804 if ( isCurrent && IsCellEditControlShown() )
7805 {
7806 // NB: this "#if..." is temporary and fixes a problem where the
7807 // edit control is erased by this code after being rendered.
7808 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
7809 // implicitly, causing this out-of order render.
7810 #if !defined(__WXMAC__)
7811 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7812 editor->PaintBackground(rect, attr);
7813 editor->DecRef();
7814 #endif
7815 }
7816 else
7817 {
7818 // but all the rest is drawn by the cell renderer and hence may be customized
7819 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
7820 renderer->Draw(*this, *attr, dc, rect, row, col, IsInSelection(coords));
7821 renderer->DecRef();
7822 }
7823
7824 attr->DecRef();
7825 }
7826
7827 void wxGrid::DrawCellHighlight( wxDC& dc, const wxGridCellAttr *attr )
7828 {
7829 // don't show highlight when the grid doesn't have focus
7830 if ( !HasFocus() )
7831 return;
7832
7833 int row = m_currentCellCoords.GetRow();
7834 int col = m_currentCellCoords.GetCol();
7835
7836 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7837 return;
7838
7839 wxRect rect = CellToRect(row, col);
7840
7841 // hmmm... what could we do here to show that the cell is disabled?
7842 // for now, I just draw a thinner border than for the other ones, but
7843 // it doesn't look really good
7844
7845 int penWidth = attr->IsReadOnly() ? m_cellHighlightROPenWidth : m_cellHighlightPenWidth;
7846
7847 if (penWidth > 0)
7848 {
7849 // The center of the drawn line is where the position/width/height of
7850 // the rectangle is actually at (on wxMSW at least), so the
7851 // size of the rectangle is reduced to compensate for the thickness of
7852 // the line. If this is too strange on non-wxMSW platforms then
7853 // please #ifdef this appropriately.
7854 rect.x += penWidth / 2;
7855 rect.y += penWidth / 2;
7856 rect.width -= penWidth - 1;
7857 rect.height -= penWidth - 1;
7858
7859 // Now draw the rectangle
7860 // use the cellHighlightColour if the cell is inside a selection, this
7861 // will ensure the cell is always visible.
7862 dc.SetPen(wxPen(IsInSelection(row,col) ? m_selectionForeground
7863 : m_cellHighlightColour,
7864 penWidth));
7865 dc.SetBrush(*wxTRANSPARENT_BRUSH);
7866 dc.DrawRectangle(rect);
7867 }
7868 }
7869
7870 wxPen wxGrid::GetDefaultGridLinePen()
7871 {
7872 return wxPen(GetGridLineColour());
7873 }
7874
7875 wxPen wxGrid::GetRowGridLinePen(int WXUNUSED(row))
7876 {
7877 return GetDefaultGridLinePen();
7878 }
7879
7880 wxPen wxGrid::GetColGridLinePen(int WXUNUSED(col))
7881 {
7882 return GetDefaultGridLinePen();
7883 }
7884
7885 void wxGrid::DrawCellBorder( wxDC& dc, const wxGridCellCoords& coords )
7886 {
7887 int row = coords.GetRow();
7888 int col = coords.GetCol();
7889 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7890 return;
7891
7892
7893 wxRect rect = CellToRect( row, col );
7894
7895 // right hand border
7896 dc.SetPen( GetColGridLinePen(col) );
7897 dc.DrawLine( rect.x + rect.width, rect.y,
7898 rect.x + rect.width, rect.y + rect.height + 1 );
7899
7900 // bottom border
7901 dc.SetPen( GetRowGridLinePen(row) );
7902 dc.DrawLine( rect.x, rect.y + rect.height,
7903 rect.x + rect.width, rect.y + rect.height);
7904 }
7905
7906 void wxGrid::DrawHighlight(wxDC& dc, const wxGridCellCoordsArray& cells)
7907 {
7908 // This if block was previously in wxGrid::OnPaint but that doesn't
7909 // seem to get called under wxGTK - MB
7910 //
7911 if ( m_currentCellCoords == wxGridNoCellCoords &&
7912 m_numRows && m_numCols )
7913 {
7914 m_currentCellCoords.Set(0, 0);
7915 }
7916
7917 if ( IsCellEditControlShown() )
7918 {
7919 // don't show highlight when the edit control is shown
7920 return;
7921 }
7922
7923 // if the active cell was repainted, repaint its highlight too because it
7924 // might have been damaged by the grid lines
7925 size_t count = cells.GetCount();
7926 for ( size_t n = 0; n < count; n++ )
7927 {
7928 wxGridCellCoords cell = cells[n];
7929
7930 // If we are using attributes, then we may have just exposed another
7931 // cell in a partially-visible merged cluster of cells. If the "anchor"
7932 // (upper left) cell of this merged cluster is the cell indicated by
7933 // m_currentCellCoords, then we need to refresh the cell highlight even
7934 // though the "anchor" itself is not part of our update segment.
7935 if ( CanHaveAttributes() )
7936 {
7937 int rows = 0,
7938 cols = 0;
7939 GetCellSize(cell.GetRow(), cell.GetCol(), &rows, &cols);
7940
7941 if ( rows < 0 )
7942 cell.SetRow(cell.GetRow() + rows);
7943
7944 if ( cols < 0 )
7945 cell.SetCol(cell.GetCol() + cols);
7946 }
7947
7948 if ( cell == m_currentCellCoords )
7949 {
7950 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
7951 DrawCellHighlight(dc, attr);
7952 attr->DecRef();
7953
7954 break;
7955 }
7956 }
7957 }
7958
7959 // This is used to redraw all grid lines e.g. when the grid line colour
7960 // has been changed
7961 //
7962 void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) )
7963 {
7964 if ( !m_gridLinesEnabled )
7965 return;
7966
7967 int top, bottom, left, right;
7968
7969 int cw, ch;
7970 m_gridWin->GetClientSize(&cw, &ch);
7971 CalcUnscrolledPosition( 0, 0, &left, &top );
7972 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7973
7974 // avoid drawing grid lines past the last row and col
7975 if ( m_gridLinesClipHorz )
7976 {
7977 if ( !m_numCols )
7978 return;
7979
7980 const int lastColRight = GetColRight(GetColAt(m_numCols - 1));
7981 if ( right > lastColRight )
7982 right = lastColRight;
7983 }
7984
7985 if ( m_gridLinesClipVert )
7986 {
7987 if ( !m_numRows )
7988 return;
7989
7990 const int lastRowBottom = GetRowBottom(m_numRows - 1);
7991 if ( bottom > lastRowBottom )
7992 bottom = lastRowBottom;
7993 }
7994
7995 // no gridlines inside multicells, clip them out
7996 int leftCol = GetColPos( internalXToCol(left) );
7997 int topRow = internalYToRow(top);
7998 int rightCol = GetColPos( internalXToCol(right) );
7999 int bottomRow = internalYToRow(bottom);
8000
8001 wxRegion clippedcells(0, 0, cw, ch);
8002
8003 int cell_rows, cell_cols;
8004 wxRect rect;
8005
8006 for ( int j = topRow; j <= bottomRow; j++ )
8007 {
8008 for ( int colPos = leftCol; colPos <= rightCol; colPos++ )
8009 {
8010 int i = GetColAt( colPos );
8011
8012 GetCellSize( j, i, &cell_rows, &cell_cols );
8013 if ((cell_rows > 1) || (cell_cols > 1))
8014 {
8015 rect = CellToRect(j,i);
8016 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8017 clippedcells.Subtract(rect);
8018 }
8019 else if ((cell_rows < 0) || (cell_cols < 0))
8020 {
8021 rect = CellToRect(j + cell_rows, i + cell_cols);
8022 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8023 clippedcells.Subtract(rect);
8024 }
8025 }
8026 }
8027
8028 dc.SetDeviceClippingRegion( clippedcells );
8029
8030
8031 // horizontal grid lines
8032 for ( int i = internalYToRow(top); i < m_numRows; i++ )
8033 {
8034 int bot = GetRowBottom(i) - 1;
8035
8036 if ( bot > bottom )
8037 break;
8038
8039 if ( bot >= top )
8040 {
8041 dc.SetPen( GetRowGridLinePen(i) );
8042 dc.DrawLine( left, bot, right, bot );
8043 }
8044 }
8045
8046 // vertical grid lines
8047 for ( int colPos = leftCol; colPos < m_numCols; colPos++ )
8048 {
8049 int i = GetColAt( colPos );
8050
8051 int colRight = GetColRight(i);
8052 #ifdef __WXGTK__
8053 if (GetLayoutDirection() != wxLayout_RightToLeft)
8054 #endif
8055 colRight--;
8056
8057 if ( colRight > right )
8058 break;
8059
8060 if ( colRight >= left )
8061 {
8062 dc.SetPen( GetColGridLinePen(i) );
8063 dc.DrawLine( colRight, top, colRight, bottom );
8064 }
8065 }
8066
8067 dc.DestroyClippingRegion();
8068 }
8069
8070 void wxGrid::DrawRowLabels( wxDC& dc, const wxArrayInt& rows)
8071 {
8072 if ( !m_numRows )
8073 return;
8074
8075 const size_t numLabels = rows.GetCount();
8076 for ( size_t i = 0; i < numLabels; i++ )
8077 {
8078 DrawRowLabel( dc, rows[i] );
8079 }
8080 }
8081
8082 void wxGrid::DrawRowLabel( wxDC& dc, int row )
8083 {
8084 if ( GetRowHeight(row) <= 0 || m_rowLabelWidth <= 0 )
8085 return;
8086
8087 wxRect rect;
8088
8089 int rowTop = GetRowTop(row),
8090 rowBottom = GetRowBottom(row) - 1;
8091
8092 dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8093 dc.DrawLine( m_rowLabelWidth - 1, rowTop, m_rowLabelWidth - 1, rowBottom );
8094 dc.DrawLine( 0, rowTop, 0, rowBottom );
8095 dc.DrawLine( 0, rowBottom, m_rowLabelWidth, rowBottom );
8096
8097 dc.SetPen( *wxWHITE_PEN );
8098 dc.DrawLine( 1, rowTop, 1, rowBottom );
8099 dc.DrawLine( 1, rowTop, m_rowLabelWidth - 1, rowTop );
8100
8101 dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT );
8102 dc.SetTextForeground( GetLabelTextColour() );
8103 dc.SetFont( GetLabelFont() );
8104
8105 int hAlign, vAlign;
8106 GetRowLabelAlignment( &hAlign, &vAlign );
8107
8108 rect.SetX( 2 );
8109 rect.SetY( GetRowTop(row) + 2 );
8110 rect.SetWidth( m_rowLabelWidth - 4 );
8111 rect.SetHeight( GetRowHeight(row) - 4 );
8112 DrawTextRectangle( dc, GetRowLabelValue( row ), rect, hAlign, vAlign );
8113 }
8114
8115 void wxGrid::UseNativeColHeader(bool native)
8116 {
8117 if ( native == m_useNativeHeader )
8118 return;
8119
8120 delete m_colWindow;
8121 m_useNativeHeader = native;
8122
8123 CreateColumnWindow();
8124
8125 if ( m_useNativeHeader )
8126 GetColHeader()->SetColumnCount(m_numCols);
8127 CalcWindowSizes();
8128 }
8129
8130 void wxGrid::SetUseNativeColLabels( bool native )
8131 {
8132 wxASSERT_MSG( !m_useNativeHeader,
8133 "doesn't make sense when using native header" );
8134
8135 m_nativeColumnLabels = native;
8136 if (native)
8137 {
8138 int height = wxRendererNative::Get().GetHeaderButtonHeight( this );
8139 SetColLabelSize( height );
8140 }
8141
8142 GetColLabelWindow()->Refresh();
8143 m_cornerLabelWin->Refresh();
8144 }
8145
8146 void wxGrid::DrawColLabels( wxDC& dc,const wxArrayInt& cols )
8147 {
8148 if ( !m_numCols )
8149 return;
8150
8151 const size_t numLabels = cols.GetCount();
8152 for ( size_t i = 0; i < numLabels; i++ )
8153 {
8154 DrawColLabel( dc, cols[i] );
8155 }
8156 }
8157
8158 void wxGrid::DrawCornerLabel(wxDC& dc)
8159 {
8160 if ( m_nativeColumnLabels )
8161 {
8162 wxRect rect(wxSize(m_rowLabelWidth, m_colLabelHeight));
8163 rect.Deflate(1);
8164
8165 wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin, dc, rect, 0);
8166 }
8167 else
8168 {
8169 dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8170 dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1,
8171 m_rowLabelWidth - 1, 0 );
8172 dc.DrawLine( m_rowLabelWidth - 1, m_colLabelHeight - 1,
8173 0, m_colLabelHeight - 1 );
8174 dc.DrawLine( 0, 0, m_rowLabelWidth, 0 );
8175 dc.DrawLine( 0, 0, 0, m_colLabelHeight );
8176
8177 dc.SetPen( *wxWHITE_PEN );
8178 dc.DrawLine( 1, 1, m_rowLabelWidth - 1, 1 );
8179 dc.DrawLine( 1, 1, 1, m_colLabelHeight - 1 );
8180 }
8181 }
8182
8183 void wxGrid::DrawColLabel(wxDC& dc, int col)
8184 {
8185 if ( GetColWidth(col) <= 0 || m_colLabelHeight <= 0 )
8186 return;
8187
8188 int colLeft = GetColLeft(col);
8189
8190 wxRect rect(colLeft, 0, GetColWidth(col), m_colLabelHeight);
8191
8192 if ( m_nativeColumnLabels )
8193 {
8194 wxRendererNative::Get().DrawHeaderButton(GetColLabelWindow(), dc, rect, 0);
8195 }
8196 else
8197 {
8198 int colRight = GetColRight(col) - 1;
8199
8200 dc.SetPen(wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW)));
8201 dc.DrawLine( colRight, 0,
8202 colRight, m_colLabelHeight - 1 );
8203 dc.DrawLine( colLeft, 0,
8204 colRight, 0 );
8205 dc.DrawLine( colLeft, m_colLabelHeight - 1,
8206 colRight + 1, m_colLabelHeight - 1 );
8207
8208 dc.SetPen( *wxWHITE_PEN );
8209 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight - 1 );
8210 dc.DrawLine( colLeft, 1, colRight, 1 );
8211 }
8212
8213 dc.SetBackgroundMode( wxBRUSHSTYLE_TRANSPARENT );
8214 dc.SetTextForeground( GetLabelTextColour() );
8215 dc.SetFont( GetLabelFont() );
8216
8217 int hAlign, vAlign;
8218 GetColLabelAlignment( &hAlign, &vAlign );
8219 const int orient = GetColLabelTextOrientation();
8220
8221 rect.Deflate(2);
8222 DrawTextRectangle(dc, GetColLabelValue(col), rect, hAlign, vAlign, orient);
8223 }
8224
8225 // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which
8226 // we just have to add textOrientation support
8227 void wxGrid::DrawTextRectangle( wxDC& dc,
8228 const wxString& value,
8229 const wxRect& rect,
8230 int horizAlign,
8231 int vertAlign,
8232 int textOrientation )
8233 {
8234 wxArrayString lines;
8235
8236 StringToLines( value, lines );
8237
8238 DrawTextRectangle(dc, lines, rect, horizAlign, vertAlign, textOrientation);
8239 }
8240
8241 void wxGrid::DrawTextRectangle(wxDC& dc,
8242 const wxArrayString& lines,
8243 const wxRect& rect,
8244 int horizAlign,
8245 int vertAlign,
8246 int textOrientation)
8247 {
8248 if ( lines.empty() )
8249 return;
8250
8251 wxDCClipper clip(dc, rect);
8252
8253 long textWidth,
8254 textHeight;
8255
8256 if ( textOrientation == wxHORIZONTAL )
8257 GetTextBoxSize( dc, lines, &textWidth, &textHeight );
8258 else
8259 GetTextBoxSize( dc, lines, &textHeight, &textWidth );
8260
8261 int x = 0,
8262 y = 0;
8263 switch ( vertAlign )
8264 {
8265 case wxALIGN_BOTTOM:
8266 if ( textOrientation == wxHORIZONTAL )
8267 y = rect.y + (rect.height - textHeight - 1);
8268 else
8269 x = rect.x + rect.width - textWidth;
8270 break;
8271
8272 case wxALIGN_CENTRE:
8273 if ( textOrientation == wxHORIZONTAL )
8274 y = rect.y + ((rect.height - textHeight) / 2);
8275 else
8276 x = rect.x + ((rect.width - textWidth) / 2);
8277 break;
8278
8279 case wxALIGN_TOP:
8280 default:
8281 if ( textOrientation == wxHORIZONTAL )
8282 y = rect.y + 1;
8283 else
8284 x = rect.x + 1;
8285 break;
8286 }
8287
8288 // Align each line of a multi-line label
8289 size_t nLines = lines.GetCount();
8290 for ( size_t l = 0; l < nLines; l++ )
8291 {
8292 const wxString& line = lines[l];
8293
8294 if ( line.empty() )
8295 {
8296 *(textOrientation == wxHORIZONTAL ? &y : &x) += dc.GetCharHeight();
8297 continue;
8298 }
8299
8300 wxCoord lineWidth = 0,
8301 lineHeight = 0;
8302 dc.GetTextExtent(line, &lineWidth, &lineHeight);
8303
8304 switch ( horizAlign )
8305 {
8306 case wxALIGN_RIGHT:
8307 if ( textOrientation == wxHORIZONTAL )
8308 x = rect.x + (rect.width - lineWidth - 1);
8309 else
8310 y = rect.y + lineWidth + 1;
8311 break;
8312
8313 case wxALIGN_CENTRE:
8314 if ( textOrientation == wxHORIZONTAL )
8315 x = rect.x + ((rect.width - lineWidth) / 2);
8316 else
8317 y = rect.y + rect.height - ((rect.height - lineWidth) / 2);
8318 break;
8319
8320 case wxALIGN_LEFT:
8321 default:
8322 if ( textOrientation == wxHORIZONTAL )
8323 x = rect.x + 1;
8324 else
8325 y = rect.y + rect.height - 1;
8326 break;
8327 }
8328
8329 if ( textOrientation == wxHORIZONTAL )
8330 {
8331 dc.DrawText( line, x, y );
8332 y += lineHeight;
8333 }
8334 else
8335 {
8336 dc.DrawRotatedText( line, x, y, 90.0 );
8337 x += lineHeight;
8338 }
8339 }
8340 }
8341
8342 // Split multi-line text up into an array of strings.
8343 // Any existing contents of the string array are preserved.
8344 //
8345 // TODO: refactor wxTextFile::Read() and reuse the same code from here
8346 void wxGrid::StringToLines( const wxString& value, wxArrayString& lines ) const
8347 {
8348 int startPos = 0;
8349 int pos;
8350 wxString eol = wxTextFile::GetEOL( wxTextFileType_Unix );
8351 wxString tVal = wxTextFile::Translate( value, wxTextFileType_Unix );
8352
8353 while ( startPos < (int)tVal.length() )
8354 {
8355 pos = tVal.Mid(startPos).Find( eol );
8356 if ( pos < 0 )
8357 {
8358 break;
8359 }
8360 else if ( pos == 0 )
8361 {
8362 lines.Add( wxEmptyString );
8363 }
8364 else
8365 {
8366 lines.Add( tVal.Mid(startPos, pos) );
8367 }
8368
8369 startPos += pos + 1;
8370 }
8371
8372 if ( startPos < (int)tVal.length() )
8373 {
8374 lines.Add( tVal.Mid( startPos ) );
8375 }
8376 }
8377
8378 void wxGrid::GetTextBoxSize( const wxDC& dc,
8379 const wxArrayString& lines,
8380 long *width, long *height ) const
8381 {
8382 wxCoord w = 0;
8383 wxCoord h = 0;
8384 wxCoord lineW = 0, lineH = 0;
8385
8386 size_t i;
8387 for ( i = 0; i < lines.GetCount(); i++ )
8388 {
8389 dc.GetTextExtent( lines[i], &lineW, &lineH );
8390 w = wxMax( w, lineW );
8391 h += lineH;
8392 }
8393
8394 *width = w;
8395 *height = h;
8396 }
8397
8398 //
8399 // ------ Batch processing.
8400 //
8401 void wxGrid::EndBatch()
8402 {
8403 if ( m_batchCount > 0 )
8404 {
8405 m_batchCount--;
8406 if ( !m_batchCount )
8407 {
8408 CalcDimensions();
8409 m_rowLabelWin->Refresh();
8410 m_colWindow->Refresh();
8411 m_cornerLabelWin->Refresh();
8412 m_gridWin->Refresh();
8413 }
8414 }
8415 }
8416
8417 // Use this, rather than wxWindow::Refresh(), to force an immediate
8418 // repainting of the grid. Has no effect if you are already inside a
8419 // BeginBatch / EndBatch block.
8420 //
8421 void wxGrid::ForceRefresh()
8422 {
8423 BeginBatch();
8424 EndBatch();
8425 }
8426
8427 bool wxGrid::Enable(bool enable)
8428 {
8429 if ( !wxScrolledWindow::Enable(enable) )
8430 return false;
8431
8432 // redraw in the new state
8433 m_gridWin->Refresh();
8434
8435 return true;
8436 }
8437
8438 //
8439 // ------ Edit control functions
8440 //
8441
8442 void wxGrid::EnableEditing( bool edit )
8443 {
8444 if ( edit != m_editable )
8445 {
8446 if (!edit)
8447 EnableCellEditControl(edit);
8448 m_editable = edit;
8449 }
8450 }
8451
8452 void wxGrid::EnableCellEditControl( bool enable )
8453 {
8454 if (! m_editable)
8455 return;
8456
8457 if ( enable != m_cellEditCtrlEnabled )
8458 {
8459 if ( enable )
8460 {
8461 if ( SendEvent(wxEVT_GRID_EDITOR_SHOWN) == -1 )
8462 return;
8463
8464 // this should be checked by the caller!
8465 wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") );
8466
8467 // do it before ShowCellEditControl()
8468 m_cellEditCtrlEnabled = enable;
8469
8470 ShowCellEditControl();
8471 }
8472 else
8473 {
8474 //FIXME:add veto support
8475 SendEvent(wxEVT_GRID_EDITOR_HIDDEN);
8476
8477 HideCellEditControl();
8478 SaveEditControlValue();
8479
8480 // do it after HideCellEditControl()
8481 m_cellEditCtrlEnabled = enable;
8482 }
8483 }
8484 }
8485
8486 bool wxGrid::IsCurrentCellReadOnly() const
8487 {
8488 // const_cast
8489 wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords);
8490 bool readonly = attr->IsReadOnly();
8491 attr->DecRef();
8492
8493 return readonly;
8494 }
8495
8496 bool wxGrid::CanEnableCellControl() const
8497 {
8498 return m_editable && (m_currentCellCoords != wxGridNoCellCoords) &&
8499 !IsCurrentCellReadOnly();
8500 }
8501
8502 bool wxGrid::IsCellEditControlEnabled() const
8503 {
8504 // the cell edit control might be disable for all cells or just for the
8505 // current one if it's read only
8506 return m_cellEditCtrlEnabled ? !IsCurrentCellReadOnly() : false;
8507 }
8508
8509 bool wxGrid::IsCellEditControlShown() const
8510 {
8511 bool isShown = false;
8512
8513 if ( m_cellEditCtrlEnabled )
8514 {
8515 int row = m_currentCellCoords.GetRow();
8516 int col = m_currentCellCoords.GetCol();
8517 wxGridCellAttr* attr = GetCellAttr(row, col);
8518 wxGridCellEditor* editor = attr->GetEditor((wxGrid*) this, row, col);
8519 attr->DecRef();
8520
8521 if ( editor )
8522 {
8523 if ( editor->IsCreated() )
8524 {
8525 isShown = editor->GetControl()->IsShown();
8526 }
8527
8528 editor->DecRef();
8529 }
8530 }
8531
8532 return isShown;
8533 }
8534
8535 void wxGrid::ShowCellEditControl()
8536 {
8537 if ( IsCellEditControlEnabled() )
8538 {
8539 if ( !IsVisible( m_currentCellCoords, false ) )
8540 {
8541 m_cellEditCtrlEnabled = false;
8542 return;
8543 }
8544 else
8545 {
8546 wxRect rect = CellToRect( m_currentCellCoords );
8547 int row = m_currentCellCoords.GetRow();
8548 int col = m_currentCellCoords.GetCol();
8549
8550 // if this is part of a multicell, find owner (topleft)
8551 int cell_rows, cell_cols;
8552 GetCellSize( row, col, &cell_rows, &cell_cols );
8553 if ( cell_rows <= 0 || cell_cols <= 0 )
8554 {
8555 row += cell_rows;
8556 col += cell_cols;
8557 m_currentCellCoords.SetRow( row );
8558 m_currentCellCoords.SetCol( col );
8559 }
8560
8561 // erase the highlight and the cell contents because the editor
8562 // might not cover the entire cell
8563 wxClientDC dc( m_gridWin );
8564 PrepareDC( dc );
8565 wxGridCellAttr* attr = GetCellAttr(row, col);
8566 dc.SetBrush(wxBrush(attr->GetBackgroundColour()));
8567 dc.SetPen(*wxTRANSPARENT_PEN);
8568 dc.DrawRectangle(rect);
8569
8570 // convert to scrolled coords
8571 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8572
8573 int nXMove = 0;
8574 if (rect.x < 0)
8575 nXMove = rect.x;
8576
8577 // cell is shifted by one pixel
8578 // However, don't allow x or y to become negative
8579 // since the SetSize() method interprets that as
8580 // "don't change."
8581 if (rect.x > 0)
8582 rect.x--;
8583 if (rect.y > 0)
8584 rect.y--;
8585
8586 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8587 if ( !editor->IsCreated() )
8588 {
8589 editor->Create(m_gridWin, wxID_ANY,
8590 new wxGridCellEditorEvtHandler(this, editor));
8591
8592 wxGridEditorCreatedEvent evt(GetId(),
8593 wxEVT_GRID_EDITOR_CREATED,
8594 this,
8595 row,
8596 col,
8597 editor->GetControl());
8598 GetEventHandler()->ProcessEvent(evt);
8599 }
8600
8601 // resize editor to overflow into righthand cells if allowed
8602 int maxWidth = rect.width;
8603 wxString value = GetCellValue(row, col);
8604 if ( (value != wxEmptyString) && (attr->GetOverflow()) )
8605 {
8606 int y;
8607 GetTextExtent(value, &maxWidth, &y, NULL, NULL, &attr->GetFont());
8608 if (maxWidth < rect.width)
8609 maxWidth = rect.width;
8610 }
8611
8612 int client_right = m_gridWin->GetClientSize().GetWidth();
8613 if (rect.x + maxWidth > client_right)
8614 maxWidth = client_right - rect.x;
8615
8616 if ((maxWidth > rect.width) && (col < m_numCols) && m_table)
8617 {
8618 GetCellSize( row, col, &cell_rows, &cell_cols );
8619 // may have changed earlier
8620 for (int i = col + cell_cols; i < m_numCols; i++)
8621 {
8622 int c_rows, c_cols;
8623 GetCellSize( row, i, &c_rows, &c_cols );
8624
8625 // looks weird going over a multicell
8626 if (m_table->IsEmptyCell( row, i ) &&
8627 (rect.width < maxWidth) && (c_rows == 1))
8628 {
8629 rect.width += GetColWidth( i );
8630 }
8631 else
8632 break;
8633 }
8634
8635 if (rect.GetRight() > client_right)
8636 rect.SetRight( client_right - 1 );
8637 }
8638
8639 editor->SetCellAttr( attr );
8640 editor->SetSize( rect );
8641 if (nXMove != 0)
8642 editor->GetControl()->Move(
8643 editor->GetControl()->GetPosition().x + nXMove,
8644 editor->GetControl()->GetPosition().y );
8645 editor->Show( true, attr );
8646
8647 // recalc dimensions in case we need to
8648 // expand the scrolled window to account for editor
8649 CalcDimensions();
8650
8651 editor->BeginEdit(row, col, this);
8652 editor->SetCellAttr(NULL);
8653
8654 editor->DecRef();
8655 attr->DecRef();
8656 }
8657 }
8658 }
8659
8660 void wxGrid::HideCellEditControl()
8661 {
8662 if ( IsCellEditControlEnabled() )
8663 {
8664 int row = m_currentCellCoords.GetRow();
8665 int col = m_currentCellCoords.GetCol();
8666
8667 wxGridCellAttr *attr = GetCellAttr(row, col);
8668 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
8669 const bool editorHadFocus = editor->GetControl()->HasFocus();
8670 editor->Show( false );
8671 editor->DecRef();
8672 attr->DecRef();
8673
8674 // return the focus to the grid itself if the editor had it
8675 //
8676 // note that we must not do this unconditionally to avoid stealing
8677 // focus from the window which just received it if we are hiding the
8678 // editor precisely because we lost focus
8679 if ( editorHadFocus )
8680 m_gridWin->SetFocus();
8681
8682 // refresh whole row to the right
8683 wxRect rect( CellToRect(row, col) );
8684 CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y );
8685 rect.width = m_gridWin->GetClientSize().GetWidth() - rect.x;
8686
8687 #ifdef __WXMAC__
8688 // ensure that the pixels under the focus ring get refreshed as well
8689 rect.Inflate(10, 10);
8690 #endif
8691
8692 m_gridWin->Refresh( false, &rect );
8693 }
8694 }
8695
8696 void wxGrid::SaveEditControlValue()
8697 {
8698 if ( IsCellEditControlEnabled() )
8699 {
8700 int row = m_currentCellCoords.GetRow();
8701 int col = m_currentCellCoords.GetCol();
8702
8703 wxString oldval = GetCellValue(row, col);
8704
8705 wxGridCellAttr* attr = GetCellAttr(row, col);
8706 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8707 bool changed = editor->EndEdit(row, col, this);
8708
8709 editor->DecRef();
8710 attr->DecRef();
8711
8712 if (changed)
8713 {
8714 if ( SendEvent(wxEVT_GRID_CELL_CHANGE) == -1 )
8715 {
8716 // Event has been vetoed, set the data back.
8717 SetCellValue(row, col, oldval);
8718 }
8719 }
8720 }
8721 }
8722
8723 //
8724 // ------ Grid location functions
8725 // Note that all of these functions work with the logical coordinates of
8726 // grid cells and labels so you will need to convert from device
8727 // coordinates for mouse events etc.
8728 //
8729
8730 wxGridCellCoords wxGrid::XYToCell(int x, int y) const
8731 {
8732 int row = YToRow(y);
8733 int col = XToCol(x);
8734
8735 return row == -1 || col == -1 ? wxGridNoCellCoords
8736 : wxGridCellCoords(row, col);
8737 }
8738
8739 // compute row or column from some (unscrolled) coordinate value, using either
8740 // m_defaultRowHeight/m_defaultColWidth or binary search on array of
8741 // m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used
8742 // for large grids)
8743 int wxGrid::PosToLinePos(int coord,
8744 bool clipToMinMax,
8745 const wxGridOperations& oper) const
8746 {
8747 const int numLines = oper.GetNumberOfLines(this);
8748
8749 if ( coord < 0 )
8750 return clipToMinMax && numLines > 0 ? 0 : wxNOT_FOUND;
8751
8752 const int defaultLineSize = oper.GetDefaultLineSize(this);
8753 wxCHECK_MSG( defaultLineSize, -1, "can't have 0 default line size" );
8754
8755 int maxPos = coord / defaultLineSize,
8756 minPos = 0;
8757
8758 // check for the simplest case: if we have no explicit line sizes
8759 // configured, then we already know the line this position falls in
8760 const wxArrayInt& lineEnds = oper.GetLineEnds(this);
8761 if ( lineEnds.empty() )
8762 {
8763 if ( maxPos < numLines )
8764 return maxPos;
8765
8766 return clipToMinMax ? numLines - 1 : -1;
8767 }
8768
8769
8770 // adjust maxPos before starting the binary search
8771 if ( maxPos >= numLines )
8772 {
8773 maxPos = numLines - 1;
8774 }
8775 else
8776 {
8777 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos)])
8778 {
8779 minPos = maxPos;
8780 const int minDist = oper.GetMinimalAcceptableLineSize(this);
8781 if ( minDist )
8782 maxPos = coord / minDist;
8783 else
8784 maxPos = numLines - 1;
8785 }
8786
8787 if ( maxPos >= numLines )
8788 maxPos = numLines - 1;
8789 }
8790
8791 // check if the position is beyond the last column
8792 const int lineAtMaxPos = oper.GetLineAt(this, maxPos);
8793 if ( coord >= lineEnds[lineAtMaxPos] )
8794 return clipToMinMax ? maxPos : -1;
8795
8796 // or before the first one
8797 const int lineAt0 = oper.GetLineAt(this, 0);
8798 if ( coord < lineEnds[lineAt0] )
8799 return 0;
8800
8801
8802 // finally do perform the binary search
8803 while ( minPos < maxPos )
8804 {
8805 wxCHECK_MSG( lineEnds[oper.GetLineAt(this, minPos)] <= coord &&
8806 coord < lineEnds[oper.GetLineAt(this, maxPos)],
8807 -1,
8808 "wxGrid: internal error in PosToLinePos()" );
8809
8810 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos - 1)] )
8811 return maxPos;
8812 else
8813 maxPos--;
8814
8815 const int median = minPos + (maxPos - minPos + 1) / 2;
8816 if ( coord < lineEnds[oper.GetLineAt(this, median)] )
8817 maxPos = median;
8818 else
8819 minPos = median;
8820 }
8821
8822 return maxPos;
8823 }
8824
8825 int
8826 wxGrid::PosToLine(int coord,
8827 bool clipToMinMax,
8828 const wxGridOperations& oper) const
8829 {
8830 int pos = PosToLinePos(coord, clipToMinMax, oper);
8831
8832 return pos == wxNOT_FOUND ? wxNOT_FOUND : oper.GetLineAt(this, pos);
8833 }
8834
8835 int wxGrid::YToRow(int y, bool clipToMinMax) const
8836 {
8837 return PosToLine(y, clipToMinMax, wxGridRowOperations());
8838 }
8839
8840 int wxGrid::XToCol(int x, bool clipToMinMax) const
8841 {
8842 return PosToLine(x, clipToMinMax, wxGridColumnOperations());
8843 }
8844
8845 int wxGrid::XToPos(int x) const
8846 {
8847 return PosToLinePos(x, true /* clip */, wxGridColumnOperations());
8848 }
8849
8850 // return the row number that that the y coord is near the edge of, or -1 if
8851 // not near an edge.
8852 //
8853 // coords can only possibly be near an edge if
8854 // (a) the row/column is large enough to still allow for an "inner" area
8855 // that is _not_ near the edge (i.e., if the height/width is smaller
8856 // than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be
8857 // near the edge).
8858 // and
8859 // (b) resizing rows/columns (the thing for which edge detection is
8860 // relevant at all) is enabled.
8861 //
8862 int wxGrid::PosToEdgeOfLine(int pos, const wxGridOperations& oper) const
8863 {
8864 if ( !oper.CanResizeLines(this) )
8865 return -1;
8866
8867 const int line = oper.PosToLine(this, pos, true);
8868
8869 if ( oper.GetLineSize(this, line) > WXGRID_LABEL_EDGE_ZONE )
8870 {
8871 // We know that we are in this line, test whether we are close enough
8872 // to start or end border, respectively.
8873 if ( abs(oper.GetLineEndPos(this, line) - pos) < WXGRID_LABEL_EDGE_ZONE )
8874 return line;
8875 else if ( line > 0 &&
8876 pos - oper.GetLineStartPos(this,
8877 line) < WXGRID_LABEL_EDGE_ZONE )
8878 return line - 1;
8879 }
8880
8881 return -1;
8882 }
8883
8884 int wxGrid::YToEdgeOfRow(int y) const
8885 {
8886 return PosToEdgeOfLine(y, wxGridRowOperations());
8887 }
8888
8889 int wxGrid::XToEdgeOfCol(int x) const
8890 {
8891 return PosToEdgeOfLine(x, wxGridColumnOperations());
8892 }
8893
8894 wxRect wxGrid::CellToRect( int row, int col ) const
8895 {
8896 wxRect rect( -1, -1, -1, -1 );
8897
8898 if ( row >= 0 && row < m_numRows &&
8899 col >= 0 && col < m_numCols )
8900 {
8901 int i, cell_rows, cell_cols;
8902 rect.width = rect.height = 0;
8903 GetCellSize( row, col, &cell_rows, &cell_cols );
8904 // if negative then find multicell owner
8905 if (cell_rows < 0)
8906 row += cell_rows;
8907 if (cell_cols < 0)
8908 col += cell_cols;
8909 GetCellSize( row, col, &cell_rows, &cell_cols );
8910
8911 rect.x = GetColLeft(col);
8912 rect.y = GetRowTop(row);
8913 for (i=col; i < col + cell_cols; i++)
8914 rect.width += GetColWidth(i);
8915 for (i=row; i < row + cell_rows; i++)
8916 rect.height += GetRowHeight(i);
8917 }
8918
8919 // if grid lines are enabled, then the area of the cell is a bit smaller
8920 if (m_gridLinesEnabled)
8921 {
8922 rect.width -= 1;
8923 rect.height -= 1;
8924 }
8925
8926 return rect;
8927 }
8928
8929 bool wxGrid::IsVisible( int row, int col, bool wholeCellVisible ) const
8930 {
8931 // get the cell rectangle in logical coords
8932 //
8933 wxRect r( CellToRect( row, col ) );
8934
8935 // convert to device coords
8936 //
8937 int left, top, right, bottom;
8938 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
8939 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
8940
8941 // check against the client area of the grid window
8942 int cw, ch;
8943 m_gridWin->GetClientSize( &cw, &ch );
8944
8945 if ( wholeCellVisible )
8946 {
8947 // is the cell wholly visible ?
8948 return ( left >= 0 && right <= cw &&
8949 top >= 0 && bottom <= ch );
8950 }
8951 else
8952 {
8953 // is the cell partly visible ?
8954 //
8955 return ( ((left >= 0 && left < cw) || (right > 0 && right <= cw)) &&
8956 ((top >= 0 && top < ch) || (bottom > 0 && bottom <= ch)) );
8957 }
8958 }
8959
8960 // make the specified cell location visible by doing a minimal amount
8961 // of scrolling
8962 //
8963 void wxGrid::MakeCellVisible( int row, int col )
8964 {
8965 int i;
8966 int xpos = -1, ypos = -1;
8967
8968 if ( row >= 0 && row < m_numRows &&
8969 col >= 0 && col < m_numCols )
8970 {
8971 // get the cell rectangle in logical coords
8972 wxRect r( CellToRect( row, col ) );
8973
8974 // convert to device coords
8975 int left, top, right, bottom;
8976 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
8977 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
8978
8979 int cw, ch;
8980 m_gridWin->GetClientSize( &cw, &ch );
8981
8982 if ( top < 0 )
8983 {
8984 ypos = r.GetTop();
8985 }
8986 else if ( bottom > ch )
8987 {
8988 int h = r.GetHeight();
8989 ypos = r.GetTop();
8990 for ( i = row - 1; i >= 0; i-- )
8991 {
8992 int rowHeight = GetRowHeight(i);
8993 if ( h + rowHeight > ch )
8994 break;
8995
8996 h += rowHeight;
8997 ypos -= rowHeight;
8998 }
8999
9000 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
9001 // have rounding errors (this is important, because if we do,
9002 // we might not scroll at all and some cells won't be redrawn)
9003 //
9004 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
9005 // so just add a full scroll unit...
9006 ypos += m_scrollLineY;
9007 }
9008
9009 // special handling for wide cells - show always left part of the cell!
9010 // Otherwise, e.g. when stepping from row to row, it would jump between
9011 // left and right part of the cell on every step!
9012 // if ( left < 0 )
9013 if ( left < 0 || (right - left) >= cw )
9014 {
9015 xpos = r.GetLeft();
9016 }
9017 else if ( right > cw )
9018 {
9019 // position the view so that the cell is on the right
9020 int x0, y0;
9021 CalcUnscrolledPosition(0, 0, &x0, &y0);
9022 xpos = x0 + (right - cw);
9023
9024 // see comment for ypos above
9025 xpos += m_scrollLineX;
9026 }
9027
9028 if ( xpos != -1 || ypos != -1 )
9029 {
9030 if ( xpos != -1 )
9031 xpos /= m_scrollLineX;
9032 if ( ypos != -1 )
9033 ypos /= m_scrollLineY;
9034 Scroll( xpos, ypos );
9035 AdjustScrollbars();
9036 }
9037 }
9038 }
9039
9040 //
9041 // ------ Grid cursor movement functions
9042 //
9043
9044 bool
9045 wxGrid::DoMoveCursor(bool expandSelection,
9046 const wxGridDirectionOperations& diroper)
9047 {
9048 if ( m_currentCellCoords == wxGridNoCellCoords )
9049 return false;
9050
9051 if ( expandSelection )
9052 {
9053 wxGridCellCoords coords = m_selectedBlockCorner;
9054 if ( coords == wxGridNoCellCoords )
9055 coords = m_currentCellCoords;
9056
9057 if ( diroper.IsAtBoundary(coords) )
9058 return false;
9059
9060 diroper.Advance(coords);
9061
9062 UpdateBlockBeingSelected(m_currentCellCoords, coords);
9063 }
9064 else // don't expand selection
9065 {
9066 ClearSelection();
9067
9068 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9069 return false;
9070
9071 wxGridCellCoords coords = m_currentCellCoords;
9072 diroper.Advance(coords);
9073
9074 GoToCell(coords);
9075 }
9076
9077 return true;
9078 }
9079
9080 bool wxGrid::MoveCursorUp(bool expandSelection)
9081 {
9082 return DoMoveCursor(expandSelection,
9083 wxGridBackwardOperations(this, wxGridRowOperations()));
9084 }
9085
9086 bool wxGrid::MoveCursorDown(bool expandSelection)
9087 {
9088 return DoMoveCursor(expandSelection,
9089 wxGridForwardOperations(this, wxGridRowOperations()));
9090 }
9091
9092 bool wxGrid::MoveCursorLeft(bool expandSelection)
9093 {
9094 return DoMoveCursor(expandSelection,
9095 wxGridBackwardOperations(this, wxGridColumnOperations()));
9096 }
9097
9098 bool wxGrid::MoveCursorRight(bool expandSelection)
9099 {
9100 return DoMoveCursor(expandSelection,
9101 wxGridForwardOperations(this, wxGridColumnOperations()));
9102 }
9103
9104 bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations& diroper)
9105 {
9106 if ( m_currentCellCoords == wxGridNoCellCoords )
9107 return false;
9108
9109 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9110 return false;
9111
9112 const int oldRow = m_currentCellCoords.GetRow();
9113 int newRow = diroper.MoveByPixelDistance(oldRow, m_gridWin->GetClientSize().y);
9114 if ( newRow == oldRow )
9115 {
9116 wxGridCellCoords coords(m_currentCellCoords);
9117 diroper.Advance(coords);
9118 newRow = coords.GetRow();
9119 }
9120
9121 GoToCell(newRow, m_currentCellCoords.GetCol());
9122
9123 return true;
9124 }
9125
9126 bool wxGrid::MovePageUp()
9127 {
9128 return DoMoveCursorByPage(
9129 wxGridBackwardOperations(this, wxGridRowOperations()));
9130 }
9131
9132 bool wxGrid::MovePageDown()
9133 {
9134 return DoMoveCursorByPage(
9135 wxGridForwardOperations(this, wxGridRowOperations()));
9136 }
9137
9138 // helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
9139 // until we find a non-empty cell or reach the grid end
9140 void
9141 wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords& coords,
9142 const wxGridDirectionOperations& diroper)
9143 {
9144 while ( !diroper.IsAtBoundary(coords) )
9145 {
9146 diroper.Advance(coords);
9147 if ( !m_table->IsEmpty(coords) )
9148 break;
9149 }
9150 }
9151
9152 bool
9153 wxGrid::DoMoveCursorByBlock(bool expandSelection,
9154 const wxGridDirectionOperations& diroper)
9155 {
9156 if ( !m_table || m_currentCellCoords == wxGridNoCellCoords )
9157 return false;
9158
9159 if ( diroper.IsAtBoundary(m_currentCellCoords) )
9160 return false;
9161
9162 wxGridCellCoords coords(m_currentCellCoords);
9163 if ( m_table->IsEmpty(coords) )
9164 {
9165 // we are in an empty cell: find the next block of non-empty cells
9166 AdvanceToNextNonEmpty(coords, diroper);
9167 }
9168 else // current cell is not empty
9169 {
9170 diroper.Advance(coords);
9171 if ( m_table->IsEmpty(coords) )
9172 {
9173 // we started at the end of a block, find the next one
9174 AdvanceToNextNonEmpty(coords, diroper);
9175 }
9176 else // we're in a middle of a block
9177 {
9178 // go to the end of it, i.e. find the last cell before the next
9179 // empty one
9180 while ( !diroper.IsAtBoundary(coords) )
9181 {
9182 wxGridCellCoords coordsNext(coords);
9183 diroper.Advance(coordsNext);
9184 if ( m_table->IsEmpty(coordsNext) )
9185 break;
9186
9187 coords = coordsNext;
9188 }
9189 }
9190 }
9191
9192 if ( expandSelection )
9193 {
9194 UpdateBlockBeingSelected(m_currentCellCoords, coords);
9195 }
9196 else
9197 {
9198 ClearSelection();
9199 GoToCell(coords);
9200 }
9201
9202 return true;
9203 }
9204
9205 bool wxGrid::MoveCursorUpBlock(bool expandSelection)
9206 {
9207 return DoMoveCursorByBlock(
9208 expandSelection,
9209 wxGridBackwardOperations(this, wxGridRowOperations())
9210 );
9211 }
9212
9213 bool wxGrid::MoveCursorDownBlock( bool expandSelection )
9214 {
9215 return DoMoveCursorByBlock(
9216 expandSelection,
9217 wxGridForwardOperations(this, wxGridRowOperations())
9218 );
9219 }
9220
9221 bool wxGrid::MoveCursorLeftBlock( bool expandSelection )
9222 {
9223 return DoMoveCursorByBlock(
9224 expandSelection,
9225 wxGridBackwardOperations(this, wxGridColumnOperations())
9226 );
9227 }
9228
9229 bool wxGrid::MoveCursorRightBlock( bool expandSelection )
9230 {
9231 return DoMoveCursorByBlock(
9232 expandSelection,
9233 wxGridForwardOperations(this, wxGridColumnOperations())
9234 );
9235 }
9236
9237 //
9238 // ------ Label values and formatting
9239 //
9240
9241 void wxGrid::GetRowLabelAlignment( int *horiz, int *vert ) const
9242 {
9243 if ( horiz )
9244 *horiz = m_rowLabelHorizAlign;
9245 if ( vert )
9246 *vert = m_rowLabelVertAlign;
9247 }
9248
9249 void wxGrid::GetColLabelAlignment( int *horiz, int *vert ) const
9250 {
9251 if ( horiz )
9252 *horiz = m_colLabelHorizAlign;
9253 if ( vert )
9254 *vert = m_colLabelVertAlign;
9255 }
9256
9257 int wxGrid::GetColLabelTextOrientation() const
9258 {
9259 return m_colLabelTextOrientation;
9260 }
9261
9262 wxString wxGrid::GetRowLabelValue( int row ) const
9263 {
9264 if ( m_table )
9265 {
9266 return m_table->GetRowLabelValue( row );
9267 }
9268 else
9269 {
9270 wxString s;
9271 s << row;
9272 return s;
9273 }
9274 }
9275
9276 wxString wxGrid::GetColLabelValue( int col ) const
9277 {
9278 if ( m_table )
9279 {
9280 return m_table->GetColLabelValue( col );
9281 }
9282 else
9283 {
9284 wxString s;
9285 s << col;
9286 return s;
9287 }
9288 }
9289
9290 void wxGrid::SetRowLabelSize( int width )
9291 {
9292 wxASSERT( width >= 0 || width == wxGRID_AUTOSIZE );
9293
9294 if ( width == wxGRID_AUTOSIZE )
9295 {
9296 width = CalcColOrRowLabelAreaMinSize(wxGRID_ROW);
9297 }
9298
9299 if ( width != m_rowLabelWidth )
9300 {
9301 if ( width == 0 )
9302 {
9303 m_rowLabelWin->Show( false );
9304 m_cornerLabelWin->Show( false );
9305 }
9306 else if ( m_rowLabelWidth == 0 )
9307 {
9308 m_rowLabelWin->Show( true );
9309 if ( m_colLabelHeight > 0 )
9310 m_cornerLabelWin->Show( true );
9311 }
9312
9313 m_rowLabelWidth = width;
9314 CalcWindowSizes();
9315 wxScrolledWindow::Refresh( true );
9316 }
9317 }
9318
9319 void wxGrid::SetColLabelSize( int height )
9320 {
9321 wxASSERT( height >=0 || height == wxGRID_AUTOSIZE );
9322
9323 if ( height == wxGRID_AUTOSIZE )
9324 {
9325 height = CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN);
9326 }
9327
9328 if ( height != m_colLabelHeight )
9329 {
9330 if ( height == 0 )
9331 {
9332 m_colWindow->Show( false );
9333 m_cornerLabelWin->Show( false );
9334 }
9335 else if ( m_colLabelHeight == 0 )
9336 {
9337 m_colWindow->Show( true );
9338 if ( m_rowLabelWidth > 0 )
9339 m_cornerLabelWin->Show( true );
9340 }
9341
9342 m_colLabelHeight = height;
9343 CalcWindowSizes();
9344 wxScrolledWindow::Refresh( true );
9345 }
9346 }
9347
9348 void wxGrid::SetLabelBackgroundColour( const wxColour& colour )
9349 {
9350 if ( m_labelBackgroundColour != colour )
9351 {
9352 m_labelBackgroundColour = colour;
9353 m_rowLabelWin->SetBackgroundColour( colour );
9354 m_colWindow->SetBackgroundColour( colour );
9355 m_cornerLabelWin->SetBackgroundColour( colour );
9356
9357 if ( !GetBatchCount() )
9358 {
9359 m_rowLabelWin->Refresh();
9360 m_colWindow->Refresh();
9361 m_cornerLabelWin->Refresh();
9362 }
9363 }
9364 }
9365
9366 void wxGrid::SetLabelTextColour( const wxColour& colour )
9367 {
9368 if ( m_labelTextColour != colour )
9369 {
9370 m_labelTextColour = colour;
9371 if ( !GetBatchCount() )
9372 {
9373 m_rowLabelWin->Refresh();
9374 m_colWindow->Refresh();
9375 }
9376 }
9377 }
9378
9379 void wxGrid::SetLabelFont( const wxFont& font )
9380 {
9381 m_labelFont = font;
9382 if ( !GetBatchCount() )
9383 {
9384 m_rowLabelWin->Refresh();
9385 m_colWindow->Refresh();
9386 }
9387 }
9388
9389 void wxGrid::SetRowLabelAlignment( int horiz, int vert )
9390 {
9391 // allow old (incorrect) defs to be used
9392 switch ( horiz )
9393 {
9394 case wxLEFT: horiz = wxALIGN_LEFT; break;
9395 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9396 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9397 }
9398
9399 switch ( vert )
9400 {
9401 case wxTOP: vert = wxALIGN_TOP; break;
9402 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9403 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9404 }
9405
9406 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9407 {
9408 m_rowLabelHorizAlign = horiz;
9409 }
9410
9411 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9412 {
9413 m_rowLabelVertAlign = vert;
9414 }
9415
9416 if ( !GetBatchCount() )
9417 {
9418 m_rowLabelWin->Refresh();
9419 }
9420 }
9421
9422 void wxGrid::SetColLabelAlignment( int horiz, int vert )
9423 {
9424 // allow old (incorrect) defs to be used
9425 switch ( horiz )
9426 {
9427 case wxLEFT: horiz = wxALIGN_LEFT; break;
9428 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9429 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9430 }
9431
9432 switch ( vert )
9433 {
9434 case wxTOP: vert = wxALIGN_TOP; break;
9435 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9436 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9437 }
9438
9439 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9440 {
9441 m_colLabelHorizAlign = horiz;
9442 }
9443
9444 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9445 {
9446 m_colLabelVertAlign = vert;
9447 }
9448
9449 if ( !GetBatchCount() )
9450 {
9451 m_colWindow->Refresh();
9452 }
9453 }
9454
9455 // Note: under MSW, the default column label font must be changed because it
9456 // does not support vertical printing
9457 //
9458 // Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
9459 // pGrid->SetLabelFont(font);
9460 // pGrid->SetColLabelTextOrientation(wxVERTICAL);
9461 //
9462 void wxGrid::SetColLabelTextOrientation( int textOrientation )
9463 {
9464 if ( textOrientation == wxHORIZONTAL || textOrientation == wxVERTICAL )
9465 m_colLabelTextOrientation = textOrientation;
9466
9467 if ( !GetBatchCount() )
9468 m_colWindow->Refresh();
9469 }
9470
9471 void wxGrid::SetRowLabelValue( int row, const wxString& s )
9472 {
9473 if ( m_table )
9474 {
9475 m_table->SetRowLabelValue( row, s );
9476 if ( !GetBatchCount() )
9477 {
9478 wxRect rect = CellToRect( row, 0 );
9479 if ( rect.height > 0 )
9480 {
9481 CalcScrolledPosition(0, rect.y, &rect.x, &rect.y);
9482 rect.x = 0;
9483 rect.width = m_rowLabelWidth;
9484 m_rowLabelWin->Refresh( true, &rect );
9485 }
9486 }
9487 }
9488 }
9489
9490 void wxGrid::SetColLabelValue( int col, const wxString& s )
9491 {
9492 if ( m_table )
9493 {
9494 m_table->SetColLabelValue( col, s );
9495 if ( !GetBatchCount() )
9496 {
9497 if ( m_useNativeHeader )
9498 {
9499 GetColHeader()->UpdateColumn(col);
9500 }
9501 else
9502 {
9503 wxRect rect = CellToRect( 0, col );
9504 if ( rect.width > 0 )
9505 {
9506 CalcScrolledPosition(rect.x, 0, &rect.x, &rect.y);
9507 rect.y = 0;
9508 rect.height = m_colLabelHeight;
9509 GetColLabelWindow()->Refresh( true, &rect );
9510 }
9511 }
9512 }
9513 }
9514 }
9515
9516 void wxGrid::SetGridLineColour( const wxColour& colour )
9517 {
9518 if ( m_gridLineColour != colour )
9519 {
9520 m_gridLineColour = colour;
9521
9522 if ( GridLinesEnabled() )
9523 RedrawGridLines();
9524 }
9525 }
9526
9527 void wxGrid::SetCellHighlightColour( const wxColour& colour )
9528 {
9529 if ( m_cellHighlightColour != colour )
9530 {
9531 m_cellHighlightColour = colour;
9532
9533 wxClientDC dc( m_gridWin );
9534 PrepareDC( dc );
9535 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
9536 DrawCellHighlight(dc, attr);
9537 attr->DecRef();
9538 }
9539 }
9540
9541 void wxGrid::SetCellHighlightPenWidth(int width)
9542 {
9543 if (m_cellHighlightPenWidth != width)
9544 {
9545 m_cellHighlightPenWidth = width;
9546
9547 // Just redrawing the cell highlight is not enough since that won't
9548 // make any visible change if the the thickness is getting smaller.
9549 int row = m_currentCellCoords.GetRow();
9550 int col = m_currentCellCoords.GetCol();
9551 if ( row == -1 || col == -1 || GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9552 return;
9553
9554 wxRect rect = CellToRect(row, col);
9555 m_gridWin->Refresh(true, &rect);
9556 }
9557 }
9558
9559 void wxGrid::SetCellHighlightROPenWidth(int width)
9560 {
9561 if (m_cellHighlightROPenWidth != width)
9562 {
9563 m_cellHighlightROPenWidth = width;
9564
9565 // Just redrawing the cell highlight is not enough since that won't
9566 // make any visible change if the the thickness is getting smaller.
9567 int row = m_currentCellCoords.GetRow();
9568 int col = m_currentCellCoords.GetCol();
9569 if ( row == -1 || col == -1 ||
9570 GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9571 return;
9572
9573 wxRect rect = CellToRect(row, col);
9574 m_gridWin->Refresh(true, &rect);
9575 }
9576 }
9577
9578 void wxGrid::RedrawGridLines()
9579 {
9580 // the lines will be redrawn when the window is thawn
9581 if ( GetBatchCount() )
9582 return;
9583
9584 if ( GridLinesEnabled() )
9585 {
9586 wxClientDC dc( m_gridWin );
9587 PrepareDC( dc );
9588 DrawAllGridLines( dc, wxRegion() );
9589 }
9590 else // remove the grid lines
9591 {
9592 m_gridWin->Refresh();
9593 }
9594 }
9595
9596 void wxGrid::EnableGridLines( bool enable )
9597 {
9598 if ( enable != m_gridLinesEnabled )
9599 {
9600 m_gridLinesEnabled = enable;
9601
9602 RedrawGridLines();
9603 }
9604 }
9605
9606 void wxGrid::DoClipGridLines(bool& var, bool clip)
9607 {
9608 if ( clip != var )
9609 {
9610 var = clip;
9611
9612 if ( GridLinesEnabled() )
9613 RedrawGridLines();
9614 }
9615 }
9616
9617 int wxGrid::GetDefaultRowSize() const
9618 {
9619 return m_defaultRowHeight;
9620 }
9621
9622 int wxGrid::GetRowSize( int row ) const
9623 {
9624 wxCHECK_MSG( row >= 0 && row < m_numRows, 0, _T("invalid row index") );
9625
9626 return GetRowHeight(row);
9627 }
9628
9629 int wxGrid::GetDefaultColSize() const
9630 {
9631 return m_defaultColWidth;
9632 }
9633
9634 int wxGrid::GetColSize( int col ) const
9635 {
9636 wxCHECK_MSG( col >= 0 && col < m_numCols, 0, _T("invalid column index") );
9637
9638 return GetColWidth(col);
9639 }
9640
9641 // ============================================================================
9642 // access to the grid attributes: each of them has a default value in the grid
9643 // itself and may be overidden on a per-cell basis
9644 // ============================================================================
9645
9646 // ----------------------------------------------------------------------------
9647 // setting default attributes
9648 // ----------------------------------------------------------------------------
9649
9650 void wxGrid::SetDefaultCellBackgroundColour( const wxColour& col )
9651 {
9652 m_defaultCellAttr->SetBackgroundColour(col);
9653 #ifdef __WXGTK__
9654 m_gridWin->SetBackgroundColour(col);
9655 #endif
9656 }
9657
9658 void wxGrid::SetDefaultCellTextColour( const wxColour& col )
9659 {
9660 m_defaultCellAttr->SetTextColour(col);
9661 }
9662
9663 void wxGrid::SetDefaultCellAlignment( int horiz, int vert )
9664 {
9665 m_defaultCellAttr->SetAlignment(horiz, vert);
9666 }
9667
9668 void wxGrid::SetDefaultCellOverflow( bool allow )
9669 {
9670 m_defaultCellAttr->SetOverflow(allow);
9671 }
9672
9673 void wxGrid::SetDefaultCellFont( const wxFont& font )
9674 {
9675 m_defaultCellAttr->SetFont(font);
9676 }
9677
9678 // For editors and renderers the type registry takes precedence over the
9679 // default attr, so we need to register the new editor/renderer for the string
9680 // data type in order to make setting a default editor/renderer appear to
9681 // work correctly.
9682
9683 void wxGrid::SetDefaultRenderer(wxGridCellRenderer *renderer)
9684 {
9685 RegisterDataType(wxGRID_VALUE_STRING,
9686 renderer,
9687 GetDefaultEditorForType(wxGRID_VALUE_STRING));
9688 }
9689
9690 void wxGrid::SetDefaultEditor(wxGridCellEditor *editor)
9691 {
9692 RegisterDataType(wxGRID_VALUE_STRING,
9693 GetDefaultRendererForType(wxGRID_VALUE_STRING),
9694 editor);
9695 }
9696
9697 // ----------------------------------------------------------------------------
9698 // access to the default attributes
9699 // ----------------------------------------------------------------------------
9700
9701 wxColour wxGrid::GetDefaultCellBackgroundColour() const
9702 {
9703 return m_defaultCellAttr->GetBackgroundColour();
9704 }
9705
9706 wxColour wxGrid::GetDefaultCellTextColour() const
9707 {
9708 return m_defaultCellAttr->GetTextColour();
9709 }
9710
9711 wxFont wxGrid::GetDefaultCellFont() const
9712 {
9713 return m_defaultCellAttr->GetFont();
9714 }
9715
9716 void wxGrid::GetDefaultCellAlignment( int *horiz, int *vert ) const
9717 {
9718 m_defaultCellAttr->GetAlignment(horiz, vert);
9719 }
9720
9721 bool wxGrid::GetDefaultCellOverflow() const
9722 {
9723 return m_defaultCellAttr->GetOverflow();
9724 }
9725
9726 wxGridCellRenderer *wxGrid::GetDefaultRenderer() const
9727 {
9728 return m_defaultCellAttr->GetRenderer(NULL, 0, 0);
9729 }
9730
9731 wxGridCellEditor *wxGrid::GetDefaultEditor() const
9732 {
9733 return m_defaultCellAttr->GetEditor(NULL, 0, 0);
9734 }
9735
9736 // ----------------------------------------------------------------------------
9737 // access to cell attributes
9738 // ----------------------------------------------------------------------------
9739
9740 wxColour wxGrid::GetCellBackgroundColour(int row, int col) const
9741 {
9742 wxGridCellAttr *attr = GetCellAttr(row, col);
9743 wxColour colour = attr->GetBackgroundColour();
9744 attr->DecRef();
9745
9746 return colour;
9747 }
9748
9749 wxColour wxGrid::GetCellTextColour( int row, int col ) const
9750 {
9751 wxGridCellAttr *attr = GetCellAttr(row, col);
9752 wxColour colour = attr->GetTextColour();
9753 attr->DecRef();
9754
9755 return colour;
9756 }
9757
9758 wxFont wxGrid::GetCellFont( int row, int col ) const
9759 {
9760 wxGridCellAttr *attr = GetCellAttr(row, col);
9761 wxFont font = attr->GetFont();
9762 attr->DecRef();
9763
9764 return font;
9765 }
9766
9767 void wxGrid::GetCellAlignment( int row, int col, int *horiz, int *vert ) const
9768 {
9769 wxGridCellAttr *attr = GetCellAttr(row, col);
9770 attr->GetAlignment(horiz, vert);
9771 attr->DecRef();
9772 }
9773
9774 bool wxGrid::GetCellOverflow( int row, int col ) const
9775 {
9776 wxGridCellAttr *attr = GetCellAttr(row, col);
9777 bool allow = attr->GetOverflow();
9778 attr->DecRef();
9779
9780 return allow;
9781 }
9782
9783 void wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const
9784 {
9785 wxGridCellAttr *attr = GetCellAttr(row, col);
9786 attr->GetSize( num_rows, num_cols );
9787 attr->DecRef();
9788 }
9789
9790 wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col) const
9791 {
9792 wxGridCellAttr* attr = GetCellAttr(row, col);
9793 wxGridCellRenderer* renderer = attr->GetRenderer(this, row, col);
9794 attr->DecRef();
9795
9796 return renderer;
9797 }
9798
9799 wxGridCellEditor* wxGrid::GetCellEditor(int row, int col) const
9800 {
9801 wxGridCellAttr* attr = GetCellAttr(row, col);
9802 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
9803 attr->DecRef();
9804
9805 return editor;
9806 }
9807
9808 bool wxGrid::IsReadOnly(int row, int col) const
9809 {
9810 wxGridCellAttr* attr = GetCellAttr(row, col);
9811 bool isReadOnly = attr->IsReadOnly();
9812 attr->DecRef();
9813
9814 return isReadOnly;
9815 }
9816
9817 // ----------------------------------------------------------------------------
9818 // attribute support: cache, automatic provider creation, ...
9819 // ----------------------------------------------------------------------------
9820
9821 bool wxGrid::CanHaveAttributes() const
9822 {
9823 if ( !m_table )
9824 {
9825 return false;
9826 }
9827
9828 return m_table->CanHaveAttributes();
9829 }
9830
9831 void wxGrid::ClearAttrCache()
9832 {
9833 if ( m_attrCache.row != -1 )
9834 {
9835 wxGridCellAttr *oldAttr = m_attrCache.attr;
9836 m_attrCache.attr = NULL;
9837 m_attrCache.row = -1;
9838 // wxSafeDecRec(...) might cause event processing that accesses
9839 // the cached attribute, if one exists (e.g. by deleting the
9840 // editor stored within the attribute). Therefore it is important
9841 // to invalidate the cache before calling wxSafeDecRef!
9842 wxSafeDecRef(oldAttr);
9843 }
9844 }
9845
9846 void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const
9847 {
9848 if ( attr != NULL )
9849 {
9850 wxGrid *self = (wxGrid *)this; // const_cast
9851
9852 self->ClearAttrCache();
9853 self->m_attrCache.row = row;
9854 self->m_attrCache.col = col;
9855 self->m_attrCache.attr = attr;
9856 wxSafeIncRef(attr);
9857 }
9858 }
9859
9860 bool wxGrid::LookupAttr(int row, int col, wxGridCellAttr **attr) const
9861 {
9862 if ( row == m_attrCache.row && col == m_attrCache.col )
9863 {
9864 *attr = m_attrCache.attr;
9865 wxSafeIncRef(m_attrCache.attr);
9866
9867 #ifdef DEBUG_ATTR_CACHE
9868 gs_nAttrCacheHits++;
9869 #endif
9870
9871 return true;
9872 }
9873 else
9874 {
9875 #ifdef DEBUG_ATTR_CACHE
9876 gs_nAttrCacheMisses++;
9877 #endif
9878
9879 return false;
9880 }
9881 }
9882
9883 wxGridCellAttr *wxGrid::GetCellAttr(int row, int col) const
9884 {
9885 wxGridCellAttr *attr = NULL;
9886 // Additional test to avoid looking at the cache e.g. for
9887 // wxNoCellCoords, as this will confuse memory management.
9888 if ( row >= 0 )
9889 {
9890 if ( !LookupAttr(row, col, &attr) )
9891 {
9892 attr = m_table ? m_table->GetAttr(row, col, wxGridCellAttr::Any)
9893 : NULL;
9894 CacheAttr(row, col, attr);
9895 }
9896 }
9897
9898 if (attr)
9899 {
9900 attr->SetDefAttr(m_defaultCellAttr);
9901 }
9902 else
9903 {
9904 attr = m_defaultCellAttr;
9905 attr->IncRef();
9906 }
9907
9908 return attr;
9909 }
9910
9911 wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const
9912 {
9913 wxGridCellAttr *attr = NULL;
9914 bool canHave = ((wxGrid*)this)->CanHaveAttributes();
9915
9916 wxCHECK_MSG( canHave, attr, _T("Cell attributes not allowed"));
9917 wxCHECK_MSG( m_table, attr, _T("must have a table") );
9918
9919 attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell);
9920 if ( !attr )
9921 {
9922 attr = new wxGridCellAttr(m_defaultCellAttr);
9923
9924 // artificially inc the ref count to match DecRef() in caller
9925 attr->IncRef();
9926 m_table->SetAttr(attr, row, col);
9927 }
9928
9929 return attr;
9930 }
9931
9932 // ----------------------------------------------------------------------------
9933 // setting column attributes (wrappers around SetColAttr)
9934 // ----------------------------------------------------------------------------
9935
9936 void wxGrid::SetColFormatBool(int col)
9937 {
9938 SetColFormatCustom(col, wxGRID_VALUE_BOOL);
9939 }
9940
9941 void wxGrid::SetColFormatNumber(int col)
9942 {
9943 SetColFormatCustom(col, wxGRID_VALUE_NUMBER);
9944 }
9945
9946 void wxGrid::SetColFormatFloat(int col, int width, int precision)
9947 {
9948 wxString typeName = wxGRID_VALUE_FLOAT;
9949 if ( (width != -1) || (precision != -1) )
9950 {
9951 typeName << _T(':') << width << _T(',') << precision;
9952 }
9953
9954 SetColFormatCustom(col, typeName);
9955 }
9956
9957 void wxGrid::SetColFormatCustom(int col, const wxString& typeName)
9958 {
9959 wxGridCellAttr *attr = m_table->GetAttr(-1, col, wxGridCellAttr::Col );
9960 if (!attr)
9961 attr = new wxGridCellAttr;
9962 wxGridCellRenderer *renderer = GetDefaultRendererForType(typeName);
9963 attr->SetRenderer(renderer);
9964 wxGridCellEditor *editor = GetDefaultEditorForType(typeName);
9965 attr->SetEditor(editor);
9966
9967 SetColAttr(col, attr);
9968
9969 }
9970
9971 // ----------------------------------------------------------------------------
9972 // setting cell attributes: this is forwarded to the table
9973 // ----------------------------------------------------------------------------
9974
9975 void wxGrid::SetAttr(int row, int col, wxGridCellAttr *attr)
9976 {
9977 if ( CanHaveAttributes() )
9978 {
9979 m_table->SetAttr(attr, row, col);
9980 ClearAttrCache();
9981 }
9982 else
9983 {
9984 wxSafeDecRef(attr);
9985 }
9986 }
9987
9988 void wxGrid::SetRowAttr(int row, wxGridCellAttr *attr)
9989 {
9990 if ( CanHaveAttributes() )
9991 {
9992 m_table->SetRowAttr(attr, row);
9993 ClearAttrCache();
9994 }
9995 else
9996 {
9997 wxSafeDecRef(attr);
9998 }
9999 }
10000
10001 void wxGrid::SetColAttr(int col, wxGridCellAttr *attr)
10002 {
10003 if ( CanHaveAttributes() )
10004 {
10005 m_table->SetColAttr(attr, col);
10006 ClearAttrCache();
10007 }
10008 else
10009 {
10010 wxSafeDecRef(attr);
10011 }
10012 }
10013
10014 void wxGrid::SetCellBackgroundColour( int row, int col, const wxColour& colour )
10015 {
10016 if ( CanHaveAttributes() )
10017 {
10018 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10019 attr->SetBackgroundColour(colour);
10020 attr->DecRef();
10021 }
10022 }
10023
10024 void wxGrid::SetCellTextColour( int row, int col, const wxColour& colour )
10025 {
10026 if ( CanHaveAttributes() )
10027 {
10028 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10029 attr->SetTextColour(colour);
10030 attr->DecRef();
10031 }
10032 }
10033
10034 void wxGrid::SetCellFont( int row, int col, const wxFont& font )
10035 {
10036 if ( CanHaveAttributes() )
10037 {
10038 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10039 attr->SetFont(font);
10040 attr->DecRef();
10041 }
10042 }
10043
10044 void wxGrid::SetCellAlignment( int row, int col, int horiz, int vert )
10045 {
10046 if ( CanHaveAttributes() )
10047 {
10048 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10049 attr->SetAlignment(horiz, vert);
10050 attr->DecRef();
10051 }
10052 }
10053
10054 void wxGrid::SetCellOverflow( int row, int col, bool allow )
10055 {
10056 if ( CanHaveAttributes() )
10057 {
10058 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10059 attr->SetOverflow(allow);
10060 attr->DecRef();
10061 }
10062 }
10063
10064 void wxGrid::SetCellSize( int row, int col, int num_rows, int num_cols )
10065 {
10066 if ( CanHaveAttributes() )
10067 {
10068 int cell_rows, cell_cols;
10069
10070 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10071 attr->GetSize(&cell_rows, &cell_cols);
10072 attr->SetSize(num_rows, num_cols);
10073 attr->DecRef();
10074
10075 // Cannot set the size of a cell to 0 or negative values
10076 // While it is perfectly legal to do that, this function cannot
10077 // handle all the possibilies, do it by hand by getting the CellAttr.
10078 // You can only set the size of a cell to 1,1 or greater with this fn
10079 wxASSERT_MSG( !((cell_rows < 1) || (cell_cols < 1)),
10080 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
10081 wxASSERT_MSG( !((num_rows < 1) || (num_cols < 1)),
10082 wxT("wxGrid::SetCellSize setting cell size to < 1"));
10083
10084 // if this was already a multicell then "turn off" the other cells first
10085 if ((cell_rows > 1) || (cell_cols > 1))
10086 {
10087 int i, j;
10088 for (j=row; j < row + cell_rows; j++)
10089 {
10090 for (i=col; i < col + cell_cols; i++)
10091 {
10092 if ((i != col) || (j != row))
10093 {
10094 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10095 attr_stub->SetSize( 1, 1 );
10096 attr_stub->DecRef();
10097 }
10098 }
10099 }
10100 }
10101
10102 // mark the cells that will be covered by this cell to
10103 // negative or zero values to point back at this cell
10104 if (((num_rows > 1) || (num_cols > 1)) && (num_rows >= 1) && (num_cols >= 1))
10105 {
10106 int i, j;
10107 for (j=row; j < row + num_rows; j++)
10108 {
10109 for (i=col; i < col + num_cols; i++)
10110 {
10111 if ((i != col) || (j != row))
10112 {
10113 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10114 attr_stub->SetSize( row - j, col - i );
10115 attr_stub->DecRef();
10116 }
10117 }
10118 }
10119 }
10120 }
10121 }
10122
10123 void wxGrid::SetCellRenderer(int row, int col, wxGridCellRenderer *renderer)
10124 {
10125 if ( CanHaveAttributes() )
10126 {
10127 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10128 attr->SetRenderer(renderer);
10129 attr->DecRef();
10130 }
10131 }
10132
10133 void wxGrid::SetCellEditor(int row, int col, wxGridCellEditor* editor)
10134 {
10135 if ( CanHaveAttributes() )
10136 {
10137 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10138 attr->SetEditor(editor);
10139 attr->DecRef();
10140 }
10141 }
10142
10143 void wxGrid::SetReadOnly(int row, int col, bool isReadOnly)
10144 {
10145 if ( CanHaveAttributes() )
10146 {
10147 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10148 attr->SetReadOnly(isReadOnly);
10149 attr->DecRef();
10150 }
10151 }
10152
10153 // ----------------------------------------------------------------------------
10154 // Data type registration
10155 // ----------------------------------------------------------------------------
10156
10157 void wxGrid::RegisterDataType(const wxString& typeName,
10158 wxGridCellRenderer* renderer,
10159 wxGridCellEditor* editor)
10160 {
10161 m_typeRegistry->RegisterDataType(typeName, renderer, editor);
10162 }
10163
10164
10165 wxGridCellEditor * wxGrid::GetDefaultEditorForCell(int row, int col) const
10166 {
10167 wxString typeName = m_table->GetTypeName(row, col);
10168 return GetDefaultEditorForType(typeName);
10169 }
10170
10171 wxGridCellRenderer * wxGrid::GetDefaultRendererForCell(int row, int col) const
10172 {
10173 wxString typeName = m_table->GetTypeName(row, col);
10174 return GetDefaultRendererForType(typeName);
10175 }
10176
10177 wxGridCellEditor * wxGrid::GetDefaultEditorForType(const wxString& typeName) const
10178 {
10179 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10180 if ( index == wxNOT_FOUND )
10181 {
10182 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
10183
10184 return NULL;
10185 }
10186
10187 return m_typeRegistry->GetEditor(index);
10188 }
10189
10190 wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) const
10191 {
10192 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10193 if ( index == wxNOT_FOUND )
10194 {
10195 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
10196
10197 return NULL;
10198 }
10199
10200 return m_typeRegistry->GetRenderer(index);
10201 }
10202
10203 // ----------------------------------------------------------------------------
10204 // row/col size
10205 // ----------------------------------------------------------------------------
10206
10207 void wxGrid::EnableDragRowSize( bool enable )
10208 {
10209 m_canDragRowSize = enable;
10210 }
10211
10212 void wxGrid::EnableDragColSize( bool enable )
10213 {
10214 m_canDragColSize = enable;
10215 }
10216
10217 void wxGrid::EnableDragGridSize( bool enable )
10218 {
10219 m_canDragGridSize = enable;
10220 }
10221
10222 void wxGrid::EnableDragCell( bool enable )
10223 {
10224 m_canDragCell = enable;
10225 }
10226
10227 void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows )
10228 {
10229 m_defaultRowHeight = wxMax( height, m_minAcceptableRowHeight );
10230
10231 if ( resizeExistingRows )
10232 {
10233 // since we are resizing all rows to the default row size,
10234 // we can simply clear the row heights and row bottoms
10235 // arrays (which also allows us to take advantage of
10236 // some speed optimisations)
10237 m_rowHeights.Empty();
10238 m_rowBottoms.Empty();
10239 if ( !GetBatchCount() )
10240 CalcDimensions();
10241 }
10242 }
10243
10244 void wxGrid::SetRowSize( int row, int height )
10245 {
10246 wxCHECK_RET( row >= 0 && row < m_numRows, _T("invalid row index") );
10247
10248 // if < 0 then calculate new height from label
10249 if ( height < 0 )
10250 {
10251 long w, h;
10252 wxArrayString lines;
10253 wxClientDC dc(m_rowLabelWin);
10254 dc.SetFont(GetLabelFont());
10255 StringToLines(GetRowLabelValue( row ), lines);
10256 GetTextBoxSize( dc, lines, &w, &h );
10257 //check that it is not less than the minimal height
10258 height = wxMax(h, GetRowMinimalAcceptableHeight());
10259 }
10260
10261 // See comment in SetColSize
10262 if ( height < GetRowMinimalAcceptableHeight())
10263 return;
10264
10265 if ( m_rowHeights.IsEmpty() )
10266 {
10267 // need to really create the array
10268 InitRowHeights();
10269 }
10270
10271 int h = wxMax( 0, height );
10272 int diff = h - m_rowHeights[row];
10273
10274 m_rowHeights[row] = h;
10275 for ( int i = row; i < m_numRows; i++ )
10276 {
10277 m_rowBottoms[i] += diff;
10278 }
10279
10280 if ( !GetBatchCount() )
10281 CalcDimensions();
10282 }
10283
10284 void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols )
10285 {
10286 // we dont allow zero default column width
10287 m_defaultColWidth = wxMax( wxMax( width, m_minAcceptableColWidth ), 1 );
10288
10289 if ( resizeExistingCols )
10290 {
10291 // since we are resizing all columns to the default column size,
10292 // we can simply clear the col widths and col rights
10293 // arrays (which also allows us to take advantage of
10294 // some speed optimisations)
10295 m_colWidths.Empty();
10296 m_colRights.Empty();
10297 if ( !GetBatchCount() )
10298 CalcDimensions();
10299 }
10300 }
10301
10302 void wxGrid::SetColSize( int col, int width )
10303 {
10304 wxCHECK_RET( col >= 0 && col < m_numCols, _T("invalid column index") );
10305
10306 // if < 0 then calculate new width from label
10307 if ( width < 0 )
10308 {
10309 long w, h;
10310 wxArrayString lines;
10311 wxClientDC dc(m_colWindow);
10312 dc.SetFont(GetLabelFont());
10313 StringToLines(GetColLabelValue(col), lines);
10314 if ( GetColLabelTextOrientation() == wxHORIZONTAL )
10315 GetTextBoxSize( dc, lines, &w, &h );
10316 else
10317 GetTextBoxSize( dc, lines, &h, &w );
10318 width = w + 6;
10319 //check that it is not less than the minimal width
10320 width = wxMax(width, GetColMinimalAcceptableWidth());
10321 }
10322
10323 // should we check that it's bigger than GetColMinimalWidth(col) here?
10324 // (VZ)
10325 // No, because it is reasonable to assume the library user know's
10326 // what he is doing. However we should test against the weaker
10327 // constraint of minimalAcceptableWidth, as this breaks rendering
10328 //
10329 // This test then fixes sf.net bug #645734
10330
10331 if ( width < GetColMinimalAcceptableWidth() )
10332 return;
10333
10334 if ( m_colWidths.IsEmpty() )
10335 {
10336 // need to really create the array
10337 InitColWidths();
10338 }
10339
10340 int w = wxMax( 0, width );
10341 int diff = w - m_colWidths[col];
10342 m_colWidths[col] = w;
10343
10344 for ( int colPos = GetColPos(col); colPos < m_numCols; colPos++ )
10345 {
10346 m_colRights[GetColAt(colPos)] += diff;
10347 }
10348
10349 if ( !GetBatchCount() )
10350 {
10351 CalcDimensions();
10352 Refresh();
10353 }
10354 }
10355
10356 void wxGrid::SetColMinimalWidth( int col, int width )
10357 {
10358 if (width > GetColMinimalAcceptableWidth())
10359 {
10360 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10361 m_colMinWidths[key] = width;
10362 }
10363 }
10364
10365 void wxGrid::SetRowMinimalHeight( int row, int width )
10366 {
10367 if (width > GetRowMinimalAcceptableHeight())
10368 {
10369 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10370 m_rowMinHeights[key] = width;
10371 }
10372 }
10373
10374 int wxGrid::GetColMinimalWidth(int col) const
10375 {
10376 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10377 wxLongToLongHashMap::const_iterator it = m_colMinWidths.find(key);
10378
10379 return it != m_colMinWidths.end() ? (int)it->second : m_minAcceptableColWidth;
10380 }
10381
10382 int wxGrid::GetRowMinimalHeight(int row) const
10383 {
10384 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10385 wxLongToLongHashMap::const_iterator it = m_rowMinHeights.find(key);
10386
10387 return it != m_rowMinHeights.end() ? (int)it->second : m_minAcceptableRowHeight;
10388 }
10389
10390 void wxGrid::SetColMinimalAcceptableWidth( int width )
10391 {
10392 // We do allow a width of 0 since this gives us
10393 // an easy way to temporarily hiding columns.
10394 if ( width >= 0 )
10395 m_minAcceptableColWidth = width;
10396 }
10397
10398 void wxGrid::SetRowMinimalAcceptableHeight( int height )
10399 {
10400 // We do allow a height of 0 since this gives us
10401 // an easy way to temporarily hiding rows.
10402 if ( height >= 0 )
10403 m_minAcceptableRowHeight = height;
10404 }
10405
10406 int wxGrid::GetColMinimalAcceptableWidth() const
10407 {
10408 return m_minAcceptableColWidth;
10409 }
10410
10411 int wxGrid::GetRowMinimalAcceptableHeight() const
10412 {
10413 return m_minAcceptableRowHeight;
10414 }
10415
10416 // ----------------------------------------------------------------------------
10417 // auto sizing
10418 // ----------------------------------------------------------------------------
10419
10420 void
10421 wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction)
10422 {
10423 const bool column = direction == wxGRID_COLUMN;
10424
10425 wxClientDC dc(m_gridWin);
10426
10427 // cancel editing of cell
10428 HideCellEditControl();
10429 SaveEditControlValue();
10430
10431 // init both of them to avoid compiler warnings, even if we only need one
10432 int row = -1,
10433 col = -1;
10434 if ( column )
10435 col = colOrRow;
10436 else
10437 row = colOrRow;
10438
10439 wxCoord extent, extentMax = 0;
10440 int max = column ? m_numRows : m_numCols;
10441 for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ )
10442 {
10443 if ( column )
10444 row = rowOrCol;
10445 else
10446 col = rowOrCol;
10447
10448 wxGridCellAttr *attr = GetCellAttr(row, col);
10449 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
10450 if ( renderer )
10451 {
10452 wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col);
10453 extent = column ? size.x : size.y;
10454 if ( extent > extentMax )
10455 extentMax = extent;
10456
10457 renderer->DecRef();
10458 }
10459
10460 attr->DecRef();
10461 }
10462
10463 // now also compare with the column label extent
10464 wxCoord w, h;
10465 dc.SetFont( GetLabelFont() );
10466
10467 if ( column )
10468 {
10469 dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h );
10470 if ( GetColLabelTextOrientation() == wxVERTICAL )
10471 w = h;
10472 }
10473 else
10474 dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h );
10475
10476 extent = column ? w : h;
10477 if ( extent > extentMax )
10478 extentMax = extent;
10479
10480 if ( !extentMax )
10481 {
10482 // empty column - give default extent (notice that if extentMax is less
10483 // than default extent but != 0, it's OK)
10484 extentMax = column ? m_defaultColWidth : m_defaultRowHeight;
10485 }
10486 else
10487 {
10488 if ( column )
10489 // leave some space around text
10490 extentMax += 10;
10491 else
10492 extentMax += 6;
10493 }
10494
10495 if ( column )
10496 {
10497 // Ensure automatic width is not less than minimal width. See the
10498 // comment in SetColSize() for explanation of why this isn't done
10499 // in SetColSize().
10500 if ( !setAsMin )
10501 extentMax = wxMax(extentMax, GetColMinimalWidth(col));
10502
10503 SetColSize( col, extentMax );
10504 if ( !GetBatchCount() )
10505 {
10506 if ( m_useNativeHeader )
10507 {
10508 GetColHeader()->UpdateColumn(col);
10509 }
10510 else
10511 {
10512 int cw, ch, dummy;
10513 m_gridWin->GetClientSize( &cw, &ch );
10514 wxRect rect ( CellToRect( 0, col ) );
10515 rect.y = 0;
10516 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
10517 rect.width = cw - rect.x;
10518 rect.height = m_colLabelHeight;
10519 GetColLabelWindow()->Refresh( true, &rect );
10520 }
10521 }
10522 }
10523 else
10524 {
10525 // Ensure automatic width is not less than minimal height. See the
10526 // comment in SetColSize() for explanation of why this isn't done
10527 // in SetRowSize().
10528 if ( !setAsMin )
10529 extentMax = wxMax(extentMax, GetRowMinimalHeight(row));
10530
10531 SetRowSize(row, extentMax);
10532 if ( !GetBatchCount() )
10533 {
10534 int cw, ch, dummy;
10535 m_gridWin->GetClientSize( &cw, &ch );
10536 wxRect rect( CellToRect( row, 0 ) );
10537 rect.x = 0;
10538 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10539 rect.width = m_rowLabelWidth;
10540 rect.height = ch - rect.y;
10541 m_rowLabelWin->Refresh( true, &rect );
10542 }
10543 }
10544
10545 if ( setAsMin )
10546 {
10547 if ( column )
10548 SetColMinimalWidth(col, extentMax);
10549 else
10550 SetRowMinimalHeight(row, extentMax);
10551 }
10552 }
10553
10554 wxCoord wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction)
10555 {
10556 // calculate size for the rows or columns?
10557 const bool calcRows = direction == wxGRID_ROW;
10558
10559 wxClientDC dc(calcRows ? GetGridRowLabelWindow()
10560 : GetGridColLabelWindow());
10561 dc.SetFont(GetLabelFont());
10562
10563 // which dimension should we take into account for calculations?
10564 //
10565 // for columns, the text can be only horizontal so it's easy but for rows
10566 // we also have to take into account the text orientation
10567 const bool
10568 useWidth = calcRows || (GetColLabelTextOrientation() == wxVERTICAL);
10569
10570 wxArrayString lines;
10571 wxCoord extentMax = 0;
10572
10573 const int numRowsOrCols = calcRows ? m_numRows : m_numCols;
10574 for ( int rowOrCol = 0; rowOrCol < numRowsOrCols; rowOrCol++ )
10575 {
10576 lines.Clear();
10577
10578 wxString label = calcRows ? GetRowLabelValue(rowOrCol)
10579 : GetColLabelValue(rowOrCol);
10580 StringToLines(label, lines);
10581
10582 long w, h;
10583 GetTextBoxSize(dc, lines, &w, &h);
10584
10585 const wxCoord extent = useWidth ? w : h;
10586 if ( extent > extentMax )
10587 extentMax = extent;
10588 }
10589
10590 if ( !extentMax )
10591 {
10592 // empty column - give default extent (notice that if extentMax is less
10593 // than default extent but != 0, it's OK)
10594 extentMax = calcRows ? GetDefaultRowLabelSize()
10595 : GetDefaultColLabelSize();
10596 }
10597
10598 // leave some space around text (taken from AutoSizeColOrRow)
10599 if ( calcRows )
10600 extentMax += 10;
10601 else
10602 extentMax += 6;
10603
10604 return extentMax;
10605 }
10606
10607 int wxGrid::SetOrCalcColumnSizes(bool calcOnly, bool setAsMin)
10608 {
10609 int width = m_rowLabelWidth;
10610
10611 wxGridUpdateLocker locker;
10612 if(!calcOnly)
10613 locker.Create(this);
10614
10615 for ( int col = 0; col < m_numCols; col++ )
10616 {
10617 if ( !calcOnly )
10618 AutoSizeColumn(col, setAsMin);
10619
10620 width += GetColWidth(col);
10621 }
10622
10623 return width;
10624 }
10625
10626 int wxGrid::SetOrCalcRowSizes(bool calcOnly, bool setAsMin)
10627 {
10628 int height = m_colLabelHeight;
10629
10630 wxGridUpdateLocker locker;
10631 if(!calcOnly)
10632 locker.Create(this);
10633
10634 for ( int row = 0; row < m_numRows; row++ )
10635 {
10636 if ( !calcOnly )
10637 AutoSizeRow(row, setAsMin);
10638
10639 height += GetRowHeight(row);
10640 }
10641
10642 return height;
10643 }
10644
10645 void wxGrid::AutoSize()
10646 {
10647 wxGridUpdateLocker locker(this);
10648
10649 wxSize size(SetOrCalcColumnSizes(false) - m_rowLabelWidth + m_extraWidth,
10650 SetOrCalcRowSizes(false) - m_colLabelHeight + m_extraHeight);
10651
10652 // we know that we're not going to have scrollbars so disable them now to
10653 // avoid trouble in SetClientSize() which can otherwise set the correct
10654 // client size but also leave space for (not needed any more) scrollbars
10655 SetScrollbars(0, 0, 0, 0, 0, 0, true);
10656
10657 // restore the scroll rate parameters overwritten by SetScrollbars()
10658 SetScrollRate(m_scrollLineX, m_scrollLineY);
10659
10660 SetClientSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight);
10661 }
10662
10663 void wxGrid::AutoSizeRowLabelSize( int row )
10664 {
10665 // Hide the edit control, so it
10666 // won't interfere with drag-shrinking.
10667 if ( IsCellEditControlShown() )
10668 {
10669 HideCellEditControl();
10670 SaveEditControlValue();
10671 }
10672
10673 // autosize row height depending on label text
10674 SetRowSize(row, -1);
10675 ForceRefresh();
10676 }
10677
10678 void wxGrid::AutoSizeColLabelSize( int col )
10679 {
10680 // Hide the edit control, so it
10681 // won't interfere with drag-shrinking.
10682 if ( IsCellEditControlShown() )
10683 {
10684 HideCellEditControl();
10685 SaveEditControlValue();
10686 }
10687
10688 // autosize column width depending on label text
10689 SetColSize(col, -1);
10690 ForceRefresh();
10691 }
10692
10693 wxSize wxGrid::DoGetBestSize() const
10694 {
10695 wxGrid *self = (wxGrid *)this; // const_cast
10696
10697 // we do the same as in AutoSize() here with the exception that we don't
10698 // change the column/row sizes, only calculate them
10699 wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth,
10700 self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight);
10701
10702 // NOTE: This size should be cached, but first we need to add calls to
10703 // InvalidateBestSize everywhere that could change the results of this
10704 // calculation.
10705 // CacheBestSize(size);
10706
10707 return wxSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight)
10708 + GetWindowBorderSize();
10709 }
10710
10711 void wxGrid::Fit()
10712 {
10713 AutoSize();
10714 }
10715
10716 wxPen& wxGrid::GetDividerPen() const
10717 {
10718 return wxNullPen;
10719 }
10720
10721 // ----------------------------------------------------------------------------
10722 // cell value accessor functions
10723 // ----------------------------------------------------------------------------
10724
10725 void wxGrid::SetCellValue( int row, int col, const wxString& s )
10726 {
10727 if ( m_table )
10728 {
10729 m_table->SetValue( row, col, s );
10730 if ( !GetBatchCount() )
10731 {
10732 int dummy;
10733 wxRect rect( CellToRect( row, col ) );
10734 rect.x = 0;
10735 rect.width = m_gridWin->GetClientSize().GetWidth();
10736 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10737 m_gridWin->Refresh( false, &rect );
10738 }
10739
10740 if ( m_currentCellCoords.GetRow() == row &&
10741 m_currentCellCoords.GetCol() == col &&
10742 IsCellEditControlShown())
10743 // Note: If we are using IsCellEditControlEnabled,
10744 // this interacts badly with calling SetCellValue from
10745 // an EVT_GRID_CELL_CHANGE handler.
10746 {
10747 HideCellEditControl();
10748 ShowCellEditControl(); // will reread data from table
10749 }
10750 }
10751 }
10752
10753 // ----------------------------------------------------------------------------
10754 // block, row and column selection
10755 // ----------------------------------------------------------------------------
10756
10757 void wxGrid::SelectRow( int row, bool addToSelected )
10758 {
10759 if ( !m_selection )
10760 return;
10761
10762 if ( !addToSelected )
10763 ClearSelection();
10764
10765 m_selection->SelectRow(row);
10766 }
10767
10768 void wxGrid::SelectCol( int col, bool addToSelected )
10769 {
10770 if ( !m_selection )
10771 return;
10772
10773 if ( !addToSelected )
10774 ClearSelection();
10775
10776 m_selection->SelectCol(col);
10777 }
10778
10779 void wxGrid::SelectBlock(int topRow, int leftCol, int bottomRow, int rightCol,
10780 bool addToSelected)
10781 {
10782 if ( !m_selection )
10783 return;
10784
10785 if ( !addToSelected )
10786 ClearSelection();
10787
10788 m_selection->SelectBlock(topRow, leftCol, bottomRow, rightCol);
10789 }
10790
10791 void wxGrid::SelectAll()
10792 {
10793 if ( m_numRows > 0 && m_numCols > 0 )
10794 {
10795 if ( m_selection )
10796 m_selection->SelectBlock( 0, 0, m_numRows - 1, m_numCols - 1 );
10797 }
10798 }
10799
10800 // ----------------------------------------------------------------------------
10801 // cell, row and col deselection
10802 // ----------------------------------------------------------------------------
10803
10804 void wxGrid::DeselectLine(int line, const wxGridOperations& oper)
10805 {
10806 if ( !m_selection )
10807 return;
10808
10809 const wxGridSelectionModes mode = m_selection->GetSelectionMode();
10810 if ( mode == oper.GetSelectionMode() )
10811 {
10812 const wxGridCellCoords c(oper.MakeCoords(line, 0));
10813 if ( m_selection->IsInSelection(c) )
10814 m_selection->ToggleCellSelection(c);
10815 }
10816 else if ( mode != oper.Dual().GetSelectionMode() )
10817 {
10818 const int nOther = oper.Dual().GetNumberOfLines(this);
10819 for ( int i = 0; i < nOther; i++ )
10820 {
10821 const wxGridCellCoords c(oper.MakeCoords(line, i));
10822 if ( m_selection->IsInSelection(c) )
10823 m_selection->ToggleCellSelection(c);
10824 }
10825 }
10826 //else: can only select orthogonal lines so no lines in this direction
10827 // could have been selected anyhow
10828 }
10829
10830 void wxGrid::DeselectRow(int row)
10831 {
10832 DeselectLine(row, wxGridRowOperations());
10833 }
10834
10835 void wxGrid::DeselectCol(int col)
10836 {
10837 DeselectLine(col, wxGridColumnOperations());
10838 }
10839
10840 void wxGrid::DeselectCell( int row, int col )
10841 {
10842 if ( m_selection && m_selection->IsInSelection(row, col) )
10843 m_selection->ToggleCellSelection(row, col);
10844 }
10845
10846 bool wxGrid::IsSelection() const
10847 {
10848 return ( m_selection && (m_selection->IsSelection() ||
10849 ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
10850 m_selectedBlockBottomRight != wxGridNoCellCoords) ) );
10851 }
10852
10853 bool wxGrid::IsInSelection( int row, int col ) const
10854 {
10855 return ( m_selection && (m_selection->IsInSelection( row, col ) ||
10856 ( row >= m_selectedBlockTopLeft.GetRow() &&
10857 col >= m_selectedBlockTopLeft.GetCol() &&
10858 row <= m_selectedBlockBottomRight.GetRow() &&
10859 col <= m_selectedBlockBottomRight.GetCol() )) );
10860 }
10861
10862 wxGridCellCoordsArray wxGrid::GetSelectedCells() const
10863 {
10864 if (!m_selection)
10865 {
10866 wxGridCellCoordsArray a;
10867 return a;
10868 }
10869
10870 return m_selection->m_cellSelection;
10871 }
10872
10873 wxGridCellCoordsArray wxGrid::GetSelectionBlockTopLeft() const
10874 {
10875 if (!m_selection)
10876 {
10877 wxGridCellCoordsArray a;
10878 return a;
10879 }
10880
10881 return m_selection->m_blockSelectionTopLeft;
10882 }
10883
10884 wxGridCellCoordsArray wxGrid::GetSelectionBlockBottomRight() const
10885 {
10886 if (!m_selection)
10887 {
10888 wxGridCellCoordsArray a;
10889 return a;
10890 }
10891
10892 return m_selection->m_blockSelectionBottomRight;
10893 }
10894
10895 wxArrayInt wxGrid::GetSelectedRows() const
10896 {
10897 if (!m_selection)
10898 {
10899 wxArrayInt a;
10900 return a;
10901 }
10902
10903 return m_selection->m_rowSelection;
10904 }
10905
10906 wxArrayInt wxGrid::GetSelectedCols() const
10907 {
10908 if (!m_selection)
10909 {
10910 wxArrayInt a;
10911 return a;
10912 }
10913
10914 return m_selection->m_colSelection;
10915 }
10916
10917 void wxGrid::ClearSelection()
10918 {
10919 wxRect r1 = BlockToDeviceRect(m_selectedBlockTopLeft,
10920 m_selectedBlockBottomRight);
10921 wxRect r2 = BlockToDeviceRect(m_currentCellCoords,
10922 m_selectedBlockCorner);
10923
10924 m_selectedBlockTopLeft =
10925 m_selectedBlockBottomRight =
10926 m_selectedBlockCorner = wxGridNoCellCoords;
10927
10928 Refresh( false, &r1 );
10929 Refresh( false, &r2 );
10930
10931 if ( m_selection )
10932 m_selection->ClearSelection();
10933 }
10934
10935 // This function returns the rectangle that encloses the given block
10936 // in device coords clipped to the client size of the grid window.
10937 //
10938 wxRect wxGrid::BlockToDeviceRect( const wxGridCellCoords& topLeft,
10939 const wxGridCellCoords& bottomRight ) const
10940 {
10941 wxRect resultRect;
10942 wxRect tempCellRect = CellToRect(topLeft);
10943 if ( tempCellRect != wxGridNoCellRect )
10944 {
10945 resultRect = tempCellRect;
10946 }
10947 else
10948 {
10949 resultRect = wxRect(0, 0, 0, 0);
10950 }
10951
10952 tempCellRect = CellToRect(bottomRight);
10953 if ( tempCellRect != wxGridNoCellRect )
10954 {
10955 resultRect += tempCellRect;
10956 }
10957 else
10958 {
10959 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
10960 return wxGridNoCellRect;
10961 }
10962
10963 // Ensure that left/right and top/bottom pairs are in order.
10964 int left = resultRect.GetLeft();
10965 int top = resultRect.GetTop();
10966 int right = resultRect.GetRight();
10967 int bottom = resultRect.GetBottom();
10968
10969 int leftCol = topLeft.GetCol();
10970 int topRow = topLeft.GetRow();
10971 int rightCol = bottomRight.GetCol();
10972 int bottomRow = bottomRight.GetRow();
10973
10974 if (left > right)
10975 {
10976 int tmp = left;
10977 left = right;
10978 right = tmp;
10979
10980 tmp = leftCol;
10981 leftCol = rightCol;
10982 rightCol = tmp;
10983 }
10984
10985 if (top > bottom)
10986 {
10987 int tmp = top;
10988 top = bottom;
10989 bottom = tmp;
10990
10991 tmp = topRow;
10992 topRow = bottomRow;
10993 bottomRow = tmp;
10994 }
10995
10996 // The following loop is ONLY necessary to detect and handle merged cells.
10997 int cw, ch;
10998 m_gridWin->GetClientSize( &cw, &ch );
10999
11000 // Get the origin coordinates: notice that they will be negative if the
11001 // grid is scrolled downwards/to the right.
11002 int gridOriginX = 0;
11003 int gridOriginY = 0;
11004 CalcScrolledPosition(gridOriginX, gridOriginY, &gridOriginX, &gridOriginY);
11005
11006 int onScreenLeftmostCol = internalXToCol(-gridOriginX);
11007 int onScreenUppermostRow = internalYToRow(-gridOriginY);
11008
11009 int onScreenRightmostCol = internalXToCol(-gridOriginX + cw);
11010 int onScreenBottommostRow = internalYToRow(-gridOriginY + ch);
11011
11012 // Bound our loop so that we only examine the portion of the selected block
11013 // that is shown on screen. Therefore, we compare the Top-Left block values
11014 // to the Top-Left screen values, and the Bottom-Right block values to the
11015 // Bottom-Right screen values, choosing appropriately.
11016 const int visibleTopRow = wxMax(topRow, onScreenUppermostRow);
11017 const int visibleBottomRow = wxMin(bottomRow, onScreenBottommostRow);
11018 const int visibleLeftCol = wxMax(leftCol, onScreenLeftmostCol);
11019 const int visibleRightCol = wxMin(rightCol, onScreenRightmostCol);
11020
11021 for ( int j = visibleTopRow; j <= visibleBottomRow; j++ )
11022 {
11023 for ( int i = visibleLeftCol; i <= visibleRightCol; i++ )
11024 {
11025 if ( (j == visibleTopRow) || (j == visibleBottomRow) ||
11026 (i == visibleLeftCol) || (i == visibleRightCol) )
11027 {
11028 tempCellRect = CellToRect( j, i );
11029
11030 if (tempCellRect.x < left)
11031 left = tempCellRect.x;
11032 if (tempCellRect.y < top)
11033 top = tempCellRect.y;
11034 if (tempCellRect.x + tempCellRect.width > right)
11035 right = tempCellRect.x + tempCellRect.width;
11036 if (tempCellRect.y + tempCellRect.height > bottom)
11037 bottom = tempCellRect.y + tempCellRect.height;
11038 }
11039 else
11040 {
11041 i = visibleRightCol; // jump over inner cells.
11042 }
11043 }
11044 }
11045
11046 // Convert to scrolled coords
11047 CalcScrolledPosition( left, top, &left, &top );
11048 CalcScrolledPosition( right, bottom, &right, &bottom );
11049
11050 if (right < 0 || bottom < 0 || left > cw || top > ch)
11051 return wxRect(0,0,0,0);
11052
11053 resultRect.SetLeft( wxMax(0, left) );
11054 resultRect.SetTop( wxMax(0, top) );
11055 resultRect.SetRight( wxMin(cw, right) );
11056 resultRect.SetBottom( wxMin(ch, bottom) );
11057
11058 return resultRect;
11059 }
11060
11061 // ----------------------------------------------------------------------------
11062 // drop target
11063 // ----------------------------------------------------------------------------
11064
11065 #if wxUSE_DRAG_AND_DROP
11066
11067 // this allow setting drop target directly on wxGrid
11068 void wxGrid::SetDropTarget(wxDropTarget *dropTarget)
11069 {
11070 GetGridWindow()->SetDropTarget(dropTarget);
11071 }
11072
11073 #endif // wxUSE_DRAG_AND_DROP
11074
11075 // ----------------------------------------------------------------------------
11076 // grid event classes
11077 // ----------------------------------------------------------------------------
11078
11079 IMPLEMENT_DYNAMIC_CLASS( wxGridEvent, wxNotifyEvent )
11080
11081 wxGridEvent::wxGridEvent( int id, wxEventType type, wxObject* obj,
11082 int row, int col, int x, int y, bool sel,
11083 bool control, bool shift, bool alt, bool meta )
11084 : wxNotifyEvent( type, id ),
11085 wxKeyboardState(control, shift, alt, meta)
11086 {
11087 Init(row, col, x, y, sel);
11088
11089 SetEventObject(obj);
11090 }
11091
11092 IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent, wxNotifyEvent )
11093
11094 wxGridSizeEvent::wxGridSizeEvent( int id, wxEventType type, wxObject* obj,
11095 int rowOrCol, int x, int y,
11096 bool control, bool shift, bool alt, bool meta )
11097 : wxNotifyEvent( type, id ),
11098 wxKeyboardState(control, shift, alt, meta)
11099 {
11100 Init(rowOrCol, x, y);
11101
11102 SetEventObject(obj);
11103 }
11104
11105
11106 IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent, wxNotifyEvent )
11107
11108 wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id, wxEventType type, wxObject* obj,
11109 const wxGridCellCoords& topLeft,
11110 const wxGridCellCoords& bottomRight,
11111 bool sel, bool control,
11112 bool shift, bool alt, bool meta )
11113 : wxNotifyEvent( type, id ),
11114 wxKeyboardState(control, shift, alt, meta)
11115 {
11116 Init(topLeft, bottomRight, sel);
11117
11118 SetEventObject(obj);
11119 }
11120
11121
11122 IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent, wxCommandEvent)
11123
11124 wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id, wxEventType type,
11125 wxObject* obj, int row,
11126 int col, wxControl* ctrl)
11127 : wxCommandEvent(type, id)
11128 {
11129 SetEventObject(obj);
11130 m_row = row;
11131 m_col = col;
11132 m_ctrl = ctrl;
11133 }
11134
11135 #endif // wxUSE_GRID