void AssemblyGraph::buildDeBruijnGraphFromFastg(QString fullFileName)
{
    m_graphFileType = FASTG;

    QFile inputFile(fullFileName);
    if (inputFile.open(QIODevice::ReadOnly))
    {
        std::vector<QString> edgeStartingNodeNames;
        std::vector<QString> edgeEndingNodeNames;
        DeBruijnNode * node = 0;

        QTextStream in(&inputFile);
        while (!in.atEnd())
        {
            QApplication::processEvents();

            QString nodeName;
            double nodeReadDepth;

            QString line = in.readLine();

            //If the line starts with a '>', then we are beginning a new node.
            if (line.startsWith(">"))
            {
                line.remove(0, 1); //Remove '>' from start
                line.chop(1); //Remove ';' from end
                QStringList nodeDetails = line.split(":");

                QString thisNode = nodeDetails.at(0);

                //A single quote as the last character indicates a negative node.
                bool negativeNode = thisNode.at(thisNode.size() - 1) == '\'';

                QStringList thisNodeDetails = thisNode.split("_");

                if (thisNodeDetails.size() < 6)
                    throw "load error";

                nodeName = thisNodeDetails.at(1);
                if (negativeNode)
                    nodeName += "-";
                else
                    nodeName += "+";

                QString nodeReadDepthString = thisNodeDetails.at(5);
                if (negativeNode)
                {
                    //It may be necessary to remove a single quote from the end of the read depth
                    if (nodeReadDepthString.at(nodeReadDepthString.size() - 1) == '\'')
                        nodeReadDepthString.chop(1);
                }
                nodeReadDepth = nodeReadDepthString.toDouble();

                //Make the node
                node = new DeBruijnNode(nodeName, nodeReadDepth, ""); //Sequence string is currently empty - will be added to on subsequent lines of the fastg file
                m_deBruijnGraphNodes.insert(nodeName, node);

                //The second part of nodeDetails is a comma-delimited list of edge nodes.
                //Edges aren't made right now (because the other node might not yet exist),
                //so they are saved into vectors and made after all the nodes have been made.
                if (nodeDetails.size() == 1)
                    continue;
                QStringList edgeNodes = nodeDetails.at(1).split(",");
                for (int i = 0; i < edgeNodes.size(); ++i)
                {
                    QString edgeNode = edgeNodes.at(i);

                    QChar lastChar = edgeNode.at(edgeNode.size() - 1);
                    bool negativeNode = false;
                    if (lastChar == '\'')
                    {
                        negativeNode = true;
                        edgeNode.chop(1);
                    }
                    QStringList edgeNodeDetails = edgeNode.split("_");

                    if (edgeNodeDetails.size() < 2)
                        throw "load error";

                    QString edgeNodeName = edgeNodeDetails.at(1);
                    if (negativeNode)
                        edgeNodeName += "-";
                    else
                        edgeNodeName += "+";

                    edgeStartingNodeNames.push_back(nodeName);
                    edgeEndingNodeNames.push_back(edgeNodeName);
                }
            }

            //If the line does not start with a '>', then this line is part of the
            //sequence for the last node.
            else
            {
                QByteArray sequenceLine = line.simplified().toLocal8Bit();
                if (node != 0)
                    node->appendToSequence(sequenceLine);
            }
        }

        inputFile.close();

        //If all went well, each node will have a reverse complement and the code
        //will never get here.  However, I have noticed that some SPAdes fastg files
        //have, for some reason, negative nodes with no positive counterpart.  For
        //that reason, we will now make any reverse complement nodes for nodes that
        //lack them.
        QMapIterator<QString, DeBruijnNode*> i(m_deBruijnGraphNodes);
        while (i.hasNext())
        {
            i.next();
            DeBruijnNode * node = i.value();
            makeReverseComplementNodeIfNecessary(node);
        }
        pointEachNodeToItsReverseComplement();


        //Create all of the edges
        for (size_t i = 0; i < edgeStartingNodeNames.size(); ++i)
        {
            QString node1Name = edgeStartingNodeNames[i];
            QString node2Name = edgeEndingNodeNames[i];
            createDeBruijnEdge(node1Name, node2Name);
        }
    }

    autoDetermineAllEdgesExactOverlap();

    if (m_deBruijnGraphNodes.size() == 0)
        throw "load error";
}
Пример #2
0
void WordsGraphicsHandler::processFloatingPictureFrame(const MSO::OfficeArtSpContainer& o, DrawingWriter& out)
{
    debugMsDoc ;

    const MSO::OfficeArtDggContainer *dgg = 0;
#ifdef USE_OFFICEARTDGG_CONTAINER
    dgg = &m_officeArtDggContainer;
#endif
    DrawStyle ds(dgg, 0, &o);

    // A value of 0x00000000 MUST be ignored.  [MS-ODRAW] — v20101219
    if (!ds.pib()) return;

    QString styleName;
    KoGenStyle style(KoGenStyle::GraphicAutoStyle, "graphic");
    style.setAutoStyleInStylesDotXml(out.stylesxml);

    DrawClient drawclient(this);
    ODrawToOdf odrawtoodf(drawclient);
    odrawtoodf.defineGraphicProperties(style, ds, out.styles);
    definePositionAttributes(style, ds);
    defineWrappingAttributes(style, ds);
    styleName = out.styles.insert(style);

    out.xml.startElement("draw:frame");
    out.xml.addAttribute("draw:style-name", styleName);
    setAnchorTypeAttribute(out);
    setZIndexAttribute(out);

    out.xml.addAttribute("svg:width", mm(out.hLength()));
    out.xml.addAttribute("svg:height", mm(out.vLength()));
    out.xml.addAttribute("svg:x", mm(out.hOffset()));
    out.xml.addAttribute("svg:y", mm(out.vOffset()));

    QString url = getPicturePath(ds.pib());

    //if the image cannot be found, just place an empty frame
    if (url.isEmpty()) {
        out.xml.endElement(); //draw:frame
        return;
    }
    out.xml.startElement("draw:image");
    out.xml.addAttribute("xlink:href", url);
    out.xml.addAttribute("xlink:type", "simple");
    out.xml.addAttribute("xlink:show", "embed");
    out.xml.addAttribute("xlink:actuate", "onLoad");
    out.xml.endElement(); //draw:image

    //check for user edited wrap points
#if 0
    if (ds.fEditedWrap()) {
        QString points;
        IMsoArray _v = ds.pWrapPolygonVertices_complex();
        if (_v.data.size()) {
            //_v.data is an array of POINTs, MS-ODRAW, page 89
            QByteArray a, a2;
            int* p;

            for (int i = 0, offset = 0; i < _v.nElems; i++, offset += _v.cbElem) {
                // x coordinate of this point
                a = _v.data.mid(offset, _v.cbElem);
                a2 = a.mid(0, _v.cbElem / 2);
                p = (int*) a2.data();
                points.append(QString::number(twipsToPt(*p), 'f'));
                points.append(",");
                // y coordinate of this point
                a2 = a.mid(_v.cbElem / 2, _v.cbElem / 2);
                p = (int*) a2.data();
                points.append(QString::number(twipsToPt(*p), 'f'));
                points.append(" ");
            }
            points.chop(1); //remove last space
        }
        out.xml.startElement("draw:contour-polygon");
        out.xml.addAttribute("draw:points", points);
        out.xml.endElement(); //draw:contour-polygon
    }
#endif
    out.xml.endElement(); //draw:frame
    return;
}
Пример #3
0
void
ImageStackPlugin::saveTrimmedRGB(QString trimFile,
				 int dmin, int dmax,
				 int wmin, int wmax,
				 int hmin, int hmax)
{
  QStringList dtypes;
  dtypes << "No"
	 << "Yes";

  QString option = QInputDialog::getItem(0,
					 "Save Alpha Channel",
					 "Alpha Channel",
					 dtypes,
					 0,
					 false);
  
  bool saveAlpha = false;
  if (option == "Yes")
    saveAlpha = true;


  QProgressDialog progress("Saving trimmed RGB volume",
			   "Cancel",
			   0, 100,
			   0);
  progress.setMinimumDuration(0);

  int nX, nY, nZ;
  nX = m_depth;
  nY = m_width;
  nZ = m_height;

  int d, w, h;
  d = dmax-dmin+1;
  w = wmax-wmin+1;
  h = hmax-hmin+1;

  int nbytes = nY*nZ;
  uchar *tmpR = new uchar[nbytes];
  uchar *tmpG = new uchar[nbytes];
  uchar *tmpB = new uchar[nbytes];
  uchar *tmpA;
  if (saveAlpha)
    tmpA = new uchar[nbytes];


  QString voxelType = "RGB";
  if (saveAlpha) voxelType = "RGBA";
  
  //*** max 1Gb per slab
  int slabSize;
  slabSize = (1024*1024*1024)/(w*h);

  savePvlHeader(trimFile,
		d, w, h,
		voxelType,
		slabSize);			       

  VolumeFileManager rFileManager;
  VolumeFileManager gFileManager;
  VolumeFileManager bFileManager;
  VolumeFileManager aFileManager;

  QString pvlfile = trimFile;
  pvlfile.chop(6);

  QString rFilename = pvlfile + QString("red");
  QString gFilename = pvlfile + QString("green");
  QString bFilename = pvlfile + QString("blue");
  QString aFilename = pvlfile + QString("alpha");

  rFileManager.setBaseFilename(rFilename);
  rFileManager.setDepth(d);
  rFileManager.setWidth(w);
  rFileManager.setHeight(h);
  rFileManager.setVoxelType(0);
  rFileManager.setHeaderSize(13);
  rFileManager.setSlabSize(slabSize);
  rFileManager.createFile(true);
  rFileManager.createFile(true);

  gFileManager.setBaseFilename(gFilename);
  gFileManager.setDepth(d);
  gFileManager.setWidth(w);
  gFileManager.setHeight(h);
  gFileManager.setVoxelType(0);
  gFileManager.setHeaderSize(13);
  gFileManager.setSlabSize(slabSize);
  gFileManager.createFile(true);
  gFileManager.createFile(true);

  bFileManager.setBaseFilename(bFilename);
  bFileManager.setDepth(d);
  bFileManager.setWidth(w);
  bFileManager.setHeight(h);
  bFileManager.setVoxelType(0);
  bFileManager.setHeaderSize(13);
  bFileManager.setSlabSize(slabSize);
  bFileManager.createFile(true);
  bFileManager.createFile(true);

  if (saveAlpha)
    {
      aFileManager.setBaseFilename(aFilename);
      aFileManager.setDepth(d);
      aFileManager.setWidth(w);
      aFileManager.setHeight(h);
      aFileManager.setVoxelType(0);
      aFileManager.setHeaderSize(13);
      aFileManager.setSlabSize(slabSize);
      aFileManager.createFile(true);
      aFileManager.createFile(true);
    }


  for(int i=dmax; i>=dmin; i--)
    {

      QImage imgL = QImage(m_imageList[i]);
      if (imgL.format() != QImage::Format_ARGB32)
	imgL = imgL.convertToFormat(QImage::Format_ARGB32);
      
      uchar *imgbits = imgL.bits();
      for(uint j=0; j<m_width*m_height; j++)
	{
	  tmpR[j] = imgbits[4*j+2];
	  tmpG[j] = imgbits[4*j+1];
	  tmpB[j] = imgbits[4*j+0];
	}

      if (saveAlpha)
	{
	  for(uint j=0; j<m_width*m_height; j++)
	    tmpA[j] = imgbits[4*j+3];
	}

      for(uint j=wmin; j<=wmax; j++)
	memcpy(tmpR+(j-wmin)*h,
	       tmpR+(j*nZ + hmin),
	       h);

      for(uint j=wmin; j<=wmax; j++)
	memcpy(tmpG+(j-wmin)*h,
	       tmpG+(j*nZ + hmin),
	       h);

      for(uint j=wmin; j<=wmax; j++)
	memcpy(tmpB+(j-wmin)*h,
	       tmpB+(j*nZ + hmin),
	       h);

      if (saveAlpha)
	{
	  for(uint j=wmin; j<=wmax; j++)
	    memcpy(tmpA+(j-wmin)*h,
		   tmpA+(j*nZ + hmin),
		   h);
	}

      rFileManager.setSlice(dmax-i, tmpR);
      gFileManager.setSlice(dmax-i, tmpG);
      bFileManager.setSlice(dmax-i, tmpB);
      if (saveAlpha)
	aFileManager.setSlice(dmax-i, tmpA);

      progress.setValue((int)(100*(float)(dmax-i)/(float)d));
      qApp->processEvents();
    }


  delete [] tmpR;
  delete [] tmpG;
  delete [] tmpB;

  if (saveAlpha)
    delete [] tmpA;

  progress.setValue(100);
}
Пример #4
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

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

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

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

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

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

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
Пример #5
0
/**
 * Starting point for the retracing thread.
 *
 * Overrides QThread::run().
 */
