Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
    {
        Base::Quantity res;
        const double max = this->maximum;
        const double min = this->minimum;

        QString copy = input;

        int len = copy.size();

        const bool plus = max >= 0;
        const bool minus = min <= 0;

        switch (len) {
        case 0:
            state = max != min ? QValidator::Intermediate : QValidator::Invalid;
            goto end;
        case 1:
            if (copy.at(0) == locale.decimalPoint()) {
                state = QValidator::Intermediate;
                copy.prepend(QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('+')) {
                // the quantity parser doesn't allow numbers of the form '+1.0'
                state = QValidator::Invalid;
                goto end;
            }
            else if (copy.at(0) == QLatin1Char('-')) {
                if (minus)
                    state = QValidator::Intermediate;
                else
                    state = QValidator::Invalid;
                goto end;
            }
            break;
        case 2:
            if (copy.at(1) == locale.decimalPoint()
                && (plus && copy.at(0) == QLatin1Char('+'))) {
                state = QValidator::Intermediate;
                goto end;
            }
            if (copy.at(1) == locale.decimalPoint()
                && (minus && copy.at(0) == QLatin1Char('-'))) {
                state = QValidator::Intermediate;
                copy.insert(1, QLatin1Char('0'));
                pos++;
                len++;
                goto end;
            }
            break;
        default: break;
        }

        {
            if (copy.at(0) == locale.groupSeparator()) {
                state = QValidator::Invalid;
                goto end;
            }
            else if (len > 1) {
                bool decOccurred = false;
                for (int i = 0; i<copy.size(); i++) {
                    if (copy.at(i) == locale.decimalPoint()) {
                        // Disallow multiple decimal points within the same numeric substring
                        if (decOccurred) {
                            state = QValidator::Invalid;
                            goto end;
                        }
                        decOccurred = true;
                    }
                    // Reset decOcurred if non-numeric character found
                    else if (!(copy.at(i) == locale.groupSeparator() || copy.at(i).isDigit())) {
                        decOccurred = false;
                    }
                }
            }

            bool ok = false;
            double value = min;

            if (locale.negativeSign() != QLatin1Char('-'))
                copy.replace(locale.negativeSign(), QLatin1Char('-'));
            if (locale.positiveSign() != QLatin1Char('+'))
                copy.replace(locale.positiveSign(), QLatin1Char('+'));

            try {
                QString copy2 = copy;
                copy2.remove(locale.groupSeparator());

                res = Base::Quantity::parse(copy2);
                value = res.getValue();
                ok = true;
            }
            catch (Base::Exception&) {
            }

            if (!ok) {
                // input may not be finished
                state = QValidator::Intermediate;
            }
            else if (value >= min && value <= max) {
                if (copy.endsWith(locale.decimalPoint())) {
                    // input shouldn't end with a decimal point
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
                    // if not dimensionless the input should have a dimension
                    state = QValidator::Intermediate;
                }
                else if (res.getUnit() != this->unit) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Acceptable;
                }
            }
            else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
                state = QValidator::Invalid;
            }
            else {
                if ((value >= 0 && value > max) || (value < 0 && value < min)) {
                    state = QValidator::Invalid;
                }
                else {
                    state = QValidator::Intermediate;
                }
            }
        }
end:
        if (state != QValidator::Acceptable) {
            res.setValue(max > 0 ? min : max);
        }

        input = copy;
        return res;
    }
Пример #2
0
/*!
  Load, parse, and process a qdoc configuration file. This
  function is only called by the other load() function, but
  this one is recursive, i.e., it calls itself when it sees
  an \c{include} statement in the qdog configuration file.
 */
