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