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