Ejemplo n.º 1
0
void testTypingValue(
    SpinBoxType* sbox, QPushButton *okButton, const QString &value)
{
    sbox->selectAll();
    for (int i = 0; i < value.size(); ++i) {
        const QChar valChar = value[i];
	_keyClick(static_cast<QWidget *>(sbox), valChar.toAscii()); // ### always guaranteed to work?
        if (sbox->hasAcceptableInput())
            QVERIFY(okButton->isEnabled());
        else
            QVERIFY(!okButton->isEnabled());
    }
}
Ejemplo n.º 2
0
inline static bool isQuoteMeta( QChar cUnicode )
{
#if 0 // it's not worth it, especially after seeing gcc's asm output ...
    static const uchar iqm[] = {
        0x00, 0x00, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00
    }; // \'"$

    return (c < sizeof(iqm) * 8) && (iqm[c / 8] & (1 << (c & 7)));
#else
    char c = cUnicode.toAscii();
    return c == '\\' || c == '\'' || c == '"' || c == '$';
#endif
}
Ejemplo n.º 3
0
void EnhancedPathShape::modifyReference(const QString &reference, qreal value)
{
    if (reference.isEmpty())
        return;

    QChar c = reference[0];

    if (c.toAscii() == '$') {
        bool success = false;
        int modifierIndex = reference.mid(1).toInt(&success);
        if (modifierIndex >= 0 && modifierIndex < m_modifiers.count())
            m_modifiers[modifierIndex] = value;
    }
}
Ejemplo n.º 4
0
void OmaSaunalahti::sendMessage(QNetworkAccessManager* manager, QString message) {
    if (message.toAscii().length()==0)
        return;
    this->loggedIn = false;
    connect(manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)));

    this->message = message;
    this->messageTime = QString("%0 %1").arg(QDate::currentDate().toString("dd.MM.yyyy")).arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
    QChar *messageChar = this->message.data();
    while (!messageChar->isNull()) {
        if (messageChar->isSpace()) {
               QString chr = QString("%0").arg(QString::number( messageChar->toAscii(), 16 ).toUpper());
               if (chr.length()==1)
                   chr = "%0" + chr;
               this->message = this->message.replace(messageChar->toAscii(),chr);
         }
        ++messageChar;
    }
    QUrl url = QUrl(this->server);
    url.addQueryItem("username",this->username);
    url.addQueryItem("login","Sisään");
    url.addQueryItem("password",this->password);

    QNetworkRequest request;
    request.setUrl(url);
    QNetworkReply *reply = manager->post(request,url.toString().split("?")[1].toAscii());

    url.setEncodedQuery(QByteArray());
    url.addQueryItem("sender",this->sender);
    url.addQueryItem("recipients",this->receiver);
    url.addQueryItem("text",this->message);
    url.addQueryItem("size",QString("%0").arg(this->message.toAscii().length()));
    url.addQueryItem("send","Lähetä");
    connect(manager, SIGNAL(finished(QNetworkReply*)), SLOT(messageSent(QNetworkReply*)));
    reply = manager->post(request,url.toString().split("?")[1].toAscii());
}
Ejemplo n.º 5
0
KoEnhancedPathParameter * KoEnhancedPathShape::parameter( const QString & text )
{
    Q_ASSERT( ! text.isEmpty() );

    ParameterStore::const_iterator parameterIt = m_parameters.constFind( text );
    if( parameterIt != m_parameters.constEnd() )
        return parameterIt.value();
    else
    {
        KoEnhancedPathParameter *parameter = 0;
        QChar c = text[0];
        if( c.toAscii() == '$' || c.toAscii() == '?' )
            parameter = new KoEnhancedPathReferenceParameter( text, this );
        else
        {
            if( c.isDigit() )
            {
                bool success = false;
                qreal constant = text.toDouble( &success );
                if( success )
                    parameter = new KoEnhancedPathConstantParameter( constant, this );
            }
            else
            {
                Identifier identifier = KoEnhancedPathNamedParameter::identifierFromString( text );
                if( identifier != IdentifierUnknown )
                    parameter = new KoEnhancedPathNamedParameter( identifier, this );
            }
        }

        if( parameter )
            m_parameters[text] = parameter;

        return parameter;
    }
}
void Settings::loadSettings(const QString & fileName, QByteArray * windowGeometry, QByteArray * windowState)
{
	QString path = fileName;
	if(fileName.isEmpty())
	{
		path = iniDefaultPath();
	}
	QSettings ini(path, QSettings::IniFormat);
	for(ParametersMap::const_iterator iter = defaultParameters_.begin(); iter!=defaultParameters_.end(); ++iter)
	{
		const QString & key = iter.key();
		QVariant value = ini.value(key, QVariant());
		if(value.isValid())
		{
			QString str = value.toString();
			if(str.contains(";") && str.size() != getParameter(key).toString().size())
			{
				// If a string list is modified, update the value
				// (assuming that index < 10... one character for index)
				QChar index = str.at(0);
				str = getParameter(key).toString();
				str[0] = index.toAscii();
				value = QVariant(str);
				printf("Updated list of parameter \"%s\"\n", key.toStdString().c_str());
			}
			setParameter(key, value);
		}
	}

	if(windowGeometry)
	{
		QVariant value = ini.value("windowGeometry", QVariant());
		if(value.isValid())
		{
			*windowGeometry = value.toByteArray();
		}
	}
	if(windowState)
	{
		QVariant value = ini.value("windowState", QVariant());
		if(value.isValid())
		{
			*windowState = value.toByteArray();
		}
	}

	printf("Settings loaded from %s\n", path.toStdString().c_str());
}
Ejemplo n.º 7
0
QString ParseTokken(QTextStream &in) {
    static QChar last;
    QChar c;
    QString sum;
    in >> c;
    switch (c.toAscii()) {
    case '(':
    case ';':
    case ')':
    case '[':
    case ']':
    case '\\':
        return c;
    }
    return "";
}
Ejemplo n.º 8
0
bool Settings::RegistHotkey(QWidget *window,
		QChar keyValue,
		Qt::KeyboardModifiers keyMod)
{
#if WIN32
	WId w_handle = window ? window->winId(): 0;
		int modifiy = QtModToWinMod(keyMod);
		return RegisterHotKey(w_handle, hotkey_id, modifiy, VkKeyScan
				(keyValue.toAscii()));
#else //liunx or mac os are not implement...
		Q_UNUSED(window);
		Q_UNUSED(keyValue);
		Q_UNUSED(keyMod);
		return false;
#endif
		
}
 QString encodeUnicode(const QString & unicode)
 {
     QString encoded;
     for (int i = 0; i < unicode.length(); ++i)
     {
         QChar ch = unicode[i];
         if (ch == ch.toAscii())
         {
             encoded += ch;
         }
         else
         {
             encoded += "\\u" + QString("%1").arg((ushort) ch.unicode(), (int) 4, (int) 16, QChar('0')).toUpper();
         }
     }
     return encoded;
 }
