Esempio n. 1
1
bool TSReader::read(Translator &translator)
{
    STRING(both);
    STRING(byte);
    STRING(comment);
    STRING(context);
    STRING(defaultcodec);
    STRING(encoding);
    STRING(extracomment);
    STRING(filename);
    STRING(id);
    STRING(language);
    STRING(line);
    STRING(location);
    STRING(message);
    STRING(name);
    STRING(numerus);
    STRING(numerusform);
    STRING(obsolete);
    STRING(oldcomment);
    STRING(oldsource);
    STRING(source);
    STRING(sourcelanguage);
    STRING(translation);
    STRING(translatorcomment);
    STRING(true);
    STRING(TS);
    STRING(type);
    STRING(unfinished);
    STRING(userdata);
    STRING(utf8);
    STRING(value);
    //STRING(version);
    STRING(yes);

    static const QString strextrans(QLatin1String("extra-"));
    static const QString strUtf8(QLatin1String("UTF-8"));

    while (!atEnd()) {
        readNext();
        if (isStartDocument()) {
            // <!DOCTYPE TS>
            //qDebug() << attributes();
        } else if (isEndDocument()) {
            // <!DOCTYPE TS>
            //qDebug() << attributes();
        } else if (isDTD()) {
            // <!DOCTYPE TS>
            //qDebug() << tokenString();
        } else if (elementStarts(strTS)) {
            // <TS>
            //qDebug() << "TS " << attributes();
            QHash<QString, int> currentLine;
            QString currentFile;

            QXmlStreamAttributes atts = attributes();
            //QString version = atts.value(strversion).toString();
            translator.setLanguageCode(atts.value(strlanguage).toString());
            translator.setSourceLanguageCode(atts.value(strsourcelanguage).toString());
            while (!atEnd()) {
                readNext();
                if (isEndElement()) {
                    // </TS> found, finish local loop
                    break;
                } else if (isWhiteSpace()) {
                    // ignore these, just whitespace
                } else if (elementStarts(strdefaultcodec)) {
                    // <defaultcodec>
                    const QString &codec = readElementText();
                    if (!codec.isEmpty())
                        translator.setCodecName(codec.toLatin1());
                    // </defaultcodec>
                } else if (isStartElement()
                        && name().toString().startsWith(strextrans)) {
                    // <extra-...>
                    QString tag = name().toString();
                    translator.setExtra(tag.mid(6), readContents());
                    // </extra-...>
                } else if (elementStarts(strcontext)) {
                    // <context>
                    QString context;
                    while (!atEnd()) {
                        readNext();
                        if (isEndElement()) {
                            // </context> found, finish local loop
                            break;
                        } else if (isWhiteSpace()) {
                            // ignore these, just whitespace
                        } else if (elementStarts(strname)) {
                            // <name>
                            context = readElementText();
                            // </name>
                        } else if (elementStarts(strmessage)) {
                            // <message>
                            TranslatorMessage::References refs;
                            QString currentMsgFile = currentFile;

                            TranslatorMessage msg;
                            msg.setId(attributes().value(strid).toString());
                            msg.setContext(context);
                            msg.setType(TranslatorMessage::Finished);
                            msg.setPlural(attributes().value(strnumerus) == stryes);
                            const QStringRef &utf8Attr = attributes().value(strutf8);
                            msg.setNonUtf8(utf8Attr == strboth);
                            msg.setUtf8(msg.isNonUtf8() || utf8Attr == strtrue
                                 ||  attributes().value(strencoding) == strUtf8);
                            while (!atEnd()) {
                                readNext();
                                if (isEndElement()) {
                                    // </message> found, finish local loop
                                    msg.setReferences(refs);
                                    translator.append(msg);
                                    break;
                                } else if (isWhiteSpace()) {
                                    // ignore these, just whitespace
                                } else if (elementStarts(strsource)) {
                                    // <source>...</source>
                                    msg.setSourceText(readContents());
                                } else if (elementStarts(stroldsource)) {
                                    // <oldsource>...</oldsource>
                                    msg.setOldSourceText(readContents());
                                } else if (elementStarts(stroldcomment)) {
                                    // <oldcomment>...</oldcomment>
                                    msg.setOldComment(readContents());
                                } else if (elementStarts(strextracomment)) {
                                    // <extracomment>...</extracomment>
                                    msg.setExtraComment(readContents());
                                } else if (elementStarts(strtranslatorcomment)) {
                                    // <translatorcomment>...</translatorcomment>
                                    msg.setTranslatorComment(readContents());
                                } else if (elementStarts(strlocation)) {
                                    // <location/>
                                    QXmlStreamAttributes atts = attributes();
                                    QString fileName = atts.value(strfilename).toString();
                                    if (fileName.isEmpty()) {
                                        fileName = currentMsgFile;
                                    } else {
                                        if (refs.isEmpty())
                                            currentFile = fileName;
                                        currentMsgFile = fileName;
                                    }
                                    const QString lin = atts.value(strline).toString();
                                    if (lin.isEmpty()) {
                                        translator.setLocationsType(Translator::RelativeLocations);
                                        refs.append(TranslatorMessage::Reference(fileName, -1));
                                    } else {
                                        bool bOK;
                                        int lineNo = lin.toInt(&bOK);
                                        if (bOK) {
                                            if (lin.startsWith(QLatin1Char('+')) || lin.startsWith(QLatin1Char('-'))) {
                                                lineNo = (currentLine[fileName] += lineNo);
                                                translator.setLocationsType(Translator::RelativeLocations);
                                            } else {
                                                translator.setLocationsType(Translator::AbsoluteLocations);
                                            }
                                            refs.append(TranslatorMessage::Reference(fileName, lineNo));
                                        }
                                    }
                                    readContents();
                                } else if (elementStarts(strcomment)) {
                                    // <comment>...</comment>
                                    msg.setComment(readContents());
                                } else if (elementStarts(struserdata)) {
                                    // <userdata>...</userdata>
                                    msg.setUserData(readContents());
                                } else if (elementStarts(strtranslation)) {
                                    // <translation>
                                    QXmlStreamAttributes atts = attributes();
                                    QStringRef type = atts.value(strtype);
                                    if (type == strunfinished)
                                        msg.setType(TranslatorMessage::Unfinished);
                                    else if (type == strobsolete)
                                        msg.setType(TranslatorMessage::Obsolete);
                                    if (msg.isPlural()) {
                                        QStringList translations;
                                        while (!atEnd()) {
                                            readNext();
                                            if (isEndElement()) {
                                                break;
                                            } else if (isWhiteSpace()) {
                                                // ignore these, just whitespace
                                            } else if (elementStarts(strnumerusform)) {
                                                translations.append(readTransContents());
                                            } else {
                                                handleError();
                                                break;
                                            }
                                        }
                                        msg.setTranslations(translations);
                                    } else {
                                        msg.setTranslation(readTransContents());
                                    }
                                    // </translation>
                                } else if (isStartElement()
                                        && name().toString().startsWith(strextrans)) {
                                    // <extra-...>
                                    QString tag = name().toString();
                                    msg.setExtra(tag.mid(6), readContents());
                                    // </extra-...>
                                } else {
                                    handleError();
                                }
                            }
                            // </message>
                        } else {
                            handleError();
                        }
                    }
                    // </context>
                } else {
                    handleError();
                }
            } // </TS>
        } else {
            handleError();
        }
    }
    if (hasError()) {
        m_cd.appendError(errorString());
        return false;
    }
    return true;
}
Esempio n. 2
0
    int suggestedColumnSize(int column) const
    {
        QHeaderView *h = q->header();
        QTC_ASSERT(h, return -1);
        QAbstractItemModel *m = q->model();
        QTC_ASSERT(m, return -1);

        QFontMetrics fm = q->fontMetrics();
        int minimum = fm.width(m->headerData(column, Qt::Horizontal).toString()) + 2 * fm.width(QLatin1Char('m'));
        considerItems(column, q->indexAt(QPoint(1, 1)), &minimum, false);

        QVariant extraIndices = m->data(QModelIndex(), BaseTreeView::ExtraIndicesForColumnWidth);
        foreach (const QModelIndex &a, extraIndices.value<QModelIndexList>())
            considerItems(column, a, &minimum, true);

        return minimum;
    }
Esempio n. 3
0
/*!
    \fn Ebackup::generar_config()
    Genera un una copia de los valores de configuracion del programa y los prepara para la compresion.
 */
