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