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