bool Ebackup::generar_config()
{
 preferencias *p = preferencias::getInstancia();
 // Obtengo todas las claves
 QStringList claves = p->allKeys();
 PBProgreso->setRange( 0, ( claves.size() * 2 ) + 2 );
 PBProgreso->setValue( 0 );
 // Genero los datos concatenando las variables
 // Inicio de preferencias
 // Cabecera de los datos
 datos->append("|->preferencias->");
 // bucle que recorre cada valor
 QStringList::const_iterator iterador;
 for( iterador = claves.constBegin(); iterador != claves.constEnd(); ++iterador )
 {
        if( !_continuar )
        { return false; }
   datos->append( (*iterador).toLocal8Bit().constData() );
   PBProgreso->setValue( PBProgreso->value() + 1 );
   datos->append( "=" );
   // Separador de valores
   QVariant v = p->value( (*iterador), QVariant() );
   QString result;
   switch( v.type() )
   {
        ///////////////////////////////////////////////////////////////////////////
        // Copiado desde la clase qsettings de qt
       case QVariant::Invalid:
       {
            result = QLatin1String("@Invalid()");
            break;
       }

        case QVariant::ByteArray:
        {
            QByteArray a = v.toByteArray();
            result = QLatin1String("@ByteArray(");
            result += QString::fromLatin1(a.constData(), a.size());
            result += QLatin1Char(')');
            break;
        }

        case QVariant::String:
        case QVariant::LongLong:
        case QVariant::ULongLong:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::Bool:
        case QVariant::Double:
        case QVariant::KeySequence: {
            result = v.toString();
            if (result.startsWith(QLatin1Char('@')))
                result.prepend(QLatin1Char('@'));
            break;
        }
        case QVariant::Rect: {
            QRect r = qvariant_cast<QRect>(v);
            result += QLatin1String("@Rect(");
            result += QString::number(r.x());
            result += QLatin1Char(' ');
            result += QString::number(r.y());
            result += QLatin1Char(' ');
            result += QString::number(r.width());
            result += QLatin1Char(' ');
            result += QString::number(r.height());
            result += QLatin1Char(')');
            break;
        }
        case QVariant::Size: {
            QSize s = qvariant_cast<QSize>(v);
            result += QLatin1String("@Size(");
            result += QString::number(s.width());
            result += QLatin1Char(' ');
            result += QString::number(s.height());
            result += QLatin1Char(')');
            break;
        }
        case QVariant::Point: {
            QPoint p = qvariant_cast<QPoint>(v);
            result += QLatin1String("@Point(");
            result += QString::number(p.x());
            result += QLatin1Char(' ');
            result += QString::number(p.y());
            result += QLatin1Char(')');
            break;
        }
        default: {
            QByteArray a;
            {
                QDataStream s(&a, QIODevice::WriteOnly);
                s.setVersion(QDataStream::Qt_4_0);
                s << v;
            }

            result = QLatin1String("@Variant(");
            result += QString::fromLatin1(a.constData(), a.size());
            result += QLatin1Char(')');
            break;
        }
        //////////////////////////////////////////////////////////////////////////////
    }
    datos->append( result );
    PBProgreso->setValue( PBProgreso->value() + 1 );
   // Separador de preferencia
   datos->append( "\n" );
 }
 // fin de los datos
 datos->append("<-preferencias<-|");
 // Comprimo los datos y los envio al buffer de comprimidos
 LDebug->setText( LDebug->text() + "... Comprimiendo.... " );
 comprimir();
 PBProgreso->setValue( PBProgreso->value() + 1 );
 // Limpio el buffer asi se libera la memoria
 LDebug->setText( LDebug->text() + "... Limpiando.... " );
 datos->clear();
 PBProgreso->setValue( PBProgreso->value() + 1 );
 LDebug->setText( "Listo backup de configuracion" );
 return true;
}
Esempio n. 4
0
void TestResultDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);
    // make sure we paint the complete delegate instead of keeping an offset
    opt.rect.adjust(-opt.rect.x(), 0, 0, 0);
    painter->save();

    QFontMetrics fm(opt.font);
    QColor foreground;

    const QAbstractItemView *view = qobject_cast<const QAbstractItemView *>(opt.widget);
    const bool selected = view->selectionModel()->currentIndex() == index;

    if (selected) {
        painter->setBrush(opt.palette.highlight().color());
        foreground = opt.palette.highlightedText().color();
    } else {
        painter->setBrush(opt.palette.background().color());
        foreground = opt.palette.text().color();
    }
    painter->setPen(Qt::NoPen);
    painter->drawRect(opt.rect);
    painter->setPen(foreground);

    TestResultFilterModel *resultFilterModel = static_cast<TestResultFilterModel *>(view->model());
    LayoutPositions positions(opt, resultFilterModel);
    const TestResult &testResult = resultFilterModel->testResult(index);

    // draw the indicator by ourself as we paint across it with the delegate
    QStyleOptionViewItemV4 indicatorOpt = option;
    indicatorOpt.rect = QRect(0, opt.rect.y(), positions.indentation(), opt.rect.height());
    opt.widget->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &indicatorOpt, painter);

    QIcon icon = index.data(Qt::DecorationRole).value<QIcon>();
    if (!icon.isNull())
        painter->drawPixmap(positions.left(), positions.top(),
                            icon.pixmap(positions.iconSize(), positions.iconSize()));

    QString typeStr = TestResult::resultToString(testResult.result());
    if (selected) {
        painter->drawText(positions.typeAreaLeft(), positions.top() + fm.ascent(), typeStr);
    } else {
        QPen tmp = painter->pen();
        painter->setPen(TestResult::colorForType(testResult.result()));
        painter->drawText(positions.typeAreaLeft(), positions.top() + fm.ascent(), typeStr);
        painter->setPen(tmp);
    }

    QString output = outputString(testResult, selected);

    if (selected) {
        output.replace(QLatin1Char('\n'), QChar::LineSeparator);

        if (AutotestPlugin::instance()->settings()->limitResultOutput
                && output.length() > outputLimit)
            output = output.left(outputLimit).append(QLatin1String("..."));

        recalculateTextLayout(index, output, painter->font(), positions.textAreaWidth());

        m_lastCalculatedLayout.draw(painter, QPoint(positions.textAreaLeft(), positions.top()));
    } else {
        painter->setClipRect(positions.textArea());
        // cut output before generating elided text as this takes quite long for exhaustive output
        painter->drawText(positions.textAreaLeft(), positions.top() + fm.ascent(),
                          fm.elidedText(output.left(2000), Qt::ElideRight, positions.textAreaWidth()));
    }

    QString file = testResult.fileName();
    const int pos = file.lastIndexOf(QLatin1Char('/'));
    if (pos != -1)
        file = file.mid(pos + 1);

    painter->setClipRect(positions.fileArea());
    painter->drawText(positions.fileAreaLeft(), positions.top() + fm.ascent(), file);


    if (testResult.line()) {
        QString line = QString::number(testResult.line());
        painter->setClipRect(positions.lineArea());
        painter->drawText(positions.lineAreaLeft(), positions.top() + fm.ascent(), line);
    }

    painter->setClipRect(opt.rect);
    painter->setPen(opt.palette.midlight().color());
    painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
    painter->restore();
}
Esempio n. 5
0
bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode)
{
    Q_D(QFSFileEngine);
    Q_ASSERT(!isReallyOpen());

    openMode |= QIODevice::ReadWrite;

    if (!filePathIsTemplate)
        return QFSFileEngine::open(openMode);

    QString qfilename = d->fileEntry.filePath();

    // Ensure there is a placeholder mask
    uint phPos = qfilename.length();
    uint phLength = 0;

    while (phPos != 0) {
        --phPos;

        if (qfilename[phPos] == QLatin1Char('X')) {
            ++phLength;
            continue;
        }

        if (phLength >= 6
                || qfilename[phPos] == QLatin1Char('/')) {
            ++phPos;
            break;
        }

        // start over
        phLength = 0;
    }

    if (phLength < 6)
        qfilename.append(QLatin1String(".XXXXXX"));

    // "Nativify" :-)
    QFileSystemEntry::NativePath filename = QFileSystemEngine::absoluteName(
            QFileSystemEntry(qfilename, QFileSystemEntry::FromInternalPath()))
        .nativeFilePath();

    // Find mask in native path
    phPos = filename.length();
    phLength = 0;
    while (phPos != 0) {
        --phPos;

        if (filename[phPos] == Latin1Char('X')) {
            ++phLength;
            continue;
        }

        if (phLength >= 6) {
            ++phPos;
            break;
        }

        // start over
        phLength = 0;
    }

    Q_ASSERT(phLength >= 6);

    QSystemError error;
#if defined(Q_OS_WIN)
    NativeFileHandle &file = d->fileHandle;
#elif defined(Q_OS_SYMBIAN)
    NativeFileHandle &file = d->symbianFile;
#else // POSIX
    NativeFileHandle &file = d->fd;
#endif

    if (!createFileFromTemplate(file, filename, phPos, phLength, error)) {
        setError(QFile::OpenError, error.toString());
        return false;
    }

    d->fileEntry = QFileSystemEntry(filename, QFileSystemEntry::FromNativePath());

#if !defined(Q_OS_WIN)
    d->closeFileHandle = true;
#endif

    filePathIsTemplate = false;

    d->openMode = openMode;
    d->lastFlushFailed = false;
    d->tried_stat = 0;

    return true;
}
bool QLinuxFbScreen::connect(const QString &displaySpec)
{
    d_ptr->displaySpec = displaySpec;

    const QStringList args = displaySpec.split(QLatin1Char(':'));

    if (args.contains(QLatin1String("nographicsmodeswitch")))
        d_ptr->doGraphicsMode = false;

#ifdef QT_QWS_DEPTH_GENERIC
    if (args.contains(QLatin1String("genericcolors")))
        d_ptr->doGenericColors = true;
#endif

    QRegExp ttyRegExp(QLatin1String("tty=(.*)"));
    if (args.indexOf(ttyRegExp) != -1)
        d_ptr->ttyDevice = ttyRegExp.cap(1);

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN
    if (args.contains(QLatin1String("littleendian")))
#endif
        QScreen::setFrameBufferLittleEndian(true);
#endif

    QString dev = QLatin1String("/dev/fb0");
    foreach(QString d, args) {
	if (d.startsWith(QLatin1Char('/'))) {
	    dev = d;
	    break;
	}
    }

    if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0)
        d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR);
    if (d_ptr->fd == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QScreenLinuxFb::connect");
            qCritical("Error opening framebuffer device %s", qPrintable(dev));
            return false;
        }
        if (access(dev.toLatin1().constData(), R_OK) == 0)
            d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY);
    }

    ::fb_fix_screeninfo finfo;
    ::fb_var_screeninfo vinfo;
    //#######################
    // Shut up Valgrind
    memset(&vinfo, 0, sizeof(vinfo));
    memset(&finfo, 0, sizeof(finfo));
    //#######################

    /* Get fixed screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading fixed information");
        return false;
    }

    d_ptr->driverType = strcmp(finfo.id, "8TRACKFB") ? GenericDriver : EInk8Track;

    if (finfo.type == FB_TYPE_VGA_PLANES) {
        qWarning("VGA16 video mode not supported");
        return false;
    }

    /* Get variable screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading variable information");
        return false;
    }

    fixupScreenInfo(finfo, vinfo);

    grayscale = vinfo.grayscale;
    d = vinfo.bits_per_pixel;
    if (d == 24) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 24; // reset if color component lengths are not reported
    } else if (d == 16) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 16;
    }
    lstep = finfo.line_length;

    int xoff = vinfo.xoffset;
    int yoff = vinfo.yoffset;
    const char* qwssize;
    if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) {
        if (d_ptr->fd != -1) {
            if ((uint)w > vinfo.xres) w = vinfo.xres;
            if ((uint)h > vinfo.yres) h = vinfo.yres;
        }
        dw=w;
        dh=h;
        int xxoff, yyoff;
        if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) {
            if (xxoff < 0 || xxoff + w > vinfo.xres)
                xxoff = vinfo.xres - w;
            if (yyoff < 0 || yyoff + h > vinfo.yres)
                yyoff = vinfo.yres - h;
            xoff += xxoff;
            yoff += yyoff;
        } else {
            xoff += (vinfo.xres - w)/2;
            yoff += (vinfo.yres - h)/2;
        }
    } else {
        dw=w=vinfo.xres;
        dh=h=vinfo.yres;
    }

    if (w == 0 || h == 0) {
        qWarning("QScreenLinuxFb::connect(): Unable to find screen geometry, "
                 "will use 320x240.");
        dw = w = 320;
        dh = h = 240;
    }

    setPixelFormat(vinfo);

    // Handle display physical size spec.
    QStringList displayArgs = displaySpec.split(QLatin1Char(':'));
    QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)"));
    int dimIdxW = displayArgs.indexOf(mmWidthRx);
    QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)"));
    int dimIdxH = displayArgs.indexOf(mmHeightRx);
    if (dimIdxW >= 0) {
        mmWidthRx.exactMatch(displayArgs.at(dimIdxW));
        physWidth = mmWidthRx.cap(1).toInt();
        if (dimIdxH < 0)
            physHeight = dh*physWidth/dw;
    }
    if (dimIdxH >= 0) {
        mmHeightRx.exactMatch(displayArgs.at(dimIdxH));
        physHeight = mmHeightRx.cap(1).toInt();
        if (dimIdxW < 0)
            physWidth = dw*physHeight/dh;
    }
    if (dimIdxW < 0 && dimIdxH < 0) {
        if (vinfo.width != 0 && vinfo.height != 0
            && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) {
            physWidth = vinfo.width;
            physHeight = vinfo.height;
        } else {
            const int dpi = 72;
            physWidth = qRound(dw * 25.4 / dpi);
            physHeight = qRound(dh * 25.4 / dpi);
        }
    }

    dataoffset = yoff * lstep + xoff * d / 8;
    //qDebug("Using %dx%dx%d screen",w,h,d);

    /* Figure out the size of the screen in bytes */
    size = h * lstep;

    mapsize = finfo.smem_len;

    data = (unsigned char *)-1;
    if (d_ptr->fd != -1)
        data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE,
                                     MAP_SHARED, d_ptr->fd, 0);

    if ((long)data == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error: failed to map framebuffer device to memory.");
            return false;
        }
        data = 0;
    } else {
        data += dataoffset;
    }

    canaccel = useOffscreen();
    if(canaccel)
        setupOffScreen();

    // Now read in palette
    if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) {
        screencols= (vinfo.bits_per_pixel==8) ? 256 : 16;
        int loopc;
        ::fb_cmap startcmap;
        startcmap.start=0;
        startcmap.len=screencols;
        startcmap.red=(unsigned short int *)
                 malloc(sizeof(unsigned short int)*screencols);
        startcmap.green=(unsigned short int *)
                   malloc(sizeof(unsigned short int)*screencols);
        startcmap.blue=(unsigned short int *)
                  malloc(sizeof(unsigned short int)*screencols);
        startcmap.transp=(unsigned short int *)
                    malloc(sizeof(unsigned short int)*screencols);
        if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error reading palette from framebuffer, using default palette");
            createPalette(startcmap, vinfo, finfo);
        }
        int bits_used = 0;
        for(loopc=0;loopc<screencols;loopc++) {
            screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8,
                                   startcmap.green[loopc] >> 8,
                                   startcmap.blue[loopc] >> 8);
            bits_used |= startcmap.red[loopc]
                         | startcmap.green[loopc]
                         | startcmap.blue[loopc];
        }
        // WORKAROUND: Some framebuffer drivers only return 8 bit
        // color values, so we need to not bit shift them..
        if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) {
            for(loopc=0;loopc<screencols;loopc++) {
                screenclut[loopc] = qRgb(startcmap.red[loopc],
                                         startcmap.green[loopc],
                                         startcmap.blue[loopc]);
            }
            qWarning("8 bits cmap returned due to faulty FB driver, colors corrected");
        }
        free(startcmap.red);
        free(startcmap.green);
        free(startcmap.blue);
        free(startcmap.transp);
    } else {
Esempio n. 7
0
void MiamStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const
{
	switch (element) {
#if !defined(Q_OS_OSX)
	case CE_Splitter:
		break;
#endif
	case CE_MenuBarItem:{
		const QStyleOptionMenuItem *somi = static_cast<const QStyleOptionMenuItem*>(option);
		const bool act = somi->state & (State_Sunken | State_Selected);
		QPalette palette = QApplication::palette();
		QBrush brush;
		if (act) {
			painter->setPen(palette.highlight().color());
			brush = palette.highlight().color().lighter();
			painter->setBrush(brush);
			painter->drawRect(option->rect.adjusted(0, 0, -1, -1));
		} else {
			brush = palette.window();
			painter->fillRect(option->rect, palette.window());
		}

		uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
		if (!styleHint(SH_UnderlineShortcut, somi, widget)) {
			alignment |= Qt::TextHideMnemonic;
		}
		if (somi->state.testFlag(QStyle::State_Enabled)) {
			if (SettingsPrivate::instance()->isCustomTextColorOverriden()) {
				if (act) {
					painter->setPen(palette.highlightedText().color());
				} else {
					painter->setPen(palette.text().color());
				}
			} else {
				if (qAbs(palette.text().color().value() - brush.color().value()) < 128) {
					painter->setPen(palette.highlightedText().color());
				} else {
					painter->setPen(palette.text().color());
				}
			}
		} /*else if (act) {
			painter->setPen(palette.mid().color());
		}*/
		painter->drawText(option->rect, alignment, somi->text);
		break;
	}
	case CE_MenuItem:
		if (const QStyleOptionMenuItem *menuitem = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
			QGuiApplication *app = static_cast<QGuiApplication*>(QGuiApplication::instance());
			qreal checkcol = 25 / app->devicePixelRatio();
			qreal gutterWidth = 3 / app->devicePixelRatio();
			QRect rect = option->rect;
			//draw vertical menu line
			if (option->direction == Qt::LeftToRight)
				checkcol += rect.x();
			int x, y, w, h;
			menuitem->rect.getRect(&x, &y, &w, &h);
			int tab = menuitem->tabWidth;
			bool dis = !(menuitem->state & State_Enabled);
			bool checked = menuitem->checkType != QStyleOptionMenuItem::NotCheckable ? menuitem->checked : false;
			bool act = menuitem->state & State_Selected;
			QPalette palette = QApplication::palette();
			if (menuitem->menuItemType == QStyleOptionMenuItem::Separator) {
				int yoff = y - 1 + h / 2;
				qreal separatorSize = 6 / app->devicePixelRatio();
				QPoint p1 = QPoint(x + checkcol, yoff);
				QPoint p2 = QPoint(x + w + separatorSize, yoff);
				painter->save();
				painter->fillRect(menuitem->rect, palette.window());
				painter->setPen(palette.mid().color());
				painter->drawLine(p1, p2);
				painter->restore();
				return;
			}
			QString s = menuitem->text;
			QBrush fill;
			if (act) {
				fill = palette.highlight().color().lighter();
			} else {
				fill = palette.window();
			}
			painter->fillRect(menuitem->rect, fill);
			QRect vCheckRect = visualRect(option->direction, menuitem->rect, QRect(menuitem->rect.x(),
																				   menuitem->rect.y(), checkcol - (gutterWidth + menuitem->rect.x()), menuitem->rect.height()));
			if (checked) {
				QStyleOptionMenuItem newMi = *menuitem;
				int windowsItemFrame = 2;
				newMi.rect = visualRect(option->direction,
										menuitem->rect,
										QRect(menuitem->rect.x() + windowsItemFrame,
											  menuitem->rect.y() + windowsItemFrame,
											  checkcol - 2 * windowsItemFrame,
											  menuitem->rect.height() - 2 * windowsItemFrame)
										);
				painter->setRenderHint(QPainter::Antialiasing, true);
				proxy()->drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, painter, widget);
				painter->setRenderHint(QPainter::Antialiasing, false);
			}
			if (!menuitem->icon.isNull()) {
				QIcon::Mode mode = dis ? QIcon::Disabled : QIcon::Normal;
				if (act && !dis) {
					mode = QIcon::Active;
				}
				QPixmap pixmap;
				if (checked) {
					pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode, QIcon::On);
				} else {
					pixmap = menuitem->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize, option, widget), mode);
				}
				const int pixw = pixmap.width() / pixmap.devicePixelRatio();
				const int pixh = pixmap.height() / pixmap.devicePixelRatio();
				QRect pmr(0, 0, pixw, pixh);
				pmr.moveCenter(vCheckRect.center());
				painter->setPen(palette.text().color());
				painter->drawPixmap(pmr.topLeft(), pixmap);
			}
			//painter->setPen(palette.buttonText().color());
			QColor textColor = palette.text().color();
			if (dis) {
				textColor = palette.mid().color();
				painter->setPen(textColor);
			} else if (act && SettingsPrivate::instance()->isCustomTextColorOverriden()) {
				textColor = palette.highlightedText().color();
				painter->setPen(textColor);
			}
			int xm = checkcol + 2 + (gutterWidth - menuitem->rect.x()) - 1;
			int xpos = menuitem->rect.x() + xm;

			///
			int windowsItemVMargin = 3, windowsRightBorder = 3;
			QRect textRect(xpos, y + windowsItemVMargin, w - xm - windowsRightBorder - tab + 1, h - 2 * windowsItemVMargin);
			QRect vTextRect = visualRect(option->direction, menuitem->rect, textRect);
			if (!s.isEmpty()) {    // draw text
				painter->save();
				int t = s.indexOf(QLatin1Char('\t'));
				int text_flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
				if (!proxy()->styleHint(SH_UnderlineShortcut, menuitem, widget)) {
					text_flags |= Qt::TextHideMnemonic;
				}
				text_flags |= Qt::AlignLeft;
				if (t >= 0) {
					QRect vShortcutRect = visualRect(option->direction, menuitem->rect,
													 QRect(textRect.topRight(), QPoint(menuitem->rect.right(), textRect.bottom())));
					painter->drawText(vShortcutRect, text_flags, s.mid(t + 1));
					s = s.left(t);
				}
				QFont font = menuitem->font;
				if (menuitem->menuItemType == QStyleOptionMenuItem::DefaultItem) {
					font.setBold(true);
				}
				painter->setFont(font);
				painter->setPen(textColor);
				painter->drawText(vTextRect, text_flags, s.left(t));
				painter->restore();
			}
			if (menuitem->menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
				int dim = (h - 2 * 5) / 2;
				PrimitiveElement arrow;
				arrow = (option->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
				xpos = x + w - 2 - 2 - dim;
				QRect  vSubMenuRect = visualRect(option->direction, menuitem->rect, QRect(xpos, y + h / 2 - dim / 2, dim, dim));
				QStyleOptionMenuItem newMI = *menuitem;
				newMI.rect = vSubMenuRect;
				newMI.state = dis ? State_None : State_Enabled;
				proxy()->drawPrimitive(arrow, &newMI, painter, widget);
			}

		}
		break;
	case CE_MenuBarEmptyArea:{
		painter->fillRect(option->rect, QApplication::palette().window());
		break;
	}
	default:
		QProxyStyle::drawControl(element, option, painter, widget);
	}
}
Esempio n. 8
0
void QSvgText::draw(QPainter *p, QSvgExtraStates &states)
{
    applyStyle(p, states);
    qreal oldOpacity = p->opacity();
    p->setOpacity(oldOpacity * states.fillOpacity);

    // Force the font to have a size of 100 pixels to avoid truncation problems
    // when the font is very small.
    qreal scale = 100.0 / p->font().pointSizeF();
    Qt::Alignment alignment = states.textAnchor;

    QTransform oldTransform = p->worldTransform();
    p->scale(1 / scale, 1 / scale);

    qreal y = 0;
    bool initial = true;
    qreal px = m_coord.x() * scale;
    qreal py = m_coord.y() * scale;
    QSizeF scaledSize = m_size * scale;

    if (m_type == TEXTAREA) {
        if (alignment == Qt::AlignHCenter)
            px += scaledSize.width() / 2;
        else if (alignment == Qt::AlignRight)
            px += scaledSize.width();
    }

    QRectF bounds;
    if (m_size.height() != 0)
        bounds = QRectF(0, py, 1, scaledSize.height()); // x and width are not used.

    bool appendSpace = false;
    QVector<QString> paragraphs;
    QStack<QTextCharFormat> formats;
    QVector<QList<QTextLayout::FormatRange> > formatRanges;
    paragraphs.push_back(QString());
    formatRanges.push_back(QList<QTextLayout::FormatRange>());

    for (int i = 0; i < m_tspans.size(); ++i) {
        if (m_tspans[i] == LINEBREAK) {
            if (m_type == TEXTAREA) {
                if (paragraphs.back().isEmpty()) {
                    QFont font = p->font();
                    font.setPixelSize(font.pointSizeF() * scale);

                    QTextLayout::FormatRange range;
                    range.start = 0;
                    range.length = 1;
                    range.format.setFont(font);
                    formatRanges.back().append(range);

                    paragraphs.back().append(QLatin1Char(' '));;
                }
                appendSpace = false;
                paragraphs.push_back(QString());
                formatRanges.push_back(QList<QTextLayout::FormatRange>());
            }
        } else {
            WhitespaceMode mode = m_tspans[i]->whitespaceMode();
            m_tspans[i]->applyStyle(p, states);

            QFont font = p->font();
            font.setPixelSize(font.pointSizeF() * scale);

            QString newText(m_tspans[i]->text());
            newText.replace(QLatin1Char('\t'), QLatin1Char(' '));
            newText.replace(QLatin1Char('\n'), QLatin1Char(' '));

            bool prependSpace = !appendSpace && !m_tspans[i]->isTspan() && (mode == Default) && !paragraphs.back().isEmpty() && newText.startsWith(QLatin1Char(' '));
            if (appendSpace || prependSpace)
                paragraphs.back().append(QLatin1Char(' '));

            bool appendSpaceNext = (!m_tspans[i]->isTspan() && (mode == Default) && newText.endsWith(QLatin1Char(' ')));

            if (mode == Default) {
                newText = newText.simplified();
                if (newText.isEmpty())
                    appendSpaceNext = false;
            }

            QTextLayout::FormatRange range;
            range.start = paragraphs.back().length();
            range.length = newText.length();
            range.format.setFont(font);
            range.format.setTextOutline(p->pen());
            range.format.setForeground(p->brush());

            if (appendSpace) {
                Q_ASSERT(!formatRanges.back().isEmpty());
                ++formatRanges.back().back().length;
            } else if (prependSpace) {
                --range.start;
                ++range.length;
            }
            formatRanges.back().append(range);

            appendSpace = appendSpaceNext;
            paragraphs.back() += newText;

            m_tspans[i]->revertStyle(p, states);
        }
    }

    if (states.svgFont) {
        // SVG fonts not fully supported...
        QString text = paragraphs.front();
        for (int i = 1; i < paragraphs.size(); ++i) {
            text.append(QLatin1Char('\n'));
            text.append(paragraphs[i]);
        }
        states.svgFont->draw(p, m_coord * scale, text, p->font().pointSizeF() * scale, states.textAnchor);
    } else {
        for (int i = 0; i < paragraphs.size(); ++i) {
            QTextLayout tl(paragraphs[i]);
            QTextOption op = tl.textOption();
            op.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
            tl.setTextOption(op);
            tl.setAdditionalFormats(formatRanges[i]);
            tl.beginLayout();

            forever {
                QTextLine line = tl.createLine();
                if (!line.isValid())
                    break;
                if (m_size.width() != 0)
                    line.setLineWidth(scaledSize.width());
            }
            tl.endLayout();

            bool endOfBoundsReached = false;
            for (int i = 0; i < tl.lineCount(); ++i) {
                QTextLine line = tl.lineAt(i);

                qreal x = 0;
                if (alignment == Qt::AlignHCenter)
                    x -= 0.5 * line.naturalTextWidth();
                else if (alignment == Qt::AlignRight)
                    x -= line.naturalTextWidth();

                if (initial && m_type == TEXT)
                    y -= line.ascent();
                initial = false;

                line.setPosition(QPointF(x, y));

                // Check if the current line fits into the bounding rectangle.
                if ((m_size.width() != 0 && line.naturalTextWidth() > scaledSize.width())
                    || (m_size.height() != 0 && y + line.height() > scaledSize.height())) {
                    // I need to set the bounds height to 'y-epsilon' to avoid drawing the current
                    // line. Since the font is scaled to 100 units, 1 should be a safe epsilon.
                    bounds.setHeight(y - 1);
                    endOfBoundsReached = true;
                    break;
                }

                y += 1.1 * line.height();
            }
            tl.draw(p, QPointF(px, py), QVector<QTextLayout::FormatRange>(), bounds);

            if (endOfBoundsReached)
                break;
        }
    }

    p->setWorldTransform(oldTransform, false);
    p->setOpacity(oldOpacity);
    revertStyle(p, states);
}
Esempio n. 9
0
void widget::initializeGL() {
    std::ios_base::sync_with_stdio(false); // turns off sync between C and C++ output streams(to increase output speed)

    initializeOpenGLFunctions();
    ogllogger.initialize();
    QObject::connect(&ogllogger, &QOpenGLDebugLogger::messageLogged, [](const QOpenGLDebugMessage & msg){
        qDebug() << msg;
    });
    ogllogger.startLogging();

    GLint iUnits, texture_units, max_tu;
    glGetIntegerv(GL_MAX_TEXTURE_UNITS, &iUnits);
    glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &texture_units);
    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_tu);
    std::cout << "MultiTexture: " << iUnits << ' ' << texture_units << ' ' << max_tu << std::endl;

    glEnable(GL_TEXTURE_3D);
    // glEnable(GL_DEPTH_TEST);
    // glDepthFunc(GL_LEQUAL);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

    std::vector<char> data;
    // ------- load raw data -------
    layers.emplace_back();
    layers.back().opacity = 1.0f;

    {
        data.resize(std::pow(cpucubeedge, 3));
        std::fill(std::begin(data), std::end(data), 0);
        layers.back().bogusCube.reset(new gpu_raw_cube(gpucubeedge));
        boost::multi_array_ref<std::uint8_t, 3> cube(reinterpret_cast<std::uint8_t*>(data.data()), boost::extents[cpucubeedge][cpucubeedge][cpucubeedge]);
        using range = boost::multi_array_types::index_range;
        layers.back().bogusCube->generate(cube[boost::indices[range(0,gpucubeedge)][range(cpucubeedge-gpucubeedge,cpucubeedge-0)][range(0,gpucubeedge)]]);
    }

    const auto factor = cpucubeedge / gpucubeedge;
    const QString basePath("D:/New folder/cubes/2012-03-07_AreaX14_mag1_x%1_y%2_z%3.raw");
    offset = {29, 46, 23};
    for (int z = 0; z < supercubeedge; z += factor)
    for (int y = 0; y < supercubeedge; y += factor)
    for (int x = 0; x < supercubeedge; x += factor) {
        const int cubex = offset.x() + x / factor;
        const int cubey = offset.y() + y / factor;
        const int cubez = offset.z() + z / factor;
        std::string path = basePath.arg(cubex, 4, 10, QLatin1Char('0')).arg(cubey, 4, 10, QLatin1Char('0')).arg(cubez, 4, 10, QLatin1Char('0')).toStdString();

        std::ifstream file(path, std::ios_base::binary);
        data.resize(std::pow(cpucubeedge, 3));
        if (file) {
            file.read(data.data(), data.size());
        } else {
            std::cout << path << " failed" << std::endl;
            continue;
        }

        boost::multi_array_ref<std::uint8_t, 3> cube(reinterpret_cast<std::uint8_t*>(data.data()), boost::extents[cpucubeedge][cpucubeedge][cpucubeedge]);
        for (int zi = z; zi < z + factor; ++zi)
        for (int yi = y; yi < y + factor; ++yi)
        for (int xi = x; xi < x + factor; ++xi) {
            const auto x_offset = gpucubeedge * (xi % factor);
            const auto y_offset = gpucubeedge * (yi % factor);
            const auto z_offset = gpucubeedge * (zi % factor);
            using range = boost::multi_array_types::index_range;
            const auto view = cube[boost::indices[range(0+z_offset,gpucubeedge+z_offset)][range(0+y_offset,gpucubeedge+y_offset)][range(0+x_offset,gpucubeedge+x_offset)]];
            layers.back().textures[QVector3D(xi, yi, zi)].reset(new gpu_raw_cube(gpucubeedge));
            static_cast<gpu_raw_cube*>(layers.back().textures[QVector3D(xi, yi, zi)].get())->generate(view);
        }
    }

    // ------- load overlay data -------
    layers.emplace_back();
    layers.back().opacity = 0.5f;
    layers.back().isOverlayData = true;

    {
        data.resize(std::pow(cpucubeedge, 3) * 8);
        std::fill(std::begin(data), std::end(data), 0);
        layers.back().bogusCube.reset(new gpu_lut_cube(gpucubeedge));
        boost::multi_array_ref<std::uint64_t, 3> cube(reinterpret_cast<std::uint64_t*>(data.data()), boost::extents[cpucubeedge][cpucubeedge][cpucubeedge]);
        using range = boost::multi_array_types::index_range;
        static_cast<gpu_lut_cube*>(layers.back().bogusCube.get())->generate(cube[boost::indices[range(0,gpucubeedge)][range(cpucubeedge-gpucubeedge,cpucubeedge-0)][range(0,gpucubeedge)]]);
    }

    for (int z = 0; z < supercubeedge; z += factor)
    for (int y = 0; y < supercubeedge; y += factor)
    for (int x = 0; x < supercubeedge; x += factor) {
        const int cubex = offset.x() + x / factor;
        const int cubey = offset.y() + y / factor;
        const int cubez = offset.z() + z / factor;
        std::string path = basePath.arg(cubex, 4, 10, QLatin1Char('0')).arg(cubey, 4, 10, QLatin1Char('0')).arg(cubez, 4, 10, QLatin1Char('0')).toStdString() + ".segmentation.raw";
        std::ifstream file(path, std::ios_base::binary);
        data.resize(std::pow(cpucubeedge, 3)*8);
        if (file) {
            file.read(data.data(), data.size());
        } else {
            std::cout << path << " failed" << std::endl;
            continue;
        }

        boost::multi_array_ref<std::uint64_t, 3> cube(reinterpret_cast<std::uint64_t*>(data.data()), boost::extents[cpucubeedge][cpucubeedge][cpucubeedge]);
        for (int zi = z; zi < z + factor; ++zi)
        for (int yi = y; yi < y + factor; ++yi)
        for (int xi = x; xi < x + factor; ++xi) {
            const auto x_offset = gpucubeedge * (xi % factor);
            const auto y_offset = gpucubeedge * (yi % factor);
            const auto z_offset = gpucubeedge * (zi % factor);
            using range = boost::multi_array_types::index_range;
            const auto view = cube[boost::indices[range(0+z_offset,gpucubeedge+z_offset)][range(0+y_offset,gpucubeedge+y_offset)][range(0+x_offset,gpucubeedge+x_offset)]];
            layers.back().textures[QVector3D(xi, yi, zi)].reset(new gpu_lut_cube(gpucubeedge));
            static_cast<gpu_lut_cube*>(layers.back().textures[QVector3D(xi, yi, zi)].get())->generate(view);
        }
    }

    auto vertex_shader_code = R"shaderSource(
    #version 110
    uniform mat4 model_matrix;
    uniform mat4 view_matrix;
    uniform mat4 projection_matrix;
    attribute vec3 vertex;
    attribute vec3 texCoordVertex;
    varying vec3 texCoordFrag;
    void main() {
        mat4 mvp_mat = projection_matrix * view_matrix * model_matrix;
        gl_Position = mvp_mat * vec4(vertex, 1.0);
        texCoordFrag = texCoordVertex;
    })shaderSource";

    raw_data_shader.addShaderFromSourceCode(QOpenGLShader::Vertex, vertex_shader_code);
    raw_data_shader.addShaderFromSourceCode(QOpenGLShader::Fragment, R"shaderSource(
    #version 110
    uniform float textureOpacity;
    uniform sampler3D texture;
    varying vec3 texCoordFrag;//in
    //varying vec4 gl_FragColor;//out
    void main() {
        gl_FragColor = vec4(vec3(texture3D(texture, texCoordFrag).r), textureOpacity);
    })shaderSource");
