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