Make Home and End keys work as expected in wxGrid.
[wxWidgets.git] / src / generic / grid.cpp
1 ///////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/grid.cpp
3 // Purpose: wxGrid and related classes
4 // Author: Michael Bedward (based on code by Julian Smart, Robin Dunn)
5 // Modified by: Robin Dunn, Vadim Zeitlin, Santiago Palacios
6 // Created: 1/08/1999
7 // RCS-ID: $Id$
8 // Copyright: (c) Michael Bedward (mbedward@ozemail.com.au)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 /*
13 TODO:
14
15 - Replace use of wxINVERT with wxOverlay
16 - Make Begin/EndBatch() the same as the generic Freeze/Thaw()
17 - Review the column reordering code, it's a mess.
18 - Implement row reordering after dealing with the columns.
19 */
20
21 // For compilers that support precompilation, includes "wx/wx.h".
22 #include "wx/wxprec.h"
23
24 #ifdef __BORLANDC__
25 #pragma hdrstop
26 #endif
27
28 #if wxUSE_GRID
29
30 #include "wx/grid.h"
31
32 #ifndef WX_PRECOMP
33 #include "wx/utils.h"
34 #include "wx/dcclient.h"
35 #include "wx/settings.h"
36 #include "wx/log.h"
37 #include "wx/textctrl.h"
38 #include "wx/checkbox.h"
39 #include "wx/combobox.h"
40 #include "wx/valtext.h"
41 #include "wx/intl.h"
42 #include "wx/math.h"
43 #include "wx/listbox.h"
44 #endif
45
46 #include "wx/textfile.h"
47 #include "wx/spinctrl.h"
48 #include "wx/tokenzr.h"
49 #include "wx/renderer.h"
50 #include "wx/headerctrl.h"
51 #include "wx/hashset.h"
52
53 #include "wx/generic/gridsel.h"
54 #include "wx/generic/gridctrl.h"
55 #include "wx/generic/grideditors.h"
56 #include "wx/generic/private/grid.h"
57
58 const char wxGridNameStr[] = "grid";
59
60 #if defined(__WXMOTIF__)
61 #define WXUNUSED_MOTIF(identifier) WXUNUSED(identifier)
62 #else
63 #define WXUNUSED_MOTIF(identifier) identifier
64 #endif
65
66 #if defined(__WXGTK__)
67 #define WXUNUSED_GTK(identifier) WXUNUSED(identifier)
68 #else
69 #define WXUNUSED_GTK(identifier) identifier
70 #endif
71
72 // Required for wxIs... functions
73 #include <ctype.h>
74
75 WX_DECLARE_HASH_SET_WITH_DECL(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 wxDELETE(m_selection);
2104
2105 m_ownTable = false;
2106 m_numRows = 0;
2107 m_numCols = 0;
2108 checkSelection = true;
2109
2110 // kill row and column size arrays
2111 m_colWidths.Empty();
2112 m_colRights.Empty();
2113 m_rowHeights.Empty();
2114 m_rowBottoms.Empty();
2115 }
2116
2117 if (table)
2118 {
2119 m_numRows = table->GetNumberRows();
2120 m_numCols = table->GetNumberCols();
2121
2122 if ( m_useNativeHeader )
2123 GetGridColHeader()->SetColumnCount(m_numCols);
2124
2125 m_table = table;
2126 m_table->SetView( this );
2127 m_ownTable = takeOwnership;
2128 m_selection = new wxGridSelection( this, selmode );
2129 if (checkSelection)
2130 {
2131 // If the newly set table is smaller than the
2132 // original one current cell and selection regions
2133 // might be invalid,
2134 m_selectedBlockCorner = wxGridNoCellCoords;
2135 m_currentCellCoords =
2136 wxGridCellCoords(wxMin(m_numRows, m_currentCellCoords.GetRow()),
2137 wxMin(m_numCols, m_currentCellCoords.GetCol()));
2138 if (m_selectedBlockTopLeft.GetRow() >= m_numRows ||
2139 m_selectedBlockTopLeft.GetCol() >= m_numCols)
2140 {
2141 m_selectedBlockTopLeft = wxGridNoCellCoords;
2142 m_selectedBlockBottomRight = wxGridNoCellCoords;
2143 }
2144 else
2145 m_selectedBlockBottomRight =
2146 wxGridCellCoords(wxMin(m_numRows,
2147 m_selectedBlockBottomRight.GetRow()),
2148 wxMin(m_numCols,
2149 m_selectedBlockBottomRight.GetCol()));
2150 }
2151 CalcDimensions();
2152
2153 m_created = true;
2154 }
2155
2156 return m_created;
2157 }
2158
2159 void wxGrid::Init()
2160 {
2161 m_created = false;
2162
2163 m_cornerLabelWin = NULL;
2164 m_rowLabelWin = NULL;
2165 m_colWindow = NULL;
2166 m_gridWin = NULL;
2167
2168 m_table = NULL;
2169 m_ownTable = false;
2170
2171 m_selection = NULL;
2172 m_defaultCellAttr = NULL;
2173 m_typeRegistry = NULL;
2174 m_winCapture = NULL;
2175
2176 m_rowLabelWidth = WXGRID_DEFAULT_ROW_LABEL_WIDTH;
2177 m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT;
2178
2179 m_setFixedRows =
2180 m_setFixedCols = NULL;
2181
2182 // init attr cache
2183 m_attrCache.row = -1;
2184 m_attrCache.col = -1;
2185 m_attrCache.attr = NULL;
2186
2187 m_labelFont = GetFont();
2188 m_labelFont.SetWeight( wxBOLD );
2189
2190 m_rowLabelHorizAlign = wxALIGN_CENTRE;
2191 m_rowLabelVertAlign = wxALIGN_CENTRE;
2192
2193 m_colLabelHorizAlign = wxALIGN_CENTRE;
2194 m_colLabelVertAlign = wxALIGN_CENTRE;
2195 m_colLabelTextOrientation = wxHORIZONTAL;
2196
2197 m_defaultColWidth = WXGRID_DEFAULT_COL_WIDTH;
2198 m_defaultRowHeight = 0; // this will be initialized after creation
2199
2200 m_minAcceptableColWidth = WXGRID_MIN_COL_WIDTH;
2201 m_minAcceptableRowHeight = WXGRID_MIN_ROW_HEIGHT;
2202
2203 m_gridLineColour = wxColour( 192,192,192 );
2204 m_gridLinesEnabled = true;
2205 m_gridLinesClipHorz =
2206 m_gridLinesClipVert = true;
2207 m_cellHighlightColour = *wxBLACK;
2208 m_cellHighlightPenWidth = 2;
2209 m_cellHighlightROPenWidth = 1;
2210
2211 m_canDragColMove = false;
2212
2213 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
2214 m_winCapture = NULL;
2215 m_canDragRowSize = true;
2216 m_canDragColSize = true;
2217 m_canDragGridSize = true;
2218 m_canDragCell = false;
2219 m_dragLastPos = -1;
2220 m_dragRowOrCol = -1;
2221 m_isDragging = false;
2222 m_startDragPos = wxDefaultPosition;
2223
2224 m_sortCol = wxNOT_FOUND;
2225 m_sortIsAscending = true;
2226
2227 m_useNativeHeader =
2228 m_nativeColumnLabels = false;
2229
2230 m_waitForSlowClick = false;
2231
2232 m_rowResizeCursor = wxCursor( wxCURSOR_SIZENS );
2233 m_colResizeCursor = wxCursor( wxCURSOR_SIZEWE );
2234
2235 m_currentCellCoords = wxGridNoCellCoords;
2236
2237 m_selectedBlockTopLeft =
2238 m_selectedBlockBottomRight =
2239 m_selectedBlockCorner = wxGridNoCellCoords;
2240
2241 m_selectionBackground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
2242 m_selectionForeground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
2243
2244 m_editable = true; // default for whole grid
2245
2246 m_inOnKeyDown = false;
2247 m_batchCount = 0;
2248
2249 m_extraWidth =
2250 m_extraHeight = 0;
2251
2252 m_scrollLineX = GRID_SCROLL_LINE_X;
2253 m_scrollLineY = GRID_SCROLL_LINE_Y;
2254 }
2255
2256 // ----------------------------------------------------------------------------
2257 // the idea is to call these functions only when necessary because they create
2258 // quite big arrays which eat memory mostly unnecessary - in particular, if
2259 // default widths/heights are used for all rows/columns, we may not use these
2260 // arrays at all
2261 //
2262 // with some extra code, it should be possible to only store the widths/heights
2263 // different from default ones (resulting in space savings for huge grids) but
2264 // this is not done currently
2265 // ----------------------------------------------------------------------------
2266
2267 void wxGrid::InitRowHeights()
2268 {
2269 m_rowHeights.Empty();
2270 m_rowBottoms.Empty();
2271
2272 m_rowHeights.Alloc( m_numRows );
2273 m_rowBottoms.Alloc( m_numRows );
2274
2275 m_rowHeights.Add( m_defaultRowHeight, m_numRows );
2276
2277 int rowBottom = 0;
2278 for ( int i = 0; i < m_numRows; i++ )
2279 {
2280 rowBottom += m_defaultRowHeight;
2281 m_rowBottoms.Add( rowBottom );
2282 }
2283 }
2284
2285 void wxGrid::InitColWidths()
2286 {
2287 m_colWidths.Empty();
2288 m_colRights.Empty();
2289
2290 m_colWidths.Alloc( m_numCols );
2291 m_colRights.Alloc( m_numCols );
2292
2293 m_colWidths.Add( m_defaultColWidth, m_numCols );
2294
2295 for ( int i = 0; i < m_numCols; i++ )
2296 {
2297 int colRight = ( GetColPos( i ) + 1 ) * m_defaultColWidth;
2298 m_colRights.Add( colRight );
2299 }
2300 }
2301
2302 int wxGrid::GetColWidth(int col) const
2303 {
2304 return m_colWidths.IsEmpty() ? m_defaultColWidth : m_colWidths[col];
2305 }
2306
2307 int wxGrid::GetColLeft(int col) const
2308 {
2309 return m_colRights.IsEmpty() ? GetColPos( col ) * m_defaultColWidth
2310 : m_colRights[col] - m_colWidths[col];
2311 }
2312
2313 int wxGrid::GetColRight(int col) const
2314 {
2315 return m_colRights.IsEmpty() ? (GetColPos( col ) + 1) * m_defaultColWidth
2316 : m_colRights[col];
2317 }
2318
2319 int wxGrid::GetRowHeight(int row) const
2320 {
2321 return m_rowHeights.IsEmpty() ? m_defaultRowHeight : m_rowHeights[row];
2322 }
2323
2324 int wxGrid::GetRowTop(int row) const
2325 {
2326 return m_rowBottoms.IsEmpty() ? row * m_defaultRowHeight
2327 : m_rowBottoms[row] - m_rowHeights[row];
2328 }
2329
2330 int wxGrid::GetRowBottom(int row) const
2331 {
2332 return m_rowBottoms.IsEmpty() ? (row + 1) * m_defaultRowHeight
2333 : m_rowBottoms[row];
2334 }
2335
2336 void wxGrid::CalcDimensions()
2337 {
2338 // compute the size of the scrollable area
2339 int w = m_numCols > 0 ? GetColRight(GetColAt(m_numCols - 1)) : 0;
2340 int h = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
2341
2342 w += m_extraWidth;
2343 h += m_extraHeight;
2344
2345 // take into account editor if shown
2346 if ( IsCellEditControlShown() )
2347 {
2348 int w2, h2;
2349 int r = m_currentCellCoords.GetRow();
2350 int c = m_currentCellCoords.GetCol();
2351 int x = GetColLeft(c);
2352 int y = GetRowTop(r);
2353
2354 // how big is the editor
2355 wxGridCellAttr* attr = GetCellAttr(r, c);
2356 wxGridCellEditor* editor = attr->GetEditor(this, r, c);
2357 editor->GetControl()->GetSize(&w2, &h2);
2358 w2 += x;
2359 h2 += y;
2360 if ( w2 > w )
2361 w = w2;
2362 if ( h2 > h )
2363 h = h2;
2364 editor->DecRef();
2365 attr->DecRef();
2366 }
2367
2368 // preserve (more or less) the previous position
2369 int x, y;
2370 GetViewStart( &x, &y );
2371
2372 // ensure the position is valid for the new scroll ranges
2373 if ( x >= w )
2374 x = wxMax( w - 1, 0 );
2375 if ( y >= h )
2376 y = wxMax( h - 1, 0 );
2377
2378 // update the virtual size and refresh the scrollbars to reflect it
2379 m_gridWin->SetVirtualSize(w, h);
2380 Scroll(x, y);
2381 AdjustScrollbars();
2382
2383 // if our OnSize() hadn't been called (it would if we have scrollbars), we
2384 // still must reposition the children
2385 CalcWindowSizes();
2386 }
2387
2388 wxSize wxGrid::GetSizeAvailableForScrollTarget(const wxSize& size)
2389 {
2390 wxSize sizeGridWin(size);
2391 sizeGridWin.x -= m_rowLabelWidth;
2392 sizeGridWin.y -= m_colLabelHeight;
2393
2394 return sizeGridWin;
2395 }
2396
2397 void wxGrid::CalcWindowSizes()
2398 {
2399 // escape if the window is has not been fully created yet
2400
2401 if ( m_cornerLabelWin == NULL )
2402 return;
2403
2404 int cw, ch;
2405 GetClientSize( &cw, &ch );
2406
2407 // the grid may be too small to have enough space for the labels yet, don't
2408 // size the windows to negative sizes in this case
2409 int gw = cw - m_rowLabelWidth;
2410 int gh = ch - m_colLabelHeight;
2411 if (gw < 0)
2412 gw = 0;
2413 if (gh < 0)
2414 gh = 0;
2415
2416 if ( m_cornerLabelWin && m_cornerLabelWin->IsShown() )
2417 m_cornerLabelWin->SetSize( 0, 0, m_rowLabelWidth, m_colLabelHeight );
2418
2419 if ( m_colWindow && m_colWindow->IsShown() )
2420 m_colWindow->SetSize( m_rowLabelWidth, 0, gw, m_colLabelHeight );
2421
2422 if ( m_rowLabelWin && m_rowLabelWin->IsShown() )
2423 m_rowLabelWin->SetSize( 0, m_colLabelHeight, m_rowLabelWidth, gh );
2424
2425 if ( m_gridWin && m_gridWin->IsShown() )
2426 m_gridWin->SetSize( m_rowLabelWidth, m_colLabelHeight, gw, gh );
2427 }
2428
2429 // this is called when the grid table sends a message
2430 // to indicate that it has been redimensioned
2431 //
2432 bool wxGrid::Redimension( wxGridTableMessage& msg )
2433 {
2434 int i;
2435 bool result = false;
2436
2437 // Clear the attribute cache as the attribute might refer to a different
2438 // cell than stored in the cache after adding/removing rows/columns.
2439 ClearAttrCache();
2440
2441 // By the same reasoning, the editor should be dismissed if columns are
2442 // added or removed. And for consistency, it should IMHO always be
2443 // removed, not only if the cell "underneath" it actually changes.
2444 // For now, I intentionally do not save the editor's content as the
2445 // cell it might want to save that stuff to might no longer exist.
2446 HideCellEditControl();
2447
2448 switch ( msg.GetId() )
2449 {
2450 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
2451 {
2452 size_t pos = msg.GetCommandInt();
2453 int numRows = msg.GetCommandInt2();
2454
2455 m_numRows += numRows;
2456
2457 if ( !m_rowHeights.IsEmpty() )
2458 {
2459 m_rowHeights.Insert( m_defaultRowHeight, pos, numRows );
2460 m_rowBottoms.Insert( 0, pos, numRows );
2461
2462 int bottom = 0;
2463 if ( pos > 0 )
2464 bottom = m_rowBottoms[pos - 1];
2465
2466 for ( i = pos; i < m_numRows; i++ )
2467 {
2468 bottom += m_rowHeights[i];
2469 m_rowBottoms[i] = bottom;
2470 }
2471 }
2472
2473 if ( m_currentCellCoords == wxGridNoCellCoords )
2474 {
2475 // if we have just inserted cols into an empty grid the current
2476 // cell will be undefined...
2477 //
2478 SetCurrentCell( 0, 0 );
2479 }
2480
2481 if ( m_selection )
2482 m_selection->UpdateRows( pos, numRows );
2483 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
2484 if (attrProvider)
2485 attrProvider->UpdateAttrRows( pos, numRows );
2486
2487 if ( !GetBatchCount() )
2488 {
2489 CalcDimensions();
2490 m_rowLabelWin->Refresh();
2491 }
2492 }
2493 result = true;
2494 break;
2495
2496 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
2497 {
2498 int numRows = msg.GetCommandInt();
2499 int oldNumRows = m_numRows;
2500 m_numRows += numRows;
2501
2502 if ( !m_rowHeights.IsEmpty() )
2503 {
2504 m_rowHeights.Add( m_defaultRowHeight, numRows );
2505 m_rowBottoms.Add( 0, numRows );
2506
2507 int bottom = 0;
2508 if ( oldNumRows > 0 )
2509 bottom = m_rowBottoms[oldNumRows - 1];
2510
2511 for ( i = oldNumRows; i < m_numRows; i++ )
2512 {
2513 bottom += m_rowHeights[i];
2514 m_rowBottoms[i] = bottom;
2515 }
2516 }
2517
2518 if ( m_currentCellCoords == wxGridNoCellCoords )
2519 {
2520 // if we have just inserted cols into an empty grid the current
2521 // cell will be undefined...
2522 //
2523 SetCurrentCell( 0, 0 );
2524 }
2525
2526 if ( !GetBatchCount() )
2527 {
2528 CalcDimensions();
2529 m_rowLabelWin->Refresh();
2530 }
2531 }
2532 result = true;
2533 break;
2534
2535 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
2536 {
2537 size_t pos = msg.GetCommandInt();
2538 int numRows = msg.GetCommandInt2();
2539 m_numRows -= numRows;
2540
2541 if ( !m_rowHeights.IsEmpty() )
2542 {
2543 m_rowHeights.RemoveAt( pos, numRows );
2544 m_rowBottoms.RemoveAt( pos, numRows );
2545
2546 int h = 0;
2547 for ( i = 0; i < m_numRows; i++ )
2548 {
2549 h += m_rowHeights[i];
2550 m_rowBottoms[i] = h;
2551 }
2552 }
2553
2554 if ( !m_numRows )
2555 {
2556 m_currentCellCoords = wxGridNoCellCoords;
2557 }
2558 else
2559 {
2560 if ( m_currentCellCoords.GetRow() >= m_numRows )
2561 m_currentCellCoords.Set( 0, 0 );
2562 }
2563
2564 if ( m_selection )
2565 m_selection->UpdateRows( pos, -((int)numRows) );
2566 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
2567 if (attrProvider)
2568 {
2569 attrProvider->UpdateAttrRows( pos, -((int)numRows) );
2570
2571 // ifdef'd out following patch from Paul Gammans
2572 #if 0
2573 // No need to touch column attributes, unless we
2574 // removed _all_ rows, in this case, we remove
2575 // all column attributes.
2576 // I hate to do this here, but the
2577 // needed data is not available inside UpdateAttrRows.
2578 if ( !GetNumberRows() )
2579 attrProvider->UpdateAttrCols( 0, -GetNumberCols() );
2580 #endif
2581 }
2582
2583 if ( !GetBatchCount() )
2584 {
2585 CalcDimensions();
2586 m_rowLabelWin->Refresh();
2587 }
2588 }
2589 result = true;
2590 break;
2591
2592 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
2593 {
2594 size_t pos = msg.GetCommandInt();
2595 int numCols = msg.GetCommandInt2();
2596 m_numCols += numCols;
2597
2598 if ( m_useNativeHeader )
2599 GetGridColHeader()->SetColumnCount(m_numCols);
2600
2601 if ( !m_colAt.IsEmpty() )
2602 {
2603 //Shift the column IDs
2604 int i;
2605 for ( i = 0; i < m_numCols - numCols; i++ )
2606 {
2607 if ( m_colAt[i] >= (int)pos )
2608 m_colAt[i] += numCols;
2609 }
2610
2611 m_colAt.Insert( pos, pos, numCols );
2612
2613 //Set the new columns' positions
2614 for ( i = pos + 1; i < (int)pos + numCols; i++ )
2615 {
2616 m_colAt[i] = i;
2617 }
2618 }
2619
2620 if ( !m_colWidths.IsEmpty() )
2621 {
2622 m_colWidths.Insert( m_defaultColWidth, pos, numCols );
2623 m_colRights.Insert( 0, pos, numCols );
2624
2625 int right = 0;
2626 if ( pos > 0 )
2627 right = m_colRights[GetColAt( pos - 1 )];
2628
2629 int colPos;
2630 for ( colPos = pos; colPos < m_numCols; colPos++ )
2631 {
2632 i = GetColAt( colPos );
2633
2634 right += m_colWidths[i];
2635 m_colRights[i] = right;
2636 }
2637 }
2638
2639 if ( m_currentCellCoords == wxGridNoCellCoords )
2640 {
2641 // if we have just inserted cols into an empty grid the current
2642 // cell will be undefined...
2643 //
2644 SetCurrentCell( 0, 0 );
2645 }
2646
2647 if ( m_selection )
2648 m_selection->UpdateCols( pos, numCols );
2649 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
2650 if (attrProvider)
2651 attrProvider->UpdateAttrCols( pos, numCols );
2652 if ( !GetBatchCount() )
2653 {
2654 CalcDimensions();
2655 m_colWindow->Refresh();
2656 }
2657 }
2658 result = true;
2659 break;
2660
2661 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
2662 {
2663 int numCols = msg.GetCommandInt();
2664 int oldNumCols = m_numCols;
2665 m_numCols += numCols;
2666 if ( m_useNativeHeader )
2667 GetGridColHeader()->SetColumnCount(m_numCols);
2668
2669 if ( !m_colAt.IsEmpty() )
2670 {
2671 m_colAt.Add( 0, numCols );
2672
2673 //Set the new columns' positions
2674 int i;
2675 for ( i = oldNumCols; i < m_numCols; i++ )
2676 {
2677 m_colAt[i] = i;
2678 }
2679 }
2680
2681 if ( !m_colWidths.IsEmpty() )
2682 {
2683 m_colWidths.Add( m_defaultColWidth, numCols );
2684 m_colRights.Add( 0, numCols );
2685
2686 int right = 0;
2687 if ( oldNumCols > 0 )
2688 right = m_colRights[GetColAt( oldNumCols - 1 )];
2689
2690 int colPos;
2691 for ( colPos = oldNumCols; colPos < m_numCols; colPos++ )
2692 {
2693 i = GetColAt( colPos );
2694
2695 right += m_colWidths[i];
2696 m_colRights[i] = right;
2697 }
2698 }
2699
2700 if ( m_currentCellCoords == wxGridNoCellCoords )
2701 {
2702 // if we have just inserted cols into an empty grid the current
2703 // cell will be undefined...
2704 //
2705 SetCurrentCell( 0, 0 );
2706 }
2707 if ( !GetBatchCount() )
2708 {
2709 CalcDimensions();
2710 m_colWindow->Refresh();
2711 }
2712 }
2713 result = true;
2714 break;
2715
2716 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
2717 {
2718 size_t pos = msg.GetCommandInt();
2719 int numCols = msg.GetCommandInt2();
2720 m_numCols -= numCols;
2721 if ( m_useNativeHeader )
2722 GetGridColHeader()->SetColumnCount(m_numCols);
2723
2724 if ( !m_colAt.IsEmpty() )
2725 {
2726 int colID = GetColAt( pos );
2727
2728 m_colAt.RemoveAt( pos, numCols );
2729
2730 //Shift the column IDs
2731 int colPos;
2732 for ( colPos = 0; colPos < m_numCols; colPos++ )
2733 {
2734 if ( m_colAt[colPos] > colID )
2735 m_colAt[colPos] -= numCols;
2736 }
2737 }
2738
2739 if ( !m_colWidths.IsEmpty() )
2740 {
2741 m_colWidths.RemoveAt( pos, numCols );
2742 m_colRights.RemoveAt( pos, numCols );
2743
2744 int w = 0;
2745 int colPos;
2746 for ( colPos = 0; colPos < m_numCols; colPos++ )
2747 {
2748 i = GetColAt( colPos );
2749
2750 w += m_colWidths[i];
2751 m_colRights[i] = w;
2752 }
2753 }
2754
2755 if ( !m_numCols )
2756 {
2757 m_currentCellCoords = wxGridNoCellCoords;
2758 }
2759 else
2760 {
2761 if ( m_currentCellCoords.GetCol() >= m_numCols )
2762 m_currentCellCoords.Set( 0, 0 );
2763 }
2764
2765 if ( m_selection )
2766 m_selection->UpdateCols( pos, -((int)numCols) );
2767 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
2768 if (attrProvider)
2769 {
2770 attrProvider->UpdateAttrCols( pos, -((int)numCols) );
2771
2772 // ifdef'd out following patch from Paul Gammans
2773 #if 0
2774 // No need to touch row attributes, unless we
2775 // removed _all_ columns, in this case, we remove
2776 // all row attributes.
2777 // I hate to do this here, but the
2778 // needed data is not available inside UpdateAttrCols.
2779 if ( !GetNumberCols() )
2780 attrProvider->UpdateAttrRows( 0, -GetNumberRows() );
2781 #endif
2782 }
2783
2784 if ( !GetBatchCount() )
2785 {
2786 CalcDimensions();
2787 m_colWindow->Refresh();
2788 }
2789 }
2790 result = true;
2791 break;
2792 }
2793
2794 if (result && !GetBatchCount() )
2795 m_gridWin->Refresh();
2796
2797 return result;
2798 }
2799
2800 wxArrayInt wxGrid::CalcRowLabelsExposed( const wxRegion& reg ) const
2801 {
2802 wxRegionIterator iter( reg );
2803 wxRect r;
2804
2805 wxArrayInt rowlabels;
2806
2807 int top, bottom;
2808 while ( iter )
2809 {
2810 r = iter.GetRect();
2811
2812 // TODO: remove this when we can...
2813 // There is a bug in wxMotif that gives garbage update
2814 // rectangles if you jump-scroll a long way by clicking the
2815 // scrollbar with middle button. This is a work-around
2816 //
2817 #if defined(__WXMOTIF__)
2818 int cw, ch;
2819 m_gridWin->GetClientSize( &cw, &ch );
2820 if ( r.GetTop() > ch )
2821 r.SetTop( 0 );
2822 r.SetBottom( wxMin( r.GetBottom(), ch ) );
2823 #endif
2824
2825 // logical bounds of update region
2826 //
2827 int dummy;
2828 CalcUnscrolledPosition( 0, r.GetTop(), &dummy, &top );
2829 CalcUnscrolledPosition( 0, r.GetBottom(), &dummy, &bottom );
2830
2831 // find the row labels within these bounds
2832 //
2833 int row;
2834 for ( row = internalYToRow(top); row < m_numRows; row++ )
2835 {
2836 if ( GetRowBottom(row) < top )
2837 continue;
2838
2839 if ( GetRowTop(row) > bottom )
2840 break;
2841
2842 rowlabels.Add( row );
2843 }
2844
2845 ++iter;
2846 }
2847
2848 return rowlabels;
2849 }
2850
2851 wxArrayInt wxGrid::CalcColLabelsExposed( const wxRegion& reg ) const
2852 {
2853 wxRegionIterator iter( reg );
2854 wxRect r;
2855
2856 wxArrayInt colLabels;
2857
2858 int left, right;
2859 while ( iter )
2860 {
2861 r = iter.GetRect();
2862
2863 // TODO: remove this when we can...
2864 // There is a bug in wxMotif that gives garbage update
2865 // rectangles if you jump-scroll a long way by clicking the
2866 // scrollbar with middle button. This is a work-around
2867 //
2868 #if defined(__WXMOTIF__)
2869 int cw, ch;
2870 m_gridWin->GetClientSize( &cw, &ch );
2871 if ( r.GetLeft() > cw )
2872 r.SetLeft( 0 );
2873 r.SetRight( wxMin( r.GetRight(), cw ) );
2874 #endif
2875
2876 // logical bounds of update region
2877 //
2878 int dummy;
2879 CalcUnscrolledPosition( r.GetLeft(), 0, &left, &dummy );
2880 CalcUnscrolledPosition( r.GetRight(), 0, &right, &dummy );
2881
2882 // find the cells within these bounds
2883 //
2884 int col;
2885 int colPos;
2886 for ( colPos = GetColPos( internalXToCol(left) ); colPos < m_numCols; colPos++ )
2887 {
2888 col = GetColAt( colPos );
2889
2890 if ( GetColRight(col) < left )
2891 continue;
2892
2893 if ( GetColLeft(col) > right )
2894 break;
2895
2896 colLabels.Add( col );
2897 }
2898
2899 ++iter;
2900 }
2901
2902 return colLabels;
2903 }
2904
2905 wxGridCellCoordsArray wxGrid::CalcCellsExposed( const wxRegion& reg ) const
2906 {
2907 wxRegionIterator iter( reg );
2908 wxRect r;
2909
2910 wxGridCellCoordsArray cellsExposed;
2911
2912 int left, top, right, bottom;
2913 while ( iter )
2914 {
2915 r = iter.GetRect();
2916
2917 // TODO: remove this when we can...
2918 // There is a bug in wxMotif that gives garbage update
2919 // rectangles if you jump-scroll a long way by clicking the
2920 // scrollbar with middle button. This is a work-around
2921 //
2922 #if defined(__WXMOTIF__)
2923 int cw, ch;
2924 m_gridWin->GetClientSize( &cw, &ch );
2925 if ( r.GetTop() > ch ) r.SetTop( 0 );
2926 if ( r.GetLeft() > cw ) r.SetLeft( 0 );
2927 r.SetRight( wxMin( r.GetRight(), cw ) );
2928 r.SetBottom( wxMin( r.GetBottom(), ch ) );
2929 #endif
2930
2931 // logical bounds of update region
2932 //
2933 CalcUnscrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
2934 CalcUnscrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
2935
2936 // find the cells within these bounds
2937 wxArrayInt cols;
2938 for ( int row = internalYToRow(top); row < m_numRows; row++ )
2939 {
2940 if ( GetRowBottom(row) <= top )
2941 continue;
2942
2943 if ( GetRowTop(row) > bottom )
2944 break;
2945
2946 // add all dirty cells in this row: notice that the columns which
2947 // are dirty don't depend on the row so we compute them only once
2948 // for the first dirty row and then reuse for all the next ones
2949 if ( cols.empty() )
2950 {
2951 // do determine the dirty columns
2952 for ( int pos = XToPos(left); pos <= XToPos(right); pos++ )
2953 cols.push_back(GetColAt(pos));
2954
2955 // if there are no dirty columns at all, nothing to do
2956 if ( cols.empty() )
2957 break;
2958 }
2959
2960 const size_t count = cols.size();
2961 for ( size_t n = 0; n < count; n++ )
2962 cellsExposed.Add(wxGridCellCoords(row, cols[n]));
2963 }
2964
2965 ++iter;
2966 }
2967
2968 return cellsExposed;
2969 }
2970
2971
2972 void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event )
2973 {
2974 int x, y, row;
2975 wxPoint pos( event.GetPosition() );
2976 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
2977
2978 if ( event.Dragging() )
2979 {
2980 if (!m_isDragging)
2981 {
2982 m_isDragging = true;
2983 m_rowLabelWin->CaptureMouse();
2984 }
2985
2986 if ( event.LeftIsDown() )
2987 {
2988 switch ( m_cursorMode )
2989 {
2990 case WXGRID_CURSOR_RESIZE_ROW:
2991 {
2992 int cw, ch, left, dummy;
2993 m_gridWin->GetClientSize( &cw, &ch );
2994 CalcUnscrolledPosition( 0, 0, &left, &dummy );
2995
2996 wxClientDC dc( m_gridWin );
2997 PrepareDC( dc );
2998 y = wxMax( y,
2999 GetRowTop(m_dragRowOrCol) +
3000 GetRowMinimalHeight(m_dragRowOrCol) );
3001 dc.SetLogicalFunction(wxINVERT);
3002 if ( m_dragLastPos >= 0 )
3003 {
3004 dc.DrawLine( left, m_dragLastPos, left+cw, m_dragLastPos );
3005 }
3006 dc.DrawLine( left, y, left+cw, y );
3007 m_dragLastPos = y;
3008 }
3009 break;
3010
3011 case WXGRID_CURSOR_SELECT_ROW:
3012 {
3013 if ( (row = YToRow( y )) >= 0 )
3014 {
3015 if ( m_selection )
3016 m_selection->SelectRow(row, event);
3017 }
3018 }
3019 break;
3020
3021 // default label to suppress warnings about "enumeration value
3022 // 'xxx' not handled in switch
3023 default:
3024 break;
3025 }
3026 }
3027 return;
3028 }
3029
3030 if ( m_isDragging && (event.Entering() || event.Leaving()) )
3031 return;
3032
3033 if (m_isDragging)
3034 {
3035 if (m_rowLabelWin->HasCapture())
3036 m_rowLabelWin->ReleaseMouse();
3037 m_isDragging = false;
3038 }
3039
3040 // ------------ Entering or leaving the window
3041 //
3042 if ( event.Entering() || event.Leaving() )
3043 {
3044 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
3045 }
3046
3047 // ------------ Left button pressed
3048 //
3049 else if ( event.LeftDown() )
3050 {
3051 row = YToEdgeOfRow(y);
3052 if ( row != wxNOT_FOUND && CanDragRowSize(row) )
3053 {
3054 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin);
3055 }
3056 else // not a request to start resizing
3057 {
3058 row = YToRow(y);
3059 if ( row >= 0 &&
3060 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, row, -1, event ) )
3061 {
3062 if ( !event.ShiftDown() && !event.CmdDown() )
3063 ClearSelection();
3064 if ( m_selection )
3065 {
3066 if ( event.ShiftDown() )
3067 {
3068 m_selection->SelectBlock
3069 (
3070 m_currentCellCoords.GetRow(), 0,
3071 row, GetNumberCols() - 1,
3072 event
3073 );
3074 }
3075 else
3076 {
3077 m_selection->SelectRow(row, event);
3078 }
3079 }
3080
3081 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW, m_rowLabelWin);
3082 }
3083 }
3084 }
3085
3086 // ------------ Left double click
3087 //
3088 else if (event.LeftDClick() )
3089 {
3090 row = YToEdgeOfRow(y);
3091 if ( row != wxNOT_FOUND && CanDragRowSize(row) )
3092 {
3093 // adjust row height depending on label text
3094 //
3095 // TODO: generate RESIZING event, see #10754
3096 AutoSizeRowLabelSize( row );
3097
3098 SendGridSizeEvent(wxEVT_GRID_ROW_SIZE, row, -1, event);
3099
3100 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
3101 m_dragLastPos = -1;
3102 }
3103 else // not on row separator or it's not resizeable
3104 {
3105 row = YToRow(y);
3106 if ( row >=0 &&
3107 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, row, -1, event ) )
3108 {
3109 // no default action at the moment
3110 }
3111 }
3112 }
3113
3114 // ------------ Left button released
3115 //
3116 else if ( event.LeftUp() )
3117 {
3118 if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
3119 DoEndDragResizeRow(event);
3120
3121 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
3122 m_dragLastPos = -1;
3123 }
3124
3125 // ------------ Right button down
3126 //
3127 else if ( event.RightDown() )
3128 {
3129 row = YToRow(y);
3130 if ( row >=0 &&
3131 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, row, -1, event ) )
3132 {
3133 // no default action at the moment
3134 }
3135 }
3136
3137 // ------------ Right double click
3138 //
3139 else if ( event.RightDClick() )
3140 {
3141 row = YToRow(y);
3142 if ( row >= 0 &&
3143 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, row, -1, event ) )
3144 {
3145 // no default action at the moment
3146 }
3147 }
3148
3149 // ------------ No buttons down and mouse moving
3150 //
3151 else if ( event.Moving() )
3152 {
3153 m_dragRowOrCol = YToEdgeOfRow( y );
3154 if ( m_dragRowOrCol != wxNOT_FOUND )
3155 {
3156 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
3157 {
3158 if ( CanDragRowSize(m_dragRowOrCol) )
3159 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin, false);
3160 }
3161 }
3162 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
3163 {
3164 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin, false);
3165 }
3166 }
3167 }
3168
3169 void wxGrid::UpdateColumnSortingIndicator(int col)
3170 {
3171 wxCHECK_RET( col != wxNOT_FOUND, "invalid column index" );
3172
3173 if ( m_useNativeHeader )
3174 GetGridColHeader()->UpdateColumn(col);
3175 else if ( m_nativeColumnLabels )
3176 m_colWindow->Refresh();
3177 //else: sorting indicator display not yet implemented in grid version
3178 }
3179
3180 void wxGrid::SetSortingColumn(int col, bool ascending)
3181 {
3182 if ( col == m_sortCol )
3183 {
3184 // we are already using this column for sorting (or not sorting at all)
3185 // but we might still change the sorting order, check for it
3186 if ( m_sortCol != wxNOT_FOUND && ascending != m_sortIsAscending )
3187 {
3188 m_sortIsAscending = ascending;
3189
3190 UpdateColumnSortingIndicator(m_sortCol);
3191 }
3192 }
3193 else // we're changing the column used for sorting
3194 {
3195 const int sortColOld = m_sortCol;
3196
3197 // change it before updating the column as we want GetSortingColumn()
3198 // to return the correct new value
3199 m_sortCol = col;
3200
3201 if ( sortColOld != wxNOT_FOUND )
3202 UpdateColumnSortingIndicator(sortColOld);
3203
3204 if ( m_sortCol != wxNOT_FOUND )
3205 {
3206 m_sortIsAscending = ascending;
3207 UpdateColumnSortingIndicator(m_sortCol);
3208 }
3209 }
3210 }
3211
3212 void wxGrid::DoColHeaderClick(int col)
3213 {
3214 // we consider that the grid was resorted if this event is processed and
3215 // not vetoed
3216 if ( SendEvent(wxEVT_GRID_COL_SORT, -1, col) == 1 )
3217 {
3218 SetSortingColumn(col, IsSortingBy(col) ? !m_sortIsAscending : true);
3219 Refresh();
3220 }
3221 }
3222
3223 void wxGrid::DoStartResizeCol(int col)
3224 {
3225 m_dragRowOrCol = col;
3226 m_dragLastPos = -1;
3227 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol));
3228 }
3229
3230 void wxGrid::DoUpdateResizeCol(int x)
3231 {
3232 int cw, ch, dummy, top;
3233 m_gridWin->GetClientSize( &cw, &ch );
3234 CalcUnscrolledPosition( 0, 0, &dummy, &top );
3235
3236 wxClientDC dc( m_gridWin );
3237 PrepareDC( dc );
3238
3239 x = wxMax( x, GetColLeft(m_dragRowOrCol) + GetColMinimalWidth(m_dragRowOrCol));
3240 dc.SetLogicalFunction(wxINVERT);
3241 if ( m_dragLastPos >= 0 )
3242 {
3243 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
3244 }
3245 dc.DrawLine( x, top, x, top + ch );
3246 m_dragLastPos = x;
3247 }
3248
3249 void wxGrid::DoUpdateResizeColWidth(int w)
3250 {
3251 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol) + w);
3252 }
3253
3254 void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event )
3255 {
3256 int x, y;
3257 wxPoint pos( event.GetPosition() );
3258 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
3259
3260 int col = XToCol(x);
3261 if ( event.Dragging() )
3262 {
3263 if (!m_isDragging)
3264 {
3265 m_isDragging = true;
3266 GetColLabelWindow()->CaptureMouse();
3267
3268 if ( m_cursorMode == WXGRID_CURSOR_MOVE_COL && col != -1 )
3269 DoStartMoveCol(col);
3270 }
3271
3272 if ( event.LeftIsDown() )
3273 {
3274 switch ( m_cursorMode )
3275 {
3276 case WXGRID_CURSOR_RESIZE_COL:
3277 DoUpdateResizeCol(x);
3278 break;
3279
3280 case WXGRID_CURSOR_SELECT_COL:
3281 {
3282 if ( col != -1 )
3283 {
3284 if ( m_selection )
3285 m_selection->SelectCol(col, event);
3286 }
3287 }
3288 break;
3289
3290 case WXGRID_CURSOR_MOVE_COL:
3291 {
3292 int posNew = XToPos(x);
3293 int colNew = GetColAt(posNew);
3294
3295 // determine the position of the drop marker
3296 int markerX;
3297 if ( x >= GetColLeft(colNew) + (GetColWidth(colNew) / 2) )
3298 markerX = GetColRight(colNew);
3299 else
3300 markerX = GetColLeft(colNew);
3301
3302 if ( markerX != m_dragLastPos )
3303 {
3304 wxClientDC dc( GetColLabelWindow() );
3305 DoPrepareDC(dc);
3306
3307 int cw, ch;
3308 GetColLabelWindow()->GetClientSize( &cw, &ch );
3309
3310 markerX++;
3311
3312 //Clean up the last indicator
3313 if ( m_dragLastPos >= 0 )
3314 {
3315 wxPen pen( GetColLabelWindow()->GetBackgroundColour(), 2 );
3316 dc.SetPen(pen);
3317 dc.DrawLine( m_dragLastPos + 1, 0, m_dragLastPos + 1, ch );
3318 dc.SetPen(wxNullPen);
3319
3320 if ( XToCol( m_dragLastPos ) != -1 )
3321 DrawColLabel( dc, XToCol( m_dragLastPos ) );
3322 }
3323
3324 const wxColour *color;
3325 //Moving to the same place? Don't draw a marker
3326 if ( colNew == m_dragRowOrCol )
3327 color = wxLIGHT_GREY;
3328 else
3329 color = wxBLUE;
3330
3331 //Draw the marker
3332 wxPen pen( *color, 2 );
3333 dc.SetPen(pen);
3334
3335 dc.DrawLine( markerX, 0, markerX, ch );
3336
3337 dc.SetPen(wxNullPen);
3338
3339 m_dragLastPos = markerX - 1;
3340 }
3341 }
3342 break;
3343
3344 // default label to suppress warnings about "enumeration value
3345 // 'xxx' not handled in switch
3346 default:
3347 break;
3348 }
3349 }
3350 return;
3351 }
3352
3353 if ( m_isDragging && (event.Entering() || event.Leaving()) )
3354 return;
3355
3356 if (m_isDragging)
3357 {
3358 if (GetColLabelWindow()->HasCapture())
3359 GetColLabelWindow()->ReleaseMouse();
3360 m_isDragging = false;
3361 }
3362
3363 // ------------ Entering or leaving the window
3364 //
3365 if ( event.Entering() || event.Leaving() )
3366 {
3367 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
3368 }
3369
3370 // ------------ Left button pressed
3371 //
3372 else if ( event.LeftDown() )
3373 {
3374 int col = XToEdgeOfCol(x);
3375 if ( col != wxNOT_FOUND && CanDragColSize(col) )
3376 {
3377 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow());
3378 }
3379 else // not a request to start resizing
3380 {
3381 col = XToCol(x);
3382 if ( col >= 0 &&
3383 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, col, event ) )
3384 {
3385 if ( m_canDragColMove )
3386 {
3387 //Show button as pressed
3388 wxClientDC dc( GetColLabelWindow() );
3389 int colLeft = GetColLeft( col );
3390 int colRight = GetColRight( col ) - 1;
3391 dc.SetPen( wxPen( GetColLabelWindow()->GetBackgroundColour(), 1 ) );
3392 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight-1 );
3393 dc.DrawLine( colLeft, 1, colRight, 1 );
3394
3395 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL, GetColLabelWindow());
3396 }
3397 else
3398 {
3399 if ( !event.ShiftDown() && !event.CmdDown() )
3400 ClearSelection();
3401 if ( m_selection )
3402 {
3403 if ( event.ShiftDown() )
3404 {
3405 m_selection->SelectBlock
3406 (
3407 0, m_currentCellCoords.GetCol(),
3408 GetNumberRows() - 1, col,
3409 event
3410 );
3411 }
3412 else
3413 {
3414 m_selection->SelectCol(col, event);
3415 }
3416 }
3417
3418 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL, GetColLabelWindow());
3419 }
3420 }
3421 }
3422 }
3423
3424 // ------------ Left double click
3425 //
3426 if ( event.LeftDClick() )
3427 {
3428 const int colEdge = XToEdgeOfCol(x);
3429 if ( colEdge == -1 )
3430 {
3431 if ( col >= 0 &&
3432 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, col, event ) )
3433 {
3434 // no default action at the moment
3435 }
3436 }
3437 else
3438 {
3439 // adjust column width depending on label text
3440 //
3441 // TODO: generate RESIZING event, see #10754
3442 AutoSizeColLabelSize( colEdge );
3443
3444 SendGridSizeEvent(wxEVT_GRID_COL_SIZE, -1, colEdge, event);
3445
3446 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
3447 m_dragLastPos = -1;
3448 }
3449 }
3450
3451 // ------------ Left button released
3452 //
3453 else if ( event.LeftUp() )
3454 {
3455 switch ( m_cursorMode )
3456 {
3457 case WXGRID_CURSOR_RESIZE_COL:
3458 DoEndDragResizeCol(event);
3459 break;
3460
3461 case WXGRID_CURSOR_MOVE_COL:
3462 if ( m_dragLastPos == -1 || col == m_dragRowOrCol )
3463 {
3464 // the column didn't actually move anywhere
3465 if ( col != -1 )
3466 DoColHeaderClick(col);
3467 m_colWindow->Refresh(); // "unpress" the column
3468 }
3469 else
3470 {
3471 // get the position of the column we're over
3472 int pos = XToPos(x);
3473
3474 // we may need to adjust the drop position but don't bother
3475 // checking for it if we can't anyhow
3476 if ( pos > 1 )
3477 {
3478 // also find the index of the column we're over: notice
3479 // that the existing "col" variable may be invalid but
3480 // we need a valid one here
3481 const int colValid = GetColAt(pos);
3482
3483 // if we're on the "near" (usually left but right in
3484 // RTL case) part of the column, the actual position we
3485 // should be placed in is actually the one before it
3486 bool onNearPart;
3487 const int middle = GetColLeft(colValid) +
3488 GetColWidth(colValid)/2;
3489 if ( GetLayoutDirection() == wxLayout_LeftToRight )
3490 onNearPart = (x <= middle);
3491 else // wxLayout_RightToLeft
3492 onNearPart = (x > middle);
3493
3494 if ( onNearPart )
3495 pos--;
3496 }
3497
3498 DoEndMoveCol(pos);
3499 }
3500 break;
3501
3502 case WXGRID_CURSOR_SELECT_COL:
3503 case WXGRID_CURSOR_SELECT_CELL:
3504 case WXGRID_CURSOR_RESIZE_ROW:
3505 case WXGRID_CURSOR_SELECT_ROW:
3506 if ( col != -1 )
3507 DoColHeaderClick(col);
3508 break;
3509 }
3510
3511 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow());
3512 m_dragLastPos = -1;
3513 }
3514
3515 // ------------ Right button down
3516 //
3517 else if ( event.RightDown() )
3518 {
3519 if ( col >= 0 &&
3520 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, col, event ) )
3521 {
3522 // no default action at the moment
3523 }
3524 }
3525
3526 // ------------ Right double click
3527 //
3528 else if ( event.RightDClick() )
3529 {
3530 if ( col >= 0 &&
3531 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, col, event ) )
3532 {
3533 // no default action at the moment
3534 }
3535 }
3536
3537 // ------------ No buttons down and mouse moving
3538 //
3539 else if ( event.Moving() )
3540 {
3541 m_dragRowOrCol = XToEdgeOfCol( x );
3542 if ( m_dragRowOrCol >= 0 )
3543 {
3544 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
3545 {
3546 if ( CanDragColSize(m_dragRowOrCol) )
3547 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, GetColLabelWindow(), false);
3548 }
3549 }
3550 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
3551 {
3552 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, GetColLabelWindow(), false);
3553 }
3554 }
3555 }
3556
3557 void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent& event )
3558 {
3559 if ( event.LeftDown() )
3560 {
3561 // indicate corner label by having both row and
3562 // col args == -1
3563 //
3564 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, -1, event ) )
3565 {
3566 SelectAll();
3567 }
3568 }
3569 else if ( event.LeftDClick() )
3570 {
3571 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, -1, event );
3572 }
3573 else if ( event.RightDown() )
3574 {
3575 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, -1, event ) )
3576 {
3577 // no default action at the moment
3578 }
3579 }
3580 else if ( event.RightDClick() )
3581 {
3582 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, -1, event ) )
3583 {
3584 // no default action at the moment
3585 }
3586 }
3587 }
3588
3589 void wxGrid::CancelMouseCapture()
3590 {
3591 // cancel operation currently in progress, whatever it is
3592 if ( m_winCapture )
3593 {
3594 m_isDragging = false;
3595 m_startDragPos = wxDefaultPosition;
3596
3597 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
3598 m_winCapture->SetCursor( *wxSTANDARD_CURSOR );
3599 m_winCapture = NULL;
3600
3601 // remove traces of whatever we drew on screen
3602 Refresh();
3603 }
3604 }
3605
3606 void wxGrid::ChangeCursorMode(CursorMode mode,
3607 wxWindow *win,
3608 bool captureMouse)
3609 {
3610 #if wxUSE_LOG_TRACE
3611 static const wxChar *const cursorModes[] =
3612 {
3613 wxT("SELECT_CELL"),
3614 wxT("RESIZE_ROW"),
3615 wxT("RESIZE_COL"),
3616 wxT("SELECT_ROW"),
3617 wxT("SELECT_COL"),
3618 wxT("MOVE_COL"),
3619 };
3620
3621 wxLogTrace(wxT("grid"),
3622 wxT("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
3623 win == m_colWindow ? wxT("colLabelWin")
3624 : win ? wxT("rowLabelWin")
3625 : wxT("gridWin"),
3626 cursorModes[m_cursorMode], cursorModes[mode]);
3627 #endif // wxUSE_LOG_TRACE
3628
3629 if ( mode == m_cursorMode &&
3630 win == m_winCapture &&
3631 captureMouse == (m_winCapture != NULL))
3632 return;
3633
3634 if ( !win )
3635 {
3636 // by default use the grid itself
3637 win = m_gridWin;
3638 }
3639
3640 if ( m_winCapture )
3641 {
3642 m_winCapture->ReleaseMouse();
3643 m_winCapture = NULL;
3644 }
3645
3646 m_cursorMode = mode;
3647
3648 switch ( m_cursorMode )
3649 {
3650 case WXGRID_CURSOR_RESIZE_ROW:
3651 win->SetCursor( m_rowResizeCursor );
3652 break;
3653
3654 case WXGRID_CURSOR_RESIZE_COL:
3655 win->SetCursor( m_colResizeCursor );
3656 break;
3657
3658 case WXGRID_CURSOR_MOVE_COL:
3659 win->SetCursor( wxCursor(wxCURSOR_HAND) );
3660 break;
3661
3662 default:
3663 win->SetCursor( *wxSTANDARD_CURSOR );
3664 break;
3665 }
3666
3667 // we need to capture mouse when resizing
3668 bool resize = m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ||
3669 m_cursorMode == WXGRID_CURSOR_RESIZE_COL;
3670
3671 if ( captureMouse && resize )
3672 {
3673 win->CaptureMouse();
3674 m_winCapture = win;
3675 }
3676 }
3677
3678 // ----------------------------------------------------------------------------
3679 // grid mouse event processing
3680 // ----------------------------------------------------------------------------
3681
3682 void
3683 wxGrid::DoGridCellDrag(wxMouseEvent& event,
3684 const wxGridCellCoords& coords,
3685 bool isFirstDrag)
3686 {
3687 if ( coords == wxGridNoCellCoords )
3688 return; // we're outside any valid cell
3689
3690 // Hide the edit control, so it won't interfere with drag-shrinking.
3691 if ( IsCellEditControlShown() )
3692 {
3693 HideCellEditControl();
3694 SaveEditControlValue();
3695 }
3696
3697 switch ( event.GetModifiers() )
3698 {
3699 case wxMOD_CMD:
3700 if ( m_selectedBlockCorner == wxGridNoCellCoords)
3701 m_selectedBlockCorner = coords;
3702 UpdateBlockBeingSelected(m_selectedBlockCorner, coords);
3703 break;
3704
3705 case wxMOD_NONE:
3706 if ( CanDragCell() )
3707 {
3708 if ( isFirstDrag )
3709 {
3710 if ( m_selectedBlockCorner == wxGridNoCellCoords)
3711 m_selectedBlockCorner = coords;
3712
3713 SendEvent(wxEVT_GRID_CELL_BEGIN_DRAG, coords, event);
3714 return;
3715 }
3716 }
3717
3718 UpdateBlockBeingSelected(m_currentCellCoords, coords);
3719 break;
3720
3721 default:
3722 // we don't handle the other key modifiers
3723 event.Skip();
3724 }
3725 }
3726
3727 void wxGrid::DoGridLineDrag(wxMouseEvent& event, const wxGridOperations& oper)
3728 {
3729 wxClientDC dc(m_gridWin);
3730 PrepareDC(dc);
3731 dc.SetLogicalFunction(wxINVERT);
3732
3733 const wxRect rectWin(CalcUnscrolledPosition(wxPoint(0, 0)),
3734 m_gridWin->GetClientSize());
3735
3736 // erase the previously drawn line, if any
3737 if ( m_dragLastPos >= 0 )
3738 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
3739
3740 // we need the vertical position for rows and horizontal for columns here
3741 m_dragLastPos = oper.Dual().Select(CalcUnscrolledPosition(event.GetPosition()));
3742
3743 // don't allow resizing beneath the minimal size
3744 const int posMin = oper.GetLineStartPos(this, m_dragRowOrCol) +
3745 oper.GetMinimalLineSize(this, m_dragRowOrCol);
3746 if ( m_dragLastPos < posMin )
3747 m_dragLastPos = posMin;
3748
3749 // and draw it at the new position
3750 oper.DrawParallelLineInRect(dc, rectWin, m_dragLastPos);
3751 }
3752
3753 void wxGrid::DoGridDragEvent(wxMouseEvent& event, const wxGridCellCoords& coords)
3754 {
3755 if ( !m_isDragging )
3756 {
3757 // Don't start doing anything until the mouse has been dragged far
3758 // enough
3759 const wxPoint& pt = event.GetPosition();
3760 if ( m_startDragPos == wxDefaultPosition )
3761 {
3762 m_startDragPos = pt;
3763 return;
3764 }
3765
3766 if ( abs(m_startDragPos.x - pt.x) <= DRAG_SENSITIVITY &&
3767 abs(m_startDragPos.y - pt.y) <= DRAG_SENSITIVITY )
3768 return;
3769 }
3770
3771 const bool isFirstDrag = !m_isDragging;
3772 m_isDragging = true;
3773
3774 switch ( m_cursorMode )
3775 {
3776 case WXGRID_CURSOR_SELECT_CELL:
3777 DoGridCellDrag(event, coords, isFirstDrag);
3778 break;
3779
3780 case WXGRID_CURSOR_RESIZE_ROW:
3781 DoGridLineDrag(event, wxGridRowOperations());
3782 break;
3783
3784 case WXGRID_CURSOR_RESIZE_COL:
3785 DoGridLineDrag(event, wxGridColumnOperations());
3786 break;
3787
3788 default:
3789 event.Skip();
3790 }
3791
3792 if ( isFirstDrag )
3793 {
3794 wxASSERT_MSG( !m_winCapture, "shouldn't capture the mouse twice" );
3795
3796 m_winCapture = m_gridWin;
3797 m_winCapture->CaptureMouse();
3798 }
3799 }
3800
3801 void
3802 wxGrid::DoGridCellLeftDown(wxMouseEvent& event,
3803 const wxGridCellCoords& coords,
3804 const wxPoint& pos)
3805 {
3806 if ( SendEvent(wxEVT_GRID_CELL_LEFT_CLICK, coords, event) )
3807 {
3808 // event handled by user code, no need to do anything here
3809 return;
3810 }
3811
3812 if ( !event.CmdDown() )
3813 ClearSelection();
3814
3815 if ( event.ShiftDown() )
3816 {
3817 if ( m_selection )
3818 {
3819 m_selection->SelectBlock(m_currentCellCoords, coords, event);
3820 m_selectedBlockCorner = coords;
3821 }
3822 }
3823 else if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
3824 {
3825 DisableCellEditControl();
3826 MakeCellVisible( coords );
3827
3828 if ( event.CmdDown() )
3829 {
3830 if ( m_selection )
3831 {
3832 m_selection->ToggleCellSelection(coords, event);
3833 }
3834
3835 m_selectedBlockTopLeft = wxGridNoCellCoords;
3836 m_selectedBlockBottomRight = wxGridNoCellCoords;
3837 m_selectedBlockCorner = coords;
3838 }
3839 else
3840 {
3841 if ( m_selection )
3842 {
3843 // In row or column selection mode just clicking on the cell
3844 // should select the row or column containing it: this is more
3845 // convenient for the kinds of controls that use such selection
3846 // mode and is compatible with 2.8 behaviour (see #12062).
3847 switch ( m_selection->GetSelectionMode() )
3848 {
3849 case wxGridSelectCells:
3850 case wxGridSelectRowsOrColumns:
3851 // nothing to do in these cases
3852 break;
3853
3854 case wxGridSelectRows:
3855 m_selection->SelectRow(coords.GetRow());
3856 break;
3857
3858 case wxGridSelectColumns:
3859 m_selection->SelectCol(coords.GetCol());
3860 break;
3861 }
3862 }
3863
3864 m_waitForSlowClick = m_currentCellCoords == coords &&
3865 coords != wxGridNoCellCoords;
3866 SetCurrentCell( coords );
3867 }
3868 }
3869 }
3870
3871 void
3872 wxGrid::DoGridCellLeftDClick(wxMouseEvent& event,
3873 const wxGridCellCoords& coords,
3874 const wxPoint& pos)
3875 {
3876 if ( XToEdgeOfCol(pos.x) < 0 && YToEdgeOfRow(pos.y) < 0 )
3877 {
3878 if ( !SendEvent(wxEVT_GRID_CELL_LEFT_DCLICK, coords, event) )
3879 {
3880 // we want double click to select a cell and start editing
3881 // (i.e. to behave in same way as sequence of two slow clicks):
3882 m_waitForSlowClick = true;
3883 }
3884 }
3885 }
3886
3887 void
3888 wxGrid::DoGridCellLeftUp(wxMouseEvent& event, const wxGridCellCoords& coords)
3889 {
3890 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
3891 {
3892 if (m_winCapture)
3893 {
3894 m_winCapture->ReleaseMouse();
3895 m_winCapture = NULL;
3896 }
3897
3898 if ( coords == m_currentCellCoords && m_waitForSlowClick && CanEnableCellControl() )
3899 {
3900 ClearSelection();
3901 EnableCellEditControl();
3902
3903 wxGridCellAttr *attr = GetCellAttr(coords);
3904 wxGridCellEditor *editor = attr->GetEditor(this, coords.GetRow(), coords.GetCol());
3905 editor->StartingClick();
3906 editor->DecRef();
3907 attr->DecRef();
3908
3909 m_waitForSlowClick = false;
3910 }
3911 else if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
3912 m_selectedBlockBottomRight != wxGridNoCellCoords )
3913 {
3914 if ( m_selection )
3915 {
3916 m_selection->SelectBlock( m_selectedBlockTopLeft,
3917 m_selectedBlockBottomRight,
3918 event );
3919 }
3920
3921 m_selectedBlockTopLeft = wxGridNoCellCoords;
3922 m_selectedBlockBottomRight = wxGridNoCellCoords;
3923
3924 // Show the edit control, if it has been hidden for
3925 // drag-shrinking.
3926 ShowCellEditControl();
3927 }
3928 }
3929 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
3930 {
3931 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
3932 DoEndDragResizeRow(event);
3933 }
3934 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL )
3935 {
3936 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
3937 DoEndDragResizeCol(event);
3938 }
3939
3940 m_dragLastPos = -1;
3941 }
3942
3943 void
3944 wxGrid::DoGridMouseMoveEvent(wxMouseEvent& WXUNUSED(event),
3945 const wxGridCellCoords& coords,
3946 const wxPoint& pos)
3947 {
3948 if ( coords.GetRow() < 0 || coords.GetCol() < 0 )
3949 {
3950 // out of grid cell area
3951 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
3952 return;
3953 }
3954
3955 int dragRow = YToEdgeOfRow( pos.y );
3956 int dragCol = XToEdgeOfCol( pos.x );
3957
3958 // Dragging on the corner of a cell to resize in both
3959 // directions is not implemented yet...
3960 //
3961 if ( dragRow >= 0 && dragCol >= 0 )
3962 {
3963 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
3964 return;
3965 }
3966
3967 if ( dragRow >= 0 && CanDragGridSize() && CanDragRowSize(dragRow) )
3968 {
3969 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
3970 {
3971 m_dragRowOrCol = dragRow;
3972 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, NULL, false);
3973 }
3974 }
3975 // When using the native header window we can only resize the columns by
3976 // dragging the dividers in it because we can't make it enter into the
3977 // column resizing mode programmatically
3978 else if ( dragCol >= 0 && !m_useNativeHeader &&
3979 CanDragGridSize() && CanDragColSize(dragCol) )
3980 {
3981 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
3982 {
3983 m_dragRowOrCol = dragCol;
3984 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, NULL, false);
3985 }
3986 }
3987 else // Neither on a row or col edge
3988 {
3989 if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
3990 {
3991 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
3992 }
3993 }
3994 }
3995
3996 void wxGrid::ProcessGridCellMouseEvent(wxMouseEvent& event)
3997 {
3998 if ( event.Entering() || event.Leaving() )
3999 {
4000 // we don't care about these events but we must not reset m_isDragging
4001 // if they happen so return before anything else is done
4002 event.Skip();
4003 return;
4004 }
4005
4006 const wxPoint pos = CalcUnscrolledPosition(event.GetPosition());
4007
4008 // coordinates of the cell under mouse
4009 wxGridCellCoords coords = XYToCell(pos);
4010
4011 int cell_rows, cell_cols;
4012 GetCellSize( coords.GetRow(), coords.GetCol(), &cell_rows, &cell_cols );
4013 if ( (cell_rows < 0) || (cell_cols < 0) )
4014 {
4015 coords.SetRow(coords.GetRow() + cell_rows);
4016 coords.SetCol(coords.GetCol() + cell_cols);
4017 }
4018
4019 if ( event.Dragging() )
4020 {
4021 if ( event.LeftIsDown() )
4022 DoGridDragEvent(event, coords);
4023 else
4024 event.Skip();
4025 return;
4026 }
4027
4028 m_isDragging = false;
4029 m_startDragPos = wxDefaultPosition;
4030
4031 // deal with various button presses
4032 if ( event.IsButton() )
4033 {
4034 if ( coords != wxGridNoCellCoords )
4035 {
4036 DisableCellEditControl();
4037
4038 if ( event.LeftDown() )
4039 DoGridCellLeftDown(event, coords, pos);
4040 else if ( event.LeftDClick() )
4041 DoGridCellLeftDClick(event, coords, pos);
4042 else if ( event.RightDown() )
4043 SendEvent(wxEVT_GRID_CELL_RIGHT_CLICK, coords, event);
4044 else if ( event.RightDClick() )
4045 SendEvent(wxEVT_GRID_CELL_RIGHT_DCLICK, coords, event);
4046 }
4047
4048 // this one should be called even if we're not over any cell
4049 if ( event.LeftUp() )
4050 {
4051 DoGridCellLeftUp(event, coords);
4052 }
4053 }
4054 else if ( event.Moving() )
4055 {
4056 DoGridMouseMoveEvent(event, coords, pos);
4057 }
4058 else // unknown mouse event?
4059 {
4060 event.Skip();
4061 }
4062 }
4063
4064 // this function returns true only if the size really changed
4065 bool wxGrid::DoEndDragResizeLine(const wxGridOperations& oper)
4066 {
4067 if ( m_dragLastPos == -1 )
4068 return false;
4069
4070 const wxGridOperations& doper = oper.Dual();
4071
4072 const wxSize size = m_gridWin->GetClientSize();
4073
4074 const wxPoint ptOrigin = CalcUnscrolledPosition(wxPoint(0, 0));
4075
4076 // erase the last line we drew
4077 wxClientDC dc(m_gridWin);
4078 PrepareDC(dc);
4079 dc.SetLogicalFunction(wxINVERT);
4080
4081 const int posLineStart = oper.Select(ptOrigin);
4082 const int posLineEnd = oper.Select(ptOrigin) + oper.Select(size);
4083
4084 oper.DrawParallelLine(dc, posLineStart, posLineEnd, m_dragLastPos);
4085
4086 // temporarily hide the edit control before resizing
4087 HideCellEditControl();
4088 SaveEditControlValue();
4089
4090 // do resize the line
4091 const int lineStart = oper.GetLineStartPos(this, m_dragRowOrCol);
4092 const int lineSizeOld = oper.GetLineSize(this, m_dragRowOrCol);
4093 oper.SetLineSize(this, m_dragRowOrCol,
4094 wxMax(m_dragLastPos - lineStart,
4095 oper.GetMinimalLineSize(this, m_dragRowOrCol)));
4096 const bool
4097 sizeChanged = oper.GetLineSize(this, m_dragRowOrCol) != lineSizeOld;
4098
4099 m_dragLastPos = -1;
4100
4101 // refresh now if we're not frozen
4102 if ( !GetBatchCount() )
4103 {
4104 // we need to refresh everything beyond the resized line in the header
4105 // window
4106
4107 // get the position from which to refresh in the other direction
4108 wxRect rect(CellToRect(oper.MakeCoords(m_dragRowOrCol, 0)));
4109 rect.SetPosition(CalcScrolledPosition(rect.GetPosition()));
4110
4111 // we only need the ordinate (for rows) or abscissa (for columns) here,
4112 // and need to cover the entire window in the other direction
4113 oper.Select(rect) = 0;
4114
4115 wxRect rectHeader(rect.GetPosition(),
4116 oper.MakeSize
4117 (
4118 oper.GetHeaderWindowSize(this),
4119 doper.Select(size) - doper.Select(rect)
4120 ));
4121
4122 oper.GetHeaderWindow(this)->Refresh(true, &rectHeader);
4123
4124
4125 // also refresh the grid window: extend the rectangle
4126 if ( m_table )
4127 {
4128 oper.SelectSize(rect) = oper.Select(size);
4129
4130 int subtractLines = 0;
4131 const int lineStart = oper.PosToLine(this, posLineStart);
4132 if ( lineStart >= 0 )
4133 {
4134 // ensure that if we have a multi-cell block we redraw all of
4135 // it by increasing the refresh area to cover it entirely if a
4136 // part of it is affected
4137 const int lineEnd = oper.PosToLine(this, posLineEnd, true);
4138 for ( int line = lineStart; line < lineEnd; line++ )
4139 {
4140 int cellLines = oper.Select(
4141 GetCellSize(oper.MakeCoords(m_dragRowOrCol, line)));
4142 if ( cellLines < subtractLines )
4143 subtractLines = cellLines;
4144 }
4145 }
4146
4147 int startPos =
4148 oper.GetLineStartPos(this, m_dragRowOrCol + subtractLines);
4149 startPos = doper.CalcScrolledPosition(this, startPos);
4150
4151 doper.Select(rect) = startPos;
4152 doper.SelectSize(rect) = doper.Select(size) - startPos;
4153
4154 m_gridWin->Refresh(false, &rect);
4155 }
4156 }
4157
4158 // show the edit control back again
4159 ShowCellEditControl();
4160
4161 return sizeChanged;
4162 }
4163
4164 void wxGrid::DoEndDragResizeRow(const wxMouseEvent& event)
4165 {
4166 // TODO: generate RESIZING event, see #10754
4167
4168 if ( DoEndDragResizeLine(wxGridRowOperations()) )
4169 SendGridSizeEvent(wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event);
4170 }
4171
4172 void wxGrid::DoEndDragResizeCol(const wxMouseEvent& event)
4173 {
4174 // TODO: generate RESIZING event, see #10754
4175
4176 if ( DoEndDragResizeLine(wxGridColumnOperations()) )
4177 SendGridSizeEvent(wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, event);
4178 }
4179
4180 void wxGrid::DoStartMoveCol(int col)
4181 {
4182 m_dragRowOrCol = col;
4183 }
4184
4185 void wxGrid::DoEndMoveCol(int pos)
4186 {
4187 wxASSERT_MSG( m_dragRowOrCol != -1, "no matching DoStartMoveCol?" );
4188
4189 if ( SendEvent(wxEVT_GRID_COL_MOVE, -1, m_dragRowOrCol) != -1 )
4190 SetColPos(m_dragRowOrCol, pos);
4191 //else: vetoed by user
4192
4193 m_dragRowOrCol = -1;
4194 }
4195
4196 void wxGrid::RefreshAfterColPosChange()
4197 {
4198 // recalculate the column rights as the column positions have changed,
4199 // unless we calculate them dynamically because all columns widths are the
4200 // same and it's easy to do
4201 if ( !m_colWidths.empty() )
4202 {
4203 int colRight = 0;
4204 for ( int colPos = 0; colPos < m_numCols; colPos++ )
4205 {
4206 int colID = GetColAt( colPos );
4207
4208 colRight += m_colWidths[colID];
4209 m_colRights[colID] = colRight;
4210 }
4211 }
4212
4213 // and make the changes visible
4214 if ( m_useNativeHeader )
4215 {
4216 if ( m_colAt.empty() )
4217 GetGridColHeader()->ResetColumnsOrder();
4218 else
4219 GetGridColHeader()->SetColumnsOrder(m_colAt);
4220 }
4221 else
4222 {
4223 m_colWindow->Refresh();
4224 }
4225 m_gridWin->Refresh();
4226 }
4227
4228 void wxGrid::SetColumnsOrder(const wxArrayInt& order)
4229 {
4230 m_colAt = order;
4231
4232 RefreshAfterColPosChange();
4233 }
4234
4235 void wxGrid::SetColPos(int idx, int pos)
4236 {
4237 // we're going to need m_colAt now, initialize it if needed
4238 if ( m_colAt.empty() )
4239 {
4240 m_colAt.reserve(m_numCols);
4241 for ( int i = 0; i < m_numCols; i++ )
4242 m_colAt.push_back(i);
4243 }
4244
4245 wxHeaderCtrl::MoveColumnInOrderArray(m_colAt, idx, pos);
4246
4247 RefreshAfterColPosChange();
4248 }
4249
4250 void wxGrid::ResetColPos()
4251 {
4252 m_colAt.clear();
4253
4254 RefreshAfterColPosChange();
4255 }
4256
4257 void wxGrid::EnableDragColMove( bool enable )
4258 {
4259 if ( m_canDragColMove == enable )
4260 return;
4261
4262 if ( m_useNativeHeader )
4263 {
4264 // update all columns to make them [not] reorderable
4265 GetGridColHeader()->SetColumnCount(m_numCols);
4266 }
4267
4268 m_canDragColMove = enable;
4269
4270 // we use to call ResetColPos() from here if !enable but this doesn't seem
4271 // right as it would mean there would be no way to "freeze" the current
4272 // columns order by disabling moving them after putting them in the desired
4273 // order, whereas now you can always call ResetColPos() manually if needed
4274 }
4275
4276
4277 //
4278 // ------ interaction with data model
4279 //
4280 bool wxGrid::ProcessTableMessage( wxGridTableMessage& msg )
4281 {
4282 switch ( msg.GetId() )
4283 {
4284 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES:
4285 return GetModelValues();
4286
4287 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES:
4288 return SetModelValues();
4289
4290 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
4291 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
4292 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
4293 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
4294 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
4295 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
4296 return Redimension( msg );
4297
4298 default:
4299 return false;
4300 }
4301 }
4302
4303 // The behaviour of this function depends on the grid table class
4304 // Clear() function. For the default wxGridStringTable class the
4305 // behaviour is to replace all cell contents with wxEmptyString but
4306 // not to change the number of rows or cols.
4307 //
4308 void wxGrid::ClearGrid()
4309 {
4310 if ( m_table )
4311 {
4312 if (IsCellEditControlEnabled())
4313 DisableCellEditControl();
4314
4315 m_table->Clear();
4316 if (!GetBatchCount())
4317 m_gridWin->Refresh();
4318 }
4319 }
4320
4321 bool
4322 wxGrid::DoModifyLines(bool (wxGridTableBase::*funcModify)(size_t, size_t),
4323 int pos, int num, bool WXUNUSED(updateLabels) )
4324 {
4325 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
4326
4327 if ( !m_table )
4328 return false;
4329
4330 if ( IsCellEditControlEnabled() )
4331 DisableCellEditControl();
4332
4333 return (m_table->*funcModify)(pos, num);
4334
4335 // the table will have sent the results of the insert row
4336 // operation to this view object as a grid table message
4337 }
4338
4339 bool
4340 wxGrid::DoAppendLines(bool (wxGridTableBase::*funcAppend)(size_t),
4341 int num, bool WXUNUSED(updateLabels))
4342 {
4343 wxCHECK_MSG( m_created, false, "must finish creating the grid first" );
4344
4345 if ( !m_table )
4346 return false;
4347
4348 return (m_table->*funcAppend)(num);
4349 }
4350
4351 // ----------------------------------------------------------------------------
4352 // event generation helpers
4353 // ----------------------------------------------------------------------------
4354
4355 void
4356 wxGrid::SendGridSizeEvent(wxEventType type,
4357 int row, int col,
4358 const wxMouseEvent& mouseEv)
4359 {
4360 int rowOrCol = row == -1 ? col : row;
4361
4362 wxGridSizeEvent gridEvt( GetId(),
4363 type,
4364 this,
4365 rowOrCol,
4366 mouseEv.GetX() + GetRowLabelSize(),
4367 mouseEv.GetY() + GetColLabelSize(),
4368 mouseEv);
4369
4370 GetEventHandler()->ProcessEvent(gridEvt);
4371 }
4372
4373 // Generate a grid event based on a mouse event and return:
4374 // -1 if the event was vetoed
4375 // +1 if the event was processed (but not vetoed)
4376 // 0 if the event wasn't handled
4377 int
4378 wxGrid::SendEvent(const wxEventType type,
4379 int row, int col,
4380 const wxMouseEvent& mouseEv)
4381 {
4382 bool claimed, vetoed;
4383
4384 if ( type == wxEVT_GRID_RANGE_SELECT )
4385 {
4386 // Right now, it should _never_ end up here!
4387 wxGridRangeSelectEvent gridEvt( GetId(),
4388 type,
4389 this,
4390 m_selectedBlockTopLeft,
4391 m_selectedBlockBottomRight,
4392 true,
4393 mouseEv);
4394
4395 claimed = GetEventHandler()->ProcessEvent(gridEvt);
4396 vetoed = !gridEvt.IsAllowed();
4397 }
4398 else if ( type == wxEVT_GRID_LABEL_LEFT_CLICK ||
4399 type == wxEVT_GRID_LABEL_LEFT_DCLICK ||
4400 type == wxEVT_GRID_LABEL_RIGHT_CLICK ||
4401 type == wxEVT_GRID_LABEL_RIGHT_DCLICK )
4402 {
4403 wxPoint pos = mouseEv.GetPosition();
4404
4405 if ( mouseEv.GetEventObject() == GetGridRowLabelWindow() )
4406 pos.y += GetColLabelSize();
4407 if ( mouseEv.GetEventObject() == GetGridColLabelWindow() )
4408 pos.x += GetRowLabelSize();
4409
4410 wxGridEvent gridEvt( GetId(),
4411 type,
4412 this,
4413 row, col,
4414 pos.x,
4415 pos.y,
4416 false,
4417 mouseEv);
4418 claimed = GetEventHandler()->ProcessEvent(gridEvt);
4419 vetoed = !gridEvt.IsAllowed();
4420 }
4421 else
4422 {
4423 wxGridEvent gridEvt( GetId(),
4424 type,
4425 this,
4426 row, col,
4427 mouseEv.GetX() + GetRowLabelSize(),
4428 mouseEv.GetY() + GetColLabelSize(),
4429 false,
4430 mouseEv);
4431 claimed = GetEventHandler()->ProcessEvent(gridEvt);
4432 vetoed = !gridEvt.IsAllowed();
4433 }
4434
4435 // A Veto'd event may not be `claimed' so test this first
4436 if (vetoed)
4437 return -1;
4438
4439 return claimed ? 1 : 0;
4440 }
4441
4442 // Generate a grid event of specified type, return value same as above
4443 //
4444 int
4445 wxGrid::SendEvent(const wxEventType type, int row, int col, const wxString& s)
4446 {
4447 wxGridEvent gridEvt( GetId(), type, this, row, col );
4448 gridEvt.SetString(s);
4449
4450 const bool claimed = GetEventHandler()->ProcessEvent(gridEvt);
4451
4452 // A Veto'd event may not be `claimed' so test this first
4453 if ( !gridEvt.IsAllowed() )
4454 return -1;
4455
4456 return claimed ? 1 : 0;
4457 }
4458
4459 void wxGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
4460 {
4461 // needed to prevent zillions of paint events on MSW
4462 wxPaintDC dc(this);
4463 }
4464
4465 void wxGrid::Refresh(bool eraseb, const wxRect* rect)
4466 {
4467 // Don't do anything if between Begin/EndBatch...
4468 // EndBatch() will do all this on the last nested one anyway.
4469 if ( m_created && !GetBatchCount() )
4470 {
4471 // Refresh to get correct scrolled position:
4472 wxScrolledWindow::Refresh(eraseb, rect);
4473
4474 if (rect)
4475 {
4476 int rect_x, rect_y, rectWidth, rectHeight;
4477 int width_label, width_cell, height_label, height_cell;
4478 int x, y;
4479
4480 // Copy rectangle can get scroll offsets..
4481 rect_x = rect->GetX();
4482 rect_y = rect->GetY();
4483 rectWidth = rect->GetWidth();
4484 rectHeight = rect->GetHeight();
4485
4486 width_label = m_rowLabelWidth - rect_x;
4487 if (width_label > rectWidth)
4488 width_label = rectWidth;
4489
4490 height_label = m_colLabelHeight - rect_y;
4491 if (height_label > rectHeight)
4492 height_label = rectHeight;
4493
4494 if (rect_x > m_rowLabelWidth)
4495 {
4496 x = rect_x - m_rowLabelWidth;
4497 width_cell = rectWidth;
4498 }
4499 else
4500 {
4501 x = 0;
4502 width_cell = rectWidth - (m_rowLabelWidth - rect_x);
4503 }
4504
4505 if (rect_y > m_colLabelHeight)
4506 {
4507 y = rect_y - m_colLabelHeight;
4508 height_cell = rectHeight;
4509 }
4510 else
4511 {
4512 y = 0;
4513 height_cell = rectHeight - (m_colLabelHeight - rect_y);
4514 }
4515
4516 // Paint corner label part intersecting rect.
4517 if ( width_label > 0 && height_label > 0 )
4518 {
4519 wxRect anotherrect(rect_x, rect_y, width_label, height_label);
4520 m_cornerLabelWin->Refresh(eraseb, &anotherrect);
4521 }
4522
4523 // Paint col labels part intersecting rect.
4524 if ( width_cell > 0 && height_label > 0 )
4525 {
4526 wxRect anotherrect(x, rect_y, width_cell, height_label);
4527 m_colWindow->Refresh(eraseb, &anotherrect);
4528 }
4529
4530 // Paint row labels part intersecting rect.
4531 if ( width_label > 0 && height_cell > 0 )
4532 {
4533 wxRect anotherrect(rect_x, y, width_label, height_cell);
4534 m_rowLabelWin->Refresh(eraseb, &anotherrect);
4535 }
4536
4537 // Paint cell area part intersecting rect.
4538 if ( width_cell > 0 && height_cell > 0 )
4539 {
4540 wxRect anotherrect(x, y, width_cell, height_cell);
4541 m_gridWin->Refresh(eraseb, &anotherrect);
4542 }
4543 }
4544 else
4545 {
4546 m_cornerLabelWin->Refresh(eraseb, NULL);
4547 m_colWindow->Refresh(eraseb, NULL);
4548 m_rowLabelWin->Refresh(eraseb, NULL);
4549 m_gridWin->Refresh(eraseb, NULL);
4550 }
4551 }
4552 }
4553
4554 void wxGrid::OnSize(wxSizeEvent& WXUNUSED(event))
4555 {
4556 if (m_targetWindow != this) // check whether initialisation has been done
4557 {
4558 // reposition our children windows
4559 CalcWindowSizes();
4560 }
4561 }
4562
4563 void wxGrid::OnKeyDown( wxKeyEvent& event )
4564 {
4565 if ( m_inOnKeyDown )
4566 {
4567 // shouldn't be here - we are going round in circles...
4568 //
4569 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
4570 }
4571
4572 m_inOnKeyDown = true;
4573
4574 // propagate the event up and see if it gets processed
4575 wxWindow *parent = GetParent();
4576 wxKeyEvent keyEvt( event );
4577 keyEvt.SetEventObject( parent );
4578
4579 if ( !parent->GetEventHandler()->ProcessEvent( keyEvt ) )
4580 {
4581 if (GetLayoutDirection() == wxLayout_RightToLeft)
4582 {
4583 if (event.GetKeyCode() == WXK_RIGHT)
4584 event.m_keyCode = WXK_LEFT;
4585 else if (event.GetKeyCode() == WXK_LEFT)
4586 event.m_keyCode = WXK_RIGHT;
4587 }
4588
4589 // try local handlers
4590 switch ( event.GetKeyCode() )
4591 {
4592 case WXK_UP:
4593 if ( event.ControlDown() )
4594 MoveCursorUpBlock( event.ShiftDown() );
4595 else
4596 MoveCursorUp( event.ShiftDown() );
4597 break;
4598
4599 case WXK_DOWN:
4600 if ( event.ControlDown() )
4601 MoveCursorDownBlock( event.ShiftDown() );
4602 else
4603 MoveCursorDown( event.ShiftDown() );
4604 break;
4605
4606 case WXK_LEFT:
4607 if ( event.ControlDown() )
4608 MoveCursorLeftBlock( event.ShiftDown() );
4609 else
4610 MoveCursorLeft( event.ShiftDown() );
4611 break;
4612
4613 case WXK_RIGHT:
4614 if ( event.ControlDown() )
4615 MoveCursorRightBlock( event.ShiftDown() );
4616 else
4617 MoveCursorRight( event.ShiftDown() );
4618 break;
4619
4620 case WXK_RETURN:
4621 case WXK_NUMPAD_ENTER:
4622 if ( event.ControlDown() )
4623 {
4624 event.Skip(); // to let the edit control have the return
4625 }
4626 else
4627 {
4628 if ( GetGridCursorRow() < GetNumberRows()-1 )
4629 {
4630 MoveCursorDown( event.ShiftDown() );
4631 }
4632 else
4633 {
4634 // at the bottom of a column
4635 DisableCellEditControl();
4636 }
4637 }
4638 break;
4639
4640 case WXK_ESCAPE:
4641 ClearSelection();
4642 break;
4643
4644 case WXK_TAB:
4645 if (event.ShiftDown())
4646 {
4647 if ( GetGridCursorCol() > 0 )
4648 {
4649 MoveCursorLeft( false );
4650 }
4651 else
4652 {
4653 // at left of grid
4654 DisableCellEditControl();
4655 }
4656 }
4657 else
4658 {
4659 if ( GetGridCursorCol() < GetNumberCols() - 1 )
4660 {
4661 MoveCursorRight( false );
4662 }
4663 else
4664 {
4665 // at right of grid
4666 DisableCellEditControl();
4667 }
4668 }
4669 break;
4670
4671 case WXK_HOME:
4672 GoToCell(event.ControlDown() ? 0
4673 : m_currentCellCoords.GetRow(),
4674 0);
4675 break;
4676
4677 case WXK_END:
4678 GoToCell(event.ControlDown() ? m_numRows - 1
4679 : m_currentCellCoords.GetRow(),
4680 m_numCols - 1);
4681 break;
4682
4683 case WXK_PAGEUP:
4684 MovePageUp();
4685 break;
4686
4687 case WXK_PAGEDOWN:
4688 MovePageDown();
4689 break;
4690
4691 case WXK_SPACE:
4692 // Ctrl-Space selects the current column, Shift-Space -- the
4693 // current row and Ctrl-Shift-Space -- everything
4694 switch ( m_selection ? event.GetModifiers() : wxMOD_NONE )
4695 {
4696 case wxMOD_CONTROL:
4697 m_selection->SelectCol(m_currentCellCoords.GetCol());
4698 break;
4699
4700 case wxMOD_SHIFT:
4701 m_selection->SelectRow(m_currentCellCoords.GetRow());
4702 break;
4703
4704 case wxMOD_CONTROL | wxMOD_SHIFT:
4705 m_selection->SelectBlock(0, 0,
4706 m_numRows - 1, m_numCols - 1);
4707 break;
4708
4709 case wxMOD_NONE:
4710 if ( !IsEditable() )
4711 {
4712 MoveCursorRight(false);
4713 break;
4714 }
4715 //else: fall through
4716
4717 default:
4718 event.Skip();
4719 }
4720 break;
4721
4722 default:
4723 event.Skip();
4724 break;
4725 }
4726 }
4727
4728 m_inOnKeyDown = false;
4729 }
4730
4731 void wxGrid::OnKeyUp( wxKeyEvent& event )
4732 {
4733 // try local handlers
4734 //
4735 if ( event.GetKeyCode() == WXK_SHIFT )
4736 {
4737 if ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
4738 m_selectedBlockBottomRight != wxGridNoCellCoords )
4739 {
4740 if ( m_selection )
4741 {
4742 m_selection->SelectBlock(
4743 m_selectedBlockTopLeft,
4744 m_selectedBlockBottomRight,
4745 event);
4746 }
4747 }
4748
4749 m_selectedBlockTopLeft = wxGridNoCellCoords;
4750 m_selectedBlockBottomRight = wxGridNoCellCoords;
4751 m_selectedBlockCorner = wxGridNoCellCoords;
4752 }
4753 }
4754
4755 void wxGrid::OnChar( wxKeyEvent& event )
4756 {
4757 // is it possible to edit the current cell at all?
4758 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
4759 {
4760 // yes, now check whether the cells editor accepts the key
4761 int row = m_currentCellCoords.GetRow();
4762 int col = m_currentCellCoords.GetCol();
4763 wxGridCellAttr *attr = GetCellAttr(row, col);
4764 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
4765
4766 // <F2> is special and will always start editing, for
4767 // other keys - ask the editor itself
4768 if ( (event.GetKeyCode() == WXK_F2 && !event.HasModifiers())
4769 || editor->IsAcceptedKey(event) )
4770 {
4771 // ensure cell is visble
4772 MakeCellVisible(row, col);
4773 EnableCellEditControl();
4774
4775 // a problem can arise if the cell is not completely
4776 // visible (even after calling MakeCellVisible the
4777 // control is not created and calling StartingKey will
4778 // crash the app
4779 if ( event.GetKeyCode() != WXK_F2 && editor->IsCreated() && m_cellEditCtrlEnabled )
4780 editor->StartingKey(event);
4781 }
4782 else
4783 {
4784 event.Skip();
4785 }
4786
4787 editor->DecRef();
4788 attr->DecRef();
4789 }
4790 else
4791 {
4792 event.Skip();
4793 }
4794 }
4795
4796 void wxGrid::OnEraseBackground(wxEraseEvent&)
4797 {
4798 }
4799
4800 bool wxGrid::SetCurrentCell( const wxGridCellCoords& coords )
4801 {
4802 if ( SendEvent(wxEVT_GRID_SELECT_CELL, coords) == -1 )
4803 {
4804 // the event has been vetoed - do nothing
4805 return false;
4806 }
4807
4808 #if !defined(__WXMAC__)
4809 wxClientDC dc( m_gridWin );
4810 PrepareDC( dc );
4811 #endif
4812
4813 if ( m_currentCellCoords != wxGridNoCellCoords )
4814 {
4815 DisableCellEditControl();
4816
4817 if ( IsVisible( m_currentCellCoords, false ) )
4818 {
4819 wxRect r;
4820 r = BlockToDeviceRect( m_currentCellCoords, m_currentCellCoords );
4821 if ( !m_gridLinesEnabled )
4822 {
4823 r.x--;
4824 r.y--;
4825 r.width++;
4826 r.height++;
4827 }
4828
4829 wxGridCellCoordsArray cells = CalcCellsExposed( r );
4830
4831 // Otherwise refresh redraws the highlight!
4832 m_currentCellCoords = coords;
4833
4834 #if defined(__WXMAC__)
4835 m_gridWin->Refresh(true /*, & r */);
4836 #else
4837 DrawGridCellArea( dc, cells );
4838 DrawAllGridLines( dc, r );
4839 #endif
4840 }
4841 }
4842
4843 m_currentCellCoords = coords;
4844
4845 wxGridCellAttr *attr = GetCellAttr( coords );
4846 #if !defined(__WXMAC__)
4847 DrawCellHighlight( dc, attr );
4848 #endif
4849 attr->DecRef();
4850
4851 return true;
4852 }
4853
4854 void
4855 wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol,
4856 int bottomRow, int rightCol)
4857 {
4858 if ( m_selection )
4859 {
4860 switch ( m_selection->GetSelectionMode() )
4861 {
4862 default:
4863 wxFAIL_MSG( "unknown selection mode" );
4864 // fall through
4865
4866 case wxGridSelectCells:
4867 // arbitrary blocks selection allowed so just use the cell
4868 // coordinates as is
4869 break;
4870
4871 case wxGridSelectRows:
4872 // only full rows selection allowd, ensure that we do select
4873 // full rows
4874 leftCol = 0;
4875 rightCol = GetNumberCols() - 1;
4876 break;
4877
4878 case wxGridSelectColumns:
4879 // same as above but for columns
4880 topRow = 0;
4881 bottomRow = GetNumberRows() - 1;
4882 break;
4883
4884 case wxGridSelectRowsOrColumns:
4885 // in this mode we can select only full rows or full columns so
4886 // it doesn't make sense to select blocks at all (and we can't
4887 // extend the block because there is no preferred direction, we
4888 // could only extend it to cover the entire grid but this is
4889 // not useful)
4890 return;
4891 }
4892 }
4893
4894 m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol);
4895 MakeCellVisible(m_selectedBlockCorner);
4896
4897 EnsureFirstLessThanSecond(topRow, bottomRow);
4898 EnsureFirstLessThanSecond(leftCol, rightCol);
4899
4900 wxGridCellCoords updateTopLeft = wxGridCellCoords(topRow, leftCol),
4901 updateBottomRight = wxGridCellCoords(bottomRow, rightCol);
4902
4903 // First the case that we selected a completely new area
4904 if ( m_selectedBlockTopLeft == wxGridNoCellCoords ||
4905 m_selectedBlockBottomRight == wxGridNoCellCoords )
4906 {
4907 wxRect rect;
4908 rect = BlockToDeviceRect( wxGridCellCoords ( topRow, leftCol ),
4909 wxGridCellCoords ( bottomRow, rightCol ) );
4910 m_gridWin->Refresh( false, &rect );
4911 }
4912
4913 // Now handle changing an existing selection area.
4914 else if ( m_selectedBlockTopLeft != updateTopLeft ||
4915 m_selectedBlockBottomRight != updateBottomRight )
4916 {
4917 // Compute two optimal update rectangles:
4918 // Either one rectangle is a real subset of the
4919 // other, or they are (almost) disjoint!
4920 wxRect rect[4];
4921 bool need_refresh[4];
4922 need_refresh[0] =
4923 need_refresh[1] =
4924 need_refresh[2] =
4925 need_refresh[3] = false;
4926 int i;
4927
4928 // Store intermediate values
4929 wxCoord oldLeft = m_selectedBlockTopLeft.GetCol();
4930 wxCoord oldTop = m_selectedBlockTopLeft.GetRow();
4931 wxCoord oldRight = m_selectedBlockBottomRight.GetCol();
4932 wxCoord oldBottom = m_selectedBlockBottomRight.GetRow();
4933
4934 // Determine the outer/inner coordinates.
4935 EnsureFirstLessThanSecond(oldLeft, leftCol);
4936 EnsureFirstLessThanSecond(oldTop, topRow);
4937 EnsureFirstLessThanSecond(rightCol, oldRight);
4938 EnsureFirstLessThanSecond(bottomRow, oldBottom);
4939
4940 // Now, either the stuff marked old is the outer
4941 // rectangle or we don't have a situation where one
4942 // is contained in the other.
4943
4944 if ( oldLeft < leftCol )
4945 {
4946 // Refresh the newly selected or deselected
4947 // area to the left of the old or new selection.
4948 need_refresh[0] = true;
4949 rect[0] = BlockToDeviceRect(
4950 wxGridCellCoords( oldTop, oldLeft ),
4951 wxGridCellCoords( oldBottom, leftCol - 1 ) );
4952 }
4953
4954 if ( oldTop < topRow )
4955 {
4956 // Refresh the newly selected or deselected
4957 // area above the old or new selection.
4958 need_refresh[1] = true;
4959 rect[1] = BlockToDeviceRect(
4960 wxGridCellCoords( oldTop, leftCol ),
4961 wxGridCellCoords( topRow - 1, rightCol ) );
4962 }
4963
4964 if ( oldRight > rightCol )
4965 {
4966 // Refresh the newly selected or deselected
4967 // area to the right of the old or new selection.
4968 need_refresh[2] = true;
4969 rect[2] = BlockToDeviceRect(
4970 wxGridCellCoords( oldTop, rightCol + 1 ),
4971 wxGridCellCoords( oldBottom, oldRight ) );
4972 }
4973
4974 if ( oldBottom > bottomRow )
4975 {
4976 // Refresh the newly selected or deselected
4977 // area below the old or new selection.
4978 need_refresh[3] = true;
4979 rect[3] = BlockToDeviceRect(
4980 wxGridCellCoords( bottomRow + 1, leftCol ),
4981 wxGridCellCoords( oldBottom, rightCol ) );
4982 }
4983
4984 // various Refresh() calls
4985 for (i = 0; i < 4; i++ )
4986 if ( need_refresh[i] && rect[i] != wxGridNoCellRect )
4987 m_gridWin->Refresh( false, &(rect[i]) );
4988 }
4989
4990 // change selection
4991 m_selectedBlockTopLeft = updateTopLeft;
4992 m_selectedBlockBottomRight = updateBottomRight;
4993 }
4994
4995 //
4996 // ------ functions to get/send data (see also public functions)
4997 //
4998
4999 bool wxGrid::GetModelValues()
5000 {
5001 // Hide the editor, so it won't hide a changed value.
5002 HideCellEditControl();
5003
5004 if ( m_table )
5005 {
5006 // all we need to do is repaint the grid
5007 //
5008 m_gridWin->Refresh();
5009 return true;
5010 }
5011
5012 return false;
5013 }
5014
5015 bool wxGrid::SetModelValues()
5016 {
5017 int row, col;
5018
5019 // Disable the editor, so it won't hide a changed value.
5020 // Do we also want to save the current value of the editor first?
5021 // I think so ...
5022 DisableCellEditControl();
5023
5024 if ( m_table )
5025 {
5026 for ( row = 0; row < m_numRows; row++ )
5027 {
5028 for ( col = 0; col < m_numCols; col++ )
5029 {
5030 m_table->SetValue( row, col, GetCellValue(row, col) );
5031 }
5032 }
5033
5034 return true;
5035 }
5036
5037 return false;
5038 }
5039
5040 // Note - this function only draws cells that are in the list of
5041 // exposed cells (usually set from the update region by
5042 // CalcExposedCells)
5043 //
5044 void wxGrid::DrawGridCellArea( wxDC& dc, const wxGridCellCoordsArray& cells )
5045 {
5046 if ( !m_numRows || !m_numCols )
5047 return;
5048
5049 int i, numCells = cells.GetCount();
5050 int row, col, cell_rows, cell_cols;
5051 wxGridCellCoordsArray redrawCells;
5052
5053 for ( i = numCells - 1; i >= 0; i-- )
5054 {
5055 row = cells[i].GetRow();
5056 col = cells[i].GetCol();
5057 GetCellSize( row, col, &cell_rows, &cell_cols );
5058
5059 // If this cell is part of a multicell block, find owner for repaint
5060 if ( cell_rows <= 0 || cell_cols <= 0 )
5061 {
5062 wxGridCellCoords cell( row + cell_rows, col + cell_cols );
5063 bool marked = false;
5064 for ( int j = 0; j < numCells; j++ )
5065 {
5066 if ( cell == cells[j] )
5067 {
5068 marked = true;
5069 break;
5070 }
5071 }
5072
5073 if (!marked)
5074 {
5075 int count = redrawCells.GetCount();
5076 for (int j = 0; j < count; j++)
5077 {
5078 if ( cell == redrawCells[j] )
5079 {
5080 marked = true;
5081 break;
5082 }
5083 }
5084
5085 if (!marked)
5086 redrawCells.Add( cell );
5087 }
5088
5089 // don't bother drawing this cell
5090 continue;
5091 }
5092
5093 // If this cell is empty, find cell to left that might want to overflow
5094 if (m_table && m_table->IsEmptyCell(row, col))
5095 {
5096 for ( int l = 0; l < cell_rows; l++ )
5097 {
5098 // find a cell in this row to leave already marked for repaint
5099 int left = col;
5100 for (int k = 0; k < int(redrawCells.GetCount()); k++)
5101 if ((redrawCells[k].GetCol() < left) &&
5102 (redrawCells[k].GetRow() == row))
5103 {
5104 left = redrawCells[k].GetCol();
5105 }
5106
5107 if (left == col)
5108 left = 0; // oh well
5109
5110 for (int j = col - 1; j >= left; j--)
5111 {
5112 if (!m_table->IsEmptyCell(row + l, j))
5113 {
5114 if (GetCellOverflow(row + l, j))
5115 {
5116 wxGridCellCoords cell(row + l, j);
5117 bool marked = false;
5118
5119 for (int k = 0; k < numCells; k++)
5120 {
5121 if ( cell == cells[k] )
5122 {
5123 marked = true;
5124 break;
5125 }
5126 }
5127
5128 if (!marked)
5129 {
5130 int count = redrawCells.GetCount();
5131 for (int k = 0; k < count; k++)
5132 {
5133 if ( cell == redrawCells[k] )
5134 {
5135 marked = true;
5136 break;
5137 }
5138 }
5139 if (!marked)
5140 redrawCells.Add( cell );
5141 }
5142 }
5143 break;
5144 }
5145 }
5146 }
5147 }
5148
5149 DrawCell( dc, cells[i] );
5150 }
5151
5152 numCells = redrawCells.GetCount();
5153
5154 for ( i = numCells - 1; i >= 0; i-- )
5155 {
5156 DrawCell( dc, redrawCells[i] );
5157 }
5158 }
5159
5160 void wxGrid::DrawGridSpace( wxDC& dc )
5161 {
5162 int cw, ch;
5163 m_gridWin->GetClientSize( &cw, &ch );
5164
5165 int right, bottom;
5166 CalcUnscrolledPosition( cw, ch, &right, &bottom );
5167
5168 int rightCol = m_numCols > 0 ? GetColRight(GetColAt( m_numCols - 1 )) : 0;
5169 int bottomRow = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
5170
5171 if ( right > rightCol || bottom > bottomRow )
5172 {
5173 int left, top;
5174 CalcUnscrolledPosition( 0, 0, &left, &top );
5175
5176 dc.SetBrush(GetDefaultCellBackgroundColour());
5177 dc.SetPen( *wxTRANSPARENT_PEN );
5178
5179 if ( right > rightCol )
5180 {
5181 dc.DrawRectangle( rightCol, top, right - rightCol, ch );
5182 }
5183
5184 if ( bottom > bottomRow )
5185 {
5186 dc.DrawRectangle( left, bottomRow, cw, bottom - bottomRow );
5187 }
5188 }
5189 }
5190
5191 void wxGrid::DrawCell( wxDC& dc, const wxGridCellCoords& coords )
5192 {
5193 int row = coords.GetRow();
5194 int col = coords.GetCol();
5195
5196 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
5197 return;
5198
5199 // we draw the cell border ourselves
5200 wxGridCellAttr* attr = GetCellAttr(row, col);
5201
5202 bool isCurrent = coords == m_currentCellCoords;
5203
5204 wxRect rect = CellToRect( row, col );
5205
5206 // if the editor is shown, we should use it and not the renderer
5207 // Note: However, only if it is really _shown_, i.e. not hidden!
5208 if ( isCurrent && IsCellEditControlShown() )
5209 {
5210 // NB: this "#if..." is temporary and fixes a problem where the
5211 // edit control is erased by this code after being rendered.
5212 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
5213 // implicitly, causing this out-of order render.
5214 #if !defined(__WXMAC__)
5215 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
5216 editor->PaintBackground(rect, attr);
5217 editor->DecRef();
5218 #endif
5219 }
5220 else
5221 {
5222 // but all the rest is drawn by the cell renderer and hence may be customized
5223 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
5224 renderer->Draw(*this, *attr, dc, rect, row, col, IsInSelection(coords));
5225 renderer->DecRef();
5226 }
5227
5228 attr->DecRef();
5229 }
5230
5231 void wxGrid::DrawCellHighlight( wxDC& dc, const wxGridCellAttr *attr )
5232 {
5233 // don't show highlight when the grid doesn't have focus
5234 if ( !HasFocus() )
5235 return;
5236
5237 int row = m_currentCellCoords.GetRow();
5238 int col = m_currentCellCoords.GetCol();
5239
5240 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
5241 return;
5242
5243 wxRect rect = CellToRect(row, col);
5244
5245 // hmmm... what could we do here to show that the cell is disabled?
5246 // for now, I just draw a thinner border than for the other ones, but
5247 // it doesn't look really good
5248
5249 int penWidth = attr->IsReadOnly() ? m_cellHighlightROPenWidth : m_cellHighlightPenWidth;
5250
5251 if (penWidth > 0)
5252 {
5253 // The center of the drawn line is where the position/width/height of
5254 // the rectangle is actually at (on wxMSW at least), so the
5255 // size of the rectangle is reduced to compensate for the thickness of
5256 // the line. If this is too strange on non-wxMSW platforms then
5257 // please #ifdef this appropriately.
5258 rect.x += penWidth / 2;
5259 rect.y += penWidth / 2;
5260 rect.width -= penWidth - 1;
5261 rect.height -= penWidth - 1;
5262
5263 // Now draw the rectangle
5264 // use the cellHighlightColour if the cell is inside a selection, this
5265 // will ensure the cell is always visible.
5266 dc.SetPen(wxPen(IsInSelection(row,col) ? m_selectionForeground
5267 : m_cellHighlightColour,
5268 penWidth));
5269 dc.SetBrush(*wxTRANSPARENT_BRUSH);
5270 dc.DrawRectangle(rect);
5271 }
5272 }
5273
5274 wxPen wxGrid::GetDefaultGridLinePen()
5275 {
5276 return wxPen(GetGridLineColour());
5277 }
5278
5279 wxPen wxGrid::GetRowGridLinePen(int WXUNUSED(row))
5280 {
5281 return GetDefaultGridLinePen();
5282 }
5283
5284 wxPen wxGrid::GetColGridLinePen(int WXUNUSED(col))
5285 {
5286 return GetDefaultGridLinePen();
5287 }
5288
5289 void wxGrid::DrawCellBorder( wxDC& dc, const wxGridCellCoords& coords )
5290 {
5291 int row = coords.GetRow();
5292 int col = coords.GetCol();
5293 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
5294 return;
5295
5296
5297 wxRect rect = CellToRect( row, col );
5298
5299 // right hand border
5300 dc.SetPen( GetColGridLinePen(col) );
5301 dc.DrawLine( rect.x + rect.width, rect.y,
5302 rect.x + rect.width, rect.y + rect.height + 1 );
5303
5304 // bottom border
5305 dc.SetPen( GetRowGridLinePen(row) );
5306 dc.DrawLine( rect.x, rect.y + rect.height,
5307 rect.x + rect.width, rect.y + rect.height);
5308 }
5309
5310 void wxGrid::DrawHighlight(wxDC& dc, const wxGridCellCoordsArray& cells)
5311 {
5312 // This if block was previously in wxGrid::OnPaint but that doesn't
5313 // seem to get called under wxGTK - MB
5314 //
5315 if ( m_currentCellCoords == wxGridNoCellCoords &&
5316 m_numRows && m_numCols )
5317 {
5318 m_currentCellCoords.Set(0, 0);
5319 }
5320
5321 if ( IsCellEditControlShown() )
5322 {
5323 // don't show highlight when the edit control is shown
5324 return;
5325 }
5326
5327 // if the active cell was repainted, repaint its highlight too because it
5328 // might have been damaged by the grid lines
5329 size_t count = cells.GetCount();
5330 for ( size_t n = 0; n < count; n++ )
5331 {
5332 wxGridCellCoords cell = cells[n];
5333
5334 // If we are using attributes, then we may have just exposed another
5335 // cell in a partially-visible merged cluster of cells. If the "anchor"
5336 // (upper left) cell of this merged cluster is the cell indicated by
5337 // m_currentCellCoords, then we need to refresh the cell highlight even
5338 // though the "anchor" itself is not part of our update segment.
5339 if ( CanHaveAttributes() )
5340 {
5341 int rows = 0,
5342 cols = 0;
5343 GetCellSize(cell.GetRow(), cell.GetCol(), &rows, &cols);
5344
5345 if ( rows < 0 )
5346 cell.SetRow(cell.GetRow() + rows);
5347
5348 if ( cols < 0 )
5349 cell.SetCol(cell.GetCol() + cols);
5350 }
5351
5352 if ( cell == m_currentCellCoords )
5353 {
5354 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
5355 DrawCellHighlight(dc, attr);
5356 attr->DecRef();
5357
5358 break;
5359 }
5360 }
5361 }
5362
5363 // This is used to redraw all grid lines e.g. when the grid line colour
5364 // has been changed
5365 //
5366 void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) )
5367 {
5368 if ( !m_gridLinesEnabled )
5369 return;
5370
5371 int top, bottom, left, right;
5372
5373 int cw, ch;
5374 m_gridWin->GetClientSize(&cw, &ch);
5375 CalcUnscrolledPosition( 0, 0, &left, &top );
5376 CalcUnscrolledPosition( cw, ch, &right, &bottom );
5377
5378 // avoid drawing grid lines past the last row and col
5379 if ( m_gridLinesClipHorz )
5380 {
5381 if ( !m_numCols )
5382 return;
5383
5384 const int lastColRight = GetColRight(GetColAt(m_numCols - 1));
5385 if ( right > lastColRight )
5386 right = lastColRight;
5387 }
5388
5389 if ( m_gridLinesClipVert )
5390 {
5391 if ( !m_numRows )
5392 return;
5393
5394 const int lastRowBottom = GetRowBottom(m_numRows - 1);
5395 if ( bottom > lastRowBottom )
5396 bottom = lastRowBottom;
5397 }
5398
5399 // no gridlines inside multicells, clip them out
5400 int leftCol = GetColPos( internalXToCol(left) );
5401 int topRow = internalYToRow(top);
5402 int rightCol = GetColPos( internalXToCol(right) );
5403 int bottomRow = internalYToRow(bottom);
5404
5405 wxRegion clippedcells(0, 0, cw, ch);
5406
5407 int cell_rows, cell_cols;
5408 wxRect rect;
5409
5410 for ( int j = topRow; j <= bottomRow; j++ )
5411 {
5412 for ( int colPos = leftCol; colPos <= rightCol; colPos++ )
5413 {
5414 int i = GetColAt( colPos );
5415
5416 GetCellSize( j, i, &cell_rows, &cell_cols );
5417 if ((cell_rows > 1) || (cell_cols > 1))
5418 {
5419 rect = CellToRect(j,i);
5420 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
5421 clippedcells.Subtract(rect);
5422 }
5423 else if ((cell_rows < 0) || (cell_cols < 0))
5424 {
5425 rect = CellToRect(j + cell_rows, i + cell_cols);
5426 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
5427 clippedcells.Subtract(rect);
5428 }
5429 }
5430 }
5431
5432 dc.SetDeviceClippingRegion( clippedcells );
5433
5434
5435 // horizontal grid lines
5436 for ( int i = internalYToRow(top); i < m_numRows; i++ )
5437 {
5438 int bot = GetRowBottom(i) - 1;
5439
5440 if ( bot > bottom )
5441 break;
5442
5443 if ( bot >= top )
5444 {
5445 dc.SetPen( GetRowGridLinePen(i) );
5446 dc.DrawLine( left, bot, right, bot );
5447 }
5448 }
5449
5450 // vertical grid lines
5451 for ( int colPos = leftCol; colPos < m_numCols; colPos++ )
5452 {
5453 int i = GetColAt( colPos );
5454
5455 int colRight = GetColRight(i);
5456 #ifdef __WXGTK__
5457 if (GetLayoutDirection() != wxLayout_RightToLeft)
5458 #endif
5459 colRight--;
5460
5461 if ( colRight > right )
5462 break;
5463
5464 if ( colRight >= left )
5465 {
5466 dc.SetPen( GetColGridLinePen(i) );
5467 dc.DrawLine( colRight, top, colRight, bottom );
5468 }
5469 }
5470
5471 dc.DestroyClippingRegion();
5472 }
5473
5474 void wxGrid::DrawRowLabels( wxDC& dc, const wxArrayInt& rows)
5475 {
5476 if ( !m_numRows )
5477 return;
5478
5479 const size_t numLabels = rows.GetCount();
5480 for ( size_t i = 0; i < numLabels; i++ )
5481 {
5482 DrawRowLabel( dc, rows[i] );
5483 }
5484 }
5485
5486 void wxGrid::DrawRowLabel( wxDC& dc, int row )
5487 {
5488 if ( GetRowHeight(row) <= 0 || m_rowLabelWidth <= 0 )
5489 return;
5490
5491 wxGridCellAttrProvider * const
5492 attrProvider = m_table ? m_table->GetAttrProvider() : NULL;
5493
5494 // notice that an explicit static_cast is needed to avoid a compilation
5495 // error with VC7.1 which, for some reason, tries to instantiate (abstract)
5496 // wxGridRowHeaderRenderer class without it
5497 const wxGridRowHeaderRenderer&
5498 rend = attrProvider ? attrProvider->GetRowHeaderRenderer(row)
5499 : static_cast<const wxGridRowHeaderRenderer&>
5500 (gs_defaultHeaderRenderers.rowRenderer);
5501
5502 wxRect rect(0, GetRowTop(row), m_rowLabelWidth, GetRowHeight(row));
5503 rend.DrawBorder(*this, dc, rect);
5504
5505 int hAlign, vAlign;
5506 GetRowLabelAlignment(&hAlign, &vAlign);
5507
5508 rend.DrawLabel(*this, dc, GetRowLabelValue(row),
5509 rect, hAlign, vAlign, wxHORIZONTAL);
5510 }
5511
5512 void wxGrid::UseNativeColHeader(bool native)
5513 {
5514 if ( native == m_useNativeHeader )
5515 return;
5516
5517 delete m_colWindow;
5518 m_useNativeHeader = native;
5519
5520 CreateColumnWindow();
5521
5522 if ( m_useNativeHeader )
5523 GetGridColHeader()->SetColumnCount(m_numCols);
5524 CalcWindowSizes();
5525 }
5526
5527 void wxGrid::SetUseNativeColLabels( bool native )
5528 {
5529 wxASSERT_MSG( !m_useNativeHeader,
5530 "doesn't make sense when using native header" );
5531
5532 m_nativeColumnLabels = native;
5533 if (native)
5534 {
5535 int height = wxRendererNative::Get().GetHeaderButtonHeight( this );
5536 SetColLabelSize( height );
5537 }
5538
5539 GetColLabelWindow()->Refresh();
5540 m_cornerLabelWin->Refresh();
5541 }
5542
5543 void wxGrid::DrawColLabels( wxDC& dc,const wxArrayInt& cols )
5544 {
5545 if ( !m_numCols )
5546 return;
5547
5548 const size_t numLabels = cols.GetCount();
5549 for ( size_t i = 0; i < numLabels; i++ )
5550 {
5551 DrawColLabel( dc, cols[i] );
5552 }
5553 }
5554
5555 void wxGrid::DrawCornerLabel(wxDC& dc)
5556 {
5557 wxRect rect(wxSize(m_rowLabelWidth, m_colLabelHeight));
5558
5559 if ( m_nativeColumnLabels )
5560 {
5561 rect.Deflate(1);
5562
5563 wxRendererNative::Get().DrawHeaderButton(m_cornerLabelWin, dc, rect, 0);
5564 }
5565 else
5566 {
5567 rect.width++;
5568 rect.height++;
5569
5570 wxGridCellAttrProvider * const
5571 attrProvider = m_table ? m_table->GetAttrProvider() : NULL;
5572 const wxGridCornerHeaderRenderer&
5573 rend = attrProvider ? attrProvider->GetCornerRenderer()
5574 : static_cast<wxGridCornerHeaderRenderer&>
5575 (gs_defaultHeaderRenderers.cornerRenderer);
5576
5577 rend.DrawBorder(*this, dc, rect);
5578 }
5579 }
5580
5581 void wxGrid::DrawColLabel(wxDC& dc, int col)
5582 {
5583 if ( GetColWidth(col) <= 0 || m_colLabelHeight <= 0 )
5584 return;
5585
5586 int colLeft = GetColLeft(col);
5587
5588 wxRect rect(colLeft, 0, GetColWidth(col), m_colLabelHeight);
5589 wxGridCellAttrProvider * const
5590 attrProvider = m_table ? m_table->GetAttrProvider() : NULL;
5591 const wxGridColumnHeaderRenderer&
5592 rend = attrProvider ? attrProvider->GetColumnHeaderRenderer(col)
5593 : static_cast<wxGridColumnHeaderRenderer&>
5594 (gs_defaultHeaderRenderers.colRenderer);
5595
5596 if ( m_nativeColumnLabels )
5597 {
5598 wxRendererNative::Get().DrawHeaderButton
5599 (
5600 GetColLabelWindow(),
5601 dc,
5602 rect,
5603 0,
5604 IsSortingBy(col)
5605 ? IsSortOrderAscending()
5606 ? wxHDR_SORT_ICON_UP
5607 : wxHDR_SORT_ICON_DOWN
5608 : wxHDR_SORT_ICON_NONE
5609 );
5610 rect.Deflate(2);
5611 }
5612 else
5613 {
5614 // It is reported that we need to erase the background to avoid display
5615 // artefacts, see #12055.
5616 wxDCBrushChanger setBrush(dc, m_colWindow->GetBackgroundColour());
5617 dc.DrawRectangle(rect);
5618
5619 rend.DrawBorder(*this, dc, rect);
5620 }
5621
5622 int hAlign, vAlign;
5623 GetColLabelAlignment(&hAlign, &vAlign);
5624 const int orient = GetColLabelTextOrientation();
5625
5626 rend.DrawLabel(*this, dc, GetColLabelValue(col), rect, hAlign, vAlign, orient);
5627 }
5628
5629 // TODO: these 2 functions should be replaced with wxDC::DrawLabel() to which
5630 // we just have to add textOrientation support
5631 void wxGrid::DrawTextRectangle( wxDC& dc,
5632 const wxString& value,
5633 const wxRect& rect,
5634 int horizAlign,
5635 int vertAlign,
5636 int textOrientation ) const
5637 {
5638 wxArrayString lines;
5639
5640 StringToLines( value, lines );
5641
5642 DrawTextRectangle(dc, lines, rect, horizAlign, vertAlign, textOrientation);
5643 }
5644
5645 void wxGrid::DrawTextRectangle(wxDC& dc,
5646 const wxArrayString& lines,
5647 const wxRect& rect,
5648 int horizAlign,
5649 int vertAlign,
5650 int textOrientation) const
5651 {
5652 if ( lines.empty() )
5653 return;
5654
5655 wxDCClipper clip(dc, rect);
5656
5657 long textWidth,
5658 textHeight;
5659
5660 if ( textOrientation == wxHORIZONTAL )
5661 GetTextBoxSize( dc, lines, &textWidth, &textHeight );
5662 else
5663 GetTextBoxSize( dc, lines, &textHeight, &textWidth );
5664
5665 int x = 0,
5666 y = 0;
5667 switch ( vertAlign )
5668 {
5669 case wxALIGN_BOTTOM:
5670 if ( textOrientation == wxHORIZONTAL )
5671 y = rect.y + (rect.height - textHeight - 1);
5672 else
5673 x = rect.x + rect.width - textWidth;
5674 break;
5675
5676 case wxALIGN_CENTRE:
5677 if ( textOrientation == wxHORIZONTAL )
5678 y = rect.y + ((rect.height - textHeight) / 2);
5679 else
5680 x = rect.x + ((rect.width - textWidth) / 2);
5681 break;
5682
5683 case wxALIGN_TOP:
5684 default:
5685 if ( textOrientation == wxHORIZONTAL )
5686 y = rect.y + 1;
5687 else
5688 x = rect.x + 1;
5689 break;
5690 }
5691
5692 // Align each line of a multi-line label
5693 size_t nLines = lines.GetCount();
5694 for ( size_t l = 0; l < nLines; l++ )
5695 {
5696 const wxString& line = lines[l];
5697
5698 if ( line.empty() )
5699 {
5700 *(textOrientation == wxHORIZONTAL ? &y : &x) += dc.GetCharHeight();
5701 continue;
5702 }
5703
5704 wxCoord lineWidth = 0,
5705 lineHeight = 0;
5706 dc.GetTextExtent(line, &lineWidth, &lineHeight);
5707
5708 switch ( horizAlign )
5709 {
5710 case wxALIGN_RIGHT:
5711 if ( textOrientation == wxHORIZONTAL )
5712 x = rect.x + (rect.width - lineWidth - 1);
5713 else
5714 y = rect.y + lineWidth + 1;
5715 break;
5716
5717 case wxALIGN_CENTRE:
5718 if ( textOrientation == wxHORIZONTAL )
5719 x = rect.x + ((rect.width - lineWidth) / 2);
5720 else
5721 y = rect.y + rect.height - ((rect.height - lineWidth) / 2);
5722 break;
5723
5724 case wxALIGN_LEFT:
5725 default:
5726 if ( textOrientation == wxHORIZONTAL )
5727 x = rect.x + 1;
5728 else
5729 y = rect.y + rect.height - 1;
5730 break;
5731 }
5732
5733 if ( textOrientation == wxHORIZONTAL )
5734 {
5735 dc.DrawText( line, x, y );
5736 y += lineHeight;
5737 }
5738 else
5739 {
5740 dc.DrawRotatedText( line, x, y, 90.0 );
5741 x += lineHeight;
5742 }
5743 }
5744 }
5745
5746 // Split multi-line text up into an array of strings.
5747 // Any existing contents of the string array are preserved.
5748 //
5749 // TODO: refactor wxTextFile::Read() and reuse the same code from here
5750 void wxGrid::StringToLines( const wxString& value, wxArrayString& lines ) const
5751 {
5752 int startPos = 0;
5753 int pos;
5754 wxString eol = wxTextFile::GetEOL( wxTextFileType_Unix );
5755 wxString tVal = wxTextFile::Translate( value, wxTextFileType_Unix );
5756
5757 while ( startPos < (int)tVal.length() )
5758 {
5759 pos = tVal.Mid(startPos).Find( eol );
5760 if ( pos < 0 )
5761 {
5762 break;
5763 }
5764 else if ( pos == 0 )
5765 {
5766 lines.Add( wxEmptyString );
5767 }
5768 else
5769 {
5770 lines.Add( tVal.Mid(startPos, pos) );
5771 }
5772
5773 startPos += pos + 1;
5774 }
5775
5776 if ( startPos < (int)tVal.length() )
5777 {
5778 lines.Add( tVal.Mid( startPos ) );
5779 }
5780 }
5781
5782 void wxGrid::GetTextBoxSize( const wxDC& dc,
5783 const wxArrayString& lines,
5784 long *width, long *height ) const
5785 {
5786 wxCoord w = 0;
5787 wxCoord h = 0;
5788 wxCoord lineW = 0, lineH = 0;
5789
5790 size_t i;
5791 for ( i = 0; i < lines.GetCount(); i++ )
5792 {
5793 dc.GetTextExtent( lines[i], &lineW, &lineH );
5794 w = wxMax( w, lineW );
5795 h += lineH;
5796 }
5797
5798 *width = w;
5799 *height = h;
5800 }
5801
5802 //
5803 // ------ Batch processing.
5804 //
5805 void wxGrid::EndBatch()
5806 {
5807 if ( m_batchCount > 0 )
5808 {
5809 m_batchCount--;
5810 if ( !m_batchCount )
5811 {
5812 CalcDimensions();
5813 m_rowLabelWin->Refresh();
5814 m_colWindow->Refresh();
5815 m_cornerLabelWin->Refresh();
5816 m_gridWin->Refresh();
5817 }
5818 }
5819 }
5820
5821 // Use this, rather than wxWindow::Refresh(), to force an immediate
5822 // repainting of the grid. Has no effect if you are already inside a
5823 // BeginBatch / EndBatch block.
5824 //
5825 void wxGrid::ForceRefresh()
5826 {
5827 BeginBatch();
5828 EndBatch();
5829 }
5830
5831 bool wxGrid::Enable(bool enable)
5832 {
5833 if ( !wxScrolledWindow::Enable(enable) )
5834 return false;
5835
5836 // redraw in the new state
5837 m_gridWin->Refresh();
5838
5839 return true;
5840 }
5841
5842 //
5843 // ------ Edit control functions
5844 //
5845
5846 void wxGrid::EnableEditing( bool edit )
5847 {
5848 if ( edit != m_editable )
5849 {
5850 if (!edit)
5851 EnableCellEditControl(edit);
5852 m_editable = edit;
5853 }
5854 }
5855
5856 void wxGrid::EnableCellEditControl( bool enable )
5857 {
5858 if (! m_editable)
5859 return;
5860
5861 if ( enable != m_cellEditCtrlEnabled )
5862 {
5863 if ( enable )
5864 {
5865 if ( SendEvent(wxEVT_GRID_EDITOR_SHOWN) == -1 )
5866 return;
5867
5868 // this should be checked by the caller!
5869 wxASSERT_MSG( CanEnableCellControl(), wxT("can't enable editing for this cell!") );
5870
5871 // do it before ShowCellEditControl()
5872 m_cellEditCtrlEnabled = enable;
5873
5874 ShowCellEditControl();
5875 }
5876 else
5877 {
5878 SendEvent(wxEVT_GRID_EDITOR_HIDDEN);
5879
5880 HideCellEditControl();
5881 SaveEditControlValue();
5882
5883 // do it after HideCellEditControl()
5884 m_cellEditCtrlEnabled = enable;
5885 }
5886 }
5887 }
5888
5889 bool wxGrid::IsCurrentCellReadOnly() const
5890 {
5891 // const_cast
5892 wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords);
5893 bool readonly = attr->IsReadOnly();
5894 attr->DecRef();
5895
5896 return readonly;
5897 }
5898
5899 bool wxGrid::CanEnableCellControl() const
5900 {
5901 return m_editable && (m_currentCellCoords != wxGridNoCellCoords) &&
5902 !IsCurrentCellReadOnly();
5903 }
5904
5905 bool wxGrid::IsCellEditControlEnabled() const
5906 {
5907 // the cell edit control might be disable for all cells or just for the
5908 // current one if it's read only
5909 return m_cellEditCtrlEnabled ? !IsCurrentCellReadOnly() : false;
5910 }
5911
5912 bool wxGrid::IsCellEditControlShown() const
5913 {
5914 bool isShown = false;
5915
5916 if ( m_cellEditCtrlEnabled )
5917 {
5918 int row = m_currentCellCoords.GetRow();
5919 int col = m_currentCellCoords.GetCol();
5920 wxGridCellAttr* attr = GetCellAttr(row, col);
5921 wxGridCellEditor* editor = attr->GetEditor((wxGrid*) this, row, col);
5922 attr->DecRef();
5923
5924 if ( editor )
5925 {
5926 if ( editor->IsCreated() )
5927 {
5928 isShown = editor->GetControl()->IsShown();
5929 }
5930
5931 editor->DecRef();
5932 }
5933 }
5934
5935 return isShown;
5936 }
5937
5938 void wxGrid::ShowCellEditControl()
5939 {
5940 if ( IsCellEditControlEnabled() )
5941 {
5942 if ( !IsVisible( m_currentCellCoords, false ) )
5943 {
5944 m_cellEditCtrlEnabled = false;
5945 return;
5946 }
5947 else
5948 {
5949 wxRect rect = CellToRect( m_currentCellCoords );
5950 int row = m_currentCellCoords.GetRow();
5951 int col = m_currentCellCoords.GetCol();
5952
5953 // if this is part of a multicell, find owner (topleft)
5954 int cell_rows, cell_cols;
5955 GetCellSize( row, col, &cell_rows, &cell_cols );
5956 if ( cell_rows <= 0 || cell_cols <= 0 )
5957 {
5958 row += cell_rows;
5959 col += cell_cols;
5960 m_currentCellCoords.SetRow( row );
5961 m_currentCellCoords.SetCol( col );
5962 }
5963
5964 // erase the highlight and the cell contents because the editor
5965 // might not cover the entire cell
5966 wxClientDC dc( m_gridWin );
5967 PrepareDC( dc );
5968 wxGridCellAttr* attr = GetCellAttr(row, col);
5969 dc.SetBrush(wxBrush(attr->GetBackgroundColour()));
5970 dc.SetPen(*wxTRANSPARENT_PEN);
5971 dc.DrawRectangle(rect);
5972
5973 // convert to scrolled coords
5974 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
5975
5976 int nXMove = 0;
5977 if (rect.x < 0)
5978 nXMove = rect.x;
5979
5980 // cell is shifted by one pixel
5981 // However, don't allow x or y to become negative
5982 // since the SetSize() method interprets that as
5983 // "don't change."
5984 if (rect.x > 0)
5985 rect.x--;
5986 if (rect.y > 0)
5987 rect.y--;
5988
5989 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
5990 if ( !editor->IsCreated() )
5991 {
5992 editor->Create(m_gridWin, wxID_ANY,
5993 new wxGridCellEditorEvtHandler(this, editor));
5994
5995 wxGridEditorCreatedEvent evt(GetId(),
5996 wxEVT_GRID_EDITOR_CREATED,
5997 this,
5998 row,
5999 col,
6000 editor->GetControl());
6001 GetEventHandler()->ProcessEvent(evt);
6002 }
6003
6004 // resize editor to overflow into righthand cells if allowed
6005 int maxWidth = rect.width;
6006 wxString value = GetCellValue(row, col);
6007 if ( (value != wxEmptyString) && (attr->GetOverflow()) )
6008 {
6009 int y;
6010 GetTextExtent(value, &maxWidth, &y, NULL, NULL, &attr->GetFont());
6011 if (maxWidth < rect.width)
6012 maxWidth = rect.width;
6013 }
6014
6015 int client_right = m_gridWin->GetClientSize().GetWidth();
6016 if (rect.x + maxWidth > client_right)
6017 maxWidth = client_right - rect.x;
6018
6019 if ((maxWidth > rect.width) && (col < m_numCols) && m_table)
6020 {
6021 GetCellSize( row, col, &cell_rows, &cell_cols );
6022 // may have changed earlier
6023 for (int i = col + cell_cols; i < m_numCols; i++)
6024 {
6025 int c_rows, c_cols;
6026 GetCellSize( row, i, &c_rows, &c_cols );
6027
6028 // looks weird going over a multicell
6029 if (m_table->IsEmptyCell( row, i ) &&
6030 (rect.width < maxWidth) && (c_rows == 1))
6031 {
6032 rect.width += GetColWidth( i );
6033 }
6034 else
6035 break;
6036 }
6037
6038 if (rect.GetRight() > client_right)
6039 rect.SetRight( client_right - 1 );
6040 }
6041
6042 editor->SetCellAttr( attr );
6043 editor->SetSize( rect );
6044 if (nXMove != 0)
6045 editor->GetControl()->Move(
6046 editor->GetControl()->GetPosition().x + nXMove,
6047 editor->GetControl()->GetPosition().y );
6048 editor->Show( true, attr );
6049
6050 // recalc dimensions in case we need to
6051 // expand the scrolled window to account for editor
6052 CalcDimensions();
6053
6054 editor->BeginEdit(row, col, this);
6055 editor->SetCellAttr(NULL);
6056
6057 editor->DecRef();
6058 attr->DecRef();
6059 }
6060 }
6061 }
6062
6063 void wxGrid::HideCellEditControl()
6064 {
6065 if ( IsCellEditControlEnabled() )
6066 {
6067 int row = m_currentCellCoords.GetRow();
6068 int col = m_currentCellCoords.GetCol();
6069
6070 wxGridCellAttr *attr = GetCellAttr(row, col);
6071 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
6072 const bool editorHadFocus = editor->GetControl()->HasFocus();
6073 editor->Show( false );
6074 editor->DecRef();
6075 attr->DecRef();
6076
6077 // return the focus to the grid itself if the editor had it
6078 //
6079 // note that we must not do this unconditionally to avoid stealing
6080 // focus from the window which just received it if we are hiding the
6081 // editor precisely because we lost focus
6082 if ( editorHadFocus )
6083 m_gridWin->SetFocus();
6084
6085 // refresh whole row to the right
6086 wxRect rect( CellToRect(row, col) );
6087 CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y );
6088 rect.width = m_gridWin->GetClientSize().GetWidth() - rect.x;
6089
6090 #ifdef __WXMAC__
6091 // ensure that the pixels under the focus ring get refreshed as well
6092 rect.Inflate(10, 10);
6093 #endif
6094
6095 m_gridWin->Refresh( false, &rect );
6096 }
6097 }
6098
6099 void wxGrid::SaveEditControlValue()
6100 {
6101 if ( IsCellEditControlEnabled() )
6102 {
6103 int row = m_currentCellCoords.GetRow();
6104 int col = m_currentCellCoords.GetCol();
6105
6106 wxString oldval = GetCellValue(row, col);
6107
6108 wxGridCellAttr* attr = GetCellAttr(row, col);
6109 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
6110
6111 wxString newval;
6112 bool changed = editor->EndEdit(row, col, this, oldval, &newval);
6113
6114 if ( changed && SendEvent(wxEVT_GRID_CELL_CHANGING, newval) != -1 )
6115 {
6116 editor->ApplyEdit(row, col, this);
6117
6118 // for compatibility reasons dating back to wx 2.8 when this event
6119 // was called wxEVT_GRID_CELL_CHANGE and wxEVT_GRID_CELL_CHANGING
6120 // didn't exist we allow vetoing this one too
6121 if ( SendEvent(wxEVT_GRID_CELL_CHANGED, oldval) == -1 )
6122 {
6123 // Event has been vetoed, set the data back.
6124 SetCellValue(row, col, oldval);
6125 }
6126 }
6127
6128 editor->DecRef();
6129 attr->DecRef();
6130 }
6131 }
6132
6133 //
6134 // ------ Grid location functions
6135 // Note that all of these functions work with the logical coordinates of
6136 // grid cells and labels so you will need to convert from device
6137 // coordinates for mouse events etc.
6138 //
6139
6140 wxGridCellCoords wxGrid::XYToCell(int x, int y) const
6141 {
6142 int row = YToRow(y);
6143 int col = XToCol(x);
6144
6145 return row == -1 || col == -1 ? wxGridNoCellCoords
6146 : wxGridCellCoords(row, col);
6147 }
6148
6149 // compute row or column from some (unscrolled) coordinate value, using either
6150 // m_defaultRowHeight/m_defaultColWidth or binary search on array of
6151 // m_rowBottoms/m_colRights to do it quickly (linear search shouldn't be used
6152 // for large grids)
6153 int wxGrid::PosToLinePos(int coord,
6154 bool clipToMinMax,
6155 const wxGridOperations& oper) const
6156 {
6157 const int numLines = oper.GetNumberOfLines(this);
6158
6159 if ( coord < 0 )
6160 return clipToMinMax && numLines > 0 ? 0 : wxNOT_FOUND;
6161
6162 const int defaultLineSize = oper.GetDefaultLineSize(this);
6163 wxCHECK_MSG( defaultLineSize, -1, "can't have 0 default line size" );
6164
6165 int maxPos = coord / defaultLineSize,
6166 minPos = 0;
6167
6168 // check for the simplest case: if we have no explicit line sizes
6169 // configured, then we already know the line this position falls in
6170 const wxArrayInt& lineEnds = oper.GetLineEnds(this);
6171 if ( lineEnds.empty() )
6172 {
6173 if ( maxPos < numLines )
6174 return maxPos;
6175
6176 return clipToMinMax ? numLines - 1 : -1;
6177 }
6178
6179
6180 // adjust maxPos before starting the binary search
6181 if ( maxPos >= numLines )
6182 {
6183 maxPos = numLines - 1;
6184 }
6185 else
6186 {
6187 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos)])
6188 {
6189 minPos = maxPos;
6190 const int minDist = oper.GetMinimalAcceptableLineSize(this);
6191 if ( minDist )
6192 maxPos = coord / minDist;
6193 else
6194 maxPos = numLines - 1;
6195 }
6196
6197 if ( maxPos >= numLines )
6198 maxPos = numLines - 1;
6199 }
6200
6201 // check if the position is beyond the last column
6202 const int lineAtMaxPos = oper.GetLineAt(this, maxPos);
6203 if ( coord >= lineEnds[lineAtMaxPos] )
6204 return clipToMinMax ? maxPos : -1;
6205
6206 // or before the first one
6207 const int lineAt0 = oper.GetLineAt(this, 0);
6208 if ( coord < lineEnds[lineAt0] )
6209 return 0;
6210
6211
6212 // finally do perform the binary search
6213 while ( minPos < maxPos )
6214 {
6215 wxCHECK_MSG( lineEnds[oper.GetLineAt(this, minPos)] <= coord &&
6216 coord < lineEnds[oper.GetLineAt(this, maxPos)],
6217 -1,
6218 "wxGrid: internal error in PosToLinePos()" );
6219
6220 if ( coord >= lineEnds[oper.GetLineAt(this, maxPos - 1)] )
6221 return maxPos;
6222 else
6223 maxPos--;
6224
6225 const int median = minPos + (maxPos - minPos + 1) / 2;
6226 if ( coord < lineEnds[oper.GetLineAt(this, median)] )
6227 maxPos = median;
6228 else
6229 minPos = median;
6230 }
6231
6232 return maxPos;
6233 }
6234
6235 int
6236 wxGrid::PosToLine(int coord,
6237 bool clipToMinMax,
6238 const wxGridOperations& oper) const
6239 {
6240 int pos = PosToLinePos(coord, clipToMinMax, oper);
6241
6242 return pos == wxNOT_FOUND ? wxNOT_FOUND : oper.GetLineAt(this, pos);
6243 }
6244
6245 int wxGrid::YToRow(int y, bool clipToMinMax) const
6246 {
6247 return PosToLine(y, clipToMinMax, wxGridRowOperations());
6248 }
6249
6250 int wxGrid::XToCol(int x, bool clipToMinMax) const
6251 {
6252 return PosToLine(x, clipToMinMax, wxGridColumnOperations());
6253 }
6254
6255 int wxGrid::XToPos(int x) const
6256 {
6257 return PosToLinePos(x, true /* clip */, wxGridColumnOperations());
6258 }
6259
6260 // return the row number such that the y coord is near the edge of, or -1 if
6261 // not near an edge.
6262 //
6263 // notice that position can only possibly be near an edge if the row/column is
6264 // large enough to still allow for an "inner" area that is _not_ near the edge
6265 // (i.e., if the height/width is smaller than WXGRID_LABEL_EDGE_ZONE, pos will
6266 // _never_ be considered to be near the edge).
6267 int wxGrid::PosToEdgeOfLine(int pos, const wxGridOperations& oper) const
6268 {
6269 const int line = oper.PosToLine(this, pos, true);
6270
6271 if ( oper.GetLineSize(this, line) > WXGRID_LABEL_EDGE_ZONE )
6272 {
6273 // We know that we are in this line, test whether we are close enough
6274 // to start or end border, respectively.
6275 if ( abs(oper.GetLineEndPos(this, line) - pos) < WXGRID_LABEL_EDGE_ZONE )
6276 return line;
6277 else if ( line > 0 &&
6278 pos - oper.GetLineStartPos(this,
6279 line) < WXGRID_LABEL_EDGE_ZONE )
6280 return line - 1;
6281 }
6282
6283 return -1;
6284 }
6285
6286 int wxGrid::YToEdgeOfRow(int y) const
6287 {
6288 return PosToEdgeOfLine(y, wxGridRowOperations());
6289 }
6290
6291 int wxGrid::XToEdgeOfCol(int x) const
6292 {
6293 return PosToEdgeOfLine(x, wxGridColumnOperations());
6294 }
6295
6296 wxRect wxGrid::CellToRect( int row, int col ) const
6297 {
6298 wxRect rect( -1, -1, -1, -1 );
6299
6300 if ( row >= 0 && row < m_numRows &&
6301 col >= 0 && col < m_numCols )
6302 {
6303 int i, cell_rows, cell_cols;
6304 rect.width = rect.height = 0;
6305 GetCellSize( row, col, &cell_rows, &cell_cols );
6306 // if negative then find multicell owner
6307 if (cell_rows < 0)
6308 row += cell_rows;
6309 if (cell_cols < 0)
6310 col += cell_cols;
6311 GetCellSize( row, col, &cell_rows, &cell_cols );
6312
6313 rect.x = GetColLeft(col);
6314 rect.y = GetRowTop(row);
6315 for (i=col; i < col + cell_cols; i++)
6316 rect.width += GetColWidth(i);
6317 for (i=row; i < row + cell_rows; i++)
6318 rect.height += GetRowHeight(i);
6319
6320 // if grid lines are enabled, then the area of the cell is a bit smaller
6321 if (m_gridLinesEnabled)
6322 {
6323 rect.width -= 1;
6324 rect.height -= 1;
6325 }
6326 }
6327
6328 return rect;
6329 }
6330
6331 bool wxGrid::IsVisible( int row, int col, bool wholeCellVisible ) const
6332 {
6333 // get the cell rectangle in logical coords
6334 //
6335 wxRect r( CellToRect( row, col ) );
6336
6337 // convert to device coords
6338 //
6339 int left, top, right, bottom;
6340 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
6341 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
6342
6343 // check against the client area of the grid window
6344 int cw, ch;
6345 m_gridWin->GetClientSize( &cw, &ch );
6346
6347 if ( wholeCellVisible )
6348 {
6349 // is the cell wholly visible ?
6350 return ( left >= 0 && right <= cw &&
6351 top >= 0 && bottom <= ch );
6352 }
6353 else
6354 {
6355 // is the cell partly visible ?
6356 //
6357 return ( ((left >= 0 && left < cw) || (right > 0 && right <= cw)) &&
6358 ((top >= 0 && top < ch) || (bottom > 0 && bottom <= ch)) );
6359 }
6360 }
6361
6362 // make the specified cell location visible by doing a minimal amount
6363 // of scrolling
6364 //
6365 void wxGrid::MakeCellVisible( int row, int col )
6366 {
6367 int i;
6368 int xpos = -1, ypos = -1;
6369
6370 if ( row >= 0 && row < m_numRows &&
6371 col >= 0 && col < m_numCols )
6372 {
6373 // get the cell rectangle in logical coords
6374 wxRect r( CellToRect( row, col ) );
6375
6376 // convert to device coords
6377 int left, top, right, bottom;
6378 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
6379 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
6380
6381 int cw, ch;
6382 m_gridWin->GetClientSize( &cw, &ch );
6383
6384 if ( top < 0 )
6385 {
6386 ypos = r.GetTop();
6387 }
6388 else if ( bottom > ch )
6389 {
6390 int h = r.GetHeight();
6391 ypos = r.GetTop();
6392 for ( i = row - 1; i >= 0; i-- )
6393 {
6394 int rowHeight = GetRowHeight(i);
6395 if ( h + rowHeight > ch )
6396 break;
6397
6398 h += rowHeight;
6399 ypos -= rowHeight;
6400 }
6401
6402 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
6403 // have rounding errors (this is important, because if we do,
6404 // we might not scroll at all and some cells won't be redrawn)
6405 //
6406 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
6407 // so just add a full scroll unit...
6408 ypos += m_scrollLineY;
6409 }
6410
6411 // special handling for wide cells - show always left part of the cell!
6412 // Otherwise, e.g. when stepping from row to row, it would jump between
6413 // left and right part of the cell on every step!
6414 // if ( left < 0 )
6415 if ( left < 0 || (right - left) >= cw )
6416 {
6417 xpos = r.GetLeft();
6418 }
6419 else if ( right > cw )
6420 {
6421 // position the view so that the cell is on the right
6422 int x0, y0;
6423 CalcUnscrolledPosition(0, 0, &x0, &y0);
6424 xpos = x0 + (right - cw);
6425
6426 // see comment for ypos above
6427 xpos += m_scrollLineX;
6428 }
6429
6430 if ( xpos != -1 || ypos != -1 )
6431 {
6432 if ( xpos != -1 )
6433 xpos /= m_scrollLineX;
6434 if ( ypos != -1 )
6435 ypos /= m_scrollLineY;
6436 Scroll( xpos, ypos );
6437 AdjustScrollbars();
6438 }
6439 }
6440 }
6441
6442 //
6443 // ------ Grid cursor movement functions
6444 //
6445
6446 bool
6447 wxGrid::DoMoveCursor(bool expandSelection,
6448 const wxGridDirectionOperations& diroper)
6449 {
6450 if ( m_currentCellCoords == wxGridNoCellCoords )
6451 return false;
6452
6453 if ( expandSelection )
6454 {
6455 wxGridCellCoords coords = m_selectedBlockCorner;
6456 if ( coords == wxGridNoCellCoords )
6457 coords = m_currentCellCoords;
6458
6459 if ( diroper.IsAtBoundary(coords) )
6460 return false;
6461
6462 diroper.Advance(coords);
6463
6464 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6465 }
6466 else // don't expand selection
6467 {
6468 ClearSelection();
6469
6470 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6471 return false;
6472
6473 wxGridCellCoords coords = m_currentCellCoords;
6474 diroper.Advance(coords);
6475
6476 GoToCell(coords);
6477 }
6478
6479 return true;
6480 }
6481
6482 bool wxGrid::MoveCursorUp(bool expandSelection)
6483 {
6484 return DoMoveCursor(expandSelection,
6485 wxGridBackwardOperations(this, wxGridRowOperations()));
6486 }
6487
6488 bool wxGrid::MoveCursorDown(bool expandSelection)
6489 {
6490 return DoMoveCursor(expandSelection,
6491 wxGridForwardOperations(this, wxGridRowOperations()));
6492 }
6493
6494 bool wxGrid::MoveCursorLeft(bool expandSelection)
6495 {
6496 return DoMoveCursor(expandSelection,
6497 wxGridBackwardOperations(this, wxGridColumnOperations()));
6498 }
6499
6500 bool wxGrid::MoveCursorRight(bool expandSelection)
6501 {
6502 return DoMoveCursor(expandSelection,
6503 wxGridForwardOperations(this, wxGridColumnOperations()));
6504 }
6505
6506 bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations& diroper)
6507 {
6508 if ( m_currentCellCoords == wxGridNoCellCoords )
6509 return false;
6510
6511 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6512 return false;
6513
6514 const int oldRow = m_currentCellCoords.GetRow();
6515 int newRow = diroper.MoveByPixelDistance(oldRow, m_gridWin->GetClientSize().y);
6516 if ( newRow == oldRow )
6517 {
6518 wxGridCellCoords coords(m_currentCellCoords);
6519 diroper.Advance(coords);
6520 newRow = coords.GetRow();
6521 }
6522
6523 GoToCell(newRow, m_currentCellCoords.GetCol());
6524
6525 return true;
6526 }
6527
6528 bool wxGrid::MovePageUp()
6529 {
6530 return DoMoveCursorByPage(
6531 wxGridBackwardOperations(this, wxGridRowOperations()));
6532 }
6533
6534 bool wxGrid::MovePageDown()
6535 {
6536 return DoMoveCursorByPage(
6537 wxGridForwardOperations(this, wxGridRowOperations()));
6538 }
6539
6540 // helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
6541 // until we find a non-empty cell or reach the grid end
6542 void
6543 wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords& coords,
6544 const wxGridDirectionOperations& diroper)
6545 {
6546 while ( !diroper.IsAtBoundary(coords) )
6547 {
6548 diroper.Advance(coords);
6549 if ( !m_table->IsEmpty(coords) )
6550 break;
6551 }
6552 }
6553
6554 bool
6555 wxGrid::DoMoveCursorByBlock(bool expandSelection,
6556 const wxGridDirectionOperations& diroper)
6557 {
6558 if ( !m_table || m_currentCellCoords == wxGridNoCellCoords )
6559 return false;
6560
6561 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6562 return false;
6563
6564 wxGridCellCoords coords(m_currentCellCoords);
6565 if ( m_table->IsEmpty(coords) )
6566 {
6567 // we are in an empty cell: find the next block of non-empty cells
6568 AdvanceToNextNonEmpty(coords, diroper);
6569 }
6570 else // current cell is not empty
6571 {
6572 diroper.Advance(coords);
6573 if ( m_table->IsEmpty(coords) )
6574 {
6575 // we started at the end of a block, find the next one
6576 AdvanceToNextNonEmpty(coords, diroper);
6577 }
6578 else // we're in a middle of a block
6579 {
6580 // go to the end of it, i.e. find the last cell before the next
6581 // empty one
6582 while ( !diroper.IsAtBoundary(coords) )
6583 {
6584 wxGridCellCoords coordsNext(coords);
6585 diroper.Advance(coordsNext);
6586 if ( m_table->IsEmpty(coordsNext) )
6587 break;
6588
6589 coords = coordsNext;
6590 }
6591 }
6592 }
6593
6594 if ( expandSelection )
6595 {
6596 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6597 }
6598 else
6599 {
6600 ClearSelection();
6601 GoToCell(coords);
6602 }
6603
6604 return true;
6605 }
6606
6607 bool wxGrid::MoveCursorUpBlock(bool expandSelection)
6608 {
6609 return DoMoveCursorByBlock(
6610 expandSelection,
6611 wxGridBackwardOperations(this, wxGridRowOperations())
6612 );
6613 }
6614
6615 bool wxGrid::MoveCursorDownBlock( bool expandSelection )
6616 {
6617 return DoMoveCursorByBlock(
6618 expandSelection,
6619 wxGridForwardOperations(this, wxGridRowOperations())
6620 );
6621 }
6622
6623 bool wxGrid::MoveCursorLeftBlock( bool expandSelection )
6624 {
6625 return DoMoveCursorByBlock(
6626 expandSelection,
6627 wxGridBackwardOperations(this, wxGridColumnOperations())
6628 );
6629 }
6630
6631 bool wxGrid::MoveCursorRightBlock( bool expandSelection )
6632 {
6633 return DoMoveCursorByBlock(
6634 expandSelection,
6635 wxGridForwardOperations(this, wxGridColumnOperations())
6636 );
6637 }
6638
6639 //
6640 // ------ Label values and formatting
6641 //
6642
6643 void wxGrid::GetRowLabelAlignment( int *horiz, int *vert ) const
6644 {
6645 if ( horiz )
6646 *horiz = m_rowLabelHorizAlign;
6647 if ( vert )
6648 *vert = m_rowLabelVertAlign;
6649 }
6650
6651 void wxGrid::GetColLabelAlignment( int *horiz, int *vert ) const
6652 {
6653 if ( horiz )
6654 *horiz = m_colLabelHorizAlign;
6655 if ( vert )
6656 *vert = m_colLabelVertAlign;
6657 }
6658
6659 int wxGrid::GetColLabelTextOrientation() const
6660 {
6661 return m_colLabelTextOrientation;
6662 }
6663
6664 wxString wxGrid::GetRowLabelValue( int row ) const
6665 {
6666 if ( m_table )
6667 {
6668 return m_table->GetRowLabelValue( row );
6669 }
6670 else
6671 {
6672 wxString s;
6673 s << row;
6674 return s;
6675 }
6676 }
6677
6678 wxString wxGrid::GetColLabelValue( int col ) const
6679 {
6680 if ( m_table )
6681 {
6682 return m_table->GetColLabelValue( col );
6683 }
6684 else
6685 {
6686 wxString s;
6687 s << col;
6688 return s;
6689 }
6690 }
6691
6692 void wxGrid::SetRowLabelSize( int width )
6693 {
6694 wxASSERT( width >= 0 || width == wxGRID_AUTOSIZE );
6695
6696 if ( width == wxGRID_AUTOSIZE )
6697 {
6698 width = CalcColOrRowLabelAreaMinSize(wxGRID_ROW);
6699 }
6700
6701 if ( width != m_rowLabelWidth )
6702 {
6703 if ( width == 0 )
6704 {
6705 m_rowLabelWin->Show( false );
6706 m_cornerLabelWin->Show( false );
6707 }
6708 else if ( m_rowLabelWidth == 0 )
6709 {
6710 m_rowLabelWin->Show( true );
6711 if ( m_colLabelHeight > 0 )
6712 m_cornerLabelWin->Show( true );
6713 }
6714
6715 m_rowLabelWidth = width;
6716 CalcWindowSizes();
6717 wxScrolledWindow::Refresh( true );
6718 }
6719 }
6720
6721 void wxGrid::SetColLabelSize( int height )
6722 {
6723 wxASSERT( height >=0 || height == wxGRID_AUTOSIZE );
6724
6725 if ( height == wxGRID_AUTOSIZE )
6726 {
6727 height = CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN);
6728 }
6729
6730 if ( height != m_colLabelHeight )
6731 {
6732 if ( height == 0 )
6733 {
6734 m_colWindow->Show( false );
6735 m_cornerLabelWin->Show( false );
6736 }
6737 else if ( m_colLabelHeight == 0 )
6738 {
6739 m_colWindow->Show( true );
6740 if ( m_rowLabelWidth > 0 )
6741 m_cornerLabelWin->Show( true );
6742 }
6743
6744 m_colLabelHeight = height;
6745 CalcWindowSizes();
6746 wxScrolledWindow::Refresh( true );
6747 }
6748 }
6749
6750 void wxGrid::SetLabelBackgroundColour( const wxColour& colour )
6751 {
6752 if ( m_labelBackgroundColour != colour )
6753 {
6754 m_labelBackgroundColour = colour;
6755 m_rowLabelWin->SetBackgroundColour( colour );
6756 m_colWindow->SetBackgroundColour( colour );
6757 m_cornerLabelWin->SetBackgroundColour( colour );
6758
6759 if ( !GetBatchCount() )
6760 {
6761 m_rowLabelWin->Refresh();
6762 m_colWindow->Refresh();
6763 m_cornerLabelWin->Refresh();
6764 }
6765 }
6766 }
6767
6768 void wxGrid::SetLabelTextColour( const wxColour& colour )
6769 {
6770 if ( m_labelTextColour != colour )
6771 {
6772 m_labelTextColour = colour;
6773 if ( !GetBatchCount() )
6774 {
6775 m_rowLabelWin->Refresh();
6776 m_colWindow->Refresh();
6777 }
6778 }
6779 }
6780
6781 void wxGrid::SetLabelFont( const wxFont& font )
6782 {
6783 m_labelFont = font;
6784 if ( !GetBatchCount() )
6785 {
6786 m_rowLabelWin->Refresh();
6787 m_colWindow->Refresh();
6788 }
6789 }
6790
6791 void wxGrid::SetRowLabelAlignment( int horiz, int vert )
6792 {
6793 // allow old (incorrect) defs to be used
6794 switch ( horiz )
6795 {
6796 case wxLEFT: horiz = wxALIGN_LEFT; break;
6797 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
6798 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
6799 }
6800
6801 switch ( vert )
6802 {
6803 case wxTOP: vert = wxALIGN_TOP; break;
6804 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
6805 case wxCENTRE: vert = wxALIGN_CENTRE; break;
6806 }
6807
6808 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
6809 {
6810 m_rowLabelHorizAlign = horiz;
6811 }
6812
6813 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
6814 {
6815 m_rowLabelVertAlign = vert;
6816 }
6817
6818 if ( !GetBatchCount() )
6819 {
6820 m_rowLabelWin->Refresh();
6821 }
6822 }
6823
6824 void wxGrid::SetColLabelAlignment( int horiz, int vert )
6825 {
6826 // allow old (incorrect) defs to be used
6827 switch ( horiz )
6828 {
6829 case wxLEFT: horiz = wxALIGN_LEFT; break;
6830 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
6831 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
6832 }
6833
6834 switch ( vert )
6835 {
6836 case wxTOP: vert = wxALIGN_TOP; break;
6837 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
6838 case wxCENTRE: vert = wxALIGN_CENTRE; break;
6839 }
6840
6841 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
6842 {
6843 m_colLabelHorizAlign = horiz;
6844 }
6845
6846 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
6847 {
6848 m_colLabelVertAlign = vert;
6849 }
6850
6851 if ( !GetBatchCount() )
6852 {
6853 m_colWindow->Refresh();
6854 }
6855 }
6856
6857 // Note: under MSW, the default column label font must be changed because it
6858 // does not support vertical printing
6859 //
6860 // Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
6861 // pGrid->SetLabelFont(font);
6862 // pGrid->SetColLabelTextOrientation(wxVERTICAL);
6863 //
6864 void wxGrid::SetColLabelTextOrientation( int textOrientation )
6865 {
6866 if ( textOrientation == wxHORIZONTAL || textOrientation == wxVERTICAL )
6867 m_colLabelTextOrientation = textOrientation;
6868
6869 if ( !GetBatchCount() )
6870 m_colWindow->Refresh();
6871 }
6872
6873 void wxGrid::SetRowLabelValue( int row, const wxString& s )
6874 {
6875 if ( m_table )
6876 {
6877 m_table->SetRowLabelValue( row, s );
6878 if ( !GetBatchCount() )
6879 {
6880 wxRect rect = CellToRect( row, 0 );
6881 if ( rect.height > 0 )
6882 {
6883 CalcScrolledPosition(0, rect.y, &rect.x, &rect.y);
6884 rect.x = 0;
6885 rect.width = m_rowLabelWidth;
6886 m_rowLabelWin->Refresh( true, &rect );
6887 }
6888 }
6889 }
6890 }
6891
6892 void wxGrid::SetColLabelValue( int col, const wxString& s )
6893 {
6894 if ( m_table )
6895 {
6896 m_table->SetColLabelValue( col, s );
6897 if ( !GetBatchCount() )
6898 {
6899 if ( m_useNativeHeader )
6900 {
6901 GetGridColHeader()->UpdateColumn(col);
6902 }
6903 else
6904 {
6905 wxRect rect = CellToRect( 0, col );
6906 if ( rect.width > 0 )
6907 {
6908 CalcScrolledPosition(rect.x, 0, &rect.x, &rect.y);
6909 rect.y = 0;
6910 rect.height = m_colLabelHeight;
6911 GetColLabelWindow()->Refresh( true, &rect );
6912 }
6913 }
6914 }
6915 }
6916 }
6917
6918 void wxGrid::SetGridLineColour( const wxColour& colour )
6919 {
6920 if ( m_gridLineColour != colour )
6921 {
6922 m_gridLineColour = colour;
6923
6924 if ( GridLinesEnabled() )
6925 RedrawGridLines();
6926 }
6927 }
6928
6929 void wxGrid::SetCellHighlightColour( const wxColour& colour )
6930 {
6931 if ( m_cellHighlightColour != colour )
6932 {
6933 m_cellHighlightColour = colour;
6934
6935 wxClientDC dc( m_gridWin );
6936 PrepareDC( dc );
6937 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
6938 DrawCellHighlight(dc, attr);
6939 attr->DecRef();
6940 }
6941 }
6942
6943 void wxGrid::SetCellHighlightPenWidth(int width)
6944 {
6945 if (m_cellHighlightPenWidth != width)
6946 {
6947 m_cellHighlightPenWidth = width;
6948
6949 // Just redrawing the cell highlight is not enough since that won't
6950 // make any visible change if the the thickness is getting smaller.
6951 int row = m_currentCellCoords.GetRow();
6952 int col = m_currentCellCoords.GetCol();
6953 if ( row == -1 || col == -1 || GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
6954 return;
6955
6956 wxRect rect = CellToRect(row, col);
6957 m_gridWin->Refresh(true, &rect);
6958 }
6959 }
6960
6961 void wxGrid::SetCellHighlightROPenWidth(int width)
6962 {
6963 if (m_cellHighlightROPenWidth != width)
6964 {
6965 m_cellHighlightROPenWidth = width;
6966
6967 // Just redrawing the cell highlight is not enough since that won't
6968 // make any visible change if the the thickness is getting smaller.
6969 int row = m_currentCellCoords.GetRow();
6970 int col = m_currentCellCoords.GetCol();
6971 if ( row == -1 || col == -1 ||
6972 GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
6973 return;
6974
6975 wxRect rect = CellToRect(row, col);
6976 m_gridWin->Refresh(true, &rect);
6977 }
6978 }
6979
6980 void wxGrid::RedrawGridLines()
6981 {
6982 // the lines will be redrawn when the window is thawn
6983 if ( GetBatchCount() )
6984 return;
6985
6986 if ( GridLinesEnabled() )
6987 {
6988 wxClientDC dc( m_gridWin );
6989 PrepareDC( dc );
6990 DrawAllGridLines( dc, wxRegion() );
6991 }
6992 else // remove the grid lines
6993 {
6994 m_gridWin->Refresh();
6995 }
6996 }
6997
6998 void wxGrid::EnableGridLines( bool enable )
6999 {
7000 if ( enable != m_gridLinesEnabled )
7001 {
7002 m_gridLinesEnabled = enable;
7003
7004 RedrawGridLines();
7005 }
7006 }
7007
7008 void wxGrid::DoClipGridLines(bool& var, bool clip)
7009 {
7010 if ( clip != var )
7011 {
7012 var = clip;
7013
7014 if ( GridLinesEnabled() )
7015 RedrawGridLines();
7016 }
7017 }
7018
7019 int wxGrid::GetDefaultRowSize() const
7020 {
7021 return m_defaultRowHeight;
7022 }
7023
7024 int wxGrid::GetRowSize( int row ) const
7025 {
7026 wxCHECK_MSG( row >= 0 && row < m_numRows, 0, wxT("invalid row index") );
7027
7028 return GetRowHeight(row);
7029 }
7030
7031 int wxGrid::GetDefaultColSize() const
7032 {
7033 return m_defaultColWidth;
7034 }
7035
7036 int wxGrid::GetColSize( int col ) const
7037 {
7038 wxCHECK_MSG( col >= 0 && col < m_numCols, 0, wxT("invalid column index") );
7039
7040 return GetColWidth(col);
7041 }
7042
7043 // ============================================================================
7044 // access to the grid attributes: each of them has a default value in the grid
7045 // itself and may be overidden on a per-cell basis
7046 // ============================================================================
7047
7048 // ----------------------------------------------------------------------------
7049 // setting default attributes
7050 // ----------------------------------------------------------------------------
7051
7052 void wxGrid::SetDefaultCellBackgroundColour( const wxColour& col )
7053 {
7054 m_defaultCellAttr->SetBackgroundColour(col);
7055 #ifdef __WXGTK__
7056 m_gridWin->SetBackgroundColour(col);
7057 #endif
7058 }
7059
7060 void wxGrid::SetDefaultCellTextColour( const wxColour& col )
7061 {
7062 m_defaultCellAttr->SetTextColour(col);
7063 }
7064
7065 void wxGrid::SetDefaultCellAlignment( int horiz, int vert )
7066 {
7067 m_defaultCellAttr->SetAlignment(horiz, vert);
7068 }
7069
7070 void wxGrid::SetDefaultCellOverflow( bool allow )
7071 {
7072 m_defaultCellAttr->SetOverflow(allow);
7073 }
7074
7075 void wxGrid::SetDefaultCellFont( const wxFont& font )
7076 {
7077 m_defaultCellAttr->SetFont(font);
7078 }
7079
7080 // For editors and renderers the type registry takes precedence over the
7081 // default attr, so we need to register the new editor/renderer for the string
7082 // data type in order to make setting a default editor/renderer appear to
7083 // work correctly.
7084
7085 void wxGrid::SetDefaultRenderer(wxGridCellRenderer *renderer)
7086 {
7087 RegisterDataType(wxGRID_VALUE_STRING,
7088 renderer,
7089 GetDefaultEditorForType(wxGRID_VALUE_STRING));
7090 }
7091
7092 void wxGrid::SetDefaultEditor(wxGridCellEditor *editor)
7093 {
7094 RegisterDataType(wxGRID_VALUE_STRING,
7095 GetDefaultRendererForType(wxGRID_VALUE_STRING),
7096 editor);
7097 }
7098
7099 // ----------------------------------------------------------------------------
7100 // access to the default attributes
7101 // ----------------------------------------------------------------------------
7102
7103 wxColour wxGrid::GetDefaultCellBackgroundColour() const
7104 {
7105 return m_defaultCellAttr->GetBackgroundColour();
7106 }
7107
7108 wxColour wxGrid::GetDefaultCellTextColour() const
7109 {
7110 return m_defaultCellAttr->GetTextColour();
7111 }
7112
7113 wxFont wxGrid::GetDefaultCellFont() const
7114 {
7115 return m_defaultCellAttr->GetFont();
7116 }
7117
7118 void wxGrid::GetDefaultCellAlignment( int *horiz, int *vert ) const
7119 {
7120 m_defaultCellAttr->GetAlignment(horiz, vert);
7121 }
7122
7123 bool wxGrid::GetDefaultCellOverflow() const
7124 {
7125 return m_defaultCellAttr->GetOverflow();
7126 }
7127
7128 wxGridCellRenderer *wxGrid::GetDefaultRenderer() const
7129 {
7130 return m_defaultCellAttr->GetRenderer(NULL, 0, 0);
7131 }
7132
7133 wxGridCellEditor *wxGrid::GetDefaultEditor() const
7134 {
7135 return m_defaultCellAttr->GetEditor(NULL, 0, 0);
7136 }
7137
7138 // ----------------------------------------------------------------------------
7139 // access to cell attributes
7140 // ----------------------------------------------------------------------------
7141
7142 wxColour wxGrid::GetCellBackgroundColour(int row, int col) const
7143 {
7144 wxGridCellAttr *attr = GetCellAttr(row, col);
7145 wxColour colour = attr->GetBackgroundColour();
7146 attr->DecRef();
7147
7148 return colour;
7149 }
7150
7151 wxColour wxGrid::GetCellTextColour( int row, int col ) const
7152 {
7153 wxGridCellAttr *attr = GetCellAttr(row, col);
7154 wxColour colour = attr->GetTextColour();
7155 attr->DecRef();
7156
7157 return colour;
7158 }
7159
7160 wxFont wxGrid::GetCellFont( int row, int col ) const
7161 {
7162 wxGridCellAttr *attr = GetCellAttr(row, col);
7163 wxFont font = attr->GetFont();
7164 attr->DecRef();
7165
7166 return font;
7167 }
7168
7169 void wxGrid::GetCellAlignment( int row, int col, int *horiz, int *vert ) const
7170 {
7171 wxGridCellAttr *attr = GetCellAttr(row, col);
7172 attr->GetAlignment(horiz, vert);
7173 attr->DecRef();
7174 }
7175
7176 bool wxGrid::GetCellOverflow( int row, int col ) const
7177 {
7178 wxGridCellAttr *attr = GetCellAttr(row, col);
7179 bool allow = attr->GetOverflow();
7180 attr->DecRef();
7181
7182 return allow;
7183 }
7184
7185 wxGrid::CellSpan
7186 wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const
7187 {
7188 wxGridCellAttr *attr = GetCellAttr(row, col);
7189 attr->GetSize( num_rows, num_cols );
7190 attr->DecRef();
7191
7192 if ( *num_rows == 1 && *num_cols == 1 )
7193 return CellSpan_None; // just a normal cell
7194
7195 if ( *num_rows < 0 || *num_cols < 0 )
7196 return CellSpan_Inside; // covered by a multi-span cell
7197
7198 // this cell spans multiple cells to its right/bottom
7199 return CellSpan_Main;
7200 }
7201
7202 wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col) const
7203 {
7204 wxGridCellAttr* attr = GetCellAttr(row, col);
7205 wxGridCellRenderer* renderer = attr->GetRenderer(this, row, col);
7206 attr->DecRef();
7207
7208 return renderer;
7209 }
7210
7211 wxGridCellEditor* wxGrid::GetCellEditor(int row, int col) const
7212 {
7213 wxGridCellAttr* attr = GetCellAttr(row, col);
7214 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
7215 attr->DecRef();
7216
7217 return editor;
7218 }
7219
7220 bool wxGrid::IsReadOnly(int row, int col) const
7221 {
7222 wxGridCellAttr* attr = GetCellAttr(row, col);
7223 bool isReadOnly = attr->IsReadOnly();
7224 attr->DecRef();
7225
7226 return isReadOnly;
7227 }
7228
7229 // ----------------------------------------------------------------------------
7230 // attribute support: cache, automatic provider creation, ...
7231 // ----------------------------------------------------------------------------
7232
7233 bool wxGrid::CanHaveAttributes() const
7234 {
7235 if ( !m_table )
7236 {
7237 return false;
7238 }
7239
7240 return m_table->CanHaveAttributes();
7241 }
7242
7243 void wxGrid::ClearAttrCache()
7244 {
7245 if ( m_attrCache.row != -1 )
7246 {
7247 wxGridCellAttr *oldAttr = m_attrCache.attr;
7248 m_attrCache.attr = NULL;
7249 m_attrCache.row = -1;
7250 // wxSafeDecRec(...) might cause event processing that accesses
7251 // the cached attribute, if one exists (e.g. by deleting the
7252 // editor stored within the attribute). Therefore it is important
7253 // to invalidate the cache before calling wxSafeDecRef!
7254 wxSafeDecRef(oldAttr);
7255 }
7256 }
7257
7258 void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const
7259 {
7260 if ( attr != NULL )
7261 {
7262 wxGrid *self = (wxGrid *)this; // const_cast
7263
7264 self->ClearAttrCache();
7265 self->m_attrCache.row = row;
7266 self->m_attrCache.col = col;
7267 self->m_attrCache.attr = attr;
7268 wxSafeIncRef(attr);
7269 }
7270 }
7271
7272 bool wxGrid::LookupAttr(int row, int col, wxGridCellAttr **attr) const
7273 {
7274 if ( row == m_attrCache.row && col == m_attrCache.col )
7275 {
7276 *attr = m_attrCache.attr;
7277 wxSafeIncRef(m_attrCache.attr);
7278
7279 #ifdef DEBUG_ATTR_CACHE
7280 gs_nAttrCacheHits++;
7281 #endif
7282
7283 return true;
7284 }
7285 else
7286 {
7287 #ifdef DEBUG_ATTR_CACHE
7288 gs_nAttrCacheMisses++;
7289 #endif
7290
7291 return false;
7292 }
7293 }
7294
7295 wxGridCellAttr *wxGrid::GetCellAttr(int row, int col) const
7296 {
7297 wxGridCellAttr *attr = NULL;
7298 // Additional test to avoid looking at the cache e.g. for
7299 // wxNoCellCoords, as this will confuse memory management.
7300 if ( row >= 0 )
7301 {
7302 if ( !LookupAttr(row, col, &attr) )
7303 {
7304 attr = m_table ? m_table->GetAttr(row, col, wxGridCellAttr::Any)
7305 : NULL;
7306 CacheAttr(row, col, attr);
7307 }
7308 }
7309
7310 if (attr)
7311 {
7312 attr->SetDefAttr(m_defaultCellAttr);
7313 }
7314 else
7315 {
7316 attr = m_defaultCellAttr;
7317 attr->IncRef();
7318 }
7319
7320 return attr;
7321 }
7322
7323 wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const
7324 {
7325 wxGridCellAttr *attr = NULL;
7326 bool canHave = ((wxGrid*)this)->CanHaveAttributes();
7327
7328 wxCHECK_MSG( canHave, attr, wxT("Cell attributes not allowed"));
7329 wxCHECK_MSG( m_table, attr, wxT("must have a table") );
7330
7331 attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell);
7332 if ( !attr )
7333 {
7334 attr = new wxGridCellAttr(m_defaultCellAttr);
7335
7336 // artificially inc the ref count to match DecRef() in caller
7337 attr->IncRef();
7338 m_table->SetAttr(attr, row, col);
7339 }
7340
7341 return attr;
7342 }
7343
7344 // ----------------------------------------------------------------------------
7345 // setting column attributes (wrappers around SetColAttr)
7346 // ----------------------------------------------------------------------------
7347
7348 void wxGrid::SetColFormatBool(int col)
7349 {
7350 SetColFormatCustom(col, wxGRID_VALUE_BOOL);
7351 }
7352
7353 void wxGrid::SetColFormatNumber(int col)
7354 {
7355 SetColFormatCustom(col, wxGRID_VALUE_NUMBER);
7356 }
7357
7358 void wxGrid::SetColFormatFloat(int col, int width, int precision)
7359 {
7360 wxString typeName = wxGRID_VALUE_FLOAT;
7361 if ( (width != -1) || (precision != -1) )
7362 {
7363 typeName << wxT(':') << width << wxT(',') << precision;
7364 }
7365
7366 SetColFormatCustom(col, typeName);
7367 }
7368
7369 void wxGrid::SetColFormatCustom(int col, const wxString& typeName)
7370 {
7371 wxGridCellAttr *attr = m_table->GetAttr(-1, col, wxGridCellAttr::Col );
7372 if (!attr)
7373 attr = new wxGridCellAttr;
7374 wxGridCellRenderer *renderer = GetDefaultRendererForType(typeName);
7375 attr->SetRenderer(renderer);
7376 wxGridCellEditor *editor = GetDefaultEditorForType(typeName);
7377 attr->SetEditor(editor);
7378
7379 SetColAttr(col, attr);
7380
7381 }
7382
7383 // ----------------------------------------------------------------------------
7384 // setting cell attributes: this is forwarded to the table
7385 // ----------------------------------------------------------------------------
7386
7387 void wxGrid::SetAttr(int row, int col, wxGridCellAttr *attr)
7388 {
7389 if ( CanHaveAttributes() )
7390 {
7391 m_table->SetAttr(attr, row, col);
7392 ClearAttrCache();
7393 }
7394 else
7395 {
7396 wxSafeDecRef(attr);
7397 }
7398 }
7399
7400 void wxGrid::SetRowAttr(int row, wxGridCellAttr *attr)
7401 {
7402 if ( CanHaveAttributes() )
7403 {
7404 m_table->SetRowAttr(attr, row);
7405 ClearAttrCache();
7406 }
7407 else
7408 {
7409 wxSafeDecRef(attr);
7410 }
7411 }
7412
7413 void wxGrid::SetColAttr(int col, wxGridCellAttr *attr)
7414 {
7415 if ( CanHaveAttributes() )
7416 {
7417 m_table->SetColAttr(attr, col);
7418 ClearAttrCache();
7419 }
7420 else
7421 {
7422 wxSafeDecRef(attr);
7423 }
7424 }
7425
7426 void wxGrid::SetCellBackgroundColour( int row, int col, const wxColour& colour )
7427 {
7428 if ( CanHaveAttributes() )
7429 {
7430 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7431 attr->SetBackgroundColour(colour);
7432 attr->DecRef();
7433 }
7434 }
7435
7436 void wxGrid::SetCellTextColour( int row, int col, const wxColour& colour )
7437 {
7438 if ( CanHaveAttributes() )
7439 {
7440 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7441 attr->SetTextColour(colour);
7442 attr->DecRef();
7443 }
7444 }
7445
7446 void wxGrid::SetCellFont( int row, int col, const wxFont& font )
7447 {
7448 if ( CanHaveAttributes() )
7449 {
7450 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7451 attr->SetFont(font);
7452 attr->DecRef();
7453 }
7454 }
7455
7456 void wxGrid::SetCellAlignment( int row, int col, int horiz, int vert )
7457 {
7458 if ( CanHaveAttributes() )
7459 {
7460 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7461 attr->SetAlignment(horiz, vert);
7462 attr->DecRef();
7463 }
7464 }
7465
7466 void wxGrid::SetCellOverflow( int row, int col, bool allow )
7467 {
7468 if ( CanHaveAttributes() )
7469 {
7470 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7471 attr->SetOverflow(allow);
7472 attr->DecRef();
7473 }
7474 }
7475
7476 void wxGrid::SetCellSize( int row, int col, int num_rows, int num_cols )
7477 {
7478 if ( CanHaveAttributes() )
7479 {
7480 int cell_rows, cell_cols;
7481
7482 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7483 attr->GetSize(&cell_rows, &cell_cols);
7484 attr->SetSize(num_rows, num_cols);
7485 attr->DecRef();
7486
7487 // Cannot set the size of a cell to 0 or negative values
7488 // While it is perfectly legal to do that, this function cannot
7489 // handle all the possibilies, do it by hand by getting the CellAttr.
7490 // You can only set the size of a cell to 1,1 or greater with this fn
7491 wxASSERT_MSG( !((cell_rows < 1) || (cell_cols < 1)),
7492 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
7493 wxASSERT_MSG( !((num_rows < 1) || (num_cols < 1)),
7494 wxT("wxGrid::SetCellSize setting cell size to < 1"));
7495
7496 // if this was already a multicell then "turn off" the other cells first
7497 if ((cell_rows > 1) || (cell_cols > 1))
7498 {
7499 int i, j;
7500 for (j=row; j < row + cell_rows; j++)
7501 {
7502 for (i=col; i < col + cell_cols; i++)
7503 {
7504 if ((i != col) || (j != row))
7505 {
7506 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
7507 attr_stub->SetSize( 1, 1 );
7508 attr_stub->DecRef();
7509 }
7510 }
7511 }
7512 }
7513
7514 // mark the cells that will be covered by this cell to
7515 // negative or zero values to point back at this cell
7516 if (((num_rows > 1) || (num_cols > 1)) && (num_rows >= 1) && (num_cols >= 1))
7517 {
7518 int i, j;
7519 for (j=row; j < row + num_rows; j++)
7520 {
7521 for (i=col; i < col + num_cols; i++)
7522 {
7523 if ((i != col) || (j != row))
7524 {
7525 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
7526 attr_stub->SetSize( row - j, col - i );
7527 attr_stub->DecRef();
7528 }
7529 }
7530 }
7531 }
7532 }
7533 }
7534
7535 void wxGrid::SetCellRenderer(int row, int col, wxGridCellRenderer *renderer)
7536 {
7537 if ( CanHaveAttributes() )
7538 {
7539 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7540 attr->SetRenderer(renderer);
7541 attr->DecRef();
7542 }
7543 }
7544
7545 void wxGrid::SetCellEditor(int row, int col, wxGridCellEditor* editor)
7546 {
7547 if ( CanHaveAttributes() )
7548 {
7549 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7550 attr->SetEditor(editor);
7551 attr->DecRef();
7552 }
7553 }
7554
7555 void wxGrid::SetReadOnly(int row, int col, bool isReadOnly)
7556 {
7557 if ( CanHaveAttributes() )
7558 {
7559 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7560 attr->SetReadOnly(isReadOnly);
7561 attr->DecRef();
7562 }
7563 }
7564
7565 // ----------------------------------------------------------------------------
7566 // Data type registration
7567 // ----------------------------------------------------------------------------
7568
7569 void wxGrid::RegisterDataType(const wxString& typeName,
7570 wxGridCellRenderer* renderer,
7571 wxGridCellEditor* editor)
7572 {
7573 m_typeRegistry->RegisterDataType(typeName, renderer, editor);
7574 }
7575
7576
7577 wxGridCellEditor * wxGrid::GetDefaultEditorForCell(int row, int col) const
7578 {
7579 wxString typeName = m_table->GetTypeName(row, col);
7580 return GetDefaultEditorForType(typeName);
7581 }
7582
7583 wxGridCellRenderer * wxGrid::GetDefaultRendererForCell(int row, int col) const
7584 {
7585 wxString typeName = m_table->GetTypeName(row, col);
7586 return GetDefaultRendererForType(typeName);
7587 }
7588
7589 wxGridCellEditor * wxGrid::GetDefaultEditorForType(const wxString& typeName) const
7590 {
7591 int index = m_typeRegistry->FindOrCloneDataType(typeName);
7592 if ( index == wxNOT_FOUND )
7593 {
7594 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
7595
7596 return NULL;
7597 }
7598
7599 return m_typeRegistry->GetEditor(index);
7600 }
7601
7602 wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) const
7603 {
7604 int index = m_typeRegistry->FindOrCloneDataType(typeName);
7605 if ( index == wxNOT_FOUND )
7606 {
7607 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
7608
7609 return NULL;
7610 }
7611
7612 return m_typeRegistry->GetRenderer(index);
7613 }
7614
7615 // ----------------------------------------------------------------------------
7616 // row/col size
7617 // ----------------------------------------------------------------------------
7618
7619 void wxGrid::DoDisableLineResize(int line, wxGridFixedIndicesSet *& setFixed)
7620 {
7621 if ( !setFixed )
7622 {
7623 setFixed = new wxGridFixedIndicesSet;
7624 }
7625
7626 setFixed->insert(line);
7627 }
7628
7629 bool
7630 wxGrid::DoCanResizeLine(int line, const wxGridFixedIndicesSet *setFixed) const
7631 {
7632 return !setFixed || !setFixed->count(line);
7633 }
7634
7635 void wxGrid::EnableDragRowSize( bool enable )
7636 {
7637 m_canDragRowSize = enable;
7638 }
7639
7640 void wxGrid::EnableDragColSize( bool enable )
7641 {
7642 m_canDragColSize = enable;
7643 }
7644
7645 void wxGrid::EnableDragGridSize( bool enable )
7646 {
7647 m_canDragGridSize = enable;
7648 }
7649
7650 void wxGrid::EnableDragCell( bool enable )
7651 {
7652 m_canDragCell = enable;
7653 }
7654
7655 void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows )
7656 {
7657 m_defaultRowHeight = wxMax( height, m_minAcceptableRowHeight );
7658
7659 if ( resizeExistingRows )
7660 {
7661 // since we are resizing all rows to the default row size,
7662 // we can simply clear the row heights and row bottoms
7663 // arrays (which also allows us to take advantage of
7664 // some speed optimisations)
7665 m_rowHeights.Empty();
7666 m_rowBottoms.Empty();
7667 if ( !GetBatchCount() )
7668 CalcDimensions();
7669 }
7670 }
7671
7672 void wxGrid::SetRowSize( int row, int height )
7673 {
7674 wxCHECK_RET( row >= 0 && row < m_numRows, wxT("invalid row index") );
7675
7676 // if < 0 then calculate new height from label
7677 if ( height < 0 )
7678 {
7679 long w, h;
7680 wxArrayString lines;
7681 wxClientDC dc(m_rowLabelWin);
7682 dc.SetFont(GetLabelFont());
7683 StringToLines(GetRowLabelValue( row ), lines);
7684 GetTextBoxSize( dc, lines, &w, &h );
7685 //check that it is not less than the minimal height
7686 height = wxMax(h, GetRowMinimalAcceptableHeight());
7687 }
7688
7689 // See comment in SetColSize
7690 if ( height < GetRowMinimalAcceptableHeight())
7691 return;
7692
7693 if ( m_rowHeights.IsEmpty() )
7694 {
7695 // need to really create the array
7696 InitRowHeights();
7697 }
7698
7699 int h = wxMax( 0, height );
7700 int diff = h - m_rowHeights[row];
7701
7702 m_rowHeights[row] = h;
7703 for ( int i = row; i < m_numRows; i++ )
7704 {
7705 m_rowBottoms[i] += diff;
7706 }
7707
7708 if ( !GetBatchCount() )
7709 CalcDimensions();
7710 }
7711
7712 void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols )
7713 {
7714 // we dont allow zero default column width
7715 m_defaultColWidth = wxMax( wxMax( width, m_minAcceptableColWidth ), 1 );
7716
7717 if ( resizeExistingCols )
7718 {
7719 // since we are resizing all columns to the default column size,
7720 // we can simply clear the col widths and col rights
7721 // arrays (which also allows us to take advantage of
7722 // some speed optimisations)
7723 m_colWidths.Empty();
7724 m_colRights.Empty();
7725 if ( !GetBatchCount() )
7726 CalcDimensions();
7727 }
7728 }
7729
7730 void wxGrid::SetColSize( int col, int width )
7731 {
7732 wxCHECK_RET( col >= 0 && col < m_numCols, wxT("invalid column index") );
7733
7734 // if < 0 then calculate new width from label
7735 if ( width < 0 )
7736 {
7737 long w, h;
7738 wxArrayString lines;
7739 wxClientDC dc(m_colWindow);
7740 dc.SetFont(GetLabelFont());
7741 StringToLines(GetColLabelValue(col), lines);
7742 if ( GetColLabelTextOrientation() == wxHORIZONTAL )
7743 GetTextBoxSize( dc, lines, &w, &h );
7744 else
7745 GetTextBoxSize( dc, lines, &h, &w );
7746 width = w + 6;
7747 //check that it is not less than the minimal width
7748 width = wxMax(width, GetColMinimalAcceptableWidth());
7749 }
7750
7751 // we intentionally don't test whether the width is less than
7752 // GetColMinimalWidth() here but we do compare it with
7753 // GetColMinimalAcceptableWidth() as otherwise things currently break (see
7754 // #651) -- and we also always allow the width of 0 as it has the special
7755 // sense of hiding the column
7756 if ( width > 0 && width < GetColMinimalAcceptableWidth() )
7757 return;
7758
7759 if ( m_colWidths.IsEmpty() )
7760 {
7761 // need to really create the array
7762 InitColWidths();
7763 }
7764
7765 const int diff = width - m_colWidths[col];
7766 m_colWidths[col] = width;
7767 if ( m_useNativeHeader )
7768 GetGridColHeader()->UpdateColumn(col);
7769 //else: will be refreshed when the header is redrawn
7770
7771 for ( int colPos = GetColPos(col); colPos < m_numCols; colPos++ )
7772 {
7773 m_colRights[GetColAt(colPos)] += diff;
7774 }
7775
7776 if ( !GetBatchCount() )
7777 {
7778 CalcDimensions();
7779 Refresh();
7780 }
7781 }
7782
7783 void wxGrid::SetColMinimalWidth( int col, int width )
7784 {
7785 if (width > GetColMinimalAcceptableWidth())
7786 {
7787 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
7788 m_colMinWidths[key] = width;
7789 }
7790 }
7791
7792 void wxGrid::SetRowMinimalHeight( int row, int width )
7793 {
7794 if (width > GetRowMinimalAcceptableHeight())
7795 {
7796 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
7797 m_rowMinHeights[key] = width;
7798 }
7799 }
7800
7801 int wxGrid::GetColMinimalWidth(int col) const
7802 {
7803 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
7804 wxLongToLongHashMap::const_iterator it = m_colMinWidths.find(key);
7805
7806 return it != m_colMinWidths.end() ? (int)it->second : m_minAcceptableColWidth;
7807 }
7808
7809 int wxGrid::GetRowMinimalHeight(int row) const
7810 {
7811 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
7812 wxLongToLongHashMap::const_iterator it = m_rowMinHeights.find(key);
7813
7814 return it != m_rowMinHeights.end() ? (int)it->second : m_minAcceptableRowHeight;
7815 }
7816
7817 void wxGrid::SetColMinimalAcceptableWidth( int width )
7818 {
7819 // We do allow a width of 0 since this gives us
7820 // an easy way to temporarily hiding columns.
7821 if ( width >= 0 )
7822 m_minAcceptableColWidth = width;
7823 }
7824
7825 void wxGrid::SetRowMinimalAcceptableHeight( int height )
7826 {
7827 // We do allow a height of 0 since this gives us
7828 // an easy way to temporarily hiding rows.
7829 if ( height >= 0 )
7830 m_minAcceptableRowHeight = height;
7831 }
7832
7833 int wxGrid::GetColMinimalAcceptableWidth() const
7834 {
7835 return m_minAcceptableColWidth;
7836 }
7837
7838 int wxGrid::GetRowMinimalAcceptableHeight() const
7839 {
7840 return m_minAcceptableRowHeight;
7841 }
7842
7843 // ----------------------------------------------------------------------------
7844 // auto sizing
7845 // ----------------------------------------------------------------------------
7846
7847 void
7848 wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction)
7849 {
7850 const bool column = direction == wxGRID_COLUMN;
7851
7852 wxClientDC dc(m_gridWin);
7853
7854 // cancel editing of cell
7855 HideCellEditControl();
7856 SaveEditControlValue();
7857
7858 // initialize both of them just to avoid compiler warnings even if only
7859 // really needs to be initialized here
7860 int row,
7861 col;
7862 if ( column )
7863 {
7864 row = -1;
7865 col = colOrRow;
7866 }
7867 else
7868 {
7869 row = colOrRow;
7870 col = -1;
7871 }
7872
7873 wxCoord extent, extentMax = 0;
7874 int max = column ? m_numRows : m_numCols;
7875 for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ )
7876 {
7877 if ( column )
7878 row = rowOrCol;
7879 else
7880 col = rowOrCol;
7881
7882 // we need to account for the cells spanning multiple columns/rows:
7883 // while they may need a lot of space, they don't need all of it in
7884 // this column/row
7885 int numRows, numCols;
7886 const CellSpan span = GetCellSize(row, col, &numRows, &numCols);
7887 if ( span == CellSpan_Inside )
7888 {
7889 // we need to get the size of the main cell, not of a cell hidden
7890 // by it
7891 row += numRows;
7892 col += numCols;
7893
7894 // get the size of the main cell too
7895 GetCellSize(row, col, &numRows, &numCols);
7896 }
7897
7898 wxGridCellAttr *attr = GetCellAttr(row, col);
7899 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
7900 if ( renderer )
7901 {
7902 wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col);
7903 extent = column ? size.x : size.y;
7904
7905 if ( span != CellSpan_None )
7906 {
7907 // we spread the size of a spanning cell over all the cells it
7908 // covers evenly -- this is probably not ideal but we can't
7909 // really do much better here
7910 //
7911 // notice that numCols and numRows are never 0 as they
7912 // correspond to the size of the main cell of the span and not
7913 // of the cell inside it
7914 extent /= column ? numCols : numRows;
7915 }
7916
7917 if ( extent > extentMax )
7918 extentMax = extent;
7919
7920 renderer->DecRef();
7921 }
7922
7923 attr->DecRef();
7924 }
7925
7926 // now also compare with the column label extent
7927 wxCoord w, h;
7928 dc.SetFont( GetLabelFont() );
7929
7930 if ( column )
7931 {
7932 dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h );
7933 if ( GetColLabelTextOrientation() == wxVERTICAL )
7934 w = h;
7935 }
7936 else
7937 dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h );
7938
7939 extent = column ? w : h;
7940 if ( extent > extentMax )
7941 extentMax = extent;
7942
7943 if ( !extentMax )
7944 {
7945 // empty column - give default extent (notice that if extentMax is less
7946 // than default extent but != 0, it's OK)
7947 extentMax = column ? m_defaultColWidth : m_defaultRowHeight;
7948 }
7949 else
7950 {
7951 if ( column )
7952 // leave some space around text
7953 extentMax += 10;
7954 else
7955 extentMax += 6;
7956 }
7957
7958 if ( column )
7959 {
7960 // Ensure automatic width is not less than minimal width. See the
7961 // comment in SetColSize() for explanation of why this isn't done
7962 // in SetColSize().
7963 if ( !setAsMin )
7964 extentMax = wxMax(extentMax, GetColMinimalWidth(col));
7965
7966 SetColSize( col, extentMax );
7967 if ( !GetBatchCount() )
7968 {
7969 if ( m_useNativeHeader )
7970 {
7971 GetGridColHeader()->UpdateColumn(col);
7972 }
7973 else
7974 {
7975 int cw, ch, dummy;
7976 m_gridWin->GetClientSize( &cw, &ch );
7977 wxRect rect ( CellToRect( 0, col ) );
7978 rect.y = 0;
7979 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
7980 rect.width = cw - rect.x;
7981 rect.height = m_colLabelHeight;
7982 GetColLabelWindow()->Refresh( true, &rect );
7983 }
7984 }
7985 }
7986 else
7987 {
7988 // Ensure automatic width is not less than minimal height. See the
7989 // comment in SetColSize() for explanation of why this isn't done
7990 // in SetRowSize().
7991 if ( !setAsMin )
7992 extentMax = wxMax(extentMax, GetRowMinimalHeight(row));
7993
7994 SetRowSize(row, extentMax);
7995 if ( !GetBatchCount() )
7996 {
7997 int cw, ch, dummy;
7998 m_gridWin->GetClientSize( &cw, &ch );
7999 wxRect rect( CellToRect( row, 0 ) );
8000 rect.x = 0;
8001 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
8002 rect.width = m_rowLabelWidth;
8003 rect.height = ch - rect.y;
8004 m_rowLabelWin->Refresh( true, &rect );
8005 }
8006 }
8007
8008 if ( setAsMin )
8009 {
8010 if ( column )
8011 SetColMinimalWidth(col, extentMax);
8012 else
8013 SetRowMinimalHeight(row, extentMax);
8014 }
8015 }
8016
8017 wxCoord wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction)
8018 {
8019 // calculate size for the rows or columns?
8020 const bool calcRows = direction == wxGRID_ROW;
8021
8022 wxClientDC dc(calcRows ? GetGridRowLabelWindow()
8023 : GetGridColLabelWindow());
8024 dc.SetFont(GetLabelFont());
8025
8026 // which dimension should we take into account for calculations?
8027 //
8028 // for columns, the text can be only horizontal so it's easy but for rows
8029 // we also have to take into account the text orientation
8030 const bool
8031 useWidth = calcRows || (GetColLabelTextOrientation() == wxVERTICAL);
8032
8033 wxArrayString lines;
8034 wxCoord extentMax = 0;
8035
8036 const int numRowsOrCols = calcRows ? m_numRows : m_numCols;
8037 for ( int rowOrCol = 0; rowOrCol < numRowsOrCols; rowOrCol++ )
8038 {
8039 lines.Clear();
8040
8041 wxString label = calcRows ? GetRowLabelValue(rowOrCol)
8042 : GetColLabelValue(rowOrCol);
8043 StringToLines(label, lines);
8044
8045 long w, h;
8046 GetTextBoxSize(dc, lines, &w, &h);
8047
8048 const wxCoord extent = useWidth ? w : h;
8049 if ( extent > extentMax )
8050 extentMax = extent;
8051 }
8052
8053 if ( !extentMax )
8054 {
8055 // empty column - give default extent (notice that if extentMax is less
8056 // than default extent but != 0, it's OK)
8057 extentMax = calcRows ? GetDefaultRowLabelSize()
8058 : GetDefaultColLabelSize();
8059 }
8060
8061 // leave some space around text (taken from AutoSizeColOrRow)
8062 if ( calcRows )
8063 extentMax += 10;
8064 else
8065 extentMax += 6;
8066
8067 return extentMax;
8068 }
8069
8070 int wxGrid::SetOrCalcColumnSizes(bool calcOnly, bool setAsMin)
8071 {
8072 int width = m_rowLabelWidth;
8073
8074 wxGridUpdateLocker locker;
8075 if(!calcOnly)
8076 locker.Create(this);
8077
8078 for ( int col = 0; col < m_numCols; col++ )
8079 {
8080 if ( !calcOnly )
8081 AutoSizeColumn(col, setAsMin);
8082
8083 width += GetColWidth(col);
8084 }
8085
8086 return width;
8087 }
8088
8089 int wxGrid::SetOrCalcRowSizes(bool calcOnly, bool setAsMin)
8090 {
8091 int height = m_colLabelHeight;
8092
8093 wxGridUpdateLocker locker;
8094 if(!calcOnly)
8095 locker.Create(this);
8096
8097 for ( int row = 0; row < m_numRows; row++ )
8098 {
8099 if ( !calcOnly )
8100 AutoSizeRow(row, setAsMin);
8101
8102 height += GetRowHeight(row);
8103 }
8104
8105 return height;
8106 }
8107
8108 void wxGrid::AutoSize()
8109 {
8110 wxGridUpdateLocker locker(this);
8111
8112 wxSize size(SetOrCalcColumnSizes(false) - m_rowLabelWidth + m_extraWidth,
8113 SetOrCalcRowSizes(false) - m_colLabelHeight + m_extraHeight);
8114
8115 // we know that we're not going to have scrollbars so disable them now to
8116 // avoid trouble in SetClientSize() which can otherwise set the correct
8117 // client size but also leave space for (not needed any more) scrollbars
8118 SetScrollbars(0, 0, 0, 0, 0, 0, true);
8119
8120 // restore the scroll rate parameters overwritten by SetScrollbars()
8121 SetScrollRate(m_scrollLineX, m_scrollLineY);
8122
8123 SetClientSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight);
8124 }
8125
8126 void wxGrid::AutoSizeRowLabelSize( int row )
8127 {
8128 // Hide the edit control, so it
8129 // won't interfere with drag-shrinking.
8130 if ( IsCellEditControlShown() )
8131 {
8132 HideCellEditControl();
8133 SaveEditControlValue();
8134 }
8135
8136 // autosize row height depending on label text
8137 SetRowSize(row, -1);
8138 ForceRefresh();
8139 }
8140
8141 void wxGrid::AutoSizeColLabelSize( int col )
8142 {
8143 // Hide the edit control, so it
8144 // won't interfere with drag-shrinking.
8145 if ( IsCellEditControlShown() )
8146 {
8147 HideCellEditControl();
8148 SaveEditControlValue();
8149 }
8150
8151 // autosize column width depending on label text
8152 SetColSize(col, -1);
8153 ForceRefresh();
8154 }
8155
8156 wxSize wxGrid::DoGetBestSize() const
8157 {
8158 wxGrid *self = (wxGrid *)this; // const_cast
8159
8160 // we do the same as in AutoSize() here with the exception that we don't
8161 // change the column/row sizes, only calculate them
8162 wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth,
8163 self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight);
8164
8165 // NOTE: This size should be cached, but first we need to add calls to
8166 // InvalidateBestSize everywhere that could change the results of this
8167 // calculation.
8168 // CacheBestSize(size);
8169
8170 return wxSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight)
8171 + GetWindowBorderSize();
8172 }
8173
8174 void wxGrid::Fit()
8175 {
8176 AutoSize();
8177 }
8178
8179 wxPen& wxGrid::GetDividerPen() const
8180 {
8181 return wxNullPen;
8182 }
8183
8184 // ----------------------------------------------------------------------------
8185 // cell value accessor functions
8186 // ----------------------------------------------------------------------------
8187
8188 void wxGrid::SetCellValue( int row, int col, const wxString& s )
8189 {
8190 if ( m_table )
8191 {
8192 m_table->SetValue( row, col, s );
8193 if ( !GetBatchCount() )
8194 {
8195 int dummy;
8196 wxRect rect( CellToRect( row, col ) );
8197 rect.x = 0;
8198 rect.width = m_gridWin->GetClientSize().GetWidth();
8199 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
8200 m_gridWin->Refresh( false, &rect );
8201 }
8202
8203 if ( m_currentCellCoords.GetRow() == row &&
8204 m_currentCellCoords.GetCol() == col &&
8205 IsCellEditControlShown())
8206 // Note: If we are using IsCellEditControlEnabled,
8207 // this interacts badly with calling SetCellValue from
8208 // an EVT_GRID_CELL_CHANGE handler.
8209 {
8210 HideCellEditControl();
8211 ShowCellEditControl(); // will reread data from table
8212 }
8213 }
8214 }
8215
8216 // ----------------------------------------------------------------------------
8217 // block, row and column selection
8218 // ----------------------------------------------------------------------------
8219
8220 void wxGrid::SelectRow( int row, bool addToSelected )
8221 {
8222 if ( !m_selection )
8223 return;
8224
8225 if ( !addToSelected )
8226 ClearSelection();
8227
8228 m_selection->SelectRow(row);
8229 }
8230
8231 void wxGrid::SelectCol( int col, bool addToSelected )
8232 {
8233 if ( !m_selection )
8234 return;
8235
8236 if ( !addToSelected )
8237 ClearSelection();
8238
8239 m_selection->SelectCol(col);
8240 }
8241
8242 void wxGrid::SelectBlock(int topRow, int leftCol, int bottomRow, int rightCol,
8243 bool addToSelected)
8244 {
8245 if ( !m_selection )
8246 return;
8247
8248 if ( !addToSelected )
8249 ClearSelection();
8250
8251 m_selection->SelectBlock(topRow, leftCol, bottomRow, rightCol);
8252 }
8253
8254 void wxGrid::SelectAll()
8255 {
8256 if ( m_numRows > 0 && m_numCols > 0 )
8257 {
8258 if ( m_selection )
8259 m_selection->SelectBlock( 0, 0, m_numRows - 1, m_numCols - 1 );
8260 }
8261 }
8262
8263 // ----------------------------------------------------------------------------
8264 // cell, row and col deselection
8265 // ----------------------------------------------------------------------------
8266
8267 void wxGrid::DeselectLine(int line, const wxGridOperations& oper)
8268 {
8269 if ( !m_selection )
8270 return;
8271
8272 const wxGridSelectionModes mode = m_selection->GetSelectionMode();
8273 if ( mode == oper.GetSelectionMode() ||
8274 mode == wxGrid::wxGridSelectRowsOrColumns )
8275 {
8276 const wxGridCellCoords c(oper.MakeCoords(line, 0));
8277 if ( m_selection->IsInSelection(c) )
8278 m_selection->ToggleCellSelection(c);
8279 }
8280 else if ( mode != oper.Dual().GetSelectionMode() )
8281 {
8282 const int nOther = oper.Dual().GetNumberOfLines(this);
8283 for ( int i = 0; i < nOther; i++ )
8284 {
8285 const wxGridCellCoords c(oper.MakeCoords(line, i));
8286 if ( m_selection->IsInSelection(c) )
8287 m_selection->ToggleCellSelection(c);
8288 }
8289 }
8290 //else: can only select orthogonal lines so no lines in this direction
8291 // could have been selected anyhow
8292 }
8293
8294 void wxGrid::DeselectRow(int row)
8295 {
8296 DeselectLine(row, wxGridRowOperations());
8297 }
8298
8299 void wxGrid::DeselectCol(int col)
8300 {
8301 DeselectLine(col, wxGridColumnOperations());
8302 }
8303
8304 void wxGrid::DeselectCell( int row, int col )
8305 {
8306 if ( m_selection && m_selection->IsInSelection(row, col) )
8307 m_selection->ToggleCellSelection(row, col);
8308 }
8309
8310 bool wxGrid::IsSelection() const
8311 {
8312 return ( m_selection && (m_selection->IsSelection() ||
8313 ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
8314 m_selectedBlockBottomRight != wxGridNoCellCoords) ) );
8315 }
8316
8317 bool wxGrid::IsInSelection( int row, int col ) const
8318 {
8319 return ( m_selection && (m_selection->IsInSelection( row, col ) ||
8320 ( row >= m_selectedBlockTopLeft.GetRow() &&
8321 col >= m_selectedBlockTopLeft.GetCol() &&
8322 row <= m_selectedBlockBottomRight.GetRow() &&
8323 col <= m_selectedBlockBottomRight.GetCol() )) );
8324 }
8325
8326 wxGridCellCoordsArray wxGrid::GetSelectedCells() const
8327 {
8328 if (!m_selection)
8329 {
8330 wxGridCellCoordsArray a;
8331 return a;
8332 }
8333
8334 return m_selection->m_cellSelection;
8335 }
8336
8337 wxGridCellCoordsArray wxGrid::GetSelectionBlockTopLeft() const
8338 {
8339 if (!m_selection)
8340 {
8341 wxGridCellCoordsArray a;
8342 return a;
8343 }
8344
8345 return m_selection->m_blockSelectionTopLeft;
8346 }
8347
8348 wxGridCellCoordsArray wxGrid::GetSelectionBlockBottomRight() const
8349 {
8350 if (!m_selection)
8351 {
8352 wxGridCellCoordsArray a;
8353 return a;
8354 }
8355
8356 return m_selection->m_blockSelectionBottomRight;
8357 }
8358
8359 wxArrayInt wxGrid::GetSelectedRows() const
8360 {
8361 if (!m_selection)
8362 {
8363 wxArrayInt a;
8364 return a;
8365 }
8366
8367 return m_selection->m_rowSelection;
8368 }
8369
8370 wxArrayInt wxGrid::GetSelectedCols() const
8371 {
8372 if (!m_selection)
8373 {
8374 wxArrayInt a;
8375 return a;
8376 }
8377
8378 return m_selection->m_colSelection;
8379 }
8380
8381 void wxGrid::ClearSelection()
8382 {
8383 wxRect r1 = BlockToDeviceRect(m_selectedBlockTopLeft,
8384 m_selectedBlockBottomRight);
8385 wxRect r2 = BlockToDeviceRect(m_currentCellCoords,
8386 m_selectedBlockCorner);
8387
8388 m_selectedBlockTopLeft =
8389 m_selectedBlockBottomRight =
8390 m_selectedBlockCorner = wxGridNoCellCoords;
8391
8392 if ( !r1.IsEmpty() )
8393 RefreshRect(r1, false);
8394 if ( !r2.IsEmpty() )
8395 RefreshRect(r2, false);
8396
8397 if ( m_selection )
8398 m_selection->ClearSelection();
8399 }
8400
8401 // This function returns the rectangle that encloses the given block
8402 // in device coords clipped to the client size of the grid window.
8403 //
8404 wxRect wxGrid::BlockToDeviceRect( const wxGridCellCoords& topLeft,
8405 const wxGridCellCoords& bottomRight ) const
8406 {
8407 wxRect resultRect;
8408 wxRect tempCellRect = CellToRect(topLeft);
8409 if ( tempCellRect != wxGridNoCellRect )
8410 {
8411 resultRect = tempCellRect;
8412 }
8413 else
8414 {
8415 resultRect = wxRect(0, 0, 0, 0);
8416 }
8417
8418 tempCellRect = CellToRect(bottomRight);
8419 if ( tempCellRect != wxGridNoCellRect )
8420 {
8421 resultRect += tempCellRect;
8422 }
8423 else
8424 {
8425 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
8426 return wxGridNoCellRect;
8427 }
8428
8429 // Ensure that left/right and top/bottom pairs are in order.
8430 int left = resultRect.GetLeft();
8431 int top = resultRect.GetTop();
8432 int right = resultRect.GetRight();
8433 int bottom = resultRect.GetBottom();
8434
8435 int leftCol = topLeft.GetCol();
8436 int topRow = topLeft.GetRow();
8437 int rightCol = bottomRight.GetCol();
8438 int bottomRow = bottomRight.GetRow();
8439
8440 if (left > right)
8441 {
8442 int tmp = left;
8443 left = right;
8444 right = tmp;
8445
8446 tmp = leftCol;
8447 leftCol = rightCol;
8448 rightCol = tmp;
8449 }
8450
8451 if (top > bottom)
8452 {
8453 int tmp = top;
8454 top = bottom;
8455 bottom = tmp;
8456
8457 tmp = topRow;
8458 topRow = bottomRow;
8459 bottomRow = tmp;
8460 }
8461
8462 // The following loop is ONLY necessary to detect and handle merged cells.
8463 int cw, ch;
8464 m_gridWin->GetClientSize( &cw, &ch );
8465
8466 // Get the origin coordinates: notice that they will be negative if the
8467 // grid is scrolled downwards/to the right.
8468 int gridOriginX = 0;
8469 int gridOriginY = 0;
8470 CalcScrolledPosition(gridOriginX, gridOriginY, &gridOriginX, &gridOriginY);
8471
8472 int onScreenLeftmostCol = internalXToCol(-gridOriginX);
8473 int onScreenUppermostRow = internalYToRow(-gridOriginY);
8474
8475 int onScreenRightmostCol = internalXToCol(-gridOriginX + cw);
8476 int onScreenBottommostRow = internalYToRow(-gridOriginY + ch);
8477
8478 // Bound our loop so that we only examine the portion of the selected block
8479 // that is shown on screen. Therefore, we compare the Top-Left block values
8480 // to the Top-Left screen values, and the Bottom-Right block values to the
8481 // Bottom-Right screen values, choosing appropriately.
8482 const int visibleTopRow = wxMax(topRow, onScreenUppermostRow);
8483 const int visibleBottomRow = wxMin(bottomRow, onScreenBottommostRow);
8484 const int visibleLeftCol = wxMax(leftCol, onScreenLeftmostCol);
8485 const int visibleRightCol = wxMin(rightCol, onScreenRightmostCol);
8486
8487 for ( int j = visibleTopRow; j <= visibleBottomRow; j++ )
8488 {
8489 for ( int i = visibleLeftCol; i <= visibleRightCol; i++ )
8490 {
8491 if ( (j == visibleTopRow) || (j == visibleBottomRow) ||
8492 (i == visibleLeftCol) || (i == visibleRightCol) )
8493 {
8494 tempCellRect = CellToRect( j, i );
8495
8496 if (tempCellRect.x < left)
8497 left = tempCellRect.x;
8498 if (tempCellRect.y < top)
8499 top = tempCellRect.y;
8500 if (tempCellRect.x + tempCellRect.width > right)
8501 right = tempCellRect.x + tempCellRect.width;
8502 if (tempCellRect.y + tempCellRect.height > bottom)
8503 bottom = tempCellRect.y + tempCellRect.height;
8504 }
8505 else
8506 {
8507 i = visibleRightCol; // jump over inner cells.
8508 }
8509 }
8510 }
8511
8512 // Convert to scrolled coords
8513 CalcScrolledPosition( left, top, &left, &top );
8514 CalcScrolledPosition( right, bottom, &right, &bottom );
8515
8516 if (right < 0 || bottom < 0 || left > cw || top > ch)
8517 return wxRect(0,0,0,0);
8518
8519 resultRect.SetLeft( wxMax(0, left) );
8520 resultRect.SetTop( wxMax(0, top) );
8521 resultRect.SetRight( wxMin(cw, right) );
8522 resultRect.SetBottom( wxMin(ch, bottom) );
8523
8524 return resultRect;
8525 }
8526
8527 void wxGrid::DoSetSizes(const wxGridSizesInfo& sizeInfo,
8528 const wxGridOperations& oper)
8529 {
8530 BeginBatch();
8531 oper.SetDefaultLineSize(this, sizeInfo.m_sizeDefault, true);
8532 const int numLines = oper.GetNumberOfLines(this);
8533 for ( int i = 0; i < numLines; i++ )
8534 {
8535 int size = sizeInfo.GetSize(i);
8536 if ( size != sizeInfo.m_sizeDefault)
8537 oper.SetLineSize(this, i, size);
8538 }
8539 EndBatch();
8540 }
8541
8542 void wxGrid::SetColSizes(const wxGridSizesInfo& sizeInfo)
8543 {
8544 DoSetSizes(sizeInfo, wxGridColumnOperations());
8545 }
8546
8547 void wxGrid::SetRowSizes(const wxGridSizesInfo& sizeInfo)
8548 {
8549 DoSetSizes(sizeInfo, wxGridRowOperations());
8550 }
8551
8552 wxGridSizesInfo::wxGridSizesInfo(int defSize, const wxArrayInt& allSizes)
8553 {
8554 m_sizeDefault = defSize;
8555 for ( size_t i = 0; i < allSizes.size(); i++ )
8556 {
8557 if ( allSizes[i] != defSize )
8558 m_customSizes[i] = allSizes[i];
8559 }
8560 }
8561
8562 int wxGridSizesInfo::GetSize(unsigned pos) const
8563 {
8564 wxUnsignedToIntHashMap::const_iterator it = m_customSizes.find(pos);
8565
8566 return it == m_customSizes.end() ? m_sizeDefault : it->second;
8567 }
8568
8569 // ----------------------------------------------------------------------------
8570 // drop target
8571 // ----------------------------------------------------------------------------
8572
8573 #if wxUSE_DRAG_AND_DROP
8574
8575 // this allow setting drop target directly on wxGrid
8576 void wxGrid::SetDropTarget(wxDropTarget *dropTarget)
8577 {
8578 GetGridWindow()->SetDropTarget(dropTarget);
8579 }
8580
8581 #endif // wxUSE_DRAG_AND_DROP
8582
8583 // ----------------------------------------------------------------------------
8584 // grid event classes
8585 // ----------------------------------------------------------------------------
8586
8587 IMPLEMENT_DYNAMIC_CLASS( wxGridEvent, wxNotifyEvent )
8588
8589 wxGridEvent::wxGridEvent( int id, wxEventType type, wxObject* obj,
8590 int row, int col, int x, int y, bool sel,
8591 bool control, bool shift, bool alt, bool meta )
8592 : wxNotifyEvent( type, id ),
8593 wxKeyboardState(control, shift, alt, meta)
8594 {
8595 Init(row, col, x, y, sel);
8596
8597 SetEventObject(obj);
8598 }
8599
8600 IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent, wxNotifyEvent )
8601
8602 wxGridSizeEvent::wxGridSizeEvent( int id, wxEventType type, wxObject* obj,
8603 int rowOrCol, int x, int y,
8604 bool control, bool shift, bool alt, bool meta )
8605 : wxNotifyEvent( type, id ),
8606 wxKeyboardState(control, shift, alt, meta)
8607 {
8608 Init(rowOrCol, x, y);
8609
8610 SetEventObject(obj);
8611 }
8612
8613
8614 IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent, wxNotifyEvent )
8615
8616 wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id, wxEventType type, wxObject* obj,
8617 const wxGridCellCoords& topLeft,
8618 const wxGridCellCoords& bottomRight,
8619 bool sel, bool control,
8620 bool shift, bool alt, bool meta )
8621 : wxNotifyEvent( type, id ),
8622 wxKeyboardState(control, shift, alt, meta)
8623 {
8624 Init(topLeft, bottomRight, sel);
8625
8626 SetEventObject(obj);
8627 }
8628
8629
8630 IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent, wxCommandEvent)
8631
8632 wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id, wxEventType type,
8633 wxObject* obj, int row,
8634 int col, wxControl* ctrl)
8635 : wxCommandEvent(type, id)
8636 {
8637 SetEventObject(obj);
8638 m_row = row;
8639 m_col = col;
8640 m_ctrl = ctrl;
8641 }
8642
8643
8644 // ----------------------------------------------------------------------------
8645 // wxGridTypeRegistry
8646 // ----------------------------------------------------------------------------
8647
8648 wxGridTypeRegistry::~wxGridTypeRegistry()
8649 {
8650 size_t count = m_typeinfo.GetCount();
8651 for ( size_t i = 0; i < count; i++ )
8652 delete m_typeinfo[i];
8653 }
8654
8655 void wxGridTypeRegistry::RegisterDataType(const wxString& typeName,
8656 wxGridCellRenderer* renderer,
8657 wxGridCellEditor* editor)
8658 {
8659 wxGridDataTypeInfo* info = new wxGridDataTypeInfo(typeName, renderer, editor);
8660
8661 // is it already registered?
8662 int loc = FindRegisteredDataType(typeName);
8663 if ( loc != wxNOT_FOUND )
8664 {
8665 delete m_typeinfo[loc];
8666 m_typeinfo[loc] = info;
8667 }
8668 else
8669 {
8670 m_typeinfo.Add(info);
8671 }
8672 }
8673
8674 int wxGridTypeRegistry::FindRegisteredDataType(const wxString& typeName)
8675 {
8676 size_t count = m_typeinfo.GetCount();
8677 for ( size_t i = 0; i < count; i++ )
8678 {
8679 if ( typeName == m_typeinfo[i]->m_typeName )
8680 {
8681 return i;
8682 }
8683 }
8684
8685 return wxNOT_FOUND;
8686 }
8687
8688 int wxGridTypeRegistry::FindDataType(const wxString& typeName)
8689 {
8690 int index = FindRegisteredDataType(typeName);
8691 if ( index == wxNOT_FOUND )
8692 {
8693 // check whether this is one of the standard ones, in which case
8694 // register it "on the fly"
8695 #if wxUSE_TEXTCTRL
8696 if ( typeName == wxGRID_VALUE_STRING )
8697 {
8698 RegisterDataType(wxGRID_VALUE_STRING,
8699 new wxGridCellStringRenderer,
8700 new wxGridCellTextEditor);
8701 }
8702 else
8703 #endif // wxUSE_TEXTCTRL
8704 #if wxUSE_CHECKBOX
8705 if ( typeName == wxGRID_VALUE_BOOL )
8706 {
8707 RegisterDataType(wxGRID_VALUE_BOOL,
8708 new wxGridCellBoolRenderer,
8709 new wxGridCellBoolEditor);
8710 }
8711 else
8712 #endif // wxUSE_CHECKBOX
8713 #if wxUSE_TEXTCTRL
8714 if ( typeName == wxGRID_VALUE_NUMBER )
8715 {
8716 RegisterDataType(wxGRID_VALUE_NUMBER,
8717 new wxGridCellNumberRenderer,
8718 new wxGridCellNumberEditor);
8719 }
8720 else if ( typeName == wxGRID_VALUE_FLOAT )
8721 {
8722 RegisterDataType(wxGRID_VALUE_FLOAT,
8723 new wxGridCellFloatRenderer,
8724 new wxGridCellFloatEditor);
8725 }
8726 else
8727 #endif // wxUSE_TEXTCTRL
8728 #if wxUSE_COMBOBOX
8729 if ( typeName == wxGRID_VALUE_CHOICE )
8730 {
8731 RegisterDataType(wxGRID_VALUE_CHOICE,
8732 new wxGridCellStringRenderer,
8733 new wxGridCellChoiceEditor);
8734 }
8735 else
8736 #endif // wxUSE_COMBOBOX
8737 {
8738 return wxNOT_FOUND;
8739 }
8740
8741 // we get here only if just added the entry for this type, so return
8742 // the last index
8743 index = m_typeinfo.GetCount() - 1;
8744 }
8745
8746 return index;
8747 }
8748
8749 int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName)
8750 {
8751 int index = FindDataType(typeName);
8752 if ( index == wxNOT_FOUND )
8753 {
8754 // the first part of the typename is the "real" type, anything after ':'
8755 // are the parameters for the renderer
8756 index = FindDataType(typeName.BeforeFirst(wxT(':')));
8757 if ( index == wxNOT_FOUND )
8758 {
8759 return wxNOT_FOUND;
8760 }
8761
8762 wxGridCellRenderer *renderer = GetRenderer(index);
8763 wxGridCellRenderer *rendererOld = renderer;
8764 renderer = renderer->Clone();
8765 rendererOld->DecRef();
8766
8767 wxGridCellEditor *editor = GetEditor(index);
8768 wxGridCellEditor *editorOld = editor;
8769 editor = editor->Clone();
8770 editorOld->DecRef();
8771
8772 // do it even if there are no parameters to reset them to defaults
8773 wxString params = typeName.AfterFirst(wxT(':'));
8774 renderer->SetParameters(params);
8775 editor->SetParameters(params);
8776
8777 // register the new typename
8778 RegisterDataType(typeName, renderer, editor);
8779
8780 // we just registered it, it's the last one
8781 index = m_typeinfo.GetCount() - 1;
8782 }
8783
8784 return index;
8785 }
8786
8787 wxGridCellRenderer* wxGridTypeRegistry::GetRenderer(int index)
8788 {
8789 wxGridCellRenderer* renderer = m_typeinfo[index]->m_renderer;
8790 if (renderer)
8791 renderer->IncRef();
8792
8793 return renderer;
8794 }
8795
8796 wxGridCellEditor* wxGridTypeRegistry::GetEditor(int index)
8797 {
8798 wxGridCellEditor* editor = m_typeinfo[index]->m_editor;
8799 if (editor)
8800 editor->IncRef();
8801
8802 return editor;
8803 }
8804
8805 #endif // wxUSE_GRID