Esempio n. 10
0
CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn)
{
    QString type = typeIn;
    if (type.startsWith("class ")) // MSVC prepends class,struct
        type.remove(0, 6);
    if (type.startsWith("struct "))
        type.remove(0, 7);

    type.replace(QLatin1Char('*'), QLatin1Char('@'));

    for (int i = 0; i < 10; ++i) {
        int start = type.indexOf("std::allocator<");
        if (start == -1)
            break;
        // search for matching '>'
        int pos;
        int level = 0;
        for (pos = start + 12; pos < type.size(); ++pos) {
            int c = type.at(pos).unicode();
            if (c == '<') {
                ++level;
            } else if (c == '>') {
                --level;
                if (level == 0)
                    break;
            }
        }
        const QString alloc = fixNestedTemplates(type.mid(start, pos + 1 - start).trimmed());
        const QString inner = fixNestedTemplates(alloc.mid(15, alloc.size() - 16).trimmed());
        const QString allocEsc = QRegExp::escape(alloc);
        const QString innerEsc = QRegExp::escape(inner);
        if (inner == QLatin1String("char")) { // std::string
            simplifyStdString(QLatin1String("char"), QLatin1String("string"), &type);
        } else if (inner == QLatin1String("wchar_t")) { // std::wstring
            simplifyStdString(QLatin1String("wchar_t"), QLatin1String("wstring"), &type);
        } else if (inner == QLatin1String("unsigned short")) { // std::wstring/MSVC
            simplifyStdString(QLatin1String("unsigned short"), QLatin1String("wstring"), &type);
        }
        // std::vector, std::deque, std::list
        QRegExp re1(QString::fromLatin1("(vector|list|deque)<%1, ?%2\\s*>").arg(innerEsc, allocEsc));
        QTC_ASSERT(re1.isValid(), return typeIn);
        if (re1.indexIn(type) != -1)
            type.replace(re1.cap(0), QString::fromLatin1("%1<%2>").arg(re1.cap(1), inner));

        // std::stack
        QRegExp stackRE(QString::fromLatin1("stack<%1, ?std::deque<%2> >").arg(innerEsc, innerEsc));
        stackRE.setMinimal(true);
        QTC_ASSERT(stackRE.isValid(), return typeIn);
        if (stackRE.indexIn(type) != -1)
            type.replace(stackRE.cap(0), QString::fromLatin1("stack<%1>").arg(inner));

        // std::set
        QRegExp setRE(QString::fromLatin1("set<%1, ?std::less<%2>, ?%3\\s*>").arg(innerEsc, innerEsc, allocEsc));
        setRE.setMinimal(true);
        QTC_ASSERT(setRE.isValid(), return typeIn);
        if (setRE.indexIn(type) != -1)
            type.replace(setRE.cap(0), QString::fromLatin1("set<%1>").arg(inner));

        // std::map
        if (inner.startsWith("std::pair<")) {
            // search for outermost ',', split key and value
            int pos;
            int level = 0;
            for (pos = 10; pos < inner.size(); ++pos) {
                int c = inner.at(pos).unicode();
                if (c == '<')
                    ++level;
                else if (c == '>')
                    --level;
                else if (c == ',' && level == 0)
                    break;
            }
            const QString key = chopConst(inner.mid(10, pos - 10));
            const QString keyEsc = QRegExp::escape(key);
            // Get value: MSVC: 'pair<a const ,b>', gcc: 'pair<const a, b>'
            if (inner.at(++pos) == QLatin1Char(' '))
                pos++;
            const QString value = inner.mid(pos, inner.size() - pos - 1).trimmed();
            const QString valueEsc = QRegExp::escape(value);
            QRegExp mapRE1(QString("map<%1, ?%2, ?std::less<%3 ?>, ?%4\\s*>")
                .arg(keyEsc, valueEsc, keyEsc, allocEsc));
            mapRE1.setMinimal(true);
            QTC_ASSERT(mapRE1.isValid(), return typeIn);
            if (mapRE1.indexIn(type) != -1) {
                type.replace(mapRE1.cap(0), QString("map<%1, %2>").arg(key, value));
            } else {
                QRegExp mapRE2(QString("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>")
                    .arg(keyEsc, valueEsc, keyEsc, allocEsc));
                mapRE2.setMinimal(true);
                if (mapRE2.indexIn(type) != -1) {
                    type.replace(mapRE2.cap(0), QString("map<const %1, %2>").arg(key, value));
                }
            }
        }
    }
Esempio n. 11
0
QList<QNetworkCookie> QNetworkCookiePrivate::parseSetCookieHeaderLine(const QByteArray &cookieString)
{
    // According to http://wp.netscape.com/newsref/std/cookie_spec.html,<
    // the Set-Cookie response header is of the format:
    //
    //   Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
    //
    // where only the NAME=VALUE part is mandatory
    //
    // We do not support RFC 2965 Set-Cookie2-style cookies

    QList<QNetworkCookie> result;
    QDateTime now = QDateTime::currentDateTime().toUTC();

    int position = 0;
    const int length = cookieString.length();
    while (position < length) {
        QNetworkCookie cookie;

        // The first part is always the "NAME=VALUE" part
        QPair<QByteArray,QByteArray> field = nextField(cookieString, position, true);
        if (field.first.isEmpty())
            // parsing error
            break;
        cookie.setName(field.first);
        cookie.setValue(field.second);

        position = nextNonWhitespace(cookieString, position);
        while (position < length) {
            switch (cookieString.at(position++)) {
            case ';':
                // new field in the cookie
                field = nextField(cookieString, position, false);
                field.first = field.first.toLower(); // everything but the NAME=VALUE is case-insensitive

                if (field.first == "expires") {
                    position -= field.second.length();
                    int end;
                    for (end = position; end < length; ++end)
                        if (isValueSeparator(cookieString.at(end)))
                            break;

                    QByteArray dateString = cookieString.mid(position, end - position).trimmed();
                    position = end;
                    QDateTime dt = parseDateString(dateString.toLower());
                    if (dt.isValid())
                        cookie.setExpirationDate(dt);
                    //if unparsed, ignore the attribute but not the whole cookie (RFC6265 section 5.2.1)
                } else if (field.first == "domain") {
                    QByteArray rawDomain = field.second;
                    //empty domain should be ignored (RFC6265 section 5.2.3)
                    if (!rawDomain.isEmpty()) {
                        QString maybeLeadingDot;
                        if (rawDomain.startsWith('.')) {
                            maybeLeadingDot = QLatin1Char('.');
                            rawDomain = rawDomain.mid(1);
                        }

                        //IDN domains are required by RFC6265, accepting utf8 as well doesn't break any test cases.
                        QString normalizedDomain = QUrl::fromAce(QUrl::toAce(QString::fromUtf8(rawDomain)));
                        if (!normalizedDomain.isEmpty()) {
                            cookie.setDomain(maybeLeadingDot + normalizedDomain);
                        } else {
                            //Normalization fails for malformed domains, e.g. "..example.org", reject the cookie now
                            //rather than accepting it but never sending it due to domain match failure, as the
                            //strict reading of RFC6265 would indicate.
                            return result;
                        }
                    }
                } else if (field.first == "max-age") {
                    bool ok = false;
                    int secs = field.second.toInt(&ok);
                    if (ok) {
                        if (secs <= 0) {
                            //earliest representable time (RFC6265 section 5.2.2)
                            cookie.setExpirationDate(QDateTime::fromTime_t(0));
                        } else {
                            cookie.setExpirationDate(now.addSecs(secs));
                        }
                    }
                    //if unparsed, ignore the attribute but not the whole cookie (RFC6265 section 5.2.2)
                } else if (field.first == "path") {
                    if (field.second.startsWith('/')) {
                        // ### we should treat cookie paths as an octet sequence internally
                        // However RFC6265 says we should assume UTF-8 for presentation as a string
                        cookie.setPath(QString::fromUtf8(field.second));
                    } else {
                        // if the path doesn't start with '/' then set the default path (RFC6265 section 5.2.4)
                        // and also IETF test case path0030 which has valid and empty path in the same cookie
                        cookie.setPath(QString());
                    }
                } else if (field.first == "secure") {
                    cookie.setSecure(true);
                } else if (field.first == "httponly") {
                    cookie.setHttpOnly(true);
                } else {
                    // ignore unknown fields in the cookie (RFC6265 section 5.2, rule 6)
                }

                position = nextNonWhitespace(cookieString, position);
            }
        }

        if (!cookie.name().isEmpty())
            result += cookie;
    }

    return result;
}
Esempio n. 12
0
            }
            const QString key = chopConst(inner.mid(10, pos - 10));
            const QString keyEsc = QRegExp::escape(key);
            // Get value: MSVC: 'pair<a const ,b>', gcc: 'pair<const a, b>'
            if (inner.at(++pos) == QLatin1Char(' '))
                pos++;
            const QString value = inner.mid(pos, inner.size() - pos - 1).trimmed();
            const QString valueEsc = QRegExp::escape(value);
            QRegExp mapRE1(QString("map<%1, ?%2, ?std::less<%3 ?>, ?%4\\s*>")
                .arg(keyEsc, valueEsc, keyEsc, allocEsc));
            mapRE1.setMinimal(true);
            QTC_ASSERT(mapRE1.isValid(), return typeIn);
            if (mapRE1.indexIn(type) != -1) {
                type.replace(mapRE1.cap(0), QString("map<%1, %2>").arg(key, value));
            } else {
                QRegExp mapRE2(QString("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>")
                    .arg(keyEsc, valueEsc, keyEsc, allocEsc));
                mapRE2.setMinimal(true);
                if (mapRE2.indexIn(type) != -1) {
                    type.replace(mapRE2.cap(0), QString("map<const %1, %2>").arg(key, value));
                }
            }
        }
    }
    type.replace(QLatin1Char('@'), QLatin1Char('*'));
    type.replace(QLatin1String(" >"), QLatin1String(">"));
    return type;
}

} // namespace CPlusPlus
Esempio n. 13
0
void QStaticTextPrivate::paintText(const QPointF &topLeftPosition, QPainter *p)
{
    bool preferRichText = textFormat == Qt::RichText
                          || (textFormat == Qt::AutoText && Qt::mightBeRichText(text));

    if (!preferRichText) {
        QTextLayout textLayout;
        textLayout.setText(text);
        textLayout.setFont(font);
        textLayout.setTextOption(textOption);

        qreal leading = QFontMetricsF(font).leading();
        qreal height = -leading;

        textLayout.beginLayout();
        while (1) {
            QTextLine line = textLayout.createLine();
            if (!line.isValid())
                break;

            if (textWidth >= 0.0)
                line.setLineWidth(textWidth);
            height += leading;
            line.setPosition(QPointF(0.0, height));
            height += line.height();
        }
        textLayout.endLayout();

        actualSize = textLayout.boundingRect().size();
        textLayout.draw(p, topLeftPosition);
    } else {
        QTextDocument document;
#ifndef QT_NO_CSSPARSER
        QColor color = p->pen().color();
        document.setDefaultStyleSheet(QString::fromLatin1("body { color: #%1%2%3 }")
                                      .arg(QString::number(color.red(), 16), 2, QLatin1Char('0'))
                                      .arg(QString::number(color.green(), 16), 2, QLatin1Char('0'))
                                      .arg(QString::number(color.blue(), 16), 2, QLatin1Char('0')));
#endif
        document.setDefaultFont(font);
        document.setDocumentMargin(0.0);        
#ifndef QT_NO_TEXTHTMLPARSER
        document.setHtml(text);
#else
        document.setPlainText(text);
#endif
        if (textWidth >= 0.0)
            document.setTextWidth(textWidth);
        else
            document.adjustSize();
        document.setDefaultTextOption(textOption);

        p->save();
        p->translate(topLeftPosition);
        QAbstractTextDocumentLayout::PaintContext ctx;
        ctx.palette.setColor(QPalette::Text, p->pen().color());
        document.documentLayout()->draw(p, ctx);
        p->restore();

        if (textWidth >= 0.0)
            document.adjustSize(); // Find optimal size

        actualSize = document.size();
    }
}
QString createFullLocationString(const Debugger::DiagnosticLocation &location)
{
    const QString filePath = location.filePath;
    const QString lineNumber = QString::number(location.line);
    return filePath + QLatin1Char(':') + lineNumber;
}
int Recognizer::nextToken()
{
  QString text;

 Lagain:
  while (ch.isSpace ())
    inp ();
  
  if (ch.isNull ())
    return EOF_SYMBOL;

  int token = ch.unicode ();

  if (token == '"')
    {
      inp(); // skip "
      text.clear ();
      while (! ch.isNull () && ch != QLatin1Char ('"'))
        {
          if (ch == QLatin1Char ('\\'))
            {
              text += ch;
              inp();
            }
          text += ch;
          inp ();
        }

      if (ch == QLatin1Char ('"'))
        inp ();
      else
        qerr << _M_input_file << ":" << _M_line << ": Warning. Expected `\"'" << endl;

      _M_current_value = text;
      return (token = STRING_LITERAL);
    }

  else if (ch.isLetterOrNumber () || ch == QLatin1Char ('_'))
    {
      text.clear ();
      do { text += ch; inp (); }
      while (ch.isLetterOrNumber () || ch == QLatin1Char ('_') || ch == QLatin1Char ('.'));
      _M_current_value = text;
      return (token = ID);
    }

  else if (token == '%')
    {
      text.clear ();

      do { inp (); }
      while (ch.isSpace ());

      do { text += ch; inp (); }
      while (ch.isLetterOrNumber () || ch == QLatin1Char ('_') || ch == QLatin1Char ('-'));

      if (text == QLatin1String("token_prefix"))
        return (token = TOKEN_PREFIX);
      else if (text == QLatin1String("merged_output"))
        return (token = MERGED_OUTPUT);
      else if (text == QLatin1String("token"))
        return (token = TOKEN);
      else if (text == QLatin1String("start"))
        return (token = START);
      else if (text == QLatin1String("parser"))
        return (token = PARSER);
      else if (text == QLatin1String("decl"))
        return (token = DECL_FILE);
      else if (text == QLatin1String("impl"))
        return (token = IMPL_FILE);
      else if (text == QLatin1String("expect"))
        return (token = EXPECT);
      else if (text == QLatin1String("expect-rr"))
        return (token = EXPECT_RR);
      else if (text == QLatin1String("left"))
        return (token = LEFT);
      else if (text == QLatin1String("right"))
        return (token = RIGHT);
      else if (text == QLatin1String("nonassoc"))
        return (token = NONASSOC);
      else if (text == QLatin1String("prec"))
        return (token = PREC);
      else
        {
          qerr << _M_input_file << ":" << _M_line << ": Unknown keyword `" << text << "'" << endl;
          exit (EXIT_FAILURE);
          return (token = ERROR);
        }
    }

  inp ();

  if (token == '-' && ch == QLatin1Char ('-'))
    {
      do { inp (); }
      while (! ch.isNull () && ch != QLatin1Char ('\n'));
      goto Lagain;
    }

  else if (token == ':' && ch == QLatin1Char (':'))
    {
      inp ();
      if (ch != QLatin1Char ('='))
        return (token = ERROR);
      inp ();
      return (token = COLON);
    }

  else if (token == '/' && ch == QLatin1Char (':'))
    {
      _M_action_line = _M_line;

      text.clear ();
      if (! _M_no_lines)
        text += QLatin1String ("\n#line ") + QString::number (_M_action_line) + " \"" + _M_input_file + "\"\n";
      inp (); // skip ':'

      forever
        {
          while (! ch.isNull ())
            {
              token = ch.unicode ();
              inp ();

              if (token == ':' && ch == QLatin1Char ('/'))
                break;

              text += QLatin1Char (token);
            }

          if (ch != QLatin1Char ('/'))
            return (token = ERROR);

          inp ();

          if (ch.isNull () || ch.isSpace ())
            {
              _M_current_value = text;
              return (token = DECL);
            }
	  else
	    text += QLatin1String (":/");
        }
    }
 PropertySheetPixmapValue::PixmapSource PropertySheetPixmapValue::getPixmapSource(QDesignerFormEditorInterface *core, const QString & path)
 {
     if (const QDesignerLanguageExtension *lang = qt_extension<QDesignerLanguageExtension *>(core->extensionManager(), core))
         return lang->isLanguageResource(path) ?  LanguageResourcePixmap : FilePixmap;
     return path.startsWith(QLatin1Char(':')) ? ResourcePixmap : FilePixmap;
 }
Esempio n. 17
0
NewClassWidgetPrivate:: NewClassWidgetPrivate() :
    m_headerExtension(QLatin1Char('h')),
    m_sourceExtension(QLatin1String("cpp")),
    m_formExtension(QLatin1String("ui"))
{
}
Esempio n. 18
0
QString FaceTagsHelper::tagPath(const QString& name, int parentId)
{
    QString faceParentTagName = TagsCache::instance()->tagName(parentId);
    return faceParentTagName + QLatin1Char('/') + name;
}
Esempio n. 19
0
int main(int argc, char **argv)
{
    Common::registerMetaTypes();

    QApplication app(argc, argv);

    Q_INIT_RESOURCE(icons);
    Q_INIT_RESOURCE(license);

    QTranslator qtTranslator;
    qtTranslator.load(QLatin1String("qt_") + QLocale::system().name(),
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    QLatin1String localeSuffix("/locale");
    QString localeName(QLatin1String("trojita_common_") +
                       (qgetenv("KDE_LANG") == "x-test" ? QStringLiteral("x_test") : QLocale::system().name()));

    // The "installed to system" localization
    QTranslator appSystemTranslator;
    if (!Gui::Util::pkgDataDir().isEmpty()) {
        appSystemTranslator.load(localeName, Gui::Util::pkgDataDir() + localeSuffix);
        app.installTranslator(&appSystemTranslator);
    }

    // The "in the directory with the binary" localization
    QTranslator appDirectoryTranslator;
    appDirectoryTranslator.load(localeName, app.applicationDirPath() + localeSuffix);
    app.installTranslator(&appDirectoryTranslator);

    AppVersion::setGitVersion();
    AppVersion::setCoreApplicationData();

    app.setWindowIcon(UiUtils::loadIcon(QStringLiteral("trojita")));

    QTextStream qOut(stdout, QIODevice::WriteOnly);
    QTextStream qErr(stderr, QIODevice::WriteOnly);

    const QStringList &arguments = app.arguments();

    bool error = false;
    bool showHelp = false;
    bool showMainWindow = false;
    bool showComposeWindow = false;
    bool showAddressbookWindow = false;
    bool logToDisk = false;

    QString profileName;

    QString url;

    for (int i = 1; i < arguments.size(); ++i) {
        const QString &arg = arguments.at(i);

        if (arg.startsWith(QLatin1Char('-'))) {
            if (arg == QLatin1String("-m") || arg == QLatin1String("--mainwindow")) {
                showMainWindow = true;
            } else if (arg == QLatin1String("-a") || arg == QLatin1String("--addressbook")) {
                showAddressbookWindow = true;
            } else if (arg == QLatin1String("-c") || arg == QLatin1String("--compose")) {
                showComposeWindow = true;
            } else if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
                showHelp = true;
            } else if (arg == QLatin1String("-p") || arg == QLatin1String("--profile")) {
                if (i+1 == arguments.size() || arguments.at(i+1).startsWith(QLatin1Char('-'))) {
                    qErr << QObject::tr("Error: Profile was not specified") << endl;
                    error = true;
                    break;
                } else if (!profileName.isEmpty()) {
                    qErr << QObject::tr("Error: Duplicate profile option '%1'").arg(arg) << endl;
                    error = true;
                    break;
                } else {
                    profileName = arguments.at(i+1);
                    ++i;
                }
            } else if (arg == QLatin1String("--log-to-disk")) {
                logToDisk = true;
            } else {
                qErr << QObject::tr("Warning: Unknown option '%1'").arg(arg) << endl;
            }
        } else {
            if (!url.isEmpty() || !arg.startsWith(QLatin1String("mailto:"))) {
                qErr << QObject::tr("Warning: Unexpected argument '%1'").arg(arg) << endl;
            } else {
                url = arg;
                showComposeWindow = true;
            }
        }
    }

    if (!showMainWindow && !showComposeWindow && !showAddressbookWindow)
        showMainWindow = true;

    if (error)
        showHelp = true;

    if (showHelp) {
        qOut << endl << QObject::trUtf8(
            "Usage: %1 [options] [url]\n"
            "\n"
            "Trojitá %2 - fast Qt IMAP e-mail client\n"
            "\n"
            "Options:\n"
            "  -h, --help               Show this help\n"
            "  -m, --mainwindow         Show main window (default when no option is provided)\n"
            "  -a, --addressbook        Show addressbook window\n"
            "  -c, --compose            Compose new email (default when url is provided)\n"
            "  -p, --profile <profile>  Set profile (cannot start with char '-')\n"
            "  --log-to-disk            Activate debug traffic logging to disk by default\n"
            "\n"
            "Arguments:\n"
            "  url                      Mailto: url address for composing new email\n"
        ).arg(arguments.at(0), Common::Application::version) << endl;
        return error ? 1 : 0;
    }

    // Hack: support multiple "profiles"
    if (!profileName.isEmpty()) {
        // We are abusing the env vars here. Yes, it's a hidden global. Yes, it's ugly.
        // Take it or leave it, this is a time-limited hack.
        // The env var is also in UTF-8. I like UTF-8.
        qputenv("TROJITA_PROFILE", profileName.toUtf8());
    } else {
#ifndef Q_OS_WIN32
        unsetenv("TROJITA_PROFILE");
#else
        putenv("TROJITA_PROFILE=");
#endif
    }

    if (IPC::Instance::isRunning()) {
        if (showMainWindow)
            IPC::Instance::showMainWindow();
        if (showAddressbookWindow)
            IPC::Instance::showAddressbookWindow();
        if (showComposeWindow)
            IPC::Instance::composeMail(url);
        return 0;
    }

    QSettings settings(Common::Application::organization,
                       profileName.isEmpty() ? Common::Application::name : Common::Application::name + QLatin1Char('-') + profileName);
    Gui::MainWindow win(&settings);

    QString errmsg;
    if (!IPC::registerInstance(&win, errmsg))
        qErr << QObject::tr("Error: Registering IPC instance failed: %1").arg(errmsg) << endl;

    if ( settings.value(Common::SettingsNames::guiStartMinimized, QVariant(false)).toBool() ) {
        if ( !settings.value(Common::SettingsNames::guiShowSystray, QVariant(true)).toBool() ) {
            win.show();
            win.setWindowState(Qt::WindowMinimized);
        }
    } else {
        win.show();
    }

    if (showAddressbookWindow)
        win.invokeContactEditor();

    if (showComposeWindow) {
        if (url.isEmpty())
            win.slotComposeMail();
        else
            win.slotComposeMailUrl(QUrl::fromEncoded(url.toUtf8()));
    }

    if (logToDisk) {
        win.enableLoggingToDisk();
    }

    return app.exec();
}
Esempio n. 20
0
const QString TestResult::outputString(bool selected) const
{
    return selected ? m_description : m_description.split(QLatin1Char('\n')).first();
}
Esempio n. 21
0
bool isActivationChar(const QChar &c)
{
    if (c == QLatin1Char('(') || c == QLatin1Char('.') || c == QLatin1Char('/'))
        return true;
    return false;
}
bool QmakeAndroidBuildApkStep::init(QList<const BuildStep *> &earlierSteps)
{
    if (AndroidManager::checkForQt51Files(project()->projectDirectory()))
        emit addOutput(tr("Found old folder \"android\" in source directory. Qt 5.2 does not use that folder by default."), ErrorOutput);

    if (!AndroidBuildApkStep::init(earlierSteps))
        return false;

    QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
    if (!version)
        return false;

    QString command = version->qmakeProperty("QT_HOST_BINS");
    if (!command.endsWith(QLatin1Char('/')))
        command += QLatin1Char('/');
    command += QLatin1String("androiddeployqt");
    if (Utils::HostOsInfo::isWindowsHost())
        command += QLatin1String(".exe");

    QString deploymentMethod;
    if (m_deployAction == MinistroDeployment)
        deploymentMethod = QLatin1String("ministro");
    else if (m_deployAction == DebugDeployment)
        deploymentMethod = QLatin1String("debug");
    else if (m_deployAction == BundleLibrariesDeployment)
        deploymentMethod = QLatin1String("bundled");

    ProjectExplorer::BuildConfiguration *bc = buildConfiguration();
    QString outputDir = bc->buildDirectory().appendPath(QLatin1String(Constants::ANDROID_BUILDDIRECTORY)).toString();

    const auto *pro = static_cast<QmakeProjectManager::QmakeProject *>(project());
    const QmakeProjectManager::QmakeProFileNode *node = pro->rootProjectNode()->findProFileFor(proFilePathForInputFile());
    m_skipBuilding = !node;
    if (m_skipBuilding)
        return true;

    QString inputFile = node->singleVariableValue(QmakeProjectManager::AndroidDeploySettingsFile);
    if (inputFile.isEmpty()) {
        m_skipBuilding = true;
        return true;
    }

    QStringList arguments;
    arguments << QLatin1String("--input")
              << inputFile
              << QLatin1String("--output")
              << outputDir
              << QLatin1String("--deployment")
              << deploymentMethod
              << QLatin1String("--android-platform")
              << AndroidManager::buildTargetSDK(target())
              << QLatin1String("--jdk")
              << AndroidConfigurations::currentConfig().openJDKLocation().toString();

    if (m_verbose)
        arguments << QLatin1String("--verbose");

    if (m_useGradle)
        arguments << QLatin1String("--gradle");
    else
        arguments << QLatin1String("--ant")
                  << AndroidConfigurations::currentConfig().antToolPath().toString();


    QStringList argumentsPasswordConcealed = arguments;

    if (version->qtVersion() >= QtSupport::QtVersionNumber(5, 6, 0)) {
        if (bc->buildType() == ProjectExplorer::BuildConfiguration::Debug)
            arguments << QLatin1String("--gdbserver");
        else
            arguments << QLatin1String("--no-gdbserver");
    }

    if (m_signPackage) {
        arguments << QLatin1String("--sign")
                  << m_keystorePath.toString()
                  << m_certificateAlias
                  << QLatin1String("--storepass")
                  << m_keystorePasswd;
        argumentsPasswordConcealed << QLatin1String("--sign") << QLatin1String("******")
                                   << QLatin1String("--storepass") << QLatin1String("******");
        if (!m_certificatePasswd.isEmpty()) {
            arguments << QLatin1String("--keypass")
                      << m_certificatePasswd;
            argumentsPasswordConcealed << QLatin1String("--keypass")
                      << QLatin1String("******");
        }

    }

    ProjectExplorer::ProcessParameters *pp = processParameters();
    setupProcessParameters(pp, bc, arguments, command);

    // Generate arguments with keystore password concealed
    ProjectExplorer::ProcessParameters pp2;
    setupProcessParameters(&pp2, bc, argumentsPasswordConcealed, command);
    m_command = pp2.effectiveCommand();
    m_argumentsPasswordConcealed = pp2.prettyArguments();

    return true;
}
Esempio n. 23
0
bool readSettingsFromCommandLine(int argc, char *argv[],
                  Settings& config)
{
    bool builtWithOpenGL = false;
    Settings::Options options;

#ifndef QT_NO_OPENGL
    builtWithOpenGL = true;
#endif
    for (int i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "-manual") == 0) {
            options |= Settings::ManualTest;
            argv[i] = 0;
            break;
        }
    }

    for (int i = 1; i < argc; ++i) {
        if (!argv[i])
            continue;
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0) {
            usage(argv[0]);
            return true;
        }
        if (strcmp(argv[i], "-opengl") == 0) {
            if (builtWithOpenGL) {
                options |= Settings::UseOpenGL;
                argv[i] = 0;
            } else {
                printf("-opengl parameter can be used only with building PRECONDITIONS: QT_NO_OPENGL is off.\n");
                usage(argv[0]);
                return false;
            }
        } else if (strcmp(argv[i], "-resolution") == 0) {
            if (i + 1 >= argc) {
                printf("-resolution needs an extra parameter specifying the application UI resolution\n");
                usage(argv[0]);
                return false;
            }
            else {
                QStringList res = QString(argv[i+1]).split(QLatin1Char('x'));
                if (res.count() != 2) {
                    printf("-resolution parameter UI resolution should be set in format WxH where width and height are positive values\n");
                    usage(argv[0]);
                    return false;
                }
                int width = res.at(0).toInt();
                int height = res.at(1).toInt();

                config.setSize(QSize(width, height));

                if (width <=0 || height <=0) {
                    printf("-resolution parameter UI resolution should be set in format WxH where width and height are positive values\n");
                    usage(argv[0]);
                    return false;
                }
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        }

        if (!argv[i])
            continue;

        if (!(options & Settings::ManualTest)) {
            if (argumentOnlyAvailableInManualMode(argv[i])) {
                printf("\nWrong option: '%s' is only available in manual mode\n\n", argv[i]);
                usage(argv[0]);
                return false;
            }
            continue;
        }

        if (strcmp(argv[i], "-rotation") == 0) {
            if (i + 1 >= argc) {
                printf("-rotation needs an extra parameter specifying the application UI rotation in degrees\n");
                usage(argv[0]);
                return false;
            }
            else {
                bool ok;
                int angle = QString(argv[i+1]).toInt(&ok);
                if (!ok) {
                    printf("-rotation parameter should specify rotation angle in degrees\n");
                    usage(argv[0]);
                    return false;
                }
                config.setAngle(angle);
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        } else if (strcmp(argv[i], "-subtree-cache") == 0) {
            options |= Settings::UseListItemCache;
            argv[i] = 0;
        } else if (strcmp(argv[i], "-fps") == 0) {
             options |= Settings::OutputFps;
             argv[i] = 0;
        } else if (strcmp(argv[i], "-items") == 0) {
            if (i + 1 >= argc) {
                printf("-items needs an extra parameter specifying amount of list items\n");
                usage(argv[0]);
                return false;
            }
            else {
                bool ok;
                int amount = QString(argv[i+1]).toInt(&ok);
                if (!ok) {
                    printf("-items needs an extra parameter specifying amount (integer) of list items\n");
                    usage(argv[0]);
                    return false;
                }
                config.setListItemCount(amount);
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        }
    }

    config.setOptions(options);

    return true;
}
Esempio n. 24
0
QList<ProjectExplorer::ToolChain *> RvctToolChainFactory::autoDetect()
{
    Utils::Environment env = Utils::Environment::systemEnvironment();

    QMap<QString, QList<Utils::EnvironmentItem> > rvcts;
    QList<Utils::EnvironmentItem> globalItems;

    // Find all RVCT..x variables
    for (Utils::Environment::const_iterator i = env.constBegin(); i != env.constEnd(); ++i) {
        if (i.key() == QLatin1String(RVCT_LICENSE_KEY))
            globalItems.append(Utils::EnvironmentItem(i.key(), i.value()));
        if (!i.key().startsWith(QLatin1String("RVCT")))
            continue;

        const QString key = i.key().left(6);
        QList<Utils::EnvironmentItem> values = rvcts.value(key);

        values.append(Utils::EnvironmentItem(i.key(), i.value()));

        rvcts.insert(key, values);
    }

    // Set up toolchains for each RVCT.. set
    QList<ProjectExplorer::ToolChain *> result;
    for (QMap<QString, QList<Utils::EnvironmentItem> >::const_iterator i = rvcts.constBegin();
         i != rvcts.constEnd(); ++i) {
        QList<Utils::EnvironmentItem> changes = i.value();
        changes.append(globalItems);

        QString binary = QDir::fromNativeSeparators(valueOf(changes, QLatin1String("BIN")));
        if (binary.isEmpty())
            continue;
        binary = binary + QLatin1Char('/') + RVCT_BINARY;
        QFileInfo fi(binary);
        if (!fi.exists() || !fi.isExecutable())
            continue;

        RvctToolChain::RvctVersion v = RvctToolChain::version(binary);
        if (v.majorVersion == 0 && v.minorVersion == 0 && v.build == 0)
            continue; // Failed to start.

        //: %1 arm version, %2 major version, %3 minor version, %4 build number
        const QString name = tr("RVCT (%1 %2.%3 Build %4)");

        RvctToolChain *tc = new RvctToolChain(true);
        tc->setCompilerPath(binary);
        tc->setEnvironmentChanges(changes);
        tc->setDisplayName(name.arg(armVersionString(tc->armVersion()))
                           .arg(v.majorVersion).arg(v.minorVersion).arg(v.build));
        tc->setVersion(v);
        result.append(tc);

        tc = new RvctToolChain(true);
        tc->setCompilerPath(binary);
        tc->setEnvironmentChanges(changes);
        tc->setArmVersion(RvctToolChain::ARMv6);
        tc->setDisplayName(name.arg(armVersionString(tc->armVersion()))
                           .arg(v.majorVersion).arg(v.minorVersion).arg(v.build));
        tc->setVersion(v);
        result.append(tc);
    }

    return result;
}
Esempio n. 25
0
void QmlOutputParser::processOutput(const QString &output)
{
    m_buffer.append(output);

    while (true) {
        const int nlIndex = m_buffer.indexOf(QLatin1Char('\n'));
        if (nlIndex < 0) // no further complete lines
            break;

        const QString msg = m_buffer.left(nlIndex);
        m_buffer = m_buffer.right(m_buffer.size() - nlIndex - 1);

        // used in Qt4
        static const QString qddserver4 = QLatin1String("QDeclarativeDebugServer: ");
        // used in Qt5
        static const QString qddserver5 = QLatin1String("QML Debugger: ");

        QString status;
        int index = msg.indexOf(qddserver4);
        if (index != -1) {
            status = msg;
            status.remove(0, index + qddserver4.length()); // chop of 'QDeclarativeDebugServer: '
        } else {
            index = msg.indexOf(qddserver5);
            if (index != -1) {
                status = msg;
                status.remove(0, index + qddserver5.length()); // chop of 'QML Debugger: '
            }
        }
        if (!status.isEmpty()) {
            static QString waitingForConnection = QLatin1String(Constants::STR_WAITING_FOR_CONNECTION);
            static QString unableToListen = QLatin1String(Constants::STR_UNABLE_TO_LISTEN);
            static QString debuggingNotEnabled = QLatin1String(Constants::STR_IGNORING_DEBUGGER);
            static QString debuggingNotEnabled2 = QLatin1String(Constants::STR_IGNORING_DEBUGGER2);
            static QString connectionEstablished = QLatin1String(Constants::STR_CONNECTION_ESTABLISHED);

            if (status.startsWith(waitingForConnection)) {
                status.remove(0, waitingForConnection.size()); // chop of 'Waiting for connection '

                static QRegExp waitingTcp(
                            QString::fromLatin1(Constants::STR_ON_PORT_PATTERN));
                if (waitingTcp.indexIn(status) > -1) {
                    bool canConvert;
                    quint16 port = waitingTcp.cap(1).toUShort(&canConvert);
                    if (canConvert)
                        emit waitingForConnectionOnPort(port);
                    continue;
                }

                static QString waitingOst
                        = QLatin1String(Constants::STR_VIA_OST);
                if (status.startsWith(waitingOst))
                    emit waitingForConnectionViaOst();
            } else if (status.startsWith(unableToListen)) {
                //: Error message shown after 'Could not connect ... debugger:"
                emit errorMessage(tr("The port seems to be in use."));
            } else if (status.startsWith(debuggingNotEnabled) || status.startsWith(debuggingNotEnabled2)) {
                //: Error message shown after 'Could not connect ... debugger:"
                emit errorMessage(tr("The application is not set up for QML/JS debugging."));
            } else if (status.startsWith(connectionEstablished)) {
                emit connectionEstablishedMessage();
            } else {
                emit unknownMessage(status);
            }
        } else if (msg.contains(m_noOutputText)) {
            emit noOutputMessage();
        }


    }
}
bool QDeclarativeDirParser::parse()
{
    if (_isParsed)
        return true;

    _isParsed = true;
    _errors.clear();
    _plugins.clear();
    _components.clear();

    QTextStream stream(&_source);
    int lineNumber = 0;

    forever {
        ++lineNumber;

        const QString line = stream.readLine();
        if (line.isNull())
            break;

        QString sections[3];
        int sectionCount = 0;

        int index = 0;
        const int length = line.length();

        while (index != length) {
            const QChar ch = line.at(index);

            if (ch.isSpace()) {
                do { ++index; }
                while (index != length && line.at(index).isSpace());

            } else if (ch == QLatin1Char('#')) {
                // recognized a comment
                break;

            } else {
                const int start = index;

                do { ++index; }
                while (index != length && !line.at(index).isSpace());

                const QString lexeme = line.mid(start, index - start);

                if (sectionCount >= 3) {
                    reportError(lineNumber, start, QLatin1String("unexpected token"));

                } else {
                    sections[sectionCount++] = lexeme;
                }
            }
        }

        if (sectionCount == 0) {
            continue; // no sections, no party.

        } else if (sections[0] == QLatin1String("plugin")) {
            if (sectionCount < 2) {
                reportError(lineNumber, -1,
                            QString::fromUtf8("plugin directive requires 2 arguments, but %1 were provided").arg(sectionCount + 1));

                continue;
            }

            const Plugin entry(sections[1], sections[2]);

            _plugins.append(entry);

        } else if (sections[0] == QLatin1String("internal")) {
            if (sectionCount != 3) {
                reportError(lineNumber, -1,
                            QString::fromUtf8("internal types require 2 arguments, but %1 were provided").arg(sectionCount + 1));
                continue;
            }
            Component entry(sections[1], sections[2], -1, -1);
            entry.internal = true;
            _components.append(entry);

        } else if (sectionCount == 2) {
            // No version specified (should only be used for relative qmldir files)
            const Component entry(sections[0], sections[1], -1, -1);
            _components.append(entry);
        } else if (sectionCount == 3) {
            const QString &version = sections[1];
            const int dotIndex = version.indexOf(QLatin1Char('.'));

            if (dotIndex == -1) {
                reportError(lineNumber, -1, QLatin1String("expected '.'"));
            } else if (version.indexOf(QLatin1Char('.'), dotIndex + 1) != -1) {
                reportError(lineNumber, -1, QLatin1String("unexpected '.'"));
            } else {
                bool validVersionNumber = false;
                const int majorVersion = version.left(dotIndex).toInt(&validVersionNumber);

                if (validVersionNumber) {
                    const int minorVersion = version.mid(dotIndex + 1).toInt(&validVersionNumber);

                    if (validVersionNumber) {
                        const Component entry(sections[0], sections[2], majorVersion, minorVersion);

                        _components.append(entry);
                    }
                }
            }
        } else {
            reportError(lineNumber, -1, 
                        QString::fromUtf8("a component declaration requires 3 arguments, but %1 were provided").arg(sectionCount + 1));
        }
    }

    return hasError();
}
bool QTextHtmlImporter::appendNodeText()
{
    const int initialCursorPosition = cursor.position();
    QTextCharFormat format = currentNode->charFormat;

    if(wsm == QTextHtmlParserNode::WhiteSpacePre || wsm == QTextHtmlParserNode::WhiteSpacePreWrap)
        compressNextWhitespace = PreserveWhiteSpace;

    QString text = currentNode->text;

    QString textToInsert;
    textToInsert.reserve(text.size());

    for (int i = 0; i < text.length(); ++i) {
        QChar ch = text.at(i);

        if (ch.isSpace()
            && ch != QChar::Nbsp
            && ch != QChar::ParagraphSeparator) {

            if (compressNextWhitespace == CollapseWhiteSpace)
                compressNextWhitespace = RemoveWhiteSpace; // allow this one, and remove the ones coming next.
            else if(compressNextWhitespace == RemoveWhiteSpace)
                continue;

            if (wsm == QTextHtmlParserNode::WhiteSpacePre
                || textEditMode
               ) {
                if (ch == QLatin1Char('\n')) {
                    if (textEditMode)
                        continue;
                } else if (ch == QLatin1Char('\r')) {
                    continue;
                }
            } else if (wsm != QTextHtmlParserNode::WhiteSpacePreWrap) {
                compressNextWhitespace = RemoveWhiteSpace;
                if (wsm == QTextHtmlParserNode::WhiteSpaceNoWrap)
                    ch = QChar::Nbsp;
                else
                    ch = QLatin1Char(' ');
            }
        } else {
            compressNextWhitespace = PreserveWhiteSpace;
        }

        if (ch == QLatin1Char('\n')
            || ch == QChar::ParagraphSeparator) {

            if (!textToInsert.isEmpty()) {
                cursor.insertText(textToInsert, format);
                textToInsert.clear();
            }

            QTextBlockFormat fmt = cursor.blockFormat();

            if (fmt.hasProperty(QTextFormat::BlockBottomMargin)) {
                QTextBlockFormat tmp = fmt;
                tmp.clearProperty(QTextFormat::BlockBottomMargin);
                cursor.setBlockFormat(tmp);
            }

            fmt.clearProperty(QTextFormat::BlockTopMargin);
            appendBlock(fmt, cursor.charFormat());
        } else {
            if (!namedAnchors.isEmpty()) {
                if (!textToInsert.isEmpty()) {
                    cursor.insertText(textToInsert, format);
                    textToInsert.clear();
                }

                format.setAnchor(true);
                format.setAnchorNames(namedAnchors);
                cursor.insertText(ch, format);
                namedAnchors.clear();
                format.clearProperty(QTextFormat::IsAnchor);
                format.clearProperty(QTextFormat::AnchorName);
            } else {
                textToInsert += ch;
            }
        }
    }

    if (!textToInsert.isEmpty()) {
        cursor.insertText(textToInsert, format);
    }

    return cursor.position() != initialCursorPosition;
}
CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
                                                      bool/* resolveTarget*/, bool /*inNextSplit*/)
{
    Link link;

    int lineNumber = 0, positionInBlock = 0;
    convertPosition(cursor.position(), &lineNumber, &positionInBlock);

    const QString block = cursor.block().text();

    // check if the current position is commented out
    const int hashPos = block.indexOf(QLatin1Char('#'));
    if (hashPos >= 0 && hashPos < positionInBlock)
        return link;

    // find the beginning of a filename
    QString buffer;
    int beginPos = positionInBlock - 1;
    while (beginPos >= 0) {
        QChar c = block.at(beginPos);
        if (isValidFileNameChar(c)) {
            buffer.prepend(c);
            beginPos--;
        } else {
            break;
        }
    }

    // find the end of a filename
    int endPos = positionInBlock;
    while (endPos < block.count()) {
        QChar c = block.at(endPos);
        if (isValidFileNameChar(c)) {
            buffer.append(c);
            endPos++;
        } else {
            break;
        }
    }

    if (buffer.isEmpty())
        return link;

    // TODO: Resolve variables

    QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
    QString fileName = dir.filePath(buffer);
    QFileInfo fi(fileName);
    if (fi.exists()) {
        if (fi.isDir()) {
            QDir subDir(fi.absoluteFilePath());
            QString subProject = subDir.filePath(QLatin1String("CMakeLists.txt"));
            if (QFileInfo::exists(subProject))
                fileName = subProject;
            else
                return link;
        }
        link.targetFileName = fileName;
        link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1;
        link.linkTextEnd = cursor.position() - positionInBlock + endPos;
    }
    return link;
}
Esempio n. 29
0
/*!
  Converts the log \a log to its textual representation and returns
  a QByteArray containing the data.
*/
QByteArray TLogger::logToByteArray(const TLog &log, const QByteArray &layout, const QByteArray &dateTimeFormat, QTextCodec *codec)
{
    QByteArray message;
    message.reserve(layout.length() + log.message.length() + 100);

    int pos = 0;
    while (pos < layout.length()) {
        char c = layout.at(pos++);
        if (c != '%') {
            message.append(c);
            continue;
        }

        QByteArray dig;
        for (;;) {
            if (pos >= layout.length()) {
                message.append('%').append(dig);
                break;
            }

            c = layout.at(pos++);
            if (c >= '0' && c <= '9') {
                dig += c;
                continue;
            }

            if (c == 'd') {  // %d : timestamp
                if (!dateTimeFormat.isEmpty()) {
                    message.append(log.timestamp.toString(dateTimeFormat).toLatin1());
                } else {
                    message.append(log.timestamp.toString(Qt::ISODate).toLatin1());
                }
            } else if (c == 'p' || c == 'P') {  // %p or %P : priority
                QByteArray pri = priorityToString((TLogger::Priority)log.priority);
                if (c == 'p') {
                    pri = pri.toLower();
                }
                if (!pri.isEmpty()) {
                    message.append(pri);
                    int d = dig.toInt() - pri.length();
                    if (d > 0) {
                        message.append(QByteArray(d, ' '));
                    }
                }

            } else if (c == 't' || c == 'T') {  // %t or %T : thread ID (dec or hex)
                QChar fillChar = (dig.length() > 0 && dig[0] == '0') ? QLatin1Char('0') : QLatin1Char(' ');
                message.append(QString("%1").arg((qulonglong)log.threadId, dig.toInt(), ((c == 't') ? 10 : 16), fillChar).toLatin1());

            } else if (c == 'i' || c == 'I') {  // %i or %I : PID (dec or hex)
                QChar fillChar = (dig.length() > 0 && dig[0] == '0') ? QLatin1Char('0') : QLatin1Char(' ');
                message.append(QString("%1").arg(log.pid, dig.toInt(), ((c == 'i') ? 10 : 16), fillChar).toLatin1());

            } else if (c == 'n') {  // %n : newline
                message.append('\n');
            } else if (c == 'm') {  // %m : message
                message.append(log.message);
            } else if (c == '%') {
                message.append('%').append(dig);
                dig.clear();
                continue;
            } else {
                message.append('%').append(dig).append(c);
            }
            break;
        }
    }

    return (codec) ? codec->fromUnicode(QString::fromLocal8Bit(message.data(), message.length())) : message;
}
Esempio n. 30
0
/*!
 * Read out a widget within a category. This can either be
 * enclosed in a <ui> element or a (legacy) <widget> element which may
 * contain nested <widget> elements.
 *
 * Examples:
 *
 * <ui language="c++">
 *  <widget class="MultiPageWidget" name="multipagewidget"> ... </widget>
 *  <customwidgets>...</customwidgets>
 * <ui>
 *
 * or
 *
 * <widget>
 *   <widget> ... </widget>
 *   ...
 * <widget>
 *
 * Returns true on success, false if end was reached or an error has been encountered
 * in which case the reader has its error flag set. If successful, the current item
 * of the reader will be the closing element (</ui> or </widget>)
 */