Ejemplo n.º 10
0
bool EPath::mountNetwork(QChar drive) {
	// Mount network drive
	QProcess net_use;
	LAPP_ << "Mounting network path to " << drive.toAscii();
	QString mount_command = QString("net use %1: \"%2\"").arg(drive).arg(m_path);
	LDEBUG_ << "Executing: " << QSTR(mount_command);
	net_use.start(mount_command);
	net_use.waitForFinished();
	if (net_use.exitCode() != 0)
		return false;

	m_remote_path_mounted = true;

	m_usable_drive = drive;

	return true;
}
Ejemplo n.º 11
0
void Settings::loadSettings(const QString & fileName)
{
	QString path = fileName;
	if(fileName.isEmpty())
	{
		path = iniPath();
	}
	if(!path.isEmpty())
	{
		QSettings ini(path, QSettings::IniFormat);
		for(ParametersMap::const_iterator iter = defaultParameters_.begin(); iter!=defaultParameters_.end(); ++iter)
		{
			const QString & key = iter.key();
			QVariant value = ini.value(key, QVariant());
			if(value.isValid())
			{
				QString str = value.toString();
				if(str.contains(";") && str.size() != getParameter(key).toString().size())
				{
					// If a string list is modified, update the value
					// (assuming that index < 10... one character for index)
					QChar index = str.at(0);
					str = getParameter(key).toString();
					str[0] = index.toAscii();
					value = QVariant(str);
					UINFO("Updated list of parameter \"%s\"", key.toStdString().c_str());
				}
				setParameter(key, value);
			}
		}
		UINFO("Settings loaded from %s.", path.toStdString().c_str());
	}
	else
	{
		parameters_ = defaultParameters_;
		UINFO("Settings set to defaults.");
	}

	if(cv::gpu::getCudaEnabledDeviceCount() == 0)
	{
		Settings::setFeature2D_SURF_gpu(false);
		Settings::setFeature2D_Fast_gpu(false);
		Settings::setFeature2D_ORB_gpu(false);
	}
}
Ejemplo n.º 12
0
bool isVowell(QChar v){
    if ( v > 'A' || v < 'z')
        return false;
    v = v.toLower();
    switch (v.toAscii())
    {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'y':
            return true;
        default:
            break;
    }
    return false;
}
Ejemplo n.º 13
0
bool XLIFFHandler::characters(const QString &ch)
{
    if (currentContext() == XC_ph) {
        // handle the content of <ph> elements
        for (int i = 0; i < ch.count(); ++i) {
            QChar chr = ch.at(i);
            if (accum.endsWith(QLatin1Char('\\')))
                accum[accum.size() - 1] = QLatin1Char(charFromEscape(chr.toAscii()));
            else
                accum.append(chr);
        }
    } else {
        QString t = ch;
        t.replace(QLatin1String("\r"), QLatin1String(""));
        accum.append(t);
    }
    return true;
}
Ejemplo n.º 14
0
QString TextUtils::sanitize(QString const& original)
{
    QString result;

    for (int i = 0; i < original.length(); i++)
    {
        QChar c = original.at(i);
        uchar_t mychar = c.toAscii();
        bool valid = sfn_chars[mychar/8] & ( 1 << (mychar % 8) );

        if (valid) {
            result.append(c);
        } else {
            result.append("_");
        }
    }

    return result;
}
Ejemplo n.º 15
0
void Loader::keyPressEvent(QKeyEvent* e)
{
    int key = e->key();
    if(this->running == false)
        return;

    if(this->disableIO)
        return;

    if(e->matches((QKeySequence::Copy))) {
        copy();
        return;
    }
    if(e->matches((QKeySequence::Paste))) {
        QClipboard *clip = QApplication::clipboard();
        QString command = clip->text();
        this->insertPlainText(command);
        QByteArray barry(command.toAscii());
        process->write(barry);
        return;
    }

    switch(key)
    {
        case Qt::Key_Enter:
        case Qt::Key_Return:
            key = '\n';
            break;
        case Qt::Key_Backspace:
            key = '\b';
            break;
        default:
            if(key & Qt::Key_Escape)
                return;
            QChar c = e->text().at(0);
            key = (int)c.toAscii();
            break;
    }
    QByteArray barry;
    barry.append((char)key);
    process->write(barry);
}
Ejemplo n.º 16
0
QVariant Cell::computeFormula(const QString &formula, SpreadSheet *widget) const
{
    QVariant result = QVariant::Invalid,
             firstOperand = QVariant::Invalid,
             secondOperand = QVariant::Invalid;
    QString aux = formula;
    int firstOp = firstOperatorPosition(aux);
    if (firstOp == -1)
        result = parseMember(aux, widget);
    while (firstOp != -1)
    {
        if (result == QVariant::Invalid)
            firstOperand = parseMember(aux.left(firstOp), widget);
        else
            firstOperand = result;
        QChar firstOperator = aux[firstOp];
        aux = aux.mid(firstOp+1);
        firstOp = firstOperatorPosition(aux);
        if (firstOp == -1)
            secondOperand = parseMember(aux, widget);
        else
            secondOperand = parseMember(aux.left(firstOp), widget);

        switch (firstOperator.toAscii())
        {
            case '+':
                result = firstOperand.toDouble() + secondOperand.toDouble();
                break;
            case '-':
                result = firstOperand.toDouble() - secondOperand.toDouble();
                break;
            case '*':
                result = firstOperand.toDouble() * secondOperand.toDouble();
                break;
            case '/':
                result = firstOperand.toDouble() / secondOperand.toDouble();
                break;
        }
    }
    return result;
}
Ejemplo n.º 17
0
qreal KoEnhancedPathShape::evaluateReference( const QString &reference )
{
    if( reference.isEmpty() )
        return 0.0;

    QChar c = reference[0];

    qreal res = 0.0;

    switch( c.toAscii() )
    {
        // referenced modifier
        case '$':
        {
            bool success = false;
            int modifierIndex = reference.mid( 1 ).toInt( &success );
            res = m_modifiers[modifierIndex];
        }
        break;
        // referenced formula
        case '?':
        {
            QString fname = reference.mid( 1 );
            FormulaStore::const_iterator formulaIt = m_formulae.constFind( fname );
            if( formulaIt != m_formulae.constEnd() )
            {
                KoEnhancedPathFormula * formula = formulaIt.value();
                if( formula )
                    res = formula->evaluate();
            }
        }
        break;
        // maybe an identifier ?
        default:
            KoEnhancedPathNamedParameter p( reference, this );
            res = p.evaluate();
        break;
    }

    return res;
}
Ejemplo n.º 18
0
// convert character to attribute
CmdAttribute LatexCommands::getCharAttr(QChar ch)
{
	CmdAttribute attr;
	switch(ch.toAscii()) {
		case 'a':
			attr = CmdAttrAmsmath;
		break;
		case 'm':
			attr = CmdAttrMath;
		break;
		case 'l':
			attr = CmdAttrList;
		break;
		case 'v':
			attr = CmdAttrVerbatim;
		break;
		case 't':
			attr = CmdAttrTabular;
		break;
		case 'L':
			attr = CmdAttrLabel;
		break;
		case 'R':
			attr = CmdAttrReference;
		break;
		case 'C':
			attr = CmdAttrCitations;
		break;
		case 'I':
			attr = CmdAttrIncludes;
		break;
		case 'B':
			attr = CmdAttrBibliographies;
		break;
		default:
			KILE_DEBUG() << "\tLatexCommands error: unknown type of env/cmd: " << static_cast<char>(ch.unicode());
			return CmdAttrNone;
	}

	return attr;
}
PlayerCommandParser::PlayerCommandParser( QString line ) throw( std::invalid_argument )
{
    line = line.trimmed();
    if (line.isEmpty()) throw invalid_argument( "Command string seems to be empty" );

    qDebug() << line;

    m_command = extractCommand( line ); //removes the command string from line

    line = line.trimmed();

    QMap<QChar, QString> const args = extractArgs( line );
    QString const required = requiredArgs( m_command );

    for (int i = 0; i < required.length(); ++i)
    {
        QChar const c = required[i];
        if (!args.contains( c ))
            throw invalid_argument( "Mandatory argument unspecified: " + c.toAscii() );
    }

    m_playerId = args['c'];
    
    if (m_playerId.isEmpty())
        throw invalid_argument( "Player ID cannot be zero length" );

    switch (m_command)
    {
        case CommandStart:
            m_track = extractTrack( args );
            break;
        case CommandBootstrap:
            m_username = args['u'];
            break;
        case CommandInit:
            m_applicationPath = args['f'];
        default:
            break;
    }
}
Ejemplo n.º 20
0
int topMenu::sizeNickName(QString name)
{
    QChar lyrics;
    int ASCII = 0;
    int space = 0;

    space = 20;

    for (int var = 0; var < name.length(); ++var)
    {
        lyrics = name.at(var).toAscii();
        ASCII = lyrics.toAscii();

        if(ASCII >= 65 && ASCII <= 90)
            space += 9;
        else
            space += 7;

        space--;
    }
    return  space;
}
Ejemplo n.º 21
0
/* This function returns \a number rounded using \a precision as precision indicator.
   The assumption is that the digit in position <code>precision+1</code> is used to work
   out what rounding rule to apply. This means the <code>precision+1</code>. digit in \a number
   must still be correct.
   */
