valnum.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/valnum.h
  3. // Purpose: Numeric validator classes.
  4. // Author: Vadim Zeitlin based on the submission of Fulvio Senore
  5. // Created: 2010-11-06
  6. // Copyright: (c) 2010 wxWidgets team
  7. // (c) 2011 Vadim Zeitlin <vadim@wxwidgets.org>
  8. // Licence: wxWindows licence
  9. /////////////////////////////////////////////////////////////////////////////
  10. #ifndef _WX_VALNUM_H_
  11. #define _WX_VALNUM_H_
  12. #include "wx/defs.h"
  13. #if wxUSE_VALIDATORS
  14. #include "wx/validate.h"
  15. #include <limits>
  16. // Bit masks used for numeric validator styles.
  17. enum wxNumValidatorStyle
  18. {
  19. wxNUM_VAL_DEFAULT = 0x0,
  20. wxNUM_VAL_THOUSANDS_SEPARATOR = 0x1,
  21. wxNUM_VAL_ZERO_AS_BLANK = 0x2,
  22. wxNUM_VAL_NO_TRAILING_ZEROES = 0x4
  23. };
  24. // ----------------------------------------------------------------------------
  25. // Base class for all numeric validators.
  26. // ----------------------------------------------------------------------------
  27. class WXDLLIMPEXP_CORE wxNumValidatorBase : public wxValidator
  28. {
  29. public:
  30. // Change the validator style. Usually it's specified during construction.
  31. void SetStyle(int style) { m_style = style; }
  32. // Override base class method to not do anything but always return success:
  33. // we don't need this as we do our validation on the fly here.
  34. virtual bool Validate(wxWindow * WXUNUSED(parent)) { return true; }
  35. protected:
  36. wxNumValidatorBase(int style)
  37. {
  38. m_style = style;
  39. }
  40. wxNumValidatorBase(const wxNumValidatorBase& other) : wxValidator()
  41. {
  42. m_style = other.m_style;
  43. }
  44. bool HasFlag(wxNumValidatorStyle style) const
  45. {
  46. return (m_style & style) != 0;
  47. }
  48. // Get the text entry of the associated control. Normally shouldn't ever
  49. // return NULL (and will assert if it does return it) but the caller should
  50. // still test the return value for safety.
  51. wxTextEntry *GetTextEntry() const;
  52. // Convert wxNUM_VAL_THOUSANDS_SEPARATOR and wxNUM_VAL_NO_TRAILING_ZEROES
  53. // bits of our style to the corresponding wxNumberFormatter::Style values.
  54. int GetFormatFlags() const;
  55. // Return true if pressing a '-' key is acceptable for the current control
  56. // contents and insertion point. This is meant to be called from the
  57. // derived class IsCharOk() implementation.
  58. bool IsMinusOk(const wxString& val, int pos) const;
  59. // Return the string which would result from inserting the given character
  60. // at the specified position.
  61. wxString GetValueAfterInsertingChar(wxString val, int pos, wxChar ch) const
  62. {
  63. val.insert(pos, ch);
  64. return val;
  65. }
  66. private:
  67. // Check whether the specified character can be inserted in the control at
  68. // the given position in the string representing the current controls
  69. // contents.
  70. //
  71. // Notice that the base class checks for '-' itself so it's never passed to
  72. // this function.
  73. virtual bool IsCharOk(const wxString& val, int pos, wxChar ch) const = 0;
  74. // NormalizeString the contents of the string if it's a valid number, return
  75. // empty string otherwise.
  76. virtual wxString NormalizeString(const wxString& s) const = 0;
  77. // Event handlers.
  78. void OnChar(wxKeyEvent& event);
  79. void OnKillFocus(wxFocusEvent& event);
  80. // Determine the current insertion point and text in the associated control.
  81. void GetCurrentValueAndInsertionPoint(wxString& val, int& pos) const;
  82. // Combination of wxVAL_NUM_XXX values.
  83. int m_style;
  84. wxDECLARE_EVENT_TABLE();
  85. wxDECLARE_NO_ASSIGN_CLASS(wxNumValidatorBase);
  86. };
  87. namespace wxPrivate
  88. {
  89. // This is a helper class used by wxIntegerValidator and wxFloatingPointValidator
  90. // below that implements Transfer{To,From}Window() adapted to the type of the
  91. // variable.
  92. //
  93. // The template argument B is the name of the base class which must derive from
  94. // wxNumValidatorBase and define LongestValueType type and {To,As}String()
  95. // methods i.e. basically be one of wx{Integer,Number}ValidatorBase classes.
  96. //
  97. // The template argument T is just the type handled by the validator that will
  98. // inherit from this one.
  99. template <class B, typename T>
  100. class wxNumValidator : public B
  101. {
  102. public:
  103. typedef B BaseValidator;
  104. typedef T ValueType;
  105. typedef typename BaseValidator::LongestValueType LongestValueType;
  106. // FIXME-VC6: This compiler fails to compile the assert below with a
  107. // nonsensical error C2248: "'LongestValueType' : cannot access protected
  108. // typedef declared in class 'wxIntegerValidatorBase'" so just disable the
  109. // check for it.
  110. #ifndef __VISUALC6__
  111. wxCOMPILE_TIME_ASSERT
  112. (
  113. sizeof(ValueType) <= sizeof(LongestValueType),
  114. UnsupportedType
  115. );
  116. #endif // __VISUALC6__
  117. void SetMin(ValueType min)
  118. {
  119. this->DoSetMin(min);
  120. }
  121. void SetMax(ValueType max)
  122. {
  123. this->DoSetMax(max);
  124. }
  125. void SetRange(ValueType min, ValueType max)
  126. {
  127. SetMin(min);
  128. SetMax(max);
  129. }
  130. virtual bool TransferToWindow()
  131. {
  132. if ( m_value )
  133. {
  134. wxTextEntry * const control = BaseValidator::GetTextEntry();
  135. if ( !control )
  136. return false;
  137. control->SetValue(NormalizeValue(*m_value));
  138. }
  139. return true;
  140. }
  141. virtual bool TransferFromWindow()
  142. {
  143. if ( m_value )
  144. {
  145. wxTextEntry * const control = BaseValidator::GetTextEntry();
  146. if ( !control )
  147. return false;
  148. const wxString s(control->GetValue());
  149. LongestValueType value;
  150. if ( s.empty() && BaseValidator::HasFlag(wxNUM_VAL_ZERO_AS_BLANK) )
  151. value = 0;
  152. else if ( !BaseValidator::FromString(s, &value) )
  153. return false;
  154. if ( !this->IsInRange(value) )
  155. return false;
  156. *m_value = static_cast<ValueType>(value);
  157. }
  158. return true;
  159. }
  160. protected:
  161. wxNumValidator(ValueType *value, int style)
  162. : BaseValidator(style),
  163. m_value(value)
  164. {
  165. }
  166. // Implement wxNumValidatorBase virtual method which is the same for
  167. // both integer and floating point numbers.
  168. virtual wxString NormalizeString(const wxString& s) const
  169. {
  170. LongestValueType value;
  171. return BaseValidator::FromString(s, &value) ? NormalizeValue(value)
  172. : wxString();
  173. }
  174. private:
  175. // Just a helper which is a common part of TransferToWindow() and
  176. // NormalizeString(): returns string representation of a number honouring
  177. // wxNUM_VAL_ZERO_AS_BLANK flag.
  178. wxString NormalizeValue(LongestValueType value) const
  179. {
  180. wxString s;
  181. if ( value != 0 || !BaseValidator::HasFlag(wxNUM_VAL_ZERO_AS_BLANK) )
  182. s = this->ToString(value);
  183. return s;
  184. }
  185. ValueType * const m_value;
  186. wxDECLARE_NO_ASSIGN_CLASS(wxNumValidator);
  187. };
  188. } // namespace wxPrivate
  189. // ----------------------------------------------------------------------------
  190. // Validators for integer numbers.
  191. // ----------------------------------------------------------------------------
  192. // Base class for integer numbers validator. This class contains all non
  193. // type-dependent code of wxIntegerValidator<> and always works with values of
  194. // type LongestValueType. It is not meant to be used directly, please use
  195. // wxIntegerValidator<> only instead.
  196. class WXDLLIMPEXP_CORE wxIntegerValidatorBase : public wxNumValidatorBase
  197. {
  198. protected:
  199. // Define the type we use here, it should be the maximal-sized integer type
  200. // we support to make it possible to base wxIntegerValidator<> for any type
  201. // on it.
  202. #ifdef wxLongLong_t
  203. typedef wxLongLong_t LongestValueType;
  204. #else
  205. typedef long LongestValueType;
  206. #endif
  207. wxIntegerValidatorBase(int style)
  208. : wxNumValidatorBase(style)
  209. {
  210. wxASSERT_MSG( !(style & wxNUM_VAL_NO_TRAILING_ZEROES),
  211. "This style doesn't make sense for integers." );
  212. }
  213. wxIntegerValidatorBase(const wxIntegerValidatorBase& other)
  214. : wxNumValidatorBase(other)
  215. {
  216. m_min = other.m_min;
  217. m_max = other.m_max;
  218. }
  219. // Provide methods for wxNumValidator use.
  220. wxString ToString(LongestValueType value) const;
  221. static bool FromString(const wxString& s, LongestValueType *value);
  222. void DoSetMin(LongestValueType min) { m_min = min; }
  223. void DoSetMax(LongestValueType max) { m_max = max; }
  224. bool IsInRange(LongestValueType value) const
  225. {
  226. return m_min <= value && value <= m_max;
  227. }
  228. // Implement wxNumValidatorBase pure virtual method.
  229. virtual bool IsCharOk(const wxString& val, int pos, wxChar ch) const;
  230. private:
  231. // Minimal and maximal values accepted (inclusive).
  232. LongestValueType m_min, m_max;
  233. wxDECLARE_NO_ASSIGN_CLASS(wxIntegerValidatorBase);
  234. };
  235. // Validator for integer numbers. It can actually work with any integer type
  236. // (short, int or long and long long if supported) and their unsigned versions
  237. // as well.
  238. template <typename T>
  239. class wxIntegerValidator
  240. : public wxPrivate::wxNumValidator<wxIntegerValidatorBase, T>
  241. {
  242. public:
  243. typedef T ValueType;
  244. typedef
  245. wxPrivate::wxNumValidator<wxIntegerValidatorBase, T> Base;
  246. // Ctor for an integer validator.
  247. //
  248. // Sets the range appropriately for the type, including setting 0 as the
  249. // minimal value for the unsigned types.
  250. wxIntegerValidator(ValueType *value = NULL, int style = wxNUM_VAL_DEFAULT)
  251. : Base(value, style)
  252. {
  253. this->DoSetMin(std::numeric_limits<ValueType>::min());
  254. this->DoSetMax(std::numeric_limits<ValueType>::max());
  255. }
  256. virtual wxObject *Clone() const { return new wxIntegerValidator(*this); }
  257. private:
  258. wxDECLARE_NO_ASSIGN_CLASS(wxIntegerValidator);
  259. };
  260. // Helper function for creating integer validators which allows to avoid
  261. // explicitly specifying the type as it deduces it from its parameter.
  262. template <typename T>
  263. inline wxIntegerValidator<T>
  264. wxMakeIntegerValidator(T *value, int style = wxNUM_VAL_DEFAULT)
  265. {
  266. return wxIntegerValidator<T>(value, style);
  267. }
  268. // ----------------------------------------------------------------------------
  269. // Validators for floating point numbers.
  270. // ----------------------------------------------------------------------------
  271. // Similar to wxIntegerValidatorBase, this class is not meant to be used
  272. // directly, only wxFloatingPointValidator<> should be used in the user code.
  273. class WXDLLIMPEXP_CORE wxFloatingPointValidatorBase : public wxNumValidatorBase
  274. {
  275. public:
  276. // Set precision i.e. the number of digits shown (and accepted on input)
  277. // after the decimal point. By default this is set to the maximal precision
  278. // supported by the type handled by the validator.
  279. void SetPrecision(unsigned precision) { m_precision = precision; }
  280. protected:
  281. // Notice that we can't use "long double" here because it's not supported
  282. // by wxNumberFormatter yet, so restrict ourselves to just double (and
  283. // float).
  284. typedef double LongestValueType;
  285. wxFloatingPointValidatorBase(int style)
  286. : wxNumValidatorBase(style)
  287. {
  288. }
  289. wxFloatingPointValidatorBase(const wxFloatingPointValidatorBase& other)
  290. : wxNumValidatorBase(other)
  291. {
  292. m_precision = other.m_precision;
  293. m_min = other.m_min;
  294. m_max = other.m_max;
  295. }
  296. // Provide methods for wxNumValidator use.
  297. wxString ToString(LongestValueType value) const;
  298. static bool FromString(const wxString& s, LongestValueType *value);
  299. void DoSetMin(LongestValueType min) { m_min = min; }
  300. void DoSetMax(LongestValueType max) { m_max = max; }
  301. bool IsInRange(LongestValueType value) const
  302. {
  303. return m_min <= value && value <= m_max;
  304. }
  305. // Implement wxNumValidatorBase pure virtual method.
  306. virtual bool IsCharOk(const wxString& val, int pos, wxChar ch) const;
  307. private:
  308. // Maximum number of decimals digits after the decimal separator.
  309. unsigned m_precision;
  310. // Minimal and maximal values accepted (inclusive).
  311. LongestValueType m_min, m_max;
  312. wxDECLARE_NO_ASSIGN_CLASS(wxFloatingPointValidatorBase);
  313. };
  314. // Validator for floating point numbers. It can be used with float, double or
  315. // long double values.
  316. template <typename T>
  317. class wxFloatingPointValidator
  318. : public wxPrivate::wxNumValidator<wxFloatingPointValidatorBase, T>
  319. {
  320. public:
  321. typedef T ValueType;
  322. typedef wxPrivate::wxNumValidator<wxFloatingPointValidatorBase, T> Base;
  323. // Ctor using implicit (maximal) precision for this type.
  324. wxFloatingPointValidator(ValueType *value = NULL,
  325. int style = wxNUM_VAL_DEFAULT)
  326. : Base(value, style)
  327. {
  328. DoSetMinMax();
  329. this->SetPrecision(std::numeric_limits<ValueType>::digits10);
  330. }
  331. // Ctor specifying an explicit precision.
  332. wxFloatingPointValidator(int precision,
  333. ValueType *value = NULL,
  334. int style = wxNUM_VAL_DEFAULT)
  335. : Base(value, style)
  336. {
  337. DoSetMinMax();
  338. this->SetPrecision(precision);
  339. }
  340. virtual wxObject *Clone() const
  341. {
  342. return new wxFloatingPointValidator(*this);
  343. }
  344. private:
  345. void DoSetMinMax()
  346. {
  347. // NB: Do not use min(), it's not the smallest representable value for
  348. // the floating point types but rather the smallest representable
  349. // positive value.
  350. this->DoSetMin(-std::numeric_limits<ValueType>::max());
  351. this->DoSetMax( std::numeric_limits<ValueType>::max());
  352. }
  353. };
  354. // Helper similar to wxMakeIntValidator().
  355. //
  356. // NB: Unfortunately we can't just have a wxMakeNumericValidator() which would
  357. // return either wxIntegerValidator<> or wxFloatingPointValidator<> so we
  358. // do need two different functions.
  359. template <typename T>
  360. inline wxFloatingPointValidator<T>
  361. wxMakeFloatingPointValidator(T *value, int style = wxNUM_VAL_DEFAULT)
  362. {
  363. return wxFloatingPointValidator<T>(value, style);
  364. }
  365. template <typename T>
  366. inline wxFloatingPointValidator<T>
  367. wxMakeFloatingPointValidator(int precision, T *value, int style = wxNUM_VAL_DEFAULT)
  368. {
  369. return wxFloatingPointValidator<T>(precision, value, style);
  370. }
  371. #endif // wxUSE_VALIDATORS
  372. #endif // _WX_VALNUM_H_