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