QString roundDigits( const QString number, int precision ) {
    QString rounded = number;
    int point = number.indexOf( '.' ) ;
    if ( point > -1 && point <= precision-1 ) {
        bool up = (number.at(precision+1).isDigit() && number.at(precision+1) >= QChar('5')  );
        if ( !up ) {
            return rounded;
        }
        for ( int i = precision; i>= 0 ; i-- ) {
            if ( !up ) {
                return rounded;
            }
            QChar current = rounded.at(i);
            if ( !current.isDigit() ) {
                continue;
            }
            QChar newCurrent = (current == QChar('9')) ? QChar('0') : QChar(current.toAscii()+1) ;
            up = (newCurrent == QChar('0') );
            rounded = rounded.replace( i , 1,  newCurrent );
        }
    }
    return rounded;
}
Ejemplo n.º 22
0
void renderCode128(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc)
{
  QVector<int> str;
  int i = 0;

  // create the list.. if the list is empty then just set a start code and move on
  if(_str.isEmpty())
    str.push_back(104);
  else
  {
    int rank_a = 0;
    int rank_b = 0;
    int rank_c = 0;

    QChar c;
    for(i = 0; i < _str.length(); i++)
    {
      c = _str.at(i);
      rank_a += (code128Index(c, SETA) != -1 ? 1 : 0);
      rank_b += (code128Index(c, SETB) != -1 ? 1 : 0);
      rank_c += (c >= '0' && c <= '9' ? 1 : 0);
    }
    if(rank_c == _str.length() && ((rank_c % 2) == 0 || rank_c > 4))
    {
      // every value in the is a digit so we are going to go with mode C
      // and we have an even number or we have more than 4 values
      i = 0;
      if((rank_c % 2) == 1)
      {
        str.push_back(104); // START B
        c = _str.at(0);
        str.push_back(code128Index(c, SETB));
        str.push_back(99); // MODE C
        i = 1;
      }
      else
        str.push_back(105); // START C

      for(i = i; i < _str.length(); i+=2)
      {
        char a, b;
        c = _str.at(i);
        a = c.toAscii();
        a -= 48;
        c = _str.at(i+1);
        b = c.toAscii();
        b -= 48;
        str.push_back(int((a * 10) + b));
      }
    }
    else
    {
      // start in the mode that had the higher number of hits and then
      // just shift into the opposite mode as needed
      int set = ( rank_a > rank_b ? SETA : SETB );
      str.push_back(( rank_a > rank_b ? 103 : 104 ));
      int v = -1;
      for(i = 0; i < _str.length(); i++)
      {
        c = _str.at(i);
        v = code128Index(c, set);
        if(v == -1)
        {
          v = code128Index(c, (set == SETA ? SETB : SETA));
          if(v != -1)
          {
            str.push_back(98); // SHIFT
            str.push_back(v);
          }
        }
        else
          str.push_back(v);
      }
    }
  }

  // calculate and append the checksum value to the list
  int checksum = str.at(0);
  for(i = 1; i < str.size(); i++)
    checksum += (str.at(i) * i);
  checksum = checksum % 103;
  str.push_back(checksum);

  // lets determine some core attributes about this barcode
  qreal bar_width = bc->narrowBarWidth; 

  // this is are mandatory minimum quiet zone
  qreal quiet_zone = bar_width * 10;
  if(quiet_zone < 0.1)
    quiet_zone = 0.1;

  // what kind of area do we have to work with
  qreal draw_width = r.width();
  qreal draw_height = r.height();

  // how long is the value we need to encode?
  int val_length = str.size() - 2; // we include start and checksum in are list so
                                   // subtract them out for our calculations

  // L = (11C + 35)X 
  // L length of barcode (excluding quite zone) in units same as X and I
  // C the number of characters in the value excluding the start/stop and checksum characters
  // X the width of a bar (pixels in our case)
  qreal L;

  qreal C = val_length;
  qreal X = bar_width;

  L = (((11.0 * C) + 35.0) * X);

  // now we have the actual width the barcode will be so can determine the actual
  // size of the quiet zone (we assume we center the barcode in the given area
  // what should we do if the area is too small????
  // At the moment the way the code is written is we will always start at the minimum
  // required quiet zone if we don't have enough space.... I guess we'll just have over-run
  // to the right
  //
  // calculate the starting position based on the alignment option
  // for left align we don't need to do anything as the values are already setup for it
  if(bc->align == 1) // center
  {
    qreal nqz = (draw_width - L) / 2.0;
    if(nqz > quiet_zone)
      quiet_zone = nqz;
  }
  else if(bc->align > 1) // right
    quiet_zone = draw_width - (L + quiet_zone);
  // else if(align < 1) {} // left : do nothing

  qreal pos = r.left() + quiet_zone;
  qreal top = r.top();

  QPen pen(Qt::NoPen);
  QBrush brush(QColor("black"));

  bool space = false;
  int idx = 0, b = 0;
  qreal w = 0.0;
  for(i = 0; i < str.size(); i++)
  {
    // loop through each value and render the barcode
    idx = str.at(i);
    if(idx < 0 || idx > 105)
    {
      qDebug("Encountered a non-compliant element while rendering a 3of9 barcode -- skipping");
      continue;
    }
    space = false;
    for(b = 0; b < 6; b++, space = !space)
    {
      w = _128codes[idx].values[b] * bar_width;
      if(!space)
      {
        ORORect * rect = new ORORect(bc);
        rect->setPen(pen);
        rect->setBrush(brush);
        rect->setRect(QRectF(pos,top, w,draw_height));
        page->addPrimitive(rect);
      }
      pos += w;
    }
  }

  // we have to do the stop character seperatly like this because it has
  // 7 elements in it's bar sequence rather than 6 like the others
  int STOP_CHARACTER[]={ 2, 3, 3, 1, 1, 1, 2 };
  space = false;
  for(b = 0; b < 7; b++, space = !space)
  {
    w = STOP_CHARACTER[b] * bar_width;
    if(!space)
    {
      ORORect * rect = new ORORect(bc);
      rect->setPen(pen);
      rect->setBrush(brush);
      rect->setRect(QRectF(pos,top, w,draw_height));
      page->addPrimitive(rect);
    }
    pos += w;
  }

  return;
} 
Ejemplo n.º 23
0
static int getToken()
{
    const char tab[] = "bfnrt\"\'\\";
    const char backTab[] = "\b\f\n\r\t\"\'\\";

    yyIdent.clear();
    yyComment.clear();
    yyString.clear();

    while ( yyCh != EOF ) {
        yyLineNo = yyCurLineNo;

        if ( yyCh.isLetter() || yyCh.toLatin1() == '_' ) {
            do {
                yyIdent.append(yyCh);
                yyCh = getChar();
            } while ( yyCh.isLetterOrNumber() || yyCh.toLatin1() == '_' );

            if (yyTok != Tok_Dot) {
                switch ( yyIdent.at(0).toLatin1() ) {
                    case 'r':
                        if ( yyIdent == QLatin1String("return") )
                            return Tok_return;
                        break;
                     case 'c':
                        if ( yyIdent == QLatin1String("class") )
                            return Tok_class;
                        break;
                     case 'n':
                         if ( yyIdent == QLatin1String("null") )
                             return Tok_null;
                        break;
                }
            }
            switch ( yyIdent.at(0).toLatin1() ) {
            case 'T':
                // TR() for when all else fails
                if ( yyIdent == QLatin1String("TR") )
                    return Tok_tr;
                break;
            case 'p':
                if( yyIdent == QLatin1String("package") )
                    return Tok_Package;
                break;
            case 't':
                if ( yyIdent == QLatin1String("tr") )
                    return Tok_tr;
                if ( yyIdent == QLatin1String("translate") )
                    return Tok_translate;
                }
            return Tok_Ident;
        } else {
            switch ( yyCh.toLatin1() ) {

            case '/':
                yyCh = getChar();
                if ( yyCh == QLatin1Char('/') ) {
                    do {
                        yyCh = getChar();
                        if (yyCh == EOF)
                            break;
                        yyComment.append(yyCh);
                    } while (yyCh != QLatin1Char('\n'));
                    return Tok_Comment;

                } else if ( yyCh == QLatin1Char('*') ) {
                    bool metAster = false;
                    bool metAsterSlash = false;

                    while ( !metAsterSlash ) {
                        yyCh = getChar();
                        if ( yyCh == EOF ) {
                            qFatal( "%s: Unterminated Java comment starting at"
                                    " line %d\n",
                                    qPrintable(yyFileName), yyLineNo );

                            return Tok_Comment;
                        }

                        yyComment.append( yyCh );

                        if ( yyCh == QLatin1Char('*') )
                            metAster = true;
                        else if ( metAster && yyCh == QLatin1Char('/') )
                            metAsterSlash = true;
                        else
                            metAster = false;
                    }
                    yyComment.chop(2);
                    yyCh = getChar();

                    return Tok_Comment;
                }
                break;
            case '"':
                yyCh = getChar();

                while ( yyCh != EOF && yyCh != QLatin1Char('\n') && yyCh != QLatin1Char('"') ) {
                    if ( yyCh == QLatin1Char('\\') ) {
                        yyCh = getChar();
                        if ( yyCh == QLatin1Char('u') ) {
                            yyCh = getChar();
                            uint unicode(0);
                            for (int i = 4; i > 0; --i) {
                                unicode = unicode << 4;
                                if( yyCh.isDigit() ) {
                                    unicode += yyCh.digitValue();
                                }
                                else {
                                    int sub(yyCh.toLower().toAscii() - 87);
                                    if( sub > 15 || sub < 10) {
                                        qFatal( "%s:%d: Invalid Unicode",
                                            qPrintable(yyFileName), yyLineNo );
                                    }
                                    unicode += sub;
                                }
                                yyCh = getChar();
                            }
                            yyString.append(QChar(unicode));
                        }
                        else if ( yyCh == QLatin1Char('\n') ) {
                            yyCh = getChar();
                        }
                        else {
                            yyString.append( QLatin1Char(backTab[strchr( tab, yyCh.toAscii() ) - tab]) );
                            yyCh = getChar();
                        }
                    } else {
                        yyString.append(yyCh);
                        yyCh = getChar();
                    }
                }

                if ( yyCh != QLatin1Char('"') )
                    qFatal( "%s:%d: Unterminated string",
                        qPrintable(yyFileName), yyLineNo );

                yyCh = getChar();

                return Tok_String;

            case ':':
                yyCh = getChar();
                return Tok_Colon;
            case '\'':
                yyCh = getChar();

                if ( yyCh == QLatin1Char('\\') )
                    yyCh = getChar();
                do {
                    yyCh = getChar();
                } while ( yyCh != EOF && yyCh != QLatin1Char('\'') );
                yyCh = getChar();
                break;
            case '{':
                yyCh = getChar();
                return Tok_LeftBrace;
            case '}':
                yyCh = getChar();
                return Tok_RightBrace;
            case '(':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth++;
                yyCh = getChar();
                return Tok_LeftParen;
            case ')':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth--;
                yyCh = getChar();
                return Tok_RightParen;
            case ',':
                yyCh = getChar();
                return Tok_Comma;
            case '.':
                yyCh = getChar();
                return Tok_Dot;
            case ';':
                yyCh = getChar();
                return Tok_Semicolon;
            case '+':
                yyCh = getChar();
                if (yyCh == QLatin1Char('+')) {
                    yyCh = getChar();
                    return Tok_PlusPlus;
		}
                if( yyCh == QLatin1Char('=') ){
                    yyCh = getChar();
                    return Tok_PlusEq;
		}
                return Tok_Plus;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                {
                    QByteArray ba;
                    ba += yyCh.toLatin1();
                    yyCh = getChar();
                    bool hex = yyCh == QLatin1Char('x');
                    if ( hex ) {
                        ba += yyCh.toLatin1();
                        yyCh = getChar();
                    }
                    while ( hex ? isxdigit(yyCh.toLatin1()) : yyCh.isDigit() ) {
                        ba += yyCh.toLatin1();
                        yyCh = getChar();
                    }
                    bool ok;
                    yyInteger = ba.toLongLong(&ok);
                    if (ok) return Tok_Integer;
                    break;
                }
            default:
                yyCh = getChar();
            }
        }
    }
    return Tok_Eof;
}
Ejemplo n.º 24
0
QStringList KShell::splitArgs( const QString &args, Options flags, Errors *err)
{
    QStringList ret;
    bool firstword = flags & AbortOnMeta;

    for (int pos = 0; ; ) {
        QChar c;
        do {
            if (pos >= args.length())
                goto okret;
            c = args.unicode()[pos++];
        } while (c.isSpace());
        QString cret;
        if ((flags & TildeExpand) && c == QLatin1Char('~')) {
            int opos = pos;
            for (; ; pos++) {
                if (pos >= args.length())
                    break;
                c = args.unicode()[pos];
                if (c == QLatin1Char('/') || c.isSpace())
                    break;
                if (isQuoteMeta( c )) {
                    pos = opos;
                    c = QLatin1Char('~');
                    goto notilde;
                }
                if ((flags & AbortOnMeta) && isMeta( c ))
                    goto metaerr;
            }
            QString ccret = homeDir( args.mid(opos, pos-opos) );
            if (ccret.isEmpty()) {
                pos = opos;
                c = QLatin1Char('~');
                goto notilde;
            }
            if (pos >= args.length()) {
                ret += ccret;
                goto okret;
            }
            pos++;
            if (c.isSpace()) {
                ret += ccret;
                firstword = false;
                continue;
            }
            cret = ccret;
        }
        // before the notilde label, as a tilde does not match anyway
        if (firstword) {
            if (c == QLatin1Char('_') ||
                (c >= QLatin1Char('A') && c <= QLatin1Char('Z')) ||
                (c >= QLatin1Char('a') && c <= QLatin1Char('z')))
            {
                int pos2 = pos;
                QChar cc;
                do {
                    if (pos2 >= args.length()) {
                        // Exactly one word
                        ret += args.mid(pos - 1);
                        goto okret;
                    }
                    cc = args.unicode()[pos2++];
                } while (cc == QLatin1Char('_') ||
                       (cc >= QLatin1Char('A') && cc <= QLatin1Char('Z')) ||
                       (cc >= QLatin1Char('a') && cc <= QLatin1Char('z')) ||
                       (cc >= QLatin1Char('0') && cc <= QLatin1Char('9')));
                if (cc == QLatin1Char('='))
                    goto metaerr;
            }
        }
      notilde:
        do {
            if (c == QLatin1Char('\'')) {
                int spos = pos;
                do {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                } while (c != QLatin1Char('\''));
                cret += args.mid(spos, pos-spos-1);
            } else if (c == QLatin1Char('"')) {
                for (;;) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                    if (c == QLatin1Char('"'))
                        break;
                    if (c == QLatin1Char('\\')) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        if (c != QLatin1Char('"') &&
                            c != QLatin1Char('\\') &&
                            !((flags & AbortOnMeta) &&
                              (c == QLatin1Char('$') ||
                               c == QLatin1Char('`'))))
                            cret += QLatin1Char('\\');
                    } else if ((flags & AbortOnMeta) &&
                                (c == QLatin1Char('$') ||
                                 c == QLatin1Char('`')))
                        goto metaerr;
                    cret += c;
                }
            } else if (c == QLatin1Char('$') && pos < args.length() &&
                       args.unicode()[pos] == QLatin1Char('\'')) {
                pos++;
                for (;;) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                    if (c == QLatin1Char('\''))
                        break;
                    if (c == QLatin1Char('\\')) {
                        if (pos >= args.length())
                            goto quoteerr;
                        c = args.unicode()[pos++];
                        switch (c.toAscii()) {
                        case 'a': cret += QLatin1Char('\a'); break;
                        case 'b': cret += QLatin1Char('\b'); break;
                        case 'e': cret += QLatin1Char('\033'); break;
                        case 'f': cret += QLatin1Char('\f'); break;
                        case 'n': cret += QLatin1Char('\n'); break;
                        case 'r': cret += QLatin1Char('\r'); break;
                        case 't': cret += QLatin1Char('\t'); break;
                        case '\\': cret += QLatin1Char('\\'); break;
                        case '\'': cret += QLatin1Char('\''); break;
                        case 'c':
                            if (pos >= args.length())
                                goto quoteerr;
                            cret += args.unicode()[pos++].toAscii() & 31;
                            break;
                        case 'x':
                          {
                            if (pos >= args.length())
                                goto quoteerr;
                            int hv = fromHex( args.unicode()[pos++] );
                            if (hv < 0)
                                goto quoteerr;
                            if (pos < args.length()) {
                                int hhv = fromHex( args.unicode()[pos] );
                                if (hhv > 0) {
                                    hv = hv * 16 + hhv;
                                    pos++;
                                }
                                cret += QChar( hv );
                            }
                            break;
                          }
                        default:
                            if (c.toAscii() >= '0' && c.toAscii() <= '7') {
                                char cAscii = c.toAscii();
                                int hv = cAscii - '0';
                                for (int i = 0; i < 2; i++) {
                                    if (pos >= args.length())
                                        break;
                                    c = args.unicode()[pos];
                                    if (c.toAscii() < '0' || c.toAscii() > '7')
                                        break;
                                    hv = hv * 8 + (c.toAscii() - '0');
                                    pos++;
                                }
                                cret += QChar( hv );
                            } else {
                                cret += QLatin1Char('\\');
                                cret += c;
                            }
                            break;
                        }
                    } else
                        cret += c;
                }
            } else {
                if (c == QLatin1Char('\\')) {
                    if (pos >= args.length())
                        goto quoteerr;
                    c = args.unicode()[pos++];
                } else if ((flags & AbortOnMeta) && isMeta( c ))
                    goto metaerr;
                cret += c;
            }
            if (pos >= args.length())
                break;
            c = args.unicode()[pos++];
        } while (!c.isSpace());
        ret += cret;
        firstword = false;
    }

  okret:
    if (err)
        *err = NoError;
    return ret;

  quoteerr:
    if (err)
        *err = BadQuoting;
    return QStringList();

  metaerr:
    if (err)
        *err = FoundMeta;
    return QStringList();
}
Ejemplo n.º 25
0
LNote Lilypond::scanNote()
      {
      QChar c   = lookup();
      int pitch = 48;

      switch (c.toAscii()) {
            case 'a':   pitch += 9; break;
            case 'b':   pitch += 11; break;
            case 'c':   break;
            case 'd':   pitch += 2; break;
            case 'e':   pitch += 4; break;
            case 'f':   pitch += 5; break;
            case 'g':   pitch += 7; break;
            }
      ++ci;
printf("scanNote pitch %d relpitch %d\n", pitch, relpitch);
      if (relpitch > 0) {
            if (pitch < relpitch) {
                  while ((relpitch - pitch) > 5)
                        pitch += 12;
                  }
            else if (pitch > relpitch) {
                  while ((pitch - relpitch) > 5)
                        pitch -= 12;
                  }
            }
      int octave = 0;
      for (;;) {
            if (data[ci] == ' ' || data[ci] == '\n')
                  break;
            if (data[ci] == '\'') {
                  ++octave;
                  ++ci;
                  }
            else if (data[ci] == ',') {
                  --octave;
                  ++ci;
                  }
            else if (data[ci].isLetterOrNumber()) {
                  QString buffer;
                  while (data[ci].isLetterOrNumber())
                        buffer.append(data[ci++]);
                  int len = buffer.toInt();
                  switch(len) {
                        case 1:  curLen = MScore::division * 4; break;
                        case 2:  curLen = MScore::division * 2; break;
                        case 4:  curLen = MScore::division;     break;
                        case 8:  curLen = MScore::division / 2; break;
                        case 16: curLen = MScore::division / 4; break;
                        case 32: curLen = MScore::division / 8; break;
                        case 64: curLen = MScore::division / 16; break;
                        default:
                              printf("illegal note len %d\n", len);
                              break;
                        }
                  }
            else if (data[ci] == '.') {
                  curLen += (curLen / 2);
                  ++ci;
                  }
            }
      pitch += octave * 12;
      if (relpitch > 0)
            relpitch = pitch;
      return LNote(pitch, curLen);
      }
