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