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