void Retracer::run()
{
    QString msg = QLatin1String("Replay finished!");

    /*
     * Construct command line
     */

    QString prog;
    QStringList arguments;

    switch (m_api) {
    case trace::API_GL:
        prog = QLatin1String("glretrace");
        break;
    case trace::API_EGL:
        prog = QLatin1String("eglretrace");
        break;
    case trace::API_DX:
    case trace::API_D3D7:
    case trace::API_D3D8:
    case trace::API_D3D9:
    case trace::API_DXGI:
#ifdef Q_OS_WIN
        prog = QLatin1String("d3dretrace");
#else
        prog = QLatin1String("wine");
        arguments << QLatin1String("d3dretrace.exe");
#endif
        break;
    default:
        emit finished(QLatin1String("Unsupported API"));
        return;
    }

    arguments << retraceArguments() << m_fileName;

    /*
     * Support remote execution on a separate target.
     */

    if (m_remoteTarget.length() != 0) {
        arguments.prepend(prog);
        arguments.prepend(m_remoteTarget);
        prog = QLatin1String("ssh");
    }

    /*
     * Start the process.
     */

    {
        QDebug debug(QtDebugMsg);
        debug << "Running:";
        debug << prog;
        foreach (const QString &argument, arguments) {
            debug << argument;
        }
    }

    QProcess process;

    process.start(prog, arguments, QIODevice::ReadOnly);
    if (!process.waitForStarted(-1)) {
        emit finished(QLatin1String("Could not start process"));
        return;
    }

    /*
     * Process standard output
     */

    ImageHash thumbnails;
    QVariantMap parsedJson;
    trace::Profile* profile = NULL;

    process.setReadChannel(QProcess::StandardOutput);
    if (process.waitForReadyRead(-1)) {
        BlockingIODevice io(&process);

        if (m_captureState) {
            parsedJson = decodeUBJSONObject(&io).toMap();
            process.waitForFinished(-1);
        } else if (m_captureThumbnails) {
            /*
             * Parse concatenated PNM images from output.
             */

            while (!io.atEnd()) {
                image::PNMInfo info;

                char header[512];
                qint64 headerSize = 0;
                int headerLines = 3; // assume no optional comment line

                for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
                    qint64 headerRead = io.readLine(&header[headerSize], sizeof(header) - headerSize);

                    // if header actually contains optional comment line, ...
                    if (headerLine == 1 && header[headerSize] == '#') {
                        ++headerLines;
                    }

                    headerSize += headerRead;
                }

                const char *headerEnd = image::readPNMHeader(header, headerSize, info);

                // if invalid PNM header was encountered, ...
                if (headerEnd == NULL ||
                    info.channelType != image::TYPE_UNORM8) {
                    qDebug() << "error: invalid snapshot stream encountered";
                    break;
                }

                unsigned channels = info.channels;
                unsigned width = info.width;
                unsigned height = info.height;

                // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";

                QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);

                int rowBytes = channels * width;
                for (int y = 0; y < height; ++y) {
                    unsigned char *scanLine = snapshot.scanLine(y);
                    qint64 readBytes = io.read((char *) scanLine, rowBytes);
                    Q_ASSERT(readBytes == rowBytes);
                    (void)readBytes;
                }

                QImage thumb = thumbnail(snapshot);
                thumbnails.insert(info.commentNumber, thumb);
            }

            Q_ASSERT(process.state() != QProcess::Running);
        } else if (isProfiling()) {
            profile = new trace::Profile();

            while (!io.atEnd()) {
                char line[256];
                qint64 lineLength;

                lineLength = io.readLine(line, 256);

                if (lineLength == -1)
                    break;

                trace::Profiler::parseLine(line, profile);
            }
        } else {
            QByteArray output;
            output = process.readAllStandardOutput();
            if (output.length() < 80) {
                msg = QString::fromUtf8(output);
            }
        }
    }

    /*
     * Wait for process termination
     */

    process.waitForFinished(-1);

    if (process.exitStatus() != QProcess::NormalExit) {
        msg = QLatin1String("Process crashed");
    } else if (process.exitCode() != 0) {
        msg = QLatin1String("Process exited with non zero exit code");
    }

    /*
     * Parse errors.
     */

    QList<ApiTraceError> errors;
    process.setReadChannel(QProcess::StandardError);
    QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
    while (!process.atEnd()) {
        QString line = process.readLine();
        if (regexp.indexIn(line) != -1) {
            ApiTraceError error;
            error.callIndex = regexp.cap(1).toInt();
            error.type = regexp.cap(2);
            error.message = regexp.cap(3);
            errors.append(error);
        } else if (!errors.isEmpty()) {
            // Probably a multiligne message
            ApiTraceError &previous = errors.last();
            if (line.endsWith("\n")) {
                line.chop(1);
            }
            previous.message.append('\n');
            previous.message.append(line);
        }
    }

    /*
     * Emit signals
     */

    if (m_captureState) {
        ApiTraceState *state = new ApiTraceState(parsedJson);
        emit foundState(state);
    }

    if (m_captureThumbnails && !thumbnails.isEmpty()) {
        emit foundThumbnails(thumbnails);
    }

    if (isProfiling() && profile) {
        emit foundProfile(profile);
    }

    if (!errors.isEmpty()) {
        emit retraceErrors(errors);
    }

    emit finished(msg);
}
Пример #6
0
/*!
    Returns a SQL statement of type \a type for the table \a tableName
    with the values from \a rec. If \a preparedStatement is true, the
    string will contain placeholders instead of values.

    This method can be used to manipulate tables without having to worry
    about database-dependent SQL dialects. For non-prepared statements,
    the values will be properly escaped.
*/
QString QSqlDriver::sqlStatement(StatementType type, const QString &tableName,
                                 const QSqlRecord &rec, bool preparedStatement) const
{
    int i;
    QString s;
    s.reserve(128);
    switch (type) {
    case SelectStatement:
        for (i = 0; i < rec.count(); ++i) {
            if (rec.isGenerated(i))
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
        }
        if (s.isEmpty())
            return s;
        s.chop(2);
        s.prepend(QLatin1String("SELECT ")).append(QLatin1String(" FROM ")).append(tableName);
        break;
    case WhereStatement:
        if (preparedStatement) {
            for (int i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), FieldName,this));
                if (rec.isNull(i))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ?"));
                s.append(QLatin1String(" AND "));
            }
        } else {
            for (i = 0; i < rec.count(); ++i) {
                s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this));
                QString val = formatValue(rec.field(i));
                if (val == QLatin1String("NULL"))
                    s.append(QLatin1String(" IS NULL"));
                else
                    s.append(QLatin1String(" = ")).append(val);
                s.append(QLatin1String(" AND "));
            }
        }
        if (!s.isEmpty()) {
            s.prepend(QLatin1String("WHERE "));
            s.chop(5); // remove tailing AND
        }
        break;
    case UpdateStatement:
        s.append(QLatin1String("UPDATE ")).append(tableName).append(
                 QLatin1String(" SET "));
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i) || !rec.value(i).isValid())
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1Char('='));
            if (preparedStatement)
                s.append(QLatin1Char('?'));
            else
                s.append(formatValue(rec.field(i)));
            s.append(QLatin1String(", "));
        }
        if (s.endsWith(QLatin1String(", ")))
            s.chop(2);
        else
            s.clear();
        break;
    case DeleteStatement:
        s.append(QLatin1String("DELETE FROM ")).append(tableName);
        break;
    case InsertStatement: {
        s.append(QLatin1String("INSERT INTO ")).append(tableName).append(QLatin1String(" ("));
        QString vals;
        for (i = 0; i < rec.count(); ++i) {
            if (!rec.isGenerated(i) || !rec.value(i).isValid())
                continue;
            s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", "));
            if (preparedStatement)
                vals.append(QLatin1Char('?'));
            else
                vals.append(formatValue(rec.field(i)));
            vals.append(QLatin1String(", "));
        }
        if (vals.isEmpty()) {
            s.clear();
        } else {
            vals.chop(2); // remove trailing comma
            s[s.length() - 2] = QLatin1Char(')');
            s.append(QLatin1String("VALUES (")).append(vals).append(QLatin1Char(')'));
        }
        break; }
    }
    return s;
}
Пример #7
0
void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &sender, UserLevelFlags userLevel)
{
    const QRegExp notALetterOrNumber = QRegExp("[^a-zA-Z0-9]");

    int firstSpace = message.indexOf(' ');
    QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1);
    QString mentionIntact = fullMentionUpToSpaceOrEnd;

    while (fullMentionUpToSpaceOrEnd.size())
    {
        const ServerInfo_User *onlineUser = userlistProxy->getOnlineUser(fullMentionUpToSpaceOrEnd);
        if (onlineUser) // Is there a user online named this?
        {
            if (userName.toLower() == fullMentionUpToSpaceOrEnd.toLower()) // Is this user you?
            {
                // You have received a valid mention!!
                soundEngine->playSound("chat_mention");
                mentionFormat.setBackground(QBrush(getCustomMentionColor()));
                mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
                cursor.insertText(mention, mentionFormat);
                message = message.mid(mention.size());
                showSystemPopup(sender);
            } else {
                QString correctUserName = QString::fromStdString(onlineUser->name());
                mentionFormatOtherUser.setAnchorHref("user://" + QString::number(onlineUser->user_level()) + "_" + correctUserName);
                cursor.insertText("@" + correctUserName, mentionFormatOtherUser);

                message = message.mid(correctUserName.size() + 1);
            }

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (isModeratorSendingGlobal(userLevel, fullMentionUpToSpaceOrEnd)) {
            // Moderator Sending Global Message
            soundEngine->playSound("all_mention");
            mentionFormat.setBackground(QBrush(getCustomMentionColor()));
            mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black));
            cursor.insertText("@" + fullMentionUpToSpaceOrEnd, mentionFormat);
            message = message.mid(fullMentionUpToSpaceOrEnd.size() + 1);
            showSystemPopup(sender);

            cursor.setCharFormat(defaultFormat);
            return;
        }

        if (fullMentionUpToSpaceOrEnd.right(1).indexOf(notALetterOrNumber) == -1 || fullMentionUpToSpaceOrEnd.size() < 2)
        {
            cursor.insertText("@" + mentionIntact, defaultFormat);
            message = message.mid(mentionIntact.size() + 1);
            cursor.setCharFormat(defaultFormat);
            return;
        }

        fullMentionUpToSpaceOrEnd.chop(1);
    }

    // no valid mention found
    checkWord(cursor, message);
}
Пример #8
0
// (Un)Register the ActiveX server in the registry.
// The QAxFactory implementation provides the information.
HRESULT UpdateRegistry(BOOL bRegister)
{
    qAxIsServer = false;
    const QChar dot(QLatin1Char('.'));
    const QChar slash(QLatin1Char('/'));
    QString file = QString::fromWCharArray(qAxModuleFilename);
    const QString module = QFileInfo(file).baseName();

    const QString appId = qAxFactory()->appID().toString().toUpper();
    const QString libId = qAxFactory()->typeLibID().toString().toUpper();

    const QString libFile = qAxInit();

    TLIBATTR *libAttr = 0;
    if (qAxTypeLibrary)
        qAxTypeLibrary->GetLibAttr(&libAttr);
    if (!libAttr)
        return SELFREG_E_TYPELIB;
    bool userFallback = false;
    if (bRegister) {
        if (RegisterTypeLib(qAxTypeLibrary,
                            reinterpret_cast<wchar_t *>(const_cast<ushort *>(libFile.utf16())), 0) == TYPE_E_REGISTRYACCESS) {
#ifndef Q_CC_MINGW
            // MinGW does not have RegisterTypeLibForUser() implemented so we cannot fallback in this case
            RegisterTypeLibForUser(qAxTypeLibrary, reinterpret_cast<wchar_t *>(const_cast<ushort *>(libFile.utf16())), 0);
            userFallback = true;
#endif
        }
    } else {
        if (UnRegisterTypeLib(libAttr->guid, libAttr->wMajorVerNum, libAttr->wMinorVerNum, libAttr->lcid,
                              libAttr->syskind) == TYPE_E_REGISTRYACCESS) {
#ifndef Q_CC_MINGW
            // MinGW does not have RegisterTypeLibForUser() implemented so we cannot fallback in this case
            UnRegisterTypeLibForUser(libAttr->guid, libAttr->wMajorVerNum, libAttr->wMinorVerNum, libAttr->lcid, libAttr->syskind);
            userFallback = true;
#endif
        }
    }
    if (userFallback)
        qWarning("QAxServer: Falling back to registering as user for %s due to insufficient permission.", qPrintable(module));
    qAxTypeLibrary->ReleaseTLibAttr(libAttr);

    // check whether the user has permission to write to HKLM\Software\Classes
    // if not, use HKCU\Software\Classes
    QString keyPath(QLatin1String("HKEY_LOCAL_MACHINE\\Software\\Classes"));
    QScopedPointer<QSettings> settings(new QSettings(keyPath, QSettings::NativeFormat));
    if (userFallback || !settings->isWritable()) {
        keyPath = QLatin1String("HKEY_CURRENT_USER\\Software\\Classes");
        settings.reset(new QSettings(keyPath, QSettings::NativeFormat));
    }

    // we try to create the ActiveX widgets later on...
    bool delete_qApp = false;
    if (!qApp) {
        static int argc = 0; // static lifetime, since it's passed as reference to QApplication, which has a lifetime exceeding the stack frame
        (void)new QApplication(argc, 0);
        delete_qApp = true;
    }

    if (bRegister) {
        if (qAxOutProcServer) {
            settings->setValue(QLatin1String("/AppID/") + appId + QLatin1String("/."), module);
            settings->setValue(QLatin1String("/AppID/") + module + QLatin1String(".EXE/AppID"), appId);
        }

        const QStringList keys = qAxFactory()->featureList();
        for (const QString &classNameIn : keys) {
            QObject *object = qAxFactory()->createObject(classNameIn);
            const QMetaObject *mo = qAxFactory()->metaObject(classNameIn);
            const QString classId = qAxFactory()->classID(classNameIn).toString().toUpper();

            const QString className = qax_clean_type(classNameIn, mo);

            if (object) { // don't register subobject classes
                QString classVersion = mo ? QString::fromLatin1(mo->classInfo(mo->indexOfClassInfo("Version")).value()) : QString();
                if (classVersion.isNull())
                    classVersion = QLatin1String("1.0");
                bool insertable = mo && !qstricmp(mo->classInfo(mo->indexOfClassInfo("Insertable")).value(), "yes");
                bool control = object->isWidgetType();
                QString classMajorVersion = classVersion.left(classVersion.indexOf(dot));
                uint olemisc = OLEMISC_SETCLIENTSITEFIRST
                    |OLEMISC_ACTIVATEWHENVISIBLE
                    |OLEMISC_INSIDEOUT
                    |OLEMISC_CANTLINKINSIDE
                    |OLEMISC_RECOMPOSEONRESIZE;
                if (!control)
                    olemisc |= OLEMISC_INVISIBLEATRUNTIME;
                else if (object->findChild<QMenuBar*>() && !qax_disable_inplaceframe)
                    olemisc |= OLEMISC_WANTSTOMENUMERGE;

                const QString versionLessProgId = module + dot + className;
                const QString progId = versionLessProgId + dot + classMajorVersion;
                QString key = slash + progId;
                settings->setValue(key + QLatin1String("/."), className + QLatin1String(" Class"));
                settings->setValue(key + QLatin1String("/CLSID/."), classId);
                if (insertable)
                    settings->setValue(key + QLatin1String("/Insertable/."), QVariant(QLatin1String("")));

                key = slash + module + dot + className;
                settings->setValue(key + QLatin1String("/."), className + QLatin1String(" Class"));
                settings->setValue(key + QLatin1String("/CLSID/."), classId);
                settings->setValue(key + QLatin1String("/CurVer/."), progId);

                key = QLatin1String("/CLSID/") + classId;
                settings->setValue(key + QLatin1String("/."), className + QLatin1String(" Class"));
                if (file.endsWith(QLatin1String("exe"), Qt::CaseInsensitive))
                    settings->setValue(key + QLatin1String("/AppID"), appId);
                if (control)
                    settings->setValue(key + QLatin1String("/Control/."), QVariant(QLatin1String("")));
                if (insertable)
                    settings->setValue(key + QLatin1String("/Insertable/."), QVariant(QLatin1String("")));
                if (file.endsWith(QLatin1String("dll"), Qt::CaseInsensitive))
                    settings->setValue(key + QLatin1String("/InProcServer32/."), file);
                else
                    settings->setValue(key + QLatin1String("/LocalServer32/."),
                                      QLatin1Char('\"') + file + QLatin1String("\" -activex"));
                settings->setValue(key + QLatin1String("/MiscStatus/."), control ? QLatin1String("1") : QLatin1String("0"));
                settings->setValue(key + QLatin1String("/MiscStatus/1/."), QString::number(olemisc));
                settings->setValue(key + QLatin1String("/Programmable/."), QVariant(QLatin1String("")));
                settings->setValue(key + QLatin1String("/ToolboxBitmap32/."), QLatin1Char('\"') +
                                  file + QLatin1String("\", 101"));
                settings->setValue(key + QLatin1String("/TypeLib/."), libId);
                settings->setValue(key + QLatin1String("/Version/."), classVersion);
                settings->setValue(key + QLatin1String("/VersionIndependentProgID/."), versionLessProgId);
                settings->setValue(key + QLatin1String("/ProgID/."), progId);

                QString mime = QLatin1String(mo->classInfo(mo->indexOfClassInfo("MIME")).value());
                if (!mime.isEmpty()) {
                    QStringList mimeTypes = mime.split(QLatin1Char(';'));
                    for (int m = 0; m < mimeTypes.count(); ++m) {
                        mime = mimeTypes.at(m);
                        if (mime.isEmpty())
                            continue;
                        QString extension;
                        while (mime.contains(QLatin1Char(':'))) {
                            extension = mime.mid(mime.lastIndexOf(QLatin1Char(':')) + 1);
                            mime.chop(extension.length() + 1);
                            // Prepend '.' before extension, if required.
                            extension = extension.trimmed();
                            if (!extension.startsWith(dot))
                                extension.prepend(dot);
                        }

                        if (!extension.isEmpty()) {
                            key = slash + extension;
                            settings->setValue(key + QLatin1String("/."), module + dot + className);
                            settings->setValue(key + QLatin1String("/Content Type"), mime);

                            mime.replace(slash, QLatin1Char('\\'));
                            key = QLatin1String("/MIME/Database/Content Type/") + mime;
                            settings->setValue(key + QLatin1String("/CLSID"), classId);
                            settings->setValue(key + QLatin1String("/Extension"), extension);
                        }
                    }
                }

                delete object;
                qCDebug(lcAxRegistration).nospace().noquote() << "Registered \"" << progId
                    << "\"/" << classId << ", \"" << file << "\" at \"" << keyPath
                    << "\", insertable=" << insertable << ", control=" << control
                    << ", olemisc=" << hex << showbase << olemisc
                    << ", mime=" << mime;
            }

            qAxFactory()->registerClass(classNameIn, settings.data());
        }
    } else {
        if (qAxOutProcServer) {
            settings->remove(QLatin1String("/AppID/") + appId + QLatin1String("/."));
            settings->remove(QLatin1String("/AppID/") + module + QLatin1String(".EXE"));
        }
        const QStringList keys = qAxFactory()->featureList();
        for (const QString &classNameIn : keys) {
            const QMetaObject *mo = qAxFactory()->metaObject(classNameIn);
            const QString classId = qAxFactory()->classID(classNameIn).toString().toUpper();
            const QString className = qax_clean_type(classNameIn, mo);

            QString classVersion = mo ? QString::fromLatin1(mo->classInfo(mo->indexOfClassInfo("Version")).value()) : QString();
            if (classVersion.isNull())
                classVersion = QLatin1String("1.0");
            const QString classMajorVersion = classVersion.left(classVersion.indexOf(dot));

            qAxFactory()->unregisterClass(classNameIn, settings.data());
            const QString progId = module + dot + className + dot + classMajorVersion;
            QString key = slash + progId;
            settings->remove(key + QLatin1String("/CLSID/."));
            settings->remove(key + QLatin1String("/Insertable/."));
            settings->remove(key + QLatin1String("/."));
            settings->remove(key);

            key = slash + module + dot + className;
            settings->remove(key + QLatin1String("/CLSID/."));
            settings->remove(key + QLatin1String("/CurVer/."));
            settings->remove(key + QLatin1String("/."));
            settings->remove(key);

            key = QLatin1String("/CLSID/") + classId;
            settings->remove(key + QLatin1String("/AppID"));
            settings->remove(key + QLatin1String("/Control/."));
            settings->remove(key + QLatin1String("/Insertable/."));
            settings->remove(key + QLatin1String("/InProcServer32/."));
            settings->remove(key + QLatin1String("/LocalServer32/."));
            settings->remove(key + QLatin1String("/MiscStatus/1/."));
            settings->remove(key + QLatin1String("/MiscStatus/."));
            settings->remove(key + QLatin1String("/Programmable/."));
            settings->remove(key + QLatin1String("/ToolboxBitmap32/."));
            settings->remove(key + QLatin1String("/TypeLib/."));
            settings->remove(key + QLatin1String("/Version/."));
            settings->remove(key + QLatin1String("/VersionIndependentProgID/."));
            settings->remove(key + QLatin1String("/ProgID/."));
            settings->remove(key + QLatin1String("/."));
            settings->remove(key);

            QString mime = QLatin1String(mo->classInfo(mo->indexOfClassInfo("MIME")).value());
            if (!mime.isEmpty()) {
                QStringList mimeTypes = mime.split(QLatin1Char(';'));
                for (int m = 0; m < mimeTypes.count(); ++m) {
                    mime = mimeTypes.at(m);
                    if (mime.isEmpty())
                        continue;
                    QString extension;
                    while (mime.contains(QLatin1Char(':'))) {
                        extension = mime.mid(mime.lastIndexOf(QLatin1Char(':')) + 1);
                        mime.chop(extension.length() + 1);
                        // Prepend '.' before extension, if required.
                        extension = extension.trimmed();
                        if (extension[0] != dot)
                            extension.prepend(dot);
                    }
                    if (!extension.isEmpty()) {
                        key = slash + extension;
                        settings->remove(key + QLatin1String("/Content Type"));
                        settings->remove(key + QLatin1String("/."));
                        settings->remove(key);
                        mime.replace(slash, QLatin1Char('\\'));
                        key = QLatin1String("/MIME/Database/Content Type/") + mime;
                        settings->remove(key + QLatin1String("/Extension"));
                        settings->remove(key + QLatin1String("/CLSID"));
                        settings->remove(key + QLatin1String("/."));
                        settings->remove(key);
                    }
                }
            }
            qCDebug(lcAxRegistration).nospace().noquote() << "Unregistered \""
                << progId << "\"/" << classId << ", \"" << file << "\" from \""
                << keyPath << '"';
        }
    }

    if (delete_qApp)
        delete qApp;

    qAxCleanup();
    if (settings->status() == QSettings::NoError)
        return S_OK;
    qWarning() << module << ": Error writing to " << keyPath;
    return SELFREG_E_CLASS;
}
Пример #9
0
QPair<QStringList, QStringList> ModelGenerator::createModelParams() const
{
    QString setgetDecl;
    QString setgetImpl;
    QString crtparams;
    QString getOptDecl;
    QString getOptImpl;
    QString initParams;
    QList<QPair<QString, QString> > writableFields;
    bool optlockMethod = false;
    TableSchema ts(tableName);
    QList<QPair<QString, QString> > fieldList = ts.getFieldList();
    QString autoFieldName = ts.autoValueFieldName();

    for (QListIterator<QPair<QString, QString> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QString> &p = it.next();
        QString var = fieldNameToVariableName(p.first);

        // Getter method
        setgetDecl += QString("    %1 %2() const;\n").arg(p.second, var);
        setgetImpl += QString("%1 %2::%3() const\n{\n    return d->%4;\n}\n\n").arg(p.second, modelName, var, p.first);

        if (!excludedSetter()->contains(p.first, Qt::CaseInsensitive) && p.first != autoFieldName) {
            // Setter method
            QString str = fieldNameToEnumName(p.first);         
            setgetDecl += QString("    void set%1(%2);\n").arg(str, createParam(p.second, p.first));
            setgetImpl += QString("void %1::set%2(%3)\n{\n    d->%4 = %5;\n}\n\n").arg(modelName, str, createParam(p.second, p.first), p.first, var);

            // Appends to crtparams-string
            crtparams += createParam(p.second, p.first);
            crtparams += ", ";

            writableFields << QPair<QString, QString>(p.first, p.second);

            if (p.second == "int" || p.second == "float" || p.second == "double") {
                initParams += QString("\n    d->") + p.first + " = 0;";
            }
        }
        
        if (p.first == LOCK_REVISION_FIELD) 
            optlockMethod = true;
    }
    crtparams.chop(2);

    initParams += (initParams.isEmpty()) ? ' ' : '\n';

    // Creates parameters of get() method
    int idx = ts.primaryKeyIndex();
    QString getparams;
    if (idx < 0) {
        getparams = crtparams;
    } else {
        const QPair<QString, QString> &pair = fieldList[idx];
        getparams = createParam(pair.second, pair.first);
    }

    // Creates a declaration and a implementation of 'get' method for optimistic lock
    if (idx >= 0 &&optlockMethod) {
        const QPair<QString, QString> &pair = fieldList[idx];
        getOptDecl = QString("    static %1 get(%2, int lockRevision);\n").arg(modelName, createParam(pair.second, pair.first));

        getOptImpl = QString("%1 %1::get(%2, int lockRevision)\n"       \
                             "{\n"                                      \
                             "    TSqlORMapper<%1Object> mapper;\n"     \
                             "    TCriteria cri;\n"                     \
                             "    cri.add(%1Object::%3, %4);\n"         \
                             "    cri.add(%1Object::LockRevision, lockRevision);\n" \
                             "    return %1(mapper.findFirst(cri));\n"  \
                             "}\n\n").arg(modelName, createParam(pair.second, pair.first), fieldNameToEnumName(pair.first), fieldNameToVariableName(pair.first));
    }

    QStringList headerArgs;
    headerArgs << modelName.toUpper() << modelName << setgetDecl << crtparams << getparams << getOptDecl;

    // Creates a model implementation
    QString createImpl;
    createImpl += QString("    %1Object obj;\n").arg(modelName);

    QListIterator<QPair<QString, QString> > fi(writableFields);
    while (fi.hasNext()) {
        const QPair<QString, QString> &p = fi.next();
        createImpl += QString("    obj.%1 = %2;\n").arg(p.first, fieldNameToVariableName(p.first));
    }
    createImpl += "    if (!obj.create()) {\n";
    createImpl += "        obj.clear();\n";
    createImpl += "    }\n";
    createImpl += QString("    return %1(obj);\n").arg(modelName);

    // Creates a implementation of get() method
    QString getImpl;
    if (idx < 0) {
        // If no primary index exists
        getImpl += QString("    TCriteria cri;\n");
        fi.toFront();
        while (fi.hasNext()) {
            const QPair<QString, QString> &p = fi.next();
            getImpl += QString("    cri.add(%1Object::%2, %3);\n").arg(modelName, fieldNameToEnumName(p.first), fieldNameToVariableName(p.first));
        }
    }
    
    getImpl += QString("    TSqlORMapper<%1Object> mapper;\n").arg(modelName);
    getImpl += QString("    return %1(mapper.").arg(modelName);

    if (idx < 0) {
        getImpl += "findFirst(cri));\n";
    } else {
        const QPair<QString, QString> &pair = fieldList[idx];
        getImpl += QString("findByPrimaryKey(%1));\n").arg(fieldNameToVariableName(pair.first));
    }

    QStringList implArgs;
    implArgs << modelName.toLower() << modelName << initParams << setgetImpl << crtparams << createImpl << getparams << getImpl << getOptImpl;

    return QPair<QStringList, QStringList>(headerArgs, implArgs);
}
Пример #10
0
void QgsPalLabeling::drawLabeling( QgsRenderContext& context )
{
  Q_ASSERT( mMapRenderer != NULL );
  QPainter* painter = context.painter();
  QgsRectangle extent = context.extent();

  if ( mLabelSearchTree )
  {
    mLabelSearchTree->clear();
  }

  QTime t;
  t.start();

  // do the labeling itself
  double scale = mMapRenderer->scale(); // scale denominator
  QgsRectangle r = extent;
  double bbox[] = { r.xMinimum(), r.yMinimum(), r.xMaximum(), r.yMaximum() };

  std::list<LabelPosition*>* labels;
  pal::Problem* problem;
  try
  {
    problem = mPal->extractProblem( scale, bbox );
  }
  catch ( std::exception& e )
  {
    Q_UNUSED( e );
    QgsDebugMsg( "PAL EXCEPTION :-( " + QString::fromLatin1( e.what() ) );
    //mActiveLayers.clear(); // clean up
    return;
  }

  const QgsMapToPixel* xform = mMapRenderer->coordinateTransform();

  // draw rectangles with all candidates
  // this is done before actual solution of the problem
  // before number of candidates gets reduced
  mCandidates.clear();
  if ( mShowingCandidates && problem )
  {
    painter->setPen( QColor( 0, 0, 0, 64 ) );
    painter->setBrush( Qt::NoBrush );
    for ( int i = 0; i < problem->getNumFeatures(); i++ )
    {
      for ( int j = 0; j < problem->getFeatureCandidateCount( i ); j++ )
      {
        pal::LabelPosition* lp = problem->getFeatureCandidate( i, j );

        drawLabelCandidateRect( lp, painter, xform );
      }
    }
  }

  // find the solution
  labels = mPal->solveProblem( problem, mShowingAllLabels );

  QgsDebugMsg( QString( "LABELING work:  %1 ms ... labels# %2" ).arg( t.elapsed() ).arg( labels->size() ) );
  t.restart();

  painter->setRenderHint( QPainter::Antialiasing );

  // draw the labels
  std::list<LabelPosition*>::iterator it = labels->begin();
  for ( ; it != labels->end(); ++it )
  {
    QgsPalGeometry* palGeometry = dynamic_cast< QgsPalGeometry* >(( *it )->getFeaturePart()->getUserGeometry() );
    if ( !palGeometry )
    {
      continue;
    }

    //layer names
    QString layerNameUtf8 = QString::fromUtf8(( *it )->getLayerName() );
    if ( palGeometry->isDiagram() )
    {
      //render diagram
      QHash<QgsVectorLayer*, QgsDiagramLayerSettings>::iterator dit = mActiveDiagramLayers.begin();
      for ( dit = mActiveDiagramLayers.begin(); dit != mActiveDiagramLayers.end(); ++dit )
      {
        if ( dit.key() && dit.key()->id().append( "d" ) == layerNameUtf8 )
        {
          QgsPoint outPt = xform->transform(( *it )->getX(), ( *it )->getY() );
          dit.value().renderer->renderDiagram( palGeometry->diagramAttributes(), context, QPointF( outPt.x(), outPt.y() ) );
        }
      }

      //insert into label search tree to manipulate position interactively
      if ( mLabelSearchTree )
      {
        //for diagrams, remove the additional 'd' at the end of the layer id
        QString layerId = layerNameUtf8;
        layerId.chop( 1 );
        mLabelSearchTree->insertLabel( *it,  QString( palGeometry->strId() ).toInt(), layerId, true );
      }
      continue;
    }

    const QgsPalLayerSettings& lyr = layer( layerNameUtf8 );
    QFont fontForLabel = lyr.textFont;
    QColor fontColor = lyr.textColor;
    double bufferSize = lyr.bufferSize;
    QColor bufferColor = lyr.bufferColor;

    //apply data defined settings for the label
    //font size
    QVariant dataDefinedSize = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Size );
    if ( dataDefinedSize.isValid() )
    {
      fontForLabel.setPixelSize( lyr.sizeToPixel( dataDefinedSize.toDouble(), context ) );
    }
    //font color
    QVariant dataDefinedColor = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Color );
    if ( dataDefinedColor.isValid() )
    {
      fontColor.setNamedColor( dataDefinedColor.toString() );
      if ( !fontColor.isValid() )
      {
        fontColor = lyr.textColor;
      }
    }
    //font bold
    QVariant dataDefinedBold = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Bold );
    if ( dataDefinedBold.isValid() )
    {
      fontForLabel.setBold(( bool )dataDefinedBold.toInt() );
    }
    //font italic
    QVariant dataDefinedItalic = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Italic );
    if ( dataDefinedItalic.isValid() )
    {
      fontForLabel.setItalic(( bool ) dataDefinedItalic.toInt() );
    }
    //font underline
    QVariant dataDefinedUnderline = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Underline );
    if ( dataDefinedUnderline.isValid() )
    {
      fontForLabel.setUnderline(( bool ) dataDefinedUnderline.toInt() );
    }
    //font strikeout
    QVariant dataDefinedStrikeout = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Strikeout );
    if ( dataDefinedStrikeout.isValid() )
    {
      fontForLabel.setStrikeOut(( bool ) dataDefinedStrikeout.toInt() );
    }
    //font family
    QVariant dataDefinedFontFamily = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::Family );
    if ( dataDefinedFontFamily.isValid() )
    {
      fontForLabel.setFamily( dataDefinedFontFamily.toString() );
    }
    //buffer size
    QVariant dataDefinedBufferSize = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::BufferSize );
    if ( dataDefinedBufferSize.isValid() )
    {
      bufferSize = dataDefinedBufferSize.toDouble();
    }

    //buffer color
    QVariant dataDefinedBufferColor = palGeometry->dataDefinedValues().value( QgsPalLayerSettings::BufferColor );
    if ( dataDefinedBufferColor.isValid() )
    {
      bufferColor.setNamedColor( dataDefinedBufferColor.toString() );
      if ( !bufferColor.isValid() )
      {
        bufferColor = lyr.bufferColor;
      }
    }

    if ( lyr.bufferSize != 0 )
      drawLabel( *it, painter, fontForLabel, fontColor, xform, bufferSize, bufferColor, true );

    drawLabel( *it, painter, fontForLabel, fontColor, xform );

    if ( mLabelSearchTree )
    {
      mLabelSearchTree->insertLabel( *it,  QString( palGeometry->strId() ).toInt(), ( *it )->getLayerName() );
    }
  }

  QgsDebugMsg( QString( "LABELING draw:  %1 ms" ).arg( t.elapsed() ) );

  delete problem;
  delete labels;

  // delete all allocated geometries for features
  QHash<QgsVectorLayer*, QgsPalLayerSettings>::iterator lit;
  for ( lit = mActiveLayers.begin(); lit != mActiveLayers.end(); ++lit )
  {
    QgsPalLayerSettings& lyr = lit.value();
    for ( QList<QgsPalGeometry*>::iterator git = lyr.geometries.begin(); git != lyr.geometries.end(); ++git )
      delete *git;
    lyr.geometries.clear();
  }

  //delete all allocated geometries for diagrams
  QHash<QgsVectorLayer*, QgsDiagramLayerSettings>::iterator dIt = mActiveDiagramLayers.begin();
  for ( ; dIt != mActiveDiagramLayers.end(); ++dIt )
  {
    QgsDiagramLayerSettings& dls = dIt.value();
    for ( QList<QgsPalGeometry*>::iterator git = dls.geometries.begin(); git != dls.geometries.end(); ++git )
    {
      delete *git;
    }
    dls.geometries.clear();
  }
}
Пример #11
0
void DisassemblerLines::appendUnparsed(const QString &unparsed)
{
    QString line = unparsed.trimmed();
    if (line.isEmpty())
        return;
    if (line.startsWith(QLatin1String("Current language:")))
        return;
    if (line.startsWith(QLatin1String("Dump of assembler"))) {
        m_lastFunction.clear();
        return;
    }
    if (line.startsWith(QLatin1String("The current source")))
        return;
    if (line.startsWith(QLatin1String("End of assembler"))) {
        m_lastFunction.clear();
        return;
    }
    if (line.startsWith(QLatin1String("=> ")))
        line = line.mid(3);
    if (line.startsWith(QLatin1String("0x"))) {
        // Address line. Split at the tab.
        int tab1 = line.indexOf(QLatin1Char('\t'));
        if (tab1 == -1) {
            appendComment(line);
            return;
        }
        int tab2 = line.indexOf(QLatin1Char('\t'), tab1 + 1);
        if (tab2 == -1)
            tab2 = tab1;
        QString address = line.left(tab1);
        if (address.endsWith(QLatin1Char(':')))
            address.chop(1);
        int pos1 = address.indexOf(QLatin1Char('<')) + 1;
        DisassemblerLine dl;
        dl.bytes = line.mid(tab1, tab2 - tab1).trimmed();
        m_bytesLength = qMax(m_bytesLength, tab2 - tab1);
        dl.data = line.mid(tab2).trimmed();
        if (pos1 && address.indexOf(QLatin1String("<UNDEFINED> instruction:")) == -1) {
            if (address.endsWith(QLatin1Char('>')))
                address.chop(1);
            int pos2 = address.indexOf(QLatin1Char('+'), pos1);
            if (pos1 < pos2) {
                QString function = address.mid(pos1, pos2 - pos1);
                if (function != m_lastFunction) {
                    DisassemblerLine dl;
                    dl.data = _("Function: ") + function;
                    m_data.append(dl);
                    m_lastFunction = function;
                }
            }
            dl.address = address.left(pos1 - 1).toULongLong(0, 0);
            dl.function = m_lastFunction;
            dl.offset = address.mid(pos2).toUInt();
        } else {
            // Plain data like "0x0000cd64:\tadd\tlr, pc, lr\n"
            dl.address = address.toULongLong(0, 0);
            dl.function = m_lastFunction;
            dl.offset = 0;
        }
        m_rowCache[dl.address] = m_data.size() + 1;
        m_data.append(dl);
    } else {
        // Comment or code line.
        QTextStream ts(&line);
        DisassemblerLine dl;
        ts >> dl.lineNumber;
        dl.data = line.mid(ts.pos());
        m_data.append(dl);
    }
}
Пример #12
0
void PropagateRemoteMove::start()
{
    if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
        return;

    QString origin = propagator()->adjustRenamedPath(_item->_file);
    qCDebug(lcPropagateRemoteMove) << origin << _item->_renameTarget;

    QString targetFile(propagator()->getFilePath(_item->_renameTarget));

    if (origin == _item->_renameTarget) {
        // The parent has been renamed already so there is nothing more to do.
        finalize();
        return;
    }

    QString remoteSource = propagator()->_remoteFolder + origin;
    QString remoteDestination = QDir::cleanPath(propagator()->account()->davUrl().path() + propagator()->_remoteFolder + _item->_renameTarget);

    auto &vfs = propagator()->syncOptions()._vfs;
    auto itype = _item->_type;
    ASSERT(itype != ItemTypeVirtualFileDownload && itype != ItemTypeVirtualFileDehydration);
    if (vfs->mode() == Vfs::WithSuffix && itype != ItemTypeDirectory) {
        const auto suffix = vfs->fileSuffix();
        bool sourceHadSuffix = remoteSource.endsWith(suffix);
        bool destinationHadSuffix = remoteDestination.endsWith(suffix);

        // Remote source and destination definitely shouldn't have the suffix
        if (sourceHadSuffix)
            remoteSource.chop(suffix.size());
        if (destinationHadSuffix)
            remoteDestination.chop(suffix.size());

        QString folderTarget = _item->_renameTarget;

        // Users can rename the file *and at the same time* add or remove the vfs
        // suffix. That's a complicated case where a remote rename plus a local hydration
        // change is requested. We don't currently deal with that. Instead, the rename
        // is propagated and the local vfs suffix change is reverted.
        // The discovery would still set up _renameTarget without the changed
        // suffix, since that's what must be propagated to the remote but the local
        // file may have a different name. folderTargetAlt will contain this potential
        // name.
        QString folderTargetAlt = folderTarget;
        if (itype == ItemTypeFile) {
            ASSERT(!sourceHadSuffix && !destinationHadSuffix);

            // If foo -> bar.owncloud, the rename target will be "bar"
            folderTargetAlt = folderTarget + suffix;

        } else if (itype == ItemTypeVirtualFile) {
            ASSERT(sourceHadSuffix && destinationHadSuffix);

            // If foo.owncloud -> bar, the rename target will be "bar.owncloud"
            folderTargetAlt.chop(suffix.size());
        }

        QString localTarget = propagator()->getFilePath(folderTarget);
        QString localTargetAlt = propagator()->getFilePath(folderTargetAlt);

        // If the expected target doesn't exist but a file with different hydration
        // state does, rename the local file to bring it in line with what the discovery
        // has set up.
        if (!FileSystem::fileExists(localTarget) && FileSystem::fileExists(localTargetAlt)) {
            QString error;
            if (!FileSystem::uncheckedRenameReplace(localTargetAlt, localTarget, &error)) {
                done(SyncFileItem::NormalError, tr("Could not rename %1 to %2, error: %3")
                     .arg(folderTargetAlt, folderTarget, error));
                return;
            }
            qCInfo(lcPropagateRemoteMove) << "Suffix vfs required local rename of"
                                          << folderTargetAlt << "to" << folderTarget;
        }
    }
    qCDebug(lcPropagateRemoteMove) << remoteSource << remoteDestination;

    _job = new MoveJob(propagator()->account(), remoteSource, remoteDestination, this);
    connect(_job.data(), &MoveJob::finishedSignal, this, &PropagateRemoteMove::slotMoveJobFinished);
    propagator()->_activeJobList.append(this);
    _job->start();
}
Пример #13
0
void
VolumeRGBBase::createLowresVolume(bool redo)
{
  //---------------
  int nRGB = 3;
  if (Global::volumeType() == Global::RGBAVolume)
    nRGB = 4;
  //---------------


  int px2, py2, pz2;
  px2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.x);
  py2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.y);
  pz2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.z);

  m_subSamplingLevel = 1;
  while (px2+py2+pz2 > qMin(26, Global::textureSize()-1)) // limit lowres volume size
    {
      m_subSamplingLevel *= 2;
      px2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.x/m_subSamplingLevel);
      py2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.y/m_subSamplingLevel);
      pz2 = StaticFunctions::getPowerOf2(m_fullVolumeSize.z/m_subSamplingLevel);
    }

  // max hardware texture size is 512x512x512
  if ((px2 > 9 || py2 > 9 || pz2 > 9) &&
      m_subSamplingLevel == 1)
    m_subSamplingLevel = 2;


  m_lowresVolumeSize = m_fullVolumeSize/m_subSamplingLevel;
  int height= m_lowresVolumeSize.x;
  int width = m_lowresVolumeSize.y;
  int depth = m_lowresVolumeSize.z;

  if (m_lowresVolume) delete [] m_lowresVolume;
  
  m_lowresVolume = new unsigned char[nRGB*height*width*depth];

  int slabSize = XmlHeaderFunctions::getSlabsizeFromHeader(m_volumeFile);
  QString rgbfile = m_volumeFile;
  rgbfile.chop(6);
  VolumeFileManager rgbaFileManager[4];
  QString rFilename = rgbfile + QString("red");
  QString gFilename = rgbfile + QString("green");
  QString bFilename = rgbfile + QString("blue");
  QString aFilename = rgbfile + QString("alpha");

  rgbaFileManager[0].setBaseFilename(rFilename);
  rgbaFileManager[1].setBaseFilename(gFilename);
  rgbaFileManager[2].setBaseFilename(bFilename);
  rgbaFileManager[3].setBaseFilename(aFilename);
  for(int a=0; a<nRGB; a++)
    {
      rgbaFileManager[a].setDepth(m_depth);
      rgbaFileManager[a].setWidth(m_width);
      rgbaFileManager[a].setHeight(m_height);
      rgbaFileManager[a].setHeaderSize(13);
      rgbaFileManager[a].setSlabSize(slabSize);
    }


  int nbytes = m_width*m_height;
  if (m_subSamplingLevel == 1)
    {
      uchar *tmp;
      tmp = new uchar [m_width*m_height];  
      for(int k=0; k<m_depth; k++)
	{
	  for (int a=0; a<nRGB; a++)
	    {
	      uchar *vslice = rgbaFileManager[a].getSlice(k);
	      memcpy(tmp, vslice, nbytes);

	      for (int j=0; j<m_width*m_height; j++)
		m_lowresVolume[nRGB*(k*m_width*m_height+j) + a] = tmp[j];
	    }
	}
    }
  else
    {
      int iend,jend,kend; 
      iend = height;
      jend = width;
      kend = depth;

      uchar *tmp;
      tmp = new uchar [m_width*m_height];

      int totcount = 2*m_subSamplingLevel-1;
      int count=0;
      uchar **volX;
      volX = 0;
      if (m_subSamplingLevel > 1)
	{
	  volX = new unsigned char*[totcount];
	  for(int i=0; i<totcount; i++)
	    volX[i] = new unsigned char[nRGB*jend*iend];
	}
      uchar *tmp1;
      ushort *tmp1i;
      tmp1 = new uchar [nRGB*jend*iend];
      tmp1i = new ushort [nRGB*jend*iend];

      MainWindowUI::mainWindowUI()->menubar->parentWidget()->		\
	setWindowTitle(QString("Generating Lowres Version"));
      Global::progressBar()->show();

      int kslc=0;
      for(int k=0; k<m_depth; k++)
	{
	  Global::progressBar()->setValue((int)(100.0*(float)k/(float)m_depth));
	  qApp->processEvents();
      
	  // box-filter and scaledown the slice
	  for (int a=0; a<nRGB; a++)
	    {
	      uchar *vslice = rgbaFileManager[a].getSlice(k);
	      memcpy(tmp, vslice, nbytes);

	      int ji=0;
	      for(int j=0; j<jend; j++)
		{ 
		  int y = j*m_subSamplingLevel;
		  int loy = qMax(0, y-m_subSamplingLevel+1);
		  int hiy = qMin(m_width-1, y+m_subSamplingLevel-1);
		  for(int i=0; i<iend; i++) 
		    { 
		      int x = i*m_subSamplingLevel; 
		      int lox = qMax(0, x-m_subSamplingLevel+1);
		      int hix = qMin(m_height-1, x+m_subSamplingLevel-1);
		      
		      float sum = 0;
		      for(int jy=loy; jy<=hiy; jy++) 
			{
			  for(int ix=lox; ix<=hix; ix++) 
			    {
			      int idx = jy*m_height+ix;
			      sum += tmp[idx];
			    }
			}
		      
		      tmp1[nRGB*ji+a] = sum/((hiy-loy+1)*(hix-lox+1)); 
		      
		      ji++;
		    } 
		}
	    }

	  unsigned char *vptr;
	  vptr = volX[0];
	  for (int c=0; c<totcount-1; c++)
	    volX[c] = volX[c+1];
	  volX[totcount-1] = vptr;
	  
	  memcpy(volX[totcount-1], tmp1, nRGB*jend*iend);
      
	  count ++;
	  if (count == totcount)
	    {
	      memset(tmp1i, 0, 2*nRGB*jend*iend);

	      for(int x=0; x<totcount; x++)
		for(int j=0; j<nRGB*jend*iend; j++)
		  tmp1i[j]+=volX[x][j];	      

	      for(int j=0; j<nRGB*jend*iend; j++)
		tmp1[j] = tmp1i[j]/totcount;
		  
	      memcpy(m_lowresVolume + kslc*nRGB*jend*iend,
		     tmp1,
		     nRGB*jend*iend);

	      count = totcount/2;		  
	      // increment slice number
	      kslc ++;
	    }
	}

      int actualdepth = StaticFunctions::getScaledown(m_subSamplingLevel, m_depth);
      if (actualdepth < depth)
	{
	  // replicate the data
	  for (int dd=actualdepth; dd<depth; dd++)
	    memcpy(m_lowresVolume + nRGB*dd*jend*iend,
		   m_lowresVolume + nRGB*(dd-1)*jend*iend,
		   nRGB*jend*iend);
	}

      
      delete [] tmp;
      delete [] tmp1;
      delete [] tmp1i;
      if (m_subSamplingLevel > 1)
	{
	  for(int i=0; i<totcount; i++)
	    delete [] volX[i];
	  delete [] volX;
	}      
    }
  Global::progressBar()->setValue(100);
  Global::hideProgressBar();
}
Пример #14
0
void
VolumeRGBBase::generateHistograms(bool redo)
{
  //---------------
  int nRGB = 3;
  if (Global::volumeType() == Global::RGBAVolume)
    nRGB = 4;
  //---------------

  memset(m_1dHistogramR, 0, 256*4);
  memset(m_2dHistogramR, 0, 256*256*4);
  memset(m_1dHistogramG, 0, 256*4);
  memset(m_2dHistogramG, 0, 256*256*4);
  memset(m_1dHistogramB, 0, 256*4);
  memset(m_2dHistogramB, 0, 256*256*4);
  memset(m_1dHistogramA, 0, 256*4);
  memset(m_2dHistogramA, 0, 256*256*4);


  float *flhist1DR, *flhist2DR;
  float *flhist1DG, *flhist2DG;
  float *flhist1DB, *flhist2DB;
  float *flhist1DA, *flhist2DA;

  flhist1DR = new float[256];       memset(flhist1DR, 0, 256*4);
  flhist2DR = new float[256*256];   memset(flhist2DR, 0, 256*256*4);
  flhist1DG = new float[256];       memset(flhist1DG, 0, 256*4);
  flhist2DG = new float[256*256];   memset(flhist2DG, 0, 256*256*4);
  flhist1DB = new float[256];       memset(flhist1DB, 0, 256*4);
  flhist2DB = new float[256*256];   memset(flhist2DB, 0, 256*256*4);
  if (nRGB == 4)
    {
      flhist1DA = new float[256];       memset(flhist1DA, 0, 256*4);
      flhist2DA = new float[256*256];   memset(flhist2DA, 0, 256*256*4);
    }
  //----------------------------- process data ------------------------
  uchar *tmp[3];
  tmp[0] = new unsigned char [m_width*m_height];  
  tmp[1] = new unsigned char [m_width*m_height];  
  tmp[2] = new unsigned char [m_width*m_height];  
  if (nRGB==4)
    tmp[3] = new unsigned char [m_width*m_height];  



  int slabSize = XmlHeaderFunctions::getSlabsizeFromHeader(m_volumeFile);
  QString rgbfile = m_volumeFile;
  rgbfile.chop(6);
  VolumeFileManager rgbaFileManager[4];
  QString rFilename = rgbfile + QString("red");
  QString gFilename = rgbfile + QString("green");
  QString bFilename = rgbfile + QString("blue");
  QString aFilename = rgbfile + QString("alpha");

  rgbaFileManager[0].setBaseFilename(rFilename);
  rgbaFileManager[1].setBaseFilename(gFilename);
  rgbaFileManager[2].setBaseFilename(bFilename);
  rgbaFileManager[3].setBaseFilename(aFilename);
  for(int a=0; a<nRGB; a++)
    {
      rgbaFileManager[a].setDepth(m_depth);
      rgbaFileManager[a].setWidth(m_width);
      rgbaFileManager[a].setHeight(m_height);
      rgbaFileManager[a].setHeaderSize(13);
      rgbaFileManager[a].setSlabSize(slabSize);
    }


  MainWindowUI::mainWindowUI()->menubar->parentWidget()->\
    setWindowTitle(QString("Reading Volume"));
  Global::progressBar()->show();

  int nbytes = m_width*m_height;
  for(int k=0; k<m_depth; k++)
    {
      Global::progressBar()->setValue((int)((float)k/(float)m_depth));
      qApp->processEvents();
      for (int a=0; a<nRGB; a++)
	{
	  uchar *vslice = rgbaFileManager[a].getSlice(k);
	  memcpy(tmp[a], vslice, nbytes);
	}

      for (int j=0; j<m_width*m_height; j++)
	{
	  uchar r = tmp[0][j];
	  uchar g = tmp[1][j];
	  uchar b = tmp[2][j];

	  flhist1DR[r]++; flhist2DR[g*256 + r]++;
	  flhist1DG[g]++; flhist2DG[b*256 + g]++;
	  flhist1DB[b]++; flhist2DB[r*256 + b]++;

	  if (nRGB == 4)
	    {
	      uchar a = tmp[3][j];
	      uchar rgb = qMax(r, qMax(g, b));
	      flhist1DA[a]++; flhist2DA[rgb*256 + a]++;
	    }
	}
    }

  Global::progressBar()->setValue(100);
  Global::hideProgressBar();

  delete [] tmp[0];
  delete [] tmp[1];
  delete [] tmp[2];
  if (nRGB == 4)
    delete [] tmp[3];

  StaticFunctions::generateHistograms(flhist1DR, flhist2DR,
				      m_1dHistogramR, m_2dHistogramR);

  StaticFunctions::generateHistograms(flhist1DG, flhist2DG,
				      m_1dHistogramG, m_2dHistogramG);

  StaticFunctions::generateHistograms(flhist1DB, flhist2DB,
				      m_1dHistogramB, m_2dHistogramB);

  if (nRGB == 4)
    StaticFunctions::generateHistograms(flhist1DA, flhist2DA,
					m_1dHistogramA, m_2dHistogramA);
  delete [] flhist1DR;
  delete [] flhist2DR;
  delete [] flhist1DG;
  delete [] flhist2DG;
  delete [] flhist1DB;
  delete [] flhist2DB;
  if (nRGB == 4)
    {
      delete [] flhist1DA;
      delete [] flhist2DA;
    }
}
Пример #15
0
void Ui3Reader::createWrapperDeclContents(const QDomElement &e)
{
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;

    QDomNodeList nl;
    QString exportMacro;
    int i;
    QDomElement n;
    QStringList::ConstIterator it;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("exportmacro"));
    if (nl.length() == 1)
        exportMacro = nl.item(0).firstChild().toText().data();

    QStringList::ConstIterator ns = namespaces.constBegin();
    while (ns != namespaces.constEnd()) {
        out << "namespace " << *ns << " {" << endl;
        ++ns;
    }

    out << "class ";
    if (!exportMacro.isEmpty())
        out << exportMacro << ' ';
    out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << '{' << endl;

    /* qmake ignore Q_OBJECT */
    out << "    Q_OBJECT" << endl;
    out << endl;
    out << "public:" << endl;

    // constructor
    if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, bool modal = false, Qt::WindowFlags fl = 0);" << endl;
    } else if (objClass == QLatin1String("QWidget")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0);" << endl;
    } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = Qt::WType_TopLevel);" << endl;
        isMainWindow = true;
    } else {
        out << "    " << bareNameOfClass << "(QWidget* parent = 0, const char* name = 0);" << endl;
    }

    // destructor
    out << "    ~" << bareNameOfClass << "();" << endl;
    out << endl;

    // database connections
    dbConnections = unique(dbConnections);
    bool hadOutput = false;
    for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) {
        if (!(*it).isEmpty()) {
            // only need pointers to non-default connections
            if ((*it) != QLatin1String("(default)") && !(*it).isEmpty()) {
                out << indent << "QSqlDatabase* " << *it << "Connection;" << endl;
                hadOutput = true;
            }
        }
    }
    if (hadOutput)
        out << endl;

    QStringList publicSlots, protectedSlots, privateSlots;
    QStringList publicSlotTypes, protectedSlotTypes, privateSlotTypes;
    QStringList publicSlotSpecifier, protectedSlotSpecifier, privateSlotSpecifier;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("slots")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        QString specifier = n.attribute(QLatin1String("specifier"));
        QString access = n.attribute(QLatin1String("access"));
        if (access == QLatin1String(QLatin1String("protected"))) {
            protectedSlots += functionName;
            protectedSlotTypes += returnType;
            protectedSlotSpecifier += specifier;
        } else if (access == QLatin1String("private")) {
            privateSlots += functionName;
            privateSlotTypes += returnType;
            privateSlotSpecifier += specifier;
        } else {
            publicSlots += functionName;
            publicSlotTypes += returnType;
            publicSlotSpecifier += specifier;
        }
    }

    QStringList publicFuncts, protectedFuncts, privateFuncts;
    QStringList publicFunctRetTyp, protectedFunctRetTyp, privateFunctRetTyp;
    QStringList publicFunctSpec, protectedFunctSpec, privateFunctSpec;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("functions"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        QString specifier = n.attribute(QLatin1String("specifier"));
        QString access = n.attribute(QLatin1String("access"));
        if (access == QLatin1String("protected")) {
            protectedFuncts += functionName;
            protectedFunctRetTyp += returnType;
            protectedFunctSpec += specifier;
        } else if (access == QLatin1String("private")) {
            privateFuncts += functionName;
            privateFunctRetTyp += returnType;
            privateFunctSpec += specifier;
        } else {
            publicFuncts += functionName;
            publicFunctRetTyp += returnType;
            publicFunctSpec += specifier;
        }
    }

    QStringList publicVars, protectedVars, privateVars;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("variable"));
    for (i = 0; i < (int)nl.length(); i++) {
        n = nl.item(i).toElement();
        // Because of compatibility the next lines have to be commented out.
        // Someday it should be uncommented.
        //if (n.parentNode().toElement().tagName() != QLatin1String("variables"))
        //    continue;
        QString access = n.attribute(QLatin1String("access"), QLatin1String("protected"));
        QString var = fixDeclaration(n.firstChild().toText().data().trimmed());
        if (!var.endsWith(QLatin1Char(';')))
            var += QLatin1Char(';');
        if (access == QLatin1String("public"))
            publicVars += var;
        else if (access == QLatin1String("private"))
            privateVars += var;
        else
            protectedVars += var;
    }

    if (!publicVars.isEmpty()) {
        for (it = publicVars.constBegin(); it != publicVars.constEnd(); ++it)
            out << indent << *it << endl;
        out << endl;
    }
    if (!publicFuncts.isEmpty())
        writeFunctionsDecl(publicFuncts, publicFunctRetTyp, publicFunctSpec);

    if (!publicSlots.isEmpty()) {
        out << "public slots:" << endl;
        if (!publicSlots.isEmpty())
            writeFunctionsDecl(publicSlots, publicSlotTypes, publicSlotSpecifier);
    }

    // find signals
    QStringList extraSignals;
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("signal"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("signals")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString sigName = n.firstChild().toText().data().trimmed();
        if (sigName.endsWith(QLatin1Char(';')))
            sigName = sigName.left(sigName.length() - 1);
        extraSignals += fixDeclaration(sigName);
    }

    // create signals
    if (!extraSignals.isEmpty()) {
        out << "signals:" << endl;
        for (it = extraSignals.constBegin(); it != extraSignals.constEnd(); ++it)
            out << "    void " << (*it) << ';' << endl;
        out << endl;
    }

    if (!protectedVars.isEmpty()) {
        out << "protected:" << endl;
        for (it = protectedVars.constBegin(); it != protectedVars.constEnd(); ++it)
            out << indent << *it << endl;
        out << endl;
    }

    if (!protectedFuncts.isEmpty()) {
        if (protectedVars.isEmpty())
            out << "protected:" << endl;

        writeFunctionsDecl(protectedFuncts, protectedFunctRetTyp, protectedFunctSpec);
    }

    out << "protected slots:" << endl;
    out << "    virtual void languageChange();" << endl;

    if (!protectedSlots.isEmpty()) {
        out << endl;
        writeFunctionsDecl(protectedSlots, protectedSlotTypes, protectedSlotSpecifier);
    }
    out << endl;

    // create all private stuff
    if (!privateFuncts.isEmpty() || !privateVars.isEmpty()) {
        out << "private:" << endl;
        if (!privateVars.isEmpty()) {
            for (it = privateVars.constBegin(); it != privateVars.constEnd(); ++it)
                out << indent << *it << endl;
            out << endl;
        }
        if (!privateFuncts.isEmpty())
            writeFunctionsDecl(privateFuncts, privateFunctRetTyp, privateFunctSpec);
    }

    if (!privateSlots.isEmpty()) {
        out << "private slots:" << endl;
        writeFunctionsDecl(privateSlots, privateSlotTypes, privateSlotSpecifier);
    }

    out << "};" << endl;
    for (i = 0; i < (int) namespaces.count(); i++)
        out << '}' << endl;

    out << endl;
}
Пример #16
0
void installWorker::process() {
    p = new QProcess(this);
    //p->setProcessChannelMode(QProcess::MergedChannels);
    connect(p, SIGNAL(finished(int)), this, SLOT(lastProcessFinished(int)));
    connect(p, SIGNAL(readyReadStandardOutput()), this, SLOT(outputAvaliable()));
    connect(p, SIGNAL(readyReadStandardError()), this, SLOT(errorAvaliable()));

    standardOutput.append("[theos_installer] Executing command umount /mnt\n");
    emit output(standardOutput);

    p->start("umount", QStringList() << "/mnt");
    p->waitForFinished(-1);

    if (parentWindow->formatPartition) {
        lastProcessDone = false;
        emit message("Formatting " + parentWindow->partition + "...");

        standardOutput.append("[theos_installer] Executing command mkfs -t ext4 -F -F " + parentWindow->partition);
        p->start("mkfs -t ext4 -F -F " + parentWindow->partition);
        if (!p->waitForStarted()) {
            standardOutput.append("[theos_installer] Error occurred executing command!\n");
        }

        p->waitForFinished(-1);
    }

    emit message("Mounting " + parentWindow->partition + "...");
    standardOutput.append("[theos_installer] Executing command mount " + parentWindow->partition + " /mnt\n");
    emit output(standardOutput);

    p->start("mount " + parentWindow->partition + " /mnt");
    p->waitForFinished(-1);

    if (QDir("/sys/firmware/efi").exists()) {
        standardOutput.append("This system is EFI, attempting to mount ESP onto /boot\n");
        emit output(standardOutput);

        QProcess* lsblk = new QProcess();
        lsblk->start("lsblk -r --output NAME,PARTTYPE");
        lsblk->waitForStarted(-1);
        lsblk->waitForFinished(-1);

        QString lsblkOutput(lsblk->readAllStandardOutput());

        for (QString partition : lsblkOutput.split("\n")) {
            if (partition.split(" ").count() != 1) {
                if (partition.split(" ").at(1).contains("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", Qt::CaseInsensitive)) {
                    QDir("/mnt").mkdir("boot");

                    emit message("Mounting " + partition.split(" ").at(0) + "...");
                    standardOutput.append("[theos_installer] Executing command mount " + parentWindow->partition + " /mnt/boot\n");
                    emit output(standardOutput);


                    p->start("mount /dev/" + partition.split(" ").at(0) + " /mnt/boot");
                    p->waitForFinished(-1);
                    break;
                }
            }
        }


    }

    emit message("Downloading and copying new files...");
    standardOutput.append("[theos_installer] Executing command pacstrap /mnt base base-devel linux-headers\n");
    emit output(standardOutput);

    p->start("pacstrap /mnt base base-devel linux-headers");
    p->waitForFinished(-1);
    if (p->exitCode() != 0) {
        emit message("An error occurred. Inspect the output to see what happened.");
        emit failed();
        return;
    }

    emit message("Configuring system...");
    standardOutput.append("[theos_installer] Generating fstab...\n");
    emit output(standardOutput);
    QProcess *fstab = new QProcess(this);
    fstab->start("genfstab -p /mnt");
    fstab->waitForFinished();

    QFile fstabFile("/mnt/etc/fstab");
    fstabFile.open(QFile::WriteOnly);
    fstabFile.write(fstab->readAllStandardOutput());
    fstabFile.close();

    standardOutput.append("[theos_installer] Setting hostname...\n");

    while (parentWindow->hostname == "") {} //Stall until hostname is ready

    QFile hostnameFile("/mnt/etc/hostname");
    hostnameFile.open(QFile::WriteOnly);
    hostnameFile.write(parentWindow->hostname.toUtf8());
    hostnameFile.close();

    standardOutput.append("[theos_installer] Generating locales...\n");
    QFile::copy("/etc/locale.gen", "/mnt/etc/locale.gen");

    standardOutput.append("[theos_installer] Executing command arch-chroot /mnt locale-gen \n");
    emit output(standardOutput);

    p->start("arch-chroot /mnt locale-gen");
    p->waitForFinished(-1);


    standardOutput.append("[theos_installer] Executing command arch-chroot /mnt mkinitcpio -p linux\n");
    emit output(standardOutput);

    p->start("arch-chroot /mnt mkinitcpio -p linux");
    p->waitForFinished(-1);

    emit message("Downloading and installing bootloader...");


    standardOutput.append("[theos_installer] Executing command pacstrap /mnt os-prober grub\n");
    emit output(standardOutput);

    p->start("pacstrap /mnt os-prober efibootmgr grub");
    p->waitForFinished(-1);

    QString disk = parentWindow->partition;
    disk.chop(1);

    if (QDir("/sys/firmware/efi").exists()) {
        standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-install --target=x86_64-efi --efi-directory=/boot/ --bootloader-id=grub\n");

        p->start("arch-chroot /mnt grub-install --target=x86_64-efi --efi-directory=/boot/ --bootloader-id=grub");
        p->waitForFinished(-1);
    } else {
        standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-install --target=i386-pc " + disk + "\n");
        emit output(standardOutput);
        p->start("arch-chroot /mnt grub-install --target=i386-pc " + disk);
        p->waitForFinished(-1);
    }

    QFile grubDefault("/mnt/etc/default/grub");
    grubDefault.open(QFile::ReadOnly);
    QString grubDefaults(grubDefault.readAll());
    grubDefault.close();

    QStringList grubDefaultsArray = grubDefaults.split("\n");
    for (QString line : grubDefaultsArray) {
        if (line.startsWith("GRUB_CMDLINE_LINUX_DEFAULT")) {
            int index = grubDefaultsArray.indexOf(line);
            grubDefaultsArray.removeAt(index);
            grubDefaultsArray.insert(index, "GRUB_CMDLINE_LINUX_DEFAULT=\"quiet splash\"");
        }
    }

    grubDefaults = "";
    for (QString line : grubDefaultsArray) {
        grubDefaults.append(line + "\n");
    }
    p->waitForFinished(-1);

    grubDefault.open(QFile::WriteOnly);
    grubDefault.write(grubDefaults.toUtf8());
    grubDefault.close();

    standardOutput.append("[theos_installer] Executing command arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg\n");
    emit output(standardOutput);

    p->start("arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg");
    p->waitForFinished(-1);

    QFile grubConfig("/mnt/boot/grub/grub.cfg");
    grubConfig.open(QFile::ReadWrite);
    QString grubConfiguration(grubConfig.readAll());
    grubConfig.close();
    grubConfiguration = grubConfiguration.replace("Arch Linux", "theOS");
    grubConfig.open(QFile::ReadWrite);
    grubConfig.write(grubConfiguration.toUtf8());
    grubConfig.close();

    emit message("Downloading and installing new files...");
    standardOutput.append("[theos_installer] Installing additional packages...\n");
    emit output(standardOutput);

    p->start(QString("pacstrap /mnt xf86-video-vesa xf86-video-intel xf86-video-nouveau xf86-video-vmware kde-cli-tools kdesu")
             .append(" virtualbox-guest-utils xorg-server xorg-xinit xf86-input-synaptics lightdm breeze breeze-gtk breeze-icons")
             .append(" breeze-kde4 networkmanager gtk3 breeze-gtk chromium kinfocenter partitionmanager ntfs-3g")
             .append(" hfsprogs kate bluez bluedevil libreoffice-fresh hunspell hunspell-en kdegraphics-okular")
             .append(" ksuperkey kscreen user-manager kdeconnect gstreamer0.10 gstreamer0.10-bad gstreamer0.10-plugins")
             .append(" gstreamer0.10-base gstreamer0.10-base-plugins gstreamer0.10-ffmpeg gstreamer0.10-good")
             .append(" gstreamer0.10-good-plugins gstreamer0.10-ugly gstreamer0.10-ugly-plugins gst-plugins-good")
             .append(" gst-plugins-ugly kmail korganizer cups ark kcalc gwenview alsa-utils pulseaudio pulseaudio-alsa festival festival-english"));
    p->waitForFinished(-1);

    QDir localPackagesDir("/root/.packages/");
    QDirIterator *packageIterator = new QDirIterator(localPackagesDir);
    while (packageIterator->hasNext()) {
        QString packageName = packageIterator->next();
        QString packageToInstall = packageName;
        QString installLocation = "/mnt/var/cache/pacman/pkg/" + packageName.remove("/root/.packages/");
        if (!QFile::copy(packageToInstall, installLocation)) {
            standardOutput.append("[theos_installer] Error copying " + packageToInstall + " to " + installLocation);
            emit output(standardOutput);
        }
        p->start("arch-chroot /mnt pacman -U --noconfirm " + installLocation.remove(0, 4));
        p->waitForFinished(-1);
    }

    emit message("Configuring System...");
    standardOutput.append("[theos_installer] Configuring users...\n");

    QFile chfnDefault("/mnt/etc/login.defs");
    chfnDefault.open(QFile::ReadOnly);
    QString chfnDefaults(chfnDefault.readAll());
    chfnDefault.close();

    QStringList chfnDefaultsArray = chfnDefaults.split("\n");
    for (QString line : chfnDefaultsArray) {
        if (line.startsWith("CHFN_RESTRICT")) {
            int index = chfnDefaultsArray.indexOf(line);
            chfnDefaultsArray.removeAt(index);
            chfnDefaultsArray.insert(index, "CHFN_RESTRICT           frwh");
        }
    }

    chfnDefaults = "";
    for (QString line : chfnDefaultsArray) {
        chfnDefaults.append(line + "\n");
    }

    chfnDefault.open(QFile::WriteOnly);
    chfnDefault.write(chfnDefaults.toUtf8());
    chfnDefault.close();

    p->start("useradd -R /mnt -g wheel -M " + parentWindow->loginname);
    p->waitForFinished(-1);

    p->start("arch-chroot /mnt chfn -f \"" + parentWindow->fullname + "\" " + parentWindow->loginname);
    p->waitForFinished(-1);

    p->start("chpasswd -R /mnt");
    p->write(QString("root:" + parentWindow->password + "\n").toUtf8());
    p->write(QString(parentWindow->loginname + ":" + parentWindow->password + "\n").toUtf8());
    p->closeWriteChannel();
    p->waitForFinished(-1);

    QFile sudoersConfig("/mnt/etc/sudoers");
    sudoersConfig.open(QFile::ReadWrite);
    QString sudoersConfiguration(sudoersConfig.readAll());
    sudoersConfig.close();
    sudoersConfiguration = sudoersConfiguration.replace("# %wheel ALL=(ALL) ALL", "%wheel ALL=(ALL) ALL");
    sudoersConfig.open(QFile::ReadWrite);
    sudoersConfig.write(sudoersConfiguration.toUtf8());
    sudoersConfig.close();

    standardOutput.append("[theos_installer] Configuring services...\n");
    p->start("arch-chroot /mnt systemctl enable NetworkManager");
    p->waitForFinished(-1);
    p->start("arch-chroot /mnt systemctl enable bluetooth");
    p->waitForFinished(-1);
    p->start("arch-chroot /mnt systemctl enable lightdm");
    p->waitForFinished(-1);

    QFile lightdmConf("/mnt/etc/lightdm/lightdm.conf");
    lightdmConf.open(QFile::ReadOnly);
    QString lightdmDefaults(lightdmConf.readAll());
    lightdmConf.close();

    QStringList lightdmDefaultsArray = lightdmDefaults.split("\n");
    for (QString line : lightdmDefaultsArray) {
        if (line.startsWith("#greeter-session=")) {
            int index = lightdmDefaultsArray.indexOf(line);
            lightdmDefaultsArray.removeAt(index);
            lightdmDefaultsArray.insert(index, "greeter-session=lightdm-webkit2-greeter");
        }
    }

    lightdmDefaults = "";
    for (QString line : lightdmDefaultsArray) {
        lightdmDefaults.append(line + "\n");
    }

    lightdmConf.open(QFile::WriteOnly);
    lightdmConf.write(lightdmDefaults.toUtf8());
    lightdmConf.close();

    QFile lightdmWebkitConf("/mnt/etc/lightdm/lightdm-webkit2-greeter.conf");
    lightdmWebkitConf.open(QFile::WriteOnly);
    lightdmWebkitConf.write(QString("[greeter]\nwebkit-theme=contemporary\n").toUtf8());
    lightdmWebkitConf.close();

    QFile initConf("/mnt/etc/mkinitcpio.conf");
    initConf.open(QFile::ReadOnly);
    QString init(initConf.readAll());
    initConf.close();

    QStringList initArray = init.split("\n");
    for (QString line : initArray) {
        if (line.startsWith("HOOKS")) {
            int index = initArray.indexOf(line);
            initArray.removeAt(index);
            initArray.insert(index, "HOOKS=\"base udev plymouth autodetect modconf block filesystems keyboard fsck\"");
        } else if (line.startsWith("MODULES")) {
            int index = initArray.indexOf(line);
            initArray.removeAt(index);
            initArray.insert(index, "MODULES=\"i915\"");
        }
    }

    init = "";
    for (QString line : initArray) {
        init.append(line + "\n");
    }

    initConf.open(QFile::WriteOnly);
    initConf.write(init.toUtf8());
    initConf.close();

    QFile("/etc/os-release").copy("/mnt/etc/os-release");

    p->start("arch-chroot /mnt plymouth-set-default-theme theos --rebuild-initrd" );
    p->waitForFinished(-1);

    p->start("cp -r /root /mnt/home/" + parentWindow->loginname);
    p->waitForFinished(-1);
    p->start("arch-chroot /mnt chown -R " + parentWindow->loginname + " /home/" + parentWindow->loginname + "/ " );
    p->waitForFinished(-1);

    emit finished();
}
Пример #17
0
/*!
  Creates an implementation (cpp-file) for the form given in \a e.

  \sa createFormDecl(), createObjectImpl()
 */