Ejemplo n.º 26
0
QString ReplaceFN::parseReplacement(const int,
                                    const DynamicContext::Ptr &context) const
{
    // TODO what if there is no groups, can one rewrite to the replacement then?
    const QString input(m_operands.at(2)->evaluateSingleton(context).stringValue());

    QString retval;
    retval.reserve(input.size());
    const int len = input.length();

    for(int i = 0; i < len; ++i)
    {
        const QChar ch(input.at(i));
        switch(ch.toAscii())
        {
            case '$':
            {
                /* QRegExp uses '\' as opposed to '$' for marking sub groups. */
                retval.append(QLatin1Char('\\'));

                ++i;
                if(i == len)
                {
                    context->error(errorAtEnd('$'), ReportContext::FORX0004, this);
                    return QString();
                }

                const QChar nextCh(input.at(i));
                if(nextCh.isDigit())
                    retval.append(nextCh);
                else
                {
                    context->error(QtXmlPatterns::tr("In the replacement string, %1 must be "
                                                     "followed by at least one digit when not escaped.")
                                                     .arg(formatKeyword(QLatin1Char('$'))),
                                                ReportContext::FORX0004, this);
                    return QString();
                }

                break;
            }
            case '\\':
            {
                ++i;
                if(i == len)
                {
                    /* error, we've reached the end. */;
                    context->error(errorAtEnd('\\'), ReportContext::FORX0004, this);
                }

                const QChar nextCh(input.at(i));
                if(nextCh == QLatin1Char('\\') || nextCh == QLatin1Char('$'))
                {
                    retval.append(ch);
                    break;
                }
                else
                {
                    context->error(QtXmlPatterns::tr("In the replacement string, %1 can only be used to "
                                                     "escape itself or %2, not %3")
                                                     .arg(formatKeyword(QLatin1Char('\\')))
                                                     .arg(formatKeyword(QLatin1Char('$')))
                                                     .arg(formatKeyword(nextCh)),
                                               ReportContext::FORX0004, this);
                    return QString();
                }
            }
            default:
                retval.append(ch);
        }
    }

    return retval;
}
Ejemplo n.º 27
0
//
// This method will convert the desired text into morse code bits:
//
void TorMorse::translateTextToBits(
  QTextStream &stream)
{
  morseCodeBits.clear();

  QChar c;
  while (!stream.atEnd())
  {
    stream >> c;

    switch (c.toAscii())
    {
    case 'a':
    case 'A':
      dot(); dash(); break;

    case 'b':
    case 'B':
      dash(); dot(); dot(); dot(); break;

    case 'c':
    case 'C':
      dash(); dot(); dash(); dot(); break;

    case 'd':
    case 'D':
      dash(); dot(); dot(); break;

    case 'e':
    case 'E':
      dot(); break;

    case 'f':
    case 'F':
      dot(); dot(); dash(); dot(); break;

    case 'g':
    case 'G':
      dash(); dash(); dot(); break;

    case 'h':
    case 'H':
      dot(); dot(); dot(); dot(); break;

    case 'i':
    case 'I':
      dot(); dot(); break;

    case 'j':
    case 'J':
      dot(); dash(); dash(); dash(); break;

    case 'k':
    case 'K':
      dash(); dot(); dash(); break;

    case 'l':
    case 'L':
      dot(); dash(); dot(); dot(); break;

    case 'm':
    case 'M':
      dash(); dash(); break;

    case 'n':
    case 'N':
      dash(); dot(); break;

    case 'o':
    case 'O':
      dash(); dash(); dash(); break;

    case 'p':
    case 'P':
      dot(); dash(); dash(); dot(); break;

    case 'q':
    case 'Q':
      dash(); dash(); dot(); dash(); break;

    case 'r':
    case 'R':
      dot(); dash(); dot(); break;

    case 's':
    case 'S':
      dot(); dot(); dot(); break;

    case 't':
    case 'T':
      dash(); break;

    case 'u':
    case 'U':
      dot(); dot(); dash(); break;

    case 'v':
    case 'V':
      dot(); dot(); dot(); dash(); break;

    case 'w':
    case 'W':
      dot(); dash(); dash(); break;

    case 'x':
    case 'X':
      dash(); dot(); dot(); dash(); break;

    case 'y':
    case 'Y':
      dash(); dot(); dash(); dash(); break;

    case 'z':
    case 'Z':
      dash(); dash(); dot(); dot(); break;

    case '0':
      dash(); dash(); dash(); dash(); dash(); break;

    case '1':
      dot(); dash(); dash(); dash(); dash(); break;

    case '2':
      dot(); dot(); dash(); dash(); dash(); break;

    case '3':
      dot(); dot(); dot(); dash(); dash(); break;

    case '4':
      dot(); dot(); dot(); dot(); dash(); break;

    case '5':
      dot(); dot(); dot(); dot(); dot(); break;

    case '6':
      dash(); dot(); dot(); dot(); dot(); break;

    case '7':
      dash(); dash(); dot(); dot(); dot(); break;

    case '8':
      dash(); dash(); dash(); dot(); dot(); break;

    case '9':
      dash(); dash(); dash(); dash(); dot(); break;

    case '.':
      dot(); dash(); dot(); dash(); dot(); dash(); break;

    case ',':
      dash(); dash(); dot(); dot(); dash(); dash(); break;

    case '?':
      dot(); dot(); dash(); dash(); dot(); dot(); break;

    case '\'':
      dot(); dash(); dash(); dash(); dash(); dot(); break;

    case '!':
      dash(); dot(); dash(); dot(); dash(); dash(); break;

    case '/':
      dash(); dot(); dot(); dash(); dot(); break;

    case '(':
      dash(); dot(); dash(); dash(); dot(); break;

    case ')':
      dash(); dot(); dash(); dash(); dot(); dash(); break;

    case '&':
      dot(); dash(); dot(); dot(); dot(); break;

    case ':':
      dash(); dash(); dash(); dot(); dot(); dot(); break;

    case ';':
      dash(); dot(); dash(); dot(); dash(); dot(); break;

    case '=':
      dash(); dot(); dot(); dot(); dash(); break;

    case '+':
      dot(); dash(); dot(); dash(); dot(); break;

    case '-':
      dash(); dot(); dot(); dot(); dot(); dash(); break;

    case '_':
      dot(); dot(); dash(); dash(); dot(); dash(); break;

    case '"':
      dot(); dash(); dot(); dot(); dash(); dot(); break;

    case '$':
      dot(); dot(); dot(); dash(); dot(); dot(); dash(); break;

    case '@':
      dot(); dash(); dash(); dot(); dash(); dot(); break;

    case ' ':
      // End of a word, so need to add 4 units to the 3-unit character gap:
      fourUnitGap();
      // Also, clear out any extra whitespace chars:
      stream.skipWhiteSpace();
      break;

    default:
      break;
    }

    // At the end of every character is a 3 unit gap:
    threeUnitGap();
  }
}
Ejemplo n.º 28
0
void CppSyntaxHighlighter::highlightBlock(const QString &text)
{
    // states
    const int StateStandard = 0;
    const int StateCommentStart1 = 1;
    const int StateCCommentStart2 = 2;
    const int StateCppCommentStart2 = 3;
    const int StateCComment = 4;
    const int StateCppComment = 5;
    const int StateCCommentEnd1 = 6;
    const int StateCCommentEnd2 = 7;
    const int StateStringStart = 8;
    const int StateString = 9;
    const int StateStringEnd = 10;
    const int StateString2Start = 11;
    const int StateString2 = 12;
    const int StateString2End = 13;
    const int StateNumber = 14;
    const int StatePreProcessor = 15;

    // tokens
    const int InputAlpha = 0;
    const int InputNumber = 1;
    const int InputAsterix = 2;
    const int InputSlash = 3;
    const int InputParen = 4;
    const int InputSpace = 5;
    const int InputHash = 6;
    const int InputQuotation = 7;
    const int InputApostrophe = 8;
    const int InputSep = 9;

    static const uchar table[16][10] = {
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStandard
        { StateStandard,      StateNumber,   StateCCommentStart2, StateCppCommentStart2, StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCommentStart1
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentStart2
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // CppCommentStart2
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCComment,         StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCComment
        { StateCppComment,    StateCppComment, StateCppComment,     StateCppComment,       StateCppComment, StateCppComment, StateCppComment,   StateCppComment,  StateCppComment,   StateCppComment }, // StateCppComment
        { StateCComment,      StateCComment,   StateCCommentEnd1,   StateCCommentEnd2,     StateCComment,   StateCComment,   StateCComment,     StateCComment,    StateCComment,     StateCComment }, // StateCCommentEnd1
        { StateStandard,      StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateCCommentEnd2
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateStringStart
        { StateString,        StateString,     StateString,         StateString,           StateString,     StateString,     StateString,       StateStringEnd,   StateString,       StateString }, // StateString
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateStringEnd
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2Start
        { StateString2,       StateString2,    StateString2,        StateString2,          StateString2,    StateString2,    StateString2,      StateString2,     StateString2End,   StateString2 }, // StateString2
        { StateStandard,      StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateString2End
        { StateNumber,        StateNumber,     StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard }, // StateNumber
        { StatePreProcessor,  StateStandard,   StateStandard,       StateCommentStart1,    StateStandard,   StateStandard,   StatePreProcessor, StateStringStart, StateString2Start, StateStandard } // StatePreProcessor
    };

    QString buffer;
    QTextCharFormat emptyFormat;

    int state = StateStandard;
    const int previousState = previousBlockState();
    if (previousState != -1)
        state = previousState;

    BlockData *blockData = static_cast<BlockData *>(currentBlockUserData());
    if (blockData) {
        blockData->parentheses.clear();
    } else {
        blockData = new BlockData;
        setCurrentBlockUserData(blockData);
    }

    if (text.isEmpty()) {
        setCurrentBlockState(previousState);
        return;
    }

    int input = -1;
    int i = 0;
    bool lastWasBackSlash = false;
    bool makeLastStandard = false;

    static QString alphabeth = QString::fromLatin1("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
    static QString mathChars = QString::fromLatin1("xXeE");
    static QString numbers = QString::fromLatin1("0123456789");
    bool questionMark = false;
    bool resetLineState = true;
    QChar lastChar;
    QString firstWord;
    forever {
        QChar c = text.at(i);

        if (lastWasBackSlash) {
            input = InputSep;
        } else {
            switch (c.toAscii()) {
                case '*':
                    input = InputAsterix;
                    break;
                case '/':
                    input = InputSlash;
                    break;
                case '(': case '[': case '{':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       )
                        blockData->parentheses << Parenthesis(Parenthesis::Open, c, i);
                    break;
                case ')': case ']': case '}':
                    input = InputParen;
                    if (state == StateStandard
                        || state == StateNumber
                        || state == StatePreProcessor
                        || state == StateCCommentEnd2
                        || state == StateCCommentEnd1
                        || state == StateString2End
                        || state == StateStringEnd
                       ) {
                        blockData->parentheses << Parenthesis(Parenthesis::Closed, c, i);
                        /* #####
                        if (c == '}') {
                            if (checkFunctionEnd(string, i))
                                resetLineState = false;
                        }
                        */
                    }
                    break;
                case '#':
                    input = InputHash;
                    break;
                case '"':
                    input = InputQuotation;
                    break;
                case '\'':
                    input = InputApostrophe;
                    break;
                case ' ':
                    input = InputSpace;
                    if (firstWord == QLatin1String("function")
                        || firstWord == QLatin1String("constructor")
                        || firstWord == QLatin1String("class")
                        // || firstWord == QLatin1String("if")
                        // || firstWord == QLatin1String("for")
                        // || firstWord == QLatin1String("while")
                        // || firstWord == QLatin1String("else")
                       ) {
                        // #### paragData->lineState = ParagData::FunctionStart;
                        resetLineState = false;
                    }
                    break;
                case '1': case '2': case '3': case '4': case '5':
                case '6': case '7': case '8': case '9': case '0':
                    if (alphabeth.contains(lastChar)
                        && (!mathChars.contains(lastChar) || !numbers.contains(text.at(i - 1)))) {
                        input = InputAlpha;
                    } else {
                        if (input == InputAlpha && numbers.contains(lastChar))
                            input = InputAlpha;
                        else
                            input = InputNumber;
                    }
                    break;
                case ':': {
                              input = InputAlpha;
                              QChar nextChar = ' ';
                              if (i < text.length() - 1)
                                  nextChar = text.at(i + 1);
                              if (state == StateStandard && !questionMark &&
                                  lastChar != ':' && nextChar != ':' && lastChar.isLetter()) {
                                  for (int j = 0; j < i; ++j) {
                                      if (format(j) == emptyFormat)
                                          setFormat(j, 1, labelFormat);
                                  }
                              }
                              break;
                          }
                default: {
                             if ( c != QLatin1Char('\t') )
                                 firstWord += c;
                             const QString s = firstWord.simplified();
                             if ( s == QLatin1String("private")
                                  || s == QLatin1String("protected")
                                  || s == QLatin1String("public")
                                  || s == QLatin1String("static")
                                )
                                 firstWord.clear();
                             if (!questionMark && c == QLatin1Char('?'))
                                 questionMark = true;
                             if (c.isLetter() || c == QLatin1Char('_'))
                                 input = InputAlpha;
                             else
                                 input = InputSep;
                         } break;
            }
        }

        lastWasBackSlash = !lastWasBackSlash && c == QLatin1Char('\\');

        if (input == InputAlpha)
            buffer += c;

        state = table[state][input];

        switch (state) {
            case StateStandard: {
                                    setFormat(i, 1, emptyFormat);
                                    if (makeLastStandard)
                                        setFormat(i - 1, 1, emptyFormat);
                                    makeLastStandard = false;
                                    if (!buffer.isEmpty() && input != InputAlpha ) {
                                        highlightKeyword(i, buffer);
                                        buffer.clear();
                                    }
                                } break;
            case StateCommentStart1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = true;
                                buffer.clear();
                                break;
            case StateCCommentStart2:
                                setFormat(i - 1, 2, commentFormat);
                                makeLastStandard = false;
                                buffer.clear();
                                break;
            case StateCppCommentStart2:
                                setFormat(i - 1, 2, commentFormat);
                                makeLastStandard = false;
                                buffer.clear();
                                break;
            case StateCComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCppComment:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCCommentEnd1:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateCCommentEnd2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, commentFormat);
                                buffer.clear();
                                break;
            case StateStringStart:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, stringFormat);
                                buffer.clear();
                                break;
            case StateStringEnd:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString2Start:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateString2:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, stringFormat);
                                buffer.clear();
                                break;
            case StateString2End:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, emptyFormat);
                                buffer.clear();
                                break;
            case StateNumber:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat( i, 1, numberFormat);
                                buffer.clear();
                                break;
            case StatePreProcessor:
                                if (makeLastStandard)
                                    setFormat(i - 1, 1, emptyFormat);
                                makeLastStandard = false;
                                setFormat(i, 1, preProcessorFormat);
                                buffer = QString::null;
                                break;
        }

        lastChar = c;
        i++;
        if (i >= text.length())
            break;
    }

    highlightKeyword(text.length(), buffer);

    /*
    if (resetLineState)
        paragData->lineState = ParagData::InFunction;
    string->setExtraData( paragData );
    */

    if (state == StateCComment 
        || state == StateCCommentEnd1
        || state == StateCCommentStart2
       ) {
        state = StateCComment;
    } else if (state == StateString) {
        state = StateString;
    } else if (state == StateString2) {
        state =  StateString2;
    } else {
        state = StateStandard;
    }

    if (blockData->parenthesisMatchStart != -1) {
        for (int pos = blockData->parenthesisMatchStart;
             pos < blockData->parenthesisMatchEnd; ++pos) {
            QTextCharFormat fmt = format(pos);
            fmt.merge(blockData->parenthesisMatchingFormat);
            setFormat(pos, 1, fmt);
        }
    }

    if (blockData->errorMarkerFormat.hasProperty(ErrorMarkerPropertyId)) {
        for (int i = 0; i < text.length(); ++i) {
            QTextCharFormat fmt = format(i);
            fmt.merge(blockData->errorMarkerFormat);
            setFormat(i, 1, fmt);
        }
    }

    setCurrentBlockState(state);
}
Ejemplo n.º 29
0
void ConnectorOld::stringParser(QByteArray recv)
{
  QString recvStr = codec->toUnicode(recv);
  QChar category = recvStr[0];                        // First symbol of string
  QStringList message = recvStr.mid(1).split("\t");   // Remove first symbol & splitting
  QString cmd;
  switch (category.toAscii())
  {
  case 'R':       // Authentification request
    qDebug() << "CONN :: Auth_req:" << message;
    emit authRequestRecv(message.at(0));
    break;
  case 'b':       // Information
    qDebug() << "CONN :: Inform:" << message;
    emit infoMessage(message.at(0));
    // Verify for success auth string
    if (message.at(0).split(" ").count() == 7)
      if (message.at(0).split(" ").at(2).at(8) == ',')
        emit authSuccess();
    break;
  case 'd':       // Board
    cmd = message.at(0);
    if (cmd == "channels")  // Receved channel list
    {
      qDebug() << "CONN :: Board: channels recv";
      message.pop_front();    // Remove command from message
      emit boardChannelsRecv(parseBoardChannels(message.join("\t")));
    }
    else
    {
      if (cmd == "new")  // New messages
      {
        qDebug() << "CONN :: Board: new messages avaible";
        emit boardNewMessages();
      }
      else
      {
        if (cmd == "skins")
        {
          qDebug() << "CONN :: Board: \"skins\" cmd recv";
        }
        else
        {
          if (cmd == "admin")
          {
            qDebug() << "CONN :: Board: \"admin\" cmd recv";
          }
          else
          {
            qDebug() << "CONN :: Board: messages recv";
            emit boardMessagesRecv(parseBoardMessages(message.join("\t")));
          }
        }
      }
    }
//    qDebug() << "DBoard :: " << message;
    break;
  case 'c':       // Chat
    cmd = message.at(0);
    message.pop_front();    // Remove command from message
    if (cmd == "main")
    {
      qDebug() << "CONN :: Chat: channel message recv";
      emit chatPublicMessage(message.at(0),
                             getUserIdByName(message.at(0), message.at(2)),
                             message.at(3));
    }
    else
    {
      if (cmd == "enter")
      {
        QString channelId = message.at(0);
        if (QHostAddress().setAddress(channelId))
        {
          qDebug() << "CONN :: Host entered"
                   << message.at(2) << "@" << channelId;
        }
        else
        {
          qDebug() << "CONN :: Chat: new user entered" << message.at(3);
          emit chatUserEnter(channelId, parseEnteredUser(message));
        }
      }
      else
      {
        if (cmd == "leave")
        {
          QString channelId = message.at(0);
          if (QHostAddress().setAddress(channelId))
          {
            qDebug() << "CONN :: Host leave"
                     << message.at(2) << "@" << channelId;
          }
          else
          {
            shared_ptr<ChatChannel> ch =
                getChatInstance()->getChannel(channelId);
            bool online; // Verify for user connect state
            ch->getUser(message.at(2), &online);
            if (online)
            {
              qDebug() << "CONN :: Chat: user leave" << message.at(3);
              emit chatUserLeave(channelId, message.at(2));
            }
          }
        }
        else
        {
          if (cmd == "private")
          {
            qDebug() << "CONN :: Chat: new private message";
            emit chatPrivateMessage(parseChatPrivate(message));
          }
          else
          {
            if (cmd == "infoGet")
            {
              qDebug() << "CONN :: Chat: \"infoGet\" cmd recv";
            }
            else
            {
              if (cmd == "channels")
              {
                qDebug() << "CONN :: Chat: channels recv";
                emit chatChannelsRecv(parseChatChannels(message.join("\t")));
              }
              else
              {
                if (cmd == "userlist")
                {
                  qDebug() << "CONN :: Chat: userlist recv";
                  emit chatUsersRecv(message.at(0), parseChatUsers(message));
                }
                else
                {
                  if (cmd == "privateresived")
                  {
                    emit chatPrivateDelivered(
                          message.at(0), message.at(1), message.at(2));
                  }
                  else
                    qDebug() << "CONN ::" << cmd << message;
                }
              }
            }
          }
        }
      }
    }
//    qDebug() << "Chat   :: " << message;
    break;
  default:       // Uncategorised
    qDebug() << "Unctg  :: " << recvStr;
  }
}
void PowerManagementConfigGui::onMessageReceived(const QString &response)
{
    QStringList breakdown = response.split(",");
    int size = breakdown.size();
    if (size <= 0) return;
    QChar command = breakdown[0].at(1);
// Check for ident response
    if (command == 'E')
    {
        if (size != 4) return;
        PowerManagementConfigUi.firmwareVersion->setText("Firmware version : " + breakdown[2]);
        PowerManagementConfigUi.boardVersion->setText("Interface Board Version: " + breakdown[3]);
        return;
    }
    QChar battery = breakdown[0].at(2);
    QChar parameter = breakdown[0].at(2);
    int controlByte = 0;
    if (size > 1) controlByte = breakdown[1].simplified().toInt();
// Error Code
    switch (command.toAscii())
    {
// Show Measured Quiescent Current
        case 'Q':
        {
            if (size < 2) break;
            quiescentCurrent = breakdown[1].simplified();
            int test = breakdown[2].simplified().toInt();
            if (test < 6)
                PowerManagementConfigUi.calibrateProgressBar->setValue(test+1);
            else
            {
                PowerManagementConfigUi.quiescentCurrent
                        ->setText(QString("%1 A").arg(quiescentCurrent.
                                  toFloat()/256,0,'f',3));
                this->setEnabled(true);
                PowerManagementConfigUi.calibrateProgressBar->setVisible(false);
                PowerManagementConfigUi.calibrateProgressBar->setValue(0);
            }
            break;
        }
// Show measured battery resistance
        case 'R':
        {
            if (size < 2) break;
            QString batteryResistance = QString("%1 m").arg(breakdown[1]
                                         .simplified().toFloat()/65.536,0,'f',0)
                                         .append(QChar(0x03A9));
            if (battery == '1')
                PowerManagementConfigUi.battery1Resistance
                    ->setText(batteryResistance);
            else if (battery == '2')
                PowerManagementConfigUi.battery2Resistance
                    ->setText(batteryResistance);
            else if (battery == '3')
                PowerManagementConfigUi.battery3Resistance
                    ->setText(batteryResistance);
            break;
        }
// Show battery type and capacity
        case 'T':
        {
            if (size < 3) break;
            int batteryType = breakdown[1].simplified().toInt();
            int batteryCapacity = breakdown[2].simplified().toInt();
            if (battery == '1')
            {
                PowerManagementConfigUi.battery1TypeCombo
                    ->setCurrentIndex(batteryType);
                PowerManagementConfigUi.battery1CapacitySpinBox
                    ->setValue(batteryCapacity);
            }
            else if (battery == '2')
            {
                PowerManagementConfigUi.battery2TypeCombo
                    ->setCurrentIndex(batteryType);
                PowerManagementConfigUi.battery2CapacitySpinBox
                    ->setValue(batteryCapacity);
            }
            else if (battery == '3')
            {
                PowerManagementConfigUi.battery3TypeCombo
                    ->setCurrentIndex(batteryType);
                PowerManagementConfigUi.battery3CapacitySpinBox
                    ->setValue(batteryCapacity);
            }
            break;
        }
// Show battery absorption phase voltage and current limits
        case 'A':
        {
            if (size < 3) break;
            float absorptionVoltage = breakdown[2].simplified().toFloat()/256;
            float bulkCurrentScale = breakdown[1].simplified().toFloat();
            if (battery == '1')
            {
                PowerManagementConfigUi.battery1AbsorptionVoltage
                    ->setValue(absorptionVoltage);
                float battery1Capacity = PowerManagementConfigUi.
                            battery1CapacitySpinBox->value();
                PowerManagementConfigUi.battery1AbsorptionCurrent
                    ->setValue(battery1Capacity/bulkCurrentScale);
            }
            else if (battery == '2')
            {
                PowerManagementConfigUi.battery2AbsorptionVoltage
                    ->setValue(absorptionVoltage);
                float battery2Capacity = PowerManagementConfigUi.
                            battery2CapacitySpinBox->value();
                PowerManagementConfigUi.battery2AbsorptionCurrent
                    ->setValue(battery2Capacity/bulkCurrentScale);
            }
            else if (battery == '3')
            {
                PowerManagementConfigUi.battery3AbsorptionVoltage
                    ->setValue(absorptionVoltage);
                float battery3Capacity = PowerManagementConfigUi.
                            battery3CapacitySpinBox->value();
                PowerManagementConfigUi.battery3AbsorptionCurrent
                    ->setValue(battery3Capacity/bulkCurrentScale);
            }
            break;
        }
// Show battery float phase voltage and current limits
        case 'F':
        {
            if (size < 3) break;
            float floatVoltage = breakdown[2].simplified().toFloat()/256;
            float floatCurrentScale = breakdown[1].simplified().toFloat();
            if (battery == '1')
            {
                PowerManagementConfigUi.battery1FloatVoltage
                    ->setValue(floatVoltage);
                float battery1Capacity = PowerManagementConfigUi.
                            battery1CapacitySpinBox->value();
                PowerManagementConfigUi.battery1FloatCurrent
                    ->setValue(battery1Capacity/floatCurrentScale);
            }
            else if (battery == '2')
            {
                PowerManagementConfigUi.battery2FloatVoltage
                    ->setValue(floatVoltage);
                float battery2Capacity = PowerManagementConfigUi.
                            battery2CapacitySpinBox->value();
                PowerManagementConfigUi.battery2FloatCurrent
                    ->setValue(battery2Capacity/floatCurrentScale);
            }
            else if (battery == '3')
            {
                PowerManagementConfigUi.battery3FloatVoltage
                    ->setValue(floatVoltage);
                float battery3Capacity = PowerManagementConfigUi.
                            battery3CapacitySpinBox->value();
                PowerManagementConfigUi.battery3FloatCurrent
                    ->setValue(battery3Capacity/floatCurrentScale);
            }
            break;
        }
/* Show control settings */
        case 'D':
        {
            if (size < 2) break;
            bool dataMessage = ((controlByte & (1<<3)) > 0);
            if (dataMessage)
                PowerManagementConfigUi.dataMessageCheckbox->setChecked(true);
            else
                PowerManagementConfigUi.dataMessageCheckbox->setChecked(false);
            bool debugMessage = ((controlByte & (1<<4)) > 0);
            if (debugMessage)
                PowerManagementConfigUi.debugMessageCheckbox->setChecked(true);
            else
                PowerManagementConfigUi.debugMessageCheckbox->setChecked(false);
            break;
        }
// Show current time settings from the system
        case 'H':
        {
            if (size < 2) break;
            QDateTime systemTime =
                QDateTime::fromString(breakdown[1].simplified(),Qt::ISODate);
            PowerManagementConfigUi.date->setText(systemTime.date().toString("dd.MM.yyyy"));
            PowerManagementConfigUi.time->setText(systemTime.time().toString("H.mm.ss"));
            break;
        }
// Operational State values for "reset missing" buttons.
        case 'O':
        {
            int healthState = (controlByte >> 6) & 0x03;
            if (battery == '1')
            {
                if (healthState == 0)
                {
                    PowerManagementConfigUi.resetMissing1Button->
                        setStyleSheet("background-color:lightgreen;");
                    PowerManagementConfigUi.resetMissing1Button->setText("");
                }
                else if (healthState == 1)
                {
                    PowerManagementConfigUi.resetMissing1Button->
                        setStyleSheet("background-color:orange;");
                    PowerManagementConfigUi.resetMissing1Button->setText("");
                }
                else if (healthState == 2)
                {
                    PowerManagementConfigUi.resetMissing1Button->
                        setStyleSheet("background-color:white;");
                    PowerManagementConfigUi.resetMissing1Button->setText("X");
                }
            }
            else if (battery == '2')
            {
                if (healthState == 0)
                {
                    PowerManagementConfigUi.resetMissing2Button->
                        setStyleSheet("background-color:lightgreen;");
                    PowerManagementConfigUi.resetMissing2Button->setText("");
                }
                else if (healthState == 1)
                {
                    PowerManagementConfigUi.resetMissing2Button->
                        setStyleSheet("background-color:orange;");
                    PowerManagementConfigUi.resetMissing2Button->setText("");
                }
                else if (healthState == 2)
                {
                    PowerManagementConfigUi.resetMissing2Button->
                        setStyleSheet("background-color:white;");
                    PowerManagementConfigUi.resetMissing2Button->setText("X");
                }
            }
            else if (battery == '3')
            {
                if (healthState == 0)
                {
                    PowerManagementConfigUi.resetMissing3Button->
                        setStyleSheet("background-color:lightgreen;");
                    PowerManagementConfigUi.resetMissing3Button->setText("");
                }
                else if (healthState == 1)
                {
                    PowerManagementConfigUi.resetMissing3Button->
                        setStyleSheet("background-color:orange;");
                    PowerManagementConfigUi.resetMissing3Button->setText("");
                }
                else if (healthState == 2)
                {
                    PowerManagementConfigUi.resetMissing3Button->
                        setStyleSheet("background-color:white;");
                    PowerManagementConfigUi.resetMissing3Button->setText("X");
                }
            }
            break;
        }
// Show tracking parameters
        case 't':
        {
            if (size < 3) break;
// Low voltage and critical voltage thresholds.
            if (parameter == 'V')
            {
                float lowVoltage = (float)breakdown[1].simplified().toInt()/256;
                float criticalVoltage = (float)breakdown[2].simplified().toInt()/256;
                PowerManagementConfigUi.lowVoltageDoubleSpinBox
                    ->setValue(lowVoltage);
                PowerManagementConfigUi.criticalVoltageDoubleSpinBox
                    ->setValue(criticalVoltage);
            }
// Low SoC and critical SoC thresholds.
            else if (parameter == 'S')
            {
                int lowSoC = (float)breakdown[1].simplified().toInt()/256;
                int criticalSoC = (float)breakdown[2].simplified().toInt()/256;
                PowerManagementConfigUi.lowSoCSpinBox
                    ->setValue(lowSoC);
                PowerManagementConfigUi.criticalSoCSpinBox
                    ->setValue(criticalSoC);
            }
/* Monitor strategy byte. Bit 0 is to allow charger and load on the same
battery; bit 1 is to maintain an isolated battery in normal conditions. */
            else if (parameter == 's')
            {
                int monitorStrategy = (float)breakdown[1].simplified().toInt();
                bool separateLoad = (monitorStrategy & 1) > 0;
                PowerManagementConfigUi.loadChargeCheckBox
                    ->setChecked(separateLoad);
                bool preserveIsolation = (monitorStrategy & 2) > 0;
                PowerManagementConfigUi.isolationMaintainCheckBox
                    ->setChecked(preserveIsolation);
            }
            break;
        }
// Show charger parameters
        case 'c':
        {
            if (size < 3) break;
            if (parameter == 'R')
            {
                int restTime = (float)breakdown[1].simplified().toInt();
                int absorptionTime = (float)breakdown[2].simplified().toInt();
                PowerManagementConfigUi.restTimeSpinBox
                    ->setValue(restTime);
                PowerManagementConfigUi.absorptionTimeSpinBox
                    ->setValue(absorptionTime);
            }
            else if (parameter == 'D')
            {
                int dutyCycleMin = (float)breakdown[1].simplified().toInt()/256;
                PowerManagementConfigUi.minimumDutyCycleSpinBox
                    ->setValue(dutyCycleMin);
            }
            else if (parameter == 'F')
            {
                int floatTime = (float)breakdown[1].simplified().toInt();
                int floatSoC = (float)breakdown[2].simplified().toInt()/256;
                PowerManagementConfigUi.floatDelaySpinBox
                    ->setValue(floatTime);
                PowerManagementConfigUi.floatBulkSoCSpinBox
                    ->setValue(floatSoC);
            }
/* Charger strategy byte. Bit 0 is to suppress the absortion phase for EMI. */
            else if (parameter == 's')
            {
                int chargerStrategy = (float)breakdown[1].simplified().toInt();
                bool suppressAbsorptionPhase = (chargerStrategy & 1) > 0;
                PowerManagementConfigUi.absorptionMuteCheckbox
                    ->setChecked(suppressAbsorptionPhase);
            }
            break;
        }
    }
}