void Config::load(Location location, const QString& fileName)
{
    QRegExp keySyntax("\\w+(?:\\.\\w+)*");

#define SKIP_CHAR() \
    do { \
        location.advance(c); \
        ++i; \
        c = text.at(i); \
        cc = c.unicode(); \
    } while (0)

#define SKIP_SPACES() \
    while (c.isSpace() && cc != '\n') \
        SKIP_CHAR()

#define PUT_CHAR() \
    word += c; \
    SKIP_CHAR();

    if (location.depth() > 16)
        location.fatal(tr("Too many nested includes"));

    QFile fin(fileName);
    if (!fin.open(QFile::ReadOnly | QFile::Text)) {
        fin.setFileName(fileName + ".qdoc");
        if (!fin.open(QFile::ReadOnly | QFile::Text))
            location.fatal(tr("Cannot open file '%1': %2").arg(fileName).arg(fin.errorString()));
    }

    QTextStream stream(&fin);
    stream.setCodec("UTF-8");
    QString text = stream.readAll();
    text += QLatin1String("\n\n");
    text += QChar('\0');
    fin.close();

    location.push(fileName);
    location.start();

    int i = 0;
    QChar c = text.at(0);
    uint cc = c.unicode();
    while (i < (int) text.length()) {
        if (cc == 0)
            ++i;
        else if (c.isSpace()) {
            SKIP_CHAR();
        }
        else if (cc == '#') {
            do {
                SKIP_CHAR();
            } while (cc != '\n');
        }
        else if (isMetaKeyChar(c)) {
            Location keyLoc = location;
            bool plus = false;
            QString stringValue;
            QStringList stringListValue;
            QString word;
            bool inQuote = false;
            bool prevWordQuoted = true;
            bool metWord = false;

            MetaStack stack;
            do {
                stack.process(c, location);
                SKIP_CHAR();
            } while (isMetaKeyChar(c));

            QStringList keys = stack.getExpanded(location);
            //qDebug() << "KEYS:" << keys;
            SKIP_SPACES();

            if (keys.count() == 1 && keys.first() == "include") {
                QString includeFile;

                if (cc != '(')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                while (!c.isSpace() && cc != '#' && cc != ')') {
                    includeFile += c;
                    SKIP_CHAR();
                }
                SKIP_SPACES();
                if (cc != ')')
                    location.fatal(tr("Bad include syntax"));
                SKIP_CHAR();
                SKIP_SPACES();
                if (cc != '#' && cc != '\n')
                    location.fatal(tr("Trailing garbage"));

                /*
                  Here is the recursive call.
                 */
                load(location,
                      QFileInfo(QFileInfo(fileName).dir(), includeFile)
                      .filePath());
            }
            else {
                /*
                  It wasn't an include statement, so it;s something else.
                 */
                if (cc == '+') {
                    plus = true;
                    SKIP_CHAR();
                }
                if (cc != '=')
                    location.fatal(tr("Expected '=' or '+=' after key"));
                SKIP_CHAR();
                SKIP_SPACES();

                for (;;) {
                    if (cc == '\\') {
                        int metaCharPos;

                        SKIP_CHAR();
                        if (cc == '\n') {
                            SKIP_CHAR();
                        }
                        else if (cc > '0' && cc < '8') {
                            word += QChar(c.digitValue());
                            SKIP_CHAR();
                        }
                        else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) {
                            word += "\a\b\f\n\r\t\v"[metaCharPos];
                            SKIP_CHAR();
                        }
                        else {
                            PUT_CHAR();
                        }
                    }
                    else if (c.isSpace() || cc == '#') {
                        if (inQuote) {
                            if (cc == '\n')
                                location.fatal(tr("Unterminated string"));
                            PUT_CHAR();
                        }
                        else {
                            if (!word.isEmpty()) {
                                if (metWord)
                                    stringValue += QLatin1Char(' ');
                                stringValue += word;
                                stringListValue << word;
                                metWord = true;
                                word.clear();
                                prevWordQuoted = false;
                            }
                            if (cc == '\n' || cc == '#')
                                break;
                            SKIP_SPACES();
                        }
                    }
                    else if (cc == '"') {
                        if (inQuote) {
                            if (!prevWordQuoted)
                                stringValue += QLatin1Char(' ');
                            stringValue += word;
                            if (!word.isEmpty())
                                stringListValue << word;
                            metWord = true;
                            word.clear();
                            prevWordQuoted = true;
                        }
                        inQuote = !inQuote;
                        SKIP_CHAR();
                    }
                    else if (cc == '$') {
                        QString var;
                        SKIP_CHAR();
                        while (c.isLetterOrNumber() || cc == '_') {
                            var += c;
                            SKIP_CHAR();
                        }
                        if (!var.isEmpty()) {
                            char *val = getenv(var.toLatin1().data());
                            if (val == 0) {
                                location.fatal(tr("Environment variable '%1' undefined").arg(var));
                            }
                            else {
                                word += QString(val);
                            }
                        }
                    }
                    else {
                        if (!inQuote && cc == '=')
                            location.fatal(tr("Unexpected '='"));
                        PUT_CHAR();
                    }
                }

                QStringList::ConstIterator key = keys.begin();
                while (key != keys.end()) {
                    if (!keySyntax.exactMatch(*key))
                        keyLoc.fatal(tr("Invalid key '%1'").arg(*key));

                    if (plus) {
                        if (locMap[*key].isEmpty()) {
                            locMap[*key] = keyLoc;
                        }
                        else {
                            locMap[*key].setEtc(true);
                        }
                        if (stringValueMap[*key].isEmpty()) {
                            stringValueMap[*key] = stringValue;
                        }
                        else {
                            stringValueMap[*key] +=
                                QLatin1Char(' ') + stringValue;
                        }
                        stringListValueMap[*key] += stringListValue;
                    }
                    else {
                        locMap[*key] = keyLoc;
                        stringValueMap[*key] = stringValue;
                        stringListValueMap[*key] = stringListValue;
                    }
                    ++key;
                }
            }
        }
        else {
            location.fatal(tr("Unexpected character '%1' at beginning of line")
                            .arg(c));
        }
    }
}
Пример #3
0
void DrugStorage::getItem(int row,int column)//计算费用
{
    QString str2;
    QString str = str.fromLocal8Bit("警告");
    if (column==6)
    {
        if (ui.tableWidget->item(row,column)->text()==NULL) return;
        if (ui.tableWidget->item(row,column+2)->text()==NULL) return;

        int icount = ui.tableWidget->item(row,column)->text().toInt();
        if(icount<0)
        {
            str2 = str.fromLocal8Bit("收货数量不能为负,请核对!");
            QMessageBox::warning(this,str,str2,QMessageBox::Ok);
            QString stramount = QString::number(0);
            ui.tableWidget->setItem(row,column,new QTableWidgetItem(stramount));
            return;
        }
        double unitprice = ui.tableWidget->item(row,column+2)->text().toDouble();
        double amount = icount*unitprice;
        QString stramount = QString::number(amount);
        ui.tableWidget->setItem(row,column+3,new QTableWidgetItem(stramount));

        double icurrentamount = TotalPrice();
        QString strcurrentamount = QString::number(icurrentamount);

        //累加
        ui.lineEdit_Payable->setText(strcurrentamount);

        double iamount = ui.lineEdit_Paid->text().toInt();
        iamount = iamount - icurrentamount;
        /*if(ui.radioButton_Add->isChecked() && !ui.radioButton_Minus->isChecked())
        	iamount = iamount - icurrentamount;
        if(!ui.radioButton_Add->isChecked() && ui.radioButton_Minus->isChecked())
        	iamount = iamount + icurrentamount;*/
        strcurrentamount = QString::number(iamount);
        ui.lineEdit_debt->setText(strcurrentamount);


    }
    if(column==0)
    {
        list_widget->close();
        QString strText;
        if(ui.tableWidget->item(row,0)==NULL)  return;

        strText =  ui.tableWidget->item(row,0)->text();
        if(strText.at(0)== QChar('1')) return;

        list_widget->setGeometry(103, 160+row*30, 150, 280);
        list_widget->show();
        QSqlQuery query(*sql.db);
        strText =  ui.tableWidget->item(row,0)->text();
        QString strsql= QString("select * from sys_drugdictionary where abbr like '%%1%'or name like'%%2%'  ").arg(strText).arg(strText);

        query.exec(strsql);
        QStringList list;
        list_widget->clear();
        while(query.next())
        {
            QString str = query.value(1).toString();
            list.append(str);
        }
        list_widget->addItems(list);
    }
}
Пример #4
0
/*!
    Returns a string representation of the \a field value for the
    database. This is used, for example, when constructing INSERT and
    UPDATE statements.

    The default implementation returns the value formatted as a string
    according to the following rules:

    \list

    \li If \a field is character data, the value is returned enclosed
    in single quotation marks, which is appropriate for many SQL
    databases. Any embedded single-quote characters are escaped
    (replaced with two single-quote characters). If \a trimStrings is
    true (the default is false), all trailing whitespace is trimmed
    from the field.

    \li If \a field is date/time data, the value is formatted in ISO
    format and enclosed in single quotation marks. If the date/time
    data is invalid, "NULL" is returned.

    \li If \a field is \l{QByteArray}{bytearray} data, and the
    driver can edit binary fields, the value is formatted as a
    hexadecimal string.

    \li For any other field type, toString() is called on its value
    and the result of this is returned.

    \endlist

    \sa QVariant::toString()

*/
QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const
{
    const QLatin1String nullTxt("NULL");

    QString r;
    if (field.isNull())
        r = nullTxt;
    else {
        switch (field.type()) {
        case QVariant::Int:
        case QVariant::UInt:
            if (field.value().type() == QVariant::Bool)
                r = field.value().toBool() ? QLatin1String("1") : QLatin1String("0");
            else
                r = field.value().toString();
            break;
#ifndef QT_NO_DATESTRING
	case QVariant::Date:
            if (field.value().toDate().isValid())
                r = QLatin1Char('\'') + field.value().toDate().toString(Qt::ISODate)
                    + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::Time:
            if (field.value().toTime().isValid())
                r =  QLatin1Char('\'') + field.value().toTime().toString(Qt::ISODate)
                     + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
        case QVariant::DateTime:
            if (field.value().toDateTime().isValid())
                r = QLatin1Char('\'') +
                    field.value().toDateTime().toString(Qt::ISODate) + QLatin1Char('\'');
            else
                r = nullTxt;
            break;
#endif
        case QVariant::String:
        case QVariant::Char:
        {
            QString result = field.value().toString();
            if (trimStrings) {
                int end = result.length();
                while (end && result.at(end-1).isSpace()) /* skip white space from end */
                    end--;
                result.truncate(end);
            }
            /* escape the "'" character */
            result.replace(QLatin1Char('\''), QLatin1String("''"));
            r = QLatin1Char('\'') + result + QLatin1Char('\'');
            break;
        }
        case QVariant::Bool:
            r = QString::number(field.value().toBool());
            break;
        case QVariant::ByteArray : {
            if (hasFeature(BLOB)) {
                QByteArray ba = field.value().toByteArray();
                QString res;
                static const char hexchars[] = "0123456789abcdef";
                for (int i = 0; i < ba.size(); ++i) {
                    uchar s = (uchar) ba[i];
                    res += QLatin1Char(hexchars[s >> 4]);
                    res += QLatin1Char(hexchars[s & 0x0f]);
                }
                r = QLatin1Char('\'') + res +  QLatin1Char('\'');
                break;
            }
        }
        default:
            r = field.value().toString();
            break;
        }
    }
    return r;
}
Пример #5
0
const Molecule* LevelSet::readLevelMolecule(int levelNum) const
{
    Molecule* mol = new Molecule();
    KConfigGroup config = m_levelsFile->group("Level"+QString::number(levelNum));

    QString key;

    atom current;

    int atom_index = 1;
    QString value;
    while (true) {
        key.sprintf("atom_%c", int2atom(atom_index));
        value = config.readEntry(key,QString());
        if (value.isEmpty())
            break;

        current.obj = value.at(0).toLatin1();
        value = value.mid(2);

        strncpy(current.conn, value.toLatin1(), sizeof(current.conn));
        if (mol->m_atoms.indexOf(current) != -1)
            qWarning()
                << "OOOPS, duplicate atom definition in" << key;
        mol->m_atoms.append(current);
        atom_index++;
    }

    QString line;

    mol->m_width = 0;
    mol->m_height = 0;
    mol->m_weight = 0.0;

    int max_i = -1;
    for (int j = 0; j < MOLECULE_SIZE; j++) {

        key.sprintf("mole_%d", j);
        line = config.readEntry(key,QString());

        int max_non_null_i = -1;
        for (int i = 0; i < MOLECULE_SIZE; i++)
        {
            if (i >= line.size())
                mol->m_molek[i][j] = 0;
            else
            {
                mol->m_molek[i][j] = atom2int(line.at(i).toLatin1());
                mol->m_weight += mol->getAtom(mol->m_molek[i][j]).weight();
                max_non_null_i = i;
            }
        }
        if( max_non_null_i != -1 )
            mol->m_height++;
        max_i = qMax( max_i, max_non_null_i );
    }

    mol->m_width = max_i+1;

    mol->m_name = i18n(config.readEntry("Name", I18N_NOOP("Noname")).toUtf8());

    return mol;
}
Пример #6
0
void HighlightDefinition::removeDelimiters(const QString &characters)
{
    for (int i = 0; i < characters.length(); ++i)
        m_delimiters.remove(characters.at(i));
}
Пример #7
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
//static
bool QFileSystemEngine::fillMetaData(const QFileSystemEntry &entry, QFileSystemMetaData &data,
        QFileSystemMetaData::MetaDataFlags what)
{
#if defined(Q_OS_DARWIN)
    if (what & QFileSystemMetaData::BundleType) {
        if (!data.hasFlags(QFileSystemMetaData::DirectoryType))
            what |= QFileSystemMetaData::DirectoryType;
    }
    if (what & QFileSystemMetaData::HiddenAttribute) {
        // OS X >= 10.5: st_flags & UF_HIDDEN
        what |= QFileSystemMetaData::PosixStatFlags;
    }
#endif // defined(Q_OS_DARWIN)

    if (what & QFileSystemMetaData::PosixStatFlags)
        what |= QFileSystemMetaData::PosixStatFlags;

    if (what & QFileSystemMetaData::ExistsAttribute) {
        //  FIXME:  Would other queries being performed provide this bit?
        what |= QFileSystemMetaData::PosixStatFlags;
    }

    data.entryFlags &= ~what;

    const char * nativeFilePath;
    int nativeFilePathLength;
    {
        const QByteArray &path = entry.nativeFilePath();
        nativeFilePath = path.constData();
        nativeFilePathLength = path.size();
        Q_UNUSED(nativeFilePathLength);
    }

    bool entryExists = true; // innocent until proven otherwise

    QT_STATBUF statBuffer;
    bool statBufferValid = false;
    if (what & QFileSystemMetaData::LinkType) {
        if (QT_LSTAT(nativeFilePath, &statBuffer) == 0) {
            if (S_ISLNK(statBuffer.st_mode)) {
                data.entryFlags |= QFileSystemMetaData::LinkType;
            } else {
                statBufferValid = true;
                data.entryFlags &= ~QFileSystemMetaData::PosixStatFlags;
            }
        } else {
            entryExists = false;
        }

        data.knownFlagsMask |= QFileSystemMetaData::LinkType;
    }

    if (statBufferValid || (what & QFileSystemMetaData::PosixStatFlags)) {
        if (entryExists && !statBufferValid)
            statBufferValid = (QT_STAT(nativeFilePath, &statBuffer) == 0);

        if (statBufferValid)
            data.fillFromStatBuf(statBuffer);
        else {
            entryExists = false;
            data.creationTime_ = 0;
            data.modificationTime_ = 0;
            data.accessTime_ = 0;
            data.size_ = 0;
            data.userId_ = (uint) -2;
            data.groupId_ = (uint) -2;
        }

        // reset the mask
        data.knownFlagsMask |= QFileSystemMetaData::PosixStatFlags
            | QFileSystemMetaData::ExistsAttribute;
    }

#if defined(Q_OS_DARWIN)
    if (what & QFileSystemMetaData::AliasType)
    {
        if (entryExists && hasResourcePropertyFlag(data, entry, kCFURLIsAliasFileKey))
            data.entryFlags |= QFileSystemMetaData::AliasType;
        data.knownFlagsMask |= QFileSystemMetaData::AliasType;
    }
#endif

    if (what & QFileSystemMetaData::UserPermissions) {
        // calculate user permissions

        if (entryExists) {
            if (what & QFileSystemMetaData::UserReadPermission) {
                if (QT_ACCESS(nativeFilePath, R_OK) == 0)
                    data.entryFlags |= QFileSystemMetaData::UserReadPermission;
            }
            if (what & QFileSystemMetaData::UserWritePermission) {
                if (QT_ACCESS(nativeFilePath, W_OK) == 0)
                    data.entryFlags |= QFileSystemMetaData::UserWritePermission;
            }
            if (what & QFileSystemMetaData::UserExecutePermission) {
                if (QT_ACCESS(nativeFilePath, X_OK) == 0)
                    data.entryFlags |= QFileSystemMetaData::UserExecutePermission;
            }
        }
        data.knownFlagsMask |= (what & QFileSystemMetaData::UserPermissions);
    }

    if (what & QFileSystemMetaData::HiddenAttribute
            && !data.isHidden()) {
        QString fileName = entry.fileName();
        if ((fileName.size() > 0 && fileName.at(0) == QLatin1Char('.'))
#if defined(Q_OS_DARWIN)
                || (entryExists && hasResourcePropertyFlag(data, entry, kCFURLIsHiddenKey))
#endif
                )
            data.entryFlags |= QFileSystemMetaData::HiddenAttribute;
        data.knownFlagsMask |= QFileSystemMetaData::HiddenAttribute;
    }

#if defined(Q_OS_DARWIN)
    if (what & QFileSystemMetaData::BundleType) {
        if (entryExists && isPackage(data, entry))
            data.entryFlags |= QFileSystemMetaData::BundleType;

        data.knownFlagsMask |= QFileSystemMetaData::BundleType;
    }
#endif
    if (!entryExists) {
        data.clearFlags(what);
        return false;
    }
    return data.hasFlags(what);
}
Пример #9
0
QVariant QPSQLResult::data(int i)
{
    if (i >= PQnfields(d->result)) {
        qWarning("QPSQLResult::data: column %d out of range", i);
        return QVariant();
    }
    int ptype = PQftype(d->result, i);
    QVariant::Type type = qDecodePSQLType(ptype);
    const char *val = PQgetvalue(d->result, at(), i);
    if (PQgetisnull(d->result, at(), i))
        return QVariant(type);
    switch (type) {
    case QVariant::Bool:
        return QVariant((bool)(val[0] == 't'));
    case QVariant::String:
        return d->driver->isUtf8 ? QString::fromUtf8(val) : QString::fromAscii(val);
    case QVariant::LongLong:
        if (val[0] == '-')
            return QString::fromLatin1(val).toLongLong();
        else
            return QString::fromLatin1(val).toULongLong();
    case QVariant::Int:
        return atoi(val);
    case QVariant::Double:
        if (ptype == QNUMERICOID) {
            if (d->precisionPolicy != QSql::HighPrecision) {
                QVariant retval;
                bool convert;
                if (d->precisionPolicy == QSql::LowPrecisionInt64)
                    retval = QString::fromAscii(val).toLongLong(&convert);
                else if (d->precisionPolicy == QSql::LowPrecisionInt32)
                    retval = QString::fromAscii(val).toInt(&convert);
                else if (d->precisionPolicy == QSql::LowPrecisionDouble)
                    retval = QString::fromAscii(val).toDouble(&convert);
                if (!convert)
                    return QVariant();
                return retval;
            }
            return QString::fromAscii(val);
        }
        return strtod(val, 0);
    case QVariant::Date:
        if (val[0] == '\0') {
            return QVariant(QDate());
        } else {
#ifndef QT_NO_DATESTRING
            return QVariant(QDate::fromString(QString::fromLatin1(val), Qt::ISODate));
#else
            return QVariant(QString::fromLatin1(val));
#endif
        }
    case QVariant::Time: {
        const QString str = QString::fromLatin1(val);
#ifndef QT_NO_DATESTRING
        if (str.isEmpty())
            return QVariant(QTime());
        if (str.at(str.length() - 3) == QLatin1Char('+') || str.at(str.length() - 3) == QLatin1Char('-'))
            // strip the timezone
            // TODO: fix this when timestamp support comes into QDateTime
            return QVariant(QTime::fromString(str.left(str.length() - 3), Qt::ISODate));
        return QVariant(QTime::fromString(str, Qt::ISODate));
#else
        return QVariant(str);
#endif
    }
    case QVariant::DateTime: {
        QString dtval = QString::fromLatin1(val);
#ifndef QT_NO_DATESTRING
        if (dtval.length() < 10)
            return QVariant(QDateTime());
        // remove the timezone
        // TODO: fix this when timestamp support comes into QDateTime
        if (dtval.at(dtval.length() - 3) == QLatin1Char('+') || dtval.at(dtval.length() - 3) == QLatin1Char('-'))
            dtval.chop(3);
        // milliseconds are sometimes returned with 2 digits only
        if (dtval.at(dtval.length() - 3).isPunct())
            dtval += QLatin1Char('0');
        if (dtval.isEmpty())
            return QVariant(QDateTime());
        else
            return QVariant(QDateTime::fromString(dtval, Qt::ISODate));
#else
        return QVariant(dtval);
#endif
    }
    case QVariant::ByteArray: {
        size_t len;
        unsigned char *data = PQunescapeBytea((unsigned char*)val, &len);
        QByteArray ba((const char*)data, len);
        qPQfreemem(data);
        return QVariant(ba);
    }
    default:
    case QVariant::Invalid:
        qWarning("QPSQLResult::data: unknown data type");
    }
    return QVariant();
}
Пример #10
0
/*!
 *\~english
 *	Converted currency value to string representation (ru currency).
 *\~russian
 *	Конвертирует валюту, записанную в виде рублей и копеек в ее текстовое представление.	
 *\~
 *	\return - \~english Converted value \~russian Сконвертированное значение \~
 *	\see number2money(double rubli)
 *	\see part2string(unsigned int st3, unsigned int st2, unsigned int st1, int stepen)
*/
QString 
aService::parts2money(Q_ULLONG rubli,
			 unsigned int kopeyki,
			 bool need_kopeyki,
			 bool positive,
			 bool male,
			 const QString &end1,
			 const QString &end2,
			 const QString &end3)
{
//	if(cur!=ru) return QString("%1 dollars %2 cents").arg(rubli).arg(kopeyki);
	QString chislo = (QString("%1").arg(rubli));
	int len = chislo.length();
	//printf("length=%d\n",len);
	int count=0;
	int a,b,c;
	int stepen=(len-1)/3;
	int offset=(len%3);
	if(offset) offset = 3-offset;
	//printf("offset=%d\n",offset);
	QString res = "";
	bool has_sum=false;
	if(!positive) res+="минус ";
	while(count<len)
	{
		a=b=c=0;
		if(offset<=0)
		{
			a = chislo.at(count++).digitValue();
		}
		if(count<len)
		{
			if(offset<=1)
			{
				b = chislo.at(count++).digitValue();
			}
		}
		if(count<len)
		{
			if(offset<=2)
			{
				c = chislo.at(count++).digitValue();
			}
		}
//		printf("a=%d, b=%d, c=%d, stepen=%d\n",a,b,c,stepen);
		if(a==0 && b==0 && c==0)
		{	
			if(stepen==0 && has_sum)
			{
				res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
			}
			else
			{
				if(stepen==0)
				{
					res+=QString("ноль %1").arg(end1);
				}
				else
				{
					stepen--;
				}
			}
		}
		else
		{
			has_sum=true;
			res+=part2string(a,b,c,stepen--,male,end1,end2,end3);
		}
		offset=0;
	}
	if(need_kopeyki)
	{
		res+=part2string(0,kopeyki/10,kopeyki%10,-1,false,"копеек","копейка","копейки");
	}
	res = res.stripWhiteSpace();
	res = res.replace(0,1,res.at(0).upper());
	return res;
}
Пример #11
0
bool WorksheetPrivate::keyPressEvent(QKeyEvent *ev)
{
    ensure_caret(ws);

    if (ev == QKeySequence::SelectAll)
        return false;

    if ((ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) &&
        ev->modifiers() == Qt::ControlModifier)
    {
        if (ev->key() == Qt::Key_Up)
            historyPrev();
        else
            historyNext();
        ev->accept();
        return true;
    }

    if ((ev->key() == Qt::Key_Up || ev->key() == Qt::Key_Down) &&
        ev->modifiers() == Qt::AltModifier)
    {
        QTextCursor cr = ws->textCursor();
        if (ev->key() == Qt::Key_Up)
            prev_block(cr);
        else
            next_block(cr);
        ws->setTextCursor(cr);
        ws->ensureCursorVisible();
        ev->accept();
        return true;
    }

    bool handled;
    if (cursorMoveKeyEvent(ev, handled))
    {
        if (handled)
        {
            ev->accept();
            ws->ensureCursorVisible();
        }
        return handled;
    }

    if (ev == QKeySequence::Copy)
    {
        ws->copy();
        ev->accept();
        return true;
    }
    if (ev == QKeySequence::Cut)
    {
        ws->cut();
        goto done;
    }
    if (ev == QKeySequence::Paste)
    {
        ws->paste();
        goto done;
    }
    if (ev == QKeySequence::Undo)
    {
        ws->undo();
        goto done;
    }
    if (ev == QKeySequence::Redo)
    {
        ws->redo();
        goto done;
    }

    if (ev->key() == Qt::Key_Return || ev->key() == Qt::Key_Enter)
    {
        QTextCursor cr = ws->textCursor();
        Block *block = blockAtCursor(cr);

        if (ev->modifiers() == 0 && isPromptBlock(block))
        {
            commitInput();
        }
        else if (ev->modifiers() == Qt::AltModifier ||
                 (ev->modifiers() == 0 && isOutputBlock(block)))
        {
            QString anchor = anchorAtCursor();
            if (!anchor.isEmpty())
                ws->activateUrl(anchor);
            else
                beep();
            goto done;
        }
        else if (!(ev->modifiers() & ~Qt::ShiftModifier))
        {
            insertInteractive(ws, "\n", charFormat(), false);
            goto done;
        }
        else
        {
            beep();
        }

        ev->accept();
        return true;
    }

    {
        TextDocument::DeleteType type = (TextDocument::DeleteType) 0;

        if (ev->key() == Qt::Key_Backspace && !(ev->modifiers() & ~Qt::ShiftModifier))
            type = TextDocument::DeletePreviousChar;
        else if (ev == QKeySequence::Delete)
            type = TextDocument::DeleteNextChar;
        else if (ev == QKeySequence::DeleteEndOfWord)
            type = TextDocument::DeleteEndOfWord;
        else if (ev == QKeySequence::DeleteStartOfWord)
            type = TextDocument::DeleteStartOfWord;
        else if (ev == QKeySequence::DeleteEndOfLine)
            type = TextDocument::DeleteEndOfLine;

        if (type)
        {
            deleteInteractive(ws, type);
            goto done;
        }
    }

    {
        QString text = ev->text();
        if (text.isEmpty() || (!text.at(0).isPrint() && text.at(0) != QLatin1Char('\t')))
        {
            ev->ignore();
            return true;
        }
        else
            insertInteractive(ws, text, charFormat(), ws->overwriteMode());
    }

done:
//     cursorOn = true;
//     updateCurrentCharFormat();
    ev->accept();
    ws->ensureCursorVisible();
    return true;
}
Пример #12
0
void SourceEntryPrivate::parseData(const QString &data)
{
    if (data.isEmpty())
        return;

    QString tData = data.simplified();

    // Check for nonvalid input
    if (tData.isEmpty() || tData == QChar('#')) {
        isValid = false;
        return;
    }

    // Check source enable state
    if (tData.at(0) == '#') {
        isEnabled = false;
    }
    // Handle multiple comment characters (hey, it happens!)
    while (tData.size() > 0 && tData.at(0) == '#') {
        // Remove starting '#' from tData
        tData = tData.remove(0, 1);
        tData = tData.trimmed();
    }

    // Find any #'s past the start (these are comments)
    int idx = tData.indexOf('#');
    if (idx > 0) {
        // Save the comment, then remove from tData
        comment = tData.right(tData.size() - idx - 1);
        tData.remove(idx, tData.size() - idx + 1);
    }

    const QRegularExpression rx("^([a-z\\-]+) *");
    QRegularExpressionMatch match = rx.match(tData);

    // Parse type
    type = match.captured(1);
    const QSet<QString> types = { QLatin1String("rpm"), QLatin1String("rpm-src"), QLatin1String("deb"), QLatin1String("deb-src") };
    if (!match.isValid() || !types.contains(type)) {
        isValid = false;
        return;
    }
    
    int start = match.capturedEnd(), end = tData.size();
    // Parse architecture, see https://wiki.debian.org/Multiarch/HOWTO, Setting up sources
    if (tData[start] == '[') {
        QString metadata = tData.mid(start+1, tData.indexOf(']')-start-1);
        QStringList options = metadata.split(';');
        for (const QString &option : options) {
            QStringList parts = option.split('=');

            if (parts.size() != 2) {
                isValid = false;
                return;
            }

            QString key = parts.at(0);
            if (key != QLatin1String("arch")) {
                isValid = false;
                return;
            }

            QString value = parts.at(1);
            architectures = value.split(',');
        }
        
        start+=metadata.size()+2;
        for (; tData[start] == ' '; ++start)
        {}
    }
    
    bool inString = false;
    bool done = false;
    for (int i = start; !done && i<end; ++i) {
        switch (tData[i].toLatin1()) {
        case ' ':
            if (!inString) {
                uri = tData.mid(start, i-start);
                start = i+1;
                done = true;
            } break;
        case '[':
            inString = true;
            break;
        case ']':
            inString = false;
            break;
        }
    }
    if (uri.isEmpty() || !done) {
        isValid = false;
        return;
    }

    QStringList pieces = tData.mid(start).split(' ', QString::SkipEmptyParts);
    if (pieces.isEmpty()) {
        // Invalid source entry
        isValid = false;
        return;
    }

    // Parse distro and (optionally) components
    dist = pieces.takeFirst();
    components = pieces;
}
Пример #13
0
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mLogicalRepoApi);

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
			QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
			QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
			QString nameOfPlugin = nameOfTheDirectory.split("/").last();

			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + nameOfPlugin);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
					if (!nameOfPlugin.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ nameOfPlugin
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;

					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
Пример #14
0
List::List(const QString &labelStr)
    : QVector()
    , _clean(true)
{
    int labelPos = 0;
    bool needsValue = true;
    QRegExp rx;
    while(labelPos < labelStr.length())
    {
        // Check if we want a value or if we're expecting either an end of
        // string or a list value separator (:)
        if(!needsValue)
        {
            if(labelStr.at(labelPos) == QChar(':'))
            {
                needsValue = true;
                ++labelPos;
                continue;
            }
            else
            {
                qDebug() << "Unexpected char " << labelStr.at(labelPos) << " at "
                         << "position " << labelPos << ", was expecting a list "
                         << "value separator (:).";
                _clean = false;
                ++labelPos;
                continue;
            }
        }
        else if(labelStr.at(labelPos) == QChar(':'))
        {
            // If we encounter one right after another value then add an empty
            ++labelPos;
            push_back(ListValue("empty"));
            continue;
        }

        if(labelStr.at(labelPos) == QChar('\'')
                || labelStr.at(labelPos) == QChar('"'))
        {
            QChar matched = labelStr.at(labelPos);
            ++labelPos;
            int start = labelPos;
            while(labelPos < labelStr.length()
                  && labelStr.at(labelPos) != matched)
            {
                ++labelPos;
            }
            int len = labelPos - start;

            if(len == 0)
                push_back(ListValue(Atom("")));
            else
                push_back(ListValue(Atom(labelStr.mid(start, len))));

            if(labelPos < labelStr.length())
            {
                // We found a closing quote
                ++labelPos;
            }

            needsValue = false;
            continue;
        }

        rx = QRegExp("[a-zA-Z0-9_][a-zA-Z0-9_]{,62}");
        if(rx.indexIn(labelStr, labelPos) == labelPos)
        {
            QString identifier = rx.cap(0);
            int matchLength = rx.matchedLength();

            rx = QRegExp("\\d+");
            if(rx.indexIn(labelStr, labelPos) == labelPos &&
                    rx.matchedLength() >= matchLength)
            {
                labelPos += rx.matchedLength();
                QVariant num = rx.cap(0);
                int value = num.toInt();
                push_back(ListValue(Atom(value)));
                needsValue = false;
                continue;
            }
            labelPos += matchLength;
            push_back(ListValue(identifier));
            needsValue = false;
            continue;
        }

        qDebug() << "Unexpected char " << labelStr.at(labelPos) << " at  position "
                 << labelPos << ", was expecting an atom or variable.";
        _clean = false;
        ++labelPos;
    }
}
Пример #15
0
void SM_Dropbox_Json::parseString(QString strJson)
{
#ifdef SM_QTDROPBOX_DEBUG
    qDebug() << "parse string = " << strJson << endl;
#endif

    // clear all existing data
    emptyList();

    // basically a json is valid until it is invalidated
    valid = true;

    if(!strJson.startsWith("{") ||
            !strJson.endsWith("}"))
    {
#ifdef SM_QTDROPBOX_DEBUG
    qDebug() << "string does not start with { " << endl;
#endif

        if(strJson.startsWith("[") && strJson.endsWith("]"))
        {
#ifdef SM_QTDROPBOX_DEBUG
            qDebug() << "JSON is anonymous array" << endl;
#endif
            _anonymousArray = true;
            // fix json to be parseable by the algorithm below
            strJson = "{\"_anonArray\":"+strJson+"}";
        }
        else
        {
            valid = false;
            return;
        }
    }

    QString buffer   = "";
    QString key      = "";
    QString value    = "";

    bool isKey       = true;
    bool insertValue = false;
    bool isJson      = false;
    bool isArray     = false;
    bool openQuotes  = false;


    for(int i=0; i<strJson.size(); ++i)
    {
        switch(strJson.at(i).toLatin1())
        {
        case '"':
            if(!isKey)
            {
                buffer += "\"";
                openQuotes = !openQuotes;
            }
            continue;
            break;
        case ' ':
            if(!isKey)
                buffer += " ";
            continue;
            break;
        case '}':
        if(openQuotes)
          buffer += "}";
            continue;
            break;
        case ':':
            if(!isKey)
            {
                buffer += ":";
                continue;
            }
#ifdef SM_QTDROPBOX_DEBUG
            qDebug() << "key = " << buffer << endl;
#endif

            key    = buffer.trimmed();
            buffer = "";
            isKey  = false;
            break;
        case ',':
            if(openQuotes)
            {
                buffer += ',';
                continue;
            }
#ifdef SM_QTDROPBOX_DEBUG
            qDebug() << "value = " << buffer << endl;
#endif
            value       = buffer.trimmed();
            buffer      = "";
            isKey       = true;
            insertValue = true;
            break;
        case '{':
            if(i == 0)
                continue;
        if(!openQuotes)
              isJson  = true;
            buffer += '{';
            break;
        case '[':
        if(!openQuotes)
              isArray = true;
            buffer += '[';
            break;
        default:
            buffer += strJson.at(i);
            break;
        }

        if(isJson)
        {
            // create new json object with data until }
            sm_dropbox_json_entry e;
            int offset = parseSubJson(strJson, i, &e);
            valueMap[key] = e;
            key = "";

            // ignore next ,
            i = offset+1;
            buffer      = "";
            isJson      = false;
            insertValue = false;
            isKey       = true;
            //continue;
        }

         if(isArray)
         {
             // value is an array value -> parse array
             bool inString    = false;
             bool arrayEnd    = false;
             int arrayDepth = 0;
             int j = i+1;
             buffer = "[";
             for(;!arrayEnd && j<strJson.size();++j)
             {
                 QChar arrC = strJson.at(j);
                 switch(arrC.toLatin1())
                 {
                 case '"':
                     inString = !inString;
                     buffer += arrC;
                     break;
                 case '[':
                     buffer += "[";
                     arrayDepth += 1;
                     break;
                 case ']':
                     buffer += "]";
                     if(!inString)
                     {
                         if(arrayDepth == 0)
                         {
                            arrayEnd = true;
                         }
                         else
                         {
                            arrayDepth -= 1;
                         }
                     }
                     break;
                 case '\\':
                     if(strJson.at(j+1) == '"') // escaped double quote
                     {
                         buffer += "\"";
                         j++;
                     }
                     else
                         buffer += "\\";
                     break;
                 default:
                     buffer += arrC;
                     break;
                 }
             }

             // save array value string (buffer)
             value       = buffer;
             buffer      = "";
             i           = j;
             insertValue = true;
             isArray     = false;
             isKey       = true; // next element is started
         }

        if(insertValue)
        {
#ifdef SM_QTDROPBOX_DEBUG
            qDebug() << "insert value " << key << " with content = " << value.trimmed() << " and type = " << interpretType(value.trimmed()) << endl;
#endif
            sm_dropbox_json_entry e;
            QString *valuePointer = new QString(value.trimmed());
            e.value.value = valuePointer;
            e.type        = interpretType(value.trimmed());
            valueMap[key] = e;

            key   = "";
            value = "";
            insertValue = false;
        }
    }

    // there's some key left
    if(key.compare(""))
    {
#ifdef SM_QTDROPBOX_DEBUG
            qDebug() << "rest value = " << buffer << endl;
#endif
        // but no value in the buffer -> json is invalid because a value is missing
        if(!buffer.compare(""))
        {
            valid = false;
        }
        else
        {
            // if there's a value left we store it
            sm_dropbox_json_entry e;
            e.value.value = new QString(buffer.trimmed());
            e.type        = interpretType(buffer.trimmed());
            valueMap[key] = e;
        }

    }

    return;
}
Пример #16
0
QString SqlEditor::prepareExec(toSQLParse::tokenizer &tokens, int line, int pos)
{
	int LastLine = line;
	int LastOffset = pos;
	int endLine, endCol;

	if (ui.sqlTextEdit->lines() <= tokens.line())
	{
		endLine = ui.sqlTextEdit->lines() - 1;
		endCol = ui.sqlTextEdit->lineLength(ui.sqlTextEdit->lines() - 1);
	}
	else
	{
		endLine = tokens.line();
		if (ui.sqlTextEdit->lineLength(tokens.line()) <= tokens.offset())
			endCol = ui.sqlTextEdit->lineLength(tokens.line());
		else
		{
			endCol = tokens.offset();
		}
	}
	ui.sqlTextEdit->setSelection(line, pos, endLine, endCol);
	QString t = ui.sqlTextEdit->selectedText();

	bool comment = false;
	bool multiComment = false;
	int oline = line;
	int opos = pos;
	int i;

	for (i = 0;i < t.length() - 1;i++)
	{
		if (comment)
		{
			if (t.at(i) == '\n')
				comment = false;
		}
		else if (multiComment)
		{
			if (t.at(i) == '*' &&
						 t.at(i + 1) == '/')
			{
				multiComment = false;
				i++;
			}
		}
		else if (t.at(i) == '-' &&
					   t.at(i + 1) == '-')
			comment = true;
		else if (t.at(i) == '/' &&
					   t.at(i + 1) == '/')
			comment = true;
		else if (t.at(i) == '/' &&
					   t.at(i + 1) == '*')
			multiComment = true;
		else if (!t.at(i).isSpace() && t.at(i) != '/')
			break;

		if (t.at(i) == '\n')
		{
			line++;
			pos = 0;
		}
		else
			pos++;
	}

	if (line != oline ||
		   pos != opos)
	{
		LastLine = line;
		LastOffset = pos;
		ui.sqlTextEdit->setSelection(line, pos, endLine, endCol);
		t = t.mid(i);
	}

	return t;
}
Пример #17
0
QStringList SM_Dropbox_Json::getArray(QString key, bool force)
{
    QStringList list;
    if(!valueMap.contains(key))
        return list;

    sm_dropbox_json_entry e;
    e = valueMap.value(key);

    if(!force && e.type != SM_DROPBOX_JSON_TYPE_ARRAY)
        return list;

    QString arrayStr = e.value.value->mid(1, e.value.value->length()-2);
    QString buffer = "";
    bool inString = false;
    int  inJson   = 0;
    int  inArray  = 0;
    for(int i=0; i<arrayStr.size(); ++i)
    {
        QChar c = arrayStr.at(i);
        if( ((c != ',' && c != ' ') || inString || inJson || inArray) &&
            (c != '"' || inJson > 0 || inArray > 0))
            buffer += c;
        switch(c.toLatin1())
        {
        case '"':
            if(i > 0 && arrayStr.at(i-1).toLatin1() == '\\')
            {
                buffer += c;
                break;
            }
            else
                inString = !inString;
            break;
        case '{':
            inJson++;
            break;
        case '}':
            inJson--;
            break;
        case '[':
            inArray++;
            break;
        case ']':
            inArray--;
            break;
        case ',':
            if(inJson == 0 && inArray == 0 && !inString)
            {
                list.append(buffer);
                buffer = "";
            }
            break;
        }
    }

    if(!buffer.isEmpty())
        list.append(buffer);

    return list;
}
Пример #18
0
/**
 * Converts a double into a string which is as short as possible.
 *
 * @param value The double value
 * @param prec Precision
 */
QString RUnit::doubleToString(double value, int prec,
        bool /*showLeadingZeroes*/, bool showTrailingZeroes) {

    QString ret;

    QString formatString;
    if (showTrailingZeroes) {
        formatString = QString("%.0%1f").arg(prec);
    }
    else {
        formatString = QString("%.%1f").arg(prec);
    }

    // avoid banker's rounding, always round 0.5 up and -0.5 down:
    double fuzz = 1.0e-13;
    if (value<0.0) {
        fuzz*=-1;
    }

    ret.sprintf(formatString.toLatin1(), value + fuzz);

    if (!showTrailingZeroes) {
        if (ret.contains('.')) {
            // Remove zeros at the end:
            while (ret.at(ret.length()-1)=='0') {
                ret.truncate(ret.length()-1);
            }

            if(ret.at(ret.length()-1)=='.') {
                ret.truncate(ret.length()-1);
            }
        }
    }

    if (ret=="-0") {
        ret = "0";
    }

    return ret;

    /*
    QString valStr;

    value *= exp10(prec);
    value = RMath::mround(value);
    value /= exp10(prec);

    valStr.setNum(value, 'f', prec);

    if (valStr.contains('.')) {
        // Remove zeros at the end:
        while (valStr.at(valStr.length()-1)=='0') {
            valStr.truncate(valStr.length()-1);
        }

        if(valStr.at(valStr.length()-1)=='.') {
            valStr.truncate(valStr.length()-1);
        }
    }

    return valStr;
    */
}
Пример #19
0
void PkgConfigTool::packages_helper() const
{
    QStringList args;
    args.append(QLatin1String("--list-all"));

    QProcess pkgconfig;
    pkgconfig.start(QLatin1String("pkg-config"), args);
    while (! pkgconfig.waitForFinished()) {
    }

    QTextStream in(&pkgconfig);
    forever {
        const QString line = in.readLine();

        if (line.isNull())
            break;

        else if (line.isEmpty())
            continue;

        int i = 0;
        for (; i != line.length(); ++i) {
            if (line.at(i).isSpace())
                break;
        }

        Package package;
        package.name = line.left(i).trimmed();
        package.description = line.mid(i).trimmed();

        QStringList args;
        args << package.name << QLatin1String("--cflags");
        pkgconfig.start(QLatin1String("pkg-config"), args);

        while (! pkgconfig.waitForFinished()) {
        }

        const QString cflags = QString::fromUtf8(pkgconfig.readAll());

        int index = 0;
        while (index != cflags.size()) {
            const QChar ch = cflags.at(index);

            if (ch.isSpace()) {
                do { ++index; }
                while (index < cflags.size() && cflags.at(index).isSpace());
            }

            else if (ch == QLatin1Char('-') && index + 1 < cflags.size()) {
                ++index;

                const QChar opt = cflags.at(index);

                if (opt == QLatin1Char('I')) {
                    // include paths.

                    int start = ++index;
                    for (; index < cflags.size(); ++index) {
                        if (cflags.at(index).isSpace())
                            break;
                    }

                    qDebug() << "*** add include path:" << cflags.mid(start, index - start);
                    package.includePaths.append(cflags.mid(start, index - start));
                }
            }

            else {
                for (; index < cflags.size(); ++index) {
                    if (cflags.at(index).isSpace())
                        break;
                }
            }
        }

        m_packages.append(package);
    }
}
Пример #20
0
KJavaAppletViewer::KJavaAppletViewer(QWidget *wparent, const char *, QObject *parent, const char *name, const QStringList &args)
    : KParts::ReadOnlyPart(parent, name)
    , m_browserextension(new KJavaAppletViewerBrowserExtension(this))
    , m_liveconnect(new KJavaAppletViewerLiveConnectExtension(this))
    , m_statusbar(new KParts::StatusBarExtension(this))
    , m_statusbar_icon(0L)
    , m_closed(true)
{
    if(!serverMaintainer)
    {
        serverMaintainerDeleter.setObject(serverMaintainer, new KJavaServerMaintainer);
    }
    m_view = new CoverWidget(wparent);
    QString classname, classid, codebase, khtml_codebase, src_param;
    int width = -1;
    int height = -1;
    KJavaApplet *const applet = m_view->appletWidget()->applet();
    QStringList::const_iterator it = args.begin();
    const QStringList::const_iterator itEnd = args.end();
    for(; it != itEnd; ++it)
    {
        const int equalPos = (*it).find("=");
        if(equalPos > 0)
        {
            const QString name = (*it).left(equalPos).upper();
            QString value = (*it).right((*it).length() - equalPos - 1);
            if(value.at(0) == '\"')
                value = value.right(value.length() - 1);
            if(value.at(value.length() - 1) == '\"')
                value.truncate(value.length() - 1);
            kdDebug(6100) << "name=" << name << " value=" << value << endl;
            if(!name.isEmpty())
            {
                const QString name_lower = name.lower();
                if(name == "__KHTML__PLUGINBASEURL")
                {
                    baseurl = KURL(KURL(value), QString(".")).url();
                }
                else if(name == "__KHTML__CODEBASE")
                    khtml_codebase = value;
                else if(name_lower == QString::fromLatin1("codebase") || name_lower == QString::fromLatin1("java_codebase"))
                {
                    if(!value.isEmpty())
                        codebase = value;
                }
                else if(name == "__KHTML__CLASSID")
                    // else if (name.lower()==QString::fromLatin1("classid"))
                    classid = value;
                else if(name_lower == QString::fromLatin1("code") || name_lower == QString::fromLatin1("java_code"))
                    classname = value;
                else if(name_lower == QString::fromLatin1("src"))
                    src_param = value;
                else if(name_lower == QString::fromLatin1("archive") || name_lower == QString::fromLatin1("java_archive")
                        || name_lower.startsWith("cache_archive"))
                    applet->setArchives(value);
                else if(name_lower == QString::fromLatin1("name"))
                    applet->setAppletName(value);
                else if(name_lower == QString::fromLatin1("width"))
                    width = value.toInt();
                else if(name_lower == QString::fromLatin1("height"))
                    height = value.toInt();
                if(!name.startsWith("__KHTML__"))
                {
                    applet->setParameter(name, value);
                }
            }
        }
    }
    if(!classid.isEmpty())
    {
        applet->setParameter("CLSID", classid);
        kdDebug(6100) << "classid=" << classid << classid.startsWith("clsid:") << endl;
        if(classid.startsWith("clsid:"))
            // codeBase contains the URL to the plugin page
            khtml_codebase = baseurl;
        else if(classname.isEmpty() && classid.startsWith("java:"))
            classname = classid.mid(5);
    }
    if(classname.isEmpty())
        classname = src_param;
    else if(!src_param.isEmpty())
        applet->setParameter(QString("SRC"), src_param);
    if(codebase.isEmpty())
        codebase = khtml_codebase;
    if(baseurl.isEmpty())
    {
        // not embeded in khtml
        QString pwd = QDir().absPath();
        if(!pwd.endsWith(QChar(QDir::separator())))
            pwd += QDir::separator();
        baseurl = KURL(KURL(pwd), codebase).url();
    }
    if(width > 0 && height > 0)
    {
        m_view->resize(width, height);
        applet->setSize(QSize(width, height));
    }
    applet->setBaseURL(baseurl);
    // check codebase first
    const KURL kbaseURL(baseurl);
    const KURL newURL(kbaseURL, codebase);
    if(kapp->authorizeURLAction("redirect", KURL(baseurl), newURL))
        applet->setCodeBase(newURL.url());
    applet->setAppletClass(classname);
    KJavaAppletContext *const cxt = serverMaintainer->getContext(parent, baseurl);
    applet->setAppletContext(cxt);

    KJavaAppletServer *const server = cxt->getServer();

    serverMaintainer->setServer(server);

    if(!server->usingKIO())
    {
        /* if this page needs authentication */
        KIO::AuthInfo info;
        QString errorMsg;
        QCString replyType;
        QByteArray params;
        QByteArray reply;
        KIO::AuthInfo authResult;

        //(void) dcopClient(); // Make sure to have a dcop client.
        info.url = baseurl;
        info.verifyPath = true;

        QDataStream stream(params, IO_WriteOnly);
        stream << info << m_view->topLevelWidget()->winId();

        if(!kapp->dcopClient()->call("kded", "kpasswdserver", "checkAuthInfo(KIO::AuthInfo, long int)", params, replyType, reply))
        {
            kdWarning() << "Can't communicate with kded_kpasswdserver!" << endl;
        }
        else if(replyType == "KIO::AuthInfo")
        {
            QDataStream stream2(reply, IO_ReadOnly);
            stream2 >> authResult;
            applet->setUser(authResult.username);
            applet->setPassword(authResult.password);
            applet->setAuthName(authResult.realmValue);
        }
Пример #21
0
KDE_NO_CDTOR_EXPORT KlashPart::KlashPart (QWidget * wparent,
                    QObject * parent, const QStringList &args)
 : KParts::ReadOnlyPart (parent),
   //new KSimpleConfig ("klashrc")),
   m_browserextension (new KlashBrowserExtension (this)),
   m_liveconnectextension (new KlashLiveConnectExtension (this)),
   m_process (0L),
   m_width (0),
   m_height (0),
   m_autostart (false),
   m_fullscreen (false),
   m_started_emited (false) {
    //kdDebug () << "KlashPart(" << this << ")::KlashPart ()" << endl;
    bool show_fullscreen = false;
    // FIXME what is the right replacement for this? setInstance (KlashFactory::instance (), true);
    KAction *playact = new KAction(this);
    playact->setText(i18n("P&lay"));
    connect(playact, SIGNAL(triggered()), this, SLOT(play()));
    actionCollection()->addAction("play", playact);
    KAction *pauseact = new KAction(this);
    pauseact->setText(i18n("&Pause"));
    connect(pauseact, SIGNAL(triggered()), this, SLOT(pause()));
    actionCollection()->addAction("pause", pauseact);
    KAction *stopact = new KAction(this);
    stopact->setText(i18n("&Stop"));
    connect(stopact, SIGNAL(triggered()), this, SLOT(stop()));
    actionCollection()->addAction("stop", stopact);
    //new KAction (i18n ("Increase Volume"), QString ("player_volume"), KShortcut (), this, SLOT (increaseVolume ()), actionCollection (), "edit_volume_up");
    //new KAction (i18n ("Decrease Volume"), QString ("player_volume"), KShortcut (), this, SLOT (decreaseVolume ()), actionCollection (), "edit_volume_down");
    QStringList::const_iterator end = args.end ();
    for (QStringList::const_iterator it = args.begin () ; it != end; ++it) {
        int equalPos = (*it).indexOf("=");
        if (equalPos > 0) {
            QString name = (*it).left (equalPos).toLower ();
            QString value = (*it).right ((*it).length () - equalPos - 1);
            if (value.at(0)=='\"')
                value = value.right (value.length () - 1);
            if (value.at (value.length () - 1) == '\"')
                value.truncate (value.length () - 1);
            //kdDebug () << "name=" << name << " value=" << value << endl;
            if (name == QString::fromLatin1("width")) {
                m_width = value.toInt ();
            } else if (name == QString::fromLatin1("height")) {
                m_height = value.toInt ();
            //} else if (name == QString::fromLatin1("type")) {
            } else if (name == QString::fromLatin1("__khtml__pluginbaseurl")) {
                m_docbase = KUrl (value);
            } else if (name == QString::fromLatin1("src")) {
                m_src_url = value;
            } else if (name == QString::fromLatin1 ("fullscreenmode")) {
                show_fullscreen = getBoolValue (value);
            } else if (name == QString::fromLatin1 ("autostart")) {
                bool ok;
                m_autostart = value.toInt (&ok);
                if (!ok)
                    m_autostart = (value.toLower () == "false");
            }
            m_args.push_back(name + QChar('=') + value);
        }
    }
    KParts::Part::setWidget (new KlashView (wparent));
    setXMLFile("klashpartui.rc");
    setProgressInfoEnabled (false);

    if (m_fullscreen)
        fullScreen ();
}
Пример #22
0
void MainWindow::loadComPorts()
{
    ui->menuFile->clear();

    m_comPorts = new QActionGroup(this);
    m_comPorts->setExclusive(true);

    QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();

    for (int i = 0; i < ports.size(); i++) {
        QString fullName;
        QString friendName = ports.at(i).friendName;
        QString name = ports.at(i).portName;
        if (name.contains("LPT")) {
            continue;
        }

#ifdef Q_OS_WIN
        name.remove("\\\\.\\");
        fullName = QString("%1").arg(friendName);
#else

#ifdef Q_OS_LINUX
        name.prepend("/dev/");
#endif

        if (friendName.size() > 0) {
            fullName = QString("%1 (%2)").arg(friendName)
                                         .arg(name);
        } else {
            QChar num = name.at(name.size() - 1);

            if (name.contains("ttyS")) {
                fullName = QString("Serial Port %1 (%2)").arg(num).arg(name);
            } else if (name.contains("ttyACM")) {
                fullName = QString("Serial ACM %1 (%2)").arg(num).arg(name);
            } else if (name.contains("ttyUSB")) {
                fullName = QString("Serial USB %1 (%2)").arg(num).arg(name);
            }
        }
#endif

        QAction * com = new QAction(fullName, this);
        com->setToolTip(name);
        com->setCheckable(true);

        if (com->toolTip() == m_tty) {
            com->setChecked(true);
        }

        m_comPorts->addAction(com);

    }

    connect(m_comPorts, SIGNAL(triggered(QAction*)),
            this, SLOT(comAction_triggered(QAction*)));

    ui->menuFile->addActions(m_comPorts->actions());
    ui->menuFile->addSeparator();
    ui->menuFile->addAction(ui->actionRefresh);
    ui->menuFile->addSeparator();
    ui->menuFile->addAction(ui->actionQuit);
}
Пример #23
0
int main(int argc, char *argv[])
{
    QString outFilename;
    bool helpRequested = false, list = false;
    QStringList files;

    QStringList args = qCmdLineArgs(argc, argv);

    //parse options
    QString errorMsg;
    for (int i = 1; i < args.count() && errorMsg.isEmpty(); i++) {
        if (args[i].isEmpty())
            continue;
        if (args[i][0] == '-') {   // option
            QString opt = args[i];
            if (opt == QLatin1String("-o")) {
                if (!(i < argc-1)) {
                    errorMsg = QLatin1String("Missing output name");
                    break;
                }
                outFilename = args[++i];
            } else if (opt == QLatin1String("-name")) {
                if (!(i < argc-1)) {
                    errorMsg = QLatin1String("Missing target name");
                    break;
                }
                initName = args[++i];
            } else if (opt == QLatin1String("-root")) {
                if (!(i < argc-1)) {
                    errorMsg = QLatin1String("Missing root path");
                    break;
                }
                resourceRoot = QDir::cleanPath(args[++i]);
                if(resourceRoot.isEmpty() || resourceRoot.at(0) != QLatin1Char('/'))
                    errorMsg = QLatin1String("Root must start with a /");
            } else if (opt == QLatin1String("-compress")) {
                if (!(i < argc-1)) {
                    errorMsg = QLatin1String("Missing compression level");
                    break;
                }
                compressLevel = args[++i].toInt();
            } else if (opt == QLatin1String("-threshold")) {
                if (!(i < argc-1)) {
                    errorMsg = QLatin1String("Missing compression threshold");
                    break;
                }
                compressThreshold = args[++i].toInt();
            } else if (opt == QLatin1String("-binary")) {
                writeBinary = true;
            } else if (opt == QLatin1String("-verbose")) {
                verbose = true;
            } else if (opt == QLatin1String("-list")) {
                list = true;
            } else if (opt == QLatin1String("-version") || opt == QLatin1String("-v")) {
                fprintf(stderr, "Qt Resource Compiler version %s\n", QT_VERSION_STR);
                return 1;
            } else if (opt == QLatin1String("-help") || opt == QLatin1String("-h")) {
                helpRequested = true;
            } else if (opt == QLatin1String("-no-compress")) {
                compressLevel = -2;
            } else {
                errorMsg = QString::fromLatin1("Unknown option: '%1'").arg(args[i]);
            }
        } else {
            if (!QFile::exists(args[i])) {
                qWarning("%s: File does not exist '%s'", qPrintable(args[0]), qPrintable(args[i]));
                return 1;
            }
            files.append(args[i]);
        }
    }

    if (!files.size() || !errorMsg.isEmpty() || helpRequested)
        return showHelp(args[0], errorMsg);
    return int(!processResourceFile(files, outFilename, list));
}
/*!
    \internal

    Returns the canonicalized form of \a path (i.e., with all symlinks
    resolved, and all redundant path elements removed.
*/
QString QFSFileEnginePrivate::canonicalized(const QString &path)
{
    if (path.isEmpty())
        return path;

    // FIXME let's see if this stuff works, then we might be able to remove some of the other code.
#if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN)
    if (path.size() == 1 && path.at(0) == QLatin1Char('/'))
        return path;
#endif
#if defined(Q_OS_LINUX) || defined(Q_OS_SYMBIAN) || defined(Q_OS_MAC)
    // ... but Linux with uClibc does not have it
#if !defined(__UCLIBC__)
    char *ret = 0;
#if defined(Q_OS_MAC)
    // Mac OS X 10.5.x doesn't support the realpath(X,0) extension we use here.
    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) {
        ret = realpath(path.toLocal8Bit().constData(), (char*)0);
    } else {
        // on 10.5 we can use FSRef to resolve the file path.
        FSRef fsref;
        if (FSPathMakeRef((const UInt8 *)QDir::cleanPath(path).toUtf8().data(), &fsref, 0) == noErr) {
            CFURLRef urlref = CFURLCreateFromFSRef(NULL, &fsref);
            CFStringRef canonicalPath = CFURLCopyFileSystemPath(urlref, kCFURLPOSIXPathStyle);
            QString ret = QCFString::toQString(canonicalPath);
            CFRelease(canonicalPath);
            CFRelease(urlref);
            return ret;
        }
    }
#else
    ret = realpath(path.toLocal8Bit().constData(), (char*)0);
#endif
    if (ret) {
        QString canonicalPath = QDir::cleanPath(QString::fromLocal8Bit(ret));
        free(ret);
        return canonicalPath;
    }
#endif
#endif

    QFileInfo fi;
    const QChar slash(QLatin1Char('/'));
    QString tmpPath = path;
    int separatorPos = 0;
    QSet<QString> nonSymlinks;
    QSet<QString> known;

    known.insert(path);
    do {
#ifdef Q_OS_WIN
        // UNC, skip past the first two elements
        if (separatorPos == 0 && tmpPath.startsWith(QLatin1String("//")))
            separatorPos = tmpPath.indexOf(slash, 2);
        if (separatorPos != -1)
#endif
        separatorPos = tmpPath.indexOf(slash, separatorPos + 1);
        QString prefix = separatorPos == -1 ? tmpPath : tmpPath.left(separatorPos);
        if (
#ifdef Q_OS_SYMBIAN
            // Symbian doesn't support directory symlinks, so do not check for link unless we
            // are handling the last path element. This not only slightly improves performance,
            // but also saves us from lot of unnecessary platform security check failures
            // when dealing with files under *:/private directories.
            separatorPos == -1 &&
#endif
            !nonSymlinks.contains(prefix)) {
            fi.setFile(prefix);
            if (fi.isSymLink()) {
                QString target = fi.symLinkTarget();
                if (separatorPos != -1) {
                    if (fi.isDir() && !target.endsWith(slash))
                        target.append(slash);
                    target.append(tmpPath.mid(separatorPos));
                }
                tmpPath = QDir::cleanPath(target);
                separatorPos = 0;

                if (known.contains(tmpPath))
                    return QString();
                known.insert(tmpPath);
            } else {
                nonSymlinks.insert(prefix);
            }
        }
    } while (separatorPos != -1);

    return QDir::cleanPath(tmpPath);
}
Пример #25
0
CollapsibleEffect::CollapsibleEffect(const QDomElement &effect, const QDomElement &original_effect, const ItemInfo &info, EffectMetaInfo *metaInfo, bool canMoveUp, bool lastEffect, QWidget * parent) :
    AbstractCollapsibleWidget(parent),
    m_paramWidget(NULL),
    m_effect(effect),
    m_itemInfo(info),
    m_original_effect(original_effect),
    m_isMovable(true),
    m_animation(NULL),
    m_regionEffect(false)
{
    if (m_effect.attribute(QStringLiteral("tag")) == QLatin1String("region")) {
        m_regionEffect = true;
        decoframe->setObjectName(QStringLiteral("decoframegroup"));
    }
    filterWheelEvent = true;
    m_info.fromString(effect.attribute(QStringLiteral("kdenlive_info")));
    //setFont(QFontDatabase::systemFont(QFontDatabase::SmallestReadableFont));
    buttonUp->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-up")));
    QSize iconSize = buttonUp->iconSize();
    buttonUp->setMaximumSize(iconSize);
    buttonDown->setMaximumSize(iconSize);
    menuButton->setMaximumSize(iconSize);
    enabledButton->setMaximumSize(iconSize);
    buttonDel->setMaximumSize(iconSize);
    buttonUp->setToolTip(i18n("Move effect up"));
    buttonDown->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-down")));
    buttonDown->setToolTip(i18n("Move effect down"));
    buttonDel->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-deleffect")));
    buttonDel->setToolTip(i18n("Delete effect"));
    buttonUp->setEnabled(canMoveUp);
    buttonDown->setEnabled(!lastEffect);

    if (m_effect.attribute(QStringLiteral("id")) == QLatin1String("speed")) {
        // Speed effect is a "pseudo" effect, cannot be moved
        buttonUp->setVisible(false);
        buttonDown->setVisible(false);
        m_isMovable = false;
        setAcceptDrops(false);
    } else {
        setAcceptDrops(true);
    }

    /*buttonReset->setIcon(KoIconUtils::themedIcon("view-refresh"));
    buttonReset->setToolTip(i18n("Reset effect"));*/
    //checkAll->setToolTip(i18n("Enable/Disable all effects"));
    //buttonShowComments->setIcon(KoIconUtils::themedIcon("help-about"));
    //buttonShowComments->setToolTip(i18n("Show additional information for the parameters"));
    m_menu = new QMenu(this);
    m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("view-refresh")), i18n("Reset Effect"), this, SLOT(slotResetEffect()));
    m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("document-save")), i18n("Save Effect"), this, SLOT(slotSaveEffect()));

    QHBoxLayout *l = static_cast <QHBoxLayout *>(frame->layout());
    m_colorIcon = new QLabel(this);
    l->insertWidget(0, m_colorIcon);
    m_colorIcon->setMinimumSize(iconSize);
    title = new QLabel(this);
    l->insertWidget(2, title);

    m_enabledButton = new KDualAction(i18n("Disable Effect"), i18n("Enable Effect"), this);
    m_enabledButton->setActiveIcon(KoIconUtils::themedIcon(QStringLiteral("hint")));
    m_enabledButton->setInactiveIcon(KoIconUtils::themedIcon(QStringLiteral("visibility")));
    enabledButton->setDefaultAction(m_enabledButton);

    m_groupAction = new QAction(KoIconUtils::themedIcon(QStringLiteral("folder-new")), i18n("Create Group"), this);
    connect(m_groupAction, SIGNAL(triggered(bool)), this, SLOT(slotCreateGroup()));

    QDomElement namenode = m_effect.firstChildElement(QStringLiteral("name"));
    if (namenode.isNull()) {
        // Warning, broken effect?
        //qDebug()<<"// Could not create effect";
        return;
    }
    QString effectname = i18n(namenode.text().toUtf8().data());
    if (m_regionEffect) effectname.append(':' + QUrl(EffectsList::parameter(m_effect, QStringLiteral("resource"))).fileName());

    // Create color thumb
    QPixmap pix(iconSize);
    QColor col(m_effect.attribute(QStringLiteral("effectcolor")));
    QFont ft = font();
    ft.setBold(true);
    bool isAudio = m_effect.attribute(QStringLiteral("type")) == QLatin1String("audio");
    if (isAudio) {
        pix.fill(Qt::transparent);
    }
    else {
        pix.fill(col);
    }
    QPainter p(&pix);
    if (isAudio) {
        p.setPen(Qt::NoPen);
        p.setBrush(col);
        p.drawEllipse(pix.rect());
        p.setPen(QPen());
    }
    p.setFont(ft);
    p.drawText(pix.rect(), Qt::AlignCenter, effectname.at(0));
    p.end();
    m_iconPix = pix;
    m_colorIcon->setPixmap(pix);
    title->setText(effectname);

    if (!m_regionEffect) {
        if (m_info.groupIndex == -1) m_menu->addAction(m_groupAction);
        m_menu->addAction(KoIconUtils::themedIcon(QStringLiteral("folder-new")), i18n("Create Region"), this, SLOT(slotCreateRegion()));
    }
    setupWidget(info, metaInfo);
    menuButton->setIcon(KoIconUtils::themedIcon(QStringLiteral("kdenlive-menu")));
    menuButton->setMenu(m_menu);

    if (m_effect.attribute(QStringLiteral("disable")) == QLatin1String("1")) {
        title->setEnabled(false);
        m_enabledButton->setActive(true);
    }
    else {
        m_enabledButton->setActive(false);
    }

    connect(collapseButton, SIGNAL(clicked()), this, SLOT(slotSwitch()));
    connect(m_enabledButton, SIGNAL(activeChangedByUser(bool)), this, SLOT(slotDisable(bool)));
    connect(buttonUp, SIGNAL(clicked()), this, SLOT(slotEffectUp()));
    connect(buttonDown, SIGNAL(clicked()), this, SLOT(slotEffectDown()));
    connect(buttonDel, SIGNAL(clicked()), this, SLOT(slotDeleteEffect()));

    Q_FOREACH( QSpinBox * sp, findChildren<QSpinBox*>() ) {
        sp->installEventFilter( this );
        sp->setFocusPolicy( Qt::StrongFocus );
    }