void Ui3Reader::createFormImpl(const QDomElement &e)
{
    QDomElement n;
    QDomNodeList nl;
    int i;
    QString objClass = getClassName(e);
    if (objClass.isEmpty())
        return;
    QString objName = getObjectName(e);

    // generate local and local includes required
    QStringList globalIncludes, localIncludes;
    QStringList::Iterator it;

    QMap<QString, CustomInclude> customWidgetIncludes;

    // find additional slots and functions
    QStringList extraFuncts;
    QStringList extraFunctTyp;
    QStringList extraFunctSpecifier;

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("slot"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("slots")
             && n.parentNode().toElement().tagName() != QLatin1String("connections"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        extraFuncts += functionName;
        extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual"));
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("function"));
    for (i = 0; i < (int) nl.length(); i++) {
        n = nl.item(i).toElement();
        if (n.parentNode().toElement().tagName() != QLatin1String("functions"))
            continue;
        if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++"))
            continue;
        QString functionName = n.firstChild().toText().data().trimmed();
        if (functionName.endsWith(QLatin1Char(';')))
            functionName.chop(1);
        extraFuncts += functionName;
        extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void"));
        extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual"));
    }

    // additional includes (local or global) and forward declaractions
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("include"));
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) != QLatin1String("local")) {
            if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s))
                continue;
            if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation"))
                continue;
            globalIncludes += s;
        }
    }

    registerDatabases(e);
    dbConnections = unique(dbConnections);
    bool dbForm = false;
    if (dbForms[QLatin1String("(default)")].count())
        dbForm = true;
    bool subDbForms = false;
    for (it = dbConnections.begin(); it != dbConnections.end(); ++it) {
        if (!(*it).isEmpty()  && (*it) != QLatin1String("(default)")) {
            if (dbForms[(*it)].count()) {
                subDbForms = true;
                break;
            }
        }
    }

    // do the local includes afterwards, since global includes have priority on clashes
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) == QLatin1String("local") && !globalIncludes.contains(s)) {
            if (s.right(5) == QLatin1String(".ui.h") && !QFile::exists(s))
                continue;
            if (n2.attribute(QLatin1String("impldecl"), QLatin1String("in implementation")) != QLatin1String("in implementation"))
                continue;
            localIncludes += s;
        }
    }

    // additional custom widget headers
    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("header"));
    for (i = 0; i < (int) nl.length(); i++) {
        QDomElement n2 = nl.item(i).toElement();
        QString s = n2.firstChild().toText().data();
        if (n2.attribute(QLatin1String("location")) != QLatin1String("local"))
            globalIncludes += s;
        else
            localIncludes += s;
    }

    out << "#include <qvariant.h>" << endl; // first for gcc 2.7.2

    globalIncludes = unique(globalIncludes);
    for (it = globalIncludes.begin(); it != globalIncludes.end(); ++it) {
        if (!(*it).isEmpty())
            out << "#include <" << fixHeaderName(*it) << '>' << endl;
    }

    if (externPixmaps) {
        out << "#include <qimage.h>" << endl;
        out << "#include <qpixmap.h>" << endl << endl;
    }

    /*
      Put local includes after all global includes
    */
    localIncludes = unique(localIncludes);
    for (it = localIncludes.begin(); it != localIncludes.end(); ++it) {
        if (!(*it).isEmpty() && *it != QFileInfo(fileName + QLatin1String(".h")).fileName())
            out << "#include \"" << fixHeaderName(*it) << '\"' << endl;
    }

    QString uiDotH = fileName + QLatin1String(".h");
    if (QFile::exists(uiDotH)) {
        if (!outputFileName.isEmpty())
            uiDotH = QString::fromUtf8(combinePath(uiDotH.ascii(), outputFileName.ascii()));
        out << "#include \"" << uiDotH << '\"' << endl;
        writeFunctImpl = false;
    }

    // register the object and unify its name
    objName = registerObject(objName);

    if (externPixmaps) {
        pixmapLoaderFunction = QLatin1String("QPixmap::fromMimeSource");
    }

    // constructor
    if (objClass == QLatin1String("QDialog") || objClass == QLatin1String("QWizard")) {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " *" << endl;
        out << " *  The " << objClass.mid(1).toLower() << " will by default be modeless, unless you set 'modal' to" << endl;
        out << " *  true to construct a modal " << objClass.mid(1).toLower() << '.' << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, modal, fl)";
    } else if (objClass == QLatin1String("QWidget"))  {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, fl)";
    } else if (objClass == QLatin1String("QMainWindow") || objClass == QLatin1String("Q3MainWindow")) {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " as a child of 'parent', with the" << endl;
        out << " *  name 'name' and widget flags set to 'f'." << endl;
        out << " *" << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, Qt::WindowFlags fl)" << endl;
        out << "    : " << objClass << "(parent, name, fl)";
        isMainWindow = true;
    } else {
        out << "/*" << endl;
        out << " *  Constructs a " << nameOfClass << " which is a child of 'parent', with the" << endl;
        out << " *  name 'name'.' " << endl;
        out << " */" << endl;
        out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name)" << endl;
        out << "    : " << objClass << "(parent, name)";
    }

    out << endl;

    out << '{' << endl;

