Fix use of DELETE and BACKSPACE when starting editing grid with them.
[wxWidgets.git] / src / generic / grideditors.cpp
1 ///////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/grideditors.cpp
3 // Purpose: wxGridCellEditorEvtHandler and wxGrid editors
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 #include "wx/headerctrl.h"
42
43 #include "wx/generic/gridsel.h"
44 #include "wx/generic/grideditors.h"
45 #include "wx/generic/private/grid.h"
46
47 #if defined(__WXMOTIF__)
48 #define WXUNUSED_MOTIF(identifier) WXUNUSED(identifier)
49 #else
50 #define WXUNUSED_MOTIF(identifier) identifier
51 #endif
52
53 #if defined(__WXGTK__)
54 #define WXUNUSED_GTK(identifier) WXUNUSED(identifier)
55 #else
56 #define WXUNUSED_GTK(identifier) identifier
57 #endif
58
59 // Required for wxIs... functions
60 #include <ctype.h>
61
62 // ============================================================================
63 // implementation
64 // ============================================================================
65
66 // ----------------------------------------------------------------------------
67 // wxGridCellEditorEvtHandler
68 // ----------------------------------------------------------------------------
69
70 void wxGridCellEditorEvtHandler::OnKillFocus(wxFocusEvent& event)
71 {
72 // Don't disable the cell if we're just starting to edit it
73 if ( m_inSetFocus )
74 {
75 event.Skip();
76 return;
77 }
78
79 // accept changes
80 m_grid->DisableCellEditControl();
81
82 // notice that we must not skip the event here because the call above may
83 // delete the control which received the kill focus event in the first
84 // place and if we pretend not having processed the event, the search for a
85 // handler for it will continue using the now deleted object resulting in a
86 // crash
87 }
88
89 void wxGridCellEditorEvtHandler::OnKeyDown(wxKeyEvent& event)
90 {
91 switch ( event.GetKeyCode() )
92 {
93 case WXK_ESCAPE:
94 m_editor->Reset();
95 m_grid->DisableCellEditControl();
96 break;
97
98 case WXK_TAB:
99 m_grid->GetEventHandler()->ProcessEvent( event );
100 break;
101
102 case WXK_RETURN:
103 case WXK_NUMPAD_ENTER:
104 if (!m_grid->GetEventHandler()->ProcessEvent(event))
105 m_editor->HandleReturn(event);
106 break;
107
108 default:
109 event.Skip();
110 break;
111 }
112 }
113
114 void wxGridCellEditorEvtHandler::OnChar(wxKeyEvent& event)
115 {
116 int row = m_grid->GetGridCursorRow();
117 int col = m_grid->GetGridCursorCol();
118 wxRect rect = m_grid->CellToRect( row, col );
119 int cw, ch;
120 m_grid->GetGridWindow()->GetClientSize( &cw, &ch );
121
122 // if cell width is smaller than grid client area, cell is wholly visible
123 bool wholeCellVisible = (rect.GetWidth() < cw);
124
125 switch ( event.GetKeyCode() )
126 {
127 case WXK_ESCAPE:
128 case WXK_TAB:
129 case WXK_RETURN:
130 case WXK_NUMPAD_ENTER:
131 break;
132
133 case WXK_HOME:
134 {
135 if ( wholeCellVisible )
136 {
137 // no special processing needed...
138 event.Skip();
139 break;
140 }
141
142 // do special processing for partly visible cell...
143
144 // get the widths of all cells previous to this one
145 int colXPos = 0;
146 for ( int i = 0; i < col; i++ )
147 {
148 colXPos += m_grid->GetColSize(i);
149 }
150
151 int xUnit = 1, yUnit = 1;
152 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
153 if (col != 0)
154 {
155 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
156 }
157 else
158 {
159 m_grid->Scroll(colXPos / xUnit, m_grid->GetScrollPos(wxVERTICAL));
160 }
161 event.Skip();
162 break;
163 }
164
165 case WXK_END:
166 {
167 if ( wholeCellVisible )
168 {
169 // no special processing needed...
170 event.Skip();
171 break;
172 }
173
174 // do special processing for partly visible cell...
175
176 int textWidth = 0;
177 wxString value = m_grid->GetCellValue(row, col);
178 if ( wxEmptyString != value )
179 {
180 // get width of cell CONTENTS (text)
181 int y;
182 wxFont font = m_grid->GetCellFont(row, col);
183 m_grid->GetTextExtent(value, &textWidth, &y, NULL, NULL, &font);
184
185 // try to RIGHT align the text by scrolling
186 int client_right = m_grid->GetGridWindow()->GetClientSize().GetWidth();
187
188 // (m_grid->GetScrollLineX()*2) is a factor for not scrolling to far,
189 // otherwise the last part of the cell content might be hidden below the scroll bar
190 // FIXME: maybe there is a more suitable correction?
191 textWidth -= (client_right - (m_grid->GetScrollLineX() * 2));
192 if ( textWidth < 0 )
193 {
194 textWidth = 0;
195 }
196 }
197
198 // get the widths of all cells previous to this one
199 int colXPos = 0;
200 for ( int i = 0; i < col; i++ )
201 {
202 colXPos += m_grid->GetColSize(i);
203 }
204
205 // and add the (modified) text width of the cell contents
206 // as we'd like to see the last part of the cell contents
207 colXPos += textWidth;
208
209 int xUnit = 1, yUnit = 1;
210 m_grid->GetScrollPixelsPerUnit(&xUnit, &yUnit);
211 m_grid->Scroll(colXPos / xUnit - 1, m_grid->GetScrollPos(wxVERTICAL));
212 event.Skip();
213 break;
214 }
215
216 default:
217 event.Skip();
218 break;
219 }
220 }
221
222 // ----------------------------------------------------------------------------
223 // wxGridCellEditor
224 // ----------------------------------------------------------------------------
225
226 wxGridCellEditor::wxGridCellEditor()
227 {
228 m_control = NULL;
229 m_attr = NULL;
230 }
231
232 wxGridCellEditor::~wxGridCellEditor()
233 {
234 Destroy();
235 }
236
237 void wxGridCellEditor::Create(wxWindow* WXUNUSED(parent),
238 wxWindowID WXUNUSED(id),
239 wxEvtHandler* evtHandler)
240 {
241 if ( evtHandler )
242 m_control->PushEventHandler(evtHandler);
243 }
244
245 void wxGridCellEditor::PaintBackground(const wxRect& rectCell,
246 wxGridCellAttr *attr)
247 {
248 // erase the background because we might not fill the cell
249 wxClientDC dc(m_control->GetParent());
250 wxGridWindow* gridWindow = wxDynamicCast(m_control->GetParent(), wxGridWindow);
251 if (gridWindow)
252 gridWindow->GetOwner()->PrepareDC(dc);
253
254 dc.SetPen(*wxTRANSPARENT_PEN);
255 dc.SetBrush(wxBrush(attr->GetBackgroundColour()));
256 dc.DrawRectangle(rectCell);
257
258 // redraw the control we just painted over
259 m_control->Refresh();
260 }
261
262 void wxGridCellEditor::Destroy()
263 {
264 if (m_control)
265 {
266 m_control->PopEventHandler( true /* delete it*/ );
267
268 m_control->Destroy();
269 m_control = NULL;
270 }
271 }
272
273 void wxGridCellEditor::Show(bool show, wxGridCellAttr *attr)
274 {
275 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
276
277 m_control->Show(show);
278
279 if ( show )
280 {
281 // set the colours/fonts if we have any
282 if ( attr )
283 {
284 m_colFgOld = m_control->GetForegroundColour();
285 m_control->SetForegroundColour(attr->GetTextColour());
286
287 m_colBgOld = m_control->GetBackgroundColour();
288 m_control->SetBackgroundColour(attr->GetBackgroundColour());
289
290 // Workaround for GTK+1 font setting problem on some platforms
291 #if !defined(__WXGTK__) || defined(__WXGTK20__)
292 m_fontOld = m_control->GetFont();
293 m_control->SetFont(attr->GetFont());
294 #endif
295
296 // can't do anything more in the base class version, the other
297 // attributes may only be used by the derived classes
298 }
299 }
300 else
301 {
302 // restore the standard colours fonts
303 if ( m_colFgOld.Ok() )
304 {
305 m_control->SetForegroundColour(m_colFgOld);
306 m_colFgOld = wxNullColour;
307 }
308
309 if ( m_colBgOld.Ok() )
310 {
311 m_control->SetBackgroundColour(m_colBgOld);
312 m_colBgOld = wxNullColour;
313 }
314
315 // Workaround for GTK+1 font setting problem on some platforms
316 #if !defined(__WXGTK__) || defined(__WXGTK20__)
317 if ( m_fontOld.Ok() )
318 {
319 m_control->SetFont(m_fontOld);
320 m_fontOld = wxNullFont;
321 }
322 #endif
323 }
324 }
325
326 void wxGridCellEditor::SetSize(const wxRect& rect)
327 {
328 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
329
330 m_control->SetSize(rect, wxSIZE_ALLOW_MINUS_ONE);
331 }
332
333 void wxGridCellEditor::HandleReturn(wxKeyEvent& event)
334 {
335 event.Skip();
336 }
337
338 bool wxGridCellEditor::IsAcceptedKey(wxKeyEvent& event)
339 {
340 bool ctrl = event.ControlDown();
341 bool alt;
342
343 #ifdef __WXMAC__
344 // On the Mac the Alt key is more like shift and is used for entry of
345 // valid characters, so check for Ctrl and Meta instead.
346 alt = event.MetaDown();
347 #else // !__WXMAC__
348 alt = event.AltDown();
349 #endif // __WXMAC__/!__WXMAC__
350
351 // Assume it's not a valid char if ctrl or alt is down, but if both are
352 // down then it may be because of an AltGr key combination, so let them
353 // through in that case.
354 if ((ctrl || alt) && !(ctrl && alt))
355 return false;
356
357 #if wxUSE_UNICODE
358 if ( event.GetUnicodeKey() == WXK_NONE )
359 return false;
360 #else
361 if ( event.GetKeyCode() > WXK_START )
362 return false;
363 #endif
364
365 return true;
366 }
367
368 void wxGridCellEditor::StartingKey(wxKeyEvent& event)
369 {
370 event.Skip();
371 }
372
373 void wxGridCellEditor::StartingClick()
374 {
375 }
376
377 #if wxUSE_TEXTCTRL
378
379 // ----------------------------------------------------------------------------
380 // wxGridCellTextEditor
381 // ----------------------------------------------------------------------------
382
383 wxGridCellTextEditor::wxGridCellTextEditor()
384 {
385 m_maxChars = 0;
386 }
387
388 void wxGridCellTextEditor::Create(wxWindow* parent,
389 wxWindowID id,
390 wxEvtHandler* evtHandler)
391 {
392 DoCreate(parent, id, evtHandler);
393 }
394
395 void wxGridCellTextEditor::DoCreate(wxWindow* parent,
396 wxWindowID id,
397 wxEvtHandler* evtHandler,
398 long style)
399 {
400 // Use of wxTE_RICH2 is a strange hack to work around the bug #11681: a
401 // plain text control seems to lose its caret somehow when we hide it and
402 // show it again for a different cell.
403 style |= wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB | wxNO_BORDER | wxTE_RICH2;
404
405 m_control = new wxTextCtrl(parent, id, wxEmptyString,
406 wxDefaultPosition, wxDefaultSize,
407 style);
408
409 // set max length allowed in the textctrl, if the parameter was set
410 if ( m_maxChars != 0 )
411 {
412 Text()->SetMaxLength(m_maxChars);
413 }
414
415 wxGridCellEditor::Create(parent, id, evtHandler);
416 }
417
418 void wxGridCellTextEditor::PaintBackground(const wxRect& WXUNUSED(rectCell),
419 wxGridCellAttr * WXUNUSED(attr))
420 {
421 // as we fill the entire client area,
422 // don't do anything here to minimize flicker
423 }
424
425 void wxGridCellTextEditor::SetSize(const wxRect& rectOrig)
426 {
427 wxRect rect(rectOrig);
428
429 // Make the edit control large enough to allow for internal margins
430 //
431 // TODO: remove this if the text ctrl sizing is improved esp. for unix
432 //
433 #if defined(__WXGTK__)
434 if (rect.x != 0)
435 {
436 rect.x += 1;
437 rect.y += 1;
438 rect.width -= 1;
439 rect.height -= 1;
440 }
441 #elif defined(__WXMSW__)
442 if ( rect.x == 0 )
443 rect.x += 2;
444 else
445 rect.x += 3;
446
447 if ( rect.y == 0 )
448 rect.y += 2;
449 else
450 rect.y += 3;
451
452 rect.width -= 2;
453 rect.height -= 2;
454 #else
455 int extra_x = ( rect.x > 2 ) ? 2 : 1;
456 int extra_y = ( rect.y > 2 ) ? 2 : 1;
457
458 #if defined(__WXMOTIF__)
459 extra_x *= 2;
460 extra_y *= 2;
461 #endif
462
463 rect.SetLeft( wxMax(0, rect.x - extra_x) );
464 rect.SetTop( wxMax(0, rect.y - extra_y) );
465 rect.SetRight( rect.GetRight() + 2 * extra_x );
466 rect.SetBottom( rect.GetBottom() + 2 * extra_y );
467 #endif
468
469 wxGridCellEditor::SetSize(rect);
470 }
471
472 void wxGridCellTextEditor::BeginEdit(int row, int col, wxGrid* grid)
473 {
474 wxASSERT_MSG(m_control, wxT("The wxGridCellEditor must be created first!"));
475
476 m_value = grid->GetTable()->GetValue(row, col);
477
478 DoBeginEdit(m_value);
479 }
480
481 void wxGridCellTextEditor::DoBeginEdit(const wxString& startValue)
482 {
483 Text()->SetValue(startValue);
484 Text()->SetInsertionPointEnd();
485 Text()->SetSelection(-1, -1);
486 Text()->SetFocus();
487 }
488
489 bool wxGridCellTextEditor::EndEdit(int WXUNUSED(row),
490 int WXUNUSED(col),
491 const wxGrid* WXUNUSED(grid),
492 const wxString& WXUNUSED(oldval),
493 wxString *newval)
494 {
495 wxCHECK_MSG( m_control, false,
496 "wxGridCellTextEditor must be created first!" );
497
498 const wxString value = Text()->GetValue();
499 if ( value == m_value )
500 return false;
501
502 m_value = value;
503
504 if ( newval )
505 *newval = m_value;
506
507 return true;
508 }
509
510 void wxGridCellTextEditor::ApplyEdit(int row, int col, wxGrid* grid)
511 {
512 grid->GetTable()->SetValue(row, col, m_value);
513 m_value.clear();
514 }
515
516 void wxGridCellTextEditor::Reset()
517 {
518 wxASSERT_MSG( m_control, "wxGridCellTextEditor must be created first!" );
519
520 DoReset(m_value);
521 }
522
523 void wxGridCellTextEditor::DoReset(const wxString& startValue)
524 {
525 Text()->SetValue(startValue);
526 Text()->SetInsertionPointEnd();
527 }
528
529 bool wxGridCellTextEditor::IsAcceptedKey(wxKeyEvent& event)
530 {
531 switch ( event.GetKeyCode() )
532 {
533 case WXK_DELETE:
534 case WXK_BACK:
535 return true;
536
537 default:
538 return wxGridCellEditor::IsAcceptedKey(event);
539 }
540 }
541
542 void wxGridCellTextEditor::StartingKey(wxKeyEvent& event)
543 {
544 // Since this is now happening in the EVT_CHAR event EmulateKeyPress is no
545 // longer an appropriate way to get the character into the text control.
546 // Do it ourselves instead. We know that if we get this far that we have
547 // a valid character, so not a whole lot of testing needs to be done.
548
549 wxTextCtrl* tc = Text();
550 wxChar ch;
551
552 bool isPrintable;
553
554 #if wxUSE_UNICODE
555 ch = event.GetUnicodeKey();
556 if ( ch != WXK_NONE )
557 isPrintable = true;
558 else
559 #endif // wxUSE_UNICODE
560 {
561 ch = (wxChar)event.GetKeyCode();
562 isPrintable = ch >= WXK_SPACE && ch < WXK_START;
563 }
564
565 switch (ch)
566 {
567 case WXK_DELETE:
568 // Delete the initial character when starting to edit with DELETE.
569 tc->Remove(0, 1);
570 break;
571
572 case WXK_BACK:
573 // Delete the last character when starting to edit with BACKSPACE.
574 {
575 const long pos = tc->GetLastPosition();
576 tc->Remove(pos - 1, pos);
577 }
578 break;
579
580 default:
581 if ( isPrintable )
582 tc->WriteText(ch);
583 break;
584 }
585 }
586
587 void wxGridCellTextEditor::HandleReturn( wxKeyEvent&
588 WXUNUSED_GTK(WXUNUSED_MOTIF(event)) )
589 {
590 #if defined(__WXMOTIF__) || defined(__WXGTK__)
591 // wxMotif needs a little extra help...
592 size_t pos = (size_t)( Text()->GetInsertionPoint() );
593 wxString s( Text()->GetValue() );
594 s = s.Left(pos) + wxT("\n") + s.Mid(pos);
595 Text()->SetValue(s);
596 Text()->SetInsertionPoint( pos );
597 #else
598 // the other ports can handle a Return key press
599 //
600 event.Skip();
601 #endif
602 }
603
604 void wxGridCellTextEditor::SetParameters(const wxString& params)
605 {
606 if ( !params )
607 {
608 // reset to default
609 m_maxChars = 0;
610 }
611 else
612 {
613 long tmp;
614 if ( params.ToLong(&tmp) )
615 {
616 m_maxChars = (size_t)tmp;
617 }
618 else
619 {
620 wxLogDebug( wxT("Invalid wxGridCellTextEditor parameter string '%s' ignored"), params.c_str() );
621 }
622 }
623 }
624
625 // return the value in the text control
626 wxString wxGridCellTextEditor::GetValue() const
627 {
628 return Text()->GetValue();
629 }
630
631 // ----------------------------------------------------------------------------
632 // wxGridCellNumberEditor
633 // ----------------------------------------------------------------------------
634
635 wxGridCellNumberEditor::wxGridCellNumberEditor(int min, int max)
636 {
637 m_min = min;
638 m_max = max;
639 }
640
641 void wxGridCellNumberEditor::Create(wxWindow* parent,
642 wxWindowID id,
643 wxEvtHandler* evtHandler)
644 {
645 #if wxUSE_SPINCTRL
646 if ( HasRange() )
647 {
648 // create a spin ctrl
649 m_control = new wxSpinCtrl(parent, wxID_ANY, wxEmptyString,
650 wxDefaultPosition, wxDefaultSize,
651 wxSP_ARROW_KEYS,
652 m_min, m_max);
653
654 wxGridCellEditor::Create(parent, id, evtHandler);
655 }
656 else
657 #endif
658 {
659 // just a text control
660 wxGridCellTextEditor::Create(parent, id, evtHandler);
661
662 #if wxUSE_VALIDATORS
663 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
664 #endif
665 }
666 }
667
668 void wxGridCellNumberEditor::BeginEdit(int row, int col, wxGrid* grid)
669 {
670 // first get the value
671 wxGridTableBase *table = grid->GetTable();
672 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
673 {
674 m_value = table->GetValueAsLong(row, col);
675 }
676 else
677 {
678 m_value = 0;
679 wxString sValue = table->GetValue(row, col);
680 if (! sValue.ToLong(&m_value) && ! sValue.empty())
681 {
682 wxFAIL_MSG( wxT("this cell doesn't have numeric value") );
683 return;
684 }
685 }
686
687 #if wxUSE_SPINCTRL
688 if ( HasRange() )
689 {
690 Spin()->SetValue((int)m_value);
691 Spin()->SetFocus();
692 }
693 else
694 #endif
695 {
696 DoBeginEdit(GetString());
697 }
698 }
699
700 bool wxGridCellNumberEditor::EndEdit(int WXUNUSED(row),
701 int WXUNUSED(col),
702 const wxGrid* WXUNUSED(grid),
703 const wxString& oldval, wxString *newval)
704 {
705 long value = 0;
706 wxString text;
707
708 #if wxUSE_SPINCTRL
709 if ( HasRange() )
710 {
711 value = Spin()->GetValue();
712 if ( value == m_value )
713 return false;
714
715 text.Printf(wxT("%ld"), value);
716 }
717 else // using unconstrained input
718 #endif // wxUSE_SPINCTRL
719 {
720 text = Text()->GetValue();
721 if ( text.empty() )
722 {
723 if ( oldval.empty() )
724 return false;
725 }
726 else // non-empty text now (maybe 0)
727 {
728 if ( !text.ToLong(&value) )
729 return false;
730
731 // if value == m_value == 0 but old text was "" and new one is
732 // "0" something still did change
733 if ( value == m_value && (value || !oldval.empty()) )
734 return false;
735 }
736 }
737
738 m_value = value;
739
740 if ( newval )
741 *newval = text;
742
743 return true;
744 }
745
746 void wxGridCellNumberEditor::ApplyEdit(int row, int col, wxGrid* grid)
747 {
748 wxGridTableBase * const table = grid->GetTable();
749 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_NUMBER) )
750 table->SetValueAsLong(row, col, m_value);
751 else
752 table->SetValue(row, col, wxString::Format("%ld", m_value));
753 }
754
755 void wxGridCellNumberEditor::Reset()
756 {
757 #if wxUSE_SPINCTRL
758 if ( HasRange() )
759 {
760 Spin()->SetValue((int)m_value);
761 }
762 else
763 #endif
764 {
765 DoReset(GetString());
766 }
767 }
768
769 bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent& event)
770 {
771 if ( wxGridCellEditor::IsAcceptedKey(event) )
772 {
773 int keycode = event.GetKeyCode();
774 if ( (keycode < 128) &&
775 (wxIsdigit(keycode) || keycode == '+' || keycode == '-'))
776 {
777 return true;
778 }
779 }
780
781 return false;
782 }
783
784 void wxGridCellNumberEditor::StartingKey(wxKeyEvent& event)
785 {
786 int keycode = event.GetKeyCode();
787 if ( !HasRange() )
788 {
789 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-')
790 {
791 wxGridCellTextEditor::StartingKey(event);
792
793 // skip Skip() below
794 return;
795 }
796 }
797 #if wxUSE_SPINCTRL
798 else
799 {
800 if ( wxIsdigit(keycode) )
801 {
802 wxSpinCtrl* spin = (wxSpinCtrl*)m_control;
803 spin->SetValue(keycode - '0');
804 spin->SetSelection(1,1);
805 return;
806 }
807 }
808 #endif
809
810 event.Skip();
811 }
812
813 void wxGridCellNumberEditor::SetParameters(const wxString& params)
814 {
815 if ( !params )
816 {
817 // reset to default
818 m_min =
819 m_max = -1;
820 }
821 else
822 {
823 long tmp;
824 if ( params.BeforeFirst(wxT(',')).ToLong(&tmp) )
825 {
826 m_min = (int)tmp;
827
828 if ( params.AfterFirst(wxT(',')).ToLong(&tmp) )
829 {
830 m_max = (int)tmp;
831
832 // skip the error message below
833 return;
834 }
835 }
836
837 wxLogDebug(wxT("Invalid wxGridCellNumberEditor parameter string '%s' ignored"), params.c_str());
838 }
839 }
840
841 // return the value in the spin control if it is there (the text control otherwise)
842 wxString wxGridCellNumberEditor::GetValue() const
843 {
844 wxString s;
845
846 #if wxUSE_SPINCTRL
847 if ( HasRange() )
848 {
849 long value = Spin()->GetValue();
850 s.Printf(wxT("%ld"), value);
851 }
852 else
853 #endif
854 {
855 s = Text()->GetValue();
856 }
857
858 return s;
859 }
860
861 // ----------------------------------------------------------------------------
862 // wxGridCellFloatEditor
863 // ----------------------------------------------------------------------------
864
865 wxGridCellFloatEditor::wxGridCellFloatEditor(int width, int precision)
866 {
867 m_width = width;
868 m_precision = precision;
869 }
870
871 void wxGridCellFloatEditor::Create(wxWindow* parent,
872 wxWindowID id,
873 wxEvtHandler* evtHandler)
874 {
875 wxGridCellTextEditor::Create(parent, id, evtHandler);
876
877 #if wxUSE_VALIDATORS
878 Text()->SetValidator(wxTextValidator(wxFILTER_NUMERIC));
879 #endif
880 }
881
882 void wxGridCellFloatEditor::BeginEdit(int row, int col, wxGrid* grid)
883 {
884 // first get the value
885 wxGridTableBase * const table = grid->GetTable();
886 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_FLOAT) )
887 {
888 m_value = table->GetValueAsDouble(row, col);
889 }
890 else
891 {
892 m_value = 0.0;
893
894 const wxString value = table->GetValue(row, col);
895 if ( !value.empty() )
896 {
897 if ( !value.ToDouble(&m_value) )
898 {
899 wxFAIL_MSG( wxT("this cell doesn't have float value") );
900 return;
901 }
902 }
903 }
904
905 DoBeginEdit(GetString());
906 }
907
908 bool wxGridCellFloatEditor::EndEdit(int WXUNUSED(row),
909 int WXUNUSED(col),
910 const wxGrid* WXUNUSED(grid),
911 const wxString& oldval, wxString *newval)
912 {
913 const wxString text(Text()->GetValue());
914
915 double value;
916 if ( !text.empty() )
917 {
918 if ( !text.ToDouble(&value) )
919 return false;
920 }
921 else // new value is empty string
922 {
923 if ( oldval.empty() )
924 return false; // nothing changed
925
926 value = 0.;
927 }
928
929 // the test for empty strings ensures that we don't skip the value setting
930 // when "" is replaced by "0" or vice versa as "" numeric value is also 0.
931 if ( wxIsSameDouble(value, m_value) && !text.empty() && !oldval.empty() )
932 return false; // nothing changed
933
934 m_value = value;
935
936 if ( newval )
937 *newval = text;
938
939 return true;
940 }
941
942 void wxGridCellFloatEditor::ApplyEdit(int row, int col, wxGrid* grid)
943 {
944 wxGridTableBase * const table = grid->GetTable();
945
946 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_FLOAT) )
947 table->SetValueAsDouble(row, col, m_value);
948 else
949 table->SetValue(row, col, Text()->GetValue());
950 }
951
952 void wxGridCellFloatEditor::Reset()
953 {
954 DoReset(GetString());
955 }
956
957 void wxGridCellFloatEditor::StartingKey(wxKeyEvent& event)
958 {
959 int keycode = event.GetKeyCode();
960 char tmpbuf[2];
961 tmpbuf[0] = (char) keycode;
962 tmpbuf[1] = '\0';
963 wxString strbuf(tmpbuf, *wxConvCurrent);
964
965 #if wxUSE_INTL
966 bool is_decimal_point = ( strbuf ==
967 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER) );
968 #else
969 bool is_decimal_point = ( strbuf == wxT(".") );
970 #endif
971
972 if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-'
973 || is_decimal_point )
974 {
975 wxGridCellTextEditor::StartingKey(event);
976
977 // skip Skip() below
978 return;
979 }
980
981 event.Skip();
982 }
983
984 void wxGridCellFloatEditor::SetParameters(const wxString& params)
985 {
986 if ( !params )
987 {
988 // reset to default
989 m_width =
990 m_precision = -1;
991 }
992 else
993 {
994 long tmp;
995 if ( params.BeforeFirst(wxT(',')).ToLong(&tmp) )
996 {
997 m_width = (int)tmp;
998
999 if ( params.AfterFirst(wxT(',')).ToLong(&tmp) )
1000 {
1001 m_precision = (int)tmp;
1002
1003 // skip the error message below
1004 return;
1005 }
1006 }
1007
1008 wxLogDebug(wxT("Invalid wxGridCellFloatEditor parameter string '%s' ignored"), params.c_str());
1009 }
1010 }
1011
1012 wxString wxGridCellFloatEditor::GetString() const
1013 {
1014 wxString fmt;
1015 if ( m_precision == -1 && m_width != -1)
1016 {
1017 // default precision
1018 fmt.Printf(wxT("%%%d.f"), m_width);
1019 }
1020 else if ( m_precision != -1 && m_width == -1)
1021 {
1022 // default width
1023 fmt.Printf(wxT("%%.%df"), m_precision);
1024 }
1025 else if ( m_precision != -1 && m_width != -1 )
1026 {
1027 fmt.Printf(wxT("%%%d.%df"), m_width, m_precision);
1028 }
1029 else
1030 {
1031 // default width/precision
1032 fmt = wxT("%f");
1033 }
1034
1035 return wxString::Format(fmt, m_value);
1036 }
1037
1038 bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent& event)
1039 {
1040 if ( wxGridCellEditor::IsAcceptedKey(event) )
1041 {
1042 const int keycode = event.GetKeyCode();
1043 if ( wxIsascii(keycode) )
1044 {
1045 #if wxUSE_INTL
1046 const wxString decimalPoint =
1047 wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER);
1048 #else
1049 const wxString decimalPoint(wxT('.'));
1050 #endif
1051
1052 // accept digits, 'e' as in '1e+6', also '-', '+', and '.'
1053 if ( wxIsdigit(keycode) ||
1054 tolower(keycode) == 'e' ||
1055 keycode == decimalPoint ||
1056 keycode == '+' ||
1057 keycode == '-' )
1058 {
1059 return true;
1060 }
1061 }
1062 }
1063
1064 return false;
1065 }
1066
1067 #endif // wxUSE_TEXTCTRL
1068
1069 #if wxUSE_CHECKBOX
1070
1071 // ----------------------------------------------------------------------------
1072 // wxGridCellBoolEditor
1073 // ----------------------------------------------------------------------------
1074
1075 // the default values for GetValue()
1076 wxString wxGridCellBoolEditor::ms_stringValues[2] = { wxT(""), wxT("1") };
1077
1078 void wxGridCellBoolEditor::Create(wxWindow* parent,
1079 wxWindowID id,
1080 wxEvtHandler* evtHandler)
1081 {
1082 m_control = new wxCheckBox(parent, id, wxEmptyString,
1083 wxDefaultPosition, wxDefaultSize,
1084 wxNO_BORDER);
1085
1086 wxGridCellEditor::Create(parent, id, evtHandler);
1087 }
1088
1089 void wxGridCellBoolEditor::SetSize(const wxRect& r)
1090 {
1091 bool resize = false;
1092 wxSize size = m_control->GetSize();
1093 wxCoord minSize = wxMin(r.width, r.height);
1094
1095 // check if the checkbox is not too big/small for this cell
1096 wxSize sizeBest = m_control->GetBestSize();
1097 if ( !(size == sizeBest) )
1098 {
1099 // reset to default size if it had been made smaller
1100 size = sizeBest;
1101
1102 resize = true;
1103 }
1104
1105 if ( size.x >= minSize || size.y >= minSize )
1106 {
1107 // leave 1 pixel margin
1108 size.x = size.y = minSize - 2;
1109
1110 resize = true;
1111 }
1112
1113 if ( resize )
1114 {
1115 m_control->SetSize(size);
1116 }
1117
1118 // position it in the centre of the rectangle (TODO: support alignment?)
1119
1120 #if defined(__WXGTK__) || defined (__WXMOTIF__)
1121 // the checkbox without label still has some space to the right in wxGTK,
1122 // so shift it to the right
1123 size.x -= 8;
1124 #elif defined(__WXMSW__)
1125 // here too, but in other way
1126 size.x += 1;
1127 size.y -= 2;
1128 #endif
1129
1130 int hAlign = wxALIGN_CENTRE;
1131 int vAlign = wxALIGN_CENTRE;
1132 if (GetCellAttr())
1133 GetCellAttr()->GetAlignment(& hAlign, & vAlign);
1134
1135 int x = 0, y = 0;
1136 if (hAlign == wxALIGN_LEFT)
1137 {
1138 x = r.x + 2;
1139
1140 #ifdef __WXMSW__
1141 x += 2;
1142 #endif
1143
1144 y = r.y + r.height / 2 - size.y / 2;
1145 }
1146 else if (hAlign == wxALIGN_RIGHT)
1147 {
1148 x = r.x + r.width - size.x - 2;
1149 y = r.y + r.height / 2 - size.y / 2;
1150 }
1151 else if (hAlign == wxALIGN_CENTRE)
1152 {
1153 x = r.x + r.width / 2 - size.x / 2;
1154 y = r.y + r.height / 2 - size.y / 2;
1155 }
1156
1157 m_control->Move(x, y);
1158 }
1159
1160 void wxGridCellBoolEditor::Show(bool show, wxGridCellAttr *attr)
1161 {
1162 m_control->Show(show);
1163
1164 if ( show )
1165 {
1166 wxColour colBg = attr ? attr->GetBackgroundColour() : *wxLIGHT_GREY;
1167 CBox()->SetBackgroundColour(colBg);
1168 }
1169 }
1170
1171 void wxGridCellBoolEditor::BeginEdit(int row, int col, wxGrid* grid)
1172 {
1173 wxASSERT_MSG(m_control,
1174 wxT("The wxGridCellEditor must be created first!"));
1175
1176 if (grid->GetTable()->CanGetValueAs(row, col, wxGRID_VALUE_BOOL))
1177 {
1178 m_value = grid->GetTable()->GetValueAsBool(row, col);
1179 }
1180 else
1181 {
1182 wxString cellval( grid->GetTable()->GetValue(row, col) );
1183
1184 if ( cellval == ms_stringValues[false] )
1185 m_value = false;
1186 else if ( cellval == ms_stringValues[true] )
1187 m_value = true;
1188 else
1189 {
1190 // do not try to be smart here and convert it to true or false
1191 // because we'll still overwrite it with something different and
1192 // this risks to be very surprising for the user code, let them
1193 // know about it
1194 wxFAIL_MSG( wxT("invalid value for a cell with bool editor!") );
1195 }
1196 }
1197
1198 CBox()->SetValue(m_value);
1199 CBox()->SetFocus();
1200 }
1201
1202 bool wxGridCellBoolEditor::EndEdit(int WXUNUSED(row),
1203 int WXUNUSED(col),
1204 const wxGrid* WXUNUSED(grid),
1205 const wxString& WXUNUSED(oldval),
1206 wxString *newval)
1207 {
1208 bool value = CBox()->GetValue();
1209 if ( value == m_value )
1210 return false;
1211
1212 m_value = value;
1213
1214 if ( newval )
1215 *newval = GetValue();
1216
1217 return true;
1218 }
1219
1220 void wxGridCellBoolEditor::ApplyEdit(int row, int col, wxGrid* grid)
1221 {
1222 wxGridTableBase * const table = grid->GetTable();
1223 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_BOOL) )
1224 table->SetValueAsBool(row, col, m_value);
1225 else
1226 table->SetValue(row, col, GetValue());
1227 }
1228
1229 void wxGridCellBoolEditor::Reset()
1230 {
1231 wxASSERT_MSG(m_control,
1232 wxT("The wxGridCellEditor must be created first!"));
1233
1234 CBox()->SetValue(m_value);
1235 }
1236
1237 void wxGridCellBoolEditor::StartingClick()
1238 {
1239 CBox()->SetValue(!CBox()->GetValue());
1240 }
1241
1242 bool wxGridCellBoolEditor::IsAcceptedKey(wxKeyEvent& event)
1243 {
1244 if ( wxGridCellEditor::IsAcceptedKey(event) )
1245 {
1246 int keycode = event.GetKeyCode();
1247 switch ( keycode )
1248 {
1249 case WXK_SPACE:
1250 case '+':
1251 case '-':
1252 return true;
1253 }
1254 }
1255
1256 return false;
1257 }
1258
1259 void wxGridCellBoolEditor::StartingKey(wxKeyEvent& event)
1260 {
1261 int keycode = event.GetKeyCode();
1262 switch ( keycode )
1263 {
1264 case WXK_SPACE:
1265 CBox()->SetValue(!CBox()->GetValue());
1266 break;
1267
1268 case '+':
1269 CBox()->SetValue(true);
1270 break;
1271
1272 case '-':
1273 CBox()->SetValue(false);
1274 break;
1275 }
1276 }
1277
1278 wxString wxGridCellBoolEditor::GetValue() const
1279 {
1280 return ms_stringValues[CBox()->GetValue()];
1281 }
1282
1283 /* static */ void
1284 wxGridCellBoolEditor::UseStringValues(const wxString& valueTrue,
1285 const wxString& valueFalse)
1286 {
1287 ms_stringValues[false] = valueFalse;
1288 ms_stringValues[true] = valueTrue;
1289 }
1290
1291 /* static */ bool
1292 wxGridCellBoolEditor::IsTrueValue(const wxString& value)
1293 {
1294 return value == ms_stringValues[true];
1295 }
1296
1297 #endif // wxUSE_CHECKBOX
1298
1299 #if wxUSE_COMBOBOX
1300
1301 // ----------------------------------------------------------------------------
1302 // wxGridCellChoiceEditor
1303 // ----------------------------------------------------------------------------
1304
1305 wxGridCellChoiceEditor::wxGridCellChoiceEditor(const wxArrayString& choices,
1306 bool allowOthers)
1307 : m_choices(choices),
1308 m_allowOthers(allowOthers) { }
1309
1310 wxGridCellChoiceEditor::wxGridCellChoiceEditor(size_t count,
1311 const wxString choices[],
1312 bool allowOthers)
1313 : m_allowOthers(allowOthers)
1314 {
1315 if ( count )
1316 {
1317 m_choices.Alloc(count);
1318 for ( size_t n = 0; n < count; n++ )
1319 {
1320 m_choices.Add(choices[n]);
1321 }
1322 }
1323 }
1324
1325 wxGridCellEditor *wxGridCellChoiceEditor::Clone() const
1326 {
1327 wxGridCellChoiceEditor *editor = new wxGridCellChoiceEditor;
1328 editor->m_allowOthers = m_allowOthers;
1329 editor->m_choices = m_choices;
1330
1331 return editor;
1332 }
1333
1334 void wxGridCellChoiceEditor::Create(wxWindow* parent,
1335 wxWindowID id,
1336 wxEvtHandler* evtHandler)
1337 {
1338 int style = wxTE_PROCESS_ENTER |
1339 wxTE_PROCESS_TAB |
1340 wxBORDER_NONE;
1341
1342 if ( !m_allowOthers )
1343 style |= wxCB_READONLY;
1344 m_control = new wxComboBox(parent, id, wxEmptyString,
1345 wxDefaultPosition, wxDefaultSize,
1346 m_choices,
1347 style);
1348
1349 wxGridCellEditor::Create(parent, id, evtHandler);
1350 }
1351
1352 void wxGridCellChoiceEditor::PaintBackground(const wxRect& rectCell,
1353 wxGridCellAttr * attr)
1354 {
1355 // as we fill the entire client area, don't do anything here to minimize
1356 // flicker
1357
1358 // TODO: It doesn't actually fill the client area since the height of a
1359 // combo always defaults to the standard. Until someone has time to
1360 // figure out the right rectangle to paint, just do it the normal way.
1361 wxGridCellEditor::PaintBackground(rectCell, attr);
1362 }
1363
1364 void wxGridCellChoiceEditor::BeginEdit(int row, int col, wxGrid* grid)
1365 {
1366 wxASSERT_MSG(m_control,
1367 wxT("The wxGridCellEditor must be created first!"));
1368
1369 wxGridCellEditorEvtHandler* evtHandler = NULL;
1370 if (m_control)
1371 evtHandler = wxDynamicCast(m_control->GetEventHandler(), wxGridCellEditorEvtHandler);
1372
1373 // Don't immediately end if we get a kill focus event within BeginEdit
1374 if (evtHandler)
1375 evtHandler->SetInSetFocus(true);
1376
1377 m_value = grid->GetTable()->GetValue(row, col);
1378
1379 Reset(); // this updates combo box to correspond to m_value
1380
1381 Combo()->SetFocus();
1382
1383 if (evtHandler)
1384 {
1385 // When dropping down the menu, a kill focus event
1386 // happens after this point, so we can't reset the flag yet.
1387 #if !defined(__WXGTK20__)
1388 evtHandler->SetInSetFocus(false);
1389 #endif
1390 }
1391 }
1392
1393 bool wxGridCellChoiceEditor::EndEdit(int WXUNUSED(row),
1394 int WXUNUSED(col),
1395 const wxGrid* WXUNUSED(grid),
1396 const wxString& WXUNUSED(oldval),
1397 wxString *newval)
1398 {
1399 const wxString value = Combo()->GetValue();
1400 if ( value == m_value )
1401 return false;
1402
1403 m_value = value;
1404
1405 if ( newval )
1406 *newval = value;
1407
1408 return true;
1409 }
1410
1411 void wxGridCellChoiceEditor::ApplyEdit(int row, int col, wxGrid* grid)
1412 {
1413 grid->GetTable()->SetValue(row, col, m_value);
1414 }
1415
1416 void wxGridCellChoiceEditor::Reset()
1417 {
1418 if (m_allowOthers)
1419 {
1420 Combo()->SetValue(m_value);
1421 Combo()->SetInsertionPointEnd();
1422 }
1423 else // the combobox is read-only
1424 {
1425 // find the right position, or default to the first if not found
1426 int pos = Combo()->FindString(m_value);
1427 if (pos == wxNOT_FOUND)
1428 pos = 0;
1429 Combo()->SetSelection(pos);
1430 }
1431 }
1432
1433 void wxGridCellChoiceEditor::SetParameters(const wxString& params)
1434 {
1435 if ( !params )
1436 {
1437 // what can we do?
1438 return;
1439 }
1440
1441 m_choices.Empty();
1442
1443 wxStringTokenizer tk(params, wxT(','));
1444 while ( tk.HasMoreTokens() )
1445 {
1446 m_choices.Add(tk.GetNextToken());
1447 }
1448 }
1449
1450 // return the value in the text control
1451 wxString wxGridCellChoiceEditor::GetValue() const
1452 {
1453 return Combo()->GetValue();
1454 }
1455
1456 #endif // wxUSE_COMBOBOX
1457
1458 #if wxUSE_COMBOBOX
1459
1460 // ----------------------------------------------------------------------------
1461 // wxGridCellEnumEditor
1462 // ----------------------------------------------------------------------------
1463
1464 // A cell editor which displays an enum number as a textual equivalent. eg
1465 // data in cell is 0,1,2 ... n the cell could be displayed as
1466 // "John","Fred"..."Bob" in the combo choice box
1467
1468 wxGridCellEnumEditor::wxGridCellEnumEditor(const wxString& choices)
1469 :wxGridCellChoiceEditor()
1470 {
1471 m_index = -1;
1472
1473 if (!choices.empty())
1474 SetParameters(choices);
1475 }
1476
1477 wxGridCellEditor *wxGridCellEnumEditor::Clone() const
1478 {
1479 wxGridCellEnumEditor *editor = new wxGridCellEnumEditor();
1480 editor->m_index = m_index;
1481 return editor;
1482 }
1483
1484 void wxGridCellEnumEditor::BeginEdit(int row, int col, wxGrid* grid)
1485 {
1486 wxASSERT_MSG(m_control,
1487 wxT("The wxGridCellEnumEditor must be Created first!"));
1488
1489 wxGridTableBase *table = grid->GetTable();
1490
1491 if ( table->CanGetValueAs(row, col, wxGRID_VALUE_NUMBER) )
1492 {
1493 m_index = table->GetValueAsLong(row, col);
1494 }
1495 else
1496 {
1497 wxString startValue = table->GetValue(row, col);
1498 if (startValue.IsNumber() && !startValue.empty())
1499 {
1500 startValue.ToLong(&m_index);
1501 }
1502 else
1503 {
1504 m_index = -1;
1505 }
1506 }
1507
1508 Combo()->SetSelection(m_index);
1509 Combo()->SetInsertionPointEnd();
1510 Combo()->SetFocus();
1511
1512 }
1513
1514 bool wxGridCellEnumEditor::EndEdit(int WXUNUSED(row),
1515 int WXUNUSED(col),
1516 const wxGrid* WXUNUSED(grid),
1517 const wxString& WXUNUSED(oldval),
1518 wxString *newval)
1519 {
1520 long idx = Combo()->GetSelection();
1521 if ( idx == m_index )
1522 return false;
1523
1524 m_index = idx;
1525
1526 if ( newval )
1527 newval->Printf("%ld", m_index);
1528
1529 return true;
1530 }
1531
1532 void wxGridCellEnumEditor::ApplyEdit(int row, int col, wxGrid* grid)
1533 {
1534 wxGridTableBase * const table = grid->GetTable();
1535 if ( table->CanSetValueAs(row, col, wxGRID_VALUE_NUMBER) )
1536 table->SetValueAsLong(row, col, m_index);
1537 else
1538 table->SetValue(row, col, wxString::Format("%ld", m_index));
1539 }
1540
1541 #endif // wxUSE_COMBOBOX
1542
1543 // ----------------------------------------------------------------------------
1544 // wxGridCellAutoWrapStringEditor
1545 // ----------------------------------------------------------------------------
1546
1547 void
1548 wxGridCellAutoWrapStringEditor::Create(wxWindow* parent,
1549 wxWindowID id,
1550 wxEvtHandler* evtHandler)
1551 {
1552 wxGridCellTextEditor::DoCreate(parent, id, evtHandler,
1553 wxTE_MULTILINE | wxTE_RICH);
1554 }
1555
1556
1557 #endif // wxUSE_GRID