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