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