Refactor text to/from double conversion in wxSpinCtrlGenericBase.
[wxWidgets.git] / src / generic / spinctlg.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/spinctlg.cpp
3 // Purpose: implements wxSpinCtrl as a composite control
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 29.01.01
7 // RCS-ID: $Id$
8 // Copyright: (c) 2001 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/textctrl.h"
29 #endif //WX_PRECOMP
30
31 #include "wx/spinctrl.h"
32 #include "wx/tooltip.h"
33
34 #if wxUSE_SPINCTRL
35
36 IMPLEMENT_DYNAMIC_CLASS(wxSpinDoubleEvent, wxNotifyEvent)
37
38 // There are port-specific versions for the wxSpinCtrl, so exclude the
39 // contents of this file in those cases
40 #if !defined(wxHAS_NATIVE_SPINCTRL) || !defined(wxHAS_NATIVE_SPINCTRLDOUBLE)
41
42 #include "wx/spinbutt.h"
43
44 #if wxUSE_SPINBTN
45
46 // ----------------------------------------------------------------------------
47 // constants
48 // ----------------------------------------------------------------------------
49
50 // The margin between the text control and the spin: the value here is the same
51 // as the margin between the spin button and its "buddy" text control in wxMSW
52 // so the generic control looks similarly to the native one there, we might
53 // need to use different value for the other platforms (and maybe even
54 // determine it dynamically?).
55 static const wxCoord MARGIN = 1;
56
57 #define SPINCTRLBUT_MAX 32000 // large to avoid wrap around trouble
58
59 // ----------------------------------------------------------------------------
60 // wxSpinCtrlTextGeneric: text control used by spin control
61 // ----------------------------------------------------------------------------
62
63 class wxSpinCtrlTextGeneric : public wxTextCtrl
64 {
65 public:
66 wxSpinCtrlTextGeneric(wxSpinCtrlGenericBase *spin, const wxString& value, long style=0)
67 : wxTextCtrl(spin->GetParent(), wxID_ANY, value, wxDefaultPosition, wxDefaultSize,
68 style & wxALIGN_MASK)
69 {
70 m_spin = spin;
71
72 // remove the default minsize, the spinctrl will have one instead
73 SetSizeHints(wxDefaultCoord, wxDefaultCoord);
74 }
75
76 virtual ~wxSpinCtrlTextGeneric()
77 {
78 // MSW sends extra kill focus event on destroy
79 if (m_spin)
80 m_spin->m_textCtrl = NULL;
81
82 m_spin = NULL;
83 }
84
85 void OnChar( wxKeyEvent &event )
86 {
87 if (m_spin)
88 m_spin->ProcessWindowEvent(event);
89 }
90
91 void OnKillFocus(wxFocusEvent& event)
92 {
93 if (m_spin)
94 m_spin->ProcessWindowEvent(event);
95
96 event.Skip();
97 }
98
99 wxSpinCtrlGenericBase *m_spin;
100
101 private:
102 DECLARE_EVENT_TABLE()
103 };
104
105 BEGIN_EVENT_TABLE(wxSpinCtrlTextGeneric, wxTextCtrl)
106 EVT_CHAR(wxSpinCtrlTextGeneric::OnChar)
107
108 EVT_KILL_FOCUS(wxSpinCtrlTextGeneric::OnKillFocus)
109 END_EVENT_TABLE()
110
111 // ----------------------------------------------------------------------------
112 // wxSpinCtrlButtonGeneric: spin button used by spin control
113 // ----------------------------------------------------------------------------
114
115 class wxSpinCtrlButtonGeneric : public wxSpinButton
116 {
117 public:
118 wxSpinCtrlButtonGeneric(wxSpinCtrlGenericBase *spin, int style)
119 : wxSpinButton(spin->GetParent(), wxID_ANY, wxDefaultPosition,
120 wxDefaultSize, style | wxSP_VERTICAL)
121 {
122 m_spin = spin;
123
124 SetRange(-SPINCTRLBUT_MAX, SPINCTRLBUT_MAX);
125
126 // remove the default minsize, the spinctrl will have one instead
127 SetSizeHints(wxDefaultCoord, wxDefaultCoord);
128 }
129
130 void OnSpinButton(wxSpinEvent& event)
131 {
132 if (m_spin)
133 m_spin->OnSpinButton(event);
134 }
135
136 wxSpinCtrlGenericBase *m_spin;
137
138 private:
139 DECLARE_EVENT_TABLE()
140 };
141
142 BEGIN_EVENT_TABLE(wxSpinCtrlButtonGeneric, wxSpinButton)
143 EVT_SPIN_UP( wxID_ANY, wxSpinCtrlButtonGeneric::OnSpinButton)
144 EVT_SPIN_DOWN(wxID_ANY, wxSpinCtrlButtonGeneric::OnSpinButton)
145 END_EVENT_TABLE()
146
147 // ============================================================================
148 // wxSpinCtrlGenericBase
149 // ============================================================================
150
151 // ----------------------------------------------------------------------------
152 // wxSpinCtrlGenericBase creation
153 // ----------------------------------------------------------------------------
154
155 void wxSpinCtrlGenericBase::Init()
156 {
157 m_value = 0;
158 m_min = 0;
159 m_max = 100;
160 m_increment = 1;
161 m_snap_to_ticks = false;
162
163 m_spin_value = 0;
164
165 m_textCtrl = NULL;
166 m_spinButton = NULL;
167 }
168
169 bool wxSpinCtrlGenericBase::Create(wxWindow *parent,
170 wxWindowID id,
171 const wxString& value,
172 const wxPoint& pos, const wxSize& size,
173 long style,
174 double min, double max, double initial,
175 double increment,
176 const wxString& name)
177 {
178 // don't use borders for this control itself, it wouldn't look good with
179 // the text control borders (but we might want to use style border bits to
180 // select the text control style)
181 if ( !wxControl::Create(parent, id, wxDefaultPosition, wxDefaultSize,
182 (style & ~wxBORDER_MASK) | wxBORDER_NONE,
183 wxDefaultValidator, name) )
184 {
185 return false;
186 }
187
188 m_value = initial;
189 m_min = min;
190 m_max = max;
191 m_increment = increment;
192
193 m_textCtrl = new wxSpinCtrlTextGeneric(this, value, style);
194 m_spinButton = new wxSpinCtrlButtonGeneric(this, style);
195 #if wxUSE_TOOLTIPS
196 m_textCtrl->SetToolTip(GetToolTipText());
197 m_spinButton->SetToolTip(GetToolTipText());
198 #endif // wxUSE_TOOLTIPS
199
200 m_spin_value = m_spinButton->GetValue();
201
202 // the string value overrides the numeric one (for backwards compatibility
203 // reasons and also because it is simpler to satisfy the string value which
204 // comes much sooner in the list of arguments and leave the initial
205 // parameter unspecified)
206 if ( !value.empty() )
207 {
208 double d;
209 if ( DoTextToValue(value, &d) )
210 {
211 m_value = d;
212 m_textCtrl->SetValue(DoValueToText(m_value));
213 }
214 }
215
216 SetInitialSize(size);
217 Move(pos);
218
219 // have to disable this window to avoid interfering it with message
220 // processing to the text and the button... but pretend it is enabled to
221 // make IsEnabled() return true
222 wxControl::Enable(false); // don't use non virtual Disable() here!
223 m_isEnabled = true;
224
225 // we don't even need to show this window itself - and not doing it avoids
226 // that it overwrites the text control
227 wxControl::Show(false);
228 m_isShown = true;
229 return true;
230 }
231
232 wxSpinCtrlGenericBase::~wxSpinCtrlGenericBase()
233 {
234 // delete the controls now, don't leave them alive even though they would
235 // still be eventually deleted by our parent - but it will be too late, the
236 // user code expects them to be gone now
237
238 if (m_textCtrl)
239 {
240 // null this since MSW sends KILL_FOCUS on deletion, see ~wxSpinCtrlTextGeneric
241 wxDynamicCast(m_textCtrl, wxSpinCtrlTextGeneric)->m_spin = NULL;
242
243 wxSpinCtrlTextGeneric *text = (wxSpinCtrlTextGeneric*)m_textCtrl;
244 m_textCtrl = NULL;
245 delete text;
246 }
247
248 wxDELETE(m_spinButton);
249 }
250
251 // ----------------------------------------------------------------------------
252 // geometry
253 // ----------------------------------------------------------------------------
254
255 wxSize wxSpinCtrlGenericBase::DoGetBestSize() const
256 {
257 wxSize sizeBtn = m_spinButton->GetBestSize(),
258 sizeText = m_textCtrl->GetBestSize();
259
260 return wxSize(sizeBtn.x + sizeText.x + MARGIN, sizeText.y);
261 }
262
263 void wxSpinCtrlGenericBase::DoMoveWindow(int x, int y, int width, int height)
264 {
265 wxControl::DoMoveWindow(x, y, width, height);
266
267 // position the subcontrols inside the client area
268 wxSize sizeBtn = m_spinButton->GetSize();
269
270 wxCoord wText = width - sizeBtn.x - MARGIN;
271 m_textCtrl->SetSize(x, y, wText, height);
272 m_spinButton->SetSize(x + wText + MARGIN, y, wxDefaultCoord, height);
273 }
274
275 // ----------------------------------------------------------------------------
276 // operations forwarded to the subcontrols
277 // ----------------------------------------------------------------------------
278
279 void wxSpinCtrlGenericBase::SetFocus()
280 {
281 if ( m_textCtrl )
282 m_textCtrl->SetFocus();
283 }
284
285 #ifdef __WXMSW__
286
287 void wxSpinCtrlGenericBase::DoEnable(bool enable)
288 {
289 // We never enable this control itself, it must stay disabled to avoid
290 // interfering with the siblings event handling (see e.g. #12045 for the
291 // kind of problems which arise otherwise).
292 if ( !enable )
293 wxSpinCtrlBase::DoEnable(enable);
294 }
295
296 #endif // __WXMSW__
297
298 bool wxSpinCtrlGenericBase::Enable(bool enable)
299 {
300 if ( !wxSpinCtrlBase::Enable(enable) )
301 return false;
302
303 m_spinButton->Enable(enable);
304 m_textCtrl->Enable(enable);
305
306 return true;
307 }
308
309 bool wxSpinCtrlGenericBase::Show(bool show)
310 {
311 if ( !wxControl::Show(show) )
312 return false;
313
314 // under GTK Show() is called the first time before we are fully
315 // constructed
316 if ( m_spinButton )
317 {
318 m_spinButton->Show(show);
319 m_textCtrl->Show(show);
320 }
321
322 return true;
323 }
324
325 #if wxUSE_TOOLTIPS
326 void wxSpinCtrlGenericBase::DoSetToolTip(wxToolTip *tip)
327 {
328 // Notice that we must check for the subcontrols not being NULL (as they
329 // could be if we were created with the default ctor and this is called
330 // before Create() for some reason) and that we can't call SetToolTip(tip)
331 // because this would take ownership of the wxToolTip object (twice).
332 if ( m_textCtrl )
333 {
334 if ( tip )
335 m_textCtrl->SetToolTip(tip->GetTip());
336 else
337 m_textCtrl->SetToolTip(NULL);
338 }
339
340 if ( m_spinButton )
341 {
342 if( tip )
343 m_spinButton->SetToolTip(tip->GetTip());
344 else
345 m_spinButton->SetToolTip(NULL);
346 }
347
348 wxWindowBase::DoSetToolTip(tip);
349 }
350 #endif // wxUSE_TOOLTIPS
351
352 // ----------------------------------------------------------------------------
353 // Handle sub controls events
354 // ----------------------------------------------------------------------------
355
356 BEGIN_EVENT_TABLE(wxSpinCtrlGenericBase, wxSpinCtrlBase)
357 EVT_CHAR(wxSpinCtrlGenericBase::OnTextChar)
358 EVT_KILL_FOCUS(wxSpinCtrlGenericBase::OnTextLostFocus)
359 END_EVENT_TABLE()
360
361 void wxSpinCtrlGenericBase::OnSpinButton(wxSpinEvent& event)
362 {
363 event.Skip();
364
365 // Sync the textctrl since the user expects that the button will modify
366 // what they see in the textctrl.
367 SyncSpinToText();
368
369 int spin_value = event.GetPosition();
370 double step = (event.GetEventType() == wxEVT_SCROLL_LINEUP) ? 1 : -1;
371
372 // Use the spinbutton's acceleration, if any, but not if wrapping around
373 if (((spin_value >= 0) && (m_spin_value >= 0)) || ((spin_value <= 0) && (m_spin_value <= 0)))
374 step *= abs(spin_value - m_spin_value);
375
376 double value = AdjustToFitInRange(m_value + step*m_increment);
377
378 // Ignore the edges when it wraps since the up/down event may be opposite
379 // They are in GTK and Mac
380 if (abs(spin_value - m_spin_value) > SPINCTRLBUT_MAX)
381 {
382 m_spin_value = spin_value;
383 return;
384 }
385
386 m_spin_value = spin_value;
387
388 if ( DoSetValue(value) )
389 DoSendEvent();
390 }
391
392 void wxSpinCtrlGenericBase::OnTextLostFocus(wxFocusEvent& event)
393 {
394 SyncSpinToText();
395 DoSendEvent();
396
397 event.Skip();
398 }
399
400 void wxSpinCtrlGenericBase::OnTextChar(wxKeyEvent& event)
401 {
402 if ( !HasFlag(wxSP_ARROW_KEYS) )
403 {
404 event.Skip();
405 return;
406 }
407
408 double value = m_value;
409 switch ( event.GetKeyCode() )
410 {
411 case WXK_UP :
412 value += m_increment;
413 break;
414
415 case WXK_DOWN :
416 value -= m_increment;
417 break;
418
419 case WXK_PAGEUP :
420 value += m_increment * 10.0;
421 break;
422
423 case WXK_PAGEDOWN :
424 value -= m_increment * 10.0;
425 break;
426
427 default:
428 event.Skip();
429 return;
430 }
431
432 value = AdjustToFitInRange(value);
433
434 SyncSpinToText();
435
436 if ( DoSetValue(value) )
437 DoSendEvent();
438 }
439
440 // ----------------------------------------------------------------------------
441 // Textctrl functions
442 // ----------------------------------------------------------------------------
443
444 bool wxSpinCtrlGenericBase::SyncSpinToText()
445 {
446 if ( !m_textCtrl || !m_textCtrl->IsModified() )
447 return false;
448
449 double textValue;
450 if ( DoTextToValue(m_textCtrl->GetValue(), &textValue) )
451 {
452 if (textValue > m_max)
453 textValue = m_max;
454 else if (textValue < m_min)
455 textValue = m_min;
456 }
457 else // text contents is not a valid number at all
458 {
459 // replace its contents with the last valid value
460 textValue = m_value;
461 }
462
463 // we must always set the value here, even if it's equal to m_value, as
464 // otherwise we could be left with an out of range value when leaving the
465 // text control and the current value is already m_max for example
466 return DoSetValue(textValue);
467 }
468
469 // ----------------------------------------------------------------------------
470 // changing value and range
471 // ----------------------------------------------------------------------------
472
473 void wxSpinCtrlGenericBase::SetValue(const wxString& text)
474 {
475 wxCHECK_RET( m_textCtrl, wxT("invalid call to wxSpinCtrl::SetValue") );
476
477 double val;
478 if ( DoTextToValue(text, &val) && InRange(val) )
479 {
480 DoSetValue(val);
481 }
482 else // not a number at all or out of range
483 {
484 m_textCtrl->SetValue(text);
485 m_textCtrl->SetSelection(0, -1);
486 m_textCtrl->SetInsertionPointEnd();
487 }
488 }
489
490 bool wxSpinCtrlGenericBase::DoSetValue(double val)
491 {
492 wxCHECK_MSG( m_textCtrl, false, wxT("invalid call to wxSpinCtrl::SetValue") );
493
494 if (!InRange(val))
495 return false;
496
497 if ( m_snap_to_ticks && (m_increment != 0) )
498 {
499 double snap_value = val / m_increment;
500
501 if (wxFinite(snap_value)) // FIXME what to do about a failure?
502 {
503 if ((snap_value - floor(snap_value)) < (ceil(snap_value) - snap_value))
504 val = floor(snap_value) * m_increment;
505 else
506 val = ceil(snap_value) * m_increment;
507 }
508 }
509
510 wxString str(DoValueToText(val));
511
512 if ((val != m_value) || (str != m_textCtrl->GetValue()))
513 {
514 if ( !DoTextToValue(str, &m_value ) ) // wysiwyg for textctrl
515 m_value = val;
516 m_textCtrl->SetValue( str );
517 m_textCtrl->SetInsertionPointEnd();
518 m_textCtrl->DiscardEdits();
519 return true;
520 }
521
522 return false;
523 }
524
525 double wxSpinCtrlGenericBase::AdjustToFitInRange(double value) const
526 {
527 if (value < m_min)
528 value = HasFlag(wxSP_WRAP) ? m_max : m_min;
529 if (value > m_max)
530 value = HasFlag(wxSP_WRAP) ? m_min : m_max;
531
532 return value;
533 }
534
535 void wxSpinCtrlGenericBase::DoSetRange(double min, double max)
536 {
537 m_min = min;
538 m_max = max;
539 }
540
541 void wxSpinCtrlGenericBase::DoSetIncrement(double inc)
542 {
543 m_increment = inc;
544 }
545
546 void wxSpinCtrlGenericBase::SetSnapToTicks(bool snap_to_ticks)
547 {
548 m_snap_to_ticks = snap_to_ticks;
549 DoSetValue(m_value);
550 }
551
552 void wxSpinCtrlGenericBase::SetSelection(long from, long to)
553 {
554 wxCHECK_RET( m_textCtrl, wxT("invalid call to wxSpinCtrl::SetSelection") );
555
556 m_textCtrl->SetSelection(from, to);
557 }
558
559 #ifndef wxHAS_NATIVE_SPINCTRL
560
561 //-----------------------------------------------------------------------------
562 // wxSpinCtrl
563 //-----------------------------------------------------------------------------
564
565 void wxSpinCtrl::DoSendEvent()
566 {
567 wxSpinEvent event( wxEVT_COMMAND_SPINCTRL_UPDATED, GetId());
568 event.SetEventObject( this );
569 event.SetPosition((int)(m_value + 0.5)); // FIXME should be SetValue
570 event.SetString(m_textCtrl->GetValue());
571 GetEventHandler()->ProcessEvent( event );
572 }
573
574 bool wxSpinCtrl::DoTextToValue(const wxString& text, double *val)
575 {
576 long lval;
577 if ( !text.ToLong(&lval) )
578 return false;
579
580 *val = static_cast<double>(lval);
581
582 return true;
583 }
584
585 wxString wxSpinCtrl::DoValueToText(double val)
586 {
587 return wxString::Format("%ld", static_cast<long>(val));
588 }
589
590 #endif // !wxHAS_NATIVE_SPINCTRL
591
592 //-----------------------------------------------------------------------------
593 // wxSpinCtrlDouble
594 //-----------------------------------------------------------------------------
595
596 IMPLEMENT_DYNAMIC_CLASS(wxSpinCtrlDouble, wxSpinCtrlGenericBase)
597
598 void wxSpinCtrlDouble::DoSendEvent()
599 {
600 wxSpinDoubleEvent event( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, GetId());
601 event.SetEventObject( this );
602 event.SetValue(m_value);
603 event.SetString(m_textCtrl->GetValue());
604 GetEventHandler()->ProcessEvent( event );
605 }
606
607 bool wxSpinCtrlDouble::DoTextToValue(const wxString& text, double *val)
608 {
609 return text.ToDouble(val);
610 }
611
612 wxString wxSpinCtrlDouble::DoValueToText(double val)
613 {
614 return wxString::Format(m_format, val);
615 }
616
617 void wxSpinCtrlDouble::SetDigits(unsigned digits)
618 {
619 wxCHECK_RET( digits <= 20, "too many digits for wxSpinCtrlDouble" );
620
621 if ( digits == m_digits )
622 return;
623
624 m_digits = digits;
625
626 m_format.Printf(wxT("%%0.%ulf"), digits);
627
628 DoSetValue(m_value);
629 }
630
631 #endif // wxUSE_SPINBTN
632
633 #endif // !wxPort-with-native-spinctrl
634
635 #endif // wxUSE_SPINCTRL