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