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