/*
    Replaces t[k] by ch, unless t[k] is '\t'. Tab characters are better
    left alone since they break the "index equals column" rule. No
    provisions are taken against '\n' or '\r', which shouldn't occur in
    t anyway.
*/
void QmlJSIndenter::eraseChar(QString &t, int k, QChar ch) const
{
    if (t.at(k) != QLatin1Char('\t'))
        t[k] = ch;
}
Пример #27
0
void MainWindow::checkInput()
{
    /*
    //DELETE THIS PART!
    ui->imagePath->insert("D:/WORKSPACE/PHOTO MOSAIC/StarWars.jpg");
    ui->subImgDir->insert("D:/WORKSPACE/PHOTO MOSAIC/PICTURES/StarWars");
    ui->pmWidth->insert("15360"); //15360
    ui->pmHeight->insert("8640"); //8640
    ui->numOfSub->insert("57600"); //57600
    ui->subRatio->insert("16:9"); //16:9
    ui->precisionBox->setValue(2); // precision
    */

    QString mainImgPath = ui->imagePath->text();
    QString subImgDir = ui->subImgDir->text();
    if (subImgDir.length() >= 1) {
        if (subImgDir.at(subImgDir.size() - 1) != '/') {
            subImgDir.insert(subImgDir.size(), '/');
        }
    }


    int precision = ui->precisionBox ->value();
    int mainWidth = ui->pmWidth->text().toInt();
    int mainHeight = ui->pmHeight->text().toInt();
    int numSubImg = ui->numOfSub->text().toInt();
    QString ratio = ui->subRatio->text();

    int wRatio = ratio.split(":").value(0).toInt();
    int hRatio = ratio.split(":").value(1).toInt();


    if (allValidInput(mainWidth,mainHeight,numSubImg,ratio,mainImgPath,subImgDir)) {

        ui->graphicsView->setScene(scene);
        QPixmap img(mainImgPath);
        scene->addPixmap(img);
//                ui->graphicsView->fitInView(0,00);
        ui->graphicsView->fitInView(scene->itemsBoundingRect() ,Qt::KeepAspectRatio);

        memberVariables.append(QString::number(mainWidth));
        memberVariables.append(QString::number(mainHeight));
        memberVariables.append(QString::number(wRatio));
        memberVariables.append(QString::number(hRatio));
        memberVariables.append(QString::number(numSubImg));
        memberVariables.append(mainImgPath);
        memberVariables.append(subImgDir);
        memberVariables.append(QString::number(precision));

        qDebug() << wRatio << hRatio;
        emit updateAll(memberVariables); //emits the signal

        // inputs are read-only.
        ui->pmWidth->setEnabled(false);
        ui->pmHeight->setEnabled(false);
        ui->subRatio->setEnabled(false);
        ui->numOfSub->setEnabled(false);
        ui->imagePath->setEnabled(false);
        ui->subImgDir->setEnabled(false);
        ui->precisionBox->setEnabled(false);

        qDebug() << "EMMITED;";
    }

}
Пример #28
0
// tries to complete "string" from the tree-root
QString KCompletion::findCompletion( const QString& string )
{
    QChar ch;
    QString completion;
    const KCompTreeNode *node = myTreeRoot;

    // start at the tree-root and try to find the search-string
    for( uint i = 0; i < string.length(); i++ ) {
        ch = string.at( i );
        node = node->find( ch );

        if ( node )
            completion += ch;
        else
            return QString::null; // no completion
    }

    // Now we have the last node of the to be completed string.
    // Follow it as long as it has exactly one child (= longest possible
    // completion)

    while ( node->childrenCount() == 1 ) {
        node = node->firstChild();
        if ( !node->isNull() )
            completion += *node;
    }
    // if multiple matches and auto-completion mode
    // -> find the first complete match
    if ( node && node->childrenCount() > 1 ) {
        myHasMultipleMatches = true;
    
        if ( myCompletionMode == KGlobalSettings::CompletionAuto ) {
            myRotationIndex = 1;
            if (myOrder != Weighted) {
                while ( (node = node->firstChild()) ) {
                    if ( !node->isNull() )
                        completion += *node;
                    else
                        break;
                }
            }
            else {
                // don't just find the "first" match, but the one with the
                // highest priority
        
                const KCompTreeNode* temp_node = 0L;
                while(1) {
                    int count = node->childrenCount();
                    temp_node = node->firstChild();
                    uint weight = temp_node->weight();
                    const KCompTreeNode* hit = temp_node;
                    for( int i = 1; i < count; i++ ) {
                        temp_node = node->childAt(i);
                        if( temp_node->weight() > weight ) {
                            hit = temp_node;
                            weight = hit->weight();
                        }
                    }
                    // 0x0 has the highest priority -> we have the best match
                    if ( hit->isNull() )
                        break;

                    node = hit;
                    completion += *node;
                }
            }
        }

        else
            doBeep( PartialMatch ); // partial match -> beep
    }

    return completion;
}
Пример #29
0
bool Q3Process::start( QStringList *env )
{
#if defined(QT_Q3PROCESS_DEBUG)
    qDebug( "Q3Process::start()" );
#endif
    reset();

    if ( _arguments.isEmpty() )
	return false;

    // Open the pipes.  Make non-inheritable copies of input write and output
    // read handles to avoid non-closable handles (this is done by the
    // DuplicateHandle() call).
    SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
#ifndef Q_OS_WINCE
    // I guess there is no stdin stdout and stderr on Q_OS_WINCE to dup
    // CreatePipe and DupilcateHandle aren't available for Q_OS_WINCE
    HANDLE tmpStdin, tmpStdout, tmpStderr;
    if ( comms & Stdin ) {
	if ( !CreatePipe( &d->pipeStdin[0], &tmpStdin, &secAtt, 0 ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !DuplicateHandle( GetCurrentProcess(), tmpStdin, GetCurrentProcess(), &d->pipeStdin[1], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !CloseHandle( tmpStdin ) ) {
	    d->closeHandles();
	    return false;
	}
    }
    if ( comms & Stdout ) {
	if ( !CreatePipe( &tmpStdout, &d->pipeStdout[1], &secAtt, 0 ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !DuplicateHandle( GetCurrentProcess(), tmpStdout, GetCurrentProcess(), &d->pipeStdout[0], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !CloseHandle( tmpStdout ) ) {
	    d->closeHandles();
	    return false;
	}
    }
    if ( comms & Stderr ) {
	if ( !CreatePipe( &tmpStderr, &d->pipeStderr[1], &secAtt, 0 ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !DuplicateHandle( GetCurrentProcess(), tmpStderr, GetCurrentProcess(), &d->pipeStderr[0], 0, FALSE, DUPLICATE_SAME_ACCESS ) ) {
	    d->closeHandles();
	    return false;
	}
	if ( !CloseHandle( tmpStderr ) ) {
	    d->closeHandles();
	    return false;
	}
    }
    if ( comms & DupStderr ) {
	CloseHandle( d->pipeStderr[1] );
	d->pipeStderr[1] = d->pipeStdout[1];
    }
#endif

    // construct the arguments for CreateProcess()
    QString args;
    QString appName;
    QStringList::Iterator it = _arguments.begin();
    args = *it;
    ++it;
    if ( args.endsWith( QLatin1String(".bat") ) && args.contains( QLatin1Char(' ') ) ) {
	// CreateProcess() seems to have a strange semantics (see also
	// http://www.experts-exchange.com/Programming/Programming_Platforms/Win_Prog/Q_11138647.html):
	// If you start a batch file with spaces in the filename, the first
	// argument to CreateProcess() must be the name of the batchfile
	// without quotes, but the second argument must start with the same
	// argument with quotes included. But if the same approach is used for
	// .exe files, it doesn't work.
	appName = args;
	args = QLatin1Char('"') + args + QLatin1Char('"');
    }
    for ( ; it != _arguments.end(); ++it ) {
	QString tmp = *it;
	// escape a single " because the arguments will be parsed
	tmp.replace( QLatin1Char('\"'), QLatin1String("\\\"") );
	if ( tmp.isEmpty() || tmp.contains( QLatin1Char(' ') ) || tmp.contains( QLatin1Char('\t') ) ) {
	    // The argument must not end with a \ since this would be interpreted
	    // as escaping the quote -- rather put the \ behind the quote: e.g.
	    // rather use "foo"\ than "foo\"
	    QString endQuote( QLatin1String("\"") );
	    int i = tmp.length();
	    while ( i>0 && tmp.at( i-1 ) == QLatin1Char('\\') ) {
		--i;
		endQuote += QLatin1Char('\\');
	    }
        args += QLatin1String(" \"") + tmp.left( i ) + endQuote;
	} else {
	    args += QLatin1Char(' ') + tmp;
	}
    }
#if defined(QT_Q3PROCESS_DEBUG)
    qDebug( "Q3Process::start(): args [%s]", args.latin1() );
#endif

    // CreateProcess()
    bool success;
    d->newPid();

    STARTUPINFOW startupInfo = {
        sizeof( STARTUPINFO ), 0, 0, 0,
        (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
        0, 0, 0,
        STARTF_USESTDHANDLES,
        0, 0, 0,
        d->pipeStdin[0], d->pipeStdout[1], d->pipeStderr[1]
    };
    wchar_t *applicationName;
    if ( appName.isNull() )
        applicationName = 0;
    else
        applicationName = _wcsdup( (wchar_t*)appName.utf16() );
    wchar_t *commandLine = _wcsdup( (wchar_t*)args.utf16() );
    QByteArray envlist;
    if ( env != 0 ) {
        int pos = 0;
        // add PATH if necessary (for DLL loading)
        QByteArray path = qgetenv( "PATH" );
        if ( env->grep( QRegExp(QLatin1String("^PATH="),FALSE) ).empty() && !path.isNull() ) {
            QString tmp = QString::fromLatin1("PATH=%1").arg(QLatin1String(path.constData()));
            uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
            envlist.resize( envlist.size() + tmpSize );
            memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
            pos += tmpSize;
        }
        // add the user environment
        for ( QStringList::Iterator it = env->begin(); it != env->end(); it++ ) {
            QString tmp = *it;
            uint tmpSize = sizeof(wchar_t) * (tmp.length() + 1);
            envlist.resize( envlist.size() + tmpSize );
            memcpy( envlist.data() + pos, tmp.utf16(), tmpSize );
            pos += tmpSize;
        }
        // add the 2 terminating 0 (actually 4, just to be on the safe side)
        envlist.resize( envlist.size()+4 );
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
        envlist[pos++] = 0;
    }
    success = CreateProcess( applicationName, commandLine,
                            0, 0, TRUE, ( comms == 0 ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW )
#ifndef Q_OS_WINCE
                            | CREATE_UNICODE_ENVIRONMENT
#endif
                            , env == 0 ? 0 : envlist.data(),
                            (wchar_t*)QDir::toNativeSeparators(workingDir.absPath()).utf16(),
                            &startupInfo, d->pid );

    free( applicationName );
    free( commandLine );

    if  ( !success ) {
	d->deletePid();
	return false;
    }

#ifndef Q_OS_WINCE
    if ( comms & Stdin )
	CloseHandle( d->pipeStdin[0] );
    if ( comms & Stdout )
        CloseHandle( d->pipeStdout[1] );
    if ( (comms & Stderr) && !(comms & DupStderr) )
	CloseHandle( d->pipeStderr[1] );
#endif

    if ( ioRedirection || notifyOnExit ) {
	d->lookup->start( 100 );
    }

    // cleanup and return
    return true;
}
Пример #30
0
bool AccelTreeResourceLoader::retrieveUnparsedText(const QUrl &uri,
                                                   const QString &encoding,
                                                   const ReportContext::Ptr &context,
                                                   const SourceLocationReflection *const where)
{
    const AutoPtr<QNetworkReply> reply(load(uri, m_networkAccessDelegator, context));

    if(!reply)
        return false;

    const QTextCodec * codec;
    if(encoding.isEmpty())
    {
        /* XSL Transformations (XSLT) Version 2.0 16.2 Reading Text Files:
         *
         * "if the media type of the resource is text/xml or application/xml
         * (see [RFC2376]), or if it matches the conventions text/\*+xml or
         * application/\*+xml (see [RFC3023] and/or its successors), then the
         * encoding is recognized as specified in [XML 1.0]"
         */
        codec = QTextCodec::codecForMib(106);
    }
    else
    {
        codec = QTextCodec::codecForName(encoding.toLatin1());
        if(codec && context)
        {
            context->error(QtXmlPatterns::tr("%1 is an unsupported encoding.").arg(formatURI(encoding)),
                           ReportContext::XTDE1190,
                           where);
        }
        else
            return false;
    }

    QTextCodec::ConverterState converterState;
    const QByteArray inData(reply->readAll());
    const QString result(codec->toUnicode(inData.constData(), inData.length(), &converterState));

    if(converterState.invalidChars)
    {
        if(context)
        {
            context->error(QtXmlPatterns::tr("%1 contains octets which are disallowed in "
                                             "the requested encoding %2.").arg(formatURI(uri),
                                                                               formatURI(encoding)),
                           ReportContext::XTDE1190,
                           where);
        }
        else
            return false;
    }

    const int len = result.length();
    /* This code is a candidate for threading. Divide and conqueror. */
    for(int i = 0; i < len; ++i)
    {
        if(!QXmlUtils::isChar(result.at(i)))
        {
            if(context)
            {
                context->error(QtXmlPatterns::tr("The codepoint %1, occurring in %2 using encoding %3, "
                                                 "is an invalid XML character.").arg(formatData(result.at(i)),
                                                                                     formatURI(uri),
                                                                                     formatURI(encoding)),
                               ReportContext::XTDE1190,
                               where);
            }
            else
                return false;
        }
    }

    m_unparsedTexts.insert(qMakePair(uri, encoding), result);
    return true;
}