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