//
// setup the gui
//
    out << indent << "setupUi(this);" << endl << endl;


    if (isMainWindow)
        out << indent << "(void)statusBar();" << endl;

    // database support
    dbConnections = unique(dbConnections);
    if (dbConnections.count())
        out << endl;
    for (it = dbConnections.begin(); it != dbConnections.end(); ++it) {
        if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) {
            out << indent << (*it) << "Connection = QSqlDatabase::database(\"" <<(*it) << "\");" << endl;
        }
    }

    nl = e.parentNode().toElement().elementsByTagName(QLatin1String("widget"));
    for (i = 1; i < (int) nl.length(); i++) { // start at 1, 0 is the toplevel widget
        n = nl.item(i).toElement();
        QString s = getClassName(n);
        if ((dbForm || subDbForms) && (s == QLatin1String("QDataBrowser") || s == QLatin1String("QDataView"))) {
            QString objName = getObjectName(n);
            QString tab = getDatabaseInfo(n, QLatin1String("table"));
            QString con = getDatabaseInfo(n, QLatin1String("connection"));
            out << indent << "QSqlForm* " << objName << "Form = new QSqlForm(this);" << endl;
            out << indent << objName << "Form->setObjectName(\"" << objName << "Form\");" << endl;
            QDomElement n2;
            for (n2 = n.firstChild().toElement(); !n2.isNull(); n2 = n2.nextSibling().toElement())
                createFormImpl(n2, objName, con, tab);
            out << indent << objName << "->setForm(" << objName << "Form);" << endl;
        }
    }

    if (extraFuncts.contains(QLatin1String("init()")))
        out << indent << "init();" << endl;

    // end of constructor
    out << '}' << endl;
    out << endl;

    // destructor
    out << "/*" << endl;
    out << " *  Destroys the object and frees any allocated resources" << endl;
    out << " */" << endl;
    out << nameOfClass << "::~" << bareNameOfClass << "()" << endl;
    out << '{' << endl;
    if (extraFuncts.contains(QLatin1String("destroy()")))
        out << indent << "destroy();" << endl;
    out << indent << "// no need to delete child widgets, Qt does it all for us" << endl;
    out << '}' << endl;
    out << endl;

    // handle application events if required
    bool needFontEventHandler = false;
    bool needSqlTableEventHandler = false;
    bool needSqlDataBrowserEventHandler = false;
    nl = e.elementsByTagName(QLatin1String("widget"));
    for (i = 0; i < (int) nl.length(); i++) {
        if (!DomTool::propertiesOfType(nl.item(i).toElement() , QLatin1String("font")).isEmpty())
            needFontEventHandler = true;
        QString s = getClassName(nl.item(i).toElement());
        if (s == QLatin1String("QDataTable") || s == QLatin1String("QDataBrowser")) {
            if (!isFrameworkCodeGenerated(nl.item(i).toElement()))
                 continue;
            if (s == QLatin1String("QDataTable"))
                needSqlTableEventHandler = true;
            if (s == QLatin1String("QDataBrowser"))
                needSqlDataBrowserEventHandler = true;
        }
        if (needFontEventHandler && needSqlTableEventHandler && needSqlDataBrowserEventHandler)
            break;
    }

    out << "/*" << endl;
    out << " *  Sets the strings of the subwidgets using the current" << endl;
    out << " *  language." << endl;
    out << " */" << endl;
    out << "void " << nameOfClass << "::languageChange()" << endl;
    out << '{' << endl;
    out << "    retranslateUi(this);" << endl;
    out << '}' << endl;
    out << endl;

    // create stubs for additional slots if necessary
    if (!extraFuncts.isEmpty() && writeFunctImpl) {
        it = extraFuncts.begin();
        QStringList::Iterator it2 = extraFunctTyp.begin();
        QStringList::Iterator it3 = extraFunctSpecifier.begin();
        while (it != extraFuncts.end()) {
            QString type = fixDeclaration(*it2);
            if (type.isEmpty())
                type = QLatin1String("void");
            type = type.simplified();
            QString fname = fixDeclaration(Parser::cleanArgs(*it));
            if (!(*it3).startsWith(QLatin1String("pure"))) { // "pure virtual" or "pureVirtual"
                out << type << ' ' << nameOfClass << "::" << fname << endl;
                out << '{' << endl;
                if (*it != QLatin1String("init()") && *it != QLatin1String("destroy()")) {
                    QRegExp numeric(QLatin1String("^(?:signed|unsigned|u?char|u?short|u?int"
                                     "|u?long|Q_U?INT(?:8|16|32)|Q_U?LONG|float"
                                     "|double)$"));
                    QString retVal;

                    /*
                      We return some kind of dummy value to shut the
                      compiler up.

                      1.  If the type is 'void', we return nothing.

                      2.  If the type is 'bool', we return 'false'.

                      3.  If the type is 'unsigned long' or
                          'quint16' or 'double' or similar, we
                          return '0'.

                      4.  If the type is 'Foo *', we return '0'.

                      5.  If the type is 'Foo &', we create a static
                          variable of type 'Foo' and return it.

                      6.  If the type is 'Foo', we assume there's a
                          default constructor and use it.
                    */
                    if (type != QLatin1String("void")) {
                        QStringList toks = type.split(QLatin1String(" "));
                        bool isBasicNumericType =
                                (toks.filter(numeric).count() == toks.count());

                        if (type == QLatin1String("bool")) {
                            retVal = QLatin1String("false");
                        } else if (isBasicNumericType || type.endsWith(QLatin1Char('*'))) {
                            retVal = QLatin1String("0");
                        } else if (type.endsWith(QLatin1Char('&'))) {
                            do {
                                type.chop(1);
                            } while (type.endsWith(QLatin1Char(' ')));
                            retVal = QLatin1String("uic_temp_var");
                            out << indent << "static " << type << ' ' << retVal << ';' << endl;
                        } else {
                            retVal = type + QLatin1String("()");
                        }
                    }

                    out << indent << "qWarning(\"" << nameOfClass << "::" << fname << ": Not implemented yet\");" << endl;
                    if (!retVal.isEmpty())
                        out << indent << "return " << retVal << ';' << endl;
                }
                out << '}' << endl;
                out << endl;
            }
            ++it;
            ++it2;
            ++it3;
        }
    }
}
Пример #18
0
QString QMailComposerInterface::key() const
{
    QString val = metaObject()->className();
    val.chop(9); // remove trailing "Interface"
    return val;
}
QString TPrototypeAjaxHelper::optionsToString(const TOption &options) const
{
    QString string;

    // Adds authenticity_token
    TOption opt(options);
    QVariantMap map;
    QVariant v = opt[Tf::Parameters];
    if (v.isValid() && v.canConvert(QVariant::Map)) {
        map = v.toMap();
    }
    map.insert("authenticity_token", actionView()->authenticityToken());
    opt.insert(Tf::Parameters, map);

    for (QMapIterator<int, QVariant> i(opt); i.hasNext(); ) {
        i.next();

        // Appends ajax option
        QString s = stringOptionHash()->value(i.key());
        if (!s.isEmpty() && i.value().canConvert(QVariant::String)) {
            string += s;
            string += QLatin1Char('\'');
            string += i.value().toString();
            string += QLatin1String("', ");
            continue;
        }

        s = boolOptionHash()->value(i.key());
        if (!s.isEmpty() && i.value().canConvert(QVariant::Bool)) {
            string += s;
            string += (i.value().toBool()) ? QLatin1String("true, ") : QLatin1String("false, ");
            continue;
        }

        if (i.key() == Tf::Method && i.value().canConvert(QVariant::Int)) {
            string += QLatin1String("method:'");
            string += methodHash()->value(i.value().toInt());
            string += QLatin1String("', ");
            continue;
        }

        // Appends 'parameters' option
        if (i.key() == Tf::Parameters) {
            QString val;
            if (i.value().canConvert(QVariant::Map)) {
                QVariantMap m = i.value().toMap();
                for (QMapIterator<QString, QVariant> it(m); it.hasNext(); ) {
                    it.next();
                    if (it.value().canConvert<TJavaScriptObject>()) {
                        val += it.key();
                        val += QLatin1String(":");
                        val += it.value().value<TJavaScriptObject>().toString();
                        val += QLatin1String(", ");
                    } else if (it.value().canConvert(QVariant::String)) {
                        val += it.key();
                        val += QLatin1String(":'");
                        val += THttpUtility::toUrlEncoding(it.value().toString());
                        val += QLatin1String("', ");
                    }
                }
                val.chop(2);
            }
            
            if (!val.isEmpty()) {
                string += QLatin1String("parameters: { ");
                string += val;
                string += QLatin1String(" }, ");
            }
            continue;
        }

        // Appends ajax callbacks
        s = eventStringHash()->value(i.key());
        if (!s.isEmpty() && i.value().canConvert(QVariant::String)) {
            string += s;
            string += i.value().toString();
            string += QLatin1String(", ");
            continue;
        } else {
            tWarn("invalid parameter: %d [%s:%d]", i.key(), __FILE__, __LINE__);
        }
    }

    string.chop(2);
    return string;
}
Пример #20
0
void cLogAnalyser::storePattern( const unsigned int p_uiFileId, cActionDefList::tiPatternList p_itPattern, const QString &p_qsLogLine,
                                 tmFoundPatternList::iterator  *p_poInsertPos ) throw( cSevException )
{
    cTracer  obTracer( &g_obLogger, "cLogAnalyser::storePattern", p_itPattern->name().toStdString() );

    QString qsLogLine = p_qsLogLine.section( ':', 1 ); // Remove line number from front
    qsLogLine.chop( 1 );                               // and the new line character from end

    QRegExp obTimeStampRegExp = m_poActionDefList->timeStampRegExp();
    if( obTimeStampRegExp.indexIn( qsLogLine ) == -1 )
        throw cSevException( cSeverity::ERROR,
                             QString( "TimeStamp Regular Expression does not match on Log Line \"%1\"" ).arg( qsLogLine ).toStdString() );

    QStringList    slTimeStampParts = obTimeStampRegExp.capturedTexts();
    tsFoundPattern suFoundPattern;

    suFoundPattern.qsTimeStamp = slTimeStampParts.at( 0 );

    for( int i = 1; i < slTimeStampParts.size(); i++ )
    {
        switch( m_poActionDefList->timeStampPart( i - 1 ) )
        {
            case cTimeStampPart::YEAR:    suFoundPattern.suTimeStamp.uiYear    = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::MONTH:   suFoundPattern.suTimeStamp.uiMonth   = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::DAY:     suFoundPattern.suTimeStamp.uiDay     = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::HOUR:    suFoundPattern.suTimeStamp.uiHour    = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::MINUTE:  suFoundPattern.suTimeStamp.uiMinute  = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::SECOND:  suFoundPattern.suTimeStamp.uiSecond  = slTimeStampParts.at( i ).toUInt(); break;
            case cTimeStampPart::MSECOND: suFoundPattern.suTimeStamp.uiMSecond = slTimeStampParts.at( i ).toUInt(); break;
            default: ;
        }
    }

    suFoundPattern.uiFileId = p_uiFileId;
    suFoundPattern.ulLineNum = p_qsLogLine.section( ':', 0, 0 ).toULong();

    QStringList  slCaptures = p_itPattern->captures();
    if( slCaptures.size() )
    {
        QStringList  slCapturedTexts = p_itPattern->capturedTexts( qsLogLine );
        for( int i = 0; i < slCaptures.size(); i++ )
        {
            if( i < slCapturedTexts.size() - 1 )
            {
                QString qsCapturedValue = slCapturedTexts.at( i + 1 );
                qsCapturedValue.replace( "\"", "\\\"" );
                qsCapturedValue.replace( "\'", "\\\'" );
                suFoundPattern.maCapturedAttribs.insert( pair<QString,QString>( slCaptures.at( i ), qsCapturedValue ) );
            }
        }
    }

    *p_poInsertPos = m_maFoundPatterns.insert( *p_poInsertPos, pair<QString, tsFoundPattern>( p_itPattern->name(), suFoundPattern ) );

    if( m_poActionDefList->combilogColor() != "" )
    {
        tm tmTime;
        tmTime.tm_wday  = 0;
        tmTime.tm_yday  = 0;
        tmTime.tm_isdst = 0;
        tmTime.tm_year  = suFoundPattern.suTimeStamp.uiYear - 1900;
        tmTime.tm_mon   = suFoundPattern.suTimeStamp.uiMonth - 1;
        tmTime.tm_mday  = suFoundPattern.suTimeStamp.uiDay;
        tmTime.tm_hour  = suFoundPattern.suTimeStamp.uiHour;
        tmTime.tm_min   = suFoundPattern.suTimeStamp.uiMinute;
        tmTime.tm_sec   = suFoundPattern.suTimeStamp.uiSecond;
        time_t  uiTime  = mktime( &tmTime );
        unsigned long long ulTime = (unsigned long long)uiTime * 1000LL;
        ulTime += suFoundPattern.suTimeStamp.uiMSecond;
        if( m_poOC ) m_poOC->addCombilogEntry( ulTime, qsLogLine, m_poActionDefList->combilogColor() );
    }
}
Пример #21
0
QString cmdFromUser(int argc, char **argv, QString inFile, QString extension, QString& path, bool showDLG=false){
    //First check to see if there is a default for this extension
    QString defApp;
    if(extension=="mimetype"){
	//qDebug() << "inFile:" << inFile;
	QStringList matches = LXDG::findAppMimeForFile(inFile, true).split("::::"); //allow multiple matches
	//qDebug() << "Matches:" << matches;
	for(int i=0; i<matches.length(); i++){
	  defApp = LXDG::findDefaultAppForMime(matches[i]);
	  if(!defApp.isEmpty()){ extension = matches[i]; break; }
	  else if(i+1==matches.length()){ extension = matches[0]; }
	}
    }else{ defApp = LFileDialog::getDefaultApp(extension); }
    
    if( !defApp.isEmpty() && !showDLG ){
      bool ok = false;
      if(defApp.endsWith(".desktop")){
        XDGDesktop DF = LXDG::loadDesktopFile(defApp, ok);
        if(ok){
      	  QString exec = LXDG::getDesktopExec(DF);
      	  if(!exec.isEmpty()){
      	    qDebug() << "[lumina-open] Using default application:" << DF.name << "File:" << inFile;
            if(!DF.path.isEmpty()){ path = DF.path; }
            return exec;
          }
        }
      }else{
	//Only binary given
	if(LUtils::isValidBinary(defApp)){
	  qDebug() << "[lumina-open] Using default application:" << defApp << "File:" << inFile;
	  return defApp; //just use the binary
	}
      }
      //invalid default - reset it and continue on
      LFileDialog::setDefaultApp(extension, "");
    }
    //Final catch: directory given - no valid default found - use lumina-fm
    if(extension=="directory" && !showDLG){ return "lumina-fm"; }
    //No default set -- Start up the application selection dialog
    LTHEME::LoadCustomEnvSettings();
    QApplication App(argc, argv);
    LuminaThemeEngine theme(&App);
      LUtils::LoadTranslation(&App,"lumina-open");

    LFileDialog w;
    if(extension=="email" || extension=="webbrowser"){
      //URL
      w.setFileInfo(inFile, extension, false);
    }else{
      //File
      if(inFile.endsWith("/")){ inFile.chop(1); }
      w.setFileInfo(inFile.section("/",-1), extension, true);
    }

    w.show();
    App.exec();
    if(!w.appSelected){ return ""; }
    //Return the run path if appropriate
    if(!w.appPath.isEmpty()){ path = w.appPath; }
    //Just do the default application registration here for now
    //  might move it to the runtime phase later after seeing that the app has successfully started
    if(w.setDefault){ 
      if(!w.appFile.isEmpty()){ LFileDialog::setDefaultApp(extension, w.appFile); }
      else{ LFileDialog::setDefaultApp(extension, w.appExec); }
    }else{ LFileDialog::setDefaultApp(extension, ""); }
    //Now return the resulting application command
    return w.appExec;
}
Пример #22
0
QString FlatTextarea::getText(int32 start, int32 end) const {
    if (end >= 0 && end <= start) return QString();

    if (start < 0) start = 0;
    bool full = (start == 0) && (end < 0);

    QTextDocument *doc(document());
    QTextBlock from = full ? doc->begin() : doc->findBlock(start), till = (end < 0) ? doc->end() : doc->findBlock(end);
    if (till.isValid()) till = till.next();

    int32 possibleLen = 0;
    for (QTextBlock b = from; b != till; b = b.next()) {
        possibleLen += b.length();
    }
    QString result;
    result.reserve(possibleLen + 1);
    if (!full && end < 0) {
        end = possibleLen;
    }

    for (QTextBlock b = from; b != till; b = b.next()) {
        for (QTextBlock::Iterator iter = b.begin(); !iter.atEnd(); ++iter) {
            QTextFragment fragment(iter.fragment());
            if (!fragment.isValid()) continue;

            int32 p = full ? 0 : fragment.position(), e = full ? 0 : (p + fragment.length());
            if (!full) {
                if (p >= end || e <= start) {
                    continue;
                }
            }

            QTextCharFormat f = fragment.charFormat();
            QString emojiText;
            QString t(fragment.text());
            if (!full) {
                if (p < start) {
                    t = t.mid(start - p, end - start);
                } else if (e > end) {
                    t = t.mid(0, end - p);
                }
            }
            QChar *ub = t.data(), *uc = ub, *ue = uc + t.size();
            for (; uc != ue; ++uc) {
                switch (uc->unicode()) {
                case 0xfdd0: // QTextBeginningOfFrame
                case 0xfdd1: // QTextEndOfFrame
                case QChar::ParagraphSeparator:
                case QChar::LineSeparator:
                    *uc = QLatin1Char('\n');
                    break;
                case QChar::Nbsp:
                    *uc = QLatin1Char(' ');
                    break;
                case QChar::ObjectReplacementCharacter:
                    if (emojiText.isEmpty() && f.isImageFormat()) {
                        QString imageName = static_cast<QTextImageFormat*>(&f)->name();
                        if (imageName.startsWith(qstr("emoji://e."))) {
                            if (EmojiPtr emoji = emojiFromUrl(imageName)) {
                                emojiText = emojiString(emoji);
                            }
                        }
                    }
                    if (uc > ub) result.append(ub, uc - ub);
                    if (!emojiText.isEmpty()) result.append(emojiText);
                    ub = uc + 1;
                    break;
                }
            }
            if (uc > ub) result.append(ub, uc - ub);
        }
        result.append('\n');
    }
    result.chop(1);
    return result;
}
Пример #23
0
double EqonomizeValueEdit::fixup_sub(QString &input, QStringList &errors, bool &calculated) const {
	input = input.trimmed();
	if(input.isEmpty()) {
		return 0.0;
	}
	if(o_currency) {
		input.remove(budget->monetary_group_separator);
		if(!budget->monetary_negative_sign.isEmpty()) input.replace(budget->monetary_negative_sign, "-");
		if(!budget->monetary_positive_sign.isEmpty()) input.replace(budget->monetary_positive_sign, "+");
	} else {
		input.remove(budget->group_separator);
		if(!budget->negative_sign.isEmpty()) input.replace(budget->negative_sign, "-");
		if(!budget->positive_sign.isEmpty()) input.replace(budget->positive_sign, "+");
	}
	input.replace(QLocale().negativeSign(), '-');
	input.replace(QLocale().positiveSign(), '+');
	int i = input.indexOf(')', 1);
	if(i < 1) {
		i = input.indexOf('(', 0);
		if(i == 0) {
			input.remove(0, 1);
			return fixup_sub(input, errors, calculated);
		} else if(i >= 0) {
			input += ')';
			i = input.length() - 1;
		} else {
			i = -1;
		}
	}
	if(i >= 1) {
		int i2 = input.lastIndexOf('(', i - 1);
		if(i2 < 0 || i2 > i) {
			if(i == input.length() - 1) {
				input.chop(1);
				return fixup_sub(input, errors, calculated);
			}
			input.prepend('(');
			i++;
			i2 = 0;
		}
		if(i2 == 0 && i == input.length() - 1) {
			input.remove(0, 1);
			input.chop(1);
			return fixup_sub(input, errors, calculated);
		}
		if(i < input.length() - 1 && (input[i + 1].isNumber() || input[i + 1] == '(')) input.insert(i + 1, '*');
		QString str = input.mid(i2 + 1, i - i2 - 1);
		double v = fixup_sub(str, errors, calculated);
		input.replace(i2, i - i2 + 1, o_currency ? o_currency->formatValue(0.5, decimals() + 2, false, false, true) : budget->formatValue(v, decimals() + 2));
		if(i2 > 0 && (input[i2 - 1].isNumber() || input[i2 - 1] == ')')) input.insert(i2, '*');
		calculated = true;
		return fixup_sub(input, errors, calculated);
	}
	i = input.indexOf(QRegExp("[-+]"), 1);
	if(i >= 1) {
		QStringList terms = input.split(QRegExp("[-+]"));
		i = 0;
		double v = 0.0;
		QList<bool> signs;
		signs << true;
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			i += terms[terms_i].length();
			if(input[i] == '-') signs << false;
			else signs << true;
			i++;
		}
		for(int terms_i = 0; terms_i < terms.size() - 1; terms_i++) {
			if(terms[terms_i].endsWith('*') || terms[terms_i].endsWith('/') || terms[terms_i].endsWith('^')) {
				if(!signs[terms_i + 1]) terms[terms_i] += '-';
				else terms[terms_i] += '+';
				terms[terms_i] += terms[terms_i + 1];
				signs.removeAt(terms_i + 1);
				terms.removeAt(terms_i + 1);
				terms_i--;
			}
		}
		if(terms.size() > 1) {
			for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
				if(terms[terms_i].isEmpty()) {
					if(!signs[terms_i] && terms_i + 1 < terms.size()) {
						signs[terms_i + 1] = !signs[terms_i + 1];
					}
				} else {					
					if(!signs[terms_i]) v -= fixup_sub(terms[terms_i], errors, calculated);
					else v += fixup_sub(terms[terms_i], errors, calculated);
				}
			}			
			calculated = true;
			return v;
		}
	}
	if(input.indexOf("**") >= 0) input.replace("**", "^");
	i = input.indexOf(QRegExp("[*/]"), 0);
	if(i >= 0) {
		QStringList terms = input.split(QRegExp("[*/]"));
		QChar c = '*';
		i = 0;
		double v = 1.0;
		for(int terms_i = 0; terms_i < terms.size(); terms_i++) {
			if(terms[terms_i].isEmpty()) {
				if(c == '/') {
					errors << tr("Empty denominator.");
				} else {
					errors << tr("Empty factor.");
				}
			} else {
				i += terms[terms_i].length();
				if(c == '/') {
					double den = fixup_sub(terms[terms_i], errors, calculated);
					if(den == 0.0) {
						errors << tr("Division by zero.");
					} else {
						v /= den;
					}
				} else {
					v *= fixup_sub(terms[terms_i], errors, calculated);
				}
				if(i < input.length()) c = input[i];
			}
			i++;
		}
		calculated = true;
		return v;
	}
	i = input.indexOf(QLocale().percent());
	if(i >= 0) {
		double v = 0.01;
		if(input.length() > 1) {
			if(i > 0 && i < input.length() - 1) {
				QString str = input.right(input.length() - 1 - i);
				input = input.left(i);
				i = 0;
				v = fixup_sub(str, errors, calculated) * v;
			} else if(i == input.length() - 1) {
				input = input.left(i);
			} else if(i == 0) {
				input = input.right(input.length() - 1);
			}
			v = fixup_sub(input, errors, calculated) * v;
		}
		calculated = true;
		return v;
	}	
	if(o_currency) {
		QString reg_exp_str = "[\\d\\+\\-\\^";
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->monetary_group_separator;
		if(budget->monetary_decimal_separator != "." && budget->monetary_group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		int i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 1) {
			QString scur = input.left(i).trimmed();
			Currency *cur = budget->findCurrency(scur);
			if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(scur, true);
			if(cur) {
				QString value = input.right(input.length() - i);				
				double v = fixup_sub(value, errors, calculated);
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
		}
		if(i >= 0) {
			i = input.lastIndexOf(QRegExp(reg_exp_str));
			if(i >= 0 && i < input.length() - 1) {
				QString scur = input.right(input.length() - (i + 1)).trimmed();
				Currency *cur = budget->findCurrency(scur);
				if(!cur && budget->defaultCurrency()->symbol(false) == scur) cur = budget->defaultCurrency();
				if(!cur) cur = budget->findCurrencySymbol(scur, true);
				if(cur) {
					QString value = input.left(i + 1);
					double v = fixup_sub(value, errors, calculated);
					if(cur != o_currency) {
						v = cur->convertTo(v, o_currency);
					}
					calculated = true;
					return v;
				}
				errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(scur);
			}
		} else {
			Currency *cur = budget->findCurrency(input);
			if(!cur && budget->defaultCurrency()->symbol(false) == input) cur = budget->defaultCurrency();
			if(!cur) cur = budget->findCurrencySymbol(input, true);
			if(cur) {
				double v = 1.0;
				if(cur != o_currency) {
					v = cur->convertTo(v, o_currency);
				}
				calculated = true;
				return v;
			}
			errors << tr("Unknown or ambiguous currency, or unrecognized characters, in expression: %1.").arg(input);
		}
	}
	i = input.indexOf('^', 0);
	if(i >= 0 && i != input.length() - 1) {
		QString base = input.left(i);
		if(base.isEmpty()) {
			errors << tr("Empty base.");
		} else {
			QString exp = input.right(input.length() - (i + 1));
			double v;
			if(exp.isEmpty()) {
				errors << tr("Error"), tr("Empty exponent.");
				v = 1.0;
			} else {
				v = pow(fixup_sub(base, errors, calculated), fixup_sub(exp, errors, calculated));
			}
			calculated = true;
			return v;
		}
	}
	
	if(!o_currency) {
		QString reg_exp_str = "[^\\d\\+\\-";
		reg_exp_str += '\\';
		reg_exp_str += budget->decimal_separator;
		reg_exp_str += '\\';
		reg_exp_str += budget->group_separator;
		if(budget->decimal_separator != "." && budget->group_separator != ".") {
			reg_exp_str += '\\';
			reg_exp_str += '.';
		}
		reg_exp_str += "]";
		i = input.indexOf(QRegExp(reg_exp_str));
		if(i >= 0) {
			errors << tr("Unrecognized characters in expression.");
		}
		input.remove(budget->group_separator);
		input.replace(budget->decimal_separator, ".");
		return input.toDouble();
	}
	input.remove(budget->monetary_group_separator);
	input.replace(budget->monetary_decimal_separator, ".");
	return input.toDouble();
}
Пример #24
0
QString PageGenerator::fileBase(const Node *node) const
{
    if (node->relates())
	node = node->relates();
    else if (!node->isInnerNode())
	node = node->parent();
#ifdef QDOC_QML
    if (node->subType() == Node::QmlPropertyGroup) {
        node = node->parent();
    }
#endif        

    QString base = node->doc().baseName();
    if (!base.isEmpty())
        return base;

    const Node *p = node;

    forever {
        const Node *pp = p->parent();
        base.prepend(p->name());
#ifdef QDOC_QML
        /*
          To avoid file name conflicts in the html directory,
          we prepend a prefix (by default, "qml-") to the file name of QML
          element doc files.
         */
        if ((p->subType() == Node::QmlClass) ||
            (p->subType() == Node::QmlBasicType)) {
            if (!base.startsWith(QLatin1String("QML:")))
                base.prepend(outputPrefix(QLatin1String("QML")));
        }
#endif
        if (!pp || pp->name().isEmpty() || pp->type() == Node::Fake)
            break;
        base.prepend(QLatin1Char('-'));
        p = pp;
    }
    
    if (node->type() == Node::Fake) {
#ifdef QDOC2_COMPAT
        if (base.endsWith(".html"))
            base.truncate(base.length() - 5);
#endif
    }

    // the code below is effectively equivalent to:
    //   base.replace(QRegExp("[^A-Za-z0-9]+"), " ");
    //   base = base.trimmed();
    //   base.replace(" ", "-");
    //   base = base.toLower();
    // as this function accounted for ~8% of total running time
    // we optimize a bit...

    QString res;
    // +5 prevents realloc in fileName() below
    res.reserve(base.size() + 5);
    bool begun = false;
    for (int i = 0; i != base.size(); ++i) {
        QChar c = base.at(i);
        uint u = c.unicode();
        if (u >= 'A' && u <= 'Z')
            u -= 'A' - 'a';
        if ((u >= 'a' &&  u <= 'z') || (u >= '0' && u <= '9')) {
            res += QLatin1Char(u);
            begun = true;
        }
        else if (begun) {
            res += QLatin1Char('-');
            begun = false;
        }
    }
    while (res.endsWith(QLatin1Char('-')))
        res.chop(1);
    return res;
}
Пример #25
0
void
KeyboardPage::init()
{
    //### Detect current keyboard layout and variant
    QString currentLayout;
    QString currentVariant;
    QProcess process;
    process.start( "setxkbmap", QStringList() << "-print" );

    if ( process.waitForFinished() )
    {
        const QStringList list = QString( process.readAll() )
                                 .split( "\n", QString::SkipEmptyParts );

        for ( QString line : list )
        {
            line = line.trimmed();
            if ( !line.startsWith( "xkb_symbols" ) )
                continue;

            line = line.remove( "}" )
                   .remove( "{" )
                   .remove( ";" );
            line = line.mid( line.indexOf( "\"" ) + 1 );

            QStringList split = line.split( "+", QString::SkipEmptyParts );
            if ( split.size() >= 2 )
            {
                currentLayout = split.at( 1 );

                if ( currentLayout.contains( "(" ) )
                {
                    int parenthesisIndex = currentLayout.indexOf( "(" );
                    currentVariant = currentLayout.mid( parenthesisIndex + 1 )
                                     .trimmed();
                    currentVariant.chop( 1 );
                    currentLayout = currentLayout
                                    .mid( 0, parenthesisIndex )
                                    .trimmed();
                }

                break;
            }
        }
    }

    //### Models
    m_models = KeyboardGlobal::getKeyboardModels();
    QMapIterator< QString, QString > mi( m_models );

    ui->comboBoxModel->blockSignals( true );

    while ( mi.hasNext() )
    {
        mi.next();

        if ( mi.value() == "pc105" )
            m_defaultIndex = ui->comboBoxModel->count();

        ui->comboBoxModel->addItem( mi.key() );
    }

    ui->comboBoxModel->blockSignals( false );

    // Set to default value pc105
    ui->comboBoxModel->setCurrentIndex( m_defaultIndex );


    //### Layouts and Variants

    KeyboardLayoutModel* klm = new KeyboardLayoutModel( this );
    ui->listLayout->setModel( klm );
    connect( ui->listLayout->selectionModel(), &QItemSelectionModel::currentChanged,
             this, &KeyboardPage::onListLayoutCurrentItemChanged );

    // Block signals
    ui->listLayout->blockSignals( true );

    QPersistentModelIndex currentLayoutItem = findLayout( klm, currentLayout );
    if ( !currentLayoutItem.isValid() && (
                ( currentLayout == "latin" )
                || ( currentLayout == "pc" ) ) )
    {
        currentLayout = "us";
        currentLayoutItem = findLayout( klm, currentLayout );
    }

    // Set current layout and variant
    if ( currentLayoutItem.isValid() )
    {
        ui->listLayout->setCurrentIndex( currentLayoutItem );
        updateVariants( currentLayoutItem, currentVariant );
    }

    // Unblock signals
    ui->listLayout->blockSignals( false );

    // Default to the first available layout if none was set
    // Do this after unblocking signals so we get the default variant handling.
    if ( !currentLayoutItem.isValid() && klm->rowCount() > 0 )
        ui->listLayout->setCurrentIndex( klm->index( 0 ) );
}
Пример #26
0
int CommandExec::exec(const QCommandLineParser *parser)
{
    m_pCPart->parser = const_cast<QCommandLineParser*>(parser);
    m_pCPart->args = parser->positionalArguments();
    if (m_pCPart->args.isEmpty()) {
        return -1;
    }
    m_lastMessages.clear();
    m_lastMessagesLines = 0;
    m_pCPart->m_SvnWrapper->reInitClient();
    bool dont_check_second = false;
    bool dont_check_all = false;
    bool path_only = false;
    bool no_revision = false;
    bool check_force = false;

    if (m_pCPart->args.count() >= 2) {
        m_pCPart->cmd = m_pCPart->args.at(1);
        m_pCPart->cmd = m_pCPart->cmd.toLower();
    }
    QByteArray slotCmd;
    if (!QString::compare(m_pCPart->cmd, "log")) {
        slotCmd = SLOT(slotCmd_log());
    } else if (!QString::compare(m_pCPart->cmd, "cat")) {
        slotCmd = SLOT(slotCmd_cat());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "get")) {
        slotCmd = SLOT(slotCmd_get());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "help")) {
        slotCmd = SLOT(slotCmd_help());
    } else if (!QString::compare(m_pCPart->cmd, "blame") ||
               !QString::compare(m_pCPart->cmd, "annotate")) {
        slotCmd = SLOT(slotCmd_blame());
    } else if (!QString::compare(m_pCPart->cmd, "update")) {
        slotCmd = SLOT(slotCmd_update());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "diff")) {
        m_pCPart->start = svn::Revision::WORKING;
        slotCmd = SLOT(slotCmd_diff());
    } else if (!QString::compare(m_pCPart->cmd, "info")) {
        slotCmd = SLOT(slotCmd_info());
        m_pCPart->single_revision = true;
    } else if (!QString::compare(m_pCPart->cmd, "commit") ||
               !QString::compare(m_pCPart->cmd, "ci")) {
        slotCmd = SLOT(slotCmd_commit());
    } else if (!QString::compare(m_pCPart->cmd, "list") ||
               !QString::compare(m_pCPart->cmd, "ls")) {
        slotCmd = SLOT(slotCmd_list());
    } else if (!QString::compare(m_pCPart->cmd, "copy") ||
               !QString::compare(m_pCPart->cmd, "cp")) {
        slotCmd = SLOT(slotCmd_copy());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "move") ||
               !QString::compare(m_pCPart->cmd, "rename") ||
               !QString::compare(m_pCPart->cmd, "mv")) {
        slotCmd = SLOT(slotCmd_move());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "checkout") ||
               !QString::compare(m_pCPart->cmd, "co")) {
        slotCmd = SLOT(slotCmd_checkout());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "checkoutto") ||
               !QString::compare(m_pCPart->cmd, "coto")) {
        slotCmd = SLOT(slotCmd_checkoutto());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "export")) {
        slotCmd = SLOT(slotCmd_export());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "exportto")) {
        slotCmd = SLOT(slotCmd_exportto());
        dont_check_second = true;
    } else if (!QString::compare(m_pCPart->cmd, "delete") ||
               !QString::compare(m_pCPart->cmd, "del") ||
               !QString::compare(m_pCPart->cmd, "rm") ||
               !QString::compare(m_pCPart->cmd, "remove")) {
        slotCmd = SLOT(slotCmd_delete());
    } else if (!QString::compare(m_pCPart->cmd, "add")) {
        slotCmd = SLOT(slotCmd_add());
        dont_check_all = true;
        path_only = true;
    } else if (!QString::compare(m_pCPart->cmd, "undo") ||
               !QString::compare(m_pCPart->cmd, "revert")) {
        slotCmd = SLOT(slotCmd_revert());
    } else if (!QString::compare(m_pCPart->cmd, "checknew") ||
               !QString::compare(m_pCPart->cmd, "addnew")) {
        slotCmd = SLOT(slotCmd_addnew());
    } else if (!QString::compare(m_pCPart->cmd, "switch")) {
        slotCmd = SLOT(slotCmd_switch());
    } else if (!QString::compare(m_pCPart->cmd, "tree")) {
        slotCmd = SLOT(slotCmd_tree());
    } else if (!QString::compare(m_pCPart->cmd, "lock")) {
        slotCmd = SLOT(slotCmd_lock());
        no_revision = true;
        check_force = true;
    } else if (!QString::compare(m_pCPart->cmd, "unlock")) {
        slotCmd = SLOT(slotCmd_unlock());
        no_revision = true;
        check_force = true;
    }

    bool found = connect(this, SIGNAL(executeMe()), this, slotCmd.constData());
    if (!found) {
        KMessageBox::sorry(0,
                           i18n("Command \"%1\" not implemented or known", m_pCPart->cmd),
                           i18n("SVN Error"));
        return -1;
    }

    QString tmp;
    QString mainProto;
    for (int j = 2; j < m_pCPart->args.count(); ++j) {
        QUrl tmpurl = QUrl::fromUserInput(m_pCPart->args.at(j),
                                          QDir::currentPath());
        tmpurl.setScheme(svn::Url::transformProtokoll(tmpurl.scheme()));
        if (tmpurl.scheme().indexOf(QLatin1String("ssh")) != -1) {
            SshAgent ag;
            // this class itself checks if done before
            ag.addSshIdentities();
        }
        m_pCPart->extraRevisions[j - 2] = svn::Revision::HEAD;

        if (tmpurl.isLocalFile() && (j == 2 || !dont_check_second) && !dont_check_all) {
            QUrl repoUrl;
            if (m_pCPart->m_SvnWrapper->isLocalWorkingCopy(tmpurl.path(), repoUrl)) {
                tmp = tmpurl.path();
                m_pCPart->repoUrls[j - 2] = repoUrl;
                m_pCPart->extraRevisions[j - 2] = svn::Revision::WORKING;
                if (j == 2) {
                    mainProto.clear();
                }
            } else {
                tmp = tmpurl.url();
                if (j == 2) {
                    mainProto = QLatin1String("file://");
                }
            }
        } else if (path_only) {
            tmp = tmpurl.path();
        } else {
            tmp = tmpurl.url();
            if (j == 2) {
                mainProto = tmpurl.scheme();
            }
        }
        if ((j > 2 && dont_check_second) || dont_check_all) {
            if (mainProto.isEmpty()) {
                tmp = tmpurl.path();
            }
        }
        const QStringList l = tmp.split(QLatin1Char('?'), QString::SkipEmptyParts);
        if (!l.isEmpty()) {
            tmp = l[0];
        }
        while (tmp.endsWith(QLatin1Char('/'))) {
            tmp.chop(1);
        }
        m_pCPart->urls.append(tmp);
        if ((j > 2 && dont_check_second) || dont_check_all) {
            continue;
        }
        const QList<QPair<QString, QString> > q = QUrlQuery(tmpurl).queryItems();
        for(int i = 0; i < q.size(); ++i) {
            if (q.at(i).first == QLatin1String("rev")) {
                svn::Revision re = q.at(i).second;
                if (re) {
                    m_pCPart->extraRevisions[j - 2] = re;
                }
            }
        }
    }
    if (m_pCPart->urls.isEmpty()) {
        m_pCPart->urls.append(QLatin1String("."));
    }

    if (!no_revision) {
        if (m_pCPart->parser->isSet("R")) {
            m_pCPart->ask_revision = true;
            if (!askRevision()) {
                return 0;
            }
        } else if (m_pCPart->parser->isSet("r")) {
            scanRevision();
        }
    }

    m_pCPart->force = check_force && m_pCPart->parser->isSet("f");

    if (m_pCPart->parser->isSet("o")) {
        m_pCPart->outfile_set = true;
        m_pCPart->outfile = m_pCPart->parser->value("o");
    }
    if (m_pCPart->parser->isSet("l")) {
        QString s = m_pCPart->parser->value("l");
        m_pCPart->log_limit = s.toInt();
        if (m_pCPart->log_limit < 0) {
            m_pCPart->log_limit = 0;
        }
    }

    emit executeMe();
    if (Kdesvnsettings::self()->cmdline_show_logwindow() &&
            m_lastMessagesLines >= Kdesvnsettings::self()->cmdline_log_minline()) {
        QPointer<KSvnSimpleOkDialog> dlg(new KSvnSimpleOkDialog(QStringLiteral("kdesvn_cmd_log"), QApplication::activeModalWidget()));
        QTextBrowser *ptr = new QTextBrowser(dlg);
        ptr->setText(m_lastMessages);
        ptr->setReadOnly(true);
        dlg->addWidget(ptr);
        QString cmd = qApp->arguments().join(QLatin1Char(' '));
        dlg->setWindowTitle(cmd);
        dlg->exec();
        delete dlg;
    }
    return 0;
}
void ScCodeEditor::toggleCommentSelection()
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();

    if (isBlockOnlySelection(cursor)) {
        const bool isComment = isSingleLineComment(cursor);

        QTextCursor selectionCursor(cursor);
        selectionCursor.setPosition(cursor.selectionStart());

        QTextBlock currentBlock = selectionCursor.block();
        int firstBlockIndentation = isComment ? 0
                                              : indentationLevel(selectionCursor);

        do {
            QTextCursor blockCursor(currentBlock);
            if (!isComment)
                addSingleLineComment(blockCursor, firstBlockIndentation);
            else
                removeSingleLineComment(blockCursor);
            currentBlock = currentBlock.next();
        } while (currentBlock.isValid() && currentBlock.position() < cursor.selectionEnd());

        if (!isComment) {
            // fix up selection
            QTextCursor newSelection(cursor);
            if (cursor.anchor() < cursor.position()) {
                newSelection.setPosition(newSelection.selectionStart());
                newSelection.movePosition(QTextCursor::StartOfBlock);
                newSelection.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
            } else {
                newSelection.setPosition(newSelection.selectionEnd());
                newSelection.setPosition(cursor.selectionStart(), QTextCursor::KeepAnchor);
                newSelection.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
            }
            setTextCursor(newSelection);
        }
    } else {
        QString selectionText = cursor.selectedText();
        QTextCursor selectionCursor(cursor);
        if (isSelectionComment(selectionText)) {
            selectionText = selectionText.trimmed().remove(0, 2);
            selectionText.chop(2);
            selectionCursor.insertText(selectionText);
        } else {
            selectionText = QString("/*") + selectionText + QString("*/");
            selectionCursor.insertText(selectionText);
        }

        // fix up selection
        const int position = selectionCursor.position();
        const int anchor   = selectionCursor.anchor();
        if (position > anchor) {
            cursor.setPosition(position - selectionText.size());
            cursor.setPosition(position, QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(position);
            cursor.setPosition(position - selectionText.size(), QTextCursor::KeepAnchor);
        }
        setTextCursor(cursor);
    }

    cursor.endEditBlock();
}
Пример #28
0
bool AircraftData::import(QProgressDialog &progress, MainObject *mainObject){

	int c = 0;
	int found = 0;

	progress.setRange(0, 2000);
	progress.setWindowTitle("Scanning Aircraft Directories");
	progress.show();
	progress.repaint();

	//= Cache File
	QFile cacheFile( mainObject->data_file("aircraft.txt") );
	if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){
		//qDebug() << "TODO Open error cachce file=";
		return true;
	}



	QTextStream out(&cacheFile);

	//= Get files Entries from Aircaft/ directory
	QDir aircraftDir( mainObject->X->aircraft_path() );
	aircraftDir.setFilter( QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot);

	QStringList entries = aircraftDir.entryList();
	progress.setRange(0, entries.size() + 20);

	for( QStringList::ConstIterator entry=entries.begin(); entry!=entries.end(); ++entry ){

		// Filter out default dir names, should be a QDir name filter?
		if (*entry != "Instruments" &&  *entry != "Instruments-3d" && *entry != "Generic") {

			progress.setValue(c);
			progress.setLabelText(*entry);
			progress.repaint();

			//** get the List of *-set.xml files in dir
			QDir dir( mainObject->X->aircraft_path(*entry) );
			QStringList filters;
			filters << "*-set.xml";
			QStringList list_xml = dir.entryList(filters);

			if(list_xml.count() > 0){ // << Scan MOdels
				QString directory;
				QString description;
				QString author;
				QString fdm;
				QString xml_file;
				QString aero;

				//** Add Path Node
				directory = QString(*entry);
				//** Add Models
				for (int i = 0; i < list_xml.size(); ++i){

					xml_file = QString(list_xml.at(i));
					aero = QString(xml_file);
					aero.chop(8);

					//*=parse the Xml file - f&*& long winded
					QString file_path =  mainObject->X->aircraft_path(*entry);
					file_path.append("/");
					file_path.append(list_xml.at(i));
					QFile xmlFile( file_path);
					if (xmlFile.open(QIODevice::ReadOnly | QIODevice::Text)){

						/* The file content is converted to UTF-8.
							 Some files are Windows, encoding and throw error with QxmlQuery etc
							 Its a hack and don't quite understand whats happening.. said pedro
						*/
						QString xmlString = QString(xmlFile.readAll()).toUtf8();

						QXmlQuery query;
						query.setFocus(xmlString);
						//query.setFocus(&xmlFile); << Because file is not QTF8 using sting instead
						query.setQuery("PropertyList/sim");
						if (query.isValid()){

							QString res;
							query.evaluateTo(&res);
							xmlFile.close();

							QDomDocument dom;
							dom.setContent("" + res + "");
							QDomNodeList nodes = dom.elementsByTagName("sim");

							QDomNode n = nodes.at(0);
							description = n.firstChildElement("description").text();
							author = n.firstChildElement("author").text().trimmed().replace(("\n"),"");
							fdm = n.firstChildElement("flight-model").text();
						} /* !query.isValid() */
					} /*  xmlFile.open() */

					QStringList lines;
					lines  << directory << aero << xml_file << description << fdm << author << file_path;
					out << lines.join("\t") << "\n";

					found++;

					if(progress.wasCanceled()){
						//qDebug() << "Progress cancelled!";
						progress.hide();
						return true;
					}
					c++;
				}

			} /* list_xml.count() > 0 */
		} /* entry != INstruments etc */
	} /* loop entries.() */

	cacheFile.close();
	return false;
}
Пример #29
0
Donate::Donate(QWidget *parent) : QDialog(parent)
{
    resize(400, 0);
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    // Initialize "Thanks" section:

    QString thanks = QString("<hr>%1:<br>").arg(tr("Thank you for your support"));

    QRegExp rx("\\((.+)\\)");
    rx.setMinimal(true);

    QFile inputFile(APPDIR + "/authors.txt");
    if (inputFile.open(QIODevice::ReadOnly)) {

        QTextStream stream(&inputFile);

        while (!stream.atEnd()) {

            QString line = stream.readLine();

            if (line == "Supported by:") {
                while (!line.isEmpty() && !stream.atEnd()) {
                    line = stream.readLine();
                    line = line.replace(rx, "(<a href=\"\\1\">\\1</a>)");
                    thanks += line + "<br>";
                }
                thanks.chop(8);
                break;
            }
        }

        inputFile.close();
    }

    // Create GUI:

    QGridLayout *grid = new QGridLayout(this);
    QLabel *donators = new QLabel(this);
    donators->setAlignment(Qt::AlignCenter);
    donators->setTextFormat(Qt::RichText);
    donators->setOpenExternalLinks(true);
    donators->setText(thanks);

    QLabel *titlePayPal = new QLabel("PayPal", this);
    QLabel *titleBitCoin = new QLabel("BitCoin", this);
    QLineEdit *fieldPayPal = new QLineEdit(PAYPAL, this);
    QLineEdit *fieldBitCoin = new QLineEdit(BITCOIN, this);
    fieldPayPal->setReadOnly(true);
    fieldBitCoin->setReadOnly(true);
    fieldPayPal->setCursor(Qt::IBeamCursor);
    fieldBitCoin->setCursor(Qt::IBeamCursor);

    QToolButton *btnPayPal = new QToolButton(this);
    QToolButton *btnBitCoin = new QToolButton(this);
    btnPayPal->setIcon(QIcon(":/gfx/actions/copy.png"));
    btnBitCoin->setIcon(QIcon(":/gfx/actions/copy.png"));
    btnPayPal->setToolTip(tr("Copy to Clipboard"));
    btnBitCoin->setToolTip(tr("Copy to Clipboard"));

    QPushButton *btnOk = new QPushButton("OK", this);

    grid->addWidget(titlePayPal, 0, 0);
    grid->addWidget(fieldPayPal, 0, 1);
    grid->addWidget(btnPayPal, 0, 2);
    grid->addWidget(titleBitCoin, 1, 0);
    grid->addWidget(fieldBitCoin, 1, 1);
    grid->addWidget(btnBitCoin, 1, 2);
    grid->addWidget(btnOk, 2, 1);
    grid->addWidget(donators, 3, 1);

    connect(btnPayPal, SIGNAL(clicked()), this, SLOT(copyPayPal()));
    connect(btnBitCoin, SIGNAL(clicked()), this, SLOT(copyBitCoin()));
    connect(btnOk, SIGNAL(clicked()), this, SLOT(accept()));
}
Пример #30
-1
  void Server::acceptUser() {
    //to be called every time a new connection is received
    QTcpSocket *socket = m_tcp_server->nextPendingConnection();
    debugInfo("New incoming connection, from IP " +
	      socket->peerAddress().toString() +
	      " and port: " + QString::number(socket->peerPort()));
    //check if ip is registered
    if (!isThisIpRegistered(socket->peerAddress().toString())) {
      //then parse user
      UE new_ue;
      new_ue.name = "";
      new_ue.ip = socket->peerAddress().toString();
      //will change when ue_name() is sent
      new_ue.rx_port = 0;
      m_online_users.append(new_ue);
      debugInfo("New empty UE registered!");
    } else {
      debugInfo("user is transmitting either its name or data");
      socket->waitForReadyRead(1000);
      //parse data
      QDataStream in(socket);
      in.setVersion(QDataStream::Qt_4_0);
      debugInfo("m_block_size: " + QString::number(m_block_size));
      if (m_block_size == 0) {
	if (socket->bytesAvailable() < (int)sizeof(quint16))
	  return;
      
	in >> m_block_size;
      }
      debugInfo("bytes available in socket: " + QString::number(socket->bytesAvailable()));
    
      if (socket->bytesAvailable() < m_block_size)
	return;
    
      QString message;
      in >> message;
    
      debugInfo(">Message: [" + message + "]");

      ProtocolStreamType_UE type;
      QStringList params = m_protocol->parseStream_UE(type, message);

      switch (type) {
      case UE_REGISTER:
	{
	  QString temp_name = params.at(0);
	  quint16 temp_port = (quint16) params.at(1).toInt();
	  DLOG (INFO) << "Parsed port: " << temp_port;
	  if (temp_name.isEmpty()) {
	    m_block_size=0;
	    return;
	  }
	  UE temp;
	  int index;
	  if (!isThisNameRegistered(temp_name)) {
	    //case for same ip, different name
	    debugInfo("New user " + temp_name + " connected from same IP. Registering user.");
	    temp.name = temp_name;
	    temp.ip = socket->peerAddress().toString();
	    //parse ue_rx_port
	    temp.rx_port = temp_port;
	    index = getIndexOfUEIp(socket->peerAddress().toString());
	    if (m_online_users.at(index).name.isEmpty()) {
	      //first time, when username is still empty
	      if (index != -1) {
		temp = m_online_users.at(index);
		temp.name = temp_name;
		temp.rx_port = temp_port;
		m_online_users.replace(index,temp);
	      }
	    } else {
	      //same ip but different username, then append new UE
	      m_online_users.append(temp);
	    }
	  } else {
	    LOG (ERROR) << "User already exists on server. Notifying user...";
	    //inform user of currently online users
	    QByteArray block;
	    QDataStream out(&block, QIODevice::WriteOnly);
	    out.setVersion(QDataStream::Qt_4_0);
	    out << (quint16)0;
	    out << QString("ue_error(Existing user on server. Choose other username);");
	    out.device()->seek(0);
	    out << (quint16)(block.size() - sizeof(quint16));
	    DLOG (INFO) <<"Sending error message to UE ...\n";
	    m_log_label->setText(m_log_label->toPlainText()
			      + "\nError: attempted connection with same "
			      "username from same IP. Sending error to client...");
	    socket->write(block);
	    //reset m_block_size
	    m_block_size = 0;
	    return;
	  }
	  DLOG (INFO) << "New user is online: " << temp;
	  debugInfo("Nr. online users: " + QString::number(m_online_users.size()));
	  if (m_log_label->toPlainText() != "") {
	    m_log_label->setText(m_log_label->toPlainText() + "\n[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  } else {
	    m_log_label->setText(m_log_label->toPlainText() + "[" + temp.name + "]@" +
			      temp.ip + ":" +
			      QString::number(temp.rx_port) + " is now online.");
	  }
	  //parse online users
	  QString users;
	  for (auto user: m_online_users) {
	    users += user.name + "\n";
	  }
	  users.chop(1);
	  m_online_users_label->setText(users);
	  qobject_cast<QLabel*>(m_main_layout->itemAt(2)->widget())->setText("Currently online users("
									  + QString::number(m_online_users.size()) + "):");
	  //inform user of currently online users
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  QStringList params;
	  for (auto user: m_online_users) {
	    params << user.name;
	  }
	  out << m_protocol->constructStream_Server(params,
						    ProtocolStreamType_Server::SERVER_ALL);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  DLOG (INFO) <<"Sending information about currently online users...\n";
	  /*At this point, this block will be sent to all current users, not only to the
	    user that is currently connected*/
	  for (auto connection: m_online_users) {
	    QTcpSocket *temp_socket = new QTcpSocket(this);
	    temp_socket->connectToHost(QHostAddress(connection.ip), connection.rx_port);
	    if (!temp_socket->waitForConnected(3000)) {
	      LOG (ERROR) << "ERROR: Connection attempt @"
			  << connection.ip.toStdString() << ":"
			  << connection.rx_port << " timed out. Omitting current...";
	    } else {
	      debugInfo("Connection to client @" + connection.ip + ":"
			+ QString::number(connection.rx_port) + " was established. Now sending...");
	      temp_socket->write(block);
	      if (!temp_socket->waitForBytesWritten()) {
		LOG (ERROR) << "ERROR: Connection attempt @"
			    << connection.ip.toStdString() << ":"
			    << connection.rx_port << " timed out. Omitting current...";
	      } else {
		debugInfo("Transmission to client @" + connection.ip + ":"
			  + QString::number(connection.rx_port) + " was successful!");
	      }
	    }
	    temp_socket->disconnectFromHost();
	    if (temp_socket->state() == QAbstractSocket::UnconnectedState ||
		temp_socket->waitForDisconnected(1000)) {
	      debugInfo("Socket disconnected.");
	    }
	  }

	  break;

	  
	}
      case UE_ACK:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  debugInfo("Going to forward user ack to destination");
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));

	  //and lookup destination details for given user
	  QString dest = params.at(0);
	  QString from = params.at(1);
	  unsigned int message_id = (unsigned int) params.at(2).toInt();

	  //Create temporary socket
	  QTcpSocket* dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward ack to " + dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);

	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Forwarding user ack...");
	    dest_socket->write(block);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! ACK was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }
	  break;
	}
      case UE_ERROR:
	{
	  debugInfo("Some error encountered by user. Returning ...");
	  m_block_size=0;
	  return;
	}
      case UE_MESSAGE:
	{
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //and send it back to the user
	  debugInfo("Going to resend message to dest client: [" + message + "]");
	  
	  QString content = params.at(0);
	  QString dest = params.at(1);
	  QString from = params.at(2);
	  unsigned int message_id = (unsigned int) params.at(3).toInt();
	  
	  DLOG (INFO) << "Message: " << content.toStdString() << ", from " << from.toStdString()
		      << " and to " << dest.toStdString()
		      << ", with message ID: " << message_id;
	  QByteArray block;
	  QDataStream out(&block, QIODevice::WriteOnly);
	  out.setVersion(QDataStream::Qt_4_0);
	  out << (quint16)0;
	  out << m_protocol->constructStream_Server(QStringList(message),
						    ProtocolStreamType_Server::SERVER_FWD_TO_SENDER);
	  out.device()->seek(0);
	  out << (quint16)(block.size() - sizeof(quint16));
	  if (dest == from) {
	    debugInfo("WARNING: Message intended for self UE. Sending back to user...");
	    socket->write(block);
	    if (!socket->waitForBytesWritten(2000)) {
	      LOG (ERROR) << "ERROR: transmission timeout";
	    } else {
	      debugInfo("Success!");
	    }
	  } else {
	    QTcpSocket *dest_socket = new QTcpSocket(this);
	    QString dest_ip;
	    quint16 dest_port;
	    int index = getIndexOfUEName(dest);
	    if (index != -1) {
	      dest_ip = m_online_users.at(index).ip;
	      dest_port = m_online_users.at(index).rx_port;
	      debugInfo("Going to forward message to " + dest_ip + ":" + QString::number(dest_port));
	    } else {
	      LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	      m_block_size=0;
	      return;
	    }
	    dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	    if (!dest_socket->waitForConnected(2000)) {
	      debugInfo("ERROR: request timed out");
	    } else {
	      debugInfo("Established connection with client. Sending...");
	      dest_socket->write(block);
	      if (!dest_socket->waitForBytesWritten(5000)) {
		debugInfo("ERROR: transmission timed out");
	      } else {
		debugInfo("Success! Message was forwarded to destination");
	      }
	      dest_socket->disconnectFromHost();
	      //and send an ack to the user to inform that message was received
	      QByteArray ack_data;
	      QDataStream ack(&ack_data, QIODevice::WriteOnly);
	      ack.setVersion(QDataStream::Qt_4_0);
	      ack << (quint16)0;
	      QStringList params;
	      params << from << QString::number(message_id);
	      ack << m_protocol->constructStream_Server(params,
							ProtocolStreamType_Server::SERVER_ACK);
	      ack.device()->seek(0);
	      debugInfo("Sending ack to user: "******"ERROR: transmission timeout!";
	      } else {
		debugInfo("Success!");
	      }
	    }
	  }
	  break;
	}
      case UE_UNREGISTER:
	{
	  unregisterUser();
	  break;
	}
      case UE_TYPING:
	{
	  debugInfo("User is typing...");
	  m_log_label->setText(m_log_label->toPlainText() + "\n" + message);
	  //no need to parse parameters, going to forward to user
	  
	  QString dest = params.at(0);
	  QString from = params.at(1);

	  debugInfo(dest + "," + from);
	  
	  QByteArray typing_data;
	  QDataStream typing_stream(&typing_data, QIODevice::WriteOnly);
	  typing_stream.setVersion(QDataStream::Qt_4_0);
	  typing_stream << (quint16)0;
	  QStringList typing_params;
	  typing_params << params.at(0) << params.at(1) << params.at(2);
	  typing_stream << m_protocol->constructStream_Server(typing_params,
							      ProtocolStreamType_Server::SERVER_FWD_TYPING);
	  typing_stream.device()->seek(0);

	  DLOG (INFO) << "Sending: " << m_protocol->constructStream_Server(typing_params,
							    ProtocolStreamType_Server::SERVER_FWD_TYPING).toStdString();
	  
	  QTcpSocket *dest_socket = new QTcpSocket(this);
	  QString dest_ip;
	  quint16 dest_port;
	  int index = getIndexOfUEName(dest);
	  if (index != -1) {
	    dest_ip = m_online_users.at(index).ip;
	    dest_port = m_online_users.at(index).rx_port;
	    debugInfo("Going to forward typing info to " +
		      dest_ip + ":" + QString::number(dest_port));
	  } else {
	    LOG (ERROR) << "ERROR: name was not found on server. Returning...";
	    m_block_size=0;
	    return;
	  }
	  dest_socket->connectToHost(QHostAddress(dest_ip), dest_port);
	  if (!dest_socket->waitForConnected(2000)) {
	    debugInfo("ERROR: request timed out");
	  } else {
	    debugInfo("Established connection with client. Sending...");
	    dest_socket->write(typing_data);
	    if (!dest_socket->waitForBytesWritten(5000)) {
	      debugInfo("ERROR: transmission timed out");
	    } else {
	      debugInfo("Success! Typing information was forwarded to destination");
	    }
	    dest_socket->disconnectFromHost();
	  }

	  break;
	}
      default:
	LOG (WARNING) << "Unrecognized stream type";
	break;
      }
    
    }
    //reset m_block_size
    m_block_size=0;
  }