tonalutils.cpp raw

   1  // Copyright (c) 2016 The Limenka developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #include <qt/tonalutils.h>
   6  
   7  #include <QFont>
   8  #include <QFontMetrics>
   9  #include <QRegularExpression>
  10  #include <QRegularExpressionValidator>
  11  #include <QString>
  12  
  13  static const QList<QChar> tonal_digits{QChar(0xe8ef), QChar(0xe8ee), QChar(0xe8ed), QChar(0xe8ec), QChar(0xe8eb), QChar(0xe8ea), QChar(0xe8e9), '8', '7', '6', '5', '4', '3', '2', '1', '0'};
  14  
  15  bool TonalUtils::font_supports_tonal(const QFont& font)
  16  {
  17      const QFontMetrics fm(font);
  18      QString s = "000";
  19      const QSize sz = fm.size(0, s);
  20      for (const auto& c : tonal_digits) {
  21          if (!fm.inFont(c)) return false;
  22          s[0] = s[1] = s[2] = c;
  23          if (sz != fm.size(0, s)) return false;
  24      }
  25      return true;
  26  }
  27  
  28  #define RE_TONAL_DIGIT "[\\d\\xe8e0-\\xe8ef\\xe9d0-\\xe9df]"
  29  static QRegularExpressionValidator tv(QRegularExpression("-?(?:" RE_TONAL_DIGIT "+\\.?|" RE_TONAL_DIGIT "*\\." RE_TONAL_DIGIT "+)"), nullptr);
  30  
  31  QValidator::State TonalUtils::validate(QString&input, int&pos)
  32  {
  33      return tv.validate(input, pos);
  34  }
  35  
  36  void TonalUtils::ConvertFromHex(QString&str)
  37  {
  38      for (int i = 0; i < str.size(); ++i) {
  39          ushort c = str[i].unicode();
  40          if (c == '9') {
  41              str[i] = QChar(0xe8e9);
  42          } else if (c >= 'A' && c <= 'F') {
  43              str[i] = QChar(c + (0xe8ea - 'A'));
  44          } else if (c >= 'a' && c <= 'f') {
  45              str[i] = QChar(c + (0xe8ea - 'a'));
  46          }
  47      }
  48  }
  49  
  50  void TonalUtils::ConvertToHex(QString&str)
  51  {
  52      for (int i = 0; i < str.size(); ++i) {
  53          ushort c = str[i].unicode();
  54          if (c == '9') {
  55              str[i] = 'a';
  56          } else if (c >= 0xe8e0 && c <= 0xe8e9) {  // UCSUR 0-9
  57              str[i] = QChar(c - (0xe8e0 - '0'));
  58          } else if (c >= 0xe8ea && c <= 0xe8ef) {  // UCSUR a-f
  59              str[i] = QChar(c - (0xe8ea - 'a'));
  60          } else if (c >= 0xe9d0 && c <= 0xe9d9) {
  61              str[i] = QChar(c - (0xe9d0 - '0'));
  62          } else if (c >= 0xe9da && c <= 0xe9df) {
  63              str[i] = QChar(c - 0xe999);
  64          }
  65      }
  66  }
  67