]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/generic/grid.cpp
don't wake up on Windows messages when waiting for thread termination in a console...
[wxWidgets.git] / src / generic / grid.cpp
... / ...
CommitLineData
1///////////////////////////////////////////////////////////////////////////
2// Name: src/generic/grid.cpp
3// Purpose: wxGrid and related classes
4// Author: Michael Bedward (based on code by Julian Smart, Robin Dunn)
5// Modified by: Robin Dunn, Vadim Zeitlin, Santiago Palacios
6// Created: 1/08/1999
7// RCS-ID: $Id$
8// Copyright: (c) Michael Bedward (mbedward@ozemail.com.au)
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// For compilers that support precompilation, includes "wx/wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
16 #pragma hdrstop
17#endif
18
19#if wxUSE_GRID
20
21#include "wx/grid.h"
22
23#ifndef WX_PRECOMP
24 #include "wx/utils.h"
25 #include "wx/dcclient.h"
26 #include "wx/settings.h"
27 #include "wx/log.h"
28 #include "wx/textctrl.h"
29 #include "wx/checkbox.h"
30 #include "wx/combobox.h"
31 #include "wx/valtext.h"
32 #include "wx/intl.h"
33 #include "wx/math.h"
34 #include "wx/listbox.h"
35#endif
36
37#include "wx/textfile.h"
38#include "wx/spinctrl.h"
39#include "wx/tokenzr.h"
40#include "wx/renderer.h"
41
42#include "wx/generic/gridsel.h"
43
44const wxChar wxGridNameStr[] = wxT("grid");
45
46#if defined(__WXMOTIF__)
47 #define WXUNUSED_MOTIF(identifier) WXUNUSED(identifier)
48#else
49 #define WXUNUSED_MOTIF(identifier) identifier
50#endif
51
52#if defined(__WXGTK__)
53 #define WXUNUSED_GTK(identifier) WXUNUSED(identifier)
54#else
55 #define WXUNUSED_GTK(identifier) identifier
56#endif
57
58// Required for wxIs... functions
59#include <ctype.h>
60
61// ----------------------------------------------------------------------------
62// array classes
63// ----------------------------------------------------------------------------
64
65WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridCellAttr *, wxArrayAttrs,
66 class WXDLLIMPEXP_ADV);
67
68struct wxGridCellWithAttr
69{
70 wxGridCellWithAttr(int row, int col, wxGridCellAttr *attr_)
71 : coords(row, col), attr(attr_)
72 {
73 }
74
75 ~wxGridCellWithAttr()
76 {
77 attr->DecRef();
78 }
79
80 wxGridCellCoords coords;
81 wxGridCellAttr *attr;
82
83// Cannot do this:
84// DECLARE_NO_COPY_CLASS(wxGridCellWithAttr)
85// without rewriting the macros, which require a public copy constructor.
86};
87
88WX_DECLARE_OBJARRAY_WITH_DECL(wxGridCellWithAttr, wxGridCellWithAttrArray,
89 class WXDLLIMPEXP_ADV);
90
91#include "wx/arrimpl.cpp"
92
93WX_DEFINE_OBJARRAY(wxGridCellCoordsArray)
94WX_DEFINE_OBJARRAY(wxGridCellWithAttrArray)
95
96// ----------------------------------------------------------------------------
97// events
98// ----------------------------------------------------------------------------
99
100DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_LEFT_CLICK)
101DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_RIGHT_CLICK)
102DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_LEFT_DCLICK)
103DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_RIGHT_DCLICK)
104DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_BEGIN_DRAG)
105DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_LEFT_CLICK)
106DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_RIGHT_CLICK)
107DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_LEFT_DCLICK)
108DEFINE_EVENT_TYPE(wxEVT_GRID_LABEL_RIGHT_DCLICK)
109DEFINE_EVENT_TYPE(wxEVT_GRID_ROW_SIZE)
110DEFINE_EVENT_TYPE(wxEVT_GRID_COL_SIZE)
111DEFINE_EVENT_TYPE(wxEVT_GRID_COL_MOVE)
112DEFINE_EVENT_TYPE(wxEVT_GRID_RANGE_SELECT)
113DEFINE_EVENT_TYPE(wxEVT_GRID_CELL_CHANGE)
114DEFINE_EVENT_TYPE(wxEVT_GRID_SELECT_CELL)
115DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_SHOWN)
116DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_HIDDEN)
117DEFINE_EVENT_TYPE(wxEVT_GRID_EDITOR_CREATED)
118
119// ----------------------------------------------------------------------------
120// private classes
121// ----------------------------------------------------------------------------
122
123class WXDLLIMPEXP_ADV wxGridRowLabelWindow : public wxWindow
124{
125public:
126 wxGridRowLabelWindow() { m_owner = (wxGrid *)NULL; }
127 wxGridRowLabelWindow( wxGrid *parent, wxWindowID id,
128 const wxPoint &pos, const wxSize &size );
129
130private:
131 wxGrid *m_owner;
132
133 void OnPaint( wxPaintEvent& event );
134 void OnMouseEvent( wxMouseEvent& event );
135 void OnMouseWheel( wxMouseEvent& event );
136 void OnKeyDown( wxKeyEvent& event );
137 void OnKeyUp( wxKeyEvent& );
138 void OnChar( wxKeyEvent& );
139
140 DECLARE_DYNAMIC_CLASS(wxGridRowLabelWindow)
141 DECLARE_EVENT_TABLE()
142 DECLARE_NO_COPY_CLASS(wxGridRowLabelWindow)
143};
144
145
146class WXDLLIMPEXP_ADV wxGridColLabelWindow : public wxWindow
147{
148public:
149 wxGridColLabelWindow() { m_owner = (wxGrid *)NULL; }
150 wxGridColLabelWindow( wxGrid *parent, wxWindowID id,
151 const wxPoint &pos, const wxSize &size );
152
153private:
154 wxGrid *m_owner;
155
156 void OnPaint( wxPaintEvent& event );
157 void OnMouseEvent( wxMouseEvent& event );
158 void OnMouseWheel( wxMouseEvent& event );
159 void OnKeyDown( wxKeyEvent& event );
160 void OnKeyUp( wxKeyEvent& );
161 void OnChar( wxKeyEvent& );
162
163 DECLARE_DYNAMIC_CLASS(wxGridColLabelWindow)
164 DECLARE_EVENT_TABLE()
165 DECLARE_NO_COPY_CLASS(wxGridColLabelWindow)
166};
167
168
169class WXDLLIMPEXP_ADV wxGridCornerLabelWindow : public wxWindow
170{
171public:
172 wxGridCornerLabelWindow() { m_owner = (wxGrid *)NULL; }
173 wxGridCornerLabelWindow( wxGrid *parent, wxWindowID id,
174 const wxPoint &pos, const wxSize &size );
175
176private:
177 wxGrid *m_owner;
178
179 void OnMouseEvent( wxMouseEvent& event );
180 void OnMouseWheel( wxMouseEvent& event );
181 void OnKeyDown( wxKeyEvent& event );
182 void OnKeyUp( wxKeyEvent& );
183 void OnChar( wxKeyEvent& );
184 void OnPaint( wxPaintEvent& event );
185
186 DECLARE_DYNAMIC_CLASS(wxGridCornerLabelWindow)
187 DECLARE_EVENT_TABLE()
188 DECLARE_NO_COPY_CLASS(wxGridCornerLabelWindow)
189};
190
191class WXDLLIMPEXP_ADV wxGridWindow : public wxWindow
192{
193public:
194 wxGridWindow()
195 {
196 m_owner = NULL;
197 m_rowLabelWin = NULL;
198 m_colLabelWin = NULL;
199 }
200
201 wxGridWindow( wxGrid *parent,
202 wxGridRowLabelWindow *rowLblWin,
203 wxGridColLabelWindow *colLblWin,
204 wxWindowID id, const wxPoint &pos, const wxSize &size );
205 virtual ~wxGridWindow() {}
206
207 void ScrollWindow( int dx, int dy, const wxRect *rect );
208
209 wxGrid* GetOwner() { return m_owner; }
210
211private:
212 wxGrid *m_owner;
213 wxGridRowLabelWindow *m_rowLabelWin;
214 wxGridColLabelWindow *m_colLabelWin;
215
216 void OnPaint( wxPaintEvent &event );
217 void OnMouseWheel( wxMouseEvent& event );
218 void OnMouseEvent( wxMouseEvent& event );
219 void OnKeyDown( wxKeyEvent& );
220 void OnKeyUp( wxKeyEvent& );
221 void OnChar( wxKeyEvent& );
222 void OnEraseBackground( wxEraseEvent& );
223 void OnFocus( wxFocusEvent& );
224
225 DECLARE_DYNAMIC_CLASS(wxGridWindow)
226 DECLARE_EVENT_TABLE()
227 DECLARE_NO_COPY_CLASS(wxGridWindow)
228};
229
230
231class wxGridCellEditorEvtHandler : public wxEvtHandler
232{
233public:
234 wxGridCellEditorEvtHandler(wxGrid* grid, wxGridCellEditor* editor)
235 : m_grid(grid),
236 m_editor(editor),
237 m_inSetFocus(false)
238 {
239 }
240
241 void OnKillFocus(wxFocusEvent& event);
242 void OnKeyDown(wxKeyEvent& event);
243 void OnChar(wxKeyEvent& event);
244
245 void SetInSetFocus(bool inSetFocus) { m_inSetFocus = inSetFocus; }
246
247private:
248 wxGrid *m_grid;
249 wxGridCellEditor *m_editor;
250
251 // Work around the fact that a focus kill event can be sent to
252 // a combobox within a set focus event.
253 bool m_inSetFocus;
254
255 DECLARE_EVENT_TABLE()
256 DECLARE_DYNAMIC_CLASS(wxGridCellEditorEvtHandler)
257 DECLARE_NO_COPY_CLASS(wxGridCellEditorEvtHandler)
258};
259
260
261IMPLEMENT_ABSTRACT_CLASS(wxGridCellEditorEvtHandler, wxEvtHandler)
262
263BEGIN_EVENT_TABLE( wxGridCellEditorEvtHandler, wxEvtHandler )
264 EVT_KILL_FOCUS( wxGridCellEditorEvtHandler::OnKillFocus )
265 EVT_KEY_DOWN( wxGridCellEditorEvtHandler::OnKeyDown )
266 EVT_CHAR( wxGridCellEditorEvtHandler::OnChar )
267END_EVENT_TABLE()
268
269
270// ----------------------------------------------------------------------------
271// the internal data representation used by wxGridCellAttrProvider
272// ----------------------------------------------------------------------------
273
274// this class stores attributes set for cells
275class WXDLLIMPEXP_ADV wxGridCellAttrData
276{
277public:
278 void SetAttr(wxGridCellAttr *attr, int row, int col);
279 wxGridCellAttr *GetAttr(int row, int col) const;
280 void UpdateAttrRows( size_t pos, int numRows );
281 void UpdateAttrCols( size_t pos, int numCols );
282
283private:
284 // searches for the attr for given cell, returns wxNOT_FOUND if not found
285 int FindIndex(int row, int col) const;
286
287 wxGridCellWithAttrArray m_attrs;
288};
289
290// this class stores attributes set for rows or columns
291class WXDLLIMPEXP_ADV wxGridRowOrColAttrData
292{
293public:
294 // empty ctor to suppress warnings
295 wxGridRowOrColAttrData() {}
296 ~wxGridRowOrColAttrData();
297
298 void SetAttr(wxGridCellAttr *attr, int rowOrCol);
299 wxGridCellAttr *GetAttr(int rowOrCol) const;
300 void UpdateAttrRowsOrCols( size_t pos, int numRowsOrCols );
301
302private:
303 wxArrayInt m_rowsOrCols;
304 wxArrayAttrs m_attrs;
305};
306
307// NB: this is just a wrapper around 3 objects: one which stores cell
308// attributes, and 2 others for row/col ones
309class WXDLLIMPEXP_ADV wxGridCellAttrProviderData
310{
311public:
312 wxGridCellAttrData m_cellAttrs;
313 wxGridRowOrColAttrData m_rowAttrs,
314 m_colAttrs;
315};
316
317
318// ----------------------------------------------------------------------------
319// data structures used for the data type registry
320// ----------------------------------------------------------------------------
321
322struct wxGridDataTypeInfo
323{
324 wxGridDataTypeInfo(const wxString& typeName,
325 wxGridCellRenderer* renderer,
326 wxGridCellEditor* editor)
327 : m_typeName(typeName), m_renderer(renderer), m_editor(editor)
328 {}
329
330 ~wxGridDataTypeInfo()
331 {
332 wxSafeDecRef(m_renderer);
333 wxSafeDecRef(m_editor);
334 }
335
336 wxString m_typeName;
337 wxGridCellRenderer* m_renderer;
338 wxGridCellEditor* m_editor;
339
340 DECLARE_NO_COPY_CLASS(wxGridDataTypeInfo)
341};
342
343
344WX_DEFINE_ARRAY_WITH_DECL_PTR(wxGridDataTypeInfo*, wxGridDataTypeInfoArray,
345 class WXDLLIMPEXP_ADV);
346
347
348class WXDLLIMPEXP_ADV wxGridTypeRegistry
349{
350public:
351 wxGridTypeRegistry() {}
352 ~wxGridTypeRegistry();
353
354 void RegisterDataType(const wxString& typeName,
355 wxGridCellRenderer* renderer,
356 wxGridCellEditor* editor);
357
358 // find one of already registered data types
359 int FindRegisteredDataType(const wxString& typeName);
360
361 // try to FindRegisteredDataType(), if this fails and typeName is one of
362 // standard typenames, register it and return its index
363 int FindDataType(const wxString& typeName);
364
365 // try to FindDataType(), if it fails see if it is not one of already
366 // registered data types with some params in which case clone the
367 // registered data type and set params for it
368 int FindOrCloneDataType(const wxString& typeName);
369
370 wxGridCellRenderer* GetRenderer(int index);
371 wxGridCellEditor* GetEditor(int index);
372
373private:
374 wxGridDataTypeInfoArray m_typeinfo;
375};
376
377
378// ----------------------------------------------------------------------------
379// conditional compilation
380// ----------------------------------------------------------------------------
381
382#ifndef WXGRID_DRAW_LINES
383#define WXGRID_DRAW_LINES 1
384#endif
385
386// ----------------------------------------------------------------------------
387// globals
388// ----------------------------------------------------------------------------
389
390//#define DEBUG_ATTR_CACHE
391#ifdef DEBUG_ATTR_CACHE
392 static size_t gs_nAttrCacheHits = 0;
393 static size_t gs_nAttrCacheMisses = 0;
394#endif
395
396// ----------------------------------------------------------------------------
397// constants
398// ----------------------------------------------------------------------------
399
400wxGridCellCoords wxGridNoCellCoords( -1, -1 );
401wxRect wxGridNoCellRect( -1, -1, -1, -1 );
402
403// scroll line size
404// TODO: this doesn't work at all, grid cells have different sizes and approx
405// calculations don't work as because of the size mismatch scrollbars
406// sometimes fail to be shown when they should be or vice versa
407//
408// The scroll bars may be a little flakey once in a while, but that is
409// surely much less horrible than having scroll lines of only 1!!!
410// -- Robin
411//
412// Well, it's still seriously broken so it might be better but needs
413// fixing anyhow
414// -- Vadim
415static const size_t GRID_SCROLL_LINE_X = 15; // 1;
416static const size_t GRID_SCROLL_LINE_Y = GRID_SCROLL_LINE_X;
417
418// the size of hash tables used a bit everywhere (the max number of elements
419// in these hash tables is the number of rows/columns)
420static const int GRID_HASH_SIZE = 100;
421
422#if 0
423// ----------------------------------------------------------------------------
424// private functions
425// ----------------------------------------------------------------------------
426
427static inline int GetScrollX(int x)
428{
429 return (x + GRID_SCROLL_LINE_X - 1) / GRID_SCROLL_LINE_X;
430}
431
432static inline int GetScrollY(int y)
433{
434 return (y + GRID_SCROLL_LINE_Y - 1) / GRID_SCROLL_LINE_Y;
435}
436#endif
437
438// ============================================================================
439// implementation
440// ============================================================================
441
442// ----------------------------------------------------------------------------
443// wxGridCellEditor
444// ----------------------------------------------------------------------------
445
446wxGridCellEditor::wxGridCellEditor()
447{
448 m_control = NULL;
449 m_attr = NULL;
450}
451
452wxGridCellEditor::~wxGridCellEditor()
453{
454 Destroy();
455}
456
457void wxGridCellEditor::Create(wxWindow* WXUNUSED(parent),
458 wxWindowID WXUNUSED(id),
459 wxEvtHandler* evtHandler)
460{
461 if ( evtHandler )
462 m_control->PushEventHandler(evtHandler);
463}
464
465void wxGridCellEditor::PaintBackground(const wxRect& rectCell,
466 wxGridCellAttr *attr)
467{
468 // erase the background because we might not fill the cell
469 wxClientDC dc(m_control->GetParent());
470 wxGridWindow* gridWindow = wxDynamicCast(m_control->GetParent(), wxGridWindow);
471 if (gridWindow)
472 gridWindow->GetOwner()->PrepareDC(dc);
473
474 dc.SetPen(*wxTRANSPARENT_PEN);
475 dc.SetBrush(wxBrush(attr->GetBackgroundColour(), wxSOLID));
476 dc.DrawRectangle(rectCell);
477
478 // redraw the control we just painted over
479 m_control->Refresh();
480}
481
482void wxGridCellEditor::Destroy()
483{
484 if (m_control)
485 {
486 m_control->PopEventHandler( true /* delete it*/ );
487
488 m_control->Destroy();
489 m_control = NULL;
490 }
491}
492
493void wxGridCellEditor::Show(bool show, wxGridCellAttr *attr)
494{
495 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
496
497 m_control->Show(show);
498
499 if ( show )
500 {
501 // set the colours/fonts if we have any
502 if ( attr )
503 {
504 m_colFgOld = m_control->GetForegroundColour();
505 m_control->SetForegroundColour(attr->GetTextColour());
506
507 m_colBgOld = m_control->GetBackgroundColour();
508 m_control->SetBackgroundColour(attr->GetBackgroundColour());
509
510// Workaround for GTK+1 font setting problem on some platforms
511#if !defined(__WXGTK__) || defined(__WXGTK20__)
512 m_fontOld = m_control->GetFont();
513 m_control->SetFont(attr->GetFont());
514#endif
515
516 // can't do anything more in the base class version, the other
517 // attributes may only be used by the derived classes
518 }
519 }
520 else
521 {
522 // restore the standard colours fonts
523 if ( m_colFgOld.Ok() )
524 {
525 m_control->SetForegroundColour(m_colFgOld);
526 m_colFgOld = wxNullColour;
527 }
528
529 if ( m_colBgOld.Ok() )
530 {
531 m_control->SetBackgroundColour(m_colBgOld);
532 m_colBgOld = wxNullColour;
533 }
534
535// Workaround for GTK+1 font setting problem on some platforms
536#if !defined(__WXGTK__) || defined(__WXGTK20__)
537 if ( m_fontOld.Ok() )
538 {
539 m_control->SetFont(m_fontOld);
540 m_fontOld = wxNullFont;
541 }
542#endif
543 }
544}
545
546void wxGridCellEditor::SetSize(const wxRect& rect)
547{
548 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
549
550 m_control->SetSize(rect, wxSIZE_ALLOW_MINUS_ONE);
551}
552
553void wxGridCellEditor::HandleReturn(wxKeyEvent& event)
554{
555 event.Skip();
556}
557
558bool wxGridCellEditor::IsAcceptedKey(wxKeyEvent& event)
559{
560 bool ctrl = event.ControlDown();
561 bool alt = event.AltDown();
562
563#ifdef __WXMAC__
564 // On the Mac the Alt key is more like shift and is used for entry of
565 // valid characters, so check for Ctrl and Meta instead.
566 alt = event.MetaDown();
567#endif
568
569 // Assume it's not a valid char if ctrl or alt is down, but if both are
570 // down then it may be because of an AltGr key combination, so let them
571 // through in that case.
572 if ((ctrl || alt) && !(ctrl && alt))
573 return false;
574
575 int key = 0;
576 bool keyOk = true;
577
578#ifdef __WXGTK20__
579 // If it's a F-Key or other special key then it shouldn't start the
580 // editor.
581 if (event.GetKeyCode() >= WXK_START)
582 return false;
583#endif
584#if wxUSE_UNICODE
585 // if the unicode key code is not really a unicode character (it may
586 // be a function key or etc., the platforms appear to always give us a
587 // small value in this case) then fallback to the ASCII key code but
588 // don't do anything for function keys or etc.
589 key = event.GetUnicodeKey();
590 if (key <= 127)
591 {
592 key = event.GetKeyCode();
593 keyOk = (key <= 127);
594 }
595#else
596 key = event.GetKeyCode();
597 keyOk = (key <= 255);
598#endif
599
600 return keyOk;
601}
602
603void wxGridCellEditor::StartingKey(wxKeyEvent& event)
604{
605 event.Skip();
606}
607
608void wxGridCellEditor::StartingClick()
609{
610}
611
612#if wxUSE_TEXTCTRL
613
614// ----------------------------------------------------------------------------
615// wxGridCellTextEditor
616// ----------------------------------------------------------------------------
617
618wxGridCellTextEditor::wxGridCellTextEditor()
619{
620 m_maxChars = 0;
621}
622
623void wxGridCellTextEditor::Create(wxWindow* parent,
624 wxWindowID id,
625 wxEvtHandler* evtHandler)
626{
627 m_control = new wxTextCtrl(parent, id, wxEmptyString,
628 wxDefaultPosition, wxDefaultSize
629#if defined(__WXMSW__)
630 ,
631 wxTE_PROCESS_ENTER |
632 wxTE_PROCESS_TAB |
633 wxTE_AUTO_SCROLL |
634 wxNO_BORDER
635#endif
636 );
637
638 // set max length allowed in the textctrl, if the parameter was set
639 if (m_maxChars != 0)
640 {
641 ((wxTextCtrl*)m_control)->SetMaxLength(m_maxChars);
642 }
643
644 wxGridCellEditor::Create(parent, id, evtHandler);
645}
646
647void wxGridCellTextEditor::PaintBackground(const wxRect& WXUNUSED(rectCell),
648 wxGridCellAttr * WXUNUSED(attr))
649{
650 // as we fill the entire client area,
651 // don't do anything here to minimize flicker
652}
653
654void wxGridCellTextEditor::SetSize(const wxRect& rectOrig)
655{
656 wxRect rect(rectOrig);
657
658 // Make the edit control large enough to allow for internal margins
659 //
660 // TODO: remove this if the text ctrl sizing is improved esp. for unix
661 //
662#if defined(__WXGTK__)
663 if (rect.x != 0)
664 {
665 rect.x += 1;
666 rect.y += 1;
667 rect.width -= 1;
668 rect.height -= 1;
669 }
670#elif defined(__WXMSW__)
671 if ( rect.x == 0 )
672 rect.x += 2;
673 else
674 rect.x += 3;
675
676 if ( rect.y == 0 )
677 rect.y += 2;
678 else
679 rect.y += 3;
680
681 rect.width -= 2;
682 rect.height -= 2;
683#else
684 int extra_x = ( rect.x > 2 ) ? 2 : 1;
685 int extra_y = ( rect.y > 2 ) ? 2 : 1;
686
687 #if defined(__WXMOTIF__)
688 extra_x *= 2;
689 extra_y *= 2;
690 #endif
691
692 rect.SetLeft( wxMax(0, rect.x - extra_x) );
693 rect.SetTop( wxMax(0, rect.y - extra_y) );
694 rect.SetRight( rect.GetRight() + 2 * extra_x );
695 rect.SetBottom( rect.GetBottom() + 2 * extra_y );
696#endif
697
698 wxGridCellEditor::SetSize(rect);
699}
700
701void wxGridCellTextEditor::BeginEdit(int row, int col, wxGrid* grid)
702{
703 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
704
705 m_startValue = grid->GetTable()->GetValue(row, col);
706
707 DoBeginEdit(m_startValue);
708}
709
710void wxGridCellTextEditor::DoBeginEdit(const wxString& startValue)
711{
712 Text()->SetValue(startValue);
713 Text()->SetInsertionPointEnd();
714 Text()->SetSelection(-1, -1);
715 Text()->SetFocus();
716}
717
718bool wxGridCellTextEditor::EndEdit(int row, int col, wxGrid* grid)
719{
720 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
721
722 bool changed = false;
723 wxString value = Text()->GetValue();
724 if (value != m_startValue)
725 changed = true;
726
727 if (changed)
728 grid->GetTable()->SetValue(row, col, value);
729
730 m_startValue = wxEmptyString;
731
732 // No point in setting the text of the hidden control
733 //Text()->SetValue(m_startValue);
734
735 return changed;
736}
737
738void wxGridCellTextEditor::Reset()
739{
740 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
741
742 DoReset(m_startValue);
743}
744
745void wxGridCellTextEditor::DoReset(const wxString& startValue)
746{
747 Text()->SetValue(startValue);
748 Text()->SetInsertionPointEnd();
749}
750
751bool wxGridCellTextEditor::IsAcceptedKey(wxKeyEvent& event)
752{
753 return wxGridCellEditor::IsAcceptedKey(event);
754}
755
756void wxGridCellTextEditor::StartingKey(wxKeyEvent& event)
757{
758 // Since this is now happening in the EVT_CHAR event EmulateKeyPress is no
759 // longer an appropriate way to get the character into the text control.
760 // Do it ourselves instead. We know that if we get this far that we have
761 // a valid character, so not a whole lot of testing needs to be done.
762
763 wxTextCtrl* tc = Text();
764 wxChar ch;
765 long pos;
766
767#if wxUSE_UNICODE
768 ch = event.GetUnicodeKey();
769 if (ch <= 127)
770 ch = (wxChar)event.GetKeyCode();
771#else
772 ch = (wxChar)event.GetKeyCode();
773#endif
774
775 switch (ch)
776 {
777 case WXK_DELETE:
778 // delete the character at the cursor
779 pos = tc->GetInsertionPoint();
780 if (pos < tc->GetLastPosition())
781 tc->Remove(pos, pos + 1);
782 break;
783
784 case WXK_BACK:
785 // delete the character before the cursor
786 pos = tc->GetInsertionPoint();
787 if (pos > 0)
788 tc->Remove(pos - 1, pos);
789 break;
790
791 default:
792 tc->WriteText(ch);
793 break;
794 }
795}
796
797void wxGridCellTextEditor::HandleReturn( wxKeyEvent&
798 WXUNUSED_GTK(WXUNUSED_MOTIF(event)) )
799{
800#if defined(__WXMOTIF__) || defined(__WXGTK__)
801 // wxMotif needs a little extra help...
802 size_t pos = (size_t)( Text()->GetInsertionPoint() );
803 wxString s( Text()->GetValue() );
804 s = s.Left(pos) + wxT("\n") + s.Mid(pos);
805 Text()->SetValue(s);
806 Text()->SetInsertionPoint( pos );
807#else
808 // the other ports can handle a Return key press
809 //
810 event.Skip();
811#endif
812}
813
814void wxGridCellTextEditor::SetParameters(const wxString& params)
815{
816 if ( !params )
817 {
818 // reset to default
819 m_maxChars = 0;
820 }
821 else
822 {
823 long tmp;
824 if ( params.ToLong(&tmp) )
825 {
826 m_maxChars = (size_t)tmp;
827 }
828 else
829 {
830 wxLogDebug( _T("Invalid wxGridCellTextEditor parameter string '%s' ignored"), params.c_str() );
831 }
832 }
833}
834
835// return the value in the text control
836wxString wxGridCellTextEditor::GetValue() const
837{
838 return Text()->GetValue();
839}
840
841// ----------------------------------------------------------------------------
842// wxGridCellNumberEditor
843// ----------------------------------------------------------------------------
844
845wxGridCellNumberEditor::wxGridCellNumberEditor(int min, int max)
846{
847 m_min = min;
848 m_max = max;
849}
850
851void wxGridCellNumberEditor::Create(wxWindow* parent,
852 wxWindowID id,
853 wxEvtHandler* evtHandler)
854{
855#if wxUSE_SPINCTRL
856 if ( HasRange() )
857 {
858 // create a spin ctrl
859 m_control = new wxSpinCtrl(parent, wxID_ANY, wxEmptyString,
860 wxDefaultPosition, wxDefaultSize,
861 wxSP_ARROW_KEYS,
862 m_min, m_max);
863
864 wxGridCellEditor::Create(parent, id, evtHandler);
865 }
866 else
867#endif
868 {
869 // just a text control
870 wxGridCellTextEditor::Create(parent, id, evtHandler);
871
872#if wxUSE_VALIDATORS
873 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
874#endif
875 }
876}
877
878void wxGridCellNumberEditor::BeginEdit(int row, int col, wxGrid* grid)
879{
880 // first get the value
881 wxGridTableBase *table = grid->GetTable();
882 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
883 {
884 m_valueOld = table->GetValueAsLong(row, col);
885 }
886 else
887 {
888 m_valueOld = 0;
889 wxString sValue = table->GetValue(row, col);
890 if (! sValue.ToLong(&m_valueOld) && ! sValue.empty())
891 {
892 wxFAIL_MSG( _T("this cell doesn't have numeric value") );
893 return;
894 }
895 }
896
897#if wxUSE_SPINCTRL
898 if ( HasRange() )
899 {
900 Spin()->SetValue((int)m_valueOld);
901 Spin()->SetFocus();
902 }
903 else
904#endif
905 {
906 DoBeginEdit(GetString());
907 }
908}
909
910bool wxGridCellNumberEditor::EndEdit(int row, int col,
911 wxGrid* grid)
912{
913 bool changed;
914 long value = 0;
915 wxString text;
916
917#if wxUSE_SPINCTRL
918 if ( HasRange() )
919 {
920 value = Spin()->GetValue();
921 changed = value != m_valueOld;
922 if (changed)
923 text = wxString::Format(wxT("%ld"), value);
924 }
925 else
926#endif
927 {
928 text = Text()->GetValue();
929 changed = (text.empty() || text.ToLong(&value)) && (value != m_valueOld);
930 }
931
932 if ( changed )
933 {
934 if (grid->GetTable()->CanSetValueAs(row, col, wxGRID_VALUE_NUMBER))
935 grid->GetTable()->SetValueAsLong(row, col, value);
936 else
937 grid->GetTable()->SetValue(row, col, text);
938 }
939
940 return changed;
941}
942
943void wxGridCellNumberEditor::Reset()
944{
945#if wxUSE_SPINCTRL
946 if ( HasRange() )
947 {
948 Spin()->SetValue((int)m_valueOld);
949 }
950 else
951#endif
952 {
953 DoReset(GetString());
954 }
955}
956
957bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent& event)
958{
959 if ( wxGridCellEditor::IsAcceptedKey(event) )
960 {
961 int keycode = event.GetKeyCode();
962 if ( (keycode < 128) &&
963 (wxIsdigit(keycode) || keycode == '+' || keycode == '-'))
964 {
965 return true;
966 }
967 }
968
969 return false;
970}
971
972void wxGridCellNumberEditor::StartingKey(wxKeyEvent& event)
973{
974 int keycode = event.GetKeyCode();
975 if ( !HasRange() )
976 {
977 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-')
978 {
979 wxGridCellTextEditor::StartingKey(event);
980
981 // skip Skip() below
982 return;
983 }
984 }
985#if wxUSE_SPINCTRL
986 else
987 {
988 if ( wxIsdigit(keycode) )
989 {
990 wxSpinCtrl* spin = (wxSpinCtrl*)m_control;
991 spin->SetValue(keycode - '0');
992 spin->SetSelection(1,1);
993 return;
994 }
995 }
996#endif
997
998 event.Skip();
999}
1000
1001void wxGridCellNumberEditor::SetParameters(const wxString& params)
1002{
1003 if ( !params )
1004 {
1005 // reset to default
1006 m_min =
1007 m_max = -1;
1008 }
1009 else
1010 {
1011 long tmp;
1012 if ( params.BeforeFirst(_T(',')).ToLong(&tmp) )
1013 {
1014 m_min = (int)tmp;
1015
1016 if ( params.AfterFirst(_T(',')).ToLong(&tmp) )
1017 {
1018 m_max = (int)tmp;
1019
1020 // skip the error message below
1021 return;
1022 }
1023 }
1024
1025 wxLogDebug(_T("Invalid wxGridCellNumberEditor parameter string '%s' ignored"), params.c_str());
1026 }
1027}
1028
1029// return the value in the spin control if it is there (the text control otherwise)
1030wxString wxGridCellNumberEditor::GetValue() const
1031{
1032 wxString s;
1033
1034#if wxUSE_SPINCTRL
1035 if ( HasRange() )
1036 {
1037 long value = Spin()->GetValue();
1038 s.Printf(wxT("%ld"), value);
1039 }
1040 else
1041#endif
1042 {
1043 s = Text()->GetValue();
1044 }
1045
1046 return s;
1047}
1048
1049// ----------------------------------------------------------------------------
1050// wxGridCellFloatEditor
1051// ----------------------------------------------------------------------------
1052
1053wxGridCellFloatEditor::wxGridCellFloatEditor(int width, int precision)
1054{
1055 m_width = width;
1056 m_precision = precision;
1057}
1058
1059void wxGridCellFloatEditor::Create(wxWindow* parent,
1060 wxWindowID id,
1061 wxEvtHandler* evtHandler)
1062{
1063 wxGridCellTextEditor::Create(parent, id, evtHandler);
1064
1065#if wxUSE_VALIDATORS
1066 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
1067#endif
1068}
1069
1070void wxGridCellFloatEditor::BeginEdit(int row, int col, wxGrid* grid)
1071{
1072 // first get the value
1073 wxGridTableBase *table = grid->GetTable();
1074 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_FLOAT) )
1075 {
1076 m_valueOld = table->GetValueAsDouble(row, col);
1077 }
1078 else
1079 {
1080 m_valueOld = 0.0;
1081 wxString sValue = table->GetValue(row, col);
1082 if (! sValue.ToDouble(&m_valueOld) && ! sValue.empty())
1083 {
1084 wxFAIL_MSG( _T("this cell doesn't have float value") );
1085 return;
1086 }
1087 }
1088
1089 DoBeginEdit(GetString());
1090}
1091
1092bool wxGridCellFloatEditor::EndEdit(int row, int col,
1093 wxGrid* grid)
1094{
1095 double value = 0.0;
1096 wxString text(Text()->GetValue());
1097
1098 if ( (text.empty() || text.ToDouble(&value)) &&
1099 !wxIsSameDouble(value, m_valueOld) )
1100 {
1101 if (grid->GetTable()->CanSetValueAs(row, col, wxGRID_VALUE_FLOAT))
1102 grid->GetTable()->SetValueAsDouble(row, col, value);
1103 else
1104 grid->GetTable()->SetValue(row, col, text);
1105
1106 return true;
1107 }
1108
1109 return false;
1110}
1111
1112void wxGridCellFloatEditor::Reset()
1113{
1114 DoReset(GetString());
1115}
1116
1117void wxGridCellFloatEditor::StartingKey(wxKeyEvent& event)
1118{
1119 int keycode = event.GetKeyCode();
1120 char tmpbuf[2];
1121 tmpbuf[0] = (char) keycode;
1122 tmpbuf[1] = '\0';
1123 wxString strbuf(tmpbuf, *wxConvCurrent);
1124
1125#if wxUSE_INTL
1126 bool is_decimal_point = ( strbuf ==
1127 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER) );
1128#else
1129 bool is_decimal_point = ( strbuf == _T(".") );
1130#endif
1131
1132 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-'
1133 || is_decimal_point )
1134 {
1135 wxGridCellTextEditor::StartingKey(event);
1136
1137 // skip Skip() below
1138 return;
1139 }
1140
1141 event.Skip();
1142}
1143
1144void wxGridCellFloatEditor::SetParameters(const wxString& params)
1145{
1146 if ( !params )
1147 {
1148 // reset to default
1149 m_width =
1150 m_precision = -1;
1151 }
1152 else
1153 {
1154 long tmp;
1155 if ( params.BeforeFirst(_T(',')).ToLong(&tmp) )
1156 {
1157 m_width = (int)tmp;
1158
1159 if ( params.AfterFirst(_T(',')).ToLong(&tmp) )
1160 {
1161 m_precision = (int)tmp;
1162
1163 // skip the error message below
1164 return;
1165 }
1166 }
1167
1168 wxLogDebug(_T("Invalid wxGridCellFloatEditor parameter string '%s' ignored"), params.c_str());
1169 }
1170}
1171
1172wxString wxGridCellFloatEditor::GetString() const
1173{
1174 wxString fmt;
1175 if ( m_precision == -1 && m_width != -1)
1176 {
1177 // default precision
1178 fmt.Printf(_T("%%%d.f"), m_width);
1179 }
1180 else if ( m_precision != -1 && m_width == -1)
1181 {
1182 // default width
1183 fmt.Printf(_T("%%.%df"), m_precision);
1184 }
1185 else if ( m_precision != -1 && m_width != -1 )
1186 {
1187 fmt.Printf(_T("%%%d.%df"), m_width, m_precision);
1188 }
1189 else
1190 {
1191 // default width/precision
1192 fmt = _T("%f");
1193 }
1194
1195 return wxString::Format(fmt, m_valueOld);
1196}
1197
1198bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent& event)
1199{
1200 if ( wxGridCellEditor::IsAcceptedKey(event) )
1201 {
1202 const int keycode = event.GetKeyCode();
1203 if ( isascii(keycode) )
1204 {
1205 char tmpbuf[2];
1206 tmpbuf[0] = (char) keycode;
1207 tmpbuf[1] = '\0';
1208 wxString strbuf(tmpbuf, *wxConvCurrent);
1209
1210#if wxUSE_INTL
1211 const wxString decimalPoint =
1212 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER);
1213#else
1214 const wxString decimalPoint(_T('.'));
1215#endif
1216
1217 // accept digits, 'e' as in '1e+6', also '-', '+', and '.'
1218 if ( wxIsdigit(keycode) ||
1219 tolower(keycode) == 'e' ||
1220 keycode == decimalPoint ||
1221 keycode == '+' ||
1222 keycode == '-' )
1223 {
1224 return true;
1225 }
1226 }
1227 }
1228
1229 return false;
1230}
1231
1232#endif // wxUSE_TEXTCTRL
1233
1234#if wxUSE_CHECKBOX
1235
1236// ----------------------------------------------------------------------------
1237// wxGridCellBoolEditor
1238// ----------------------------------------------------------------------------
1239
1240// the default values for GetValue()
1241wxString wxGridCellBoolEditor::ms_stringValues[2] = { _T(""), _T("1") };
1242
1243void wxGridCellBoolEditor::Create(wxWindow* parent,
1244 wxWindowID id,
1245 wxEvtHandler* evtHandler)
1246{
1247 m_control = new wxCheckBox(parent, id, wxEmptyString,
1248 wxDefaultPosition, wxDefaultSize,
1249 wxNO_BORDER);
1250
1251 wxGridCellEditor::Create(parent, id, evtHandler);
1252}
1253
1254void wxGridCellBoolEditor::SetSize(const wxRect& r)
1255{
1256 bool resize = false;
1257 wxSize size = m_control->GetSize();
1258 wxCoord minSize = wxMin(r.width, r.height);
1259
1260 // check if the checkbox is not too big/small for this cell
1261 wxSize sizeBest = m_control->GetBestSize();
1262 if ( !(size == sizeBest) )
1263 {
1264 // reset to default size if it had been made smaller
1265 size = sizeBest;
1266
1267 resize = true;
1268 }
1269
1270 if ( size.x >= minSize || size.y >= minSize )
1271 {
1272 // leave 1 pixel margin
1273 size.x = size.y = minSize - 2;
1274
1275 resize = true;
1276 }
1277
1278 if ( resize )
1279 {
1280 m_control->SetSize(size);
1281 }
1282
1283 // position it in the centre of the rectangle (TODO: support alignment?)
1284
1285#if defined(__WXGTK__) || defined (__WXMOTIF__)
1286 // the checkbox without label still has some space to the right in wxGTK,
1287 // so shift it to the right
1288 size.x -= 8;
1289#elif defined(__WXMSW__)
1290 // here too, but in other way
1291 size.x += 1;
1292 size.y -= 2;
1293#endif
1294
1295 int hAlign = wxALIGN_CENTRE;
1296 int vAlign = wxALIGN_CENTRE;
1297 if (GetCellAttr())
1298 GetCellAttr()->GetAlignment(& hAlign, & vAlign);
1299
1300 int x = 0, y = 0;
1301 if (hAlign == wxALIGN_LEFT)
1302 {
1303 x = r.x + 2;
1304
1305#ifdef __WXMSW__
1306 x += 2;
1307#endif
1308
1309 y = r.y + r.height / 2 - size.y / 2;
1310 }
1311 else if (hAlign == wxALIGN_RIGHT)
1312 {
1313 x = r.x + r.width - size.x - 2;
1314 y = r.y + r.height / 2 - size.y / 2;
1315 }
1316 else if (hAlign == wxALIGN_CENTRE)
1317 {
1318 x = r.x + r.width / 2 - size.x / 2;
1319 y = r.y + r.height / 2 - size.y / 2;
1320 }
1321
1322 m_control->Move(x, y);
1323}
1324
1325void wxGridCellBoolEditor::Show(bool show, wxGridCellAttr *attr)
1326{
1327 m_control->Show(show);
1328
1329 if ( show )
1330 {
1331 wxColour colBg = attr ? attr->GetBackgroundColour() : *wxLIGHT_GREY;
1332 CBox()->SetBackgroundColour(colBg);
1333 }
1334}
1335
1336void wxGridCellBoolEditor::BeginEdit(int row, int col, wxGrid* grid)
1337{
1338 wxASSERT_MSG(m_control,
1339 wxT("The wxGridCellEditor must be created first!"));
1340
1341 if (grid->GetTable()->CanGetValueAs(row, col, wxGRID_VALUE_BOOL))
1342 {
1343 m_startValue = grid->GetTable()->GetValueAsBool(row, col);
1344 }
1345 else
1346 {
1347 wxString cellval( grid->GetTable()->GetValue(row, col) );
1348
1349 if ( cellval == ms_stringValues[false] )
1350 m_startValue = false;
1351 else if ( cellval == ms_stringValues[true] )
1352 m_startValue = true;
1353 else
1354 {
1355 // do not try to be smart here and convert it to true or false
1356 // because we'll still overwrite it with something different and
1357 // this risks to be very surprising for the user code, let them
1358 // know about it
1359 wxFAIL_MSG( _T("invalid value for a cell with bool editor!") );
1360 }
1361 }
1362
1363 CBox()->SetValue(m_startValue);
1364 CBox()->SetFocus();
1365}
1366
1367bool wxGridCellBoolEditor::EndEdit(int row, int col,
1368 wxGrid* grid)
1369{
1370 wxASSERT_MSG(m_control,
1371 wxT("The wxGridCellEditor must be created first!"));
1372
1373 bool changed = false;
1374 bool value = CBox()->GetValue();
1375 if ( value != m_startValue )
1376 changed = true;
1377
1378 if ( changed )
1379 {
1380 wxGridTableBase * const table = grid->GetTable();
1381 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_BOOL) )
1382 table->SetValueAsBool(row, col, value);
1383 else
1384 table->SetValue(row, col, GetValue());
1385 }
1386
1387 return changed;
1388}
1389
1390void wxGridCellBoolEditor::Reset()
1391{
1392 wxASSERT_MSG(m_control,
1393 wxT("The wxGridCellEditor must be created first!"));
1394
1395 CBox()->SetValue(m_startValue);
1396}
1397
1398void wxGridCellBoolEditor::StartingClick()
1399{
1400 CBox()->SetValue(!CBox()->GetValue());
1401}
1402
1403bool wxGridCellBoolEditor::IsAcceptedKey(wxKeyEvent& event)
1404{
1405 if ( wxGridCellEditor::IsAcceptedKey(event) )
1406 {
1407 int keycode = event.GetKeyCode();
1408 switch ( keycode )
1409 {
1410 case WXK_SPACE:
1411 case '+':
1412 case '-':
1413 return true;
1414 }
1415 }
1416
1417 return false;
1418}
1419
1420void wxGridCellBoolEditor::StartingKey(wxKeyEvent& event)
1421{
1422 int keycode = event.GetKeyCode();
1423 switch ( keycode )
1424 {
1425 case WXK_SPACE:
1426 CBox()->SetValue(!CBox()->GetValue());
1427 break;
1428
1429 case '+':
1430 CBox()->SetValue(true);
1431 break;
1432
1433 case '-':
1434 CBox()->SetValue(false);
1435 break;
1436 }
1437}
1438
1439wxString wxGridCellBoolEditor::GetValue() const
1440{
1441 return ms_stringValues[CBox()->GetValue()];
1442}
1443
1444/* static */ void
1445wxGridCellBoolEditor::UseStringValues(const wxString& valueTrue,
1446 const wxString& valueFalse)
1447{
1448 ms_stringValues[false] = valueFalse;
1449 ms_stringValues[true] = valueTrue;
1450}
1451
1452/* static */ bool
1453wxGridCellBoolEditor::IsTrueValue(const wxString& value)
1454{
1455 return value == ms_stringValues[true];
1456}
1457
1458#endif // wxUSE_CHECKBOX
1459
1460#if wxUSE_COMBOBOX
1461
1462// ----------------------------------------------------------------------------
1463// wxGridCellChoiceEditor
1464// ----------------------------------------------------------------------------
1465
1466wxGridCellChoiceEditor::wxGridCellChoiceEditor(const wxArrayString& choices,
1467 bool allowOthers)
1468 : m_choices(choices),
1469 m_allowOthers(allowOthers) { }
1470
1471wxGridCellChoiceEditor::wxGridCellChoiceEditor(size_t count,
1472 const wxString choices[],
1473 bool allowOthers)
1474 : m_allowOthers(allowOthers)
1475{
1476 if ( count )
1477 {
1478 m_choices.Alloc(count);
1479 for ( size_t n = 0; n < count; n++ )
1480 {
1481 m_choices.Add(choices[n]);
1482 }
1483 }
1484}
1485
1486wxGridCellEditor *wxGridCellChoiceEditor::Clone() const
1487{
1488 wxGridCellChoiceEditor *editor = new wxGridCellChoiceEditor;
1489 editor->m_allowOthers = m_allowOthers;
1490 editor->m_choices = m_choices;
1491
1492 return editor;
1493}
1494
1495void wxGridCellChoiceEditor::Create(wxWindow* parent,
1496 wxWindowID id,
1497 wxEvtHandler* evtHandler)
1498{
1499 m_control = new wxComboBox(parent, id, wxEmptyString,
1500 wxDefaultPosition, wxDefaultSize,
1501 m_choices,
1502 m_allowOthers ? 0 : wxCB_READONLY);
1503
1504 wxGridCellEditor::Create(parent, id, evtHandler);
1505}
1506
1507void wxGridCellChoiceEditor::PaintBackground(const wxRect& rectCell,
1508 wxGridCellAttr * attr)
1509{
1510 // as we fill the entire client area, don't do anything here to minimize
1511 // flicker
1512
1513 // TODO: It doesn't actually fill the client area since the height of a
1514 // combo always defaults to the standard. Until someone has time to
1515 // figure out the right rectangle to paint, just do it the normal way.
1516 wxGridCellEditor::PaintBackground(rectCell, attr);
1517}
1518
1519void wxGridCellChoiceEditor::BeginEdit(int row, int col, wxGrid* grid)
1520{
1521 wxASSERT_MSG(m_control,
1522 wxT("The wxGridCellEditor must be created first!"));
1523
1524 wxGridCellEditorEvtHandler* evtHandler = NULL;
1525 if (m_control)
1526 evtHandler = wxDynamicCast(m_control->GetEventHandler(), wxGridCellEditorEvtHandler);
1527
1528 // Don't immediately end if we get a kill focus event within BeginEdit
1529 if (evtHandler)
1530 evtHandler->SetInSetFocus(true);
1531
1532 m_startValue = grid->GetTable()->GetValue(row, col);
1533
1534 if (m_allowOthers)
1535 {
1536 Combo()->SetValue(m_startValue);
1537 }
1538 else
1539 {
1540 // find the right position, or default to the first if not found
1541 int pos = Combo()->FindString(m_startValue);
1542 if (pos == wxNOT_FOUND)
1543 pos = 0;
1544 Combo()->SetSelection(pos);
1545 }
1546
1547 Combo()->SetInsertionPointEnd();
1548 Combo()->SetFocus();
1549
1550 if (evtHandler)
1551 {
1552 // When dropping down the menu, a kill focus event
1553 // happens after this point, so we can't reset the flag yet.
1554#if !defined(__WXGTK20__)
1555 evtHandler->SetInSetFocus(false);
1556#endif
1557 }
1558}
1559
1560bool wxGridCellChoiceEditor::EndEdit(int row, int col,
1561 wxGrid* grid)
1562{
1563 wxString value = Combo()->GetValue();
1564 if ( value == m_startValue )
1565 return false;
1566
1567 grid->GetTable()->SetValue(row, col, value);
1568
1569 return true;
1570}
1571
1572void wxGridCellChoiceEditor::Reset()
1573{
1574 Combo()->SetValue(m_startValue);
1575 Combo()->SetInsertionPointEnd();
1576}
1577
1578void wxGridCellChoiceEditor::SetParameters(const wxString& params)
1579{
1580 if ( !params )
1581 {
1582 // what can we do?
1583 return;
1584 }
1585
1586 m_choices.Empty();
1587
1588 wxStringTokenizer tk(params, _T(','));
1589 while ( tk.HasMoreTokens() )
1590 {
1591 m_choices.Add(tk.GetNextToken());
1592 }
1593}
1594
1595// return the value in the text control
1596wxString wxGridCellChoiceEditor::GetValue() const
1597{
1598 return Combo()->GetValue();
1599}
1600
1601#endif // wxUSE_COMBOBOX
1602
1603// ----------------------------------------------------------------------------
1604// wxGridCellEditorEvtHandler
1605// ----------------------------------------------------------------------------
1606
1607void wxGridCellEditorEvtHandler::OnKillFocus(wxFocusEvent& event)
1608{
1609 // Don't disable the cell if we're just starting to edit it
1610 if (m_inSetFocus)
1611 return;
1612
1613 // accept changes
1614 m_grid->DisableCellEditControl();
1615
1616 event.Skip();
1617}
1618
1619void wxGridCellEditorEvtHandler::OnKeyDown(wxKeyEvent& event)
1620{
1621 switch ( event.GetKeyCode() )
1622 {
1623 case WXK_ESCAPE:
1624 m_editor->Reset();
1625 m_grid->DisableCellEditControl();
1626 break;
1627
1628 case WXK_TAB:
1629 m_grid->GetEventHandler()->ProcessEvent( event );
1630 break;
1631
1632 case WXK_RETURN:
1633 case WXK_NUMPAD_ENTER:
1634 if (!m_grid->GetEventHandler()->ProcessEvent(event))
1635 m_editor->HandleReturn(event);
1636 break;
1637
1638 default:
1639 event.Skip();
1640 break;
1641 }
1642}
1643
1644void wxGridCellEditorEvtHandler::OnChar(wxKeyEvent& event)
1645{
1646 int row = m_grid->GetGridCursorRow();
1647 int col = m_grid->GetGridCursorCol();
1648 wxRect rect = m_grid->CellToRect( row, col );
1649 int cw, ch;
1650 m_grid->GetGridWindow()->GetClientSize( &cw, &ch );
1651
1652 // if cell width is smaller than grid client area, cell is wholly visible
1653 bool wholeCellVisible = (rect.GetWidth() < cw);
1654
1655 switch ( event.GetKeyCode() )
1656 {
1657 case WXK_ESCAPE:
1658 case WXK_TAB:
1659 case WXK_RETURN:
1660 case WXK_NUMPAD_ENTER:
1661 break;
1662
1663 case WXK_HOME:
1664 {
1665 if ( wholeCellVisible )
1666 {
1667 // no special processing needed...
1668 event.Skip();
1669 break;
1670 }
1671
1672 // do special processing for partly visible cell...
1673
1674 // get the widths of all cells previous to this one
1675 int colXPos = 0;
1676 for ( int i = 0; i < col; i++ )
1677 {
1678 colXPos += m_grid->GetColSize(i);
1679 }
1680
1681 int xUnit = 1, yUnit = 1;
1682 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
1683 if (col != 0)
1684 {
1685 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
1686 }
1687 else
1688 {
1689 m_grid->Scroll(colXPos / xUnit, m_grid->GetScrollPos(wxVERTICAL));
1690 }
1691 event.Skip();
1692 break;
1693 }
1694
1695 case WXK_END:
1696 {
1697 if ( wholeCellVisible )
1698 {
1699 // no special processing needed...
1700 event.Skip();
1701 break;
1702 }
1703
1704 // do special processing for partly visible cell...
1705
1706 int textWidth = 0;
1707 wxString value = m_grid->GetCellValue(row, col);
1708 if ( wxEmptyString != value )
1709 {
1710 // get width of cell CONTENTS (text)
1711 int y;
1712 wxFont font = m_grid->GetCellFont(row, col);
1713 m_grid->GetTextExtent(value, &textWidth, &y, NULL, NULL, &font);
1714
1715 // try to RIGHT align the text by scrolling
1716 int client_right = m_grid->GetGridWindow()->GetClientSize().GetWidth();
1717
1718 // (m_grid->GetScrollLineX()*2) is a factor for not scrolling to far,
1719 // otherwise the last part of the cell content might be hidden below the scroll bar
1720 // FIXME: maybe there is a more suitable correction?
1721 textWidth -= (client_right - (m_grid->GetScrollLineX() * 2));
1722 if ( textWidth < 0 )
1723 {
1724 textWidth = 0;
1725 }
1726 }
1727
1728 // get the widths of all cells previous to this one
1729 int colXPos = 0;
1730 for ( int i = 0; i < col; i++ )
1731 {
1732 colXPos += m_grid->GetColSize(i);
1733 }
1734
1735 // and add the (modified) text width of the cell contents
1736 // as we'd like to see the last part of the cell contents
1737 colXPos += textWidth;
1738
1739 int xUnit = 1, yUnit = 1;
1740 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
1741 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
1742 event.Skip();
1743 break;
1744 }
1745
1746 default:
1747 event.Skip();
1748 break;
1749 }
1750}
1751
1752// ----------------------------------------------------------------------------
1753// wxGridCellWorker is an (almost) empty common base class for
1754// wxGridCellRenderer and wxGridCellEditor managing ref counting
1755// ----------------------------------------------------------------------------
1756
1757void wxGridCellWorker::SetParameters(const wxString& WXUNUSED(params))
1758{
1759 // nothing to do
1760}
1761
1762wxGridCellWorker::~wxGridCellWorker()
1763{
1764}
1765
1766// ============================================================================
1767// renderer classes
1768// ============================================================================
1769
1770// ----------------------------------------------------------------------------
1771// wxGridCellRenderer
1772// ----------------------------------------------------------------------------
1773
1774void wxGridCellRenderer::Draw(wxGrid& grid,
1775 wxGridCellAttr& attr,
1776 wxDC& dc,
1777 const wxRect& rect,
1778 int WXUNUSED(row), int WXUNUSED(col),
1779 bool isSelected)
1780{
1781 dc.SetBackgroundMode( wxSOLID );
1782
1783 // grey out fields if the grid is disabled
1784 if ( grid.IsEnabled() )
1785 {
1786 if ( isSelected )
1787 {
1788 dc.SetBrush( wxBrush(grid.GetSelectionBackground(), wxSOLID) );
1789 }
1790 else
1791 {
1792 dc.SetBrush( wxBrush(attr.GetBackgroundColour(), wxSOLID) );
1793 }
1794 }
1795 else
1796 {
1797 dc.SetBrush(wxBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE), wxSOLID));
1798 }
1799
1800 dc.SetPen( *wxTRANSPARENT_PEN );
1801 dc.DrawRectangle(rect);
1802}
1803
1804// ----------------------------------------------------------------------------
1805// wxGridCellStringRenderer
1806// ----------------------------------------------------------------------------
1807
1808void wxGridCellStringRenderer::SetTextColoursAndFont(const wxGrid& grid,
1809 const wxGridCellAttr& attr,
1810 wxDC& dc,
1811 bool isSelected)
1812{
1813 dc.SetBackgroundMode( wxTRANSPARENT );
1814
1815 // TODO some special colours for attr.IsReadOnly() case?
1816
1817 // different coloured text when the grid is disabled
1818 if ( grid.IsEnabled() )
1819 {
1820 if ( isSelected )
1821 {
1822 dc.SetTextBackground( grid.GetSelectionBackground() );
1823 dc.SetTextForeground( grid.GetSelectionForeground() );
1824 }
1825 else
1826 {
1827 dc.SetTextBackground( attr.GetBackgroundColour() );
1828 dc.SetTextForeground( attr.GetTextColour() );
1829 }
1830 }
1831 else
1832 {
1833 dc.SetTextBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
1834 dc.SetTextForeground(wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT));
1835 }
1836
1837 dc.SetFont( attr.GetFont() );
1838}
1839
1840wxSize wxGridCellStringRenderer::DoGetBestSize(const wxGridCellAttr& attr,
1841 wxDC& dc,
1842 const wxString& text)
1843{
1844 wxCoord x = 0, y = 0, max_x = 0;
1845 dc.SetFont(attr.GetFont());
1846 wxStringTokenizer tk(text, _T('\n'));
1847 while ( tk.HasMoreTokens() )
1848 {
1849 dc.GetTextExtent(tk.GetNextToken(), &x, &y);
1850 max_x = wxMax(max_x, x);
1851 }
1852
1853 y *= 1 + text.Freq(wxT('\n')); // multiply by the number of lines.
1854
1855 return wxSize(max_x, y);
1856}
1857
1858wxSize wxGridCellStringRenderer::GetBestSize(wxGrid& grid,
1859 wxGridCellAttr& attr,
1860 wxDC& dc,
1861 int row, int col)
1862{
1863 return DoGetBestSize(attr, dc, grid.GetCellValue(row, col));
1864}
1865
1866void wxGridCellStringRenderer::Draw(wxGrid& grid,
1867 wxGridCellAttr& attr,
1868 wxDC& dc,
1869 const wxRect& rectCell,
1870 int row, int col,
1871 bool isSelected)
1872{
1873 wxRect rect = rectCell;
1874 rect.Inflate(-1);
1875
1876 // erase only this cells background, overflow cells should have been erased
1877 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
1878
1879 int hAlign, vAlign;
1880 attr.GetAlignment(&hAlign, &vAlign);
1881
1882 int overflowCols = 0;
1883
1884 if (attr.GetOverflow())
1885 {
1886 int cols = grid.GetNumberCols();
1887 int best_width = GetBestSize(grid,attr,dc,row,col).GetWidth();
1888 int cell_rows, cell_cols;
1889 attr.GetSize( &cell_rows, &cell_cols ); // shouldn't get here if <= 0
1890 if ((best_width > rectCell.width) && (col < cols) && grid.GetTable())
1891 {
1892 int i, c_cols, c_rows;
1893 for (i = col+cell_cols; i < cols; i++)
1894 {
1895 bool is_empty = true;
1896 for (int j=row; j < row + cell_rows; j++)
1897 {
1898 // check w/ anchor cell for multicell block
1899 grid.GetCellSize(j, i, &c_rows, &c_cols);
1900 if (c_rows > 0)
1901 c_rows = 0;
1902 if (!grid.GetTable()->IsEmptyCell(j + c_rows, i))
1903 {
1904 is_empty = false;
1905 break;
1906 }
1907 }
1908
1909 if (is_empty)
1910 {
1911 rect.width += grid.GetColSize(i);
1912 }
1913 else
1914 {
1915 i--;
1916 break;
1917 }
1918
1919 if (rect.width >= best_width)
1920 break;
1921 }
1922
1923 overflowCols = i - col - cell_cols + 1;
1924 if (overflowCols >= cols)
1925 overflowCols = cols - 1;
1926 }
1927
1928 if (overflowCols > 0) // redraw overflow cells w/ proper hilight
1929 {
1930 hAlign = wxALIGN_LEFT; // if oveflowed then it's left aligned
1931 wxRect clip = rect;
1932 clip.x += rectCell.width;
1933 // draw each overflow cell individually
1934 int col_end = col + cell_cols + overflowCols;
1935 if (col_end >= grid.GetNumberCols())
1936 col_end = grid.GetNumberCols() - 1;
1937 for (int i = col + cell_cols; i <= col_end; i++)
1938 {
1939 clip.width = grid.GetColSize(i) - 1;
1940 dc.DestroyClippingRegion();
1941 dc.SetClippingRegion(clip);
1942
1943 SetTextColoursAndFont(grid, attr, dc,
1944 grid.IsInSelection(row,i));
1945
1946 grid.DrawTextRectangle(dc, grid.GetCellValue(row, col),
1947 rect, hAlign, vAlign);
1948 clip.x += grid.GetColSize(i) - 1;
1949 }
1950
1951 rect = rectCell;
1952 rect.Inflate(-1);
1953 rect.width++;
1954 dc.DestroyClippingRegion();
1955 }
1956 }
1957
1958 // now we only have to draw the text
1959 SetTextColoursAndFont(grid, attr, dc, isSelected);
1960
1961 grid.DrawTextRectangle(dc, grid.GetCellValue(row, col),
1962 rect, hAlign, vAlign);
1963}
1964
1965// ----------------------------------------------------------------------------
1966// wxGridCellNumberRenderer
1967// ----------------------------------------------------------------------------
1968
1969wxString wxGridCellNumberRenderer::GetString(const wxGrid& grid, int row, int col)
1970{
1971 wxGridTableBase *table = grid.GetTable();
1972 wxString text;
1973 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
1974 {
1975 text.Printf(_T("%ld"), table->GetValueAsLong(row, col));
1976 }
1977 else
1978 {
1979 text = table->GetValue(row, col);
1980 }
1981
1982 return text;
1983}
1984
1985void wxGridCellNumberRenderer::Draw(wxGrid& grid,
1986 wxGridCellAttr& attr,
1987 wxDC& dc,
1988 const wxRect& rectCell,
1989 int row, int col,
1990 bool isSelected)
1991{
1992 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
1993
1994 SetTextColoursAndFont(grid, attr, dc, isSelected);
1995
1996 // draw the text right aligned by default
1997 int hAlign, vAlign;
1998 attr.GetAlignment(&hAlign, &vAlign);
1999 hAlign = wxALIGN_RIGHT;
2000
2001 wxRect rect = rectCell;
2002 rect.Inflate(-1);
2003
2004 grid.DrawTextRectangle(dc, GetString(grid, row, col), rect, hAlign, vAlign);
2005}
2006
2007wxSize wxGridCellNumberRenderer::GetBestSize(wxGrid& grid,
2008 wxGridCellAttr& attr,
2009 wxDC& dc,
2010 int row, int col)
2011{
2012 return DoGetBestSize(attr, dc, GetString(grid, row, col));
2013}
2014
2015// ----------------------------------------------------------------------------
2016// wxGridCellFloatRenderer
2017// ----------------------------------------------------------------------------
2018
2019wxGridCellFloatRenderer::wxGridCellFloatRenderer(int width, int precision)
2020{
2021 SetWidth(width);
2022 SetPrecision(precision);
2023}
2024
2025wxGridCellRenderer *wxGridCellFloatRenderer::Clone() const
2026{
2027 wxGridCellFloatRenderer *renderer = new wxGridCellFloatRenderer;
2028 renderer->m_width = m_width;
2029 renderer->m_precision = m_precision;
2030 renderer->m_format = m_format;
2031
2032 return renderer;
2033}
2034
2035wxString wxGridCellFloatRenderer::GetString(const wxGrid& grid, int row, int col)
2036{
2037 wxGridTableBase *table = grid.GetTable();
2038
2039 bool hasDouble;
2040 double val;
2041 wxString text;
2042 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_FLOAT) )
2043 {
2044 val = table->GetValueAsDouble(row, col);
2045 hasDouble = true;
2046 }
2047 else
2048 {
2049 text = table->GetValue(row, col);
2050 hasDouble = text.ToDouble(&val);
2051 }
2052
2053 if ( hasDouble )
2054 {
2055 if ( !m_format )
2056 {
2057 if ( m_width == -1 )
2058 {
2059 if ( m_precision == -1 )
2060 {
2061 // default width/precision
2062 m_format = _T("%f");
2063 }
2064 else
2065 {
2066 m_format.Printf(_T("%%.%df"), m_precision);
2067 }
2068 }
2069 else if ( m_precision == -1 )
2070 {
2071 // default precision
2072 m_format.Printf(_T("%%%d.f"), m_width);
2073 }
2074 else
2075 {
2076 m_format.Printf(_T("%%%d.%df"), m_width, m_precision);
2077 }
2078 }
2079
2080 text.Printf(m_format, val);
2081
2082 }
2083 //else: text already contains the string
2084
2085 return text;
2086}
2087
2088void wxGridCellFloatRenderer::Draw(wxGrid& grid,
2089 wxGridCellAttr& attr,
2090 wxDC& dc,
2091 const wxRect& rectCell,
2092 int row, int col,
2093 bool isSelected)
2094{
2095 wxGridCellRenderer::Draw(grid, attr, dc, rectCell, row, col, isSelected);
2096
2097 SetTextColoursAndFont(grid, attr, dc, isSelected);
2098
2099 // draw the text right aligned by default
2100 int hAlign, vAlign;
2101 attr.GetAlignment(&hAlign, &vAlign);
2102 hAlign = wxALIGN_RIGHT;
2103
2104 wxRect rect = rectCell;
2105 rect.Inflate(-1);
2106
2107 grid.DrawTextRectangle(dc, GetString(grid, row, col), rect, hAlign, vAlign);
2108}
2109
2110wxSize wxGridCellFloatRenderer::GetBestSize(wxGrid& grid,
2111 wxGridCellAttr& attr,
2112 wxDC& dc,
2113 int row, int col)
2114{
2115 return DoGetBestSize(attr, dc, GetString(grid, row, col));
2116}
2117
2118void wxGridCellFloatRenderer::SetParameters(const wxString& params)
2119{
2120 if ( !params )
2121 {
2122 // reset to defaults
2123 SetWidth(-1);
2124 SetPrecision(-1);
2125 }
2126 else
2127 {
2128 wxString tmp = params.BeforeFirst(_T(','));
2129 if ( !tmp.empty() )
2130 {
2131 long width;
2132 if ( tmp.ToLong(&width) )
2133 {
2134 SetWidth((int)width);
2135 }
2136 else
2137 {
2138 wxLogDebug(_T("Invalid wxGridCellFloatRenderer width parameter string '%s ignored"), params.c_str());
2139 }
2140 }
2141
2142 tmp = params.AfterFirst(_T(','));
2143 if ( !tmp.empty() )
2144 {
2145 long precision;
2146 if ( tmp.ToLong(&precision) )
2147 {
2148 SetPrecision((int)precision);
2149 }
2150 else
2151 {
2152 wxLogDebug(_T("Invalid wxGridCellFloatRenderer precision parameter string '%s ignored"), params.c_str());
2153 }
2154 }
2155 }
2156}
2157
2158// ----------------------------------------------------------------------------
2159// wxGridCellBoolRenderer
2160// ----------------------------------------------------------------------------
2161
2162wxSize wxGridCellBoolRenderer::ms_sizeCheckMark;
2163
2164// FIXME these checkbox size calculations are really ugly...
2165
2166// between checkmark and box
2167static const wxCoord wxGRID_CHECKMARK_MARGIN = 2;
2168
2169wxSize wxGridCellBoolRenderer::GetBestSize(wxGrid& grid,
2170 wxGridCellAttr& WXUNUSED(attr),
2171 wxDC& WXUNUSED(dc),
2172 int WXUNUSED(row),
2173 int WXUNUSED(col))
2174{
2175 // compute it only once (no locks for MT safeness in GUI thread...)
2176 if ( !ms_sizeCheckMark.x )
2177 {
2178 // get checkbox size
2179 wxCheckBox *checkbox = new wxCheckBox(&grid, wxID_ANY, wxEmptyString);
2180 wxSize size = checkbox->GetBestSize();
2181 wxCoord checkSize = size.y + 2 * wxGRID_CHECKMARK_MARGIN;
2182
2183 // FIXME wxGTK::wxCheckBox::GetBestSize() gives "wrong" result
2184#if defined(__WXGTK__) || defined(__WXMOTIF__)
2185 checkSize -= size.y / 2;
2186#endif
2187
2188 delete checkbox;
2189
2190 ms_sizeCheckMark.x = ms_sizeCheckMark.y = checkSize;
2191 }
2192
2193 return ms_sizeCheckMark;
2194}
2195
2196void wxGridCellBoolRenderer::Draw(wxGrid& grid,
2197 wxGridCellAttr& attr,
2198 wxDC& dc,
2199 const wxRect& rect,
2200 int row, int col,
2201 bool isSelected)
2202{
2203 wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, isSelected);
2204
2205 // draw a check mark in the centre (ignoring alignment - TODO)
2206 wxSize size = GetBestSize(grid, attr, dc, row, col);
2207
2208 // don't draw outside the cell
2209 wxCoord minSize = wxMin(rect.width, rect.height);
2210 if ( size.x >= minSize || size.y >= minSize )
2211 {
2212 // and even leave (at least) 1 pixel margin
2213 size.x = size.y = minSize - 2;
2214 }
2215
2216 // draw a border around checkmark
2217 int vAlign, hAlign;
2218 attr.GetAlignment(&hAlign, &vAlign);
2219
2220 wxRect rectBorder;
2221 if (hAlign == wxALIGN_CENTRE)
2222 {
2223 rectBorder.x = rect.x + rect.width / 2 - size.x / 2;
2224 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2225 rectBorder.width = size.x;
2226 rectBorder.height = size.y;
2227 }
2228 else if (hAlign == wxALIGN_LEFT)
2229 {
2230 rectBorder.x = rect.x + 2;
2231 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2232 rectBorder.width = size.x;
2233 rectBorder.height = size.y;
2234 }
2235 else if (hAlign == wxALIGN_RIGHT)
2236 {
2237 rectBorder.x = rect.x + rect.width - size.x - 2;
2238 rectBorder.y = rect.y + rect.height / 2 - size.y / 2;
2239 rectBorder.width = size.x;
2240 rectBorder.height = size.y;
2241 }
2242
2243 bool value;
2244 if ( grid.GetTable()->CanGetValueAs(row, col, wxGRID_VALUE_BOOL) )
2245 {
2246 value = grid.GetTable()->GetValueAsBool(row, col);
2247 }
2248 else
2249 {
2250 wxString cellval( grid.GetTable()->GetValue(row, col) );
2251 value = wxGridCellBoolEditor::IsTrueValue(cellval);
2252 }
2253
2254 if ( value )
2255 {
2256 wxRect rectMark = rectBorder;
2257
2258#ifdef __WXMSW__
2259 // MSW DrawCheckMark() is weird (and should probably be changed...)
2260 rectMark.Inflate(-wxGRID_CHECKMARK_MARGIN / 2);
2261 rectMark.x++;
2262 rectMark.y++;
2263#else
2264 rectMark.Inflate(-wxGRID_CHECKMARK_MARGIN);
2265#endif
2266
2267 dc.SetTextForeground(attr.GetTextColour());
2268 dc.DrawCheckMark(rectMark);
2269 }
2270
2271 dc.SetBrush(*wxTRANSPARENT_BRUSH);
2272 dc.SetPen(wxPen(attr.GetTextColour(), 1, wxSOLID));
2273 dc.DrawRectangle(rectBorder);
2274}
2275
2276// ----------------------------------------------------------------------------
2277// wxGridCellAttr
2278// ----------------------------------------------------------------------------
2279
2280void wxGridCellAttr::Init(wxGridCellAttr *attrDefault)
2281{
2282 m_nRef = 1;
2283
2284 m_isReadOnly = Unset;
2285
2286 m_renderer = NULL;
2287 m_editor = NULL;
2288
2289 m_attrkind = wxGridCellAttr::Cell;
2290
2291 m_sizeRows = m_sizeCols = 1;
2292 m_overflow = UnsetOverflow;
2293
2294 SetDefAttr(attrDefault);
2295}
2296
2297wxGridCellAttr *wxGridCellAttr::Clone() const
2298{
2299 wxGridCellAttr *attr = new wxGridCellAttr(m_defGridAttr);
2300
2301 if ( HasTextColour() )
2302 attr->SetTextColour(GetTextColour());
2303 if ( HasBackgroundColour() )
2304 attr->SetBackgroundColour(GetBackgroundColour());
2305 if ( HasFont() )
2306 attr->SetFont(GetFont());
2307 if ( HasAlignment() )
2308 attr->SetAlignment(m_hAlign, m_vAlign);
2309
2310 attr->SetSize( m_sizeRows, m_sizeCols );
2311
2312 if ( m_renderer )
2313 {
2314 attr->SetRenderer(m_renderer);
2315 m_renderer->IncRef();
2316 }
2317 if ( m_editor )
2318 {
2319 attr->SetEditor(m_editor);
2320 m_editor->IncRef();
2321 }
2322
2323 if ( IsReadOnly() )
2324 attr->SetReadOnly();
2325
2326 attr->SetOverflow( m_overflow == Overflow );
2327 attr->SetKind( m_attrkind );
2328
2329 return attr;
2330}
2331
2332void wxGridCellAttr::MergeWith(wxGridCellAttr *mergefrom)
2333{
2334 if ( !HasTextColour() && mergefrom->HasTextColour() )
2335 SetTextColour(mergefrom->GetTextColour());
2336 if ( !HasBackgroundColour() && mergefrom->HasBackgroundColour() )
2337 SetBackgroundColour(mergefrom->GetBackgroundColour());
2338 if ( !HasFont() && mergefrom->HasFont() )
2339 SetFont(mergefrom->GetFont());
2340 if ( !HasAlignment() && mergefrom->HasAlignment() )
2341 {
2342 int hAlign, vAlign;
2343 mergefrom->GetAlignment( &hAlign, &vAlign);
2344 SetAlignment(hAlign, vAlign);
2345 }
2346 if ( !HasSize() && mergefrom->HasSize() )
2347 mergefrom->GetSize( &m_sizeRows, &m_sizeCols );
2348
2349 // Directly access member functions as GetRender/Editor don't just return
2350 // m_renderer/m_editor
2351 //
2352 // Maybe add support for merge of Render and Editor?
2353 if (!HasRenderer() && mergefrom->HasRenderer() )
2354 {
2355 m_renderer = mergefrom->m_renderer;
2356 m_renderer->IncRef();
2357 }
2358 if ( !HasEditor() && mergefrom->HasEditor() )
2359 {
2360 m_editor = mergefrom->m_editor;
2361 m_editor->IncRef();
2362 }
2363 if ( !HasReadWriteMode() && mergefrom->HasReadWriteMode() )
2364 SetReadOnly(mergefrom->IsReadOnly());
2365
2366 if (!HasOverflowMode() && mergefrom->HasOverflowMode() )
2367 SetOverflow(mergefrom->GetOverflow());
2368
2369 SetDefAttr(mergefrom->m_defGridAttr);
2370}
2371
2372void wxGridCellAttr::SetSize(int num_rows, int num_cols)
2373{
2374 // The size of a cell is normally 1,1
2375
2376 // If this cell is larger (2,2) then this is the top left cell
2377 // the other cells that will be covered (lower right cells) must be
2378 // set to negative or zero values such that
2379 // row + num_rows of the covered cell points to the larger cell (this cell)
2380 // same goes for the col + num_cols.
2381
2382 // Size of 0,0 is NOT valid, neither is <=0 and any positive value
2383
2384 wxASSERT_MSG( (!((num_rows > 0) && (num_cols <= 0)) ||
2385 !((num_rows <= 0) && (num_cols > 0)) ||
2386 !((num_rows == 0) && (num_cols == 0))),
2387 wxT("wxGridCellAttr::SetSize only takes two postive values or negative/zero values"));
2388
2389 m_sizeRows = num_rows;
2390 m_sizeCols = num_cols;
2391}
2392
2393const wxColour& wxGridCellAttr::GetTextColour() const
2394{
2395 if (HasTextColour())
2396 {
2397 return m_colText;
2398 }
2399 else if (m_defGridAttr && m_defGridAttr != this)
2400 {
2401 return m_defGridAttr->GetTextColour();
2402 }
2403 else
2404 {
2405 wxFAIL_MSG(wxT("Missing default cell attribute"));
2406 return wxNullColour;
2407 }
2408}
2409
2410const wxColour& wxGridCellAttr::GetBackgroundColour() const
2411{
2412 if (HasBackgroundColour())
2413 {
2414 return m_colBack;
2415 }
2416 else if (m_defGridAttr && m_defGridAttr != this)
2417 {
2418 return m_defGridAttr->GetBackgroundColour();
2419 }
2420 else
2421 {
2422 wxFAIL_MSG(wxT("Missing default cell attribute"));
2423 return wxNullColour;
2424 }
2425}
2426
2427const wxFont& wxGridCellAttr::GetFont() const
2428{
2429 if (HasFont())
2430 {
2431 return m_font;
2432 }
2433 else if (m_defGridAttr && m_defGridAttr != this)
2434 {
2435 return m_defGridAttr->GetFont();
2436 }
2437 else
2438 {
2439 wxFAIL_MSG(wxT("Missing default cell attribute"));
2440 return wxNullFont;
2441 }
2442}
2443
2444void wxGridCellAttr::GetAlignment(int *hAlign, int *vAlign) const
2445{
2446 if (HasAlignment())
2447 {
2448 if ( hAlign )
2449 *hAlign = m_hAlign;
2450 if ( vAlign )
2451 *vAlign = m_vAlign;
2452 }
2453 else if (m_defGridAttr && m_defGridAttr != this)
2454 {
2455 m_defGridAttr->GetAlignment(hAlign, vAlign);
2456 }
2457 else
2458 {
2459 wxFAIL_MSG(wxT("Missing default cell attribute"));
2460 }
2461}
2462
2463void wxGridCellAttr::GetSize( int *num_rows, int *num_cols ) const
2464{
2465 if ( num_rows )
2466 *num_rows = m_sizeRows;
2467 if ( num_cols )
2468 *num_cols = m_sizeCols;
2469}
2470
2471// GetRenderer and GetEditor use a slightly different decision path about
2472// which attribute to use. If a non-default attr object has one then it is
2473// used, otherwise the default editor or renderer is fetched from the grid and
2474// used. It should be the default for the data type of the cell. If it is
2475// NULL (because the table has a type that the grid does not have in its
2476// registry), then the grid's default editor or renderer is used.
2477
2478wxGridCellRenderer* wxGridCellAttr::GetRenderer(wxGrid* grid, int row, int col) const
2479{
2480 wxGridCellRenderer *renderer = NULL;
2481
2482 if ( m_renderer && this != m_defGridAttr )
2483 {
2484 // use the cells renderer if it has one
2485 renderer = m_renderer;
2486 renderer->IncRef();
2487 }
2488 else // no non-default cell renderer
2489 {
2490 // get default renderer for the data type
2491 if ( grid )
2492 {
2493 // GetDefaultRendererForCell() will do IncRef() for us
2494 renderer = grid->GetDefaultRendererForCell(row, col);
2495 }
2496
2497 if ( renderer == NULL )
2498 {
2499 if ( (m_defGridAttr != NULL) && (m_defGridAttr != this) )
2500 {
2501 // if we still don't have one then use the grid default
2502 // (no need for IncRef() here neither)
2503 renderer = m_defGridAttr->GetRenderer(NULL, 0, 0);
2504 }
2505 else // default grid attr
2506 {
2507 // use m_renderer which we had decided not to use initially
2508 renderer = m_renderer;
2509 if ( renderer )
2510 renderer->IncRef();
2511 }
2512 }
2513 }
2514
2515 // we're supposed to always find something
2516 wxASSERT_MSG(renderer, wxT("Missing default cell renderer"));
2517
2518 return renderer;
2519}
2520
2521// same as above, except for s/renderer/editor/g
2522wxGridCellEditor* wxGridCellAttr::GetEditor(wxGrid* grid, int row, int col) const
2523{
2524 wxGridCellEditor *editor = NULL;
2525
2526 if ( m_editor && this != m_defGridAttr )
2527 {
2528 // use the cells editor if it has one
2529 editor = m_editor;
2530 editor->IncRef();
2531 }
2532 else // no non default cell editor
2533 {
2534 // get default editor for the data type
2535 if ( grid )
2536 {
2537 // GetDefaultEditorForCell() will do IncRef() for us
2538 editor = grid->GetDefaultEditorForCell(row, col);
2539 }
2540
2541 if ( editor == NULL )
2542 {
2543 if ( (m_defGridAttr != NULL) && (m_defGridAttr != this) )
2544 {
2545 // if we still don't have one then use the grid default
2546 // (no need for IncRef() here neither)
2547 editor = m_defGridAttr->GetEditor(NULL, 0, 0);
2548 }
2549 else // default grid attr
2550 {
2551 // use m_editor which we had decided not to use initially
2552 editor = m_editor;
2553 if ( editor )
2554 editor->IncRef();
2555 }
2556 }
2557 }
2558
2559 // we're supposed to always find something
2560 wxASSERT_MSG(editor, wxT("Missing default cell editor"));
2561
2562 return editor;
2563}
2564
2565// ----------------------------------------------------------------------------
2566// wxGridCellAttrData
2567// ----------------------------------------------------------------------------
2568
2569void wxGridCellAttrData::SetAttr(wxGridCellAttr *attr, int row, int col)
2570{
2571 int n = FindIndex(row, col);
2572 if ( n == wxNOT_FOUND )
2573 {
2574 // add the attribute
2575 m_attrs.Add(new wxGridCellWithAttr(row, col, attr));
2576 }
2577 else
2578 {
2579 // free the old attribute
2580 m_attrs[(size_t)n].attr->DecRef();
2581
2582 if ( attr )
2583 {
2584 // change the attribute
2585 m_attrs[(size_t)n].attr = attr;
2586 }
2587 else
2588 {
2589 // remove this attribute
2590 m_attrs.RemoveAt((size_t)n);
2591 }
2592 }
2593}
2594
2595wxGridCellAttr *wxGridCellAttrData::GetAttr(int row, int col) const
2596{
2597 wxGridCellAttr *attr = (wxGridCellAttr *)NULL;
2598
2599 int n = FindIndex(row, col);
2600 if ( n != wxNOT_FOUND )
2601 {
2602 attr = m_attrs[(size_t)n].attr;
2603 attr->IncRef();
2604 }
2605
2606 return attr;
2607}
2608
2609void wxGridCellAttrData::UpdateAttrRows( size_t pos, int numRows )
2610{
2611 size_t count = m_attrs.GetCount();
2612 for ( size_t n = 0; n < count; n++ )
2613 {
2614 wxGridCellCoords& coords = m_attrs[n].coords;
2615 wxCoord row = coords.GetRow();
2616 if ((size_t)row >= pos)
2617 {
2618 if (numRows > 0)
2619 {
2620 // If rows inserted, include row counter where necessary
2621 coords.SetRow(row + numRows);
2622 }
2623 else if (numRows < 0)
2624 {
2625 // If rows deleted ...
2626 if ((size_t)row >= pos - numRows)
2627 {
2628 // ...either decrement row counter (if row still exists)...
2629 coords.SetRow(row + numRows);
2630 }
2631 else
2632 {
2633 // ...or remove the attribute
2634 // No need to DecRef the attribute itself since this is
2635 // done be wxGridCellWithAttr's destructor!
2636 m_attrs.RemoveAt(n);
2637 n--;
2638 count--;
2639 }
2640 }
2641 }
2642 }
2643}
2644
2645void wxGridCellAttrData::UpdateAttrCols( size_t pos, int numCols )
2646{
2647 size_t count = m_attrs.GetCount();
2648 for ( size_t n = 0; n < count; n++ )
2649 {
2650 wxGridCellCoords& coords = m_attrs[n].coords;
2651 wxCoord col = coords.GetCol();
2652 if ( (size_t)col >= pos )
2653 {
2654 if ( numCols > 0 )
2655 {
2656 // If rows inserted, include row counter where necessary
2657 coords.SetCol(col + numCols);
2658 }
2659 else if (numCols < 0)
2660 {
2661 // If rows deleted ...
2662 if ((size_t)col >= pos - numCols)
2663 {
2664 // ...either decrement row counter (if row still exists)...
2665 coords.SetCol(col + numCols);
2666 }
2667 else
2668 {
2669 // ...or remove the attribute
2670 // No need to DecRef the attribute itself since this is
2671 // done be wxGridCellWithAttr's destructor!
2672 m_attrs.RemoveAt(n);
2673 n--;
2674 count--;
2675 }
2676 }
2677 }
2678 }
2679}
2680
2681int wxGridCellAttrData::FindIndex(int row, int col) const
2682{
2683 size_t count = m_attrs.GetCount();
2684 for ( size_t n = 0; n < count; n++ )
2685 {
2686 const wxGridCellCoords& coords = m_attrs[n].coords;
2687 if ( (coords.GetRow() == row) && (coords.GetCol() == col) )
2688 {
2689 return n;
2690 }
2691 }
2692
2693 return wxNOT_FOUND;
2694}
2695
2696// ----------------------------------------------------------------------------
2697// wxGridRowOrColAttrData
2698// ----------------------------------------------------------------------------
2699
2700wxGridRowOrColAttrData::~wxGridRowOrColAttrData()
2701{
2702 size_t count = m_attrs.Count();
2703 for ( size_t n = 0; n < count; n++ )
2704 {
2705 m_attrs[n]->DecRef();
2706 }
2707}
2708
2709wxGridCellAttr *wxGridRowOrColAttrData::GetAttr(int rowOrCol) const
2710{
2711 wxGridCellAttr *attr = (wxGridCellAttr *)NULL;
2712
2713 int n = m_rowsOrCols.Index(rowOrCol);
2714 if ( n != wxNOT_FOUND )
2715 {
2716 attr = m_attrs[(size_t)n];
2717 attr->IncRef();
2718 }
2719
2720 return attr;
2721}
2722
2723void wxGridRowOrColAttrData::SetAttr(wxGridCellAttr *attr, int rowOrCol)
2724{
2725 int i = m_rowsOrCols.Index(rowOrCol);
2726 if ( i == wxNOT_FOUND )
2727 {
2728 // add the attribute
2729 m_rowsOrCols.Add(rowOrCol);
2730 m_attrs.Add(attr);
2731 }
2732 else
2733 {
2734 size_t n = (size_t)i;
2735 if ( attr )
2736 {
2737 // change the attribute
2738 m_attrs[n]->DecRef();
2739 m_attrs[n] = attr;
2740 }
2741 else
2742 {
2743 // remove this attribute
2744 m_attrs[n]->DecRef();
2745 m_rowsOrCols.RemoveAt(n);
2746 m_attrs.RemoveAt(n);
2747 }
2748 }
2749}
2750
2751void wxGridRowOrColAttrData::UpdateAttrRowsOrCols( size_t pos, int numRowsOrCols )
2752{
2753 size_t count = m_attrs.GetCount();
2754 for ( size_t n = 0; n < count; n++ )
2755 {
2756 int & rowOrCol = m_rowsOrCols[n];
2757 if ( (size_t)rowOrCol >= pos )
2758 {
2759 if ( numRowsOrCols > 0 )
2760 {
2761 // If rows inserted, include row counter where necessary
2762 rowOrCol += numRowsOrCols;
2763 }
2764 else if ( numRowsOrCols < 0)
2765 {
2766 // If rows deleted, either decrement row counter (if row still exists)
2767 if ((size_t)rowOrCol >= pos - numRowsOrCols)
2768 rowOrCol += numRowsOrCols;
2769 else
2770 {
2771 m_rowsOrCols.RemoveAt(n);
2772 m_attrs[n]->DecRef();
2773 m_attrs.RemoveAt(n);
2774 n--;
2775 count--;
2776 }
2777 }
2778 }
2779 }
2780}
2781
2782// ----------------------------------------------------------------------------
2783// wxGridCellAttrProvider
2784// ----------------------------------------------------------------------------
2785
2786wxGridCellAttrProvider::wxGridCellAttrProvider()
2787{
2788 m_data = (wxGridCellAttrProviderData *)NULL;
2789}
2790
2791wxGridCellAttrProvider::~wxGridCellAttrProvider()
2792{
2793 delete m_data;
2794}
2795
2796void wxGridCellAttrProvider::InitData()
2797{
2798 m_data = new wxGridCellAttrProviderData;
2799}
2800
2801wxGridCellAttr *wxGridCellAttrProvider::GetAttr(int row, int col,
2802 wxGridCellAttr::wxAttrKind kind ) const
2803{
2804 wxGridCellAttr *attr = (wxGridCellAttr *)NULL;
2805 if ( m_data )
2806 {
2807 switch (kind)
2808 {
2809 case (wxGridCellAttr::Any):
2810 // Get cached merge attributes.
2811 // Currently not used as no cache implemented as not mutable
2812 // attr = m_data->m_mergeAttr.GetAttr(row, col);
2813 if (!attr)
2814 {
2815 // Basically implement old version.
2816 // Also check merge cache, so we don't have to re-merge every time..
2817 wxGridCellAttr *attrcell = m_data->m_cellAttrs.GetAttr(row, col);
2818 wxGridCellAttr *attrrow = m_data->m_rowAttrs.GetAttr(row);
2819 wxGridCellAttr *attrcol = m_data->m_colAttrs.GetAttr(col);
2820
2821 if ((attrcell != attrrow) && (attrrow != attrcol) && (attrcell != attrcol))
2822 {
2823 // Two or more are non NULL
2824 attr = new wxGridCellAttr;
2825 attr->SetKind(wxGridCellAttr::Merged);
2826
2827 // Order is important..
2828 if (attrcell)
2829 {
2830 attr->MergeWith(attrcell);
2831 attrcell->DecRef();
2832 }
2833 if (attrcol)
2834 {
2835 attr->MergeWith(attrcol);
2836 attrcol->DecRef();
2837 }
2838 if (attrrow)
2839 {
2840 attr->MergeWith(attrrow);
2841 attrrow->DecRef();
2842 }
2843
2844 // store merge attr if cache implemented
2845 //attr->IncRef();
2846 //m_data->m_mergeAttr.SetAttr(attr, row, col);
2847 }
2848 else
2849 {
2850 // one or none is non null return it or null.
2851 if (attrrow)
2852 attr = attrrow;
2853 if (attrcol)
2854 {
2855 if (attr)
2856 attr->DecRef();
2857 attr = attrcol;
2858 }
2859 if (attrcell)
2860 {
2861 if (attr)
2862 attr->DecRef();
2863 attr = attrcell;
2864 }
2865 }
2866 }
2867 break;
2868
2869 case (wxGridCellAttr::Cell):
2870 attr = m_data->m_cellAttrs.GetAttr(row, col);
2871 break;
2872
2873 case (wxGridCellAttr::Col):
2874 attr = m_data->m_colAttrs.GetAttr(col);
2875 break;
2876
2877 case (wxGridCellAttr::Row):
2878 attr = m_data->m_rowAttrs.GetAttr(row);
2879 break;
2880
2881 default:
2882 // unused as yet...
2883 // (wxGridCellAttr::Default):
2884 // (wxGridCellAttr::Merged):
2885 break;
2886 }
2887 }
2888
2889 return attr;
2890}
2891
2892void wxGridCellAttrProvider::SetAttr(wxGridCellAttr *attr,
2893 int row, int col)
2894{
2895 if ( !m_data )
2896 InitData();
2897
2898 m_data->m_cellAttrs.SetAttr(attr, row, col);
2899}
2900
2901void wxGridCellAttrProvider::SetRowAttr(wxGridCellAttr *attr, int row)
2902{
2903 if ( !m_data )
2904 InitData();
2905
2906 m_data->m_rowAttrs.SetAttr(attr, row);
2907}
2908
2909void wxGridCellAttrProvider::SetColAttr(wxGridCellAttr *attr, int col)
2910{
2911 if ( !m_data )
2912 InitData();
2913
2914 m_data->m_colAttrs.SetAttr(attr, col);
2915}
2916
2917void wxGridCellAttrProvider::UpdateAttrRows( size_t pos, int numRows )
2918{
2919 if ( m_data )
2920 {
2921 m_data->m_cellAttrs.UpdateAttrRows( pos, numRows );
2922
2923 m_data->m_rowAttrs.UpdateAttrRowsOrCols( pos, numRows );
2924 }
2925}
2926
2927void wxGridCellAttrProvider::UpdateAttrCols( size_t pos, int numCols )
2928{
2929 if ( m_data )
2930 {
2931 m_data->m_cellAttrs.UpdateAttrCols( pos, numCols );
2932
2933 m_data->m_colAttrs.UpdateAttrRowsOrCols( pos, numCols );
2934 }
2935}
2936
2937// ----------------------------------------------------------------------------
2938// wxGridTypeRegistry
2939// ----------------------------------------------------------------------------
2940
2941wxGridTypeRegistry::~wxGridTypeRegistry()
2942{
2943 size_t count = m_typeinfo.Count();
2944 for ( size_t i = 0; i < count; i++ )
2945 delete m_typeinfo[i];
2946}
2947
2948void wxGridTypeRegistry::RegisterDataType(const wxString& typeName,
2949 wxGridCellRenderer* renderer,
2950 wxGridCellEditor* editor)
2951{
2952 wxGridDataTypeInfo* info = new wxGridDataTypeInfo(typeName, renderer, editor);
2953
2954 // is it already registered?
2955 int loc = FindRegisteredDataType(typeName);
2956 if ( loc != wxNOT_FOUND )
2957 {
2958 delete m_typeinfo[loc];
2959 m_typeinfo[loc] = info;
2960 }
2961 else
2962 {
2963 m_typeinfo.Add(info);
2964 }
2965}
2966
2967int wxGridTypeRegistry::FindRegisteredDataType(const wxString& typeName)
2968{
2969 size_t count = m_typeinfo.GetCount();
2970 for ( size_t i = 0; i < count; i++ )
2971 {
2972 if ( typeName == m_typeinfo[i]->m_typeName )
2973 {
2974 return i;
2975 }
2976 }
2977
2978 return wxNOT_FOUND;
2979}
2980
2981int wxGridTypeRegistry::FindDataType(const wxString& typeName)
2982{
2983 int index = FindRegisteredDataType(typeName);
2984 if ( index == wxNOT_FOUND )
2985 {
2986 // check whether this is one of the standard ones, in which case
2987 // register it "on the fly"
2988#if wxUSE_TEXTCTRL
2989 if ( typeName == wxGRID_VALUE_STRING )
2990 {
2991 RegisterDataType(wxGRID_VALUE_STRING,
2992 new wxGridCellStringRenderer,
2993 new wxGridCellTextEditor);
2994 }
2995 else
2996#endif // wxUSE_TEXTCTRL
2997#if wxUSE_CHECKBOX
2998 if ( typeName == wxGRID_VALUE_BOOL )
2999 {
3000 RegisterDataType(wxGRID_VALUE_BOOL,
3001 new wxGridCellBoolRenderer,
3002 new wxGridCellBoolEditor);
3003 }
3004 else
3005#endif // wxUSE_CHECKBOX
3006#if wxUSE_TEXTCTRL
3007 if ( typeName == wxGRID_VALUE_NUMBER )
3008 {
3009 RegisterDataType(wxGRID_VALUE_NUMBER,
3010 new wxGridCellNumberRenderer,
3011 new wxGridCellNumberEditor);
3012 }
3013 else if ( typeName == wxGRID_VALUE_FLOAT )
3014 {
3015 RegisterDataType(wxGRID_VALUE_FLOAT,
3016 new wxGridCellFloatRenderer,
3017 new wxGridCellFloatEditor);
3018 }
3019 else
3020#endif // wxUSE_TEXTCTRL
3021#if wxUSE_COMBOBOX
3022 if ( typeName == wxGRID_VALUE_CHOICE )
3023 {
3024 RegisterDataType(wxGRID_VALUE_CHOICE,
3025 new wxGridCellStringRenderer,
3026 new wxGridCellChoiceEditor);
3027 }
3028 else
3029#endif // wxUSE_COMBOBOX
3030 {
3031 return wxNOT_FOUND;
3032 }
3033
3034 // we get here only if just added the entry for this type, so return
3035 // the last index
3036 index = m_typeinfo.GetCount() - 1;
3037 }
3038
3039 return index;
3040}
3041
3042int wxGridTypeRegistry::FindOrCloneDataType(const wxString& typeName)
3043{
3044 int index = FindDataType(typeName);
3045 if ( index == wxNOT_FOUND )
3046 {
3047 // the first part of the typename is the "real" type, anything after ':'
3048 // are the parameters for the renderer
3049 index = FindDataType(typeName.BeforeFirst(_T(':')));
3050 if ( index == wxNOT_FOUND )
3051 {
3052 return wxNOT_FOUND;
3053 }
3054
3055 wxGridCellRenderer *renderer = GetRenderer(index);
3056 wxGridCellRenderer *rendererOld = renderer;
3057 renderer = renderer->Clone();
3058 rendererOld->DecRef();
3059
3060 wxGridCellEditor *editor = GetEditor(index);
3061 wxGridCellEditor *editorOld = editor;
3062 editor = editor->Clone();
3063 editorOld->DecRef();
3064
3065 // do it even if there are no parameters to reset them to defaults
3066 wxString params = typeName.AfterFirst(_T(':'));
3067 renderer->SetParameters(params);
3068 editor->SetParameters(params);
3069
3070 // register the new typename
3071 RegisterDataType(typeName, renderer, editor);
3072
3073 // we just registered it, it's the last one
3074 index = m_typeinfo.GetCount() - 1;
3075 }
3076
3077 return index;
3078}
3079
3080wxGridCellRenderer* wxGridTypeRegistry::GetRenderer(int index)
3081{
3082 wxGridCellRenderer* renderer = m_typeinfo[index]->m_renderer;
3083 if (renderer)
3084 renderer->IncRef();
3085
3086 return renderer;
3087}
3088
3089wxGridCellEditor* wxGridTypeRegistry::GetEditor(int index)
3090{
3091 wxGridCellEditor* editor = m_typeinfo[index]->m_editor;
3092 if (editor)
3093 editor->IncRef();
3094
3095 return editor;
3096}
3097
3098// ----------------------------------------------------------------------------
3099// wxGridTableBase
3100// ----------------------------------------------------------------------------
3101
3102IMPLEMENT_ABSTRACT_CLASS( wxGridTableBase, wxObject )
3103
3104wxGridTableBase::wxGridTableBase()
3105{
3106 m_view = (wxGrid *) NULL;
3107 m_attrProvider = (wxGridCellAttrProvider *) NULL;
3108}
3109
3110wxGridTableBase::~wxGridTableBase()
3111{
3112 delete m_attrProvider;
3113}
3114
3115void wxGridTableBase::SetAttrProvider(wxGridCellAttrProvider *attrProvider)
3116{
3117 delete m_attrProvider;
3118 m_attrProvider = attrProvider;
3119}
3120
3121bool wxGridTableBase::CanHaveAttributes()
3122{
3123 if ( ! GetAttrProvider() )
3124 {
3125 // use the default attr provider by default
3126 SetAttrProvider(new wxGridCellAttrProvider);
3127 }
3128
3129 return true;
3130}
3131
3132wxGridCellAttr *wxGridTableBase::GetAttr(int row, int col, wxGridCellAttr::wxAttrKind kind)
3133{
3134 if ( m_attrProvider )
3135 return m_attrProvider->GetAttr(row, col, kind);
3136 else
3137 return (wxGridCellAttr *)NULL;
3138}
3139
3140void wxGridTableBase::SetAttr(wxGridCellAttr* attr, int row, int col)
3141{
3142 if ( m_attrProvider )
3143 {
3144 attr->SetKind(wxGridCellAttr::Cell);
3145 m_attrProvider->SetAttr(attr, row, col);
3146 }
3147 else
3148 {
3149 // as we take ownership of the pointer and don't store it, we must
3150 // free it now
3151 wxSafeDecRef(attr);
3152 }
3153}
3154
3155void wxGridTableBase::SetRowAttr(wxGridCellAttr *attr, int row)
3156{
3157 if ( m_attrProvider )
3158 {
3159 attr->SetKind(wxGridCellAttr::Row);
3160 m_attrProvider->SetRowAttr(attr, row);
3161 }
3162 else
3163 {
3164 // as we take ownership of the pointer and don't store it, we must
3165 // free it now
3166 wxSafeDecRef(attr);
3167 }
3168}
3169
3170void wxGridTableBase::SetColAttr(wxGridCellAttr *attr, int col)
3171{
3172 if ( m_attrProvider )
3173 {
3174 attr->SetKind(wxGridCellAttr::Col);
3175 m_attrProvider->SetColAttr(attr, col);
3176 }
3177 else
3178 {
3179 // as we take ownership of the pointer and don't store it, we must
3180 // free it now
3181 wxSafeDecRef(attr);
3182 }
3183}
3184
3185bool wxGridTableBase::InsertRows( size_t WXUNUSED(pos),
3186 size_t WXUNUSED(numRows) )
3187{
3188 wxFAIL_MSG( wxT("Called grid table class function InsertRows\nbut your derived table class does not override this function") );
3189
3190 return false;
3191}
3192
3193bool wxGridTableBase::AppendRows( size_t WXUNUSED(numRows) )
3194{
3195 wxFAIL_MSG( wxT("Called grid table class function AppendRows\nbut your derived table class does not override this function"));
3196
3197 return false;
3198}
3199
3200bool wxGridTableBase::DeleteRows( size_t WXUNUSED(pos),
3201 size_t WXUNUSED(numRows) )
3202{
3203 wxFAIL_MSG( wxT("Called grid table class function DeleteRows\nbut your derived table class does not override this function"));
3204
3205 return false;
3206}
3207
3208bool wxGridTableBase::InsertCols( size_t WXUNUSED(pos),
3209 size_t WXUNUSED(numCols) )
3210{
3211 wxFAIL_MSG( wxT("Called grid table class function InsertCols\nbut your derived table class does not override this function"));
3212
3213 return false;
3214}
3215
3216bool wxGridTableBase::AppendCols( size_t WXUNUSED(numCols) )
3217{
3218 wxFAIL_MSG(wxT("Called grid table class function AppendCols\nbut your derived table class does not override this function"));
3219
3220 return false;
3221}
3222
3223bool wxGridTableBase::DeleteCols( size_t WXUNUSED(pos),
3224 size_t WXUNUSED(numCols) )
3225{
3226 wxFAIL_MSG( wxT("Called grid table class function DeleteCols\nbut your derived table class does not override this function"));
3227
3228 return false;
3229}
3230
3231wxString wxGridTableBase::GetRowLabelValue( int row )
3232{
3233 wxString s;
3234
3235 // RD: Starting the rows at zero confuses users,
3236 // no matter how much it makes sense to us geeks.
3237 s << row + 1;
3238
3239 return s;
3240}
3241
3242wxString wxGridTableBase::GetColLabelValue( int col )
3243{
3244 // default col labels are:
3245 // cols 0 to 25 : A-Z
3246 // cols 26 to 675 : AA-ZZ
3247 // etc.
3248
3249 wxString s;
3250 unsigned int i, n;
3251 for ( n = 1; ; n++ )
3252 {
3253 s += (wxChar) (_T('A') + (wxChar)(col % 26));
3254 col = col / 26 - 1;
3255 if ( col < 0 )
3256 break;
3257 }
3258
3259 // reverse the string...
3260 wxString s2;
3261 for ( i = 0; i < n; i++ )
3262 {
3263 s2 += s[n - i - 1];
3264 }
3265
3266 return s2;
3267}
3268
3269wxString wxGridTableBase::GetTypeName( int WXUNUSED(row), int WXUNUSED(col) )
3270{
3271 return wxGRID_VALUE_STRING;
3272}
3273
3274bool wxGridTableBase::CanGetValueAs( int WXUNUSED(row), int WXUNUSED(col),
3275 const wxString& typeName )
3276{
3277 return typeName == wxGRID_VALUE_STRING;
3278}
3279
3280bool wxGridTableBase::CanSetValueAs( int row, int col, const wxString& typeName )
3281{
3282 return CanGetValueAs(row, col, typeName);
3283}
3284
3285long wxGridTableBase::GetValueAsLong( int WXUNUSED(row), int WXUNUSED(col) )
3286{
3287 return 0;
3288}
3289
3290double wxGridTableBase::GetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col) )
3291{
3292 return 0.0;
3293}
3294
3295bool wxGridTableBase::GetValueAsBool( int WXUNUSED(row), int WXUNUSED(col) )
3296{
3297 return false;
3298}
3299
3300void wxGridTableBase::SetValueAsLong( int WXUNUSED(row), int WXUNUSED(col),
3301 long WXUNUSED(value) )
3302{
3303}
3304
3305void wxGridTableBase::SetValueAsDouble( int WXUNUSED(row), int WXUNUSED(col),
3306 double WXUNUSED(value) )
3307{
3308}
3309
3310void wxGridTableBase::SetValueAsBool( int WXUNUSED(row), int WXUNUSED(col),
3311 bool WXUNUSED(value) )
3312{
3313}
3314
3315void* wxGridTableBase::GetValueAsCustom( int WXUNUSED(row), int WXUNUSED(col),
3316 const wxString& WXUNUSED(typeName) )
3317{
3318 return NULL;
3319}
3320
3321void wxGridTableBase::SetValueAsCustom( int WXUNUSED(row), int WXUNUSED(col),
3322 const wxString& WXUNUSED(typeName),
3323 void* WXUNUSED(value) )
3324{
3325}
3326
3327//////////////////////////////////////////////////////////////////////
3328//
3329// Message class for the grid table to send requests and notifications
3330// to the grid view
3331//
3332
3333wxGridTableMessage::wxGridTableMessage()
3334{
3335 m_table = (wxGridTableBase *) NULL;
3336 m_id = -1;
3337 m_comInt1 = -1;
3338 m_comInt2 = -1;
3339}
3340
3341wxGridTableMessage::wxGridTableMessage( wxGridTableBase *table, int id,
3342 int commandInt1, int commandInt2 )
3343{
3344 m_table = table;
3345 m_id = id;
3346 m_comInt1 = commandInt1;
3347 m_comInt2 = commandInt2;
3348}
3349
3350//////////////////////////////////////////////////////////////////////
3351//
3352// A basic grid table for string data. An object of this class will
3353// created by wxGrid if you don't specify an alternative table class.
3354//
3355
3356WX_DEFINE_OBJARRAY(wxGridStringArray)
3357
3358IMPLEMENT_DYNAMIC_CLASS( wxGridStringTable, wxGridTableBase )
3359
3360wxGridStringTable::wxGridStringTable()
3361 : wxGridTableBase()
3362{
3363}
3364
3365wxGridStringTable::wxGridStringTable( int numRows, int numCols )
3366 : wxGridTableBase()
3367{
3368 m_data.Alloc( numRows );
3369
3370 wxArrayString sa;
3371 sa.Alloc( numCols );
3372 sa.Add( wxEmptyString, numCols );
3373
3374 m_data.Add( sa, numRows );
3375}
3376
3377wxGridStringTable::~wxGridStringTable()
3378{
3379}
3380
3381int wxGridStringTable::GetNumberRows()
3382{
3383 return m_data.GetCount();
3384}
3385
3386int wxGridStringTable::GetNumberCols()
3387{
3388 if ( m_data.GetCount() > 0 )
3389 return m_data[0].GetCount();
3390 else
3391 return 0;
3392}
3393
3394wxString wxGridStringTable::GetValue( int row, int col )
3395{
3396 wxCHECK_MSG( (row < GetNumberRows()) && (col < GetNumberCols()),
3397 wxEmptyString,
3398 _T("invalid row or column index in wxGridStringTable") );
3399
3400 return m_data[row][col];
3401}
3402
3403void wxGridStringTable::SetValue( int row, int col, const wxString& value )
3404{
3405 wxCHECK_RET( (row < GetNumberRows()) && (col < GetNumberCols()),
3406 _T("invalid row or column index in wxGridStringTable") );
3407
3408 m_data[row][col] = value;
3409}
3410
3411bool wxGridStringTable::IsEmptyCell( int row, int col )
3412{
3413 wxCHECK_MSG( (row < GetNumberRows()) && (col < GetNumberCols()),
3414 true,
3415 _T("invalid row or column index in wxGridStringTable") );
3416
3417 return (m_data[row][col] == wxEmptyString);
3418}
3419
3420void wxGridStringTable::Clear()
3421{
3422 int row, col;
3423 int numRows, numCols;
3424
3425 numRows = m_data.GetCount();
3426 if ( numRows > 0 )
3427 {
3428 numCols = m_data[0].GetCount();
3429
3430 for ( row = 0; row < numRows; row++ )
3431 {
3432 for ( col = 0; col < numCols; col++ )
3433 {
3434 m_data[row][col] = wxEmptyString;
3435 }
3436 }
3437 }
3438}
3439
3440bool wxGridStringTable::InsertRows( size_t pos, size_t numRows )
3441{
3442 size_t curNumRows = m_data.GetCount();
3443 size_t curNumCols = ( curNumRows > 0 ? m_data[0].GetCount() :
3444 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
3445
3446 if ( pos >= curNumRows )
3447 {
3448 return AppendRows( numRows );
3449 }
3450
3451 wxArrayString sa;
3452 sa.Alloc( curNumCols );
3453 sa.Add( wxEmptyString, curNumCols );
3454 m_data.Insert( sa, pos, numRows );
3455
3456 if ( GetView() )
3457 {
3458 wxGridTableMessage msg( this,
3459 wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
3460 pos,
3461 numRows );
3462
3463 GetView()->ProcessTableMessage( msg );
3464 }
3465
3466 return true;
3467}
3468
3469bool wxGridStringTable::AppendRows( size_t numRows )
3470{
3471 size_t curNumRows = m_data.GetCount();
3472 size_t curNumCols = ( curNumRows > 0
3473 ? m_data[0].GetCount()
3474 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
3475
3476 wxArrayString sa;
3477 if ( curNumCols > 0 )
3478 {
3479 sa.Alloc( curNumCols );
3480 sa.Add( wxEmptyString, curNumCols );
3481 }
3482
3483 m_data.Add( sa, numRows );
3484
3485 if ( GetView() )
3486 {
3487 wxGridTableMessage msg( this,
3488 wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
3489 numRows );
3490
3491 GetView()->ProcessTableMessage( msg );
3492 }
3493
3494 return true;
3495}
3496
3497bool wxGridStringTable::DeleteRows( size_t pos, size_t numRows )
3498{
3499 size_t curNumRows = m_data.GetCount();
3500
3501 if ( pos >= curNumRows )
3502 {
3503 wxFAIL_MSG( wxString::Format
3504 (
3505 wxT("Called wxGridStringTable::DeleteRows(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu rows"),
3506 (unsigned long)pos,
3507 (unsigned long)numRows,
3508 (unsigned long)curNumRows
3509 ) );
3510
3511 return false;
3512 }
3513
3514 if ( numRows > curNumRows - pos )
3515 {
3516 numRows = curNumRows - pos;
3517 }
3518
3519 if ( numRows >= curNumRows )
3520 {
3521 m_data.Clear();
3522 }
3523 else
3524 {
3525 m_data.RemoveAt( pos, numRows );
3526 }
3527
3528 if ( GetView() )
3529 {
3530 wxGridTableMessage msg( this,
3531 wxGRIDTABLE_NOTIFY_ROWS_DELETED,
3532 pos,
3533 numRows );
3534
3535 GetView()->ProcessTableMessage( msg );
3536 }
3537
3538 return true;
3539}
3540
3541bool wxGridStringTable::InsertCols( size_t pos, size_t numCols )
3542{
3543 size_t row, col;
3544
3545 size_t curNumRows = m_data.GetCount();
3546 size_t curNumCols = ( curNumRows > 0
3547 ? m_data[0].GetCount()
3548 : ( GetView() ? GetView()->GetNumberCols() : 0 ) );
3549
3550 if ( pos >= curNumCols )
3551 {
3552 return AppendCols( numCols );
3553 }
3554
3555 if ( !m_colLabels.IsEmpty() )
3556 {
3557 m_colLabels.Insert( wxEmptyString, pos, numCols );
3558
3559 size_t i;
3560 for ( i = pos; i < pos + numCols; i++ )
3561 m_colLabels[i] = wxGridTableBase::GetColLabelValue( i );
3562 }
3563
3564 for ( row = 0; row < curNumRows; row++ )
3565 {
3566 for ( col = pos; col < pos + numCols; col++ )
3567 {
3568 m_data[row].Insert( wxEmptyString, col );
3569 }
3570 }
3571
3572 if ( GetView() )
3573 {
3574 wxGridTableMessage msg( this,
3575 wxGRIDTABLE_NOTIFY_COLS_INSERTED,
3576 pos,
3577 numCols );
3578
3579 GetView()->ProcessTableMessage( msg );
3580 }
3581
3582 return true;
3583}
3584
3585bool wxGridStringTable::AppendCols( size_t numCols )
3586{
3587 size_t row;
3588
3589 size_t curNumRows = m_data.GetCount();
3590
3591#if 0
3592 if ( !curNumRows )
3593 {
3594 // TODO: something better than this ?
3595 //
3596 wxFAIL_MSG( wxT("Unable to append cols to a grid table with no rows.\nCall AppendRows() first") );
3597 return false;
3598 }
3599#endif
3600
3601 for ( row = 0; row < curNumRows; row++ )
3602 {
3603 m_data[row].Add( wxEmptyString, numCols );
3604 }
3605
3606 if ( GetView() )
3607 {
3608 wxGridTableMessage msg( this,
3609 wxGRIDTABLE_NOTIFY_COLS_APPENDED,
3610 numCols );
3611
3612 GetView()->ProcessTableMessage( msg );
3613 }
3614
3615 return true;
3616}
3617
3618bool wxGridStringTable::DeleteCols( size_t pos, size_t numCols )
3619{
3620 size_t row;
3621
3622 size_t curNumRows = m_data.GetCount();
3623 size_t curNumCols = ( curNumRows > 0 ? m_data[0].GetCount() :
3624 ( GetView() ? GetView()->GetNumberCols() : 0 ) );
3625
3626 if ( pos >= curNumCols )
3627 {
3628 wxFAIL_MSG( wxString::Format
3629 (
3630 wxT("Called wxGridStringTable::DeleteCols(pos=%lu, N=%lu)\nPos value is invalid for present table with %lu cols"),
3631 (unsigned long)pos,
3632 (unsigned long)numCols,
3633 (unsigned long)curNumCols
3634 ) );
3635 return false;
3636 }
3637
3638 int colID;
3639 if ( GetView() )
3640 colID = GetView()->GetColAt( pos );
3641 else
3642 colID = pos;
3643
3644 if ( numCols > curNumCols - colID )
3645 {
3646 numCols = curNumCols - colID;
3647 }
3648
3649 if ( !m_colLabels.IsEmpty() )
3650 {
3651 m_colLabels.RemoveAt( colID, numCols );
3652 }
3653
3654 for ( row = 0; row < curNumRows; row++ )
3655 {
3656 if ( numCols >= curNumCols )
3657 {
3658 m_data[row].Clear();
3659 }
3660 else
3661 {
3662 m_data[row].RemoveAt( colID, numCols );
3663 }
3664 }
3665
3666 if ( GetView() )
3667 {
3668 wxGridTableMessage msg( this,
3669 wxGRIDTABLE_NOTIFY_COLS_DELETED,
3670 pos,
3671 numCols );
3672
3673 GetView()->ProcessTableMessage( msg );
3674 }
3675
3676 return true;
3677}
3678
3679wxString wxGridStringTable::GetRowLabelValue( int row )
3680{
3681 if ( row > (int)(m_rowLabels.GetCount()) - 1 )
3682 {
3683 // using default label
3684 //
3685 return wxGridTableBase::GetRowLabelValue( row );
3686 }
3687 else
3688 {
3689 return m_rowLabels[row];
3690 }
3691}
3692
3693wxString wxGridStringTable::GetColLabelValue( int col )
3694{
3695 if ( col > (int)(m_colLabels.GetCount()) - 1 )
3696 {
3697 // using default label
3698 //
3699 return wxGridTableBase::GetColLabelValue( col );
3700 }
3701 else
3702 {
3703 return m_colLabels[col];
3704 }
3705}
3706
3707void wxGridStringTable::SetRowLabelValue( int row, const wxString& value )
3708{
3709 if ( row > (int)(m_rowLabels.GetCount()) - 1 )
3710 {
3711 int n = m_rowLabels.GetCount();
3712 int i;
3713
3714 for ( i = n; i <= row; i++ )
3715 {
3716 m_rowLabels.Add( wxGridTableBase::GetRowLabelValue(i) );
3717 }
3718 }
3719
3720 m_rowLabels[row] = value;
3721}
3722
3723void wxGridStringTable::SetColLabelValue( int col, const wxString& value )
3724{
3725 if ( col > (int)(m_colLabels.GetCount()) - 1 )
3726 {
3727 int n = m_colLabels.GetCount();
3728 int i;
3729
3730 for ( i = n; i <= col; i++ )
3731 {
3732 m_colLabels.Add( wxGridTableBase::GetColLabelValue(i) );
3733 }
3734 }
3735
3736 m_colLabels[col] = value;
3737}
3738
3739
3740//////////////////////////////////////////////////////////////////////
3741//////////////////////////////////////////////////////////////////////
3742
3743IMPLEMENT_DYNAMIC_CLASS( wxGridRowLabelWindow, wxWindow )
3744
3745BEGIN_EVENT_TABLE( wxGridRowLabelWindow, wxWindow )
3746 EVT_PAINT( wxGridRowLabelWindow::OnPaint )
3747 EVT_MOUSEWHEEL( wxGridRowLabelWindow::OnMouseWheel )
3748 EVT_MOUSE_EVENTS( wxGridRowLabelWindow::OnMouseEvent )
3749 EVT_KEY_DOWN( wxGridRowLabelWindow::OnKeyDown )
3750 EVT_KEY_UP( wxGridRowLabelWindow::OnKeyUp )
3751 EVT_CHAR( wxGridRowLabelWindow::OnChar )
3752END_EVENT_TABLE()
3753
3754wxGridRowLabelWindow::wxGridRowLabelWindow( wxGrid *parent,
3755 wxWindowID id,
3756 const wxPoint &pos, const wxSize &size )
3757 : wxWindow( parent, id, pos, size, wxWANTS_CHARS | wxBORDER_NONE | wxFULL_REPAINT_ON_RESIZE )
3758{
3759 m_owner = parent;
3760}
3761
3762void wxGridRowLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
3763{
3764 wxPaintDC dc(this);
3765
3766 // NO - don't do this because it will set both the x and y origin
3767 // coords to match the parent scrolled window and we just want to
3768 // set the y coord - MB
3769 //
3770 // m_owner->PrepareDC( dc );
3771
3772 int x, y;
3773 m_owner->CalcUnscrolledPosition( 0, 0, &x, &y );
3774 wxPoint pt = dc.GetDeviceOrigin();
3775 dc.SetDeviceOrigin( pt.x, pt.y-y );
3776
3777 wxArrayInt rows = m_owner->CalcRowLabelsExposed( GetUpdateRegion() );
3778 m_owner->DrawRowLabels( dc, rows );
3779}
3780
3781void wxGridRowLabelWindow::OnMouseEvent( wxMouseEvent& event )
3782{
3783 m_owner->ProcessRowLabelMouseEvent( event );
3784}
3785
3786void wxGridRowLabelWindow::OnMouseWheel( wxMouseEvent& event )
3787{
3788 m_owner->GetEventHandler()->ProcessEvent( event );
3789}
3790
3791// This seems to be required for wxMotif otherwise the mouse
3792// cursor must be in the cell edit control to get key events
3793//
3794void wxGridRowLabelWindow::OnKeyDown( wxKeyEvent& event )
3795{
3796 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3797 event.Skip();
3798}
3799
3800void wxGridRowLabelWindow::OnKeyUp( wxKeyEvent& event )
3801{
3802 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3803 event.Skip();
3804}
3805
3806void wxGridRowLabelWindow::OnChar( wxKeyEvent& event )
3807{
3808 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3809 event.Skip();
3810}
3811
3812//////////////////////////////////////////////////////////////////////
3813
3814IMPLEMENT_DYNAMIC_CLASS( wxGridColLabelWindow, wxWindow )
3815
3816BEGIN_EVENT_TABLE( wxGridColLabelWindow, wxWindow )
3817 EVT_PAINT( wxGridColLabelWindow::OnPaint )
3818 EVT_MOUSEWHEEL( wxGridColLabelWindow::OnMouseWheel )
3819 EVT_MOUSE_EVENTS( wxGridColLabelWindow::OnMouseEvent )
3820 EVT_KEY_DOWN( wxGridColLabelWindow::OnKeyDown )
3821 EVT_KEY_UP( wxGridColLabelWindow::OnKeyUp )
3822 EVT_CHAR( wxGridColLabelWindow::OnChar )
3823END_EVENT_TABLE()
3824
3825wxGridColLabelWindow::wxGridColLabelWindow( wxGrid *parent,
3826 wxWindowID id,
3827 const wxPoint &pos, const wxSize &size )
3828 : wxWindow( parent, id, pos, size, wxWANTS_CHARS | wxBORDER_NONE | wxFULL_REPAINT_ON_RESIZE )
3829{
3830 m_owner = parent;
3831}
3832
3833void wxGridColLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
3834{
3835 wxPaintDC dc(this);
3836
3837 // NO - don't do this because it will set both the x and y origin
3838 // coords to match the parent scrolled window and we just want to
3839 // set the x coord - MB
3840 //
3841 // m_owner->PrepareDC( dc );
3842
3843 int x, y;
3844 m_owner->CalcUnscrolledPosition( 0, 0, &x, &y );
3845 wxPoint pt = dc.GetDeviceOrigin();
3846 if (GetLayoutDirection() == wxLayout_RightToLeft)
3847 dc.SetDeviceOrigin( pt.x+x, pt.y );
3848 else
3849 dc.SetDeviceOrigin( pt.x-x, pt.y );
3850
3851 wxArrayInt cols = m_owner->CalcColLabelsExposed( GetUpdateRegion() );
3852 m_owner->DrawColLabels( dc, cols );
3853}
3854
3855void wxGridColLabelWindow::OnMouseEvent( wxMouseEvent& event )
3856{
3857 m_owner->ProcessColLabelMouseEvent( event );
3858}
3859
3860void wxGridColLabelWindow::OnMouseWheel( wxMouseEvent& event )
3861{
3862 m_owner->GetEventHandler()->ProcessEvent( event );
3863}
3864
3865// This seems to be required for wxMotif otherwise the mouse
3866// cursor must be in the cell edit control to get key events
3867//
3868void wxGridColLabelWindow::OnKeyDown( wxKeyEvent& event )
3869{
3870 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3871 event.Skip();
3872}
3873
3874void wxGridColLabelWindow::OnKeyUp( wxKeyEvent& event )
3875{
3876 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3877 event.Skip();
3878}
3879
3880void wxGridColLabelWindow::OnChar( wxKeyEvent& event )
3881{
3882 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3883 event.Skip();
3884}
3885
3886//////////////////////////////////////////////////////////////////////
3887
3888IMPLEMENT_DYNAMIC_CLASS( wxGridCornerLabelWindow, wxWindow )
3889
3890BEGIN_EVENT_TABLE( wxGridCornerLabelWindow, wxWindow )
3891 EVT_MOUSEWHEEL( wxGridCornerLabelWindow::OnMouseWheel )
3892 EVT_MOUSE_EVENTS( wxGridCornerLabelWindow::OnMouseEvent )
3893 EVT_PAINT( wxGridCornerLabelWindow::OnPaint )
3894 EVT_KEY_DOWN( wxGridCornerLabelWindow::OnKeyDown )
3895 EVT_KEY_UP( wxGridCornerLabelWindow::OnKeyUp )
3896 EVT_CHAR( wxGridCornerLabelWindow::OnChar )
3897END_EVENT_TABLE()
3898
3899wxGridCornerLabelWindow::wxGridCornerLabelWindow( wxGrid *parent,
3900 wxWindowID id,
3901 const wxPoint &pos, const wxSize &size )
3902 : wxWindow( parent, id, pos, size, wxWANTS_CHARS | wxBORDER_NONE | wxFULL_REPAINT_ON_RESIZE )
3903{
3904 m_owner = parent;
3905}
3906
3907void wxGridCornerLabelWindow::OnPaint( wxPaintEvent& WXUNUSED(event) )
3908{
3909 wxPaintDC dc(this);
3910
3911 int client_height = 0;
3912 int client_width = 0;
3913 GetClientSize( &client_width, &client_height );
3914
3915 // VZ: any reason for this ifdef? (FIXME)
3916#if 0
3917def __WXGTK__
3918 wxRect rect;
3919 rect.SetX( 1 );
3920 rect.SetY( 1 );
3921 rect.SetWidth( client_width - 2 );
3922 rect.SetHeight( client_height - 2 );
3923
3924 wxRendererNative::Get().DrawHeaderButton( this, dc, rect, 0 );
3925#else // !__WXGTK__
3926 dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW), 1, wxSOLID) );
3927 dc.DrawLine( client_width - 1, client_height - 1, client_width - 1, 0 );
3928 dc.DrawLine( client_width - 1, client_height - 1, 0, client_height - 1 );
3929 dc.DrawLine( 0, 0, client_width, 0 );
3930 dc.DrawLine( 0, 0, 0, client_height );
3931
3932 dc.SetPen( *wxWHITE_PEN );
3933 dc.DrawLine( 1, 1, client_width - 1, 1 );
3934 dc.DrawLine( 1, 1, 1, client_height - 1 );
3935#endif
3936}
3937
3938void wxGridCornerLabelWindow::OnMouseEvent( wxMouseEvent& event )
3939{
3940 m_owner->ProcessCornerLabelMouseEvent( event );
3941}
3942
3943void wxGridCornerLabelWindow::OnMouseWheel( wxMouseEvent& event )
3944{
3945 m_owner->GetEventHandler()->ProcessEvent(event);
3946}
3947
3948// This seems to be required for wxMotif otherwise the mouse
3949// cursor must be in the cell edit control to get key events
3950//
3951void wxGridCornerLabelWindow::OnKeyDown( wxKeyEvent& event )
3952{
3953 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3954 event.Skip();
3955}
3956
3957void wxGridCornerLabelWindow::OnKeyUp( wxKeyEvent& event )
3958{
3959 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3960 event.Skip();
3961}
3962
3963void wxGridCornerLabelWindow::OnChar( wxKeyEvent& event )
3964{
3965 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
3966 event.Skip();
3967}
3968
3969//////////////////////////////////////////////////////////////////////
3970
3971IMPLEMENT_DYNAMIC_CLASS( wxGridWindow, wxWindow )
3972
3973BEGIN_EVENT_TABLE( wxGridWindow, wxWindow )
3974 EVT_PAINT( wxGridWindow::OnPaint )
3975 EVT_MOUSEWHEEL( wxGridWindow::OnMouseWheel )
3976 EVT_MOUSE_EVENTS( wxGridWindow::OnMouseEvent )
3977 EVT_KEY_DOWN( wxGridWindow::OnKeyDown )
3978 EVT_KEY_UP( wxGridWindow::OnKeyUp )
3979 EVT_CHAR( wxGridWindow::OnChar )
3980 EVT_SET_FOCUS( wxGridWindow::OnFocus )
3981 EVT_KILL_FOCUS( wxGridWindow::OnFocus )
3982 EVT_ERASE_BACKGROUND( wxGridWindow::OnEraseBackground )
3983END_EVENT_TABLE()
3984
3985wxGridWindow::wxGridWindow( wxGrid *parent,
3986 wxGridRowLabelWindow *rowLblWin,
3987 wxGridColLabelWindow *colLblWin,
3988 wxWindowID id,
3989 const wxPoint &pos,
3990 const wxSize &size )
3991 : wxWindow(
3992 parent, id, pos, size,
3993 wxWANTS_CHARS | wxBORDER_NONE | wxCLIP_CHILDREN | wxFULL_REPAINT_ON_RESIZE,
3994 wxT("grid window") )
3995{
3996 m_owner = parent;
3997 m_rowLabelWin = rowLblWin;
3998 m_colLabelWin = colLblWin;
3999}
4000
4001void wxGridWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
4002{
4003 wxPaintDC dc( this );
4004 m_owner->PrepareDC( dc );
4005 wxRegion reg = GetUpdateRegion();
4006 wxGridCellCoordsArray dirtyCells = m_owner->CalcCellsExposed( reg );
4007 m_owner->DrawGridCellArea( dc, dirtyCells );
4008
4009#if WXGRID_DRAW_LINES
4010 m_owner->DrawAllGridLines( dc, reg );
4011#endif
4012
4013 m_owner->DrawGridSpace( dc );
4014 m_owner->DrawHighlight( dc, dirtyCells );
4015}
4016
4017void wxGridWindow::ScrollWindow( int dx, int dy, const wxRect *rect )
4018{
4019 wxWindow::ScrollWindow( dx, dy, rect );
4020 m_rowLabelWin->ScrollWindow( 0, dy, rect );
4021 m_colLabelWin->ScrollWindow( dx, 0, rect );
4022}
4023
4024void wxGridWindow::OnMouseEvent( wxMouseEvent& event )
4025{
4026 if (event.ButtonDown(wxMOUSE_BTN_LEFT) && FindFocus() != this)
4027 SetFocus();
4028
4029 m_owner->ProcessGridCellMouseEvent( event );
4030}
4031
4032void wxGridWindow::OnMouseWheel( wxMouseEvent& event )
4033{
4034 m_owner->GetEventHandler()->ProcessEvent( event );
4035}
4036
4037// This seems to be required for wxMotif/wxGTK otherwise the mouse
4038// cursor must be in the cell edit control to get key events
4039//
4040void wxGridWindow::OnKeyDown( wxKeyEvent& event )
4041{
4042 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4043 event.Skip();
4044}
4045
4046void wxGridWindow::OnKeyUp( wxKeyEvent& event )
4047{
4048 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4049 event.Skip();
4050}
4051
4052void wxGridWindow::OnChar( wxKeyEvent& event )
4053{
4054 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4055 event.Skip();
4056}
4057
4058void wxGridWindow::OnEraseBackground( wxEraseEvent& WXUNUSED(event) )
4059{
4060}
4061
4062void wxGridWindow::OnFocus(wxFocusEvent& event)
4063{
4064 if ( !m_owner->GetEventHandler()->ProcessEvent( event ) )
4065 event.Skip();
4066}
4067
4068//////////////////////////////////////////////////////////////////////
4069
4070// Internal Helper function for computing row or column from some
4071// (unscrolled) coordinate value, using either
4072// m_defaultRowHeight/m_defaultColWidth or binary search on array
4073// of m_rowBottoms/m_ColRights to speed up the search!
4074
4075// Internal helper macros for simpler use of that function
4076
4077static int CoordToRowOrCol(int coord, int defaultDist, int minDist,
4078 const wxArrayInt& BorderArray, int nMax,
4079 bool clipToMinMax);
4080
4081#define internalXToCol(x) XToCol(x, true)
4082#define internalYToRow(y) CoordToRowOrCol(y, m_defaultRowHeight, \
4083 m_minAcceptableRowHeight, \
4084 m_rowBottoms, m_numRows, true)
4085
4086/////////////////////////////////////////////////////////////////////
4087
4088#if wxUSE_EXTENDED_RTTI
4089WX_DEFINE_FLAGS( wxGridStyle )
4090
4091wxBEGIN_FLAGS( wxGridStyle )
4092 // new style border flags, we put them first to
4093 // use them for streaming out
4094 wxFLAGS_MEMBER(wxBORDER_SIMPLE)
4095 wxFLAGS_MEMBER(wxBORDER_SUNKEN)
4096 wxFLAGS_MEMBER(wxBORDER_DOUBLE)
4097 wxFLAGS_MEMBER(wxBORDER_RAISED)
4098 wxFLAGS_MEMBER(wxBORDER_STATIC)
4099 wxFLAGS_MEMBER(wxBORDER_NONE)
4100
4101 // old style border flags
4102 wxFLAGS_MEMBER(wxSIMPLE_BORDER)
4103 wxFLAGS_MEMBER(wxSUNKEN_BORDER)
4104 wxFLAGS_MEMBER(wxDOUBLE_BORDER)
4105 wxFLAGS_MEMBER(wxRAISED_BORDER)
4106 wxFLAGS_MEMBER(wxSTATIC_BORDER)
4107 wxFLAGS_MEMBER(wxBORDER)
4108
4109 // standard window styles
4110 wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
4111 wxFLAGS_MEMBER(wxCLIP_CHILDREN)
4112 wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
4113 wxFLAGS_MEMBER(wxWANTS_CHARS)
4114 wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
4115 wxFLAGS_MEMBER(wxALWAYS_SHOW_SB)
4116 wxFLAGS_MEMBER(wxVSCROLL)
4117 wxFLAGS_MEMBER(wxHSCROLL)
4118
4119wxEND_FLAGS( wxGridStyle )
4120
4121IMPLEMENT_DYNAMIC_CLASS_XTI(wxGrid, wxScrolledWindow,"wx/grid.h")
4122
4123wxBEGIN_PROPERTIES_TABLE(wxGrid)
4124 wxHIDE_PROPERTY( Children )
4125 wxPROPERTY_FLAGS( WindowStyle , wxGridStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
4126wxEND_PROPERTIES_TABLE()
4127
4128wxBEGIN_HANDLERS_TABLE(wxGrid)
4129wxEND_HANDLERS_TABLE()
4130
4131wxCONSTRUCTOR_5( wxGrid , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size , long , WindowStyle )
4132
4133/*
4134 TODO : Expose more information of a list's layout, etc. via appropriate objects (e.g., NotebookPageInfo)
4135*/
4136#else
4137IMPLEMENT_DYNAMIC_CLASS( wxGrid, wxScrolledWindow )
4138#endif
4139
4140BEGIN_EVENT_TABLE( wxGrid, wxScrolledWindow )
4141 EVT_PAINT( wxGrid::OnPaint )
4142 EVT_SIZE( wxGrid::OnSize )
4143 EVT_KEY_DOWN( wxGrid::OnKeyDown )
4144 EVT_KEY_UP( wxGrid::OnKeyUp )
4145 EVT_CHAR ( wxGrid::OnChar )
4146 EVT_ERASE_BACKGROUND( wxGrid::OnEraseBackground )
4147END_EVENT_TABLE()
4148
4149wxGrid::wxGrid()
4150{
4151 // in order to make sure that a size event is not
4152 // trigerred in a unfinished state
4153 m_cornerLabelWin = NULL;
4154 m_rowLabelWin = NULL;
4155 m_colLabelWin = NULL;
4156 m_gridWin = NULL;
4157}
4158
4159wxGrid::wxGrid( wxWindow *parent,
4160 wxWindowID id,
4161 const wxPoint& pos,
4162 const wxSize& size,
4163 long style,
4164 const wxString& name )
4165 : wxScrolledWindow( parent, id, pos, size, (style | wxWANTS_CHARS), name ),
4166 m_colMinWidths(GRID_HASH_SIZE),
4167 m_rowMinHeights(GRID_HASH_SIZE)
4168{
4169 Create();
4170 SetInitialSize(size);
4171}
4172
4173bool wxGrid::Create(wxWindow *parent, wxWindowID id,
4174 const wxPoint& pos, const wxSize& size,
4175 long style, const wxString& name)
4176{
4177 if (!wxScrolledWindow::Create(parent, id, pos, size,
4178 style | wxWANTS_CHARS, name))
4179 return false;
4180
4181 m_colMinWidths = wxLongToLongHashMap(GRID_HASH_SIZE);
4182 m_rowMinHeights = wxLongToLongHashMap(GRID_HASH_SIZE);
4183
4184 Create();
4185 SetInitialSize(size);
4186
4187 return true;
4188}
4189
4190wxGrid::~wxGrid()
4191{
4192 // Must do this or ~wxScrollHelper will pop the wrong event handler
4193 SetTargetWindow(this);
4194 ClearAttrCache();
4195 wxSafeDecRef(m_defaultCellAttr);
4196
4197#ifdef DEBUG_ATTR_CACHE
4198 size_t total = gs_nAttrCacheHits + gs_nAttrCacheMisses;
4199 wxPrintf(_T("wxGrid attribute cache statistics: "
4200 "total: %u, hits: %u (%u%%)\n"),
4201 total, gs_nAttrCacheHits,
4202 total ? (gs_nAttrCacheHits*100) / total : 0);
4203#endif
4204
4205 // if we own the table, just delete it, otherwise at least don't leave it
4206 // with dangling view pointer
4207 if ( m_ownTable )
4208 delete m_table;
4209 else if ( m_table && m_table->GetView() == this )
4210 m_table->SetView(NULL);
4211
4212 delete m_typeRegistry;
4213 delete m_selection;
4214}
4215
4216//
4217// ----- internal init and update functions
4218//
4219
4220// NOTE: If using the default visual attributes works everywhere then this can
4221// be removed as well as the #else cases below.
4222#define _USE_VISATTR 0
4223
4224void wxGrid::Create()
4225{
4226 // set to true by CreateGrid
4227 m_created = false;
4228
4229 // create the type registry
4230 m_typeRegistry = new wxGridTypeRegistry;
4231 m_selection = NULL;
4232
4233 m_table = (wxGridTableBase *) NULL;
4234 m_ownTable = false;
4235
4236 m_cellEditCtrlEnabled = false;
4237
4238 m_defaultCellAttr = new wxGridCellAttr();
4239
4240 // Set default cell attributes
4241 m_defaultCellAttr->SetDefAttr(m_defaultCellAttr);
4242 m_defaultCellAttr->SetKind(wxGridCellAttr::Default);
4243 m_defaultCellAttr->SetFont(GetFont());
4244 m_defaultCellAttr->SetAlignment(wxALIGN_LEFT, wxALIGN_TOP);
4245 m_defaultCellAttr->SetRenderer(new wxGridCellStringRenderer);
4246 m_defaultCellAttr->SetEditor(new wxGridCellTextEditor);
4247
4248#if _USE_VISATTR
4249 wxVisualAttributes gva = wxListBox::GetClassDefaultAttributes();
4250 wxVisualAttributes lva = wxPanel::GetClassDefaultAttributes();
4251
4252 m_defaultCellAttr->SetTextColour(gva.colFg);
4253 m_defaultCellAttr->SetBackgroundColour(gva.colBg);
4254
4255#else
4256 m_defaultCellAttr->SetTextColour(
4257 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
4258 m_defaultCellAttr->SetBackgroundColour(
4259 wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW));
4260#endif
4261
4262 m_numRows = 0;
4263 m_numCols = 0;
4264 m_currentCellCoords = wxGridNoCellCoords;
4265
4266 m_rowLabelWidth = WXGRID_DEFAULT_ROW_LABEL_WIDTH;
4267 m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT;
4268
4269 // subwindow components that make up the wxGrid
4270 m_rowLabelWin = new wxGridRowLabelWindow( this,
4271 wxID_ANY,
4272 wxDefaultPosition,
4273 wxDefaultSize );
4274
4275 m_colLabelWin = new wxGridColLabelWindow( this,
4276 wxID_ANY,
4277 wxDefaultPosition,
4278 wxDefaultSize );
4279
4280 m_cornerLabelWin = new wxGridCornerLabelWindow( this,
4281 wxID_ANY,
4282 wxDefaultPosition,
4283 wxDefaultSize );
4284
4285 m_gridWin = new wxGridWindow( this,
4286 m_rowLabelWin,
4287 m_colLabelWin,
4288 wxID_ANY,
4289 wxDefaultPosition,
4290 wxDefaultSize );
4291
4292 SetTargetWindow( m_gridWin );
4293
4294#if _USE_VISATTR
4295 wxColour gfg = gva.colFg;
4296 wxColour gbg = gva.colBg;
4297 wxColour lfg = lva.colFg;
4298 wxColour lbg = lva.colBg;
4299#else
4300 wxColour gfg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
4301 wxColour gbg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOW );
4302 wxColour lfg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
4303 wxColour lbg = wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE );
4304#endif
4305
4306 m_cornerLabelWin->SetOwnForegroundColour(lfg);
4307 m_cornerLabelWin->SetOwnBackgroundColour(lbg);
4308 m_rowLabelWin->SetOwnForegroundColour(lfg);
4309 m_rowLabelWin->SetOwnBackgroundColour(lbg);
4310 m_colLabelWin->SetOwnForegroundColour(lfg);
4311 m_colLabelWin->SetOwnBackgroundColour(lbg);
4312
4313 m_gridWin->SetOwnForegroundColour(gfg);
4314 m_gridWin->SetOwnBackgroundColour(gbg);
4315
4316 Init();
4317}
4318
4319bool wxGrid::CreateGrid( int numRows, int numCols,
4320 wxGrid::wxGridSelectionModes selmode )
4321{
4322 wxCHECK_MSG( !m_created,
4323 false,
4324 wxT("wxGrid::CreateGrid or wxGrid::SetTable called more than once") );
4325
4326 m_numRows = numRows;
4327 m_numCols = numCols;
4328
4329 m_table = new wxGridStringTable( m_numRows, m_numCols );
4330 m_table->SetView( this );
4331 m_ownTable = true;
4332 m_selection = new wxGridSelection( this, selmode );
4333
4334 CalcDimensions();
4335
4336 m_created = true;
4337
4338 return m_created;
4339}
4340
4341void wxGrid::SetSelectionMode(wxGrid::wxGridSelectionModes selmode)
4342{
4343 wxCHECK_RET( m_created,
4344 wxT("Called wxGrid::SetSelectionMode() before calling CreateGrid()") );
4345
4346 m_selection->SetSelectionMode( selmode );
4347}
4348
4349wxGrid::wxGridSelectionModes wxGrid::GetSelectionMode() const
4350{
4351 wxCHECK_MSG( m_created, wxGrid::wxGridSelectCells,
4352 wxT("Called wxGrid::GetSelectionMode() before calling CreateGrid()") );
4353
4354 return m_selection->GetSelectionMode();
4355}
4356
4357bool wxGrid::SetTable( wxGridTableBase *table, bool takeOwnership,
4358 wxGrid::wxGridSelectionModes selmode )
4359{
4360 bool checkSelection = false;
4361 if ( m_created )
4362 {
4363 // stop all processing
4364 m_created = false;
4365
4366 if (m_table)
4367 {
4368 m_table->SetView(0);
4369 if( m_ownTable )
4370 delete m_table;
4371 m_table = NULL;
4372 }
4373
4374 delete m_selection;
4375 m_selection = NULL;
4376
4377 m_ownTable = false;
4378 m_numRows = 0;
4379 m_numCols = 0;
4380 checkSelection = true;
4381
4382 // kill row and column size arrays
4383 m_colWidths.Empty();
4384 m_colRights.Empty();
4385 m_rowHeights.Empty();
4386 m_rowBottoms.Empty();
4387 }
4388
4389 if (table)
4390 {
4391 m_numRows = table->GetNumberRows();
4392 m_numCols = table->GetNumberCols();
4393
4394 m_table = table;
4395 m_table->SetView( this );
4396 m_ownTable = takeOwnership;
4397 m_selection = new wxGridSelection( this, selmode );
4398 if (checkSelection)
4399 {
4400 // If the newly set table is smaller than the
4401 // original one current cell and selection regions
4402 // might be invalid,
4403 m_selectingKeyboard = wxGridNoCellCoords;
4404 m_currentCellCoords =
4405 wxGridCellCoords(wxMin(m_numRows, m_currentCellCoords.GetRow()),
4406 wxMin(m_numCols, m_currentCellCoords.GetCol()));
4407 if (m_selectingTopLeft.GetRow() >= m_numRows ||
4408 m_selectingTopLeft.GetCol() >= m_numCols)
4409 {
4410 m_selectingTopLeft = wxGridNoCellCoords;
4411 m_selectingBottomRight = wxGridNoCellCoords;
4412 }
4413 else
4414 m_selectingBottomRight =
4415 wxGridCellCoords(wxMin(m_numRows,
4416 m_selectingBottomRight.GetRow()),
4417 wxMin(m_numCols,
4418 m_selectingBottomRight.GetCol()));
4419 }
4420 CalcDimensions();
4421
4422 m_created = true;
4423 }
4424
4425 return m_created;
4426}
4427
4428void wxGrid::Init()
4429{
4430 m_rowLabelWidth = WXGRID_DEFAULT_ROW_LABEL_WIDTH;
4431 m_colLabelHeight = WXGRID_DEFAULT_COL_LABEL_HEIGHT;
4432
4433 if ( m_rowLabelWin )
4434 {
4435 m_labelBackgroundColour = m_rowLabelWin->GetBackgroundColour();
4436 }
4437 else
4438 {
4439 m_labelBackgroundColour = *wxWHITE;
4440 }
4441
4442 m_labelTextColour = *wxBLACK;
4443
4444 // init attr cache
4445 m_attrCache.row = -1;
4446 m_attrCache.col = -1;
4447 m_attrCache.attr = NULL;
4448
4449 // TODO: something better than this ?
4450 //
4451 m_labelFont = this->GetFont();
4452 m_labelFont.SetWeight( wxBOLD );
4453
4454 m_rowLabelHorizAlign = wxALIGN_CENTRE;
4455 m_rowLabelVertAlign = wxALIGN_CENTRE;
4456
4457 m_colLabelHorizAlign = wxALIGN_CENTRE;
4458 m_colLabelVertAlign = wxALIGN_CENTRE;
4459 m_colLabelTextOrientation = wxHORIZONTAL;
4460
4461 m_defaultColWidth = WXGRID_DEFAULT_COL_WIDTH;
4462 m_defaultRowHeight = m_gridWin->GetCharHeight();
4463
4464 m_minAcceptableColWidth = WXGRID_MIN_COL_WIDTH;
4465 m_minAcceptableRowHeight = WXGRID_MIN_ROW_HEIGHT;
4466
4467#if defined(__WXMOTIF__) || defined(__WXGTK__) // see also text ctrl sizing in ShowCellEditControl()
4468 m_defaultRowHeight += 8;
4469#else
4470 m_defaultRowHeight += 4;
4471#endif
4472
4473 m_gridLineColour = wxColour( 192,192,192 );
4474 m_gridLinesEnabled = true;
4475 m_cellHighlightColour = *wxBLACK;
4476 m_cellHighlightPenWidth = 2;
4477 m_cellHighlightROPenWidth = 1;
4478
4479 m_canDragColMove = false;
4480
4481 m_cursorMode = WXGRID_CURSOR_SELECT_CELL;
4482 m_winCapture = (wxWindow *)NULL;
4483 m_canDragRowSize = true;
4484 m_canDragColSize = true;
4485 m_canDragGridSize = true;
4486 m_canDragCell = false;
4487 m_dragLastPos = -1;
4488 m_dragRowOrCol = -1;
4489 m_isDragging = false;
4490 m_startDragPos = wxDefaultPosition;
4491
4492 m_waitForSlowClick = false;
4493
4494 m_rowResizeCursor = wxCursor( wxCURSOR_SIZENS );
4495 m_colResizeCursor = wxCursor( wxCURSOR_SIZEWE );
4496
4497 m_currentCellCoords = wxGridNoCellCoords;
4498
4499 ClearSelection();
4500
4501 m_selectionBackground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT);
4502 m_selectionForeground = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
4503
4504 m_editable = true; // default for whole grid
4505
4506 m_inOnKeyDown = false;
4507 m_batchCount = 0;
4508
4509 m_extraWidth =
4510 m_extraHeight = 0;
4511
4512 m_scrollLineX = GRID_SCROLL_LINE_X;
4513 m_scrollLineY = GRID_SCROLL_LINE_Y;
4514}
4515
4516// ----------------------------------------------------------------------------
4517// the idea is to call these functions only when necessary because they create
4518// quite big arrays which eat memory mostly unnecessary - in particular, if
4519// default widths/heights are used for all rows/columns, we may not use these
4520// arrays at all
4521//
4522// with some extra code, it should be possible to only store the widths/heights
4523// different from default ones (resulting in space savings for huge grids) but
4524// this is not done currently
4525// ----------------------------------------------------------------------------
4526
4527void wxGrid::InitRowHeights()
4528{
4529 m_rowHeights.Empty();
4530 m_rowBottoms.Empty();
4531
4532 m_rowHeights.Alloc( m_numRows );
4533 m_rowBottoms.Alloc( m_numRows );
4534
4535 m_rowHeights.Add( m_defaultRowHeight, m_numRows );
4536
4537 int rowBottom = 0;
4538 for ( int i = 0; i < m_numRows; i++ )
4539 {
4540 rowBottom += m_defaultRowHeight;
4541 m_rowBottoms.Add( rowBottom );
4542 }
4543}
4544
4545void wxGrid::InitColWidths()
4546{
4547 m_colWidths.Empty();
4548 m_colRights.Empty();
4549
4550 m_colWidths.Alloc( m_numCols );
4551 m_colRights.Alloc( m_numCols );
4552
4553 m_colWidths.Add( m_defaultColWidth, m_numCols );
4554
4555 int colRight = 0;
4556 for ( int i = 0; i < m_numCols; i++ )
4557 {
4558 colRight = ( GetColPos( i ) + 1 ) * m_defaultColWidth;
4559 m_colRights.Add( colRight );
4560 }
4561}
4562
4563int wxGrid::GetColWidth(int col) const
4564{
4565 return m_colWidths.IsEmpty() ? m_defaultColWidth : m_colWidths[col];
4566}
4567
4568int wxGrid::GetColLeft(int col) const
4569{
4570 return m_colRights.IsEmpty() ? GetColPos( col ) * m_defaultColWidth
4571 : m_colRights[col] - m_colWidths[col];
4572}
4573
4574int wxGrid::GetColRight(int col) const
4575{
4576 return m_colRights.IsEmpty() ? (GetColPos( col ) + 1) * m_defaultColWidth
4577 : m_colRights[col];
4578}
4579
4580int wxGrid::GetRowHeight(int row) const
4581{
4582 return m_rowHeights.IsEmpty() ? m_defaultRowHeight : m_rowHeights[row];
4583}
4584
4585int wxGrid::GetRowTop(int row) const
4586{
4587 return m_rowBottoms.IsEmpty() ? row * m_defaultRowHeight
4588 : m_rowBottoms[row] - m_rowHeights[row];
4589}
4590
4591int wxGrid::GetRowBottom(int row) const
4592{
4593 return m_rowBottoms.IsEmpty() ? (row + 1) * m_defaultRowHeight
4594 : m_rowBottoms[row];
4595}
4596
4597void wxGrid::CalcDimensions()
4598{
4599 // compute the size of the scrollable area
4600 int w = m_numCols > 0 ? GetColRight(GetColAt(m_numCols - 1)) : 0;
4601 int h = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
4602
4603 w += m_extraWidth;
4604 h += m_extraHeight;
4605
4606 // take into account editor if shown
4607 if ( IsCellEditControlShown() )
4608 {
4609 int w2, h2;
4610 int r = m_currentCellCoords.GetRow();
4611 int c = m_currentCellCoords.GetCol();
4612 int x = GetColLeft(c);
4613 int y = GetRowTop(r);
4614
4615 // how big is the editor
4616 wxGridCellAttr* attr = GetCellAttr(r, c);
4617 wxGridCellEditor* editor = attr->GetEditor(this, r, c);
4618 editor->GetControl()->GetSize(&w2, &h2);
4619 w2 += x;
4620 h2 += y;
4621 if ( w2 > w )
4622 w = w2;
4623 if ( h2 > h )
4624 h = h2;
4625 editor->DecRef();
4626 attr->DecRef();
4627 }
4628
4629 // preserve (more or less) the previous position
4630 int x, y;
4631 GetViewStart( &x, &y );
4632
4633 // ensure the position is valid for the new scroll ranges
4634 if ( x >= w )
4635 x = wxMax( w - 1, 0 );
4636 if ( y >= h )
4637 y = wxMax( h - 1, 0 );
4638
4639 // do set scrollbar parameters
4640 SetScrollbars( m_scrollLineX, m_scrollLineY,
4641 GetScrollX(w), GetScrollY(h),
4642 x, y,
4643 GetBatchCount() != 0);
4644
4645 // if our OnSize() hadn't been called (it would if we have scrollbars), we
4646 // still must reposition the children
4647 CalcWindowSizes();
4648}
4649
4650void wxGrid::CalcWindowSizes()
4651{
4652 // escape if the window is has not been fully created yet
4653
4654 if ( m_cornerLabelWin == NULL )
4655 return;
4656
4657 int cw, ch;
4658 GetClientSize( &cw, &ch );
4659
4660 // this block of code tries to work around the following problem: the grid
4661 // could have been just resized to have enough space to show the full grid
4662 // window contents without the scrollbars, but its client size could be
4663 // not big enough because the grid has the scrollbars right now and so the
4664 // scrollbars would remain even though we don't need them any more
4665 //
4666 // to prevent this from happening, check if we have enough space for
4667 // everything without the scrollbars and explicitly disable them then
4668 wxSize size = GetSize() - GetWindowBorderSize();
4669 if ( size != wxSize(cw, ch) )
4670 {
4671 // check if we have enough space for grid window after accounting for
4672 // the fixed size elements
4673 size.x -= m_rowLabelWidth;
4674 size.y -= m_colLabelHeight;
4675
4676 const wxSize vsize = m_gridWin->GetVirtualSize();
4677
4678 if ( size.x >= vsize.x && size.y >= vsize.y )
4679 {
4680 // yes, we do, so remove the scrollbars and use the new client size
4681 // (which should be the same as full window size - borders now)
4682 SetScrollbars(0, 0, 0, 0);
4683 GetClientSize(&cw, &ch);
4684 }
4685 }
4686
4687 if ( m_cornerLabelWin && m_cornerLabelWin->IsShown() )
4688 m_cornerLabelWin->SetSize( 0, 0, m_rowLabelWidth, m_colLabelHeight );
4689
4690 if ( m_colLabelWin && m_colLabelWin->IsShown() )
4691 m_colLabelWin->SetSize( m_rowLabelWidth, 0, cw - m_rowLabelWidth, m_colLabelHeight );
4692
4693 if ( m_rowLabelWin && m_rowLabelWin->IsShown() )
4694 m_rowLabelWin->SetSize( 0, m_colLabelHeight, m_rowLabelWidth, ch - m_colLabelHeight );
4695
4696 if ( m_gridWin && m_gridWin->IsShown() )
4697 m_gridWin->SetSize( m_rowLabelWidth, m_colLabelHeight, cw - m_rowLabelWidth, ch - m_colLabelHeight );
4698}
4699
4700// this is called when the grid table sends a message
4701// to indicate that it has been redimensioned
4702//
4703bool wxGrid::Redimension( wxGridTableMessage& msg )
4704{
4705 int i;
4706 bool result = false;
4707
4708 // Clear the attribute cache as the attribute might refer to a different
4709 // cell than stored in the cache after adding/removing rows/columns.
4710 ClearAttrCache();
4711
4712 // By the same reasoning, the editor should be dismissed if columns are
4713 // added or removed. And for consistency, it should IMHO always be
4714 // removed, not only if the cell "underneath" it actually changes.
4715 // For now, I intentionally do not save the editor's content as the
4716 // cell it might want to save that stuff to might no longer exist.
4717 HideCellEditControl();
4718
4719#if 0
4720 // if we were using the default widths/heights so far, we must change them
4721 // now
4722 if ( m_colWidths.IsEmpty() )
4723 {
4724 InitColWidths();
4725 }
4726
4727 if ( m_rowHeights.IsEmpty() )
4728 {
4729 InitRowHeights();
4730 }
4731#endif
4732
4733 switch ( msg.GetId() )
4734 {
4735 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
4736 {
4737 size_t pos = msg.GetCommandInt();
4738 int numRows = msg.GetCommandInt2();
4739
4740 m_numRows += numRows;
4741
4742 if ( !m_rowHeights.IsEmpty() )
4743 {
4744 m_rowHeights.Insert( m_defaultRowHeight, pos, numRows );
4745 m_rowBottoms.Insert( 0, pos, numRows );
4746
4747 int bottom = 0;
4748 if ( pos > 0 )
4749 bottom = m_rowBottoms[pos - 1];
4750
4751 for ( i = pos; i < m_numRows; i++ )
4752 {
4753 bottom += m_rowHeights[i];
4754 m_rowBottoms[i] = bottom;
4755 }
4756 }
4757
4758 if ( m_currentCellCoords == wxGridNoCellCoords )
4759 {
4760 // if we have just inserted cols into an empty grid the current
4761 // cell will be undefined...
4762 //
4763 SetCurrentCell( 0, 0 );
4764 }
4765
4766 if ( m_selection )
4767 m_selection->UpdateRows( pos, numRows );
4768 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
4769 if (attrProvider)
4770 attrProvider->UpdateAttrRows( pos, numRows );
4771
4772 if ( !GetBatchCount() )
4773 {
4774 CalcDimensions();
4775 m_rowLabelWin->Refresh();
4776 }
4777 }
4778 result = true;
4779 break;
4780
4781 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
4782 {
4783 int numRows = msg.GetCommandInt();
4784 int oldNumRows = m_numRows;
4785 m_numRows += numRows;
4786
4787 if ( !m_rowHeights.IsEmpty() )
4788 {
4789 m_rowHeights.Add( m_defaultRowHeight, numRows );
4790 m_rowBottoms.Add( 0, numRows );
4791
4792 int bottom = 0;
4793 if ( oldNumRows > 0 )
4794 bottom = m_rowBottoms[oldNumRows - 1];
4795
4796 for ( i = oldNumRows; i < m_numRows; i++ )
4797 {
4798 bottom += m_rowHeights[i];
4799 m_rowBottoms[i] = bottom;
4800 }
4801 }
4802
4803 if ( m_currentCellCoords == wxGridNoCellCoords )
4804 {
4805 // if we have just inserted cols into an empty grid the current
4806 // cell will be undefined...
4807 //
4808 SetCurrentCell( 0, 0 );
4809 }
4810
4811 if ( !GetBatchCount() )
4812 {
4813 CalcDimensions();
4814 m_rowLabelWin->Refresh();
4815 }
4816 }
4817 result = true;
4818 break;
4819
4820 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
4821 {
4822 size_t pos = msg.GetCommandInt();
4823 int numRows = msg.GetCommandInt2();
4824 m_numRows -= numRows;
4825
4826 if ( !m_rowHeights.IsEmpty() )
4827 {
4828 m_rowHeights.RemoveAt( pos, numRows );
4829 m_rowBottoms.RemoveAt( pos, numRows );
4830
4831 int h = 0;
4832 for ( i = 0; i < m_numRows; i++ )
4833 {
4834 h += m_rowHeights[i];
4835 m_rowBottoms[i] = h;
4836 }
4837 }
4838
4839 if ( !m_numRows )
4840 {
4841 m_currentCellCoords = wxGridNoCellCoords;
4842 }
4843 else
4844 {
4845 if ( m_currentCellCoords.GetRow() >= m_numRows )
4846 m_currentCellCoords.Set( 0, 0 );
4847 }
4848
4849 if ( m_selection )
4850 m_selection->UpdateRows( pos, -((int)numRows) );
4851 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
4852 if (attrProvider)
4853 {
4854 attrProvider->UpdateAttrRows( pos, -((int)numRows) );
4855
4856// ifdef'd out following patch from Paul Gammans
4857#if 0
4858 // No need to touch column attributes, unless we
4859 // removed _all_ rows, in this case, we remove
4860 // all column attributes.
4861 // I hate to do this here, but the
4862 // needed data is not available inside UpdateAttrRows.
4863 if ( !GetNumberRows() )
4864 attrProvider->UpdateAttrCols( 0, -GetNumberCols() );
4865#endif
4866 }
4867
4868 if ( !GetBatchCount() )
4869 {
4870 CalcDimensions();
4871 m_rowLabelWin->Refresh();
4872 }
4873 }
4874 result = true;
4875 break;
4876
4877 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
4878 {
4879 size_t pos = msg.GetCommandInt();
4880 int numCols = msg.GetCommandInt2();
4881 m_numCols += numCols;
4882
4883 if ( !m_colAt.IsEmpty() )
4884 {
4885 //Shift the column IDs
4886 int i;
4887 for ( i = 0; i < m_numCols - numCols; i++ )
4888 {
4889 if ( m_colAt[i] >= (int)pos )
4890 m_colAt[i] += numCols;
4891 }
4892
4893 m_colAt.Insert( pos, pos, numCols );
4894
4895 //Set the new columns' positions
4896 for ( i = pos + 1; i < (int)pos + numCols; i++ )
4897 {
4898 m_colAt[i] = i;
4899 }
4900 }
4901
4902 if ( !m_colWidths.IsEmpty() )
4903 {
4904 m_colWidths.Insert( m_defaultColWidth, pos, numCols );
4905 m_colRights.Insert( 0, pos, numCols );
4906
4907 int right = 0;
4908 if ( pos > 0 )
4909 right = m_colRights[GetColAt( pos - 1 )];
4910
4911 int colPos;
4912 for ( colPos = pos; colPos < m_numCols; colPos++ )
4913 {
4914 i = GetColAt( colPos );
4915
4916 right += m_colWidths[i];
4917 m_colRights[i] = right;
4918 }
4919 }
4920
4921 if ( m_currentCellCoords == wxGridNoCellCoords )
4922 {
4923 // if we have just inserted cols into an empty grid the current
4924 // cell will be undefined...
4925 //
4926 SetCurrentCell( 0, 0 );
4927 }
4928
4929 if ( m_selection )
4930 m_selection->UpdateCols( pos, numCols );
4931 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
4932 if (attrProvider)
4933 attrProvider->UpdateAttrCols( pos, numCols );
4934 if ( !GetBatchCount() )
4935 {
4936 CalcDimensions();
4937 m_colLabelWin->Refresh();
4938 }
4939 }
4940 result = true;
4941 break;
4942
4943 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
4944 {
4945 int numCols = msg.GetCommandInt();
4946 int oldNumCols = m_numCols;
4947 m_numCols += numCols;
4948
4949 if ( !m_colAt.IsEmpty() )
4950 {
4951 m_colAt.Add( 0, numCols );
4952
4953 //Set the new columns' positions
4954 int i;
4955 for ( i = oldNumCols; i < m_numCols; i++ )
4956 {
4957 m_colAt[i] = i;
4958 }
4959 }
4960
4961 if ( !m_colWidths.IsEmpty() )
4962 {
4963 m_colWidths.Add( m_defaultColWidth, numCols );
4964 m_colRights.Add( 0, numCols );
4965
4966 int right = 0;
4967 if ( oldNumCols > 0 )
4968 right = m_colRights[GetColAt( oldNumCols - 1 )];
4969
4970 int colPos;
4971 for ( colPos = oldNumCols; colPos < m_numCols; colPos++ )
4972 {
4973 i = GetColAt( colPos );
4974
4975 right += m_colWidths[i];
4976 m_colRights[i] = right;
4977 }
4978 }
4979
4980 if ( m_currentCellCoords == wxGridNoCellCoords )
4981 {
4982 // if we have just inserted cols into an empty grid the current
4983 // cell will be undefined...
4984 //
4985 SetCurrentCell( 0, 0 );
4986 }
4987 if ( !GetBatchCount() )
4988 {
4989 CalcDimensions();
4990 m_colLabelWin->Refresh();
4991 }
4992 }
4993 result = true;
4994 break;
4995
4996 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
4997 {
4998 size_t pos = msg.GetCommandInt();
4999 int numCols = msg.GetCommandInt2();
5000 m_numCols -= numCols;
5001
5002 if ( !m_colAt.IsEmpty() )
5003 {
5004 int colID = GetColAt( pos );
5005
5006 m_colAt.RemoveAt( pos, numCols );
5007
5008 //Shift the column IDs
5009 int colPos;
5010 for ( colPos = 0; colPos < m_numCols; colPos++ )
5011 {
5012 if ( m_colAt[colPos] > colID )
5013 m_colAt[colPos] -= numCols;
5014 }
5015 }
5016
5017 if ( !m_colWidths.IsEmpty() )
5018 {
5019 m_colWidths.RemoveAt( pos, numCols );
5020 m_colRights.RemoveAt( pos, numCols );
5021
5022 int w = 0;
5023 int colPos;
5024 for ( colPos = 0; colPos < m_numCols; colPos++ )
5025 {
5026 i = GetColAt( colPos );
5027
5028 w += m_colWidths[i];
5029 m_colRights[i] = w;
5030 }
5031 }
5032
5033 if ( !m_numCols )
5034 {
5035 m_currentCellCoords = wxGridNoCellCoords;
5036 }
5037 else
5038 {
5039 if ( m_currentCellCoords.GetCol() >= m_numCols )
5040 m_currentCellCoords.Set( 0, 0 );
5041 }
5042
5043 if ( m_selection )
5044 m_selection->UpdateCols( pos, -((int)numCols) );
5045 wxGridCellAttrProvider * attrProvider = m_table->GetAttrProvider();
5046 if (attrProvider)
5047 {
5048 attrProvider->UpdateAttrCols( pos, -((int)numCols) );
5049
5050// ifdef'd out following patch from Paul Gammans
5051#if 0
5052 // No need to touch row attributes, unless we
5053 // removed _all_ columns, in this case, we remove
5054 // all row attributes.
5055 // I hate to do this here, but the
5056 // needed data is not available inside UpdateAttrCols.
5057 if ( !GetNumberCols() )
5058 attrProvider->UpdateAttrRows( 0, -GetNumberRows() );
5059#endif
5060 }
5061
5062 if ( !GetBatchCount() )
5063 {
5064 CalcDimensions();
5065 m_colLabelWin->Refresh();
5066 }
5067 }
5068 result = true;
5069 break;
5070 }
5071
5072 if (result && !GetBatchCount() )
5073 m_gridWin->Refresh();
5074
5075 return result;
5076}
5077
5078wxArrayInt wxGrid::CalcRowLabelsExposed( const wxRegion& reg )
5079{
5080 wxRegionIterator iter( reg );
5081 wxRect r;
5082
5083 wxArrayInt rowlabels;
5084
5085 int top, bottom;
5086 while ( iter )
5087 {
5088 r = iter.GetRect();
5089
5090 // TODO: remove this when we can...
5091 // There is a bug in wxMotif that gives garbage update
5092 // rectangles if you jump-scroll a long way by clicking the
5093 // scrollbar with middle button. This is a work-around
5094 //
5095#if defined(__WXMOTIF__)
5096 int cw, ch;
5097 m_gridWin->GetClientSize( &cw, &ch );
5098 if ( r.GetTop() > ch )
5099 r.SetTop( 0 );
5100 r.SetBottom( wxMin( r.GetBottom(), ch ) );
5101#endif
5102
5103 // logical bounds of update region
5104 //
5105 int dummy;
5106 CalcUnscrolledPosition( 0, r.GetTop(), &dummy, &top );
5107 CalcUnscrolledPosition( 0, r.GetBottom(), &dummy, &bottom );
5108
5109 // find the row labels within these bounds
5110 //
5111 int row;
5112 for ( row = internalYToRow(top); row < m_numRows; row++ )
5113 {
5114 if ( GetRowBottom(row) < top )
5115 continue;
5116
5117 if ( GetRowTop(row) > bottom )
5118 break;
5119
5120 rowlabels.Add( row );
5121 }
5122
5123 ++iter;
5124 }
5125
5126 return rowlabels;
5127}
5128
5129wxArrayInt wxGrid::CalcColLabelsExposed( const wxRegion& reg )
5130{
5131 wxRegionIterator iter( reg );
5132 wxRect r;
5133
5134 wxArrayInt colLabels;
5135
5136 int left, right;
5137 while ( iter )
5138 {
5139 r = iter.GetRect();
5140
5141 // TODO: remove this when we can...
5142 // There is a bug in wxMotif that gives garbage update
5143 // rectangles if you jump-scroll a long way by clicking the
5144 // scrollbar with middle button. This is a work-around
5145 //
5146#if defined(__WXMOTIF__)
5147 int cw, ch;
5148 m_gridWin->GetClientSize( &cw, &ch );
5149 if ( r.GetLeft() > cw )
5150 r.SetLeft( 0 );
5151 r.SetRight( wxMin( r.GetRight(), cw ) );
5152#endif
5153
5154 // logical bounds of update region
5155 //
5156 int dummy;
5157 CalcUnscrolledPosition( r.GetLeft(), 0, &left, &dummy );
5158 CalcUnscrolledPosition( r.GetRight(), 0, &right, &dummy );
5159
5160 // find the cells within these bounds
5161 //
5162 int col;
5163 int colPos;
5164 for ( colPos = GetColPos( internalXToCol(left) ); colPos < m_numCols; colPos++ )
5165 {
5166 col = GetColAt( colPos );
5167
5168 if ( GetColRight(col) < left )
5169 continue;
5170
5171 if ( GetColLeft(col) > right )
5172 break;
5173
5174 colLabels.Add( col );
5175 }
5176
5177 ++iter;
5178 }
5179
5180 return colLabels;
5181}
5182
5183wxGridCellCoordsArray wxGrid::CalcCellsExposed( const wxRegion& reg )
5184{
5185 wxRegionIterator iter( reg );
5186 wxRect r;
5187
5188 wxGridCellCoordsArray cellsExposed;
5189
5190 int left, top, right, bottom;
5191 while ( iter )
5192 {
5193 r = iter.GetRect();
5194
5195 // TODO: remove this when we can...
5196 // There is a bug in wxMotif that gives garbage update
5197 // rectangles if you jump-scroll a long way by clicking the
5198 // scrollbar with middle button. This is a work-around
5199 //
5200#if defined(__WXMOTIF__)
5201 int cw, ch;
5202 m_gridWin->GetClientSize( &cw, &ch );
5203 if ( r.GetTop() > ch ) r.SetTop( 0 );
5204 if ( r.GetLeft() > cw ) r.SetLeft( 0 );
5205 r.SetRight( wxMin( r.GetRight(), cw ) );
5206 r.SetBottom( wxMin( r.GetBottom(), ch ) );
5207#endif
5208
5209 // logical bounds of update region
5210 //
5211 CalcUnscrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
5212 CalcUnscrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
5213
5214 // find the cells within these bounds
5215 //
5216 int row, col;
5217 for ( row = internalYToRow(top); row < m_numRows; row++ )
5218 {
5219 if ( GetRowBottom(row) <= top )
5220 continue;
5221
5222 if ( GetRowTop(row) > bottom )
5223 break;
5224
5225 int colPos;
5226 for ( colPos = GetColPos( internalXToCol(left) ); colPos < m_numCols; colPos++ )
5227 {
5228 col = GetColAt( colPos );
5229
5230 if ( GetColRight(col) <= left )
5231 continue;
5232
5233 if ( GetColLeft(col) > right )
5234 break;
5235
5236 cellsExposed.Add( wxGridCellCoords( row, col ) );
5237 }
5238 }
5239
5240 ++iter;
5241 }
5242
5243 return cellsExposed;
5244}
5245
5246
5247void wxGrid::ProcessRowLabelMouseEvent( wxMouseEvent& event )
5248{
5249 int x, y, row;
5250 wxPoint pos( event.GetPosition() );
5251 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5252
5253 if ( event.Dragging() )
5254 {
5255 if (!m_isDragging)
5256 {
5257 m_isDragging = true;
5258 m_rowLabelWin->CaptureMouse();
5259 }
5260
5261 if ( event.LeftIsDown() )
5262 {
5263 switch ( m_cursorMode )
5264 {
5265 case WXGRID_CURSOR_RESIZE_ROW:
5266 {
5267 int cw, ch, left, dummy;
5268 m_gridWin->GetClientSize( &cw, &ch );
5269 CalcUnscrolledPosition( 0, 0, &left, &dummy );
5270
5271 wxClientDC dc( m_gridWin );
5272 PrepareDC( dc );
5273 y = wxMax( y,
5274 GetRowTop(m_dragRowOrCol) +
5275 GetRowMinimalHeight(m_dragRowOrCol) );
5276 dc.SetLogicalFunction(wxINVERT);
5277 if ( m_dragLastPos >= 0 )
5278 {
5279 dc.DrawLine( left, m_dragLastPos, left+cw, m_dragLastPos );
5280 }
5281 dc.DrawLine( left, y, left+cw, y );
5282 m_dragLastPos = y;
5283 }
5284 break;
5285
5286 case WXGRID_CURSOR_SELECT_ROW:
5287 {
5288 if ( (row = YToRow( y )) >= 0 )
5289 {
5290 if ( m_selection )
5291 {
5292 m_selection->SelectRow( row,
5293 event.ControlDown(),
5294 event.ShiftDown(),
5295 event.AltDown(),
5296 event.MetaDown() );
5297 }
5298 }
5299 }
5300 break;
5301
5302 // default label to suppress warnings about "enumeration value
5303 // 'xxx' not handled in switch
5304 default:
5305 break;
5306 }
5307 }
5308 return;
5309 }
5310
5311 if ( m_isDragging && (event.Entering() || event.Leaving()) )
5312 return;
5313
5314 if (m_isDragging)
5315 {
5316 if (m_rowLabelWin->HasCapture())
5317 m_rowLabelWin->ReleaseMouse();
5318 m_isDragging = false;
5319 }
5320
5321 // ------------ Entering or leaving the window
5322 //
5323 if ( event.Entering() || event.Leaving() )
5324 {
5325 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5326 }
5327
5328 // ------------ Left button pressed
5329 //
5330 else if ( event.LeftDown() )
5331 {
5332 // don't send a label click event for a hit on the
5333 // edge of the row label - this is probably the user
5334 // wanting to resize the row
5335 //
5336 if ( YToEdgeOfRow(y) < 0 )
5337 {
5338 row = YToRow(y);
5339 if ( row >= 0 &&
5340 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, row, -1, event ) )
5341 {
5342 if ( !event.ShiftDown() && !event.CmdDown() )
5343 ClearSelection();
5344 if ( m_selection )
5345 {
5346 if ( event.ShiftDown() )
5347 {
5348 m_selection->SelectBlock( m_currentCellCoords.GetRow(),
5349 0,
5350 row,
5351 GetNumberCols() - 1,
5352 event.ControlDown(),
5353 event.ShiftDown(),
5354 event.AltDown(),
5355 event.MetaDown() );
5356 }
5357 else
5358 {
5359 m_selection->SelectRow( row,
5360 event.ControlDown(),
5361 event.ShiftDown(),
5362 event.AltDown(),
5363 event.MetaDown() );
5364 }
5365 }
5366
5367 ChangeCursorMode(WXGRID_CURSOR_SELECT_ROW, m_rowLabelWin);
5368 }
5369 }
5370 else
5371 {
5372 // starting to drag-resize a row
5373 if ( CanDragRowSize() )
5374 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin);
5375 }
5376 }
5377
5378 // ------------ Left double click
5379 //
5380 else if (event.LeftDClick() )
5381 {
5382 row = YToEdgeOfRow(y);
5383 if ( row < 0 )
5384 {
5385 row = YToRow(y);
5386 if ( row >=0 &&
5387 !SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, row, -1, event ) )
5388 {
5389 // no default action at the moment
5390 }
5391 }
5392 else
5393 {
5394 // adjust row height depending on label text
5395 AutoSizeRowLabelSize( row );
5396
5397 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_colLabelWin);
5398 m_dragLastPos = -1;
5399 }
5400 }
5401
5402 // ------------ Left button released
5403 //
5404 else if ( event.LeftUp() )
5405 {
5406 if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
5407 {
5408 DoEndDragResizeRow();
5409
5410 // Note: we are ending the event *after* doing
5411 // default processing in this case
5412 //
5413 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
5414 }
5415
5416 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin);
5417 m_dragLastPos = -1;
5418 }
5419
5420 // ------------ Right button down
5421 //
5422 else if ( event.RightDown() )
5423 {
5424 row = YToRow(y);
5425 if ( row >=0 &&
5426 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, row, -1, event ) )
5427 {
5428 // no default action at the moment
5429 }
5430 }
5431
5432 // ------------ Right double click
5433 //
5434 else if ( event.RightDClick() )
5435 {
5436 row = YToRow(y);
5437 if ( row >= 0 &&
5438 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, row, -1, event ) )
5439 {
5440 // no default action at the moment
5441 }
5442 }
5443
5444 // ------------ No buttons down and mouse moving
5445 //
5446 else if ( event.Moving() )
5447 {
5448 m_dragRowOrCol = YToEdgeOfRow( y );
5449 if ( m_dragRowOrCol >= 0 )
5450 {
5451 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
5452 {
5453 // don't capture the mouse yet
5454 if ( CanDragRowSize() )
5455 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW, m_rowLabelWin, false);
5456 }
5457 }
5458 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
5459 {
5460 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_rowLabelWin, false);
5461 }
5462 }
5463}
5464
5465void wxGrid::ProcessColLabelMouseEvent( wxMouseEvent& event )
5466{
5467 int x, y, col;
5468 wxPoint pos( event.GetPosition() );
5469 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5470
5471 if ( event.Dragging() )
5472 {
5473 if (!m_isDragging)
5474 {
5475 m_isDragging = true;
5476 m_colLabelWin->CaptureMouse();
5477
5478 if ( m_cursorMode == WXGRID_CURSOR_MOVE_COL )
5479 m_dragRowOrCol = XToCol( x );
5480 }
5481
5482 if ( event.LeftIsDown() )
5483 {
5484 switch ( m_cursorMode )
5485 {
5486 case WXGRID_CURSOR_RESIZE_COL:
5487 {
5488 int cw, ch, dummy, top;
5489 m_gridWin->GetClientSize( &cw, &ch );
5490 CalcUnscrolledPosition( 0, 0, &dummy, &top );
5491
5492 wxClientDC dc( m_gridWin );
5493 PrepareDC( dc );
5494
5495 x = wxMax( x, GetColLeft(m_dragRowOrCol) +
5496 GetColMinimalWidth(m_dragRowOrCol));
5497 dc.SetLogicalFunction(wxINVERT);
5498 if ( m_dragLastPos >= 0 )
5499 {
5500 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
5501 }
5502 dc.DrawLine( x, top, x, top + ch );
5503 m_dragLastPos = x;
5504 }
5505 break;
5506
5507 case WXGRID_CURSOR_SELECT_COL:
5508 {
5509 if ( (col = XToCol( x )) >= 0 )
5510 {
5511 if ( m_selection )
5512 {
5513 m_selection->SelectCol( col,
5514 event.ControlDown(),
5515 event.ShiftDown(),
5516 event.AltDown(),
5517 event.MetaDown() );
5518 }
5519 }
5520 }
5521 break;
5522
5523 case WXGRID_CURSOR_MOVE_COL:
5524 {
5525 if ( x < 0 )
5526 m_moveToCol = GetColAt( 0 );
5527 else
5528 m_moveToCol = XToCol( x );
5529
5530 int markerX;
5531
5532 if ( m_moveToCol < 0 )
5533 markerX = GetColRight( GetColAt( m_numCols - 1 ) );
5534 else
5535 markerX = GetColLeft( m_moveToCol );
5536
5537 if ( markerX != m_dragLastPos )
5538 {
5539 wxClientDC dc( m_colLabelWin );
5540
5541 int cw, ch;
5542 m_colLabelWin->GetClientSize( &cw, &ch );
5543
5544 markerX++;
5545
5546 //Clean up the last indicator
5547 if ( m_dragLastPos >= 0 )
5548 {
5549 wxPen pen( m_colLabelWin->GetBackgroundColour(), 2 );
5550 dc.SetPen(pen);
5551 dc.DrawLine( m_dragLastPos + 1, 0, m_dragLastPos + 1, ch );
5552 dc.SetPen(wxNullPen);
5553
5554 if ( XToCol( m_dragLastPos ) != -1 )
5555 DrawColLabel( dc, XToCol( m_dragLastPos ) );
5556 }
5557
5558 //Moving to the same place? Don't draw a marker
5559 if ( (m_moveToCol == m_dragRowOrCol)
5560 || (GetColPos( m_moveToCol ) == GetColPos( m_dragRowOrCol ) + 1)
5561 || (m_moveToCol < 0 && m_dragRowOrCol == GetColAt( m_numCols - 1 )))
5562 {
5563 m_dragLastPos = -1;
5564 return;
5565 }
5566
5567 //Draw the marker
5568 wxPen pen( *wxBLUE, 2 );
5569 dc.SetPen(pen);
5570
5571 dc.DrawLine( markerX, 0, markerX, ch );
5572
5573 dc.SetPen(wxNullPen);
5574
5575 m_dragLastPos = markerX - 1;
5576 }
5577 }
5578 break;
5579
5580 // default label to suppress warnings about "enumeration value
5581 // 'xxx' not handled in switch
5582 default:
5583 break;
5584 }
5585 }
5586 return;
5587 }
5588
5589 if ( m_isDragging && (event.Entering() || event.Leaving()) )
5590 return;
5591
5592 if (m_isDragging)
5593 {
5594 if (m_colLabelWin->HasCapture())
5595 m_colLabelWin->ReleaseMouse();
5596 m_isDragging = false;
5597 }
5598
5599 // ------------ Entering or leaving the window
5600 //
5601 if ( event.Entering() || event.Leaving() )
5602 {
5603 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_colLabelWin);
5604 }
5605
5606 // ------------ Left button pressed
5607 //
5608 else if ( event.LeftDown() )
5609 {
5610 // don't send a label click event for a hit on the
5611 // edge of the col label - this is probably the user
5612 // wanting to resize the col
5613 //
5614 if ( XToEdgeOfCol(x) < 0 )
5615 {
5616 col = XToCol(x);
5617 if ( col >= 0 &&
5618 !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, col, event ) )
5619 {
5620 if ( m_canDragColMove )
5621 {
5622 //Show button as pressed
5623 wxClientDC dc( m_colLabelWin );
5624 int colLeft = GetColLeft( col );
5625 int colRight = GetColRight( col ) - 1;
5626 dc.SetPen( wxPen( m_colLabelWin->GetBackgroundColour(), 1 ) );
5627 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight-1 );
5628 dc.DrawLine( colLeft, 1, colRight, 1 );
5629
5630 ChangeCursorMode(WXGRID_CURSOR_MOVE_COL, m_colLabelWin);
5631 }
5632 else
5633 {
5634 if ( !event.ShiftDown() && !event.CmdDown() )
5635 ClearSelection();
5636 if ( m_selection )
5637 {
5638 if ( event.ShiftDown() )
5639 {
5640 m_selection->SelectBlock( 0,
5641 m_currentCellCoords.GetCol(),
5642 GetNumberRows() - 1, col,
5643 event.ControlDown(),
5644 event.ShiftDown(),
5645 event.AltDown(),
5646 event.MetaDown() );
5647 }
5648 else
5649 {
5650 m_selection->SelectCol( col,
5651 event.ControlDown(),
5652 event.ShiftDown(),
5653 event.AltDown(),
5654 event.MetaDown() );
5655 }
5656 }
5657
5658 ChangeCursorMode(WXGRID_CURSOR_SELECT_COL, m_colLabelWin);
5659 }
5660 }
5661 }
5662 else
5663 {
5664 // starting to drag-resize a col
5665 //
5666 if ( CanDragColSize() )
5667 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, m_colLabelWin);
5668 }
5669 }
5670
5671 // ------------ Left double click
5672 //
5673 if ( event.LeftDClick() )
5674 {
5675 col = XToEdgeOfCol(x);
5676 if ( col < 0 )
5677 {
5678 col = XToCol(x);
5679 if ( col >= 0 &&
5680 ! SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, col, event ) )
5681 {
5682 // no default action at the moment
5683 }
5684 }
5685 else
5686 {
5687 // adjust column width depending on label text
5688 AutoSizeColLabelSize( col );
5689
5690 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_colLabelWin);
5691 m_dragLastPos = -1;
5692 }
5693 }
5694
5695 // ------------ Left button released
5696 //
5697 else if ( event.LeftUp() )
5698 {
5699 switch ( m_cursorMode )
5700 {
5701 case WXGRID_CURSOR_RESIZE_COL:
5702 DoEndDragResizeCol();
5703
5704 // Note: we are ending the event *after* doing
5705 // default processing in this case
5706 //
5707 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, event );
5708 break;
5709
5710 case WXGRID_CURSOR_MOVE_COL:
5711 DoEndDragMoveCol();
5712
5713 SendEvent( wxEVT_GRID_COL_MOVE, -1, m_dragRowOrCol, event );
5714 break;
5715
5716 case WXGRID_CURSOR_SELECT_COL:
5717 case WXGRID_CURSOR_SELECT_CELL:
5718 case WXGRID_CURSOR_RESIZE_ROW:
5719 case WXGRID_CURSOR_SELECT_ROW:
5720 // nothing to do (?)
5721 break;
5722 }
5723
5724 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_colLabelWin);
5725 m_dragLastPos = -1;
5726 }
5727
5728 // ------------ Right button down
5729 //
5730 else if ( event.RightDown() )
5731 {
5732 col = XToCol(x);
5733 if ( col >= 0 &&
5734 !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, col, event ) )
5735 {
5736 // no default action at the moment
5737 }
5738 }
5739
5740 // ------------ Right double click
5741 //
5742 else if ( event.RightDClick() )
5743 {
5744 col = XToCol(x);
5745 if ( col >= 0 &&
5746 !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, col, event ) )
5747 {
5748 // no default action at the moment
5749 }
5750 }
5751
5752 // ------------ No buttons down and mouse moving
5753 //
5754 else if ( event.Moving() )
5755 {
5756 m_dragRowOrCol = XToEdgeOfCol( x );
5757 if ( m_dragRowOrCol >= 0 )
5758 {
5759 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
5760 {
5761 // don't capture the cursor yet
5762 if ( CanDragColSize() )
5763 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL, m_colLabelWin, false);
5764 }
5765 }
5766 else if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
5767 {
5768 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL, m_colLabelWin, false);
5769 }
5770 }
5771}
5772
5773void wxGrid::ProcessCornerLabelMouseEvent( wxMouseEvent& event )
5774{
5775 if ( event.LeftDown() )
5776 {
5777 // indicate corner label by having both row and
5778 // col args == -1
5779 //
5780 if ( !SendEvent( wxEVT_GRID_LABEL_LEFT_CLICK, -1, -1, event ) )
5781 {
5782 SelectAll();
5783 }
5784 }
5785 else if ( event.LeftDClick() )
5786 {
5787 SendEvent( wxEVT_GRID_LABEL_LEFT_DCLICK, -1, -1, event );
5788 }
5789 else if ( event.RightDown() )
5790 {
5791 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_CLICK, -1, -1, event ) )
5792 {
5793 // no default action at the moment
5794 }
5795 }
5796 else if ( event.RightDClick() )
5797 {
5798 if ( !SendEvent( wxEVT_GRID_LABEL_RIGHT_DCLICK, -1, -1, event ) )
5799 {
5800 // no default action at the moment
5801 }
5802 }
5803}
5804
5805void wxGrid::ChangeCursorMode(CursorMode mode,
5806 wxWindow *win,
5807 bool captureMouse)
5808{
5809#ifdef __WXDEBUG__
5810 static const wxChar *cursorModes[] =
5811 {
5812 _T("SELECT_CELL"),
5813 _T("RESIZE_ROW"),
5814 _T("RESIZE_COL"),
5815 _T("SELECT_ROW"),
5816 _T("SELECT_COL"),
5817 _T("MOVE_COL"),
5818 };
5819
5820 wxLogTrace(_T("grid"),
5821 _T("wxGrid cursor mode (mouse capture for %s): %s -> %s"),
5822 win == m_colLabelWin ? _T("colLabelWin")
5823 : win ? _T("rowLabelWin")
5824 : _T("gridWin"),
5825 cursorModes[m_cursorMode], cursorModes[mode]);
5826#endif
5827
5828 if ( mode == m_cursorMode &&
5829 win == m_winCapture &&
5830 captureMouse == (m_winCapture != NULL))
5831 return;
5832
5833 if ( !win )
5834 {
5835 // by default use the grid itself
5836 win = m_gridWin;
5837 }
5838
5839 if ( m_winCapture )
5840 {
5841 if (m_winCapture->HasCapture())
5842 m_winCapture->ReleaseMouse();
5843 m_winCapture = (wxWindow *)NULL;
5844 }
5845
5846 m_cursorMode = mode;
5847
5848 switch ( m_cursorMode )
5849 {
5850 case WXGRID_CURSOR_RESIZE_ROW:
5851 win->SetCursor( m_rowResizeCursor );
5852 break;
5853
5854 case WXGRID_CURSOR_RESIZE_COL:
5855 win->SetCursor( m_colResizeCursor );
5856 break;
5857
5858 case WXGRID_CURSOR_MOVE_COL:
5859 win->SetCursor( wxCursor(wxCURSOR_HAND) );
5860 break;
5861
5862 default:
5863 win->SetCursor( *wxSTANDARD_CURSOR );
5864 break;
5865 }
5866
5867 // we need to capture mouse when resizing
5868 bool resize = m_cursorMode == WXGRID_CURSOR_RESIZE_ROW ||
5869 m_cursorMode == WXGRID_CURSOR_RESIZE_COL;
5870
5871 if ( captureMouse && resize )
5872 {
5873 win->CaptureMouse();
5874 m_winCapture = win;
5875 }
5876}
5877
5878void wxGrid::ProcessGridCellMouseEvent( wxMouseEvent& event )
5879{
5880 int x, y;
5881 wxPoint pos( event.GetPosition() );
5882 CalcUnscrolledPosition( pos.x, pos.y, &x, &y );
5883
5884 wxGridCellCoords coords;
5885 XYToCell( x, y, coords );
5886
5887 int cell_rows, cell_cols;
5888 bool isFirstDrag = !m_isDragging;
5889 GetCellSize( coords.GetRow(), coords.GetCol(), &cell_rows, &cell_cols );
5890 if ((cell_rows < 0) || (cell_cols < 0))
5891 {
5892 coords.SetRow(coords.GetRow() + cell_rows);
5893 coords.SetCol(coords.GetCol() + cell_cols);
5894 }
5895
5896 if ( event.Dragging() )
5897 {
5898 //wxLogDebug("pos(%d, %d) coords(%d, %d)", pos.x, pos.y, coords.GetRow(), coords.GetCol());
5899
5900 // Don't start doing anything until the mouse has been dragged at
5901 // least 3 pixels in any direction...
5902 if (! m_isDragging)
5903 {
5904 if (m_startDragPos == wxDefaultPosition)
5905 {
5906 m_startDragPos = pos;
5907 return;
5908 }
5909 if (abs(m_startDragPos.x - pos.x) < 4 && abs(m_startDragPos.y - pos.y) < 4)
5910 return;
5911 }
5912
5913 m_isDragging = true;
5914 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
5915 {
5916 // Hide the edit control, so it
5917 // won't interfere with drag-shrinking.
5918 if ( IsCellEditControlShown() )
5919 {
5920 HideCellEditControl();
5921 SaveEditControlValue();
5922 }
5923
5924 // Have we captured the mouse yet?
5925 if (! m_winCapture)
5926 {
5927 m_winCapture = m_gridWin;
5928 m_winCapture->CaptureMouse();
5929 }
5930
5931 if ( coords != wxGridNoCellCoords )
5932 {
5933 if ( event.CmdDown() )
5934 {
5935 if ( m_selectingKeyboard == wxGridNoCellCoords)
5936 m_selectingKeyboard = coords;
5937 HighlightBlock( m_selectingKeyboard, coords );
5938 }
5939 else if ( CanDragCell() )
5940 {
5941 if ( isFirstDrag )
5942 {
5943 if ( m_selectingKeyboard == wxGridNoCellCoords)
5944 m_selectingKeyboard = coords;
5945
5946 SendEvent( wxEVT_GRID_CELL_BEGIN_DRAG,
5947 coords.GetRow(),
5948 coords.GetCol(),
5949 event );
5950 }
5951 }
5952 else
5953 {
5954 if ( !IsSelection() )
5955 {
5956 HighlightBlock( coords, coords );
5957 }
5958 else
5959 {
5960 HighlightBlock( m_currentCellCoords, coords );
5961 }
5962 }
5963
5964 if (! IsVisible(coords))
5965 {
5966 MakeCellVisible(coords);
5967 // TODO: need to introduce a delay or something here. The
5968 // scrolling is way to fast, at least on MSW - also on GTK.
5969 }
5970 }
5971 }
5972 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
5973 {
5974 int cw, ch, left, dummy;
5975 m_gridWin->GetClientSize( &cw, &ch );
5976 CalcUnscrolledPosition( 0, 0, &left, &dummy );
5977
5978 wxClientDC dc( m_gridWin );
5979 PrepareDC( dc );
5980 y = wxMax( y, GetRowTop(m_dragRowOrCol) +
5981 GetRowMinimalHeight(m_dragRowOrCol) );
5982 dc.SetLogicalFunction(wxINVERT);
5983 if ( m_dragLastPos >= 0 )
5984 {
5985 dc.DrawLine( left, m_dragLastPos, left+cw, m_dragLastPos );
5986 }
5987 dc.DrawLine( left, y, left+cw, y );
5988 m_dragLastPos = y;
5989 }
5990 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL )
5991 {
5992 int cw, ch, dummy, top;
5993 m_gridWin->GetClientSize( &cw, &ch );
5994 CalcUnscrolledPosition( 0, 0, &dummy, &top );
5995
5996 wxClientDC dc( m_gridWin );
5997 PrepareDC( dc );
5998 x = wxMax( x, GetColLeft(m_dragRowOrCol) +
5999 GetColMinimalWidth(m_dragRowOrCol) );
6000 dc.SetLogicalFunction(wxINVERT);
6001 if ( m_dragLastPos >= 0 )
6002 {
6003 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
6004 }
6005 dc.DrawLine( x, top, x, top + ch );
6006 m_dragLastPos = x;
6007 }
6008
6009 return;
6010 }
6011
6012 m_isDragging = false;
6013 m_startDragPos = wxDefaultPosition;
6014
6015 // VZ: if we do this, the mode is reset to WXGRID_CURSOR_SELECT_CELL
6016 // immediately after it becomes WXGRID_CURSOR_RESIZE_ROW/COL under
6017 // wxGTK
6018#if 0
6019 if ( event.Entering() || event.Leaving() )
6020 {
6021 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6022 m_gridWin->SetCursor( *wxSTANDARD_CURSOR );
6023 }
6024 else
6025#endif // 0
6026
6027 // ------------ Left button pressed
6028 //
6029 if ( event.LeftDown() && coords != wxGridNoCellCoords )
6030 {
6031 if ( !SendEvent( wxEVT_GRID_CELL_LEFT_CLICK,
6032 coords.GetRow(),
6033 coords.GetCol(),
6034 event ) )
6035 {
6036 if ( !event.CmdDown() )
6037 ClearSelection();
6038 if ( event.ShiftDown() )
6039 {
6040 if ( m_selection )
6041 {
6042 m_selection->SelectBlock( m_currentCellCoords.GetRow(),
6043 m_currentCellCoords.GetCol(),
6044 coords.GetRow(),
6045 coords.GetCol(),
6046 event.ControlDown(),
6047 event.ShiftDown(),
6048 event.AltDown(),
6049 event.MetaDown() );
6050 }
6051 }
6052 else if ( XToEdgeOfCol(x) < 0 &&
6053 YToEdgeOfRow(y) < 0 )
6054 {
6055 DisableCellEditControl();
6056 MakeCellVisible( coords );
6057
6058 if ( event.CmdDown() )
6059 {
6060 if ( m_selection )
6061 {
6062 m_selection->ToggleCellSelection( coords.GetRow(),
6063 coords.GetCol(),
6064 event.ControlDown(),
6065 event.ShiftDown(),
6066 event.AltDown(),
6067 event.MetaDown() );
6068 }
6069 m_selectingTopLeft = wxGridNoCellCoords;
6070 m_selectingBottomRight = wxGridNoCellCoords;
6071 m_selectingKeyboard = coords;
6072 }
6073 else
6074 {
6075 m_waitForSlowClick = m_currentCellCoords == coords && coords != wxGridNoCellCoords;
6076 SetCurrentCell( coords );
6077 if ( m_selection )
6078 {
6079 if ( m_selection->GetSelectionMode() !=
6080 wxGrid::wxGridSelectCells )
6081 {
6082 HighlightBlock( coords, coords );
6083 }
6084 }
6085 }
6086 }
6087 }
6088 }
6089
6090 // ------------ Left double click
6091 //
6092 else if ( event.LeftDClick() && coords != wxGridNoCellCoords )
6093 {
6094 DisableCellEditControl();
6095
6096 if ( XToEdgeOfCol(x) < 0 && YToEdgeOfRow(y) < 0 )
6097 {
6098 if ( !SendEvent( wxEVT_GRID_CELL_LEFT_DCLICK,
6099 coords.GetRow(),
6100 coords.GetCol(),
6101 event ) )
6102 {
6103 // we want double click to select a cell and start editing
6104 // (i.e. to behave in same way as sequence of two slow clicks):
6105 m_waitForSlowClick = true;
6106 }
6107 }
6108 }
6109
6110 // ------------ Left button released
6111 //
6112 else if ( event.LeftUp() )
6113 {
6114 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6115 {
6116 if (m_winCapture)
6117 {
6118 if (m_winCapture->HasCapture())
6119 m_winCapture->ReleaseMouse();
6120 m_winCapture = NULL;
6121 }
6122
6123 if ( coords == m_currentCellCoords && m_waitForSlowClick && CanEnableCellControl() )
6124 {
6125 ClearSelection();
6126 EnableCellEditControl();
6127
6128 wxGridCellAttr *attr = GetCellAttr(coords);
6129 wxGridCellEditor *editor = attr->GetEditor(this, coords.GetRow(), coords.GetCol());
6130 editor->StartingClick();
6131 editor->DecRef();
6132 attr->DecRef();
6133
6134 m_waitForSlowClick = false;
6135 }
6136 else if ( m_selectingTopLeft != wxGridNoCellCoords &&
6137 m_selectingBottomRight != wxGridNoCellCoords )
6138 {
6139 if ( m_selection )
6140 {
6141 m_selection->SelectBlock( m_selectingTopLeft.GetRow(),
6142 m_selectingTopLeft.GetCol(),
6143 m_selectingBottomRight.GetRow(),
6144 m_selectingBottomRight.GetCol(),
6145 event.ControlDown(),
6146 event.ShiftDown(),
6147 event.AltDown(),
6148 event.MetaDown() );
6149 }
6150
6151 m_selectingTopLeft = wxGridNoCellCoords;
6152 m_selectingBottomRight = wxGridNoCellCoords;
6153
6154 // Show the edit control, if it has been hidden for
6155 // drag-shrinking.
6156 ShowCellEditControl();
6157 }
6158 }
6159 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_ROW )
6160 {
6161 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6162 DoEndDragResizeRow();
6163
6164 // Note: we are ending the event *after* doing
6165 // default processing in this case
6166 //
6167 SendEvent( wxEVT_GRID_ROW_SIZE, m_dragRowOrCol, -1, event );
6168 }
6169 else if ( m_cursorMode == WXGRID_CURSOR_RESIZE_COL )
6170 {
6171 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6172 DoEndDragResizeCol();
6173
6174 // Note: we are ending the event *after* doing
6175 // default processing in this case
6176 //
6177 SendEvent( wxEVT_GRID_COL_SIZE, -1, m_dragRowOrCol, event );
6178 }
6179
6180 m_dragLastPos = -1;
6181 }
6182
6183 // ------------ Right button down
6184 //
6185 else if ( event.RightDown() && coords != wxGridNoCellCoords )
6186 {
6187 DisableCellEditControl();
6188 if ( !SendEvent( wxEVT_GRID_CELL_RIGHT_CLICK,
6189 coords.GetRow(),
6190 coords.GetCol(),
6191 event ) )
6192 {
6193 // no default action at the moment
6194 }
6195 }
6196
6197 // ------------ Right double click
6198 //
6199 else if ( event.RightDClick() && coords != wxGridNoCellCoords )
6200 {
6201 DisableCellEditControl();
6202 if ( !SendEvent( wxEVT_GRID_CELL_RIGHT_DCLICK,
6203 coords.GetRow(),
6204 coords.GetCol(),
6205 event ) )
6206 {
6207 // no default action at the moment
6208 }
6209 }
6210
6211 // ------------ Moving and no button action
6212 //
6213 else if ( event.Moving() && !event.IsButton() )
6214 {
6215 if ( coords.GetRow() < 0 || coords.GetCol() < 0 )
6216 {
6217 // out of grid cell area
6218 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6219 return;
6220 }
6221
6222 int dragRow = YToEdgeOfRow( y );
6223 int dragCol = XToEdgeOfCol( x );
6224
6225 // Dragging on the corner of a cell to resize in both
6226 // directions is not implemented yet...
6227 //
6228 if ( dragRow >= 0 && dragCol >= 0 )
6229 {
6230 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6231 return;
6232 }
6233
6234 if ( dragRow >= 0 )
6235 {
6236 m_dragRowOrCol = dragRow;
6237
6238 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6239 {
6240 if ( CanDragRowSize() && CanDragGridSize() )
6241 ChangeCursorMode(WXGRID_CURSOR_RESIZE_ROW);
6242 }
6243 }
6244 else if ( dragCol >= 0 )
6245 {
6246 m_dragRowOrCol = dragCol;
6247
6248 if ( m_cursorMode == WXGRID_CURSOR_SELECT_CELL )
6249 {
6250 if ( CanDragColSize() && CanDragGridSize() )
6251 ChangeCursorMode(WXGRID_CURSOR_RESIZE_COL);
6252 }
6253 }
6254 else // Neither on a row or col edge
6255 {
6256 if ( m_cursorMode != WXGRID_CURSOR_SELECT_CELL )
6257 {
6258 ChangeCursorMode(WXGRID_CURSOR_SELECT_CELL);
6259 }
6260 }
6261 }
6262}
6263
6264void wxGrid::DoEndDragResizeRow()
6265{
6266 if ( m_dragLastPos >= 0 )
6267 {
6268 // erase the last line and resize the row
6269 //
6270 int cw, ch, left, dummy;
6271 m_gridWin->GetClientSize( &cw, &ch );
6272 CalcUnscrolledPosition( 0, 0, &left, &dummy );
6273
6274 wxClientDC dc( m_gridWin );
6275 PrepareDC( dc );
6276 dc.SetLogicalFunction( wxINVERT );
6277 dc.DrawLine( left, m_dragLastPos, left + cw, m_dragLastPos );
6278 HideCellEditControl();
6279 SaveEditControlValue();
6280
6281 int rowTop = GetRowTop(m_dragRowOrCol);
6282 SetRowSize( m_dragRowOrCol,
6283 wxMax( m_dragLastPos - rowTop, m_minAcceptableRowHeight ) );
6284
6285 if ( !GetBatchCount() )
6286 {
6287 // Only needed to get the correct rect.y:
6288 wxRect rect ( CellToRect( m_dragRowOrCol, 0 ) );
6289 rect.x = 0;
6290 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
6291 rect.width = m_rowLabelWidth;
6292 rect.height = ch - rect.y;
6293 m_rowLabelWin->Refresh( true, &rect );
6294 rect.width = cw;
6295
6296 // if there is a multicell block, paint all of it
6297 if (m_table)
6298 {
6299 int i, cell_rows, cell_cols, subtract_rows = 0;
6300 int leftCol = XToCol(left);
6301 int rightCol = internalXToCol(left + cw);
6302 if (leftCol >= 0)
6303 {
6304 for (i=leftCol; i<rightCol; i++)
6305 {
6306 GetCellSize(m_dragRowOrCol, i, &cell_rows, &cell_cols);
6307 if (cell_rows < subtract_rows)
6308 subtract_rows = cell_rows;
6309 }
6310 rect.y = GetRowTop(m_dragRowOrCol + subtract_rows);
6311 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
6312 rect.height = ch - rect.y;
6313 }
6314 }
6315 m_gridWin->Refresh( false, &rect );
6316 }
6317
6318 ShowCellEditControl();
6319 }
6320}
6321
6322
6323void wxGrid::DoEndDragResizeCol()
6324{
6325 if ( m_dragLastPos >= 0 )
6326 {
6327 // erase the last line and resize the col
6328 //
6329 int cw, ch, dummy, top;
6330 m_gridWin->GetClientSize( &cw, &ch );
6331 CalcUnscrolledPosition( 0, 0, &dummy, &top );
6332
6333 wxClientDC dc( m_gridWin );
6334 PrepareDC( dc );
6335 dc.SetLogicalFunction( wxINVERT );
6336 dc.DrawLine( m_dragLastPos, top, m_dragLastPos, top + ch );
6337 HideCellEditControl();
6338 SaveEditControlValue();
6339
6340 int colLeft = GetColLeft(m_dragRowOrCol);
6341 SetColSize( m_dragRowOrCol,
6342 wxMax( m_dragLastPos - colLeft,
6343 GetColMinimalWidth(m_dragRowOrCol) ) );
6344
6345 if ( !GetBatchCount() )
6346 {
6347 // Only needed to get the correct rect.x:
6348 wxRect rect ( CellToRect( 0, m_dragRowOrCol ) );
6349 rect.y = 0;
6350 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
6351 rect.width = cw - rect.x;
6352 rect.height = m_colLabelHeight;
6353 m_colLabelWin->Refresh( true, &rect );
6354 rect.height = ch;
6355
6356 // if there is a multicell block, paint all of it
6357 if (m_table)
6358 {
6359 int i, cell_rows, cell_cols, subtract_cols = 0;
6360 int topRow = YToRow(top);
6361 int bottomRow = internalYToRow(top + cw);
6362 if (topRow >= 0)
6363 {
6364 for (i=topRow; i<bottomRow; i++)
6365 {
6366 GetCellSize(i, m_dragRowOrCol, &cell_rows, &cell_cols);
6367 if (cell_cols < subtract_cols)
6368 subtract_cols = cell_cols;
6369 }
6370
6371 rect.x = GetColLeft(m_dragRowOrCol + subtract_cols);
6372 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
6373 rect.width = cw - rect.x;
6374 }
6375 }
6376
6377 m_gridWin->Refresh( false, &rect );
6378 }
6379
6380 ShowCellEditControl();
6381 }
6382}
6383
6384void wxGrid::DoEndDragMoveCol()
6385{
6386 //The user clicked on the column but didn't actually drag
6387 if ( m_dragLastPos < 0 )
6388 {
6389 m_colLabelWin->Refresh(); //Do this to "unpress" the column
6390 return;
6391 }
6392
6393 int newPos;
6394 if ( m_moveToCol == -1 )
6395 newPos = m_numCols - 1;
6396 else
6397 {
6398 newPos = GetColPos( m_moveToCol );
6399 if ( newPos > GetColPos( m_dragRowOrCol ) )
6400 newPos--;
6401 }
6402
6403 SetColPos( m_dragRowOrCol, newPos );
6404}
6405
6406void wxGrid::SetColPos( int colID, int newPos )
6407{
6408 if ( m_colAt.IsEmpty() )
6409 {
6410 m_colAt.Alloc( m_numCols );
6411
6412 int i;
6413 for ( i = 0; i < m_numCols; i++ )
6414 {
6415 m_colAt.Add( i );
6416 }
6417 }
6418
6419 int oldPos = GetColPos( colID );
6420
6421 //Reshuffle the m_colAt array
6422 if ( newPos > oldPos )
6423 {
6424 int i;
6425 for ( i = oldPos; i < newPos; i++ )
6426 {
6427 m_colAt[i] = m_colAt[i+1];
6428 }
6429 }
6430 else
6431 {
6432 int i;
6433 for ( i = oldPos; i > newPos; i-- )
6434 {
6435 m_colAt[i] = m_colAt[i-1];
6436 }
6437 }
6438
6439 m_colAt[newPos] = colID;
6440
6441 //Recalculate the column rights
6442 if ( !m_colWidths.IsEmpty() )
6443 {
6444 int colRight = 0;
6445 int colPos;
6446 for ( colPos = 0; colPos < m_numCols; colPos++ )
6447 {
6448 int colID = GetColAt( colPos );
6449
6450 colRight += m_colWidths[colID];
6451 m_colRights[colID] = colRight;
6452 }
6453 }
6454
6455 m_colLabelWin->Refresh();
6456 m_gridWin->Refresh();
6457}
6458
6459
6460
6461void wxGrid::EnableDragColMove( bool enable )
6462{
6463 if ( m_canDragColMove == enable )
6464 return;
6465
6466 m_canDragColMove = enable;
6467
6468 if ( !m_canDragColMove )
6469 {
6470 m_colAt.Clear();
6471
6472 //Recalculate the column rights
6473 if ( !m_colWidths.IsEmpty() )
6474 {
6475 int colRight = 0;
6476 int colPos;
6477 for ( colPos = 0; colPos < m_numCols; colPos++ )
6478 {
6479 colRight += m_colWidths[colPos];
6480 m_colRights[colPos] = colRight;
6481 }
6482 }
6483
6484 m_colLabelWin->Refresh();
6485 m_gridWin->Refresh();
6486 }
6487}
6488
6489
6490//
6491// ------ interaction with data model
6492//
6493bool wxGrid::ProcessTableMessage( wxGridTableMessage& msg )
6494{
6495 switch ( msg.GetId() )
6496 {
6497 case wxGRIDTABLE_REQUEST_VIEW_GET_VALUES:
6498 return GetModelValues();
6499
6500 case wxGRIDTABLE_REQUEST_VIEW_SEND_VALUES:
6501 return SetModelValues();
6502
6503 case wxGRIDTABLE_NOTIFY_ROWS_INSERTED:
6504 case wxGRIDTABLE_NOTIFY_ROWS_APPENDED:
6505 case wxGRIDTABLE_NOTIFY_ROWS_DELETED:
6506 case wxGRIDTABLE_NOTIFY_COLS_INSERTED:
6507 case wxGRIDTABLE_NOTIFY_COLS_APPENDED:
6508 case wxGRIDTABLE_NOTIFY_COLS_DELETED:
6509 return Redimension( msg );
6510
6511 default:
6512 return false;
6513 }
6514}
6515
6516// The behaviour of this function depends on the grid table class
6517// Clear() function. For the default wxGridStringTable class the
6518// behavious is to replace all cell contents with wxEmptyString but
6519// not to change the number of rows or cols.
6520//
6521void wxGrid::ClearGrid()
6522{
6523 if ( m_table )
6524 {
6525 if (IsCellEditControlEnabled())
6526 DisableCellEditControl();
6527
6528 m_table->Clear();
6529 if (!GetBatchCount())
6530 m_gridWin->Refresh();
6531 }
6532}
6533
6534bool wxGrid::InsertRows( int pos, int numRows, bool WXUNUSED(updateLabels) )
6535{
6536 // TODO: something with updateLabels flag
6537
6538 if ( !m_created )
6539 {
6540 wxFAIL_MSG( wxT("Called wxGrid::InsertRows() before calling CreateGrid()") );
6541 return false;
6542 }
6543
6544 if ( m_table )
6545 {
6546 if (IsCellEditControlEnabled())
6547 DisableCellEditControl();
6548
6549 bool done = m_table->InsertRows( pos, numRows );
6550 return done;
6551
6552 // the table will have sent the results of the insert row
6553 // operation to this view object as a grid table message
6554 }
6555
6556 return false;
6557}
6558
6559bool wxGrid::AppendRows( int numRows, bool WXUNUSED(updateLabels) )
6560{
6561 // TODO: something with updateLabels flag
6562
6563 if ( !m_created )
6564 {
6565 wxFAIL_MSG( wxT("Called wxGrid::AppendRows() before calling CreateGrid()") );
6566 return false;
6567 }
6568
6569 if ( m_table )
6570 {
6571 bool done = m_table && m_table->AppendRows( numRows );
6572 return done;
6573
6574 // the table will have sent the results of the append row
6575 // operation to this view object as a grid table message
6576 }
6577
6578 return false;
6579}
6580
6581bool wxGrid::DeleteRows( int pos, int numRows, bool WXUNUSED(updateLabels) )
6582{
6583 // TODO: something with updateLabels flag
6584
6585 if ( !m_created )
6586 {
6587 wxFAIL_MSG( wxT("Called wxGrid::DeleteRows() before calling CreateGrid()") );
6588 return false;
6589 }
6590
6591 if ( m_table )
6592 {
6593 if (IsCellEditControlEnabled())
6594 DisableCellEditControl();
6595
6596 bool done = m_table->DeleteRows( pos, numRows );
6597 return done;
6598 // the table will have sent the results of the delete row
6599 // operation to this view object as a grid table message
6600 }
6601
6602 return false;
6603}
6604
6605bool wxGrid::InsertCols( int pos, int numCols, bool WXUNUSED(updateLabels) )
6606{
6607 // TODO: something with updateLabels flag
6608
6609 if ( !m_created )
6610 {
6611 wxFAIL_MSG( wxT("Called wxGrid::InsertCols() before calling CreateGrid()") );
6612 return false;
6613 }
6614
6615 if ( m_table )
6616 {
6617 if (IsCellEditControlEnabled())
6618 DisableCellEditControl();
6619
6620 bool done = m_table->InsertCols( pos, numCols );
6621 return done;
6622 // the table will have sent the results of the insert col
6623 // operation to this view object as a grid table message
6624 }
6625
6626 return false;
6627}
6628
6629bool wxGrid::AppendCols( int numCols, bool WXUNUSED(updateLabels) )
6630{
6631 // TODO: something with updateLabels flag
6632
6633 if ( !m_created )
6634 {
6635 wxFAIL_MSG( wxT("Called wxGrid::AppendCols() before calling CreateGrid()") );
6636 return false;
6637 }
6638
6639 if ( m_table )
6640 {
6641 bool done = m_table->AppendCols( numCols );
6642 return done;
6643 // the table will have sent the results of the append col
6644 // operation to this view object as a grid table message
6645 }
6646
6647 return false;
6648}
6649
6650bool wxGrid::DeleteCols( int pos, int numCols, bool WXUNUSED(updateLabels) )
6651{
6652 // TODO: something with updateLabels flag
6653
6654 if ( !m_created )
6655 {
6656 wxFAIL_MSG( wxT("Called wxGrid::DeleteCols() before calling CreateGrid()") );
6657 return false;
6658 }
6659
6660 if ( m_table )
6661 {
6662 if (IsCellEditControlEnabled())
6663 DisableCellEditControl();
6664
6665 bool done = m_table->DeleteCols( pos, numCols );
6666 return done;
6667 // the table will have sent the results of the delete col
6668 // operation to this view object as a grid table message
6669 }
6670
6671 return false;
6672}
6673
6674//
6675// ----- event handlers
6676//
6677
6678// Generate a grid event based on a mouse event and
6679// return the result of ProcessEvent()
6680//
6681int wxGrid::SendEvent( const wxEventType type,
6682 int row, int col,
6683 wxMouseEvent& mouseEv )
6684{
6685 bool claimed, vetoed;
6686
6687 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
6688 {
6689 int rowOrCol = (row == -1 ? col : row);
6690
6691 wxGridSizeEvent gridEvt( GetId(),
6692 type,
6693 this,
6694 rowOrCol,
6695 mouseEv.GetX() + GetRowLabelSize(),
6696 mouseEv.GetY() + GetColLabelSize(),
6697 mouseEv.ControlDown(),
6698 mouseEv.ShiftDown(),
6699 mouseEv.AltDown(),
6700 mouseEv.MetaDown() );
6701
6702 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6703 vetoed = !gridEvt.IsAllowed();
6704 }
6705 else if ( type == wxEVT_GRID_RANGE_SELECT )
6706 {
6707 // Right now, it should _never_ end up here!
6708 wxGridRangeSelectEvent gridEvt( GetId(),
6709 type,
6710 this,
6711 m_selectingTopLeft,
6712 m_selectingBottomRight,
6713 true,
6714 mouseEv.ControlDown(),
6715 mouseEv.ShiftDown(),
6716 mouseEv.AltDown(),
6717 mouseEv.MetaDown() );
6718
6719 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6720 vetoed = !gridEvt.IsAllowed();
6721 }
6722 else if ( type == wxEVT_GRID_LABEL_LEFT_CLICK ||
6723 type == wxEVT_GRID_LABEL_LEFT_DCLICK ||
6724 type == wxEVT_GRID_LABEL_RIGHT_CLICK ||
6725 type == wxEVT_GRID_LABEL_RIGHT_DCLICK )
6726 {
6727 wxPoint pos = mouseEv.GetPosition();
6728
6729 if ( mouseEv.GetEventObject() == GetGridRowLabelWindow() )
6730 pos.y += GetColLabelSize();
6731 if ( mouseEv.GetEventObject() == GetGridColLabelWindow() )
6732 pos.x += GetRowLabelSize();
6733
6734 wxGridEvent gridEvt( GetId(),
6735 type,
6736 this,
6737 row, col,
6738 pos.x,
6739 pos.y,
6740 false,
6741 mouseEv.ControlDown(),
6742 mouseEv.ShiftDown(),
6743 mouseEv.AltDown(),
6744 mouseEv.MetaDown() );
6745 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6746 vetoed = !gridEvt.IsAllowed();
6747 }
6748 else
6749 {
6750 wxGridEvent gridEvt( GetId(),
6751 type,
6752 this,
6753 row, col,
6754 mouseEv.GetX() + GetRowLabelSize(),
6755 mouseEv.GetY() + GetColLabelSize(),
6756 false,
6757 mouseEv.ControlDown(),
6758 mouseEv.ShiftDown(),
6759 mouseEv.AltDown(),
6760 mouseEv.MetaDown() );
6761 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6762 vetoed = !gridEvt.IsAllowed();
6763 }
6764
6765 // A Veto'd event may not be `claimed' so test this first
6766 if (vetoed)
6767 return -1;
6768
6769 return claimed ? 1 : 0;
6770}
6771
6772// Generate a grid event of specified type and return the result
6773// of ProcessEvent().
6774//
6775int wxGrid::SendEvent( const wxEventType type,
6776 int row, int col )
6777{
6778 bool claimed, vetoed;
6779
6780 if ( type == wxEVT_GRID_ROW_SIZE || type == wxEVT_GRID_COL_SIZE )
6781 {
6782 int rowOrCol = (row == -1 ? col : row);
6783
6784 wxGridSizeEvent gridEvt( GetId(), type, this, rowOrCol );
6785
6786 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6787 vetoed = !gridEvt.IsAllowed();
6788 }
6789 else
6790 {
6791 wxGridEvent gridEvt( GetId(), type, this, row, col );
6792
6793 claimed = GetEventHandler()->ProcessEvent(gridEvt);
6794 vetoed = !gridEvt.IsAllowed();
6795 }
6796
6797 // A Veto'd event may not be `claimed' so test this first
6798 if (vetoed)
6799 return -1;
6800
6801 return claimed ? 1 : 0;
6802}
6803
6804void wxGrid::OnPaint( wxPaintEvent& WXUNUSED(event) )
6805{
6806 // needed to prevent zillions of paint events on MSW
6807 wxPaintDC dc(this);
6808}
6809
6810void wxGrid::Refresh(bool eraseb, const wxRect* rect)
6811{
6812 // Don't do anything if between Begin/EndBatch...
6813 // EndBatch() will do all this on the last nested one anyway.
6814 if (! GetBatchCount())
6815 {
6816 // Refresh to get correct scrolled position:
6817 wxScrolledWindow::Refresh(eraseb, rect);
6818
6819 if (rect)
6820 {
6821 int rect_x, rect_y, rectWidth, rectHeight;
6822 int width_label, width_cell, height_label, height_cell;
6823 int x, y;
6824
6825 // Copy rectangle can get scroll offsets..
6826 rect_x = rect->GetX();
6827 rect_y = rect->GetY();
6828 rectWidth = rect->GetWidth();
6829 rectHeight = rect->GetHeight();
6830
6831 width_label = m_rowLabelWidth - rect_x;
6832 if (width_label > rectWidth)
6833 width_label = rectWidth;
6834
6835 height_label = m_colLabelHeight - rect_y;
6836 if (height_label > rectHeight)
6837 height_label = rectHeight;
6838
6839 if (rect_x > m_rowLabelWidth)
6840 {
6841 x = rect_x - m_rowLabelWidth;
6842 width_cell = rectWidth;
6843 }
6844 else
6845 {
6846 x = 0;
6847 width_cell = rectWidth - (m_rowLabelWidth - rect_x);
6848 }
6849
6850 if (rect_y > m_colLabelHeight)
6851 {
6852 y = rect_y - m_colLabelHeight;
6853 height_cell = rectHeight;
6854 }
6855 else
6856 {
6857 y = 0;
6858 height_cell = rectHeight - (m_colLabelHeight - rect_y);
6859 }
6860
6861 // Paint corner label part intersecting rect.
6862 if ( width_label > 0 && height_label > 0 )
6863 {
6864 wxRect anotherrect(rect_x, rect_y, width_label, height_label);
6865 m_cornerLabelWin->Refresh(eraseb, &anotherrect);
6866 }
6867
6868 // Paint col labels part intersecting rect.
6869 if ( width_cell > 0 && height_label > 0 )
6870 {
6871 wxRect anotherrect(x, rect_y, width_cell, height_label);
6872 m_colLabelWin->Refresh(eraseb, &anotherrect);
6873 }
6874
6875 // Paint row labels part intersecting rect.
6876 if ( width_label > 0 && height_cell > 0 )
6877 {
6878 wxRect anotherrect(rect_x, y, width_label, height_cell);
6879 m_rowLabelWin->Refresh(eraseb, &anotherrect);
6880 }
6881
6882 // Paint cell area part intersecting rect.
6883 if ( width_cell > 0 && height_cell > 0 )
6884 {
6885 wxRect anotherrect(x, y, width_cell, height_cell);
6886 m_gridWin->Refresh(eraseb, &anotherrect);
6887 }
6888 }
6889 else
6890 {
6891 m_cornerLabelWin->Refresh(eraseb, NULL);
6892 m_colLabelWin->Refresh(eraseb, NULL);
6893 m_rowLabelWin->Refresh(eraseb, NULL);
6894 m_gridWin->Refresh(eraseb, NULL);
6895 }
6896 }
6897}
6898
6899void wxGrid::OnSize( wxSizeEvent& event )
6900{
6901 // position the child windows
6902 CalcWindowSizes();
6903
6904 // don't call CalcDimensions() from here, the base class handles the size
6905 // changes itself
6906 event.Skip();
6907}
6908
6909void wxGrid::OnKeyDown( wxKeyEvent& event )
6910{
6911 if ( m_inOnKeyDown )
6912 {
6913 // shouldn't be here - we are going round in circles...
6914 //
6915 wxFAIL_MSG( wxT("wxGrid::OnKeyDown called while already active") );
6916 }
6917
6918 m_inOnKeyDown = true;
6919
6920 // propagate the event up and see if it gets processed
6921 wxWindow *parent = GetParent();
6922 wxKeyEvent keyEvt( event );
6923 keyEvt.SetEventObject( parent );
6924
6925 if ( !parent->GetEventHandler()->ProcessEvent( keyEvt ) )
6926 {
6927 if (GetLayoutDirection() == wxLayout_RightToLeft)
6928 {
6929 if (event.GetKeyCode() == WXK_RIGHT)
6930 event.m_keyCode = WXK_LEFT;
6931 else if (event.GetKeyCode() == WXK_LEFT)
6932 event.m_keyCode = WXK_RIGHT;
6933 }
6934
6935 // try local handlers
6936 switch ( event.GetKeyCode() )
6937 {
6938 case WXK_UP:
6939 if ( event.ControlDown() )
6940 MoveCursorUpBlock( event.ShiftDown() );
6941 else
6942 MoveCursorUp( event.ShiftDown() );
6943 break;
6944
6945 case WXK_DOWN:
6946 if ( event.ControlDown() )
6947 MoveCursorDownBlock( event.ShiftDown() );
6948 else
6949 MoveCursorDown( event.ShiftDown() );
6950 break;
6951
6952 case WXK_LEFT:
6953 if ( event.ControlDown() )
6954 MoveCursorLeftBlock( event.ShiftDown() );
6955 else
6956 MoveCursorLeft( event.ShiftDown() );
6957 break;
6958
6959 case WXK_RIGHT:
6960 if ( event.ControlDown() )
6961 MoveCursorRightBlock( event.ShiftDown() );
6962 else
6963 MoveCursorRight( event.ShiftDown() );
6964 break;
6965
6966 case WXK_RETURN:
6967 case WXK_NUMPAD_ENTER:
6968 if ( event.ControlDown() )
6969 {
6970 event.Skip(); // to let the edit control have the return
6971 }
6972 else
6973 {
6974 if ( GetGridCursorRow() < GetNumberRows()-1 )
6975 {
6976 MoveCursorDown( event.ShiftDown() );
6977 }
6978 else
6979 {
6980 // at the bottom of a column
6981 DisableCellEditControl();
6982 }
6983 }
6984 break;
6985
6986 case WXK_ESCAPE:
6987 ClearSelection();
6988 break;
6989
6990 case WXK_TAB:
6991 if (event.ShiftDown())
6992 {
6993 if ( GetGridCursorCol() > 0 )
6994 {
6995 MoveCursorLeft( false );
6996 }
6997 else
6998 {
6999 // at left of grid
7000 DisableCellEditControl();
7001 }
7002 }
7003 else
7004 {
7005 if ( GetGridCursorCol() < GetNumberCols() - 1 )
7006 {
7007 MoveCursorRight( false );
7008 }
7009 else
7010 {
7011 // at right of grid
7012 DisableCellEditControl();
7013 }
7014 }
7015 break;
7016
7017 case WXK_HOME:
7018 if ( event.ControlDown() )
7019 {
7020 MakeCellVisible( 0, 0 );
7021 SetCurrentCell( 0, 0 );
7022 }
7023 else
7024 {
7025 event.Skip();
7026 }
7027 break;
7028
7029 case WXK_END:
7030 if ( event.ControlDown() )
7031 {
7032 MakeCellVisible( m_numRows - 1, m_numCols - 1 );
7033 SetCurrentCell( m_numRows - 1, m_numCols - 1 );
7034 }
7035 else
7036 {
7037 event.Skip();
7038 }
7039 break;
7040
7041 case WXK_PAGEUP:
7042 MovePageUp();
7043 break;
7044
7045 case WXK_PAGEDOWN:
7046 MovePageDown();
7047 break;
7048
7049 case WXK_SPACE:
7050 if ( event.ControlDown() )
7051 {
7052 if ( m_selection )
7053 {
7054 m_selection->ToggleCellSelection(
7055 m_currentCellCoords.GetRow(),
7056 m_currentCellCoords.GetCol(),
7057 event.ControlDown(),
7058 event.ShiftDown(),
7059 event.AltDown(),
7060 event.MetaDown() );
7061 }
7062 break;
7063 }
7064
7065 if ( !IsEditable() )
7066 MoveCursorRight( false );
7067 else
7068 event.Skip();
7069 break;
7070
7071 default:
7072 event.Skip();
7073 break;
7074 }
7075 }
7076
7077 m_inOnKeyDown = false;
7078}
7079
7080void wxGrid::OnKeyUp( wxKeyEvent& event )
7081{
7082 // try local handlers
7083 //
7084 if ( event.GetKeyCode() == WXK_SHIFT )
7085 {
7086 if ( m_selectingTopLeft != wxGridNoCellCoords &&
7087 m_selectingBottomRight != wxGridNoCellCoords )
7088 {
7089 if ( m_selection )
7090 {
7091 m_selection->SelectBlock(
7092 m_selectingTopLeft.GetRow(),
7093 m_selectingTopLeft.GetCol(),
7094 m_selectingBottomRight.GetRow(),
7095 m_selectingBottomRight.GetCol(),
7096 event.ControlDown(),
7097 true,
7098 event.AltDown(),
7099 event.MetaDown() );
7100 }
7101 }
7102
7103 m_selectingTopLeft = wxGridNoCellCoords;
7104 m_selectingBottomRight = wxGridNoCellCoords;
7105 m_selectingKeyboard = wxGridNoCellCoords;
7106 }
7107}
7108
7109void wxGrid::OnChar( wxKeyEvent& event )
7110{
7111 // is it possible to edit the current cell at all?
7112 if ( !IsCellEditControlEnabled() && CanEnableCellControl() )
7113 {
7114 // yes, now check whether the cells editor accepts the key
7115 int row = m_currentCellCoords.GetRow();
7116 int col = m_currentCellCoords.GetCol();
7117 wxGridCellAttr *attr = GetCellAttr(row, col);
7118 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7119
7120 // <F2> is special and will always start editing, for
7121 // other keys - ask the editor itself
7122 if ( (event.GetKeyCode() == WXK_F2 && !event.HasModifiers())
7123 || editor->IsAcceptedKey(event) )
7124 {
7125 // ensure cell is visble
7126 MakeCellVisible(row, col);
7127 EnableCellEditControl();
7128
7129 // a problem can arise if the cell is not completely
7130 // visible (even after calling MakeCellVisible the
7131 // control is not created and calling StartingKey will
7132 // crash the app
7133 if ( event.GetKeyCode() != WXK_F2 && editor->IsCreated() && m_cellEditCtrlEnabled )
7134 editor->StartingKey(event);
7135 }
7136 else
7137 {
7138 event.Skip();
7139 }
7140
7141 editor->DecRef();
7142 attr->DecRef();
7143 }
7144 else
7145 {
7146 event.Skip();
7147 }
7148}
7149
7150void wxGrid::OnEraseBackground(wxEraseEvent&)
7151{
7152}
7153
7154void wxGrid::SetCurrentCell( const wxGridCellCoords& coords )
7155{
7156 if ( SendEvent( wxEVT_GRID_SELECT_CELL, coords.GetRow(), coords.GetCol() ) )
7157 {
7158 // the event has been intercepted - do nothing
7159 return;
7160 }
7161
7162#if !(defined(__WXMAC__) && wxMAC_USE_CORE_GRAPHICS)
7163 wxClientDC dc( m_gridWin );
7164 PrepareDC( dc );
7165#endif
7166
7167 if ( m_currentCellCoords != wxGridNoCellCoords )
7168 {
7169 DisableCellEditControl();
7170
7171 if ( IsVisible( m_currentCellCoords, false ) )
7172 {
7173 wxRect r;
7174 r = BlockToDeviceRect( m_currentCellCoords, m_currentCellCoords );
7175 if ( !m_gridLinesEnabled )
7176 {
7177 r.x--;
7178 r.y--;
7179 r.width++;
7180 r.height++;
7181 }
7182
7183 wxGridCellCoordsArray cells = CalcCellsExposed( r );
7184
7185 // Otherwise refresh redraws the highlight!
7186 m_currentCellCoords = coords;
7187
7188#if defined(__WXMAC__) && wxMAC_USE_CORE_GRAPHICS
7189 m_gridWin->Refresh(true /*, & r */);
7190#else
7191 DrawGridCellArea( dc, cells );
7192 DrawAllGridLines( dc, r );
7193#endif
7194 }
7195 }
7196
7197 m_currentCellCoords = coords;
7198
7199 wxGridCellAttr *attr = GetCellAttr( coords );
7200#if !(defined(__WXMAC__) && wxMAC_USE_CORE_GRAPHICS)
7201 DrawCellHighlight( dc, attr );
7202#endif
7203 attr->DecRef();
7204}
7205
7206void wxGrid::HighlightBlock( int topRow, int leftCol, int bottomRow, int rightCol )
7207{
7208 int temp;
7209 wxGridCellCoords updateTopLeft, updateBottomRight;
7210
7211 if ( m_selection )
7212 {
7213 if ( m_selection->GetSelectionMode() == wxGrid::wxGridSelectRows )
7214 {
7215 leftCol = 0;
7216 rightCol = GetNumberCols() - 1;
7217 }
7218 else if ( m_selection->GetSelectionMode() == wxGrid::wxGridSelectColumns )
7219 {
7220 topRow = 0;
7221 bottomRow = GetNumberRows() - 1;
7222 }
7223 }
7224
7225 if ( topRow > bottomRow )
7226 {
7227 temp = topRow;
7228 topRow = bottomRow;
7229 bottomRow = temp;
7230 }
7231
7232 if ( leftCol > rightCol )
7233 {
7234 temp = leftCol;
7235 leftCol = rightCol;
7236 rightCol = temp;
7237 }
7238
7239 updateTopLeft = wxGridCellCoords( topRow, leftCol );
7240 updateBottomRight = wxGridCellCoords( bottomRow, rightCol );
7241
7242 // First the case that we selected a completely new area
7243 if ( m_selectingTopLeft == wxGridNoCellCoords ||
7244 m_selectingBottomRight == wxGridNoCellCoords )
7245 {
7246 wxRect rect;
7247 rect = BlockToDeviceRect( wxGridCellCoords ( topRow, leftCol ),
7248 wxGridCellCoords ( bottomRow, rightCol ) );
7249 m_gridWin->Refresh( false, &rect );
7250 }
7251
7252 // Now handle changing an existing selection area.
7253 else if ( m_selectingTopLeft != updateTopLeft ||
7254 m_selectingBottomRight != updateBottomRight )
7255 {
7256 // Compute two optimal update rectangles:
7257 // Either one rectangle is a real subset of the
7258 // other, or they are (almost) disjoint!
7259 wxRect rect[4];
7260 bool need_refresh[4];
7261 need_refresh[0] =
7262 need_refresh[1] =
7263 need_refresh[2] =
7264 need_refresh[3] = false;
7265 int i;
7266
7267 // Store intermediate values
7268 wxCoord oldLeft = m_selectingTopLeft.GetCol();
7269 wxCoord oldTop = m_selectingTopLeft.GetRow();
7270 wxCoord oldRight = m_selectingBottomRight.GetCol();
7271 wxCoord oldBottom = m_selectingBottomRight.GetRow();
7272
7273 // Determine the outer/inner coordinates.
7274 if (oldLeft > leftCol)
7275 {
7276 temp = oldLeft;
7277 oldLeft = leftCol;
7278 leftCol = temp;
7279 }
7280 if (oldTop > topRow )
7281 {
7282 temp = oldTop;
7283 oldTop = topRow;
7284 topRow = temp;
7285 }
7286 if (oldRight < rightCol )
7287 {
7288 temp = oldRight;
7289 oldRight = rightCol;
7290 rightCol = temp;
7291 }
7292 if (oldBottom < bottomRow)
7293 {
7294 temp = oldBottom;
7295 oldBottom = bottomRow;
7296 bottomRow = temp;
7297 }
7298
7299 // Now, either the stuff marked old is the outer
7300 // rectangle or we don't have a situation where one
7301 // is contained in the other.
7302
7303 if ( oldLeft < leftCol )
7304 {
7305 // Refresh the newly selected or deselected
7306 // area to the left of the old or new selection.
7307 need_refresh[0] = true;
7308 rect[0] = BlockToDeviceRect(
7309 wxGridCellCoords( oldTop, oldLeft ),
7310 wxGridCellCoords( oldBottom, leftCol - 1 ) );
7311 }
7312
7313 if ( oldTop < topRow )
7314 {
7315 // Refresh the newly selected or deselected
7316 // area above the old or new selection.
7317 need_refresh[1] = true;
7318 rect[1] = BlockToDeviceRect(
7319 wxGridCellCoords( oldTop, leftCol ),
7320 wxGridCellCoords( topRow - 1, rightCol ) );
7321 }
7322
7323 if ( oldRight > rightCol )
7324 {
7325 // Refresh the newly selected or deselected
7326 // area to the right of the old or new selection.
7327 need_refresh[2] = true;
7328 rect[2] = BlockToDeviceRect(
7329 wxGridCellCoords( oldTop, rightCol + 1 ),
7330 wxGridCellCoords( oldBottom, oldRight ) );
7331 }
7332
7333 if ( oldBottom > bottomRow )
7334 {
7335 // Refresh the newly selected or deselected
7336 // area below the old or new selection.
7337 need_refresh[3] = true;
7338 rect[3] = BlockToDeviceRect(
7339 wxGridCellCoords( bottomRow + 1, leftCol ),
7340 wxGridCellCoords( oldBottom, rightCol ) );
7341 }
7342
7343 // various Refresh() calls
7344 for (i = 0; i < 4; i++ )
7345 if ( need_refresh[i] && rect[i] != wxGridNoCellRect )
7346 m_gridWin->Refresh( false, &(rect[i]) );
7347 }
7348
7349 // change selection
7350 m_selectingTopLeft = updateTopLeft;
7351 m_selectingBottomRight = updateBottomRight;
7352}
7353
7354//
7355// ------ functions to get/send data (see also public functions)
7356//
7357
7358bool wxGrid::GetModelValues()
7359{
7360 // Hide the editor, so it won't hide a changed value.
7361 HideCellEditControl();
7362
7363 if ( m_table )
7364 {
7365 // all we need to do is repaint the grid
7366 //
7367 m_gridWin->Refresh();
7368 return true;
7369 }
7370
7371 return false;
7372}
7373
7374bool wxGrid::SetModelValues()
7375{
7376 int row, col;
7377
7378 // Disable the editor, so it won't hide a changed value.
7379 // Do we also want to save the current value of the editor first?
7380 // I think so ...
7381 DisableCellEditControl();
7382
7383 if ( m_table )
7384 {
7385 for ( row = 0; row < m_numRows; row++ )
7386 {
7387 for ( col = 0; col < m_numCols; col++ )
7388 {
7389 m_table->SetValue( row, col, GetCellValue(row, col) );
7390 }
7391 }
7392
7393 return true;
7394 }
7395
7396 return false;
7397}
7398
7399// Note - this function only draws cells that are in the list of
7400// exposed cells (usually set from the update region by
7401// CalcExposedCells)
7402//
7403void wxGrid::DrawGridCellArea( wxDC& dc, const wxGridCellCoordsArray& cells )
7404{
7405 if ( !m_numRows || !m_numCols )
7406 return;
7407
7408 int i, numCells = cells.GetCount();
7409 int row, col, cell_rows, cell_cols;
7410 wxGridCellCoordsArray redrawCells;
7411
7412 for ( i = numCells - 1; i >= 0; i-- )
7413 {
7414 row = cells[i].GetRow();
7415 col = cells[i].GetCol();
7416 GetCellSize( row, col, &cell_rows, &cell_cols );
7417
7418 // If this cell is part of a multicell block, find owner for repaint
7419 if ( cell_rows <= 0 || cell_cols <= 0 )
7420 {
7421 wxGridCellCoords cell( row + cell_rows, col + cell_cols );
7422 bool marked = false;
7423 for ( int j = 0; j < numCells; j++ )
7424 {
7425 if ( cell == cells[j] )
7426 {
7427 marked = true;
7428 break;
7429 }
7430 }
7431
7432 if (!marked)
7433 {
7434 int count = redrawCells.GetCount();
7435 for (int j = 0; j < count; j++)
7436 {
7437 if ( cell == redrawCells[j] )
7438 {
7439 marked = true;
7440 break;
7441 }
7442 }
7443
7444 if (!marked)
7445 redrawCells.Add( cell );
7446 }
7447
7448 // don't bother drawing this cell
7449 continue;
7450 }
7451
7452 // If this cell is empty, find cell to left that might want to overflow
7453 if (m_table && m_table->IsEmptyCell(row, col))
7454 {
7455 for ( int l = 0; l < cell_rows; l++ )
7456 {
7457 // find a cell in this row to leave already marked for repaint
7458 int left = col;
7459 for (int k = 0; k < int(redrawCells.GetCount()); k++)
7460 if ((redrawCells[k].GetCol() < left) &&
7461 (redrawCells[k].GetRow() == row))
7462 {
7463 left = redrawCells[k].GetCol();
7464 }
7465
7466 if (left == col)
7467 left = 0; // oh well
7468
7469 for (int j = col - 1; j >= left; j--)
7470 {
7471 if (!m_table->IsEmptyCell(row + l, j))
7472 {
7473 if (GetCellOverflow(row + l, j))
7474 {
7475 wxGridCellCoords cell(row + l, j);
7476 bool marked = false;
7477
7478 for (int k = 0; k < numCells; k++)
7479 {
7480 if ( cell == cells[k] )
7481 {
7482 marked = true;
7483 break;
7484 }
7485 }
7486
7487 if (!marked)
7488 {
7489 int count = redrawCells.GetCount();
7490 for (int k = 0; k < count; k++)
7491 {
7492 if ( cell == redrawCells[k] )
7493 {
7494 marked = true;
7495 break;
7496 }
7497 }
7498 if (!marked)
7499 redrawCells.Add( cell );
7500 }
7501 }
7502 break;
7503 }
7504 }
7505 }
7506 }
7507
7508 DrawCell( dc, cells[i] );
7509 }
7510
7511 numCells = redrawCells.GetCount();
7512
7513 for ( i = numCells - 1; i >= 0; i-- )
7514 {
7515 DrawCell( dc, redrawCells[i] );
7516 }
7517}
7518
7519void wxGrid::DrawGridSpace( wxDC& dc )
7520{
7521 int cw, ch;
7522 m_gridWin->GetClientSize( &cw, &ch );
7523
7524 int right, bottom;
7525 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7526
7527 int rightCol = m_numCols > 0 ? GetColRight(GetColAt( m_numCols - 1 )) : 0;
7528 int bottomRow = m_numRows > 0 ? GetRowBottom(m_numRows - 1) : 0;
7529
7530 if ( right > rightCol || bottom > bottomRow )
7531 {
7532 int left, top;
7533 CalcUnscrolledPosition( 0, 0, &left, &top );
7534
7535 dc.SetBrush( wxBrush(GetDefaultCellBackgroundColour(), wxSOLID) );
7536 dc.SetPen( *wxTRANSPARENT_PEN );
7537
7538 if ( right > rightCol )
7539 {
7540 dc.DrawRectangle( rightCol, top, right - rightCol, ch );
7541 }
7542
7543 if ( bottom > bottomRow )
7544 {
7545 dc.DrawRectangle( left, bottomRow, cw, bottom - bottomRow );
7546 }
7547 }
7548}
7549
7550void wxGrid::DrawCell( wxDC& dc, const wxGridCellCoords& coords )
7551{
7552 int row = coords.GetRow();
7553 int col = coords.GetCol();
7554
7555 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7556 return;
7557
7558 // we draw the cell border ourselves
7559#if !WXGRID_DRAW_LINES
7560 if ( m_gridLinesEnabled )
7561 DrawCellBorder( dc, coords );
7562#endif
7563
7564 wxGridCellAttr* attr = GetCellAttr(row, col);
7565
7566 bool isCurrent = coords == m_currentCellCoords;
7567
7568 wxRect rect = CellToRect( row, col );
7569
7570 // if the editor is shown, we should use it and not the renderer
7571 // Note: However, only if it is really _shown_, i.e. not hidden!
7572 if ( isCurrent && IsCellEditControlShown() )
7573 {
7574 // NB: this "#if..." is temporary and fixes a problem where the
7575 // edit control is erased by this code after being rendered.
7576 // On wxMac (QD build only), the cell editor is a wxTextCntl and is rendered
7577 // implicitly, causing this out-of order render.
7578#if !defined(__WXMAC__)
7579 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
7580 editor->PaintBackground(rect, attr);
7581 editor->DecRef();
7582#endif
7583 }
7584 else
7585 {
7586 // but all the rest is drawn by the cell renderer and hence may be customized
7587 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
7588 renderer->Draw(*this, *attr, dc, rect, row, col, IsInSelection(coords));
7589 renderer->DecRef();
7590 }
7591
7592 attr->DecRef();
7593}
7594
7595void wxGrid::DrawCellHighlight( wxDC& dc, const wxGridCellAttr *attr )
7596{
7597 int row = m_currentCellCoords.GetRow();
7598 int col = m_currentCellCoords.GetCol();
7599
7600 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7601 return;
7602
7603 wxRect rect = CellToRect(row, col);
7604
7605 // hmmm... what could we do here to show that the cell is disabled?
7606 // for now, I just draw a thinner border than for the other ones, but
7607 // it doesn't look really good
7608
7609 int penWidth = attr->IsReadOnly() ? m_cellHighlightROPenWidth : m_cellHighlightPenWidth;
7610
7611 if (penWidth > 0)
7612 {
7613 // The center of the drawn line is where the position/width/height of
7614 // the rectangle is actually at (on wxMSW at least), so the
7615 // size of the rectangle is reduced to compensate for the thickness of
7616 // the line. If this is too strange on non-wxMSW platforms then
7617 // please #ifdef this appropriately.
7618 rect.x += penWidth / 2;
7619 rect.y += penWidth / 2;
7620 rect.width -= penWidth - 1;
7621 rect.height -= penWidth - 1;
7622
7623 // Now draw the rectangle
7624 // use the cellHighlightColour if the cell is inside a selection, this
7625 // will ensure the cell is always visible.
7626 dc.SetPen(wxPen(IsInSelection(row,col) ? m_selectionForeground : m_cellHighlightColour, penWidth, wxSOLID));
7627 dc.SetBrush(*wxTRANSPARENT_BRUSH);
7628 dc.DrawRectangle(rect);
7629 }
7630
7631#if 0
7632 // VZ: my experiments with 3D borders...
7633
7634 // how to properly set colours for arbitrary bg?
7635 wxCoord x1 = rect.x,
7636 y1 = rect.y,
7637 x2 = rect.x + rect.width - 1,
7638 y2 = rect.y + rect.height - 1;
7639
7640 dc.SetPen(*wxWHITE_PEN);
7641 dc.DrawLine(x1, y1, x2, y1);
7642 dc.DrawLine(x1, y1, x1, y2);
7643
7644 dc.DrawLine(x1 + 1, y2 - 1, x2 - 1, y2 - 1);
7645 dc.DrawLine(x2 - 1, y1 + 1, x2 - 1, y2);
7646
7647 dc.SetPen(*wxBLACK_PEN);
7648 dc.DrawLine(x1, y2, x2, y2);
7649 dc.DrawLine(x2, y1, x2, y2 + 1);
7650#endif
7651}
7652
7653wxPen wxGrid::GetDefaultGridLinePen()
7654{
7655 return wxPen(GetGridLineColour(), 1, wxSOLID);
7656}
7657
7658wxPen wxGrid::GetRowGridLinePen(int WXUNUSED(row))
7659{
7660 return GetDefaultGridLinePen();
7661}
7662
7663wxPen wxGrid::GetColGridLinePen(int WXUNUSED(col))
7664{
7665 return GetDefaultGridLinePen();
7666}
7667
7668void wxGrid::DrawCellBorder( wxDC& dc, const wxGridCellCoords& coords )
7669{
7670 int row = coords.GetRow();
7671 int col = coords.GetCol();
7672 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
7673 return;
7674
7675
7676 wxRect rect = CellToRect( row, col );
7677
7678 // right hand border
7679 dc.SetPen( GetColGridLinePen(col) );
7680 dc.DrawLine( rect.x + rect.width, rect.y,
7681 rect.x + rect.width, rect.y + rect.height + 1 );
7682
7683 // bottom border
7684 dc.SetPen( GetRowGridLinePen(row) );
7685 dc.DrawLine( rect.x, rect.y + rect.height,
7686 rect.x + rect.width, rect.y + rect.height);
7687}
7688
7689void wxGrid::DrawHighlight(wxDC& dc, const wxGridCellCoordsArray& cells)
7690{
7691 // This if block was previously in wxGrid::OnPaint but that doesn't
7692 // seem to get called under wxGTK - MB
7693 //
7694 if ( m_currentCellCoords == wxGridNoCellCoords &&
7695 m_numRows && m_numCols )
7696 {
7697 m_currentCellCoords.Set(0, 0);
7698 }
7699
7700 if ( IsCellEditControlShown() )
7701 {
7702 // don't show highlight when the edit control is shown
7703 return;
7704 }
7705
7706 // if the active cell was repainted, repaint its highlight too because it
7707 // might have been damaged by the grid lines
7708 size_t count = cells.GetCount();
7709 for ( size_t n = 0; n < count; n++ )
7710 {
7711 if ( cells[n] == m_currentCellCoords )
7712 {
7713 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
7714 DrawCellHighlight(dc, attr);
7715 attr->DecRef();
7716
7717 break;
7718 }
7719 }
7720}
7721
7722// TODO: remove this ???
7723// This is used to redraw all grid lines e.g. when the grid line colour
7724// has been changed
7725//
7726void wxGrid::DrawAllGridLines( wxDC& dc, const wxRegion & WXUNUSED(reg) )
7727{
7728#if !WXGRID_DRAW_LINES
7729 return;
7730#endif
7731
7732 if ( !m_gridLinesEnabled || !m_numRows || !m_numCols )
7733 return;
7734
7735 int top, bottom, left, right;
7736
7737#if 0 //#ifndef __WXGTK__
7738 if (reg.IsEmpty())
7739 {
7740 int cw, ch;
7741 m_gridWin->GetClientSize(&cw, &ch);
7742
7743 // virtual coords of visible area
7744 //
7745 CalcUnscrolledPosition( 0, 0, &left, &top );
7746 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7747 }
7748 else
7749 {
7750 wxCoord x, y, w, h;
7751 reg.GetBox(x, y, w, h);
7752 CalcUnscrolledPosition( x, y, &left, &top );
7753 CalcUnscrolledPosition( x + w, y + h, &right, &bottom );
7754 }
7755#else
7756 int cw, ch;
7757 m_gridWin->GetClientSize(&cw, &ch);
7758 CalcUnscrolledPosition( 0, 0, &left, &top );
7759 CalcUnscrolledPosition( cw, ch, &right, &bottom );
7760#endif
7761
7762 // avoid drawing grid lines past the last row and col
7763 //
7764 right = wxMin( right, GetColRight(GetColAt( m_numCols - 1 )) );
7765 bottom = wxMin( bottom, GetRowBottom(m_numRows - 1) );
7766
7767 // no gridlines inside multicells, clip them out
7768 int leftCol = GetColPos( internalXToCol(left) );
7769 int topRow = internalYToRow(top);
7770 int rightCol = GetColPos( internalXToCol(right) );
7771 int bottomRow = internalYToRow(bottom);
7772
7773#if !defined(__WXMAC__) || wxMAC_USE_CORE_GRAPHICS
7774 wxRegion clippedcells(0, 0, cw, ch);
7775
7776 int i, j, cell_rows, cell_cols;
7777 wxRect rect;
7778
7779 for (j=topRow; j<=bottomRow; j++)
7780 {
7781 int colPos;
7782 for (colPos=leftCol; colPos<=rightCol; colPos++)
7783 {
7784 i = GetColAt( colPos );
7785
7786 GetCellSize( j, i, &cell_rows, &cell_cols );
7787 if ((cell_rows > 1) || (cell_cols > 1))
7788 {
7789 rect = CellToRect(j,i);
7790 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
7791 clippedcells.Subtract(rect);
7792 }
7793 else if ((cell_rows < 0) || (cell_cols < 0))
7794 {
7795 rect = CellToRect(j + cell_rows, i + cell_cols);
7796 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
7797 clippedcells.Subtract(rect);
7798 }
7799 }
7800 }
7801#else
7802 wxRegion clippedcells( left, top, right - left, bottom - top );
7803
7804 int i, j, cell_rows, cell_cols;
7805 wxRect rect;
7806
7807 for (j=topRow; j<=bottomRow; j++)
7808 {
7809 for (i=leftCol; i<=rightCol; i++)
7810 {
7811 GetCellSize( j, i, &cell_rows, &cell_cols );
7812 if ((cell_rows > 1) || (cell_cols > 1))
7813 {
7814 rect = CellToRect(j, i);
7815 clippedcells.Subtract(rect);
7816 }
7817 else if ((cell_rows < 0) || (cell_cols < 0))
7818 {
7819 rect = CellToRect(j + cell_rows, i + cell_cols);
7820 clippedcells.Subtract(rect);
7821 }
7822 }
7823 }
7824#endif
7825
7826 dc.SetClippingRegion( clippedcells );
7827
7828
7829 // horizontal grid lines
7830 //
7831 // already declared above - int i;
7832 for ( i = internalYToRow(top); i < m_numRows; i++ )
7833 {
7834 int bot = GetRowBottom(i) - 1;
7835
7836 if ( bot > bottom )
7837 {
7838 break;
7839 }
7840
7841 if ( bot >= top )
7842 {
7843 dc.SetPen( GetRowGridLinePen(i) );
7844 dc.DrawLine( left, bot, right, bot );
7845 }
7846 }
7847
7848 // vertical grid lines
7849 //
7850 int colPos;
7851 for ( colPos = leftCol; colPos < m_numCols; colPos++ )
7852 {
7853 i = GetColAt( colPos );
7854
7855 int colRight = GetColRight(i);
7856#ifdef __WXGTK__
7857 if (GetLayoutDirection() != wxLayout_RightToLeft)
7858#endif
7859 colRight--;
7860
7861 if ( colRight > right )
7862 {
7863 break;
7864 }
7865
7866 if ( colRight >= left )
7867 {
7868 dc.SetPen( GetColGridLinePen(i) );
7869 dc.DrawLine( colRight, top, colRight, bottom );
7870 }
7871 }
7872
7873 dc.DestroyClippingRegion();
7874}
7875
7876void wxGrid::DrawRowLabels( wxDC& dc, const wxArrayInt& rows)
7877{
7878 if ( !m_numRows )
7879 return;
7880
7881 size_t i;
7882 size_t numLabels = rows.GetCount();
7883
7884 for ( i = 0; i < numLabels; i++ )
7885 {
7886 DrawRowLabel( dc, rows[i] );
7887 }
7888}
7889
7890void wxGrid::DrawRowLabel( wxDC& dc, int row )
7891{
7892 if ( GetRowHeight(row) <= 0 || m_rowLabelWidth <= 0 )
7893 return;
7894
7895 wxRect rect;
7896
7897#if 0
7898def __WXGTK20__
7899 rect.SetX( 1 );
7900 rect.SetY( GetRowTop(row) + 1 );
7901 rect.SetWidth( m_rowLabelWidth - 2 );
7902 rect.SetHeight( GetRowHeight(row) - 2 );
7903
7904 CalcScrolledPosition( 0, rect.y, NULL, &rect.y );
7905
7906 wxWindowDC *win_dc = (wxWindowDC*) &dc;
7907
7908 wxRendererNative::Get().DrawHeaderButton( win_dc->m_owner, dc, rect, 0 );
7909#else
7910 int rowTop = GetRowTop(row),
7911 rowBottom = GetRowBottom(row) - 1;
7912
7913 dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW), 1, wxSOLID) );
7914 dc.DrawLine( m_rowLabelWidth - 1, rowTop, m_rowLabelWidth - 1, rowBottom );
7915 dc.DrawLine( 0, rowTop, 0, rowBottom );
7916 dc.DrawLine( 0, rowBottom, m_rowLabelWidth, rowBottom );
7917
7918 dc.SetPen( *wxWHITE_PEN );
7919 dc.DrawLine( 1, rowTop, 1, rowBottom );
7920 dc.DrawLine( 1, rowTop, m_rowLabelWidth - 1, rowTop );
7921#endif
7922
7923 dc.SetBackgroundMode( wxTRANSPARENT );
7924 dc.SetTextForeground( GetLabelTextColour() );
7925 dc.SetFont( GetLabelFont() );
7926
7927 int hAlign, vAlign;
7928 GetRowLabelAlignment( &hAlign, &vAlign );
7929
7930 rect.SetX( 2 );
7931 rect.SetY( GetRowTop(row) + 2 );
7932 rect.SetWidth( m_rowLabelWidth - 4 );
7933 rect.SetHeight( GetRowHeight(row) - 4 );
7934 DrawTextRectangle( dc, GetRowLabelValue( row ), rect, hAlign, vAlign );
7935}
7936
7937void wxGrid::DrawColLabels( wxDC& dc,const wxArrayInt& cols )
7938{
7939 if ( !m_numCols )
7940 return;
7941
7942 size_t i;
7943 size_t numLabels = cols.GetCount();
7944
7945 for ( i = 0; i < numLabels; i++ )
7946 {
7947 DrawColLabel( dc, cols[i] );
7948 }
7949}
7950
7951void wxGrid::DrawColLabel( wxDC& dc, int col )
7952{
7953 if ( GetColWidth(col) <= 0 || m_colLabelHeight <= 0 )
7954 return;
7955
7956 int colLeft = GetColLeft(col);
7957
7958 wxRect rect;
7959
7960#if 0
7961def __WXGTK20__
7962 rect.SetX( colLeft + 1 );
7963 rect.SetY( 1 );
7964 rect.SetWidth( GetColWidth(col) - 2 );
7965 rect.SetHeight( m_colLabelHeight - 2 );
7966
7967 wxWindowDC *win_dc = (wxWindowDC*) &dc;
7968
7969 wxRendererNative::Get().DrawHeaderButton( win_dc->m_owner, dc, rect, 0 );
7970#else
7971 int colRight = GetColRight(col) - 1;
7972
7973 dc.SetPen( wxPen(wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW), 1, wxSOLID) );
7974 dc.DrawLine( colRight, 0, colRight, m_colLabelHeight - 1 );
7975 dc.DrawLine( colLeft, 0, colRight, 0 );
7976 dc.DrawLine( colLeft, m_colLabelHeight - 1,
7977 colRight + 1, m_colLabelHeight - 1 );
7978
7979 dc.SetPen( *wxWHITE_PEN );
7980 dc.DrawLine( colLeft, 1, colLeft, m_colLabelHeight - 1 );
7981 dc.DrawLine( colLeft, 1, colRight, 1 );
7982#endif
7983
7984 dc.SetBackgroundMode( wxTRANSPARENT );
7985 dc.SetTextForeground( GetLabelTextColour() );
7986 dc.SetFont( GetLabelFont() );
7987
7988 int hAlign, vAlign, orient;
7989 GetColLabelAlignment( &hAlign, &vAlign );
7990 orient = GetColLabelTextOrientation();
7991
7992 rect.SetX( colLeft + 2 );
7993 rect.SetY( 2 );
7994 rect.SetWidth( GetColWidth(col) - 4 );
7995 rect.SetHeight( m_colLabelHeight - 4 );
7996 DrawTextRectangle( dc, GetColLabelValue( col ), rect, hAlign, vAlign, orient );
7997}
7998
7999void wxGrid::DrawTextRectangle( wxDC& dc,
8000 const wxString& value,
8001 const wxRect& rect,
8002 int horizAlign,
8003 int vertAlign,
8004 int textOrientation )
8005{
8006 wxArrayString lines;
8007
8008 StringToLines( value, lines );
8009
8010 // Forward to new API.
8011 DrawTextRectangle( dc,
8012 lines,
8013 rect,
8014 horizAlign,
8015 vertAlign,
8016 textOrientation );
8017}
8018
8019// VZ: this should be replaced with wxDC::DrawLabel() to which we just have to
8020// add textOrientation support
8021void wxGrid::DrawTextRectangle(wxDC& dc,
8022 const wxArrayString& lines,
8023 const wxRect& rect,
8024 int horizAlign,
8025 int vertAlign,
8026 int textOrientation)
8027{
8028 if ( lines.empty() )
8029 return;
8030
8031 wxDCClipper clip(dc, rect);
8032
8033 long textWidth,
8034 textHeight;
8035
8036 if ( textOrientation == wxHORIZONTAL )
8037 GetTextBoxSize( dc, lines, &textWidth, &textHeight );
8038 else
8039 GetTextBoxSize( dc, lines, &textHeight, &textWidth );
8040
8041 int x = 0,
8042 y = 0;
8043 switch ( vertAlign )
8044 {
8045 case wxALIGN_BOTTOM:
8046 if ( textOrientation == wxHORIZONTAL )
8047 y = rect.y + (rect.height - textHeight - 1);
8048 else
8049 x = rect.x + rect.width - textWidth;
8050 break;
8051
8052 case wxALIGN_CENTRE:
8053 if ( textOrientation == wxHORIZONTAL )
8054 y = rect.y + ((rect.height - textHeight) / 2);
8055 else
8056 x = rect.x + ((rect.width - textWidth) / 2);
8057 break;
8058
8059 case wxALIGN_TOP:
8060 default:
8061 if ( textOrientation == wxHORIZONTAL )
8062 y = rect.y + 1;
8063 else
8064 x = rect.x + 1;
8065 break;
8066 }
8067
8068 // Align each line of a multi-line label
8069 size_t nLines = lines.GetCount();
8070 for ( size_t l = 0; l < nLines; l++ )
8071 {
8072 const wxString& line = lines[l];
8073
8074 if ( line.empty() )
8075 {
8076 *(textOrientation == wxHORIZONTAL ? &y : &x) += dc.GetCharHeight();
8077 continue;
8078 }
8079
8080 long lineWidth = 0,
8081 lineHeight = 0;
8082 dc.GetTextExtent(line, &lineWidth, &lineHeight);
8083
8084 switch ( horizAlign )
8085 {
8086 case wxALIGN_RIGHT:
8087 if ( textOrientation == wxHORIZONTAL )
8088 x = rect.x + (rect.width - lineWidth - 1);
8089 else
8090 y = rect.y + lineWidth + 1;
8091 break;
8092
8093 case wxALIGN_CENTRE:
8094 if ( textOrientation == wxHORIZONTAL )
8095 x = rect.x + ((rect.width - lineWidth) / 2);
8096 else
8097 y = rect.y + rect.height - ((rect.height - lineWidth) / 2);
8098 break;
8099
8100 case wxALIGN_LEFT:
8101 default:
8102 if ( textOrientation == wxHORIZONTAL )
8103 x = rect.x + 1;
8104 else
8105 y = rect.y + rect.height - 1;
8106 break;
8107 }
8108
8109 if ( textOrientation == wxHORIZONTAL )
8110 {
8111 dc.DrawText( line, x, y );
8112 y += lineHeight;
8113 }
8114 else
8115 {
8116 dc.DrawRotatedText( line, x, y, 90.0 );
8117 x += lineHeight;
8118 }
8119 }
8120}
8121
8122// Split multi-line text up into an array of strings.
8123// Any existing contents of the string array are preserved.
8124//
8125void wxGrid::StringToLines( const wxString& value, wxArrayString& lines )
8126{
8127 int startPos = 0;
8128 int pos;
8129 wxString eol = wxTextFile::GetEOL( wxTextFileType_Unix );
8130 wxString tVal = wxTextFile::Translate( value, wxTextFileType_Unix );
8131
8132 while ( startPos < (int)tVal.length() )
8133 {
8134 pos = tVal.Mid(startPos).Find( eol );
8135 if ( pos < 0 )
8136 {
8137 break;
8138 }
8139 else if ( pos == 0 )
8140 {
8141 lines.Add( wxEmptyString );
8142 }
8143 else
8144 {
8145 lines.Add( value.Mid(startPos, pos) );
8146 }
8147
8148 startPos += pos + 1;
8149 }
8150
8151 if ( startPos < (int)value.length() )
8152 {
8153 lines.Add( value.Mid( startPos ) );
8154 }
8155}
8156
8157void wxGrid::GetTextBoxSize( const wxDC& dc,
8158 const wxArrayString& lines,
8159 long *width, long *height )
8160{
8161 long w = 0;
8162 long h = 0;
8163 long lineW = 0, lineH = 0;
8164
8165 size_t i;
8166 for ( i = 0; i < lines.GetCount(); i++ )
8167 {
8168 dc.GetTextExtent( lines[i], &lineW, &lineH );
8169 w = wxMax( w, lineW );
8170 h += lineH;
8171 }
8172
8173 *width = w;
8174 *height = h;
8175}
8176
8177//
8178// ------ Batch processing.
8179//
8180void wxGrid::EndBatch()
8181{
8182 if ( m_batchCount > 0 )
8183 {
8184 m_batchCount--;
8185 if ( !m_batchCount )
8186 {
8187 CalcDimensions();
8188 m_rowLabelWin->Refresh();
8189 m_colLabelWin->Refresh();
8190 m_cornerLabelWin->Refresh();
8191 m_gridWin->Refresh();
8192 }
8193 }
8194}
8195
8196// Use this, rather than wxWindow::Refresh(), to force an immediate
8197// repainting of the grid. Has no effect if you are already inside a
8198// BeginBatch / EndBatch block.
8199//
8200void wxGrid::ForceRefresh()
8201{
8202 BeginBatch();
8203 EndBatch();
8204}
8205
8206bool wxGrid::Enable(bool enable)
8207{
8208 if ( !wxScrolledWindow::Enable(enable) )
8209 return false;
8210
8211 // redraw in the new state
8212 m_gridWin->Refresh();
8213
8214 return true;
8215}
8216
8217//
8218// ------ Edit control functions
8219//
8220
8221void wxGrid::EnableEditing( bool edit )
8222{
8223 // TODO: improve this ?
8224 //
8225 if ( edit != m_editable )
8226 {
8227 if (!edit)
8228 EnableCellEditControl(edit);
8229 m_editable = edit;
8230 }
8231}
8232
8233void wxGrid::EnableCellEditControl( bool enable )
8234{
8235 if (! m_editable)
8236 return;
8237
8238 if ( enable != m_cellEditCtrlEnabled )
8239 {
8240 if ( enable )
8241 {
8242 if (SendEvent( wxEVT_GRID_EDITOR_SHOWN) <0)
8243 return;
8244
8245 // this should be checked by the caller!
8246 wxASSERT_MSG( CanEnableCellControl(), _T("can't enable editing for this cell!") );
8247
8248 // do it before ShowCellEditControl()
8249 m_cellEditCtrlEnabled = enable;
8250
8251 ShowCellEditControl();
8252 }
8253 else
8254 {
8255 //FIXME:add veto support
8256 SendEvent( wxEVT_GRID_EDITOR_HIDDEN );
8257
8258 HideCellEditControl();
8259 SaveEditControlValue();
8260
8261 // do it after HideCellEditControl()
8262 m_cellEditCtrlEnabled = enable;
8263 }
8264 }
8265}
8266
8267bool wxGrid::IsCurrentCellReadOnly() const
8268{
8269 // const_cast
8270 wxGridCellAttr* attr = ((wxGrid *)this)->GetCellAttr(m_currentCellCoords);
8271 bool readonly = attr->IsReadOnly();
8272 attr->DecRef();
8273
8274 return readonly;
8275}
8276
8277bool wxGrid::CanEnableCellControl() const
8278{
8279 return m_editable && (m_currentCellCoords != wxGridNoCellCoords) &&
8280 !IsCurrentCellReadOnly();
8281}
8282
8283bool wxGrid::IsCellEditControlEnabled() const
8284{
8285 // the cell edit control might be disable for all cells or just for the
8286 // current one if it's read only
8287 return m_cellEditCtrlEnabled ? !IsCurrentCellReadOnly() : false;
8288}
8289
8290bool wxGrid::IsCellEditControlShown() const
8291{
8292 bool isShown = false;
8293
8294 if ( m_cellEditCtrlEnabled )
8295 {
8296 int row = m_currentCellCoords.GetRow();
8297 int col = m_currentCellCoords.GetCol();
8298 wxGridCellAttr* attr = GetCellAttr(row, col);
8299 wxGridCellEditor* editor = attr->GetEditor((wxGrid*) this, row, col);
8300 attr->DecRef();
8301
8302 if ( editor )
8303 {
8304 if ( editor->IsCreated() )
8305 {
8306 isShown = editor->GetControl()->IsShown();
8307 }
8308
8309 editor->DecRef();
8310 }
8311 }
8312
8313 return isShown;
8314}
8315
8316void wxGrid::ShowCellEditControl()
8317{
8318 if ( IsCellEditControlEnabled() )
8319 {
8320 if ( !IsVisible( m_currentCellCoords, false ) )
8321 {
8322 m_cellEditCtrlEnabled = false;
8323 return;
8324 }
8325 else
8326 {
8327 wxRect rect = CellToRect( m_currentCellCoords );
8328 int row = m_currentCellCoords.GetRow();
8329 int col = m_currentCellCoords.GetCol();
8330
8331 // if this is part of a multicell, find owner (topleft)
8332 int cell_rows, cell_cols;
8333 GetCellSize( row, col, &cell_rows, &cell_cols );
8334 if ( cell_rows <= 0 || cell_cols <= 0 )
8335 {
8336 row += cell_rows;
8337 col += cell_cols;
8338 m_currentCellCoords.SetRow( row );
8339 m_currentCellCoords.SetCol( col );
8340 }
8341
8342 // erase the highlight and the cell contents because the editor
8343 // might not cover the entire cell
8344 wxClientDC dc( m_gridWin );
8345 PrepareDC( dc );
8346 wxGridCellAttr* attr = GetCellAttr(row, col);
8347 dc.SetBrush(wxBrush(attr->GetBackgroundColour(), wxSOLID));
8348 dc.SetPen(*wxTRANSPARENT_PEN);
8349 dc.DrawRectangle(rect);
8350
8351 // convert to scrolled coords
8352 CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
8353
8354 int nXMove = 0;
8355 if (rect.x < 0)
8356 nXMove = rect.x;
8357
8358 // cell is shifted by one pixel
8359 // However, don't allow x or y to become negative
8360 // since the SetSize() method interprets that as
8361 // "don't change."
8362 if (rect.x > 0)
8363 rect.x--;
8364 if (rect.y > 0)
8365 rect.y--;
8366
8367 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8368 if ( !editor->IsCreated() )
8369 {
8370 editor->Create(m_gridWin, wxID_ANY,
8371 new wxGridCellEditorEvtHandler(this, editor));
8372
8373 wxGridEditorCreatedEvent evt(GetId(),
8374 wxEVT_GRID_EDITOR_CREATED,
8375 this,
8376 row,
8377 col,
8378 editor->GetControl());
8379 GetEventHandler()->ProcessEvent(evt);
8380 }
8381
8382 // resize editor to overflow into righthand cells if allowed
8383 int maxWidth = rect.width;
8384 wxString value = GetCellValue(row, col);
8385 if ( (value != wxEmptyString) && (attr->GetOverflow()) )
8386 {
8387 int y;
8388 GetTextExtent(value, &maxWidth, &y, NULL, NULL, &attr->GetFont());
8389 if (maxWidth < rect.width)
8390 maxWidth = rect.width;
8391 }
8392
8393 int client_right = m_gridWin->GetClientSize().GetWidth();
8394 if (rect.x + maxWidth > client_right)
8395 maxWidth = client_right - rect.x;
8396
8397 if ((maxWidth > rect.width) && (col < m_numCols) && m_table)
8398 {
8399 GetCellSize( row, col, &cell_rows, &cell_cols );
8400 // may have changed earlier
8401 for (int i = col + cell_cols; i < m_numCols; i++)
8402 {
8403 int c_rows, c_cols;
8404 GetCellSize( row, i, &c_rows, &c_cols );
8405
8406 // looks weird going over a multicell
8407 if (m_table->IsEmptyCell( row, i ) &&
8408 (rect.width < maxWidth) && (c_rows == 1))
8409 {
8410 rect.width += GetColWidth( i );
8411 }
8412 else
8413 break;
8414 }
8415
8416 if (rect.GetRight() > client_right)
8417 rect.SetRight( client_right - 1 );
8418 }
8419
8420 editor->SetCellAttr( attr );
8421 editor->SetSize( rect );
8422 if (nXMove != 0)
8423 editor->GetControl()->Move(
8424 editor->GetControl()->GetPosition().x + nXMove,
8425 editor->GetControl()->GetPosition().y );
8426 editor->Show( true, attr );
8427
8428 // recalc dimensions in case we need to
8429 // expand the scrolled window to account for editor
8430 CalcDimensions();
8431
8432 editor->BeginEdit(row, col, this);
8433 editor->SetCellAttr(NULL);
8434
8435 editor->DecRef();
8436 attr->DecRef();
8437 }
8438 }
8439}
8440
8441void wxGrid::HideCellEditControl()
8442{
8443 if ( IsCellEditControlEnabled() )
8444 {
8445 int row = m_currentCellCoords.GetRow();
8446 int col = m_currentCellCoords.GetCol();
8447
8448 wxGridCellAttr *attr = GetCellAttr(row, col);
8449 wxGridCellEditor *editor = attr->GetEditor(this, row, col);
8450 editor->Show( false );
8451 editor->DecRef();
8452 attr->DecRef();
8453
8454 m_gridWin->SetFocus();
8455
8456 // refresh whole row to the right
8457 wxRect rect( CellToRect(row, col) );
8458 CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y );
8459 rect.width = m_gridWin->GetClientSize().GetWidth() - rect.x;
8460
8461#ifdef __WXMAC__
8462 // ensure that the pixels under the focus ring get refreshed as well
8463 rect.Inflate(10, 10);
8464#endif
8465
8466 m_gridWin->Refresh( false, &rect );
8467 }
8468}
8469
8470void wxGrid::SaveEditControlValue()
8471{
8472 if ( IsCellEditControlEnabled() )
8473 {
8474 int row = m_currentCellCoords.GetRow();
8475 int col = m_currentCellCoords.GetCol();
8476
8477 wxString oldval = GetCellValue(row, col);
8478
8479 wxGridCellAttr* attr = GetCellAttr(row, col);
8480 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
8481 bool changed = editor->EndEdit(row, col, this);
8482
8483 editor->DecRef();
8484 attr->DecRef();
8485
8486 if (changed)
8487 {
8488 if ( SendEvent( wxEVT_GRID_CELL_CHANGE,
8489 m_currentCellCoords.GetRow(),
8490 m_currentCellCoords.GetCol() ) < 0 )
8491 {
8492 // Event has been vetoed, set the data back.
8493 SetCellValue(row, col, oldval);
8494 }
8495 }
8496 }
8497}
8498
8499//
8500// ------ Grid location functions
8501// Note that all of these functions work with the logical coordinates of
8502// grid cells and labels so you will need to convert from device
8503// coordinates for mouse events etc.
8504//
8505
8506void wxGrid::XYToCell( int x, int y, wxGridCellCoords& coords )
8507{
8508 int row = YToRow(y);
8509 int col = XToCol(x);
8510
8511 if ( row == -1 || col == -1 )
8512 {
8513 coords = wxGridNoCellCoords;
8514 }
8515 else
8516 {
8517 coords.Set( row, col );
8518 }
8519}
8520
8521// Internal Helper function for computing row or column from some
8522// (unscrolled) coordinate value, using either
8523// m_defaultRowHeight/m_defaultColWidth or binary search on array
8524// of m_rowBottoms/m_ColRights to speed up the search!
8525
8526static int CoordToRowOrCol(int coord, int defaultDist, int minDist,
8527 const wxArrayInt& BorderArray, int nMax,
8528 bool clipToMinMax)
8529{
8530 if (coord < 0)
8531 return clipToMinMax && (nMax > 0) ? 0 : -1;
8532
8533 if (!defaultDist)
8534 defaultDist = 1;
8535
8536 size_t i_max = coord / defaultDist,
8537 i_min = 0;
8538
8539 if (BorderArray.IsEmpty())
8540 {
8541 if ((int) i_max < nMax)
8542 return i_max;
8543 return clipToMinMax ? nMax - 1 : -1;
8544 }
8545
8546 if ( i_max >= BorderArray.GetCount())
8547 {
8548 i_max = BorderArray.GetCount() - 1;
8549 }
8550 else
8551 {
8552 if ( coord >= BorderArray[i_max])
8553 {
8554 i_min = i_max;
8555 if (minDist)
8556 i_max = coord / minDist;
8557 else
8558 i_max = BorderArray.GetCount() - 1;
8559 }
8560
8561 if ( i_max >= BorderArray.GetCount())
8562 i_max = BorderArray.GetCount() - 1;
8563 }
8564
8565 if ( coord >= BorderArray[i_max])
8566 return clipToMinMax ? (int)i_max : -1;
8567 if ( coord < BorderArray[0] )
8568 return 0;
8569
8570 while ( i_max - i_min > 0 )
8571 {
8572 wxCHECK_MSG(BorderArray[i_min] <= coord && coord < BorderArray[i_max],
8573 0, _T("wxGrid: internal error in CoordToRowOrCol"));
8574 if (coord >= BorderArray[ i_max - 1])
8575 return i_max;
8576 else
8577 i_max--;
8578 int median = i_min + (i_max - i_min + 1) / 2;
8579 if (coord < BorderArray[median])
8580 i_max = median;
8581 else
8582 i_min = median;
8583 }
8584
8585 return i_max;
8586}
8587
8588int wxGrid::YToRow( int y )
8589{
8590 return CoordToRowOrCol(y, m_defaultRowHeight,
8591 m_minAcceptableRowHeight, m_rowBottoms, m_numRows, false);
8592}
8593
8594int wxGrid::XToCol( int x, bool clipToMinMax )
8595{
8596 if (x < 0)
8597 return clipToMinMax && (m_numCols > 0) ? GetColAt( 0 ) : -1;
8598
8599 if (!m_defaultColWidth)
8600 m_defaultColWidth = 1;
8601
8602 int maxPos = x / m_defaultColWidth;
8603 int minPos = 0;
8604
8605 if (m_colRights.IsEmpty())
8606 {
8607 if(maxPos < m_numCols)
8608 return GetColAt( maxPos );
8609 return clipToMinMax ? GetColAt( m_numCols - 1 ) : -1;
8610 }
8611
8612 if ( maxPos >= m_numCols)
8613 maxPos = m_numCols - 1;
8614 else
8615 {
8616 if ( x >= m_colRights[GetColAt( maxPos )])
8617 {
8618 minPos = maxPos;
8619 if (m_minAcceptableColWidth)
8620 maxPos = x / m_minAcceptableColWidth;
8621 else
8622 maxPos = m_numCols - 1;
8623 }
8624 if ( maxPos >= m_numCols)
8625 maxPos = m_numCols - 1;
8626 }
8627
8628 //X is beyond the last column
8629 if ( x >= m_colRights[GetColAt( maxPos )])
8630 return clipToMinMax ? GetColAt( maxPos ) : -1;
8631
8632 //X is before the first column
8633 if ( x < m_colRights[GetColAt( 0 )] )
8634 return GetColAt( 0 );
8635
8636 //Perform a binary search
8637 while ( maxPos - minPos > 0 )
8638 {
8639 wxCHECK_MSG(m_colRights[GetColAt( minPos )] <= x && x < m_colRights[GetColAt( maxPos )],
8640 0, _T("wxGrid: internal error in XToCol"));
8641
8642 if (x >= m_colRights[GetColAt( maxPos - 1 )])
8643 return GetColAt( maxPos );
8644 else
8645 maxPos--;
8646 int median = minPos + (maxPos - minPos + 1) / 2;
8647 if (x < m_colRights[GetColAt( median )])
8648 maxPos = median;
8649 else
8650 minPos = median;
8651 }
8652 return GetColAt( maxPos );
8653}
8654
8655// return the row number that that the y coord is near
8656// the edge of, or -1 if not near an edge.
8657// coords can only possibly be near an edge if
8658// (a) the row/column is large enough to still allow for an "inner" area
8659// that is _not_ nead the edge (i.e., if the height/width is smaller
8660// than WXGRID_LABEL_EDGE_ZONE, coords are _never_ considered to be
8661// near the edge).
8662// and
8663// (b) resizing rows/columns (the thing for which edge detection is
8664// relevant at all) is enabled.
8665//
8666int wxGrid::YToEdgeOfRow( int y )
8667{
8668 int i;
8669 i = internalYToRow(y);
8670
8671 if ( GetRowHeight(i) > WXGRID_LABEL_EDGE_ZONE && CanDragRowSize() )
8672 {
8673 // We know that we are in row i, test whether we are
8674 // close enough to lower or upper border, respectively.
8675 if ( abs(GetRowBottom(i) - y) < WXGRID_LABEL_EDGE_ZONE )
8676 return i;
8677 else if ( i > 0 && y - GetRowTop(i) < WXGRID_LABEL_EDGE_ZONE )
8678 return i - 1;
8679 }
8680
8681 return -1;
8682}
8683
8684// return the col number that that the x coord is near the edge of, or
8685// -1 if not near an edge
8686// See comment at YToEdgeOfRow for conditions on edge detection.
8687//
8688int wxGrid::XToEdgeOfCol( int x )
8689{
8690 int i;
8691 i = internalXToCol(x);
8692
8693 if ( GetColWidth(i) > WXGRID_LABEL_EDGE_ZONE && CanDragColSize() )
8694 {
8695 // We know that we are in column i; test whether we are
8696 // close enough to right or left border, respectively.
8697 if ( abs(GetColRight(i) - x) < WXGRID_LABEL_EDGE_ZONE )
8698 return i;
8699 else if ( i > 0 && x - GetColLeft(i) < WXGRID_LABEL_EDGE_ZONE )
8700 return i - 1;
8701 }
8702
8703 return -1;
8704}
8705
8706wxRect wxGrid::CellToRect( int row, int col )
8707{
8708 wxRect rect( -1, -1, -1, -1 );
8709
8710 if ( row >= 0 && row < m_numRows &&
8711 col >= 0 && col < m_numCols )
8712 {
8713 int i, cell_rows, cell_cols;
8714 rect.width = rect.height = 0;
8715 GetCellSize( row, col, &cell_rows, &cell_cols );
8716 // if negative then find multicell owner
8717 if (cell_rows < 0)
8718 row += cell_rows;
8719 if (cell_cols < 0)
8720 col += cell_cols;
8721 GetCellSize( row, col, &cell_rows, &cell_cols );
8722
8723 rect.x = GetColLeft(col);
8724 rect.y = GetRowTop(row);
8725 for (i=col; i < col + cell_cols; i++)
8726 rect.width += GetColWidth(i);
8727 for (i=row; i < row + cell_rows; i++)
8728 rect.height += GetRowHeight(i);
8729 }
8730
8731 // if grid lines are enabled, then the area of the cell is a bit smaller
8732 if (m_gridLinesEnabled)
8733 {
8734 rect.width -= 1;
8735 rect.height -= 1;
8736 }
8737
8738 return rect;
8739}
8740
8741bool wxGrid::IsVisible( int row, int col, bool wholeCellVisible )
8742{
8743 // get the cell rectangle in logical coords
8744 //
8745 wxRect r( CellToRect( row, col ) );
8746
8747 // convert to device coords
8748 //
8749 int left, top, right, bottom;
8750 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
8751 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
8752
8753 // check against the client area of the grid window
8754 int cw, ch;
8755 m_gridWin->GetClientSize( &cw, &ch );
8756
8757 if ( wholeCellVisible )
8758 {
8759 // is the cell wholly visible ?
8760 return ( left >= 0 && right <= cw &&
8761 top >= 0 && bottom <= ch );
8762 }
8763 else
8764 {
8765 // is the cell partly visible ?
8766 //
8767 return ( ((left >= 0 && left < cw) || (right > 0 && right <= cw)) &&
8768 ((top >= 0 && top < ch) || (bottom > 0 && bottom <= ch)) );
8769 }
8770}
8771
8772// make the specified cell location visible by doing a minimal amount
8773// of scrolling
8774//
8775void wxGrid::MakeCellVisible( int row, int col )
8776{
8777 int i;
8778 int xpos = -1, ypos = -1;
8779
8780 if ( row >= 0 && row < m_numRows &&
8781 col >= 0 && col < m_numCols )
8782 {
8783 // get the cell rectangle in logical coords
8784 wxRect r( CellToRect( row, col ) );
8785
8786 // convert to device coords
8787 int left, top, right, bottom;
8788 CalcScrolledPosition( r.GetLeft(), r.GetTop(), &left, &top );
8789 CalcScrolledPosition( r.GetRight(), r.GetBottom(), &right, &bottom );
8790
8791 int cw, ch;
8792 m_gridWin->GetClientSize( &cw, &ch );
8793
8794 if ( top < 0 )
8795 {
8796 ypos = r.GetTop();
8797 }
8798 else if ( bottom > ch )
8799 {
8800 int h = r.GetHeight();
8801 ypos = r.GetTop();
8802 for ( i = row - 1; i >= 0; i-- )
8803 {
8804 int rowHeight = GetRowHeight(i);
8805 if ( h + rowHeight > ch )
8806 break;
8807
8808 h += rowHeight;
8809 ypos -= rowHeight;
8810 }
8811
8812 // we divide it later by GRID_SCROLL_LINE, make sure that we don't
8813 // have rounding errors (this is important, because if we do,
8814 // we might not scroll at all and some cells won't be redrawn)
8815 //
8816 // Sometimes GRID_SCROLL_LINE / 2 is not enough,
8817 // so just add a full scroll unit...
8818 ypos += m_scrollLineY;
8819 }
8820
8821 // special handling for wide cells - show always left part of the cell!
8822 // Otherwise, e.g. when stepping from row to row, it would jump between
8823 // left and right part of the cell on every step!
8824// if ( left < 0 )
8825 if ( left < 0 || (right - left) >= cw )
8826 {
8827 xpos = r.GetLeft();
8828 }
8829 else if ( right > cw )
8830 {
8831 // position the view so that the cell is on the right
8832 int x0, y0;
8833 CalcUnscrolledPosition(0, 0, &x0, &y0);
8834 xpos = x0 + (right - cw);
8835
8836 // see comment for ypos above
8837 xpos += m_scrollLineX;
8838 }
8839
8840 if ( xpos != -1 || ypos != -1 )
8841 {
8842 if ( xpos != -1 )
8843 xpos /= m_scrollLineX;
8844 if ( ypos != -1 )
8845 ypos /= m_scrollLineY;
8846 Scroll( xpos, ypos );
8847 AdjustScrollbars();
8848 }
8849 }
8850}
8851
8852//
8853// ------ Grid cursor movement functions
8854//
8855
8856bool wxGrid::MoveCursorUp( bool expandSelection )
8857{
8858 if ( m_currentCellCoords != wxGridNoCellCoords &&
8859 m_currentCellCoords.GetRow() >= 0 )
8860 {
8861 if ( expandSelection )
8862 {
8863 if ( m_selectingKeyboard == wxGridNoCellCoords )
8864 m_selectingKeyboard = m_currentCellCoords;
8865 if ( m_selectingKeyboard.GetRow() > 0 )
8866 {
8867 m_selectingKeyboard.SetRow( m_selectingKeyboard.GetRow() - 1 );
8868 MakeCellVisible( m_selectingKeyboard.GetRow(),
8869 m_selectingKeyboard.GetCol() );
8870 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
8871 }
8872 }
8873 else if ( m_currentCellCoords.GetRow() > 0 )
8874 {
8875 int row = m_currentCellCoords.GetRow() - 1;
8876 int col = m_currentCellCoords.GetCol();
8877 ClearSelection();
8878 MakeCellVisible( row, col );
8879 SetCurrentCell( row, col );
8880 }
8881 else
8882 return false;
8883
8884 return true;
8885 }
8886
8887 return false;
8888}
8889
8890bool wxGrid::MoveCursorDown( bool expandSelection )
8891{
8892 if ( m_currentCellCoords != wxGridNoCellCoords &&
8893 m_currentCellCoords.GetRow() < m_numRows )
8894 {
8895 if ( expandSelection )
8896 {
8897 if ( m_selectingKeyboard == wxGridNoCellCoords )
8898 m_selectingKeyboard = m_currentCellCoords;
8899 if ( m_selectingKeyboard.GetRow() < m_numRows - 1 )
8900 {
8901 m_selectingKeyboard.SetRow( m_selectingKeyboard.GetRow() + 1 );
8902 MakeCellVisible( m_selectingKeyboard.GetRow(),
8903 m_selectingKeyboard.GetCol() );
8904 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
8905 }
8906 }
8907 else if ( m_currentCellCoords.GetRow() < m_numRows - 1 )
8908 {
8909 int row = m_currentCellCoords.GetRow() + 1;
8910 int col = m_currentCellCoords.GetCol();
8911 ClearSelection();
8912 MakeCellVisible( row, col );
8913 SetCurrentCell( row, col );
8914 }
8915 else
8916 return false;
8917
8918 return true;
8919 }
8920
8921 return false;
8922}
8923
8924bool wxGrid::MoveCursorLeft( bool expandSelection )
8925{
8926 if ( m_currentCellCoords != wxGridNoCellCoords &&
8927 m_currentCellCoords.GetCol() >= 0 )
8928 {
8929 if ( expandSelection )
8930 {
8931 if ( m_selectingKeyboard == wxGridNoCellCoords )
8932 m_selectingKeyboard = m_currentCellCoords;
8933 if ( m_selectingKeyboard.GetCol() > 0 )
8934 {
8935 m_selectingKeyboard.SetCol( m_selectingKeyboard.GetCol() - 1 );
8936 MakeCellVisible( m_selectingKeyboard.GetRow(),
8937 m_selectingKeyboard.GetCol() );
8938 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
8939 }
8940 }
8941 else if ( GetColPos( m_currentCellCoords.GetCol() ) > 0 )
8942 {
8943 int row = m_currentCellCoords.GetRow();
8944 int col = GetColAt( GetColPos( m_currentCellCoords.GetCol() ) - 1 );
8945 ClearSelection();
8946
8947 MakeCellVisible( row, col );
8948 SetCurrentCell( row, col );
8949 }
8950 else
8951 return false;
8952
8953 return true;
8954 }
8955
8956 return false;
8957}
8958
8959bool wxGrid::MoveCursorRight( bool expandSelection )
8960{
8961 if ( m_currentCellCoords != wxGridNoCellCoords &&
8962 m_currentCellCoords.GetCol() < m_numCols )
8963 {
8964 if ( expandSelection )
8965 {
8966 if ( m_selectingKeyboard == wxGridNoCellCoords )
8967 m_selectingKeyboard = m_currentCellCoords;
8968 if ( m_selectingKeyboard.GetCol() < m_numCols - 1 )
8969 {
8970 m_selectingKeyboard.SetCol( m_selectingKeyboard.GetCol() + 1 );
8971 MakeCellVisible( m_selectingKeyboard.GetRow(),
8972 m_selectingKeyboard.GetCol() );
8973 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
8974 }
8975 }
8976 else if ( GetColPos( m_currentCellCoords.GetCol() ) < m_numCols - 1 )
8977 {
8978 int row = m_currentCellCoords.GetRow();
8979 int col = GetColAt( GetColPos( m_currentCellCoords.GetCol() ) + 1 );
8980 ClearSelection();
8981
8982 MakeCellVisible( row, col );
8983 SetCurrentCell( row, col );
8984 }
8985 else
8986 return false;
8987
8988 return true;
8989 }
8990
8991 return false;
8992}
8993
8994bool wxGrid::MovePageUp()
8995{
8996 if ( m_currentCellCoords == wxGridNoCellCoords )
8997 return false;
8998
8999 int row = m_currentCellCoords.GetRow();
9000 if ( row > 0 )
9001 {
9002 int cw, ch;
9003 m_gridWin->GetClientSize( &cw, &ch );
9004
9005 int y = GetRowTop(row);
9006 int newRow = internalYToRow( y - ch + 1 );
9007
9008 if ( newRow == row )
9009 {
9010 // row > 0, so newRow can never be less than 0 here.
9011 newRow = row - 1;
9012 }
9013
9014 MakeCellVisible( newRow, m_currentCellCoords.GetCol() );
9015 SetCurrentCell( newRow, m_currentCellCoords.GetCol() );
9016
9017 return true;
9018 }
9019
9020 return false;
9021}
9022
9023bool wxGrid::MovePageDown()
9024{
9025 if ( m_currentCellCoords == wxGridNoCellCoords )
9026 return false;
9027
9028 int row = m_currentCellCoords.GetRow();
9029 if ( (row + 1) < m_numRows )
9030 {
9031 int cw, ch;
9032 m_gridWin->GetClientSize( &cw, &ch );
9033
9034 int y = GetRowTop(row);
9035 int newRow = internalYToRow( y + ch );
9036 if ( newRow == row )
9037 {
9038 // row < m_numRows, so newRow can't overflow here.
9039 newRow = row + 1;
9040 }
9041
9042 MakeCellVisible( newRow, m_currentCellCoords.GetCol() );
9043 SetCurrentCell( newRow, m_currentCellCoords.GetCol() );
9044
9045 return true;
9046 }
9047
9048 return false;
9049}
9050
9051bool wxGrid::MoveCursorUpBlock( bool expandSelection )
9052{
9053 if ( m_table &&
9054 m_currentCellCoords != wxGridNoCellCoords &&
9055 m_currentCellCoords.GetRow() > 0 )
9056 {
9057 int row = m_currentCellCoords.GetRow();
9058 int col = m_currentCellCoords.GetCol();
9059
9060 if ( m_table->IsEmptyCell(row, col) )
9061 {
9062 // starting in an empty cell: find the next block of
9063 // non-empty cells
9064 //
9065 while ( row > 0 )
9066 {
9067 row--;
9068 if ( !(m_table->IsEmptyCell(row, col)) )
9069 break;
9070 }
9071 }
9072 else if ( m_table->IsEmptyCell(row - 1, col) )
9073 {
9074 // starting at the top of a block: find the next block
9075 //
9076 row--;
9077 while ( row > 0 )
9078 {
9079 row--;
9080 if ( !(m_table->IsEmptyCell(row, col)) )
9081 break;
9082 }
9083 }
9084 else
9085 {
9086 // starting within a block: find the top of the block
9087 //
9088 while ( row > 0 )
9089 {
9090 row--;
9091 if ( m_table->IsEmptyCell(row, col) )
9092 {
9093 row++;
9094 break;
9095 }
9096 }
9097 }
9098
9099 MakeCellVisible( row, col );
9100 if ( expandSelection )
9101 {
9102 m_selectingKeyboard = wxGridCellCoords( row, col );
9103 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
9104 }
9105 else
9106 {
9107 ClearSelection();
9108 SetCurrentCell( row, col );
9109 }
9110
9111 return true;
9112 }
9113
9114 return false;
9115}
9116
9117bool wxGrid::MoveCursorDownBlock( bool expandSelection )
9118{
9119 if ( m_table &&
9120 m_currentCellCoords != wxGridNoCellCoords &&
9121 m_currentCellCoords.GetRow() < m_numRows - 1 )
9122 {
9123 int row = m_currentCellCoords.GetRow();
9124 int col = m_currentCellCoords.GetCol();
9125
9126 if ( m_table->IsEmptyCell(row, col) )
9127 {
9128 // starting in an empty cell: find the next block of
9129 // non-empty cells
9130 //
9131 while ( row < m_numRows - 1 )
9132 {
9133 row++;
9134 if ( !(m_table->IsEmptyCell(row, col)) )
9135 break;
9136 }
9137 }
9138 else if ( m_table->IsEmptyCell(row + 1, col) )
9139 {
9140 // starting at the bottom of a block: find the next block
9141 //
9142 row++;
9143 while ( row < m_numRows - 1 )
9144 {
9145 row++;
9146 if ( !(m_table->IsEmptyCell(row, col)) )
9147 break;
9148 }
9149 }
9150 else
9151 {
9152 // starting within a block: find the bottom of the block
9153 //
9154 while ( row < m_numRows - 1 )
9155 {
9156 row++;
9157 if ( m_table->IsEmptyCell(row, col) )
9158 {
9159 row--;
9160 break;
9161 }
9162 }
9163 }
9164
9165 MakeCellVisible( row, col );
9166 if ( expandSelection )
9167 {
9168 m_selectingKeyboard = wxGridCellCoords( row, col );
9169 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
9170 }
9171 else
9172 {
9173 ClearSelection();
9174 SetCurrentCell( row, col );
9175 }
9176
9177 return true;
9178 }
9179
9180 return false;
9181}
9182
9183bool wxGrid::MoveCursorLeftBlock( bool expandSelection )
9184{
9185 if ( m_table &&
9186 m_currentCellCoords != wxGridNoCellCoords &&
9187 m_currentCellCoords.GetCol() > 0 )
9188 {
9189 int row = m_currentCellCoords.GetRow();
9190 int col = m_currentCellCoords.GetCol();
9191
9192 if ( m_table->IsEmptyCell(row, col) )
9193 {
9194 // starting in an empty cell: find the next block of
9195 // non-empty cells
9196 //
9197 while ( col > 0 )
9198 {
9199 col--;
9200 if ( !(m_table->IsEmptyCell(row, col)) )
9201 break;
9202 }
9203 }
9204 else if ( m_table->IsEmptyCell(row, col - 1) )
9205 {
9206 // starting at the left of a block: find the next block
9207 //
9208 col--;
9209 while ( col > 0 )
9210 {
9211 col--;
9212 if ( !(m_table->IsEmptyCell(row, col)) )
9213 break;
9214 }
9215 }
9216 else
9217 {
9218 // starting within a block: find the left of the block
9219 //
9220 while ( col > 0 )
9221 {
9222 col--;
9223 if ( m_table->IsEmptyCell(row, col) )
9224 {
9225 col++;
9226 break;
9227 }
9228 }
9229 }
9230
9231 MakeCellVisible( row, col );
9232 if ( expandSelection )
9233 {
9234 m_selectingKeyboard = wxGridCellCoords( row, col );
9235 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
9236 }
9237 else
9238 {
9239 ClearSelection();
9240 SetCurrentCell( row, col );
9241 }
9242
9243 return true;
9244 }
9245
9246 return false;
9247}
9248
9249bool wxGrid::MoveCursorRightBlock( bool expandSelection )
9250{
9251 if ( m_table &&
9252 m_currentCellCoords != wxGridNoCellCoords &&
9253 m_currentCellCoords.GetCol() < m_numCols - 1 )
9254 {
9255 int row = m_currentCellCoords.GetRow();
9256 int col = m_currentCellCoords.GetCol();
9257
9258 if ( m_table->IsEmptyCell(row, col) )
9259 {
9260 // starting in an empty cell: find the next block of
9261 // non-empty cells
9262 //
9263 while ( col < m_numCols - 1 )
9264 {
9265 col++;
9266 if ( !(m_table->IsEmptyCell(row, col)) )
9267 break;
9268 }
9269 }
9270 else if ( m_table->IsEmptyCell(row, col + 1) )
9271 {
9272 // starting at the right of a block: find the next block
9273 //
9274 col++;
9275 while ( col < m_numCols - 1 )
9276 {
9277 col++;
9278 if ( !(m_table->IsEmptyCell(row, col)) )
9279 break;
9280 }
9281 }
9282 else
9283 {
9284 // starting within a block: find the right of the block
9285 //
9286 while ( col < m_numCols - 1 )
9287 {
9288 col++;
9289 if ( m_table->IsEmptyCell(row, col) )
9290 {
9291 col--;
9292 break;
9293 }
9294 }
9295 }
9296
9297 MakeCellVisible( row, col );
9298 if ( expandSelection )
9299 {
9300 m_selectingKeyboard = wxGridCellCoords( row, col );
9301 HighlightBlock( m_currentCellCoords, m_selectingKeyboard );
9302 }
9303 else
9304 {
9305 ClearSelection();
9306 SetCurrentCell( row, col );
9307 }
9308
9309 return true;
9310 }
9311
9312 return false;
9313}
9314
9315//
9316// ------ Label values and formatting
9317//
9318
9319void wxGrid::GetRowLabelAlignment( int *horiz, int *vert )
9320{
9321 if ( horiz )
9322 *horiz = m_rowLabelHorizAlign;
9323 if ( vert )
9324 *vert = m_rowLabelVertAlign;
9325}
9326
9327void wxGrid::GetColLabelAlignment( int *horiz, int *vert )
9328{
9329 if ( horiz )
9330 *horiz = m_colLabelHorizAlign;
9331 if ( vert )
9332 *vert = m_colLabelVertAlign;
9333}
9334
9335int wxGrid::GetColLabelTextOrientation()
9336{
9337 return m_colLabelTextOrientation;
9338}
9339
9340wxString wxGrid::GetRowLabelValue( int row )
9341{
9342 if ( m_table )
9343 {
9344 return m_table->GetRowLabelValue( row );
9345 }
9346 else
9347 {
9348 wxString s;
9349 s << row;
9350 return s;
9351 }
9352}
9353
9354wxString wxGrid::GetColLabelValue( int col )
9355{
9356 if ( m_table )
9357 {
9358 return m_table->GetColLabelValue( col );
9359 }
9360 else
9361 {
9362 wxString s;
9363 s << col;
9364 return s;
9365 }
9366}
9367
9368void wxGrid::SetRowLabelSize( int width )
9369{
9370 width = wxMax( width, 0 );
9371 if ( width != m_rowLabelWidth )
9372 {
9373 if ( width == 0 )
9374 {
9375 m_rowLabelWin->Show( false );
9376 m_cornerLabelWin->Show( false );
9377 }
9378 else if ( m_rowLabelWidth == 0 )
9379 {
9380 m_rowLabelWin->Show( true );
9381 if ( m_colLabelHeight > 0 )
9382 m_cornerLabelWin->Show( true );
9383 }
9384
9385 m_rowLabelWidth = width;
9386 CalcWindowSizes();
9387 wxScrolledWindow::Refresh( true );
9388 }
9389}
9390
9391void wxGrid::SetColLabelSize( int height )
9392{
9393 height = wxMax( height, 0 );
9394 if ( height != m_colLabelHeight )
9395 {
9396 if ( height == 0 )
9397 {
9398 m_colLabelWin->Show( false );
9399 m_cornerLabelWin->Show( false );
9400 }
9401 else if ( m_colLabelHeight == 0 )
9402 {
9403 m_colLabelWin->Show( true );
9404 if ( m_rowLabelWidth > 0 )
9405 m_cornerLabelWin->Show( true );
9406 }
9407
9408 m_colLabelHeight = height;
9409 CalcWindowSizes();
9410 wxScrolledWindow::Refresh( true );
9411 }
9412}
9413
9414void wxGrid::SetLabelBackgroundColour( const wxColour& colour )
9415{
9416 if ( m_labelBackgroundColour != colour )
9417 {
9418 m_labelBackgroundColour = colour;
9419 m_rowLabelWin->SetBackgroundColour( colour );
9420 m_colLabelWin->SetBackgroundColour( colour );
9421 m_cornerLabelWin->SetBackgroundColour( colour );
9422
9423 if ( !GetBatchCount() )
9424 {
9425 m_rowLabelWin->Refresh();
9426 m_colLabelWin->Refresh();
9427 m_cornerLabelWin->Refresh();
9428 }
9429 }
9430}
9431
9432void wxGrid::SetLabelTextColour( const wxColour& colour )
9433{
9434 if ( m_labelTextColour != colour )
9435 {
9436 m_labelTextColour = colour;
9437 if ( !GetBatchCount() )
9438 {
9439 m_rowLabelWin->Refresh();
9440 m_colLabelWin->Refresh();
9441 }
9442 }
9443}
9444
9445void wxGrid::SetLabelFont( const wxFont& font )
9446{
9447 m_labelFont = font;
9448 if ( !GetBatchCount() )
9449 {
9450 m_rowLabelWin->Refresh();
9451 m_colLabelWin->Refresh();
9452 }
9453}
9454
9455void wxGrid::SetRowLabelAlignment( int horiz, int vert )
9456{
9457 // allow old (incorrect) defs to be used
9458 switch ( horiz )
9459 {
9460 case wxLEFT: horiz = wxALIGN_LEFT; break;
9461 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9462 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9463 }
9464
9465 switch ( vert )
9466 {
9467 case wxTOP: vert = wxALIGN_TOP; break;
9468 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9469 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9470 }
9471
9472 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9473 {
9474 m_rowLabelHorizAlign = horiz;
9475 }
9476
9477 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9478 {
9479 m_rowLabelVertAlign = vert;
9480 }
9481
9482 if ( !GetBatchCount() )
9483 {
9484 m_rowLabelWin->Refresh();
9485 }
9486}
9487
9488void wxGrid::SetColLabelAlignment( int horiz, int vert )
9489{
9490 // allow old (incorrect) defs to be used
9491 switch ( horiz )
9492 {
9493 case wxLEFT: horiz = wxALIGN_LEFT; break;
9494 case wxRIGHT: horiz = wxALIGN_RIGHT; break;
9495 case wxCENTRE: horiz = wxALIGN_CENTRE; break;
9496 }
9497
9498 switch ( vert )
9499 {
9500 case wxTOP: vert = wxALIGN_TOP; break;
9501 case wxBOTTOM: vert = wxALIGN_BOTTOM; break;
9502 case wxCENTRE: vert = wxALIGN_CENTRE; break;
9503 }
9504
9505 if ( horiz == wxALIGN_LEFT || horiz == wxALIGN_CENTRE || horiz == wxALIGN_RIGHT )
9506 {
9507 m_colLabelHorizAlign = horiz;
9508 }
9509
9510 if ( vert == wxALIGN_TOP || vert == wxALIGN_CENTRE || vert == wxALIGN_BOTTOM )
9511 {
9512 m_colLabelVertAlign = vert;
9513 }
9514
9515 if ( !GetBatchCount() )
9516 {
9517 m_colLabelWin->Refresh();
9518 }
9519}
9520
9521// Note: under MSW, the default column label font must be changed because it
9522// does not support vertical printing
9523//
9524// Example: wxFont font(9, wxSWISS, wxNORMAL, wxBOLD);
9525// pGrid->SetLabelFont(font);
9526// pGrid->SetColLabelTextOrientation(wxVERTICAL);
9527//
9528void wxGrid::SetColLabelTextOrientation( int textOrientation )
9529{
9530 if ( textOrientation == wxHORIZONTAL || textOrientation == wxVERTICAL )
9531 m_colLabelTextOrientation = textOrientation;
9532
9533 if ( !GetBatchCount() )
9534 m_colLabelWin->Refresh();
9535}
9536
9537void wxGrid::SetRowLabelValue( int row, const wxString& s )
9538{
9539 if ( m_table )
9540 {
9541 m_table->SetRowLabelValue( row, s );
9542 if ( !GetBatchCount() )
9543 {
9544 wxRect rect = CellToRect( row, 0 );
9545 if ( rect.height > 0 )
9546 {
9547 CalcScrolledPosition(0, rect.y, &rect.x, &rect.y);
9548 rect.x = 0;
9549 rect.width = m_rowLabelWidth;
9550 m_rowLabelWin->Refresh( true, &rect );
9551 }
9552 }
9553 }
9554}
9555
9556void wxGrid::SetColLabelValue( int col, const wxString& s )
9557{
9558 if ( m_table )
9559 {
9560 m_table->SetColLabelValue( col, s );
9561 if ( !GetBatchCount() )
9562 {
9563 wxRect rect = CellToRect( 0, col );
9564 if ( rect.width > 0 )
9565 {
9566 CalcScrolledPosition(rect.x, 0, &rect.x, &rect.y);
9567 rect.y = 0;
9568 rect.height = m_colLabelHeight;
9569 m_colLabelWin->Refresh( true, &rect );
9570 }
9571 }
9572 }
9573}
9574
9575void wxGrid::SetGridLineColour( const wxColour& colour )
9576{
9577 if ( m_gridLineColour != colour )
9578 {
9579 m_gridLineColour = colour;
9580
9581 wxClientDC dc( m_gridWin );
9582 PrepareDC( dc );
9583 DrawAllGridLines( dc, wxRegion() );
9584 }
9585}
9586
9587void wxGrid::SetCellHighlightColour( const wxColour& colour )
9588{
9589 if ( m_cellHighlightColour != colour )
9590 {
9591 m_cellHighlightColour = colour;
9592
9593 wxClientDC dc( m_gridWin );
9594 PrepareDC( dc );
9595 wxGridCellAttr* attr = GetCellAttr(m_currentCellCoords);
9596 DrawCellHighlight(dc, attr);
9597 attr->DecRef();
9598 }
9599}
9600
9601void wxGrid::SetCellHighlightPenWidth(int width)
9602{
9603 if (m_cellHighlightPenWidth != width)
9604 {
9605 m_cellHighlightPenWidth = width;
9606
9607 // Just redrawing the cell highlight is not enough since that won't
9608 // make any visible change if the the thickness is getting smaller.
9609 int row = m_currentCellCoords.GetRow();
9610 int col = m_currentCellCoords.GetCol();
9611 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9612 return;
9613
9614 wxRect rect = CellToRect(row, col);
9615 m_gridWin->Refresh(true, &rect);
9616 }
9617}
9618
9619void wxGrid::SetCellHighlightROPenWidth(int width)
9620{
9621 if (m_cellHighlightROPenWidth != width)
9622 {
9623 m_cellHighlightROPenWidth = width;
9624
9625 // Just redrawing the cell highlight is not enough since that won't
9626 // make any visible change if the the thickness is getting smaller.
9627 int row = m_currentCellCoords.GetRow();
9628 int col = m_currentCellCoords.GetCol();
9629 if ( GetColWidth(col) <= 0 || GetRowHeight(row) <= 0 )
9630 return;
9631
9632 wxRect rect = CellToRect(row, col);
9633 m_gridWin->Refresh(true, &rect);
9634 }
9635}
9636
9637void wxGrid::EnableGridLines( bool enable )
9638{
9639 if ( enable != m_gridLinesEnabled )
9640 {
9641 m_gridLinesEnabled = enable;
9642
9643 if ( !GetBatchCount() )
9644 {
9645 if ( enable )
9646 {
9647 wxClientDC dc( m_gridWin );
9648 PrepareDC( dc );
9649 DrawAllGridLines( dc, wxRegion() );
9650 }
9651 else
9652 {
9653 m_gridWin->Refresh();
9654 }
9655 }
9656 }
9657}
9658
9659int wxGrid::GetDefaultRowSize()
9660{
9661 return m_defaultRowHeight;
9662}
9663
9664int wxGrid::GetRowSize( int row )
9665{
9666 wxCHECK_MSG( row >= 0 && row < m_numRows, 0, _T("invalid row index") );
9667
9668 return GetRowHeight(row);
9669}
9670
9671int wxGrid::GetDefaultColSize()
9672{
9673 return m_defaultColWidth;
9674}
9675
9676int wxGrid::GetColSize( int col )
9677{
9678 wxCHECK_MSG( col >= 0 && col < m_numCols, 0, _T("invalid column index") );
9679
9680 return GetColWidth(col);
9681}
9682
9683// ============================================================================
9684// access to the grid attributes: each of them has a default value in the grid
9685// itself and may be overidden on a per-cell basis
9686// ============================================================================
9687
9688// ----------------------------------------------------------------------------
9689// setting default attributes
9690// ----------------------------------------------------------------------------
9691
9692void wxGrid::SetDefaultCellBackgroundColour( const wxColour& col )
9693{
9694 m_defaultCellAttr->SetBackgroundColour(col);
9695#ifdef __WXGTK__
9696 m_gridWin->SetBackgroundColour(col);
9697#endif
9698}
9699
9700void wxGrid::SetDefaultCellTextColour( const wxColour& col )
9701{
9702 m_defaultCellAttr->SetTextColour(col);
9703}
9704
9705void wxGrid::SetDefaultCellAlignment( int horiz, int vert )
9706{
9707 m_defaultCellAttr->SetAlignment(horiz, vert);
9708}
9709
9710void wxGrid::SetDefaultCellOverflow( bool allow )
9711{
9712 m_defaultCellAttr->SetOverflow(allow);
9713}
9714
9715void wxGrid::SetDefaultCellFont( const wxFont& font )
9716{
9717 m_defaultCellAttr->SetFont(font);
9718}
9719
9720// For editors and renderers the type registry takes precedence over the
9721// default attr, so we need to register the new editor/renderer for the string
9722// data type in order to make setting a default editor/renderer appear to
9723// work correctly.
9724
9725void wxGrid::SetDefaultRenderer(wxGridCellRenderer *renderer)
9726{
9727 RegisterDataType(wxGRID_VALUE_STRING,
9728 renderer,
9729 GetDefaultEditorForType(wxGRID_VALUE_STRING));
9730}
9731
9732void wxGrid::SetDefaultEditor(wxGridCellEditor *editor)
9733{
9734 RegisterDataType(wxGRID_VALUE_STRING,
9735 GetDefaultRendererForType(wxGRID_VALUE_STRING),
9736 editor);
9737}
9738
9739// ----------------------------------------------------------------------------
9740// access to the default attrbiutes
9741// ----------------------------------------------------------------------------
9742
9743wxColour wxGrid::GetDefaultCellBackgroundColour()
9744{
9745 return m_defaultCellAttr->GetBackgroundColour();
9746}
9747
9748wxColour wxGrid::GetDefaultCellTextColour()
9749{
9750 return m_defaultCellAttr->GetTextColour();
9751}
9752
9753wxFont wxGrid::GetDefaultCellFont()
9754{
9755 return m_defaultCellAttr->GetFont();
9756}
9757
9758void wxGrid::GetDefaultCellAlignment( int *horiz, int *vert )
9759{
9760 m_defaultCellAttr->GetAlignment(horiz, vert);
9761}
9762
9763bool wxGrid::GetDefaultCellOverflow()
9764{
9765 return m_defaultCellAttr->GetOverflow();
9766}
9767
9768wxGridCellRenderer *wxGrid::GetDefaultRenderer() const
9769{
9770 return m_defaultCellAttr->GetRenderer(NULL, 0, 0);
9771}
9772
9773wxGridCellEditor *wxGrid::GetDefaultEditor() const
9774{
9775 return m_defaultCellAttr->GetEditor(NULL, 0, 0);
9776}
9777
9778// ----------------------------------------------------------------------------
9779// access to cell attributes
9780// ----------------------------------------------------------------------------
9781
9782wxColour wxGrid::GetCellBackgroundColour(int row, int col)
9783{
9784 wxGridCellAttr *attr = GetCellAttr(row, col);
9785 wxColour colour = attr->GetBackgroundColour();
9786 attr->DecRef();
9787
9788 return colour;
9789}
9790
9791wxColour wxGrid::GetCellTextColour( int row, int col )
9792{
9793 wxGridCellAttr *attr = GetCellAttr(row, col);
9794 wxColour colour = attr->GetTextColour();
9795 attr->DecRef();
9796
9797 return colour;
9798}
9799
9800wxFont wxGrid::GetCellFont( int row, int col )
9801{
9802 wxGridCellAttr *attr = GetCellAttr(row, col);
9803 wxFont font = attr->GetFont();
9804 attr->DecRef();
9805
9806 return font;
9807}
9808
9809void wxGrid::GetCellAlignment( int row, int col, int *horiz, int *vert )
9810{
9811 wxGridCellAttr *attr = GetCellAttr(row, col);
9812 attr->GetAlignment(horiz, vert);
9813 attr->DecRef();
9814}
9815
9816bool wxGrid::GetCellOverflow( int row, int col )
9817{
9818 wxGridCellAttr *attr = GetCellAttr(row, col);
9819 bool allow = attr->GetOverflow();
9820 attr->DecRef();
9821
9822 return allow;
9823}
9824
9825void wxGrid::GetCellSize( int row, int col, int *num_rows, int *num_cols )
9826{
9827 wxGridCellAttr *attr = GetCellAttr(row, col);
9828 attr->GetSize( num_rows, num_cols );
9829 attr->DecRef();
9830}
9831
9832wxGridCellRenderer* wxGrid::GetCellRenderer(int row, int col)
9833{
9834 wxGridCellAttr* attr = GetCellAttr(row, col);
9835 wxGridCellRenderer* renderer = attr->GetRenderer(this, row, col);
9836 attr->DecRef();
9837
9838 return renderer;
9839}
9840
9841wxGridCellEditor* wxGrid::GetCellEditor(int row, int col)
9842{
9843 wxGridCellAttr* attr = GetCellAttr(row, col);
9844 wxGridCellEditor* editor = attr->GetEditor(this, row, col);
9845 attr->DecRef();
9846
9847 return editor;
9848}
9849
9850bool wxGrid::IsReadOnly(int row, int col) const
9851{
9852 wxGridCellAttr* attr = GetCellAttr(row, col);
9853 bool isReadOnly = attr->IsReadOnly();
9854 attr->DecRef();
9855
9856 return isReadOnly;
9857}
9858
9859// ----------------------------------------------------------------------------
9860// attribute support: cache, automatic provider creation, ...
9861// ----------------------------------------------------------------------------
9862
9863bool wxGrid::CanHaveAttributes()
9864{
9865 if ( !m_table )
9866 {
9867 return false;
9868 }
9869
9870 return m_table->CanHaveAttributes();
9871}
9872
9873void wxGrid::ClearAttrCache()
9874{
9875 if ( m_attrCache.row != -1 )
9876 {
9877 wxSafeDecRef(m_attrCache.attr);
9878 m_attrCache.attr = NULL;
9879 m_attrCache.row = -1;
9880 }
9881}
9882
9883void wxGrid::CacheAttr(int row, int col, wxGridCellAttr *attr) const
9884{
9885 if ( attr != NULL )
9886 {
9887 wxGrid *self = (wxGrid *)this; // const_cast
9888
9889 self->ClearAttrCache();
9890 self->m_attrCache.row = row;
9891 self->m_attrCache.col = col;
9892 self->m_attrCache.attr = attr;
9893 wxSafeIncRef(attr);
9894 }
9895}
9896
9897bool wxGrid::LookupAttr(int row, int col, wxGridCellAttr **attr) const
9898{
9899 if ( row == m_attrCache.row && col == m_attrCache.col )
9900 {
9901 *attr = m_attrCache.attr;
9902 wxSafeIncRef(m_attrCache.attr);
9903
9904#ifdef DEBUG_ATTR_CACHE
9905 gs_nAttrCacheHits++;
9906#endif
9907
9908 return true;
9909 }
9910 else
9911 {
9912#ifdef DEBUG_ATTR_CACHE
9913 gs_nAttrCacheMisses++;
9914#endif
9915
9916 return false;
9917 }
9918}
9919
9920wxGridCellAttr *wxGrid::GetCellAttr(int row, int col) const
9921{
9922 wxGridCellAttr *attr = NULL;
9923 // Additional test to avoid looking at the cache e.g. for
9924 // wxNoCellCoords, as this will confuse memory management.
9925 if ( row >= 0 )
9926 {
9927 if ( !LookupAttr(row, col, &attr) )
9928 {
9929 attr = m_table ? m_table->GetAttr(row, col, wxGridCellAttr::Any)
9930 : (wxGridCellAttr *)NULL;
9931 CacheAttr(row, col, attr);
9932 }
9933 }
9934
9935 if (attr)
9936 {
9937 attr->SetDefAttr(m_defaultCellAttr);
9938 }
9939 else
9940 {
9941 attr = m_defaultCellAttr;
9942 attr->IncRef();
9943 }
9944
9945 return attr;
9946}
9947
9948wxGridCellAttr *wxGrid::GetOrCreateCellAttr(int row, int col) const
9949{
9950 wxGridCellAttr *attr = (wxGridCellAttr *)NULL;
9951 bool canHave = ((wxGrid*)this)->CanHaveAttributes();
9952
9953 wxCHECK_MSG( canHave, attr, _T("Cell attributes not allowed"));
9954 wxCHECK_MSG( m_table, attr, _T("must have a table") );
9955
9956 attr = m_table->GetAttr(row, col, wxGridCellAttr::Cell);
9957 if ( !attr )
9958 {
9959 attr = new wxGridCellAttr(m_defaultCellAttr);
9960
9961 // artificially inc the ref count to match DecRef() in caller
9962 attr->IncRef();
9963 m_table->SetAttr(attr, row, col);
9964 }
9965
9966 return attr;
9967}
9968
9969// ----------------------------------------------------------------------------
9970// setting column attributes (wrappers around SetColAttr)
9971// ----------------------------------------------------------------------------
9972
9973void wxGrid::SetColFormatBool(int col)
9974{
9975 SetColFormatCustom(col, wxGRID_VALUE_BOOL);
9976}
9977
9978void wxGrid::SetColFormatNumber(int col)
9979{
9980 SetColFormatCustom(col, wxGRID_VALUE_NUMBER);
9981}
9982
9983void wxGrid::SetColFormatFloat(int col, int width, int precision)
9984{
9985 wxString typeName = wxGRID_VALUE_FLOAT;
9986 if ( (width != -1) || (precision != -1) )
9987 {
9988 typeName << _T(':') << width << _T(',') << precision;
9989 }
9990
9991 SetColFormatCustom(col, typeName);
9992}
9993
9994void wxGrid::SetColFormatCustom(int col, const wxString& typeName)
9995{
9996 wxGridCellAttr *attr = m_table->GetAttr(-1, col, wxGridCellAttr::Col );
9997 if (!attr)
9998 attr = new wxGridCellAttr;
9999 wxGridCellRenderer *renderer = GetDefaultRendererForType(typeName);
10000 attr->SetRenderer(renderer);
10001
10002 SetColAttr(col, attr);
10003
10004}
10005
10006// ----------------------------------------------------------------------------
10007// setting cell attributes: this is forwarded to the table
10008// ----------------------------------------------------------------------------
10009
10010void wxGrid::SetAttr(int row, int col, wxGridCellAttr *attr)
10011{
10012 if ( CanHaveAttributes() )
10013 {
10014 m_table->SetAttr(attr, row, col);
10015 ClearAttrCache();
10016 }
10017 else
10018 {
10019 wxSafeDecRef(attr);
10020 }
10021}
10022
10023void wxGrid::SetRowAttr(int row, wxGridCellAttr *attr)
10024{
10025 if ( CanHaveAttributes() )
10026 {
10027 m_table->SetRowAttr(attr, row);
10028 ClearAttrCache();
10029 }
10030 else
10031 {
10032 wxSafeDecRef(attr);
10033 }
10034}
10035
10036void wxGrid::SetColAttr(int col, wxGridCellAttr *attr)
10037{
10038 if ( CanHaveAttributes() )
10039 {
10040 m_table->SetColAttr(attr, col);
10041 ClearAttrCache();
10042 }
10043 else
10044 {
10045 wxSafeDecRef(attr);
10046 }
10047}
10048
10049void wxGrid::SetCellBackgroundColour( int row, int col, const wxColour& colour )
10050{
10051 if ( CanHaveAttributes() )
10052 {
10053 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10054 attr->SetBackgroundColour(colour);
10055 attr->DecRef();
10056 }
10057}
10058
10059void wxGrid::SetCellTextColour( int row, int col, const wxColour& colour )
10060{
10061 if ( CanHaveAttributes() )
10062 {
10063 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10064 attr->SetTextColour(colour);
10065 attr->DecRef();
10066 }
10067}
10068
10069void wxGrid::SetCellFont( int row, int col, const wxFont& font )
10070{
10071 if ( CanHaveAttributes() )
10072 {
10073 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10074 attr->SetFont(font);
10075 attr->DecRef();
10076 }
10077}
10078
10079void wxGrid::SetCellAlignment( int row, int col, int horiz, int vert )
10080{
10081 if ( CanHaveAttributes() )
10082 {
10083 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10084 attr->SetAlignment(horiz, vert);
10085 attr->DecRef();
10086 }
10087}
10088
10089void wxGrid::SetCellOverflow( int row, int col, bool allow )
10090{
10091 if ( CanHaveAttributes() )
10092 {
10093 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10094 attr->SetOverflow(allow);
10095 attr->DecRef();
10096 }
10097}
10098
10099void wxGrid::SetCellSize( int row, int col, int num_rows, int num_cols )
10100{
10101 if ( CanHaveAttributes() )
10102 {
10103 int cell_rows, cell_cols;
10104
10105 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10106 attr->GetSize(&cell_rows, &cell_cols);
10107 attr->SetSize(num_rows, num_cols);
10108 attr->DecRef();
10109
10110 // Cannot set the size of a cell to 0 or negative values
10111 // While it is perfectly legal to do that, this function cannot
10112 // handle all the possibilies, do it by hand by getting the CellAttr.
10113 // You can only set the size of a cell to 1,1 or greater with this fn
10114 wxASSERT_MSG( !((cell_rows < 1) || (cell_cols < 1)),
10115 wxT("wxGrid::SetCellSize setting cell size that is already part of another cell"));
10116 wxASSERT_MSG( !((num_rows < 1) || (num_cols < 1)),
10117 wxT("wxGrid::SetCellSize setting cell size to < 1"));
10118
10119 // if this was already a multicell then "turn off" the other cells first
10120 if ((cell_rows > 1) || (cell_rows > 1))
10121 {
10122 int i, j;
10123 for (j=row; j < row + cell_rows; j++)
10124 {
10125 for (i=col; i < col + cell_cols; i++)
10126 {
10127 if ((i != col) || (j != row))
10128 {
10129 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10130 attr_stub->SetSize( 1, 1 );
10131 attr_stub->DecRef();
10132 }
10133 }
10134 }
10135 }
10136
10137 // mark the cells that will be covered by this cell to
10138 // negative or zero values to point back at this cell
10139 if (((num_rows > 1) || (num_cols > 1)) && (num_rows >= 1) && (num_cols >= 1))
10140 {
10141 int i, j;
10142 for (j=row; j < row + num_rows; j++)
10143 {
10144 for (i=col; i < col + num_cols; i++)
10145 {
10146 if ((i != col) || (j != row))
10147 {
10148 wxGridCellAttr *attr_stub = GetOrCreateCellAttr(j, i);
10149 attr_stub->SetSize( row - j, col - i );
10150 attr_stub->DecRef();
10151 }
10152 }
10153 }
10154 }
10155 }
10156}
10157
10158void wxGrid::SetCellRenderer(int row, int col, wxGridCellRenderer *renderer)
10159{
10160 if ( CanHaveAttributes() )
10161 {
10162 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10163 attr->SetRenderer(renderer);
10164 attr->DecRef();
10165 }
10166}
10167
10168void wxGrid::SetCellEditor(int row, int col, wxGridCellEditor* editor)
10169{
10170 if ( CanHaveAttributes() )
10171 {
10172 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10173 attr->SetEditor(editor);
10174 attr->DecRef();
10175 }
10176}
10177
10178void wxGrid::SetReadOnly(int row, int col, bool isReadOnly)
10179{
10180 if ( CanHaveAttributes() )
10181 {
10182 wxGridCellAttr *attr = GetOrCreateCellAttr(row, col);
10183 attr->SetReadOnly(isReadOnly);
10184 attr->DecRef();
10185 }
10186}
10187
10188// ----------------------------------------------------------------------------
10189// Data type registration
10190// ----------------------------------------------------------------------------
10191
10192void wxGrid::RegisterDataType(const wxString& typeName,
10193 wxGridCellRenderer* renderer,
10194 wxGridCellEditor* editor)
10195{
10196 m_typeRegistry->RegisterDataType(typeName, renderer, editor);
10197}
10198
10199
10200wxGridCellEditor * wxGrid::GetDefaultEditorForCell(int row, int col) const
10201{
10202 wxString typeName = m_table->GetTypeName(row, col);
10203 return GetDefaultEditorForType(typeName);
10204}
10205
10206wxGridCellRenderer * wxGrid::GetDefaultRendererForCell(int row, int col) const
10207{
10208 wxString typeName = m_table->GetTypeName(row, col);
10209 return GetDefaultRendererForType(typeName);
10210}
10211
10212wxGridCellEditor * wxGrid::GetDefaultEditorForType(const wxString& typeName) const
10213{
10214 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10215 if ( index == wxNOT_FOUND )
10216 {
10217 wxString errStr;
10218
10219 errStr.Printf(wxT("Unknown data type name [%s]"), typeName.c_str());
10220 wxFAIL_MSG(errStr.c_str());
10221
10222 return NULL;
10223 }
10224
10225 return m_typeRegistry->GetEditor(index);
10226}
10227
10228wxGridCellRenderer * wxGrid::GetDefaultRendererForType(const wxString& typeName) const
10229{
10230 int index = m_typeRegistry->FindOrCloneDataType(typeName);
10231 if ( index == wxNOT_FOUND )
10232 {
10233 wxString errStr;
10234
10235 errStr.Printf(wxT("Unknown data type name [%s]"), typeName.c_str());
10236 wxFAIL_MSG(errStr.c_str());
10237
10238 return NULL;
10239 }
10240
10241 return m_typeRegistry->GetRenderer(index);
10242}
10243
10244// ----------------------------------------------------------------------------
10245// row/col size
10246// ----------------------------------------------------------------------------
10247
10248void wxGrid::EnableDragRowSize( bool enable )
10249{
10250 m_canDragRowSize = enable;
10251}
10252
10253void wxGrid::EnableDragColSize( bool enable )
10254{
10255 m_canDragColSize = enable;
10256}
10257
10258void wxGrid::EnableDragGridSize( bool enable )
10259{
10260 m_canDragGridSize = enable;
10261}
10262
10263void wxGrid::EnableDragCell( bool enable )
10264{
10265 m_canDragCell = enable;
10266}
10267
10268void wxGrid::SetDefaultRowSize( int height, bool resizeExistingRows )
10269{
10270 m_defaultRowHeight = wxMax( height, m_minAcceptableRowHeight );
10271
10272 if ( resizeExistingRows )
10273 {
10274 // since we are resizing all rows to the default row size,
10275 // we can simply clear the row heights and row bottoms
10276 // arrays (which also allows us to take advantage of
10277 // some speed optimisations)
10278 m_rowHeights.Empty();
10279 m_rowBottoms.Empty();
10280 if ( !GetBatchCount() )
10281 CalcDimensions();
10282 }
10283}
10284
10285void wxGrid::SetRowSize( int row, int height )
10286{
10287 wxCHECK_RET( row >= 0 && row < m_numRows, _T("invalid row index") );
10288
10289 // See comment in SetColSize
10290 if ( height < GetRowMinimalAcceptableHeight())
10291 return;
10292
10293 if ( m_rowHeights.IsEmpty() )
10294 {
10295 // need to really create the array
10296 InitRowHeights();
10297 }
10298
10299 int h = wxMax( 0, height );
10300 int diff = h - m_rowHeights[row];
10301
10302 m_rowHeights[row] = h;
10303 for ( int i = row; i < m_numRows; i++ )
10304 {
10305 m_rowBottoms[i] += diff;
10306 }
10307
10308 if ( !GetBatchCount() )
10309 CalcDimensions();
10310}
10311
10312void wxGrid::SetDefaultColSize( int width, bool resizeExistingCols )
10313{
10314 m_defaultColWidth = wxMax( width, m_minAcceptableColWidth );
10315
10316 if ( resizeExistingCols )
10317 {
10318 // since we are resizing all columns to the default column size,
10319 // we can simply clear the col widths and col rights
10320 // arrays (which also allows us to take advantage of
10321 // some speed optimisations)
10322 m_colWidths.Empty();
10323 m_colRights.Empty();
10324 if ( !GetBatchCount() )
10325 CalcDimensions();
10326 }
10327}
10328
10329void wxGrid::SetColSize( int col, int width )
10330{
10331 wxCHECK_RET( col >= 0 && col < m_numCols, _T("invalid column index") );
10332
10333 // should we check that it's bigger than GetColMinimalWidth(col) here?
10334 // (VZ)
10335 // No, because it is reasonable to assume the library user know's
10336 // what he is doing. However we should test against the weaker
10337 // constraint of minimalAcceptableWidth, as this breaks rendering
10338 //
10339 // This test then fixes sf.net bug #645734
10340
10341 if ( width < GetColMinimalAcceptableWidth() )
10342 return;
10343
10344 if ( m_colWidths.IsEmpty() )
10345 {
10346 // need to really create the array
10347 InitColWidths();
10348 }
10349
10350 // if < 0 then calculate new width from label
10351 if ( width < 0 )
10352 {
10353 long w, h;
10354 wxArrayString lines;
10355 wxClientDC dc(m_colLabelWin);
10356 dc.SetFont(GetLabelFont());
10357 StringToLines(GetColLabelValue(col), lines);
10358 GetTextBoxSize(dc, lines, &w, &h);
10359 width = w + 6;
10360 }
10361
10362 int w = wxMax( 0, width );
10363 int diff = w - m_colWidths[col];
10364 m_colWidths[col] = w;
10365
10366 for ( int colPos = GetColPos(col); colPos < m_numCols; colPos++ )
10367 {
10368 m_colRights[GetColAt(colPos)] += diff;
10369 }
10370
10371 if ( !GetBatchCount() )
10372 CalcDimensions();
10373}
10374
10375void wxGrid::SetColMinimalWidth( int col, int width )
10376{
10377 if (width > GetColMinimalAcceptableWidth())
10378 {
10379 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10380 m_colMinWidths[key] = width;
10381 }
10382}
10383
10384void wxGrid::SetRowMinimalHeight( int row, int width )
10385{
10386 if (width > GetRowMinimalAcceptableHeight())
10387 {
10388 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10389 m_rowMinHeights[key] = width;
10390 }
10391}
10392
10393int wxGrid::GetColMinimalWidth(int col) const
10394{
10395 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)col;
10396 wxLongToLongHashMap::const_iterator it = m_colMinWidths.find(key);
10397
10398 return it != m_colMinWidths.end() ? (int)it->second : m_minAcceptableColWidth;
10399}
10400
10401int wxGrid::GetRowMinimalHeight(int row) const
10402{
10403 wxLongToLongHashMap::key_type key = (wxLongToLongHashMap::key_type)row;
10404 wxLongToLongHashMap::const_iterator it = m_rowMinHeights.find(key);
10405
10406 return it != m_rowMinHeights.end() ? (int)it->second : m_minAcceptableRowHeight;
10407}
10408
10409void wxGrid::SetColMinimalAcceptableWidth( int width )
10410{
10411 // We do allow a width of 0 since this gives us
10412 // an easy way to temporarily hiding columns.
10413 if ( width >= 0 )
10414 m_minAcceptableColWidth = width;
10415}
10416
10417void wxGrid::SetRowMinimalAcceptableHeight( int height )
10418{
10419 // We do allow a height of 0 since this gives us
10420 // an easy way to temporarily hiding rows.
10421 if ( height >= 0 )
10422 m_minAcceptableRowHeight = height;
10423}
10424
10425int wxGrid::GetColMinimalAcceptableWidth() const
10426{
10427 return m_minAcceptableColWidth;
10428}
10429
10430int wxGrid::GetRowMinimalAcceptableHeight() const
10431{
10432 return m_minAcceptableRowHeight;
10433}
10434
10435// ----------------------------------------------------------------------------
10436// auto sizing
10437// ----------------------------------------------------------------------------
10438
10439void wxGrid::AutoSizeColOrRow( int colOrRow, bool setAsMin, bool column )
10440{
10441 wxClientDC dc(m_gridWin);
10442
10443 // cancel editing of cell
10444 HideCellEditControl();
10445 SaveEditControlValue();
10446
10447 // init both of them to avoid compiler warnings, even if we only need one
10448 int row = -1,
10449 col = -1;
10450 if ( column )
10451 col = colOrRow;
10452 else
10453 row = colOrRow;
10454
10455 wxCoord extent, extentMax = 0;
10456 int max = column ? m_numRows : m_numCols;
10457 for ( int rowOrCol = 0; rowOrCol < max; rowOrCol++ )
10458 {
10459 if ( column )
10460 row = rowOrCol;
10461 else
10462 col = rowOrCol;
10463
10464 wxGridCellAttr *attr = GetCellAttr(row, col);
10465 wxGridCellRenderer *renderer = attr->GetRenderer(this, row, col);
10466 if ( renderer )
10467 {
10468 wxSize size = renderer->GetBestSize(*this, *attr, dc, row, col);
10469 extent = column ? size.x : size.y;
10470 if ( extent > extentMax )
10471 extentMax = extent;
10472
10473 renderer->DecRef();
10474 }
10475
10476 attr->DecRef();
10477 }
10478
10479 // now also compare with the column label extent
10480 wxCoord w, h;
10481 dc.SetFont( GetLabelFont() );
10482
10483 if ( column )
10484 {
10485 dc.GetMultiLineTextExtent( GetColLabelValue(col), &w, &h );
10486 if ( GetColLabelTextOrientation() == wxVERTICAL )
10487 w = h;
10488 }
10489 else
10490 dc.GetMultiLineTextExtent( GetRowLabelValue(row), &w, &h );
10491
10492 extent = column ? w : h;
10493 if ( extent > extentMax )
10494 extentMax = extent;
10495
10496 if ( !extentMax )
10497 {
10498 // empty column - give default extent (notice that if extentMax is less
10499 // than default extent but != 0, it's OK)
10500 extentMax = column ? m_defaultColWidth : m_defaultRowHeight;
10501 }
10502 else
10503 {
10504 if ( column )
10505 // leave some space around text
10506 extentMax += 10;
10507 else
10508 extentMax += 6;
10509 }
10510
10511 if ( column )
10512 {
10513 SetColSize( col, extentMax );
10514 if ( !GetBatchCount() )
10515 {
10516 int cw, ch, dummy;
10517 m_gridWin->GetClientSize( &cw, &ch );
10518 wxRect rect ( CellToRect( 0, col ) );
10519 rect.y = 0;
10520 CalcScrolledPosition(rect.x, 0, &rect.x, &dummy);
10521 rect.width = cw - rect.x;
10522 rect.height = m_colLabelHeight;
10523 m_colLabelWin->Refresh( true, &rect );
10524 }
10525 }
10526 else
10527 {
10528 SetRowSize(row, extentMax);
10529 if ( !GetBatchCount() )
10530 {
10531 int cw, ch, dummy;
10532 m_gridWin->GetClientSize( &cw, &ch );
10533 wxRect rect( CellToRect( row, 0 ) );
10534 rect.x = 0;
10535 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10536 rect.width = m_rowLabelWidth;
10537 rect.height = ch - rect.y;
10538 m_rowLabelWin->Refresh( true, &rect );
10539 }
10540 }
10541
10542 if ( setAsMin )
10543 {
10544 if ( column )
10545 SetColMinimalWidth(col, extentMax);
10546 else
10547 SetRowMinimalHeight(row, extentMax);
10548 }
10549}
10550
10551int wxGrid::SetOrCalcColumnSizes(bool calcOnly, bool setAsMin)
10552{
10553 int width = m_rowLabelWidth;
10554
10555 if ( !calcOnly )
10556 BeginBatch();
10557
10558 for ( int col = 0; col < m_numCols; col++ )
10559 {
10560 if ( !calcOnly )
10561 AutoSizeColumn(col, setAsMin);
10562
10563 width += GetColWidth(col);
10564 }
10565
10566 if ( !calcOnly )
10567 EndBatch();
10568
10569 return width;
10570}
10571
10572int wxGrid::SetOrCalcRowSizes(bool calcOnly, bool setAsMin)
10573{
10574 int height = m_colLabelHeight;
10575
10576 if ( !calcOnly )
10577 BeginBatch();
10578
10579 for ( int row = 0; row < m_numRows; row++ )
10580 {
10581 if ( !calcOnly )
10582 AutoSizeRow(row, setAsMin);
10583
10584 height += GetRowHeight(row);
10585 }
10586
10587 if ( !calcOnly )
10588 EndBatch();
10589
10590 return height;
10591}
10592
10593void wxGrid::AutoSize()
10594{
10595 BeginBatch();
10596
10597 // we need to round up the size of the scrollable area to a multiple of
10598 // scroll step to ensure that we don't get the scrollbars when we're sized
10599 // exactly to fit our contents
10600 wxSize size(SetOrCalcColumnSizes(false) - m_rowLabelWidth + m_extraWidth,
10601 SetOrCalcRowSizes(false) - m_colLabelHeight + m_extraHeight);
10602 wxSize sizeFit(GetScrollX(size.x) * GetScrollLineX(),
10603 GetScrollY(size.y) * GetScrollLineY());
10604
10605 // distribute the extra space between the columns/rows to avoid having
10606 // extra white space
10607 wxCoord diff = sizeFit.x - size.x;
10608 if ( diff && m_numCols )
10609 {
10610 // try to resize the columns uniformly
10611 wxCoord diffPerCol = diff / m_numCols;
10612 if ( diffPerCol )
10613 {
10614 for ( int col = 0; col < m_numCols; col++ )
10615 {
10616 SetColSize(col, GetColWidth(col) + diffPerCol);
10617 }
10618 }
10619
10620 // add remaining amount to the last columns
10621 diff -= diffPerCol * m_numCols;
10622 if ( diff )
10623 {
10624 for ( int col = m_numCols - 1; col >= m_numCols - diff; col-- )
10625 {
10626 SetColSize(col, GetColWidth(col) + 1);
10627 }
10628 }
10629 }
10630
10631 // same for rows
10632 diff = sizeFit.y - size.y;
10633 if ( diff && m_numRows )
10634 {
10635 // try to resize the columns uniformly
10636 wxCoord diffPerRow = diff / m_numRows;
10637 if ( diffPerRow )
10638 {
10639 for ( int row = 0; row < m_numRows; row++ )
10640 {
10641 SetRowSize(row, GetRowHeight(row) + diffPerRow);
10642 }
10643 }
10644
10645 // add remaining amount to the last rows
10646 diff -= diffPerRow * m_numRows;
10647 if ( diff )
10648 {
10649 for ( int row = m_numRows - 1; row >= m_numRows - diff; row-- )
10650 {
10651 SetRowSize(row, GetRowHeight(row) + 1);
10652 }
10653 }
10654 }
10655
10656 // we know that we're not going to have scrollbars so disable them now to
10657 // avoid trouble in SetClientSize() which can otherwise set the correct
10658 // client size but also leave space for (not needed any more) scrollbars
10659 SetScrollbars(0, 0, 0, 0, 0, 0, true);
10660 SetClientSize(sizeFit.x + m_rowLabelWidth, sizeFit.y + m_colLabelHeight);
10661
10662 EndBatch();
10663}
10664
10665void wxGrid::AutoSizeRowLabelSize( int row )
10666{
10667 wxArrayString lines;
10668 long w, h;
10669
10670 // Hide the edit control, so it
10671 // won't interfere with drag-shrinking.
10672 if ( IsCellEditControlShown() )
10673 {
10674 HideCellEditControl();
10675 SaveEditControlValue();
10676 }
10677
10678 // autosize row height depending on label text
10679 StringToLines( GetRowLabelValue( row ), lines );
10680 wxClientDC dc( m_rowLabelWin );
10681 GetTextBoxSize( dc, lines, &w, &h );
10682 if ( h < m_defaultRowHeight )
10683 h = m_defaultRowHeight;
10684 SetRowSize(row, h);
10685 ForceRefresh();
10686}
10687
10688void wxGrid::AutoSizeColLabelSize( int col )
10689{
10690 wxArrayString lines;
10691 long w, h;
10692
10693 // Hide the edit control, so it
10694 // won't interfere with drag-shrinking.
10695 if ( IsCellEditControlShown() )
10696 {
10697 HideCellEditControl();
10698 SaveEditControlValue();
10699 }
10700
10701 // autosize column width depending on label text
10702 StringToLines( GetColLabelValue( col ), lines );
10703 wxClientDC dc( m_colLabelWin );
10704 if ( GetColLabelTextOrientation() == wxHORIZONTAL )
10705 GetTextBoxSize( dc, lines, &w, &h );
10706 else
10707 GetTextBoxSize( dc, lines, &h, &w );
10708 if ( w < m_defaultColWidth )
10709 w = m_defaultColWidth;
10710 SetColSize(col, w);
10711 ForceRefresh();
10712}
10713
10714wxSize wxGrid::DoGetBestSize() const
10715{
10716 wxGrid *self = (wxGrid *)this; // const_cast
10717
10718 // we do the same as in AutoSize() here with the exception that we don't
10719 // change the column/row sizes, only calculate them
10720 wxSize size(self->SetOrCalcColumnSizes(true) - m_rowLabelWidth + m_extraWidth,
10721 self->SetOrCalcRowSizes(true) - m_colLabelHeight + m_extraHeight);
10722 wxSize sizeFit(GetScrollX(size.x) * GetScrollLineX(),
10723 GetScrollY(size.y) * GetScrollLineY());
10724
10725 // NOTE: This size should be cached, but first we need to add calls to
10726 // InvalidateBestSize everywhere that could change the results of this
10727 // calculation.
10728 // CacheBestSize(size);
10729
10730 return wxSize(sizeFit.x + m_rowLabelWidth, sizeFit.y + m_colLabelHeight)
10731 + GetWindowBorderSize();
10732}
10733
10734void wxGrid::Fit()
10735{
10736 AutoSize();
10737}
10738
10739wxPen& wxGrid::GetDividerPen() const
10740{
10741 return wxNullPen;
10742}
10743
10744// ----------------------------------------------------------------------------
10745// cell value accessor functions
10746// ----------------------------------------------------------------------------
10747
10748void wxGrid::SetCellValue( int row, int col, const wxString& s )
10749{
10750 if ( m_table )
10751 {
10752 m_table->SetValue( row, col, s );
10753 if ( !GetBatchCount() )
10754 {
10755 int dummy;
10756 wxRect rect( CellToRect( row, col ) );
10757 rect.x = 0;
10758 rect.width = m_gridWin->GetClientSize().GetWidth();
10759 CalcScrolledPosition(0, rect.y, &dummy, &rect.y);
10760 m_gridWin->Refresh( false, &rect );
10761 }
10762
10763 if ( m_currentCellCoords.GetRow() == row &&
10764 m_currentCellCoords.GetCol() == col &&
10765 IsCellEditControlShown())
10766 // Note: If we are using IsCellEditControlEnabled,
10767 // this interacts badly with calling SetCellValue from
10768 // an EVT_GRID_CELL_CHANGE handler.
10769 {
10770 HideCellEditControl();
10771 ShowCellEditControl(); // will reread data from table
10772 }
10773 }
10774}
10775
10776// ----------------------------------------------------------------------------
10777// block, row and column selection
10778// ----------------------------------------------------------------------------
10779
10780void wxGrid::SelectRow( int row, bool addToSelected )
10781{
10782 if ( IsSelection() && !addToSelected )
10783 ClearSelection();
10784
10785 if ( m_selection )
10786 m_selection->SelectRow( row, false, addToSelected );
10787}
10788
10789void wxGrid::SelectCol( int col, bool addToSelected )
10790{
10791 if ( IsSelection() && !addToSelected )
10792 ClearSelection();
10793
10794 if ( m_selection )
10795 m_selection->SelectCol( col, false, addToSelected );
10796}
10797
10798void wxGrid::SelectBlock( int topRow, int leftCol, int bottomRow, int rightCol,
10799 bool addToSelected )
10800{
10801 if ( IsSelection() && !addToSelected )
10802 ClearSelection();
10803
10804 if ( m_selection )
10805 m_selection->SelectBlock( topRow, leftCol, bottomRow, rightCol,
10806 false, addToSelected );
10807}
10808
10809void wxGrid::SelectAll()
10810{
10811 if ( m_numRows > 0 && m_numCols > 0 )
10812 {
10813 if ( m_selection )
10814 m_selection->SelectBlock( 0, 0, m_numRows - 1, m_numCols - 1 );
10815 }
10816}
10817
10818// ----------------------------------------------------------------------------
10819// cell, row and col deselection
10820// ----------------------------------------------------------------------------
10821
10822void wxGrid::DeselectRow( int row )
10823{
10824 if ( !m_selection )
10825 return;
10826
10827 if ( m_selection->GetSelectionMode() == wxGrid::wxGridSelectRows )
10828 {
10829 if ( m_selection->IsInSelection(row, 0 ) )
10830 m_selection->ToggleCellSelection(row, 0);
10831 }
10832 else
10833 {
10834 int nCols = GetNumberCols();
10835 for ( int i = 0; i < nCols; i++ )
10836 {
10837 if ( m_selection->IsInSelection(row, i ) )
10838 m_selection->ToggleCellSelection(row, i);
10839 }
10840 }
10841}
10842
10843void wxGrid::DeselectCol( int col )
10844{
10845 if ( !m_selection )
10846 return;
10847
10848 if ( m_selection->GetSelectionMode() == wxGrid::wxGridSelectColumns )
10849 {
10850 if ( m_selection->IsInSelection(0, col ) )
10851 m_selection->ToggleCellSelection(0, col);
10852 }
10853 else
10854 {
10855 int nRows = GetNumberRows();
10856 for ( int i = 0; i < nRows; i++ )
10857 {
10858 if ( m_selection->IsInSelection(i, col ) )
10859 m_selection->ToggleCellSelection(i, col);
10860 }
10861 }
10862}
10863
10864void wxGrid::DeselectCell( int row, int col )
10865{
10866 if ( m_selection && m_selection->IsInSelection(row, col) )
10867 m_selection->ToggleCellSelection(row, col);
10868}
10869
10870bool wxGrid::IsSelection()
10871{
10872 return ( m_selection && (m_selection->IsSelection() ||
10873 ( m_selectingTopLeft != wxGridNoCellCoords &&
10874 m_selectingBottomRight != wxGridNoCellCoords) ) );
10875}
10876
10877bool wxGrid::IsInSelection( int row, int col ) const
10878{
10879 return ( m_selection && (m_selection->IsInSelection( row, col ) ||
10880 ( row >= m_selectingTopLeft.GetRow() &&
10881 col >= m_selectingTopLeft.GetCol() &&
10882 row <= m_selectingBottomRight.GetRow() &&
10883 col <= m_selectingBottomRight.GetCol() )) );
10884}
10885
10886wxGridCellCoordsArray wxGrid::GetSelectedCells() const
10887{
10888 if (!m_selection)
10889 {
10890 wxGridCellCoordsArray a;
10891 return a;
10892 }
10893
10894 return m_selection->m_cellSelection;
10895}
10896
10897wxGridCellCoordsArray wxGrid::GetSelectionBlockTopLeft() const
10898{
10899 if (!m_selection)
10900 {
10901 wxGridCellCoordsArray a;
10902 return a;
10903 }
10904
10905 return m_selection->m_blockSelectionTopLeft;
10906}
10907
10908wxGridCellCoordsArray wxGrid::GetSelectionBlockBottomRight() const
10909{
10910 if (!m_selection)
10911 {
10912 wxGridCellCoordsArray a;
10913 return a;
10914 }
10915
10916 return m_selection->m_blockSelectionBottomRight;
10917}
10918
10919wxArrayInt wxGrid::GetSelectedRows() const
10920{
10921 if (!m_selection)
10922 {
10923 wxArrayInt a;
10924 return a;
10925 }
10926
10927 return m_selection->m_rowSelection;
10928}
10929
10930wxArrayInt wxGrid::GetSelectedCols() const
10931{
10932 if (!m_selection)
10933 {
10934 wxArrayInt a;
10935 return a;
10936 }
10937
10938 return m_selection->m_colSelection;
10939}
10940
10941void wxGrid::ClearSelection()
10942{
10943 m_selectingTopLeft =
10944 m_selectingBottomRight =
10945 m_selectingKeyboard = wxGridNoCellCoords;
10946 if ( m_selection )
10947 m_selection->ClearSelection();
10948}
10949
10950// This function returns the rectangle that encloses the given block
10951// in device coords clipped to the client size of the grid window.
10952//
10953wxRect wxGrid::BlockToDeviceRect( const wxGridCellCoords &topLeft,
10954 const wxGridCellCoords &bottomRight )
10955{
10956 wxRect rect( wxGridNoCellRect );
10957 wxRect cellRect;
10958
10959 cellRect = CellToRect( topLeft );
10960 if ( cellRect != wxGridNoCellRect )
10961 {
10962 rect = cellRect;
10963 }
10964 else
10965 {
10966 rect = wxRect(0, 0, 0, 0);
10967 }
10968
10969 cellRect = CellToRect( bottomRight );
10970 if ( cellRect != wxGridNoCellRect )
10971 {
10972 rect += cellRect;
10973 }
10974 else
10975 {
10976 return wxGridNoCellRect;
10977 }
10978
10979 int i, j;
10980 int left = rect.GetLeft();
10981 int top = rect.GetTop();
10982 int right = rect.GetRight();
10983 int bottom = rect.GetBottom();
10984
10985 int leftCol = topLeft.GetCol();
10986 int topRow = topLeft.GetRow();
10987 int rightCol = bottomRight.GetCol();
10988 int bottomRow = bottomRight.GetRow();
10989
10990 if (left > right)
10991 {
10992 i = left;
10993 left = right;
10994 right = i;
10995 i = leftCol;
10996 leftCol = rightCol;
10997 rightCol = i;
10998 }
10999
11000 if (top > bottom)
11001 {
11002 i = top;
11003 top = bottom;
11004 bottom = i;
11005 i = topRow;
11006 topRow = bottomRow;
11007 bottomRow = i;
11008 }
11009
11010 for ( j = topRow; j <= bottomRow; j++ )
11011 {
11012 for ( i = leftCol; i <= rightCol; i++ )
11013 {
11014 if ((j == topRow) || (j == bottomRow) || (i == leftCol) || (i == rightCol))
11015 {
11016 cellRect = CellToRect( j, i );
11017
11018 if (cellRect.x < left)
11019 left = cellRect.x;
11020 if (cellRect.y < top)
11021 top = cellRect.y;
11022 if (cellRect.x + cellRect.width > right)
11023 right = cellRect.x + cellRect.width;
11024 if (cellRect.y + cellRect.height > bottom)
11025 bottom = cellRect.y + cellRect.height;
11026 }
11027 else
11028 {
11029 i = rightCol; // jump over inner cells.
11030 }
11031 }
11032 }
11033
11034 // convert to scrolled coords
11035 //
11036 CalcScrolledPosition( left, top, &left, &top );
11037 CalcScrolledPosition( right, bottom, &right, &bottom );
11038
11039 int cw, ch;
11040 m_gridWin->GetClientSize( &cw, &ch );
11041
11042 if (right < 0 || bottom < 0 || left > cw || top > ch)
11043 return wxRect(0,0,0,0);
11044
11045 rect.SetLeft( wxMax(0, left) );
11046 rect.SetTop( wxMax(0, top) );
11047 rect.SetRight( wxMin(cw, right) );
11048 rect.SetBottom( wxMin(ch, bottom) );
11049
11050 return rect;
11051}
11052
11053// ----------------------------------------------------------------------------
11054// grid event classes
11055// ----------------------------------------------------------------------------
11056
11057IMPLEMENT_DYNAMIC_CLASS( wxGridEvent, wxNotifyEvent )
11058
11059wxGridEvent::wxGridEvent( int id, wxEventType type, wxObject* obj,
11060 int row, int col, int x, int y, bool sel,
11061 bool control, bool shift, bool alt, bool meta )
11062 : wxNotifyEvent( type, id )
11063{
11064 m_row = row;
11065 m_col = col;
11066 m_x = x;
11067 m_y = y;
11068 m_selecting = sel;
11069 m_control = control;
11070 m_shift = shift;
11071 m_alt = alt;
11072 m_meta = meta;
11073
11074 SetEventObject(obj);
11075}
11076
11077
11078IMPLEMENT_DYNAMIC_CLASS( wxGridSizeEvent, wxNotifyEvent )
11079
11080wxGridSizeEvent::wxGridSizeEvent( int id, wxEventType type, wxObject* obj,
11081 int rowOrCol, int x, int y,
11082 bool control, bool shift, bool alt, bool meta )
11083 : wxNotifyEvent( type, id )
11084{
11085 m_rowOrCol = rowOrCol;
11086 m_x = x;
11087 m_y = y;
11088 m_control = control;
11089 m_shift = shift;
11090 m_alt = alt;
11091 m_meta = meta;
11092
11093 SetEventObject(obj);
11094}
11095
11096
11097IMPLEMENT_DYNAMIC_CLASS( wxGridRangeSelectEvent, wxNotifyEvent )
11098
11099wxGridRangeSelectEvent::wxGridRangeSelectEvent(int id, wxEventType type, wxObject* obj,
11100 const wxGridCellCoords& topLeft,
11101 const wxGridCellCoords& bottomRight,
11102 bool sel, bool control,
11103 bool shift, bool alt, bool meta )
11104 : wxNotifyEvent( type, id )
11105{
11106 m_topLeft = topLeft;
11107 m_bottomRight = bottomRight;
11108 m_selecting = sel;
11109 m_control = control;
11110 m_shift = shift;
11111 m_alt = alt;
11112 m_meta = meta;
11113
11114 SetEventObject(obj);
11115}
11116
11117
11118IMPLEMENT_DYNAMIC_CLASS(wxGridEditorCreatedEvent, wxCommandEvent)
11119
11120wxGridEditorCreatedEvent::wxGridEditorCreatedEvent(int id, wxEventType type,
11121 wxObject* obj, int row,
11122 int col, wxControl* ctrl)
11123 : wxCommandEvent(type, id)
11124{
11125 SetEventObject(obj);
11126 m_row = row;
11127 m_col = col;
11128 m_ctrl = ctrl;
11129}
11130
11131#endif // wxUSE_GRID