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