bool WidgetBoxTreeWidget::readWidget(Widget *w, const QString &xml, QXmlStreamReader &r)
{
    qint64 startTagPosition =0, endTagPosition = 0;

    int nesting = 0;
    bool endEncountered = false;
    bool parsedWidgetTag = false;
    QString outmostElement;
    while (!endEncountered) {
        const qint64 currentPosition = r.characterOffset();
        switch(r.readNext()) {
        case QXmlStreamReader::StartElement:
            if (nesting++ == 0) {
                // First element must be <ui> or (legacy) <widget>
                const QStringRef name = r.name();
                if (name == QLatin1String(uiElementC)) {
                    startTagPosition = currentPosition;
                } else {
                    if (name == QLatin1String(widgetElementC)) {
                        startTagPosition = currentPosition;
                        parsedWidgetTag = true;
                    } else {
                        r.raiseError(QDesignerWidgetBox::tr("Unexpected element <%1> encountered when parsing for <widget> or <ui>").arg(name.toString()));
                        return false;
                    }
                }
            } else {
                // We are within <ui> looking for the first <widget> tag
                if (!parsedWidgetTag && r.name() == QLatin1String(widgetElementC)) {
                    parsedWidgetTag = true;
                }
            }
            break;
        case QXmlStreamReader::EndElement:
            // Reached end of widget?
            if (--nesting == 0)  {
                endTagPosition = r.characterOffset();
                endEncountered = true;
            }
            break;
        case QXmlStreamReader::EndDocument:
            r.raiseError(QDesignerWidgetBox::tr("Unexpected end of file encountered when parsing widgets."));
            return false;
        case QXmlStreamReader::Invalid:
            return false;
        default:
            break;
        }
    }
    if (!parsedWidgetTag) {
        r.raiseError(QDesignerWidgetBox::tr("A widget element could not be found."));
        return false;
    }
    // Oddity: Startposition is 1 off
    QString widgetXml = xml.mid(startTagPosition, endTagPosition - startTagPosition);
    const QChar lessThan = QLatin1Char('<');
    if (!widgetXml.startsWith(lessThan))
        widgetXml.prepend(lessThan);
    w->setDomXml(widgetXml);
    return true;
}