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