]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/generic/grid.cpp
Improve wxGTK print and page setup dialogs.
[wxWidgets.git] / src / generic / grid.cpp
... / ...
CommitLineData
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
58const 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
75WX_DECLARE_HASH_SET_WITH_DECL(int, wxIntegerHash, wxIntegerEqual,
76 wxGridFixedIndicesSet, class WXDLLIMPEXP_ADV);
77
78
79// ----------------------------------------------------------------------------
80// globals
81// ----------------------------------------------------------------------------
82
83namespace
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
96struct DefaultHeaderRenderers
97{
98 wxGridColumnHeaderRendererDefault colRenderer;
99 wxGridRowHeaderRendererDefault rowRenderer;
100 wxGridCornerHeaderRendererDefault cornerRenderer;
101} gs_defaultHeaderRenderers;
102
103} // anonymous namespace
104
105// ----------------------------------------------------------------------------
106// constants
107// ----------------------------------------------------------------------------
108
109wxGridCellCoords wxGridNoCellCoords( -1, -1 );
110wxRect wxGridNoCellRect( -1, -1, -1, -1 );
111
112namespace
113{
114
115// scroll line size
116const size_t GRID_SCROLL_LINE_X = 15;
117const 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)
121const int GRID_HASH_SIZE = 100;
122
123// the minimal distance in pixels the mouse needs to move to start a drag
124// operation
125const int DRAG_SENSITIVITY = 3;
126
127} // anonymous namespace
128
129#include "wx/arrimpl.cpp"
130
131WX_DEFINE_OBJARRAY(wxGridCellCoordsArray)
132WX_DEFINE_OBJARRAY(wxGridCellWithAttrArray)
133
134// ----------------------------------------------------------------------------
135// events
136// ----------------------------------------------------------------------------
137
138wxDEFINE_EVENT( wxEVT_GRID_CELL_LEFT_CLICK, wxGridEvent );
139wxDEFINE_EVENT( wxEVT_GRID_CELL_RIGHT_CLICK, wxGridEvent );
140wxDEFINE_EVENT( wxEVT_GRID_CELL_LEFT_DCLICK, wxGridEvent );
141wxDEFINE_EVENT( wxEVT_GRID_CELL_RIGHT_DCLICK, wxGridEvent );
142wxDEFINE_EVENT( wxEVT_GRID_CELL_BEGIN_DRAG, wxGridEvent );
143wxDEFINE_EVENT( wxEVT_GRID_LABEL_LEFT_CLICK, wxGridEvent );
144wxDEFINE_EVENT( wxEVT_GRID_LABEL_RIGHT_CLICK, wxGridEvent );
145wxDEFINE_EVENT( wxEVT_GRID_LABEL_LEFT_DCLICK, wxGridEvent );
146wxDEFINE_EVENT( wxEVT_GRID_LABEL_RIGHT_DCLICK, wxGridEvent );
147wxDEFINE_EVENT( wxEVT_GRID_ROW_SIZE, wxGridSizeEvent );
148wxDEFINE_EVENT( wxEVT_GRID_COL_SIZE, wxGridSizeEvent );
149wxDEFINE_EVENT( wxEVT_GRID_COL_MOVE, wxGridEvent );
150wxDEFINE_EVENT( wxEVT_GRID_COL_SORT, wxGridEvent );
151wxDEFINE_EVENT( wxEVT_GRID_RANGE_SELECT, wxGridRangeSelectEvent );
152wxDEFINE_EVENT( wxEVT_GRID_CELL_CHANGING, wxGridEvent );
153wxDEFINE_EVENT( wxEVT_GRID_CELL_CHANGED, wxGridEvent );
154wxDEFINE_EVENT( wxEVT_GRID_SELECT_CELL, wxGridEvent );
155wxDEFINE_EVENT( wxEVT_GRID_EDITOR_SHOWN, wxGridEvent );
156wxDEFINE_EVENT( wxEVT_GRID_EDITOR_HIDDEN, wxGridEvent );
157wxDEFINE_EVENT( wxEVT_GRID_EDITOR_CREATED, wxGridEditorCreatedEvent );
158
159// ============================================================================
160// implementation
161// ============================================================================
162
163IMPLEMENT_ABSTRACT_CLASS(wxGridCellEditorEvtHandler, wxEvtHandler)
164
165BEGIN_EVENT_TABLE( wxGridCellEditorEvtHandler, wxEvtHandler )
166 EVT_KILL_FOCUS( wxGridCellEditorEvtHandler::OnKillFocus )
167 EVT_KEY_DOWN( wxGridCellEditorEvtHandler::OnKeyDown )
168 EVT_CHAR( wxGridCellEditorEvtHandler::OnChar )
169END_EVENT_TABLE()
170
171BEGIN_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)
182END_EVENT_TABLE()
183
184wxGridOperations& wxGridRowOperations::Dual() const
185{
186 static wxGridColumnOperations s_colOper;
187
188 return s_colOper;
189}
190
191wxGridOperations& 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
203void wxGridCellWorker::SetParameters(const wxString& WXUNUSED(params))
204{
205 // nothing to do
206}
207
208wxGridCellWorker::~wxGridCellWorker()
209{
210}
211
212// ----------------------------------------------------------------------------
213// wxGridHeaderLabelsRenderer and related classes
214// ----------------------------------------------------------------------------
215
216void 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
231void 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
252void 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
273void 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
300void 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
315wxGridCellAttr *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
350void 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
390void 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
411const 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
428const 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
445const 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
462void 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
481void 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
490void 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
505wxGridCellRenderer* 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
549wxGridCellEditor* 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
596void 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
626wxGridCellAttr *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
640void 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
674void 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
708int 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
727wxGridRowOrColAttrData::~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
736wxGridCellAttr *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
750void 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
787void 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
822wxGridCellAttrProvider::wxGridCellAttrProvider()
823{
824 m_data = NULL;
825}
826
827wxGridCellAttrProvider::~wxGridCellAttrProvider()
828{
829 delete m_data;
830}
831
832void wxGridCellAttrProvider::InitData()
833{
834 m_data = new wxGridCellAttrProviderData;
835}
836
837wxGridCellAttr *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
928void 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
937void wxGridCellAttrProvider::SetRowAttr(wxGridCellAttr *attr, int row)
938{
939 if ( !m_data )
940 InitData();
941
942 m_data->m_rowAttrs.SetAttr(attr, row);
943}
944
945void wxGridCellAttrProvider::SetColAttr(wxGridCellAttr *attr, int col)
946{
947 if ( !m_data )
948 InitData();
949
950 m_data->m_colAttrs.SetAttr(attr, col);
951}
952
953void 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
963void 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
973const wxGridColumnHeaderRenderer&
974wxGridCellAttrProvider::GetColumnHeaderRenderer(int WXUNUSED(col))
975{
976 return gs_defaultHeaderRenderers.colRenderer;
977}
978
979const wxGridRowHeaderRenderer&
980wxGridCellAttrProvider::GetRowHeaderRenderer(int WXUNUSED(row))
981{
982 return gs_defaultHeaderRenderers.rowRenderer;
983}
984
985const wxGridCornerHeaderRenderer& wxGridCellAttrProvider::GetCornerRenderer()
986{
987 return gs_defaultHeaderRenderers.cornerRenderer;
988}
989
990// ----------------------------------------------------------------------------
991// wxGridTableBase
992// ----------------------------------------------------------------------------
993
994IMPLEMENT_ABSTRACT_CLASS( wxGridTableBase, wxObject )
995
996wxGridTableBase::wxGridTableBase()
997{
998 m_view = NULL;
999 m_attrProvider = NULL;
1000}
1001
1002wxGridTableBase::~wxGridTableBase()
1003{
1004 delete m_attrProvider;
1005}
1006
1007void wxGridTableBase::SetAttrProvider(wxGridCellAttrProvider *attrProvider)
1008{
1009 delete m_attrProvider;
1010 m_attrProvider = attrProvider;
1011}
1012
1013bool 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
1024wxGridCellAttr *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
1032void 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
1048void 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
1063void 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
1078bool 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
1086bool 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
1093bool 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
1101bool 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
1109bool 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
1116bool 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
1124wxString 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
1135wxString 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
1162wxString wxGridTableBase::GetTypeName( int WXUNUSED(row), int WXUNUSED(col) )
1163{
1164 return wxGRID_VALUE_STRING;
1165}
1166
1167bool wxGridTableBase::CanGetValueAs( int WXUNUSED(row), int WXUNUSED(col),
1168 const wxString& typeName )
1169{
1170 return typeName == wxGRID_VALUE_STRING;
1171}
1172
1173bool wxGridTableBase::CanSetValueAs( int row, int col, const wxString& typeName )
1174{
1175 return CanGetValueAs(row, col, typeName);
1176}
1177
1178long wxGridTableBase::GetValueAsLong( int WXUNUSED(row), int WXUNUSED(col) )
1179{
1180 return 0;
1181}
1182
1183double wxGridTableBase::GetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col) )
1184{
1185 return 0.0;
1186}
1187
1188bool wxGridTableBase::GetValueAsBool( int WXUNUSED(row), int WXUNUSED(col) )
1189{
1190 return false;
1191}
1192
1193void wxGridTableBase::SetValueAsLong( int WXUNUSED(row), int WXUNUSED(col),
1194 long WXUNUSED(value) )
1195{
1196}
1197
1198void wxGridTableBase::SetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col),
1199 double WXUNUSED(value) )
1200{
1201}
1202
1203void wxGridTableBase::SetValueAsBool( int WXUNUSED(row), int WXUNUSED(col),
1204 bool WXUNUSED(value) )
1205{
1206}
1207
1208void* wxGridTableBase::GetValueAsCustom( int WXUNUSED(row), int WXUNUSED(col),
1209 const wxString& WXUNUSED(typeName) )
1210{
1211 return NULL;
1212}
1213
1214void 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
1226wxGridTableMessage::wxGridTableMessage()
1227{
1228 m_table = NULL;
1229 m_id = -1;
1230 m_comInt1 = -1;
1231 m_comInt2 = -1;
1232}
1233
1234wxGridTableMessage::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
1249WX_DEFINE_OBJARRAY(wxGridStringArray)
1250
1251IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable, wxGridTableBase )
1252
1253wxGridStringTable::wxGridStringTable()
1254 : wxGridTableBase()
1255{
1256 m_numCols = 0;
1257}
1258
1259wxGridStringTable::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
1273wxString 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
1283void 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
1292void 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
1312bool 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
1341bool 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
1369bool 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
1413bool 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
1459bool 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
1484bool 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
1557wxString 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
1571wxString 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
1585void 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
1601void 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
1621BEGIN_EVENT_TABLE(wxGridSubwindow, wxWindow)
1622 EVT_MOUSE_CAPTURE_LOST(wxGridSubwindow::OnMouseCaptureLost)
1623END_EVENT_TABLE()
1624
1625void wxGridSubwindow::OnMouseCaptureLost(wxMouseCaptureLostEvent& WXUNUSED(event))
1626{
1627 m_owner->CancelMouseCapture();
1628}
1629
1630BEGIN_EVENT_TABLE( wxGridRowLabelWindow, wxGridSubwindow )
1631 EVT_PAINT( wxGridRowLabelWindow::OnPaint )
1632 EVT_MOUSEWHEEL( wxGridRowLabelWindow::OnMouseWheel )
1633 EVT_MOUSE_EVENTS( wxGridRowLabelWindow::OnMouseEvent )
1634END_EVENT_TABLE()
1635
1636void 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
1655void wxGridRowLabelWindow::OnMouseEvent( wxMouseEvent& event )
1656{
1657 m_owner->ProcessRowLabelMouseEvent( event );
1658}
1659
1660void wxGridRowLabelWindow::OnMouseWheel( wxMouseEvent& event )
1661{
1662 if (!m_owner->GetEventHandler()->ProcessEvent( event ))
1663 event.Skip();
1664}
1665
1666//////////////////////////////////////////////////////////////////////
1667
1668BEGIN_EVENT_TABLE( wxGridColLabelWindow, wxGridSubwindow )
1669 EVT_PAINT( wxGridColLabelWindow::OnPaint )
1670 EVT_MOUSEWHEEL( wxGridColLabelWindow::OnMouseWheel )
1671 EVT_MOUSE_EVENTS( wxGridColLabelWindow::OnMouseEvent )
1672END_EVENT_TABLE()
1673
1674void 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
1696void wxGridColLabelWindow::OnMouseEvent( wxMouseEvent& event )
1697{
1698 m_owner->ProcessColLabelMouseEvent( event );
1699}
1700
1701void wxGridColLabelWindow::OnMouseWheel( wxMouseEvent& event )
1702{
1703 if (!m_owner->GetEventHandler()->ProcessEvent( event ))
1704 event.Skip();
1705}
1706
1707//////////////////////////////////////////////////////////////////////
1708
1709BEGIN_EVENT_TABLE( wxGridCornerLabelWindow, wxGridSubwindow )
1710 EVT_MOUSEWHEEL( wxGridCornerLabelWindow::OnMouseWheel )
1711 EVT_MOUSE_EVENTS( wxGridCornerLabelWindow::OnMouseEvent )
1712 EVT_PAINT( wxGridCornerLabelWindow::OnPaint )
1713END_EVENT_TABLE()
1714
1715void wxGridCornerLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
1716{
1717 wxPaintDC dc(this);
1718
1719 m_owner->DrawCornerLabel(dc);
1720}
1721
1722void wxGridCornerLabelWindow::OnMouseEvent( wxMouseEvent& event )
1723{
1724 m_owner->ProcessCornerLabelMouseEvent( event );
1725}
1726
1727void wxGridCornerLabelWindow::OnMouseWheel( wxMouseEvent& event )
1728{
1729 if (!m_owner->GetEventHandler()->ProcessEvent(event))
1730 event.Skip();
1731}
1732
1733//////////////////////////////////////////////////////////////////////
1734
1735BEGIN_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 )
1745END_EVENT_TABLE()
1746
1747void 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
1762void 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
1769void wxGridWindow::OnMouseEvent( wxMouseEvent& event )
1770{
1771 if (event.ButtonDown(wxMOUSE_BTN_LEFT) && FindFocus() != this)
1772 SetFocus();
1773
1774 m_owner->ProcessGridCellMouseEvent( event );
1775}
1776
1777void 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//
1786void wxGridWindow::OnKeyDown( wxKeyEvent& event )
1787{
1788 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
1789 event.Skip();
1790}
1791
1792void wxGridWindow::OnKeyUp( wxKeyEvent& event )
1793{
1794 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
1795 event.Skip();
1796}
1797
1798void wxGridWindow::OnChar( wxKeyEvent& event )
1799{
1800 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
1801 event.Skip();
1802}
1803
1804void wxGridWindow::OnEraseBackground( wxEraseEvent& WXUNUSED(event) )
1805{
1806}
1807
1808void 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
1843WX_DEFINE_FLAGS( wxGridStyle )
1844
1845wxBEGIN_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
1873wxEND_FLAGS( wxGridStyle )
1874
1875IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid, wxScrolledWindow,"wx/grid.h")
1876
1877wxBEGIN_PROPERTIES_TABLE(wxGrid)
1878 wxHIDE_PROPERTY( Children )
1879 wxPROPERTY_FLAGS( WindowStyle , wxGridStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
1880wxEND_PROPERTIES_TABLE()
1881
1882wxBEGIN_HANDLERS_TABLE(wxGrid)
1883wxEND_HANDLERS_TABLE()
1884
1885wxCONSTRUCTOR_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
1891IMPLEMENT_DYNAMIC_CLASS( wxGrid, wxScrolledWindow )
1892#endif
1893
1894BEGIN_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 )
1901END_EVENT_TABLE()
1902
1903bool 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
1921wxGrid::~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
1966void 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
2045void 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
2059bool 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
2069void 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
2077wxGrid::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
2085bool
2086wxGrid::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
2160void 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
2271void 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
2289void 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
2306int wxGrid::GetColWidth(int col) const
2307{
2308 return m_colWidths.IsEmpty() ? m_defaultColWidth : m_colWidths[col];
2309}
2310
2311int wxGrid::GetColLeft(int col) const
2312{
2313 return m_colRights.IsEmpty() ? GetColPos( col ) * m_defaultColWidth
2314 : m_colRights[col] - m_colWidths[col];
2315}
2316
2317int wxGrid::GetColRight(int col) const
2318{
2319 return m_colRights.IsEmpty() ? (GetColPos( col ) + 1) * m_defaultColWidth
2320 : m_colRights[col];
2321}
2322
2323int wxGrid::GetRowHeight(int row) const
2324{
2325 return m_rowHeights.IsEmpty() ? m_defaultRowHeight : m_rowHeights[row];
2326}
2327
2328int wxGrid::GetRowTop(int row) const
2329{
2330 return m_rowBottoms.IsEmpty() ? row * m_defaultRowHeight
2331 : m_rowBottoms[row] - m_rowHeights[row];
2332}
2333
2334int wxGrid::GetRowBottom(int row) const
2335{
2336 return m_rowBottoms.IsEmpty() ? (row + 1) * m_defaultRowHeight
2337 : m_rowBottoms[row];
2338}
2339
2340void 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
2392wxSize 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
2401void 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//
2436bool 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
2804wxArrayInt 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
2855wxArrayInt 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
2909wxGridCellCoordsArray 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
2976void 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
3173void 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
3184void 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
3216void 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
3227void wxGrid::DoStartResizeCol(int col)
3228{
3229 m_dragRowOrCol = col;
3230 m_dragLastPos = -1;
3231 DoUpdateResizeColWidth(GetColWidth(m_dragRowOrCol));
3232}
3233
3234void 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
3253void wxGrid::DoUpdateResizeColWidth(int w)
3254{
3255 DoUpdateResizeCol(GetColLeft(m_dragRowOrCol) + w);
3256}
3257
3258void 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
3561void 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
3593void 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
3610void 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
3686void
3687wxGrid::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
3731void 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
3757void 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
3805void
3806wxGrid::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
3875void
3876wxGrid::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
3891void
3892wxGrid::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
3947void
3948wxGrid::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
4000void 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
4069bool 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
4168void 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
4176void 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
4184void wxGrid::DoStartMoveCol(int col)
4185{
4186 m_dragRowOrCol = col;
4187}
4188
4189void 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
4200void 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
4232void wxGrid::SetColumnsOrder(const wxArrayInt& order)
4233{
4234 m_colAt = order;
4235
4236 RefreshAfterColPosChange();
4237}
4238
4239void 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
4254void wxGrid::ResetColPos()
4255{
4256 m_colAt.clear();
4257
4258 RefreshAfterColPosChange();
4259}
4260
4261void 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//
4284bool 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//
4312void 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
4325bool
4326wxGrid::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
4343bool
4344wxGrid::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
4359void
4360wxGrid::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
4381int
4382wxGrid::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//
4448int
4449wxGrid::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
4463void wxGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
4464{
4465 // needed to prevent zillions of paint events on MSW
4466 wxPaintDC dc(this);
4467}
4468
4469void 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
4558void 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
4567void 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
4735void 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
4759void 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
4800void wxGrid::OnEraseBackground(wxEraseEvent&)
4801{
4802}
4803
4804bool 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
4858void
4859wxGrid::UpdateBlockBeingSelected(int topRow, int leftCol,
4860 int bottomRow, int rightCol)
4861{
4862 if ( m_selection )
4863 {
4864 switch ( m_selection->GetSelectionMode() )
4865 {
4866 default:
4867 wxFAIL_MSG( "unknown selection mode" );
4868 // fall through
4869
4870 case wxGridSelectCells:
4871 // arbitrary blocks selection allowed so just use the cell
4872 // coordinates as is
4873 break;
4874
4875 case wxGridSelectRows:
4876 // only full rows selection allowd, ensure that we do select
4877 // full rows
4878 leftCol = 0;
4879 rightCol = GetNumberCols() - 1;
4880 break;
4881
4882 case wxGridSelectColumns:
4883 // same as above but for columns
4884 topRow = 0;
4885 bottomRow = GetNumberRows() - 1;
4886 break;
4887
4888 case wxGridSelectRowsOrColumns:
4889 // in this mode we can select only full rows or full columns so
4890 // it doesn't make sense to select blocks at all (and we can't
4891 // extend the block because there is no preferred direction, we
4892 // could only extend it to cover the entire grid but this is
4893 // not useful)
4894 return;
4895 }
4896 }
4897
4898 m_selectedBlockCorner = wxGridCellCoords(bottomRow, rightCol);
4899 MakeCellVisible(m_selectedBlockCorner);
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
5003bool 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
5019bool 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//
5048void 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
5164void 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
5195void 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
5235void 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
5278wxPen wxGrid::GetDefaultGridLinePen()
5279{
5280 return wxPen(GetGridLineColour());
5281}
5282
5283wxPen wxGrid::GetRowGridLinePen(int WXUNUSED(row))
5284{
5285 return GetDefaultGridLinePen();
5286}
5287
5288wxPen wxGrid::GetColGridLinePen(int WXUNUSED(col))
5289{
5290 return GetDefaultGridLinePen();
5291}
5292
5293void 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
5314void 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//
5370void 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
5478void 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
5490void 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
5516void 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
5531void 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
5547void 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
5559void 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
5585void 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
5635void 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
5649void 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
5754void 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
5786void 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//
5809void 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//
5829void wxGrid::ForceRefresh()
5830{
5831 BeginBatch();
5832 EndBatch();
5833}
5834
5835bool 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
5850void wxGrid::EnableEditing( bool edit )
5851{
5852 if ( edit != m_editable )
5853 {
5854 if (!edit)
5855 EnableCellEditControl(edit);
5856 m_editable = edit;
5857 }
5858}
5859
5860void 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
5893bool wxGrid::IsCurrentCellReadOnly() const
5894{
5895 // const_cast
5896 wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords);
5897 bool readonly = attr->IsReadOnly();
5898 attr->DecRef();
5899
5900 return readonly;
5901}
5902
5903bool wxGrid::CanEnableCellControl() const
5904{
5905 return m_editable && (m_currentCellCoords != wxGridNoCellCoords) &&
5906 !IsCurrentCellReadOnly();
5907}
5908
5909bool 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
5916bool 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
5942void 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
6067void 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
6103void 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
6144wxGridCellCoords 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)
6157int 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
6239int
6240wxGrid::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
6249int wxGrid::YToRow(int y, bool clipToMinMax) const
6250{
6251 return PosToLine(y, clipToMinMax, wxGridRowOperations());
6252}
6253
6254int wxGrid::XToCol(int x, bool clipToMinMax) const
6255{
6256 return PosToLine(x, clipToMinMax, wxGridColumnOperations());
6257}
6258
6259int 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).
6271int 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 return line - 1;
6285 }
6286
6287 return -1;
6288}
6289
6290int wxGrid::YToEdgeOfRow(int y) const
6291{
6292 return PosToEdgeOfLine(y, wxGridRowOperations());
6293}
6294
6295int wxGrid::XToEdgeOfCol(int x) const
6296{
6297 return PosToEdgeOfLine(x, wxGridColumnOperations());
6298}
6299
6300wxRect wxGrid::CellToRect( int row, int col ) const
6301{
6302 wxRect rect( -1, -1, -1, -1 );
6303
6304 if ( row >= 0 && row < m_numRows &&
6305 col >= 0 && col < m_numCols )
6306 {
6307 int i, cell_rows, cell_cols;
6308 rect.width = rect.height = 0;
6309 GetCellSize( row, col, &cell_rows, &cell_cols );
6310 // if negative then find multicell owner
6311 if (cell_rows < 0)
6312 row += cell_rows;
6313 if (cell_cols < 0)
6314 col += cell_cols;
6315 GetCellSize( row, col, &cell_rows, &cell_cols );
6316
6317 rect.x = GetColLeft(col);
6318 rect.y = GetRowTop(row);
6319 for (i=col; i < col + cell_cols; i++)
6320 rect.width += GetColWidth(i);
6321 for (i=row; i < row + cell_rows; i++)
6322 rect.height += GetRowHeight(i);
6323
6324 // if grid lines are enabled, then the area of the cell is a bit smaller
6325 if (m_gridLinesEnabled)
6326 {
6327 rect.width -= 1;
6328 rect.height -= 1;
6329 }
6330 }
6331
6332 return rect;
6333}
6334
6335bool wxGrid::IsVisible( int row, int col, bool wholeCellVisible ) const
6336{
6337 // get the cell rectangle in logical coords
6338 //
6339 wxRect r( CellToRect( row, col ) );
6340
6341 // convert to device coords
6342 //
6343 int left, top, right, bottom;
6344 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
6345 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
6346
6347 // check against the client area of the grid window
6348 int cw, ch;
6349 m_gridWin->GetClientSize( &cw, &ch );
6350
6351 if ( wholeCellVisible )
6352 {
6353 // is the cell wholly visible ?
6354 return ( left >= 0 && right <= cw &&
6355 top >= 0 && bottom <= ch );
6356 }
6357 else
6358 {
6359 // is the cell partly visible ?
6360 //
6361 return ( ((left >= 0 && left < cw) || (right > 0 && right <= cw)) &&
6362 ((top >= 0 && top < ch) || (bottom > 0 && bottom <= ch)) );
6363 }
6364}
6365
6366// make the specified cell location visible by doing a minimal amount
6367// of scrolling
6368//
6369void wxGrid::MakeCellVisible( int row, int col )
6370{
6371 int i;
6372 int xpos = -1, ypos = -1;
6373
6374 if ( row >= 0 && row < m_numRows &&
6375 col >= 0 && col < m_numCols )
6376 {
6377 // get the cell rectangle in logical coords
6378 wxRect r( CellToRect( row, col ) );
6379
6380 // convert to device coords
6381 int left, top, right, bottom;
6382 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
6383 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
6384
6385 int cw, ch;
6386 m_gridWin->GetClientSize( &cw, &ch );
6387
6388 if ( top < 0 )
6389 {
6390 ypos = r.GetTop();
6391 }
6392 else if ( bottom > ch )
6393 {
6394 int h = r.GetHeight();
6395 ypos = r.GetTop();
6396 for ( i = row - 1; i >= 0; i-- )
6397 {
6398 int rowHeight = GetRowHeight(i);
6399 if ( h + rowHeight > ch )
6400 break;
6401
6402 h += rowHeight;
6403 ypos -= rowHeight;
6404 }
6405
6406 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
6407 // have rounding errors (this is important, because if we do,
6408 // we might not scroll at all and some cells won't be redrawn)
6409 //
6410 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
6411 // so just add a full scroll unit...
6412 ypos += m_yScrollPixelsPerLine;
6413 }
6414
6415 // special handling for wide cells - show always left part of the cell!
6416 // Otherwise, e.g. when stepping from row to row, it would jump between
6417 // left and right part of the cell on every step!
6418// if ( left < 0 )
6419 if ( left < 0 || (right - left) >= cw )
6420 {
6421 xpos = r.GetLeft();
6422 }
6423 else if ( right > cw )
6424 {
6425 // position the view so that the cell is on the right
6426 int x0, y0;
6427 CalcUnscrolledPosition(0, 0, &x0, &y0);
6428 xpos = x0 + (right - cw);
6429
6430 // see comment for ypos above
6431 xpos += m_xScrollPixelsPerLine;
6432 }
6433
6434 if ( xpos != -1 || ypos != -1 )
6435 {
6436 if ( xpos != -1 )
6437 xpos /= m_xScrollPixelsPerLine;
6438 if ( ypos != -1 )
6439 ypos /= m_yScrollPixelsPerLine;
6440 Scroll( xpos, ypos );
6441 AdjustScrollbars();
6442 }
6443 }
6444}
6445
6446//
6447// ------ Grid cursor movement functions
6448//
6449
6450bool
6451wxGrid::DoMoveCursor(bool expandSelection,
6452 const wxGridDirectionOperations& diroper)
6453{
6454 if ( m_currentCellCoords == wxGridNoCellCoords )
6455 return false;
6456
6457 if ( expandSelection )
6458 {
6459 wxGridCellCoords coords = m_selectedBlockCorner;
6460 if ( coords == wxGridNoCellCoords )
6461 coords = m_currentCellCoords;
6462
6463 if ( diroper.IsAtBoundary(coords) )
6464 return false;
6465
6466 diroper.Advance(coords);
6467
6468 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6469 }
6470 else // don't expand selection
6471 {
6472 ClearSelection();
6473
6474 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6475 return false;
6476
6477 wxGridCellCoords coords = m_currentCellCoords;
6478 diroper.Advance(coords);
6479
6480 GoToCell(coords);
6481 }
6482
6483 return true;
6484}
6485
6486bool wxGrid::MoveCursorUp(bool expandSelection)
6487{
6488 return DoMoveCursor(expandSelection,
6489 wxGridBackwardOperations(this, wxGridRowOperations()));
6490}
6491
6492bool wxGrid::MoveCursorDown(bool expandSelection)
6493{
6494 return DoMoveCursor(expandSelection,
6495 wxGridForwardOperations(this, wxGridRowOperations()));
6496}
6497
6498bool wxGrid::MoveCursorLeft(bool expandSelection)
6499{
6500 return DoMoveCursor(expandSelection,
6501 wxGridBackwardOperations(this, wxGridColumnOperations()));
6502}
6503
6504bool wxGrid::MoveCursorRight(bool expandSelection)
6505{
6506 return DoMoveCursor(expandSelection,
6507 wxGridForwardOperations(this, wxGridColumnOperations()));
6508}
6509
6510bool wxGrid::DoMoveCursorByPage(const wxGridDirectionOperations& diroper)
6511{
6512 if ( m_currentCellCoords == wxGridNoCellCoords )
6513 return false;
6514
6515 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6516 return false;
6517
6518 const int oldRow = m_currentCellCoords.GetRow();
6519 int newRow = diroper.MoveByPixelDistance(oldRow, m_gridWin->GetClientSize().y);
6520 if ( newRow == oldRow )
6521 {
6522 wxGridCellCoords coords(m_currentCellCoords);
6523 diroper.Advance(coords);
6524 newRow = coords.GetRow();
6525 }
6526
6527 GoToCell(newRow, m_currentCellCoords.GetCol());
6528
6529 return true;
6530}
6531
6532bool wxGrid::MovePageUp()
6533{
6534 return DoMoveCursorByPage(
6535 wxGridBackwardOperations(this, wxGridRowOperations()));
6536}
6537
6538bool wxGrid::MovePageDown()
6539{
6540 return DoMoveCursorByPage(
6541 wxGridForwardOperations(this, wxGridRowOperations()));
6542}
6543
6544// helper of DoMoveCursorByBlock(): advance the cell coordinates using diroper
6545// until we find a non-empty cell or reach the grid end
6546void
6547wxGrid::AdvanceToNextNonEmpty(wxGridCellCoords& coords,
6548 const wxGridDirectionOperations& diroper)
6549{
6550 while ( !diroper.IsAtBoundary(coords) )
6551 {
6552 diroper.Advance(coords);
6553 if ( !m_table->IsEmpty(coords) )
6554 break;
6555 }
6556}
6557
6558bool
6559wxGrid::DoMoveCursorByBlock(bool expandSelection,
6560 const wxGridDirectionOperations& diroper)
6561{
6562 if ( !m_table || m_currentCellCoords == wxGridNoCellCoords )
6563 return false;
6564
6565 if ( diroper.IsAtBoundary(m_currentCellCoords) )
6566 return false;
6567
6568 wxGridCellCoords coords(m_currentCellCoords);
6569 if ( m_table->IsEmpty(coords) )
6570 {
6571 // we are in an empty cell: find the next block of non-empty cells
6572 AdvanceToNextNonEmpty(coords, diroper);
6573 }
6574 else // current cell is not empty
6575 {
6576 diroper.Advance(coords);
6577 if ( m_table->IsEmpty(coords) )
6578 {
6579 // we started at the end of a block, find the next one
6580 AdvanceToNextNonEmpty(coords, diroper);
6581 }
6582 else // we're in a middle of a block
6583 {
6584 // go to the end of it, i.e. find the last cell before the next
6585 // empty one
6586 while ( !diroper.IsAtBoundary(coords) )
6587 {
6588 wxGridCellCoords coordsNext(coords);
6589 diroper.Advance(coordsNext);
6590 if ( m_table->IsEmpty(coordsNext) )
6591 break;
6592
6593 coords = coordsNext;
6594 }
6595 }
6596 }
6597
6598 if ( expandSelection )
6599 {
6600 UpdateBlockBeingSelected(m_currentCellCoords, coords);
6601 }
6602 else
6603 {
6604 ClearSelection();
6605 GoToCell(coords);
6606 }
6607
6608 return true;
6609}
6610
6611bool wxGrid::MoveCursorUpBlock(bool expandSelection)
6612{
6613 return DoMoveCursorByBlock(
6614 expandSelection,
6615 wxGridBackwardOperations(this, wxGridRowOperations())
6616 );
6617}
6618
6619bool wxGrid::MoveCursorDownBlock( bool expandSelection )
6620{
6621 return DoMoveCursorByBlock(
6622 expandSelection,
6623 wxGridForwardOperations(this, wxGridRowOperations())
6624 );
6625}
6626
6627bool wxGrid::MoveCursorLeftBlock( bool expandSelection )
6628{
6629 return DoMoveCursorByBlock(
6630 expandSelection,
6631 wxGridBackwardOperations(this, wxGridColumnOperations())
6632 );
6633}
6634
6635bool wxGrid::MoveCursorRightBlock( bool expandSelection )
6636{
6637 return DoMoveCursorByBlock(
6638 expandSelection,
6639 wxGridForwardOperations(this, wxGridColumnOperations())
6640 );
6641}
6642
6643//
6644// ------ Label values and formatting
6645//
6646
6647void wxGrid::GetRowLabelAlignment( int *horiz, int *vert ) const
6648{
6649 if ( horiz )
6650 *horiz = m_rowLabelHorizAlign;
6651 if ( vert )
6652 *vert = m_rowLabelVertAlign;
6653}
6654
6655void wxGrid::GetColLabelAlignment( int *horiz, int *vert ) const
6656{
6657 if ( horiz )
6658 *horiz = m_colLabelHorizAlign;
6659 if ( vert )
6660 *vert = m_colLabelVertAlign;
6661}
6662
6663int wxGrid::GetColLabelTextOrientation() const
6664{
6665 return m_colLabelTextOrientation;
6666}
6667
6668wxString wxGrid::GetRowLabelValue( int row ) const
6669{
6670 if ( m_table )
6671 {
6672 return m_table->GetRowLabelValue( row );
6673 }
6674 else
6675 {
6676 wxString s;
6677 s << row;
6678 return s;
6679 }
6680}
6681
6682wxString wxGrid::GetColLabelValue( int col ) const
6683{
6684 if ( m_table )
6685 {
6686 return m_table->GetColLabelValue( col );
6687 }
6688 else
6689 {
6690 wxString s;
6691 s << col;
6692 return s;
6693 }
6694}
6695
6696void wxGrid::SetRowLabelSize( int width )
6697{
6698 wxASSERT( width >= 0 || width == wxGRID_AUTOSIZE );
6699
6700 if ( width == wxGRID_AUTOSIZE )
6701 {
6702 width = CalcColOrRowLabelAreaMinSize(wxGRID_ROW);
6703 }
6704
6705 if ( width != m_rowLabelWidth )
6706 {
6707 if ( width == 0 )
6708 {
6709 m_rowLabelWin->Show( false );
6710 m_cornerLabelWin->Show( false );
6711 }
6712 else if ( m_rowLabelWidth == 0 )
6713 {
6714 m_rowLabelWin->Show( true );
6715 if ( m_colLabelHeight > 0 )
6716 m_cornerLabelWin->Show( true );
6717 }
6718
6719 m_rowLabelWidth = width;
6720 CalcWindowSizes();
6721 wxScrolledWindow::Refresh( true );
6722 }
6723}
6724
6725void wxGrid::SetColLabelSize( int height )
6726{
6727 wxASSERT( height >=0 || height == wxGRID_AUTOSIZE );
6728
6729 if ( height == wxGRID_AUTOSIZE )
6730 {
6731 height = CalcColOrRowLabelAreaMinSize(wxGRID_COLUMN);
6732 }
6733
6734 if ( height != m_colLabelHeight )
6735 {
6736 if ( height == 0 )
6737 {
6738 m_colWindow->Show( false );
6739 m_cornerLabelWin->Show( false );
6740 }
6741 else if ( m_colLabelHeight == 0 )
6742 {
6743 m_colWindow->Show( true );
6744 if ( m_rowLabelWidth > 0 )
6745 m_cornerLabelWin->Show( true );
6746 }
6747
6748 m_colLabelHeight = height;
6749 CalcWindowSizes();
6750 wxScrolledWindow::Refresh( true );
6751 }
6752}
6753
6754void wxGrid::SetLabelBackgroundColour( const wxColour& colour )
6755{
6756 if ( m_labelBackgroundColour != colour )
6757 {
6758 m_labelBackgroundColour = colour;
6759 m_rowLabelWin->SetBackgroundColour( colour );
6760 m_colWindow->SetBackgroundColour( colour );
6761 m_cornerLabelWin->SetBackgroundColour( colour );
6762
6763 if ( !GetBatchCount() )
6764 {
6765 m_rowLabelWin->Refresh();
6766 m_colWindow->Refresh();
6767 m_cornerLabelWin->Refresh();
6768 }
6769 }
6770}
6771
6772void wxGrid::SetLabelTextColour( const wxColour& colour )
6773{
6774 if ( m_labelTextColour != colour )
6775 {
6776 m_labelTextColour = colour;
6777 if ( !GetBatchCount() )
6778 {
6779 m_rowLabelWin->Refresh();
6780 m_colWindow->Refresh();
6781 }
6782 }
6783}
6784
6785void wxGrid::SetLabelFont( const wxFont& font )
6786{
6787 m_labelFont = font;
6788 if ( !GetBatchCount() )
6789 {
6790 m_rowLabelWin->Refresh();
6791 m_colWindow->Refresh();
6792 }
6793}
6794
6795void wxGrid::SetRowLabelAlignment( int horiz, int vert )
6796{
6797 // allow old (incorrect) defs to be used
6798 switch ( horiz )
6799 {
6800 case wxLEFT: horiz = wxALIGN_LEFT; break;
6801 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
6802 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
6803 }
6804
6805 switch ( vert )
6806 {
6807 case wxTOP: vert = wxALIGN_TOP; break;
6808 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
6809 case wxCENTRE: vert = wxALIGN_CENTRE; break;
6810 }
6811
6812 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
6813 {
6814 m_rowLabelHorizAlign = horiz;
6815 }
6816
6817 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
6818 {
6819 m_rowLabelVertAlign = vert;
6820 }
6821
6822 if ( !GetBatchCount() )
6823 {
6824 m_rowLabelWin->Refresh();
6825 }
6826}
6827
6828void wxGrid::SetColLabelAlignment( int horiz, int vert )
6829{
6830 // allow old (incorrect) defs to be used
6831 switch ( horiz )
6832 {
6833 case wxLEFT: horiz = wxALIGN_LEFT; break;
6834 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
6835 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
6836 }
6837
6838 switch ( vert )
6839 {
6840 case wxTOP: vert = wxALIGN_TOP; break;
6841 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
6842 case wxCENTRE: vert = wxALIGN_CENTRE; break;
6843 }
6844
6845 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
6846 {
6847 m_colLabelHorizAlign = horiz;
6848 }
6849
6850 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
6851 {
6852 m_colLabelVertAlign = vert;
6853 }
6854
6855 if ( !GetBatchCount() )
6856 {
6857 m_colWindow->Refresh();
6858 }
6859}
6860
6861// Note: under MSW, the default column label font must be changed because it
6862// does not support vertical printing
6863//
6864// Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
6865// pGrid->SetLabelFont(font);
6866// pGrid->SetColLabelTextOrientation(wxVERTICAL);
6867//
6868void wxGrid::SetColLabelTextOrientation( int textOrientation )
6869{
6870 if ( textOrientation == wxHORIZONTAL || textOrientation == wxVERTICAL )
6871 m_colLabelTextOrientation = textOrientation;
6872
6873 if ( !GetBatchCount() )
6874 m_colWindow->Refresh();
6875}
6876
6877void wxGrid::SetRowLabelValue( int row, const wxString& s )
6878{
6879 if ( m_table )
6880 {
6881 m_table->SetRowLabelValue( row, s );
6882 if ( !GetBatchCount() )
6883 {
6884 wxRect rect = CellToRect( row, 0 );
6885 if ( rect.height > 0 )
6886 {
6887 CalcScrolledPosition(0, rect.y, &rect.x, &rect.y);
6888 rect.x = 0;
6889 rect.width = m_rowLabelWidth;
6890 m_rowLabelWin->Refresh( true, &rect );
6891 }
6892 }
6893 }
6894}
6895
6896void wxGrid::SetColLabelValue( int col, const wxString& s )
6897{
6898 if ( m_table )
6899 {
6900 m_table->SetColLabelValue( col, s );
6901 if ( !GetBatchCount() )
6902 {
6903 if ( m_useNativeHeader )
6904 {
6905 GetGridColHeader()->UpdateColumn(col);
6906 }
6907 else
6908 {
6909 wxRect rect = CellToRect( 0, col );
6910 if ( rect.width > 0 )
6911 {
6912 CalcScrolledPosition(rect.x, 0, &rect.x, &rect.y);
6913 rect.y = 0;
6914 rect.height = m_colLabelHeight;
6915 GetColLabelWindow()->Refresh( true, &rect );
6916 }
6917 }
6918 }
6919 }
6920}
6921
6922void wxGrid::SetGridLineColour( const wxColour& colour )
6923{
6924 if ( m_gridLineColour != colour )
6925 {
6926 m_gridLineColour = colour;
6927
6928 if ( GridLinesEnabled() )
6929 RedrawGridLines();
6930 }
6931}
6932
6933void wxGrid::SetCellHighlightColour( const wxColour& colour )
6934{
6935 if ( m_cellHighlightColour != colour )
6936 {
6937 m_cellHighlightColour = colour;
6938
6939 wxClientDC dc( m_gridWin );
6940 PrepareDC( dc );
6941 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
6942 DrawCellHighlight(dc, attr);
6943 attr->DecRef();
6944 }
6945}
6946
6947void wxGrid::SetCellHighlightPenWidth(int width)
6948{
6949 if (m_cellHighlightPenWidth != width)
6950 {
6951 m_cellHighlightPenWidth = width;
6952
6953 // Just redrawing the cell highlight is not enough since that won't
6954 // make any visible change if the the thickness is getting smaller.
6955 int row = m_currentCellCoords.GetRow();
6956 int col = m_currentCellCoords.GetCol();
6957 if ( row == -1 || col == -1 || GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
6958 return;
6959
6960 wxRect rect = CellToRect(row, col);
6961 m_gridWin->Refresh(true, &rect);
6962 }
6963}
6964
6965void wxGrid::SetCellHighlightROPenWidth(int width)
6966{
6967 if (m_cellHighlightROPenWidth != width)
6968 {
6969 m_cellHighlightROPenWidth = width;
6970
6971 // Just redrawing the cell highlight is not enough since that won't
6972 // make any visible change if the the thickness is getting smaller.
6973 int row = m_currentCellCoords.GetRow();
6974 int col = m_currentCellCoords.GetCol();
6975 if ( row == -1 || col == -1 ||
6976 GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
6977 return;
6978
6979 wxRect rect = CellToRect(row, col);
6980 m_gridWin->Refresh(true, &rect);
6981 }
6982}
6983
6984void wxGrid::RedrawGridLines()
6985{
6986 // the lines will be redrawn when the window is thawn
6987 if ( GetBatchCount() )
6988 return;
6989
6990 if ( GridLinesEnabled() )
6991 {
6992 wxClientDC dc( m_gridWin );
6993 PrepareDC( dc );
6994 DrawAllGridLines( dc, wxRegion() );
6995 }
6996 else // remove the grid lines
6997 {
6998 m_gridWin->Refresh();
6999 }
7000}
7001
7002void wxGrid::EnableGridLines( bool enable )
7003{
7004 if ( enable != m_gridLinesEnabled )
7005 {
7006 m_gridLinesEnabled = enable;
7007
7008 RedrawGridLines();
7009 }
7010}
7011
7012void wxGrid::DoClipGridLines(bool& var, bool clip)
7013{
7014 if ( clip != var )
7015 {
7016 var = clip;
7017
7018 if ( GridLinesEnabled() )
7019 RedrawGridLines();
7020 }
7021}
7022
7023int wxGrid::GetDefaultRowSize() const
7024{
7025 return m_defaultRowHeight;
7026}
7027
7028int wxGrid::GetRowSize( int row ) const
7029{
7030 wxCHECK_MSG( row >= 0 && row < m_numRows, 0, wxT("invalid row index") );
7031
7032 return GetRowHeight(row);
7033}
7034
7035int wxGrid::GetDefaultColSize() const
7036{
7037 return m_defaultColWidth;
7038}
7039
7040int wxGrid::GetColSize( int col ) const
7041{
7042 wxCHECK_MSG( col >= 0 && col < m_numCols, 0, wxT("invalid column index") );
7043
7044 return GetColWidth(col);
7045}
7046
7047// ============================================================================
7048// access to the grid attributes: each of them has a default value in the grid
7049// itself and may be overidden on a per-cell basis
7050// ============================================================================
7051
7052// ----------------------------------------------------------------------------
7053// setting default attributes
7054// ----------------------------------------------------------------------------
7055
7056void wxGrid::SetDefaultCellBackgroundColour( const wxColour& col )
7057{
7058 m_defaultCellAttr->SetBackgroundColour(col);
7059#ifdef __WXGTK__
7060 m_gridWin->SetBackgroundColour(col);
7061#endif
7062}
7063
7064void wxGrid::SetDefaultCellTextColour( const wxColour& col )
7065{
7066 m_defaultCellAttr->SetTextColour(col);
7067}
7068
7069void wxGrid::SetDefaultCellAlignment( int horiz, int vert )
7070{
7071 m_defaultCellAttr->SetAlignment(horiz, vert);
7072}
7073
7074void wxGrid::SetDefaultCellOverflow( bool allow )
7075{
7076 m_defaultCellAttr->SetOverflow(allow);
7077}
7078
7079void wxGrid::SetDefaultCellFont( const wxFont& font )
7080{
7081 m_defaultCellAttr->SetFont(font);
7082}
7083
7084// For editors and renderers the type registry takes precedence over the
7085// default attr, so we need to register the new editor/renderer for the string
7086// data type in order to make setting a default editor/renderer appear to
7087// work correctly.
7088
7089void wxGrid::SetDefaultRenderer(wxGridCellRenderer *renderer)
7090{
7091 RegisterDataType(wxGRID_VALUE_STRING,
7092 renderer,
7093 GetDefaultEditorForType(wxGRID_VALUE_STRING));
7094}
7095
7096void wxGrid::SetDefaultEditor(wxGridCellEditor *editor)
7097{
7098 RegisterDataType(wxGRID_VALUE_STRING,
7099 GetDefaultRendererForType(wxGRID_VALUE_STRING),
7100 editor);
7101}
7102
7103// ----------------------------------------------------------------------------
7104// access to the default attributes
7105// ----------------------------------------------------------------------------
7106
7107wxColour wxGrid::GetDefaultCellBackgroundColour() const
7108{
7109 return m_defaultCellAttr->GetBackgroundColour();
7110}
7111
7112wxColour wxGrid::GetDefaultCellTextColour() const
7113{
7114 return m_defaultCellAttr->GetTextColour();
7115}
7116
7117wxFont wxGrid::GetDefaultCellFont() const
7118{
7119 return m_defaultCellAttr->GetFont();
7120}
7121
7122void wxGrid::GetDefaultCellAlignment( int *horiz, int *vert ) const
7123{
7124 m_defaultCellAttr->GetAlignment(horiz, vert);
7125}
7126
7127bool wxGrid::GetDefaultCellOverflow() const
7128{
7129 return m_defaultCellAttr->GetOverflow();
7130}
7131
7132wxGridCellRenderer *wxGrid::GetDefaultRenderer() const
7133{
7134 return m_defaultCellAttr->GetRenderer(NULL, 0, 0);
7135}
7136
7137wxGridCellEditor *wxGrid::GetDefaultEditor() const
7138{
7139 return m_defaultCellAttr->GetEditor(NULL, 0, 0);
7140}
7141
7142// ----------------------------------------------------------------------------
7143// access to cell attributes
7144// ----------------------------------------------------------------------------
7145
7146wxColour wxGrid::GetCellBackgroundColour(int row, int col) const
7147{
7148 wxGridCellAttr *attr = GetCellAttr(row, col);
7149 wxColour colour = attr->GetBackgroundColour();
7150 attr->DecRef();
7151
7152 return colour;
7153}
7154
7155wxColour wxGrid::GetCellTextColour( int row, int col ) const
7156{
7157 wxGridCellAttr *attr = GetCellAttr(row, col);
7158 wxColour colour = attr->GetTextColour();
7159 attr->DecRef();
7160
7161 return colour;
7162}
7163
7164wxFont wxGrid::GetCellFont( int row, int col ) const
7165{
7166 wxGridCellAttr *attr = GetCellAttr(row, col);
7167 wxFont font = attr->GetFont();
7168 attr->DecRef();
7169
7170 return font;
7171}
7172
7173void wxGrid::GetCellAlignment( int row, int col, int *horiz, int *vert ) const
7174{
7175 wxGridCellAttr *attr = GetCellAttr(row, col);
7176 attr->GetAlignment(horiz, vert);
7177 attr->DecRef();
7178}
7179
7180bool wxGrid::GetCellOverflow( int row, int col ) const
7181{
7182 wxGridCellAttr *attr = GetCellAttr(row, col);
7183 bool allow = attr->GetOverflow();
7184 attr->DecRef();
7185
7186 return allow;
7187}
7188
7189wxGrid::CellSpan
7190wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols ) const
7191{
7192 wxGridCellAttr *attr = GetCellAttr(row, col);
7193 attr->GetSize( num_rows, num_cols );
7194 attr->DecRef();
7195
7196 if ( *num_rows == 1 && *num_cols == 1 )
7197 return CellSpan_None; // just a normal cell
7198
7199 if ( *num_rows < 0 || *num_cols < 0 )
7200 return CellSpan_Inside; // covered by a multi-span cell
7201
7202 // this cell spans multiple cells to its right/bottom
7203 return CellSpan_Main;
7204}
7205
7206wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col) const
7207{
7208 wxGridCellAttr* attr = GetCellAttr(row, col);
7209 wxGridCellRenderer* renderer = attr->GetRenderer(this, row, col);
7210 attr->DecRef();
7211
7212 return renderer;
7213}
7214
7215wxGridCellEditor* wxGrid::GetCellEditor(int row, int col) const
7216{
7217 wxGridCellAttr* attr = GetCellAttr(row, col);
7218 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
7219 attr->DecRef();
7220
7221 return editor;
7222}
7223
7224bool wxGrid::IsReadOnly(int row, int col) const
7225{
7226 wxGridCellAttr* attr = GetCellAttr(row, col);
7227 bool isReadOnly = attr->IsReadOnly();
7228 attr->DecRef();
7229
7230 return isReadOnly;
7231}
7232
7233// ----------------------------------------------------------------------------
7234// attribute support: cache, automatic provider creation, ...
7235// ----------------------------------------------------------------------------
7236
7237bool wxGrid::CanHaveAttributes() const
7238{
7239 if ( !m_table )
7240 {
7241 return false;
7242 }
7243
7244 return m_table->CanHaveAttributes();
7245}
7246
7247void wxGrid::ClearAttrCache()
7248{
7249 if ( m_attrCache.row != -1 )
7250 {
7251 wxGridCellAttr *oldAttr = m_attrCache.attr;
7252 m_attrCache.attr = NULL;
7253 m_attrCache.row = -1;
7254 // wxSafeDecRec(...) might cause event processing that accesses
7255 // the cached attribute, if one exists (e.g. by deleting the
7256 // editor stored within the attribute). Therefore it is important
7257 // to invalidate the cache before calling wxSafeDecRef!
7258 wxSafeDecRef(oldAttr);
7259 }
7260}
7261
7262void wxGrid::RefreshAttr(int row, int col)
7263{
7264 if ( m_attrCache.row == row && m_attrCache.col == col )
7265 ClearAttrCache();
7266}
7267
7268
7269void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const
7270{
7271 if ( attr != NULL )
7272 {
7273 wxGrid *self = (wxGrid *)this; // const_cast
7274
7275 self->ClearAttrCache();
7276 self->m_attrCache.row = row;
7277 self->m_attrCache.col = col;
7278 self->m_attrCache.attr = attr;
7279 wxSafeIncRef(attr);
7280 }
7281}
7282
7283bool wxGrid::LookupAttr(int row, int col, wxGridCellAttr **attr) const
7284{
7285 if ( row == m_attrCache.row && col == m_attrCache.col )
7286 {
7287 *attr = m_attrCache.attr;
7288 wxSafeIncRef(m_attrCache.attr);
7289
7290#ifdef DEBUG_ATTR_CACHE
7291 gs_nAttrCacheHits++;
7292#endif
7293
7294 return true;
7295 }
7296 else
7297 {
7298#ifdef DEBUG_ATTR_CACHE
7299 gs_nAttrCacheMisses++;
7300#endif
7301
7302 return false;
7303 }
7304}
7305
7306wxGridCellAttr *wxGrid::GetCellAttr(int row, int col) const
7307{
7308 wxGridCellAttr *attr = NULL;
7309 // Additional test to avoid looking at the cache e.g. for
7310 // wxNoCellCoords, as this will confuse memory management.
7311 if ( row >= 0 )
7312 {
7313 if ( !LookupAttr(row, col, &attr) )
7314 {
7315 attr = m_table ? m_table->GetAttr(row, col, wxGridCellAttr::Any)
7316 : NULL;
7317 CacheAttr(row, col, attr);
7318 }
7319 }
7320
7321 if (attr)
7322 {
7323 attr->SetDefAttr(m_defaultCellAttr);
7324 }
7325 else
7326 {
7327 attr = m_defaultCellAttr;
7328 attr->IncRef();
7329 }
7330
7331 return attr;
7332}
7333
7334wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const
7335{
7336 wxGridCellAttr *attr = NULL;
7337 bool canHave = ((wxGrid*)this)->CanHaveAttributes();
7338
7339 wxCHECK_MSG( canHave, attr, wxT("Cell attributes not allowed"));
7340 wxCHECK_MSG( m_table, attr, wxT("must have a table") );
7341
7342 attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell);
7343 if ( !attr )
7344 {
7345 attr = new wxGridCellAttr(m_defaultCellAttr);
7346
7347 // artificially inc the ref count to match DecRef() in caller
7348 attr->IncRef();
7349 m_table->SetAttr(attr, row, col);
7350 }
7351
7352 return attr;
7353}
7354
7355// ----------------------------------------------------------------------------
7356// setting column attributes (wrappers around SetColAttr)
7357// ----------------------------------------------------------------------------
7358
7359void wxGrid::SetColFormatBool(int col)
7360{
7361 SetColFormatCustom(col, wxGRID_VALUE_BOOL);
7362}
7363
7364void wxGrid::SetColFormatNumber(int col)
7365{
7366 SetColFormatCustom(col, wxGRID_VALUE_NUMBER);
7367}
7368
7369void wxGrid::SetColFormatFloat(int col, int width, int precision)
7370{
7371 wxString typeName = wxGRID_VALUE_FLOAT;
7372 if ( (width != -1) || (precision != -1) )
7373 {
7374 typeName << wxT(':') << width << wxT(',') << precision;
7375 }
7376
7377 SetColFormatCustom(col, typeName);
7378}
7379
7380void wxGrid::SetColFormatCustom(int col, const wxString& typeName)
7381{
7382 wxGridCellAttr *attr = m_table->GetAttr(-1, col, wxGridCellAttr::Col );
7383 if (!attr)
7384 attr = new wxGridCellAttr;
7385 wxGridCellRenderer *renderer = GetDefaultRendererForType(typeName);
7386 attr->SetRenderer(renderer);
7387 wxGridCellEditor *editor = GetDefaultEditorForType(typeName);
7388 attr->SetEditor(editor);
7389
7390 SetColAttr(col, attr);
7391
7392}
7393
7394// ----------------------------------------------------------------------------
7395// setting cell attributes: this is forwarded to the table
7396// ----------------------------------------------------------------------------
7397
7398void wxGrid::SetAttr(int row, int col, wxGridCellAttr *attr)
7399{
7400 if ( CanHaveAttributes() )
7401 {
7402 m_table->SetAttr(attr, row, col);
7403 ClearAttrCache();
7404 }
7405 else
7406 {
7407 wxSafeDecRef(attr);
7408 }
7409}
7410
7411void wxGrid::SetRowAttr(int row, wxGridCellAttr *attr)
7412{
7413 if ( CanHaveAttributes() )
7414 {
7415 m_table->SetRowAttr(attr, row);
7416 ClearAttrCache();
7417 }
7418 else
7419 {
7420 wxSafeDecRef(attr);
7421 }
7422}
7423
7424void wxGrid::SetColAttr(int col, wxGridCellAttr *attr)
7425{
7426 if ( CanHaveAttributes() )
7427 {
7428 m_table->SetColAttr(attr, col);
7429 ClearAttrCache();
7430 }
7431 else
7432 {
7433 wxSafeDecRef(attr);
7434 }
7435}
7436
7437void wxGrid::SetCellBackgroundColour( int row, int col, const wxColour& colour )
7438{
7439 if ( CanHaveAttributes() )
7440 {
7441 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7442 attr->SetBackgroundColour(colour);
7443 attr->DecRef();
7444 }
7445}
7446
7447void wxGrid::SetCellTextColour( int row, int col, const wxColour& colour )
7448{
7449 if ( CanHaveAttributes() )
7450 {
7451 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7452 attr->SetTextColour(colour);
7453 attr->DecRef();
7454 }
7455}
7456
7457void wxGrid::SetCellFont( int row, int col, const wxFont& font )
7458{
7459 if ( CanHaveAttributes() )
7460 {
7461 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7462 attr->SetFont(font);
7463 attr->DecRef();
7464 }
7465}
7466
7467void wxGrid::SetCellAlignment( int row, int col, int horiz, int vert )
7468{
7469 if ( CanHaveAttributes() )
7470 {
7471 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7472 attr->SetAlignment(horiz, vert);
7473 attr->DecRef();
7474 }
7475}
7476
7477void wxGrid::SetCellOverflow( int row, int col, bool allow )
7478{
7479 if ( CanHaveAttributes() )
7480 {
7481 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7482 attr->SetOverflow(allow);
7483 attr->DecRef();
7484 }
7485}
7486
7487void wxGrid::SetCellSize( int row, int col, int num_rows, int num_cols )
7488{
7489 if ( CanHaveAttributes() )
7490 {
7491 int cell_rows, cell_cols;
7492
7493 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7494 attr->GetSize(&cell_rows, &cell_cols);
7495 attr->SetSize(num_rows, num_cols);
7496 attr->DecRef();
7497
7498 // Cannot set the size of a cell to 0 or negative values
7499 // While it is perfectly legal to do that, this function cannot
7500 // handle all the possibilies, do it by hand by getting the CellAttr.
7501 // You can only set the size of a cell to 1,1 or greater with this fn
7502 wxASSERT_MSG( !((cell_rows < 1) || (cell_cols < 1)),
7503 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
7504 wxASSERT_MSG( !((num_rows < 1) || (num_cols < 1)),
7505 wxT("wxGrid::SetCellSize setting cell size to < 1"));
7506
7507 // if this was already a multicell then "turn off" the other cells first
7508 if ((cell_rows > 1) || (cell_cols > 1))
7509 {
7510 int i, j;
7511 for (j=row; j < row + cell_rows; j++)
7512 {
7513 for (i=col; i < col + cell_cols; i++)
7514 {
7515 if ((i != col) || (j != row))
7516 {
7517 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
7518 attr_stub->SetSize( 1, 1 );
7519 attr_stub->DecRef();
7520 }
7521 }
7522 }
7523 }
7524
7525 // mark the cells that will be covered by this cell to
7526 // negative or zero values to point back at this cell
7527 if (((num_rows > 1) || (num_cols > 1)) && (num_rows >= 1) && (num_cols >= 1))
7528 {
7529 int i, j;
7530 for (j=row; j < row + num_rows; j++)
7531 {
7532 for (i=col; i < col + num_cols; i++)
7533 {
7534 if ((i != col) || (j != row))
7535 {
7536 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
7537 attr_stub->SetSize( row - j, col - i );
7538 attr_stub->DecRef();
7539 }
7540 }
7541 }
7542 }
7543 }
7544}
7545
7546void wxGrid::SetCellRenderer(int row, int col, wxGridCellRenderer *renderer)
7547{
7548 if ( CanHaveAttributes() )
7549 {
7550 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7551 attr->SetRenderer(renderer);
7552 attr->DecRef();
7553 }
7554}
7555
7556void wxGrid::SetCellEditor(int row, int col, wxGridCellEditor* editor)
7557{
7558 if ( CanHaveAttributes() )
7559 {
7560 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7561 attr->SetEditor(editor);
7562 attr->DecRef();
7563 }
7564}
7565
7566void wxGrid::SetReadOnly(int row, int col, bool isReadOnly)
7567{
7568 if ( CanHaveAttributes() )
7569 {
7570 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
7571 attr->SetReadOnly(isReadOnly);
7572 attr->DecRef();
7573 }
7574}
7575
7576// ----------------------------------------------------------------------------
7577// Data type registration
7578// ----------------------------------------------------------------------------
7579
7580void wxGrid::RegisterDataType(const wxString& typeName,
7581 wxGridCellRenderer* renderer,
7582 wxGridCellEditor* editor)
7583{
7584 m_typeRegistry->RegisterDataType(typeName, renderer, editor);
7585}
7586
7587
7588wxGridCellEditor * wxGrid::GetDefaultEditorForCell(int row, int col) const
7589{
7590 wxString typeName = m_table->GetTypeName(row, col);
7591 return GetDefaultEditorForType(typeName);
7592}
7593
7594wxGridCellRenderer * wxGrid::GetDefaultRendererForCell(int row, int col) const
7595{
7596 wxString typeName = m_table->GetTypeName(row, col);
7597 return GetDefaultRendererForType(typeName);
7598}
7599
7600wxGridCellEditor * wxGrid::GetDefaultEditorForType(const wxString& typeName) const
7601{
7602 int index = m_typeRegistry->FindOrCloneDataType(typeName);
7603 if ( index == wxNOT_FOUND )
7604 {
7605 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
7606
7607 return NULL;
7608 }
7609
7610 return m_typeRegistry->GetEditor(index);
7611}
7612
7613wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) const
7614{
7615 int index = m_typeRegistry->FindOrCloneDataType(typeName);
7616 if ( index == wxNOT_FOUND )
7617 {
7618 wxFAIL_MSG(wxString::Format(wxT("Unknown data type name [%s]"), typeName.c_str()));
7619
7620 return NULL;
7621 }
7622
7623 return m_typeRegistry->GetRenderer(index);
7624}
7625
7626// ----------------------------------------------------------------------------
7627// row/col size
7628// ----------------------------------------------------------------------------
7629
7630void wxGrid::DoDisableLineResize(int line, wxGridFixedIndicesSet *& setFixed)
7631{
7632 if ( !setFixed )
7633 {
7634 setFixed = new wxGridFixedIndicesSet;
7635 }
7636
7637 setFixed->insert(line);
7638}
7639
7640bool
7641wxGrid::DoCanResizeLine(int line, const wxGridFixedIndicesSet *setFixed) const
7642{
7643 return !setFixed || !setFixed->count(line);
7644}
7645
7646void wxGrid::EnableDragRowSize( bool enable )
7647{
7648 m_canDragRowSize = enable;
7649}
7650
7651void wxGrid::EnableDragColSize( bool enable )
7652{
7653 m_canDragColSize = enable;
7654}
7655
7656void wxGrid::EnableDragGridSize( bool enable )
7657{
7658 m_canDragGridSize = enable;
7659}
7660
7661void wxGrid::EnableDragCell( bool enable )
7662{
7663 m_canDragCell = enable;
7664}
7665
7666void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows )
7667{
7668 m_defaultRowHeight = wxMax( height, m_minAcceptableRowHeight );
7669
7670 if ( resizeExistingRows )
7671 {
7672 // since we are resizing all rows to the default row size,
7673 // we can simply clear the row heights and row bottoms
7674 // arrays (which also allows us to take advantage of
7675 // some speed optimisations)
7676 m_rowHeights.Empty();
7677 m_rowBottoms.Empty();
7678 if ( !GetBatchCount() )
7679 CalcDimensions();
7680 }
7681}
7682
7683void wxGrid::SetRowSize( int row, int height )
7684{
7685 wxCHECK_RET( row >= 0 && row < m_numRows, wxT("invalid row index") );
7686
7687 // if < 0 then calculate new height from label
7688 if ( height < 0 )
7689 {
7690 long w, h;
7691 wxArrayString lines;
7692 wxClientDC dc(m_rowLabelWin);
7693 dc.SetFont(GetLabelFont());
7694 StringToLines(GetRowLabelValue( row ), lines);
7695 GetTextBoxSize( dc, lines, &w, &h );
7696 //check that it is not less than the minimal height
7697 height = wxMax(h, GetRowMinimalAcceptableHeight());
7698 }
7699
7700 // See comment in SetColSize
7701 if ( height < GetRowMinimalAcceptableHeight())
7702 return;
7703
7704 if ( m_rowHeights.IsEmpty() )
7705 {
7706 // need to really create the array
7707 InitRowHeights();
7708 }
7709
7710 int h = wxMax( 0, height );
7711 int diff = h - m_rowHeights[row];
7712
7713 m_rowHeights[row] = h;
7714 for ( int i = row; i < m_numRows; i++ )
7715 {
7716 m_rowBottoms[i] += diff;
7717 }
7718
7719 if ( !GetBatchCount() )
7720 CalcDimensions();
7721}
7722
7723void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols )
7724{
7725 // we dont allow zero default column width
7726 m_defaultColWidth = wxMax( wxMax( width, m_minAcceptableColWidth ), 1 );
7727
7728 if ( resizeExistingCols )
7729 {
7730 // since we are resizing all columns to the default column size,
7731 // we can simply clear the col widths and col rights
7732 // arrays (which also allows us to take advantage of
7733 // some speed optimisations)
7734 m_colWidths.Empty();
7735 m_colRights.Empty();
7736 if ( !GetBatchCount() )
7737 CalcDimensions();
7738 }
7739}
7740
7741void wxGrid::SetColSize( int col, int width )
7742{
7743 wxCHECK_RET( col >= 0 && col < m_numCols, wxT("invalid column index") );
7744
7745 // if < 0 then calculate new width from label
7746 if ( width < 0 )
7747 {
7748 long w, h;
7749 wxArrayString lines;
7750 wxClientDC dc(m_colWindow);
7751 dc.SetFont(GetLabelFont());
7752 StringToLines(GetColLabelValue(col), lines);
7753 if ( GetColLabelTextOrientation() == wxHORIZONTAL )
7754 GetTextBoxSize( dc, lines, &w, &h );
7755 else
7756 GetTextBoxSize( dc, lines, &h, &w );
7757 width = w + 6;
7758 //check that it is not less than the minimal width
7759 width = wxMax(width, GetColMinimalAcceptableWidth());
7760 }
7761
7762 // we intentionally don't test whether the width is less than
7763 // GetColMinimalWidth() here but we do compare it with
7764 // GetColMinimalAcceptableWidth() as otherwise things currently break (see
7765 // #651) -- and we also always allow the width of 0 as it has the special
7766 // sense of hiding the column
7767 if ( width > 0 && width < GetColMinimalAcceptableWidth() )
7768 return;
7769
7770 if ( m_colWidths.IsEmpty() )
7771 {
7772 // need to really create the array
7773 InitColWidths();
7774 }
7775
7776 const int diff = width - m_colWidths[col];
7777 m_colWidths[col] = width;
7778 if ( m_useNativeHeader )
7779 GetGridColHeader()->UpdateColumn(col);
7780 //else: will be refreshed when the header is redrawn
7781
7782 for ( int colPos = GetColPos(col); colPos < m_numCols; colPos++ )
7783 {
7784 m_colRights[GetColAt(colPos)] += diff;
7785 }
7786
7787 if ( !GetBatchCount() )
7788 {
7789 CalcDimensions();
7790 Refresh();
7791 }
7792}
7793
7794void wxGrid::SetColMinimalWidth( int col, int width )
7795{
7796 if (width > GetColMinimalAcceptableWidth())
7797 {
7798 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
7799 m_colMinWidths[key] = width;
7800 }
7801}
7802
7803void wxGrid::SetRowMinimalHeight( int row, int width )
7804{
7805 if (width > GetRowMinimalAcceptableHeight())
7806 {
7807 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
7808 m_rowMinHeights[key] = width;
7809 }
7810}
7811
7812int wxGrid::GetColMinimalWidth(int col) const
7813{
7814 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
7815 wxLongToLongHashMap::const_iterator it = m_colMinWidths.find(key);
7816
7817 return it != m_colMinWidths.end() ? (int)it->second : m_minAcceptableColWidth;
7818}
7819
7820int wxGrid::GetRowMinimalHeight(int row) const
7821{
7822 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
7823 wxLongToLongHashMap::const_iterator it = m_rowMinHeights.find(key);
7824
7825 return it != m_rowMinHeights.end() ? (int)it->second : m_minAcceptableRowHeight;
7826}
7827
7828void wxGrid::SetColMinimalAcceptableWidth( int width )
7829{
7830 // We do allow a width of 0 since this gives us
7831 // an easy way to temporarily hiding columns.
7832 if ( width >= 0 )
7833 m_minAcceptableColWidth = width;
7834}
7835
7836void wxGrid::SetRowMinimalAcceptableHeight( int height )
7837{
7838 // We do allow a height of 0 since this gives us
7839 // an easy way to temporarily hiding rows.
7840 if ( height >= 0 )
7841 m_minAcceptableRowHeight = height;
7842}
7843
7844int wxGrid::GetColMinimalAcceptableWidth() const
7845{
7846 return m_minAcceptableColWidth;
7847}
7848
7849int wxGrid::GetRowMinimalAcceptableHeight() const
7850{
7851 return m_minAcceptableRowHeight;
7852}
7853
7854// ----------------------------------------------------------------------------
7855// auto sizing
7856// ----------------------------------------------------------------------------
7857
7858void
7859wxGrid::AutoSizeColOrRow(int colOrRow, bool setAsMin, wxGridDirection direction)
7860{
7861 const bool column = direction == wxGRID_COLUMN;
7862
7863 wxClientDC dc(m_gridWin);
7864
7865 // cancel editing of cell
7866 HideCellEditControl();
7867 SaveEditControlValue();
7868
7869 // initialize both of them just to avoid compiler warnings even if only
7870 // really needs to be initialized here
7871 int row,
7872 col;
7873 if ( column )
7874 {
7875 row = -1;
7876 col = colOrRow;
7877 }
7878 else
7879 {
7880 row = colOrRow;
7881 col = -1;
7882 }
7883
7884 wxCoord extent, extentMax = 0;
7885 int max = column ? m_numRows : m_numCols;
7886 for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ )
7887 {
7888 if ( column )
7889 row = rowOrCol;
7890 else
7891 col = rowOrCol;
7892
7893 // we need to account for the cells spanning multiple columns/rows:
7894 // while they may need a lot of space, they don't need all of it in
7895 // this column/row
7896 int numRows, numCols;
7897 const CellSpan span = GetCellSize(row, col, &numRows, &numCols);
7898 if ( span == CellSpan_Inside )
7899 {
7900 // we need to get the size of the main cell, not of a cell hidden
7901 // by it
7902 row += numRows;
7903 col += numCols;
7904
7905 // get the size of the main cell too
7906 GetCellSize(row, col, &numRows, &numCols);
7907 }
7908
7909 wxGridCellAttr *attr = GetCellAttr(row, col);
7910 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
7911 if ( renderer )
7912 {
7913 wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col);
7914 extent = column ? size.x : size.y;
7915
7916 if ( span != CellSpan_None )
7917 {
7918 // we spread the size of a spanning cell over all the cells it
7919 // covers evenly -- this is probably not ideal but we can't
7920 // really do much better here
7921 //
7922 // notice that numCols and numRows are never 0 as they
7923 // correspond to the size of the main cell of the span and not
7924 // of the cell inside it
7925 extent /= column ? numCols : numRows;
7926 }
7927
7928 if ( extent > extentMax )
7929 extentMax = extent;
7930
7931 renderer->DecRef();
7932 }
7933
7934 attr->DecRef();
7935 }
7936
7937 // now also compare with the column label extent
7938 wxCoord w, h;
7939 dc.SetFont( GetLabelFont() );
7940
7941 if ( column )
7942 {
7943 dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h );
7944 if ( GetColLabelTextOrientation() == wxVERTICAL )
7945 w = h;
7946 }
7947 else
7948 dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h );
7949
7950 extent = column ? w : h;
7951 if ( extent > extentMax )
7952 extentMax = extent;
7953
7954 if ( !extentMax )
7955 {
7956 // empty column - give default extent (notice that if extentMax is less
7957 // than default extent but != 0, it's OK)
7958 extentMax = column ? m_defaultColWidth : m_defaultRowHeight;
7959 }
7960 else
7961 {
7962 if ( column )
7963 // leave some space around text
7964 extentMax += 10;
7965 else
7966 extentMax += 6;
7967 }
7968
7969 if ( column )
7970 {
7971 // Ensure automatic width is not less than minimal width. See the
7972 // comment in SetColSize() for explanation of why this isn't done
7973 // in SetColSize().
7974 if ( !setAsMin )
7975 extentMax = wxMax(extentMax, GetColMinimalWidth(col));
7976
7977 SetColSize( col, extentMax );
7978 if ( !GetBatchCount() )
7979 {
7980 if ( m_useNativeHeader )
7981 {
7982 GetGridColHeader()->UpdateColumn(col);
7983 }
7984 else
7985 {
7986 int cw, ch, dummy;
7987 m_gridWin->GetClientSize( &cw, &ch );
7988 wxRect rect ( CellToRect( 0, col ) );
7989 rect.y = 0;
7990 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
7991 rect.width = cw - rect.x;
7992 rect.height = m_colLabelHeight;
7993 GetColLabelWindow()->Refresh( true, &rect );
7994 }
7995 }
7996 }
7997 else
7998 {
7999 // Ensure automatic width is not less than minimal height. See the
8000 // comment in SetColSize() for explanation of why this isn't done
8001 // in SetRowSize().
8002 if ( !setAsMin )
8003 extentMax = wxMax(extentMax, GetRowMinimalHeight(row));
8004
8005 SetRowSize(row, extentMax);
8006 if ( !GetBatchCount() )
8007 {
8008 int cw, ch, dummy;
8009 m_gridWin->GetClientSize( &cw, &ch );
8010 wxRect rect( CellToRect( row, 0 ) );
8011 rect.x = 0;
8012 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
8013 rect.width = m_rowLabelWidth;
8014 rect.height = ch - rect.y;
8015 m_rowLabelWin->Refresh( true, &rect );
8016 }
8017 }
8018
8019 if ( setAsMin )
8020 {
8021 if ( column )
8022 SetColMinimalWidth(col, extentMax);
8023 else
8024 SetRowMinimalHeight(row, extentMax);
8025 }
8026}
8027
8028wxCoord wxGrid::CalcColOrRowLabelAreaMinSize(wxGridDirection direction)
8029{
8030 // calculate size for the rows or columns?
8031 const bool calcRows = direction == wxGRID_ROW;
8032
8033 wxClientDC dc(calcRows ? GetGridRowLabelWindow()
8034 : GetGridColLabelWindow());
8035 dc.SetFont(GetLabelFont());
8036
8037 // which dimension should we take into account for calculations?
8038 //
8039 // for columns, the text can be only horizontal so it's easy but for rows
8040 // we also have to take into account the text orientation
8041 const bool
8042 useWidth = calcRows || (GetColLabelTextOrientation() == wxVERTICAL);
8043
8044 wxArrayString lines;
8045 wxCoord extentMax = 0;
8046
8047 const int numRowsOrCols = calcRows ? m_numRows : m_numCols;
8048 for ( int rowOrCol = 0; rowOrCol < numRowsOrCols; rowOrCol++ )
8049 {
8050 lines.Clear();
8051
8052 wxString label = calcRows ? GetRowLabelValue(rowOrCol)
8053 : GetColLabelValue(rowOrCol);
8054 StringToLines(label, lines);
8055
8056 long w, h;
8057 GetTextBoxSize(dc, lines, &w, &h);
8058
8059 const wxCoord extent = useWidth ? w : h;
8060 if ( extent > extentMax )
8061 extentMax = extent;
8062 }
8063
8064 if ( !extentMax )
8065 {
8066 // empty column - give default extent (notice that if extentMax is less
8067 // than default extent but != 0, it's OK)
8068 extentMax = calcRows ? GetDefaultRowLabelSize()
8069 : GetDefaultColLabelSize();
8070 }
8071
8072 // leave some space around text (taken from AutoSizeColOrRow)
8073 if ( calcRows )
8074 extentMax += 10;
8075 else
8076 extentMax += 6;
8077
8078 return extentMax;
8079}
8080
8081int wxGrid::SetOrCalcColumnSizes(bool calcOnly, bool setAsMin)
8082{
8083 int width = m_rowLabelWidth;
8084
8085 wxGridUpdateLocker locker;
8086 if(!calcOnly)
8087 locker.Create(this);
8088
8089 for ( int col = 0; col < m_numCols; col++ )
8090 {
8091 if ( !calcOnly )
8092 AutoSizeColumn(col, setAsMin);
8093
8094 width += GetColWidth(col);
8095 }
8096
8097 return width;
8098}
8099
8100int wxGrid::SetOrCalcRowSizes(bool calcOnly, bool setAsMin)
8101{
8102 int height = m_colLabelHeight;
8103
8104 wxGridUpdateLocker locker;
8105 if(!calcOnly)
8106 locker.Create(this);
8107
8108 for ( int row = 0; row < m_numRows; row++ )
8109 {
8110 if ( !calcOnly )
8111 AutoSizeRow(row, setAsMin);
8112
8113 height += GetRowHeight(row);
8114 }
8115
8116 return height;
8117}
8118
8119void wxGrid::AutoSize()
8120{
8121 wxGridUpdateLocker locker(this);
8122
8123 wxSize size(SetOrCalcColumnSizes(false) - m_rowLabelWidth + m_extraWidth,
8124 SetOrCalcRowSizes(false) - m_colLabelHeight + m_extraHeight);
8125
8126 // we know that we're not going to have scrollbars so disable them now to
8127 // avoid trouble in SetClientSize() which can otherwise set the correct
8128 // client size but also leave space for (not needed any more) scrollbars
8129 SetScrollbars(m_xScrollPixelsPerLine, m_yScrollPixelsPerLine,
8130 0, 0, 0, 0, true);
8131
8132 SetClientSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight);
8133}
8134
8135void wxGrid::AutoSizeRowLabelSize( int row )
8136{
8137 // Hide the edit control, so it
8138 // won't interfere with drag-shrinking.
8139 if ( IsCellEditControlShown() )
8140 {
8141 HideCellEditControl();
8142 SaveEditControlValue();
8143 }
8144
8145 // autosize row height depending on label text
8146 SetRowSize(row, -1);
8147 ForceRefresh();
8148}
8149
8150void wxGrid::AutoSizeColLabelSize( int col )
8151{
8152 // Hide the edit control, so it
8153 // won't interfere with drag-shrinking.
8154 if ( IsCellEditControlShown() )
8155 {
8156 HideCellEditControl();
8157 SaveEditControlValue();
8158 }
8159
8160 // autosize column width depending on label text
8161 SetColSize(col, -1);
8162 ForceRefresh();
8163}
8164
8165wxSize wxGrid::DoGetBestSize() const
8166{
8167 wxGrid *self = (wxGrid *)this; // const_cast
8168
8169 // we do the same as in AutoSize() here with the exception that we don't
8170 // change the column/row sizes, only calculate them
8171 wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth,
8172 self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight);
8173
8174 // NOTE: This size should be cached, but first we need to add calls to
8175 // InvalidateBestSize everywhere that could change the results of this
8176 // calculation.
8177 // CacheBestSize(size);
8178
8179 return wxSize(size.x + m_rowLabelWidth, size.y + m_colLabelHeight)
8180 + GetWindowBorderSize();
8181}
8182
8183void wxGrid::Fit()
8184{
8185 AutoSize();
8186}
8187
8188wxPen& wxGrid::GetDividerPen() const
8189{
8190 return wxNullPen;
8191}
8192
8193// ----------------------------------------------------------------------------
8194// cell value accessor functions
8195// ----------------------------------------------------------------------------
8196
8197void wxGrid::SetCellValue( int row, int col, const wxString& s )
8198{
8199 if ( m_table )
8200 {
8201 m_table->SetValue( row, col, s );
8202 if ( !GetBatchCount() )
8203 {
8204 int dummy;
8205 wxRect rect( CellToRect( row, col ) );
8206 rect.x = 0;
8207 rect.width = m_gridWin->GetClientSize().GetWidth();
8208 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
8209 m_gridWin->Refresh( false, &rect );
8210 }
8211
8212 if ( m_currentCellCoords.GetRow() == row &&
8213 m_currentCellCoords.GetCol() == col &&
8214 IsCellEditControlShown())
8215 // Note: If we are using IsCellEditControlEnabled,
8216 // this interacts badly with calling SetCellValue from
8217 // an EVT_GRID_CELL_CHANGE handler.
8218 {
8219 HideCellEditControl();
8220 ShowCellEditControl(); // will reread data from table
8221 }
8222 }
8223}
8224
8225// ----------------------------------------------------------------------------
8226// block, row and column selection
8227// ----------------------------------------------------------------------------
8228
8229void wxGrid::SelectRow( int row, bool addToSelected )
8230{
8231 if ( !m_selection )
8232 return;
8233
8234 if ( !addToSelected )
8235 ClearSelection();
8236
8237 m_selection->SelectRow(row);
8238}
8239
8240void wxGrid::SelectCol( int col, bool addToSelected )
8241{
8242 if ( !m_selection )
8243 return;
8244
8245 if ( !addToSelected )
8246 ClearSelection();
8247
8248 m_selection->SelectCol(col);
8249}
8250
8251void wxGrid::SelectBlock(int topRow, int leftCol, int bottomRow, int rightCol,
8252 bool addToSelected)
8253{
8254 if ( !m_selection )
8255 return;
8256
8257 if ( !addToSelected )
8258 ClearSelection();
8259
8260 m_selection->SelectBlock(topRow, leftCol, bottomRow, rightCol);
8261}
8262
8263void wxGrid::SelectAll()
8264{
8265 if ( m_numRows > 0 && m_numCols > 0 )
8266 {
8267 if ( m_selection )
8268 m_selection->SelectBlock( 0, 0, m_numRows - 1, m_numCols - 1 );
8269 }
8270}
8271
8272// ----------------------------------------------------------------------------
8273// cell, row and col deselection
8274// ----------------------------------------------------------------------------
8275
8276void wxGrid::DeselectLine(int line, const wxGridOperations& oper)
8277{
8278 if ( !m_selection )
8279 return;
8280
8281 const wxGridSelectionModes mode = m_selection->GetSelectionMode();
8282 if ( mode == oper.GetSelectionMode() ||
8283 mode == wxGrid::wxGridSelectRowsOrColumns )
8284 {
8285 const wxGridCellCoords c(oper.MakeCoords(line, 0));
8286 if ( m_selection->IsInSelection(c) )
8287 m_selection->ToggleCellSelection(c);
8288 }
8289 else if ( mode != oper.Dual().GetSelectionMode() )
8290 {
8291 const int nOther = oper.Dual().GetNumberOfLines(this);
8292 for ( int i = 0; i < nOther; i++ )
8293 {
8294 const wxGridCellCoords c(oper.MakeCoords(line, i));
8295 if ( m_selection->IsInSelection(c) )
8296 m_selection->ToggleCellSelection(c);
8297 }
8298 }
8299 //else: can only select orthogonal lines so no lines in this direction
8300 // could have been selected anyhow
8301}
8302
8303void wxGrid::DeselectRow(int row)
8304{
8305 DeselectLine(row, wxGridRowOperations());
8306}
8307
8308void wxGrid::DeselectCol(int col)
8309{
8310 DeselectLine(col, wxGridColumnOperations());
8311}
8312
8313void wxGrid::DeselectCell( int row, int col )
8314{
8315 if ( m_selection && m_selection->IsInSelection(row, col) )
8316 m_selection->ToggleCellSelection(row, col);
8317}
8318
8319bool wxGrid::IsSelection() const
8320{
8321 return ( m_selection && (m_selection->IsSelection() ||
8322 ( m_selectedBlockTopLeft != wxGridNoCellCoords &&
8323 m_selectedBlockBottomRight != wxGridNoCellCoords) ) );
8324}
8325
8326bool wxGrid::IsInSelection( int row, int col ) const
8327{
8328 return ( m_selection && (m_selection->IsInSelection( row, col ) ||
8329 ( row >= m_selectedBlockTopLeft.GetRow() &&
8330 col >= m_selectedBlockTopLeft.GetCol() &&
8331 row <= m_selectedBlockBottomRight.GetRow() &&
8332 col <= m_selectedBlockBottomRight.GetCol() )) );
8333}
8334
8335wxGridCellCoordsArray wxGrid::GetSelectedCells() const
8336{
8337 if (!m_selection)
8338 {
8339 wxGridCellCoordsArray a;
8340 return a;
8341 }
8342
8343 return m_selection->m_cellSelection;
8344}
8345
8346wxGridCellCoordsArray wxGrid::GetSelectionBlockTopLeft() const
8347{
8348 if (!m_selection)
8349 {
8350 wxGridCellCoordsArray a;
8351 return a;
8352 }
8353
8354 return m_selection->m_blockSelectionTopLeft;
8355}
8356
8357wxGridCellCoordsArray wxGrid::GetSelectionBlockBottomRight() const
8358{
8359 if (!m_selection)
8360 {
8361 wxGridCellCoordsArray a;
8362 return a;
8363 }
8364
8365 return m_selection->m_blockSelectionBottomRight;
8366}
8367
8368wxArrayInt wxGrid::GetSelectedRows() const
8369{
8370 if (!m_selection)
8371 {
8372 wxArrayInt a;
8373 return a;
8374 }
8375
8376 return m_selection->m_rowSelection;
8377}
8378
8379wxArrayInt wxGrid::GetSelectedCols() const
8380{
8381 if (!m_selection)
8382 {
8383 wxArrayInt a;
8384 return a;
8385 }
8386
8387 return m_selection->m_colSelection;
8388}
8389
8390void wxGrid::ClearSelection()
8391{
8392 wxRect r1 = BlockToDeviceRect(m_selectedBlockTopLeft,
8393 m_selectedBlockBottomRight);
8394 wxRect r2 = BlockToDeviceRect(m_currentCellCoords,
8395 m_selectedBlockCorner);
8396
8397 m_selectedBlockTopLeft =
8398 m_selectedBlockBottomRight =
8399 m_selectedBlockCorner = wxGridNoCellCoords;
8400
8401 if ( !r1.IsEmpty() )
8402 RefreshRect(r1, false);
8403 if ( !r2.IsEmpty() )
8404 RefreshRect(r2, false);
8405
8406 if ( m_selection )
8407 m_selection->ClearSelection();
8408}
8409
8410// This function returns the rectangle that encloses the given block
8411// in device coords clipped to the client size of the grid window.
8412//
8413wxRect wxGrid::BlockToDeviceRect( const wxGridCellCoords& topLeft,
8414 const wxGridCellCoords& bottomRight ) const
8415{
8416 wxRect resultRect;
8417 wxRect tempCellRect = CellToRect(topLeft);
8418 if ( tempCellRect != wxGridNoCellRect )
8419 {
8420 resultRect = tempCellRect;
8421 }
8422 else
8423 {
8424 resultRect = wxRect(0, 0, 0, 0);
8425 }
8426
8427 tempCellRect = CellToRect(bottomRight);
8428 if ( tempCellRect != wxGridNoCellRect )
8429 {
8430 resultRect += tempCellRect;
8431 }
8432 else
8433 {
8434 // If both inputs were "wxGridNoCellRect," then there's nothing to do.
8435 return wxGridNoCellRect;
8436 }
8437
8438 // Ensure that left/right and top/bottom pairs are in order.
8439 int left = resultRect.GetLeft();
8440 int top = resultRect.GetTop();
8441 int right = resultRect.GetRight();
8442 int bottom = resultRect.GetBottom();
8443
8444 int leftCol = topLeft.GetCol();
8445 int topRow = topLeft.GetRow();
8446 int rightCol = bottomRight.GetCol();
8447 int bottomRow = bottomRight.GetRow();
8448
8449 if (left > right)
8450 {
8451 int tmp = left;
8452 left = right;
8453 right = tmp;
8454
8455 tmp = leftCol;
8456 leftCol = rightCol;
8457 rightCol = tmp;
8458 }
8459
8460 if (top > bottom)
8461 {
8462 int tmp = top;
8463 top = bottom;
8464 bottom = tmp;
8465
8466 tmp = topRow;
8467 topRow = bottomRow;
8468 bottomRow = tmp;
8469 }
8470
8471 // The following loop is ONLY necessary to detect and handle merged cells.
8472 int cw, ch;
8473 m_gridWin->GetClientSize( &cw, &ch );
8474
8475 // Get the origin coordinates: notice that they will be negative if the
8476 // grid is scrolled downwards/to the right.
8477 int gridOriginX = 0;
8478 int gridOriginY = 0;
8479 CalcScrolledPosition(gridOriginX, gridOriginY, &gridOriginX, &gridOriginY);
8480
8481 int onScreenLeftmostCol = internalXToCol(-gridOriginX);
8482 int onScreenUppermostRow = internalYToRow(-gridOriginY);
8483
8484 int onScreenRightmostCol = internalXToCol(-gridOriginX + cw);
8485 int onScreenBottommostRow = internalYToRow(-gridOriginY + ch);
8486
8487 // Bound our loop so that we only examine the portion of the selected block
8488 // that is shown on screen. Therefore, we compare the Top-Left block values
8489 // to the Top-Left screen values, and the Bottom-Right block values to the
8490 // Bottom-Right screen values, choosing appropriately.
8491 const int visibleTopRow = wxMax(topRow, onScreenUppermostRow);
8492 const int visibleBottomRow = wxMin(bottomRow, onScreenBottommostRow);
8493 const int visibleLeftCol = wxMax(leftCol, onScreenLeftmostCol);
8494 const int visibleRightCol = wxMin(rightCol, onScreenRightmostCol);
8495
8496 for ( int j = visibleTopRow; j <= visibleBottomRow; j++ )
8497 {
8498 for ( int i = visibleLeftCol; i <= visibleRightCol; i++ )
8499 {
8500 if ( (j == visibleTopRow) || (j == visibleBottomRow) ||
8501 (i == visibleLeftCol) || (i == visibleRightCol) )
8502 {
8503 tempCellRect = CellToRect( j, i );
8504
8505 if (tempCellRect.x < left)
8506 left = tempCellRect.x;
8507 if (tempCellRect.y < top)
8508 top = tempCellRect.y;
8509 if (tempCellRect.x + tempCellRect.width > right)
8510 right = tempCellRect.x + tempCellRect.width;
8511 if (tempCellRect.y + tempCellRect.height > bottom)
8512 bottom = tempCellRect.y + tempCellRect.height;
8513 }
8514 else
8515 {
8516 i = visibleRightCol; // jump over inner cells.
8517 }
8518 }
8519 }
8520
8521 // Convert to scrolled coords
8522 CalcScrolledPosition( left, top, &left, &top );
8523 CalcScrolledPosition( right, bottom, &right, &bottom );
8524
8525 if (right < 0 || bottom < 0 || left > cw || top > ch)
8526 return wxRect(0,0,0,0);
8527
8528 resultRect.SetLeft( wxMax(0, left) );
8529 resultRect.SetTop( wxMax(0, top) );
8530 resultRect.SetRight( wxMin(cw, right) );
8531 resultRect.SetBottom( wxMin(ch, bottom) );
8532
8533 return resultRect;
8534}
8535
8536void wxGrid::DoSetSizes(const wxGridSizesInfo& sizeInfo,
8537 const wxGridOperations& oper)
8538{
8539 BeginBatch();
8540 oper.SetDefaultLineSize(this, sizeInfo.m_sizeDefault, true);
8541 const int numLines = oper.GetNumberOfLines(this);
8542 for ( int i = 0; i < numLines; i++ )
8543 {
8544 int size = sizeInfo.GetSize(i);
8545 if ( size != sizeInfo.m_sizeDefault)
8546 oper.SetLineSize(this, i, size);
8547 }
8548 EndBatch();
8549}
8550
8551void wxGrid::SetColSizes(const wxGridSizesInfo& sizeInfo)
8552{
8553 DoSetSizes(sizeInfo, wxGridColumnOperations());
8554}
8555
8556void wxGrid::SetRowSizes(const wxGridSizesInfo& sizeInfo)
8557{
8558 DoSetSizes(sizeInfo, wxGridRowOperations());
8559}
8560
8561wxGridSizesInfo::wxGridSizesInfo(int defSize, const wxArrayInt& allSizes)
8562{
8563 m_sizeDefault = defSize;
8564 for ( size_t i = 0; i < allSizes.size(); i++ )
8565 {
8566 if ( allSizes[i] != defSize )
8567 m_customSizes[i] = allSizes[i];
8568 }
8569}
8570
8571int wxGridSizesInfo::GetSize(unsigned pos) const
8572{
8573 wxUnsignedToIntHashMap::const_iterator it = m_customSizes.find(pos);
8574
8575 return it == m_customSizes.end() ? m_sizeDefault : it->second;
8576}
8577
8578// ----------------------------------------------------------------------------
8579// drop target
8580// ----------------------------------------------------------------------------
8581
8582#if wxUSE_DRAG_AND_DROP
8583
8584// this allow setting drop target directly on wxGrid
8585void wxGrid::SetDropTarget(wxDropTarget *dropTarget)
8586{
8587 GetGridWindow()->SetDropTarget(dropTarget);
8588}
8589
8590#endif // wxUSE_DRAG_AND_DROP
8591
8592// ----------------------------------------------------------------------------
8593// grid event classes
8594// ----------------------------------------------------------------------------
8595
8596IMPLEMENT_DYNAMIC_CLASS( wxGridEvent, wxNotifyEvent )
8597
8598wxGridEvent::wxGridEvent( int id, wxEventType type, wxObject* obj,
8599 int row, int col, int x, int y, bool sel,
8600 bool control, bool shift, bool alt, bool meta )
8601 : wxNotifyEvent( type, id ),
8602 wxKeyboardState(control, shift, alt, meta)
8603{
8604 Init(row, col, x, y, sel);
8605
8606 SetEventObject(obj);
8607}
8608
8609IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent, wxNotifyEvent )
8610
8611wxGridSizeEvent::wxGridSizeEvent( int id, wxEventType type, wxObject* obj,
8612 int rowOrCol, int x, int y,
8613 bool control, bool shift, bool alt, bool meta )
8614 : wxNotifyEvent( type, id ),
8615 wxKeyboardState(control, shift, alt, meta)
8616{
8617 Init(rowOrCol, x, y);
8618
8619 SetEventObject(obj);
8620}
8621
8622
8623IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent, wxNotifyEvent )
8624
8625wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id, wxEventType type, wxObject* obj,
8626 const wxGridCellCoords& topLeft,
8627 const wxGridCellCoords& bottomRight,
8628 bool sel, bool control,
8629 bool shift, bool alt, bool meta )
8630 : wxNotifyEvent( type, id ),
8631 wxKeyboardState(control, shift, alt, meta)
8632{
8633 Init(topLeft, bottomRight, sel);
8634
8635 SetEventObject(obj);
8636}
8637
8638
8639IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent, wxCommandEvent)
8640
8641wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id, wxEventType type,
8642 wxObject* obj, int row,
8643 int col, wxControl* ctrl)
8644 : wxCommandEvent(type, id)
8645{
8646 SetEventObject(obj);
8647 m_row = row;
8648 m_col = col;
8649 m_ctrl = ctrl;
8650}
8651
8652
8653// ----------------------------------------------------------------------------
8654// wxGridTypeRegistry
8655// ----------------------------------------------------------------------------
8656
8657wxGridTypeRegistry::~wxGridTypeRegistry()
8658{
8659 size_t count = m_typeinfo.GetCount();
8660 for ( size_t i = 0; i < count; i++ )
8661 delete m_typeinfo[i];
8662}
8663
8664void wxGridTypeRegistry::RegisterDataType(const wxString& typeName,
8665 wxGridCellRenderer* renderer,
8666 wxGridCellEditor* editor)
8667{
8668 wxGridDataTypeInfo* info = new wxGridDataTypeInfo(typeName, renderer, editor);
8669
8670 // is it already registered?
8671 int loc = FindRegisteredDataType(typeName);
8672 if ( loc != wxNOT_FOUND )
8673 {
8674 delete m_typeinfo[loc];
8675 m_typeinfo[loc] = info;
8676 }
8677 else
8678 {
8679 m_typeinfo.Add(info);
8680 }
8681}
8682
8683int wxGridTypeRegistry::FindRegisteredDataType(const wxString& typeName)
8684{
8685 size_t count = m_typeinfo.GetCount();
8686 for ( size_t i = 0; i < count; i++ )
8687 {
8688 if ( typeName == m_typeinfo[i]->m_typeName )
8689 {
8690 return i;
8691 }
8692 }
8693
8694 return wxNOT_FOUND;
8695}
8696
8697int wxGridTypeRegistry::FindDataType(const wxString& typeName)
8698{
8699 int index = FindRegisteredDataType(typeName);
8700 if ( index == wxNOT_FOUND )
8701 {
8702 // check whether this is one of the standard ones, in which case
8703 // register it "on the fly"
8704#if wxUSE_TEXTCTRL
8705 if ( typeName == wxGRID_VALUE_STRING )
8706 {
8707 RegisterDataType(wxGRID_VALUE_STRING,
8708 new wxGridCellStringRenderer,
8709 new wxGridCellTextEditor);
8710 }
8711 else
8712#endif // wxUSE_TEXTCTRL
8713#if wxUSE_CHECKBOX
8714 if ( typeName == wxGRID_VALUE_BOOL )
8715 {
8716 RegisterDataType(wxGRID_VALUE_BOOL,
8717 new wxGridCellBoolRenderer,
8718 new wxGridCellBoolEditor);
8719 }
8720 else
8721#endif // wxUSE_CHECKBOX
8722#if wxUSE_TEXTCTRL
8723 if ( typeName == wxGRID_VALUE_NUMBER )
8724 {
8725 RegisterDataType(wxGRID_VALUE_NUMBER,
8726 new wxGridCellNumberRenderer,
8727 new wxGridCellNumberEditor);
8728 }
8729 else if ( typeName == wxGRID_VALUE_FLOAT )
8730 {
8731 RegisterDataType(wxGRID_VALUE_FLOAT,
8732 new wxGridCellFloatRenderer,
8733 new wxGridCellFloatEditor);
8734 }
8735 else
8736#endif // wxUSE_TEXTCTRL
8737#if wxUSE_COMBOBOX
8738 if ( typeName == wxGRID_VALUE_CHOICE )
8739 {
8740 RegisterDataType(wxGRID_VALUE_CHOICE,
8741 new wxGridCellStringRenderer,
8742 new wxGridCellChoiceEditor);
8743 }
8744 else
8745#endif // wxUSE_COMBOBOX
8746 {
8747 return wxNOT_FOUND;
8748 }
8749
8750 // we get here only if just added the entry for this type, so return
8751 // the last index
8752 index = m_typeinfo.GetCount() - 1;
8753 }
8754
8755 return index;
8756}
8757
8758int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName)
8759{
8760 int index = FindDataType(typeName);
8761 if ( index == wxNOT_FOUND )
8762 {
8763 // the first part of the typename is the "real" type, anything after ':'
8764 // are the parameters for the renderer
8765 index = FindDataType(typeName.BeforeFirst(wxT(':')));
8766 if ( index == wxNOT_FOUND )
8767 {
8768 return wxNOT_FOUND;
8769 }
8770
8771 wxGridCellRenderer *renderer = GetRenderer(index);
8772 wxGridCellRenderer *rendererOld = renderer;
8773 renderer = renderer->Clone();
8774 rendererOld->DecRef();
8775
8776 wxGridCellEditor *editor = GetEditor(index);
8777 wxGridCellEditor *editorOld = editor;
8778 editor = editor->Clone();
8779 editorOld->DecRef();
8780
8781 // do it even if there are no parameters to reset them to defaults
8782 wxString params = typeName.AfterFirst(wxT(':'));
8783 renderer->SetParameters(params);
8784 editor->SetParameters(params);
8785
8786 // register the new typename
8787 RegisterDataType(typeName, renderer, editor);
8788
8789 // we just registered it, it's the last one
8790 index = m_typeinfo.GetCount() - 1;
8791 }
8792
8793 return index;
8794}
8795
8796wxGridCellRenderer* wxGridTypeRegistry::GetRenderer(int index)
8797{
8798 wxGridCellRenderer* renderer = m_typeinfo[index]->m_renderer;
8799 if (renderer)
8800 renderer->IncRef();
8801
8802 return renderer;
8803}
8804
8805wxGridCellEditor* wxGridTypeRegistry::GetEditor(int index)
8806{
8807 wxGridCellEditor* editor = m_typeinfo[index]->m_editor;
8808 if (editor)
8809 editor->IncRef();
8810
8811 return editor;
8812}
8813
8814#endif // wxUSE_GRID