Exemplo n.º 1
0
void MainWindow::displayTooltip(QMouseEvent *e)
{
    static bool isFirstTime = true;
    static int selectionStart;
    static QString selectedText;
    static bool isExisted = false; //мы выделяли существующее в словаре?
    bool isExist = false;
    int i;

    QPoint p = e->pos();

    QTextCursor tc = ui->textEdit->cursorForPosition(p);
    tc.select(QTextCursor::WordUnderCursor);

    if (selectionStart != tc.selectionStart()) {

        //проверяем, есть ли слово в словаре
        for(i = 0; i < bptr->getListWords().size(); i++)
        {
            if(!bptr->getListWords().at(i).word.compare(tc.selectedText(), Qt::CaseInsensitive))
            {
                isExist = true;
                break;
            }
            if(!bptr->getListWords().at(i).word.compare(selectedText, Qt::CaseInsensitive))
            {
                isExisted = true;
            }
        }

        if (!isFirstTime)
        {
            QToolTip::hideText();   //скрываем предыдущий тултип
            //Надо удалить выделение предыдущего слова
            QTextCursor tc(ui->textEdit->document());
            tc.setPosition(selectionStart);
            tc.select(QTextCursor::WordUnderCursor);

            if(isExisted)
                tc.insertHtml(QString("<u>" + selectedText + "</b>"));
            else
            {
                tc.insertHtml(QString(selectedText));
            }
            isExisted = false;
        }
        selectionStart = tc.selectionStart();
        selectedText = tc.selectedText();

        if (tc.selectedText().length() > 0 && isExist)
        {
//            QToolTip::showText(e->globalPos(), bptr->getListWords().at(i).toString(),
//                               ui->textEdit, ui->textEdit->cursorRect());
            QToolTip::showText(e->globalPos(), bptr->getListWords().at(i).toString(),
                               ui->textEdit, ui->textEdit->cursorRect(tc));
            isFirstTime = false;
            tc.insertHtml(QString("<b>" + tc.selectedText() + "</b>"));
        }
    }
}
Exemplo n.º 2
0
void DocBlock::addLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = Link;
    path = url.toString();
    QString str = path;

    // add file icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    QFileInfo info(url.toLocalFile());
    QFileIconProvider *provider = new QFileIconProvider();
    QImage image(provider->icon(info).pixmap(16, 16).toImage());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(image);
	
    if (str.lastIndexOf("/") > -1)
        str = str.right(str.size() - str.lastIndexOf("/") - 1);

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);
	
    if (arrow != 0) arrow->setColor(getHoverColor());

    updateBlock(false);
}
Exemplo n.º 3
0
void FillCellHelper::fill( QTextTable* textTable, KDReports::ReportBuilder& builder, QTextDocument& textDoc, QTextTableCell& cell )
{
    cellCursor = cell.firstCursorPosition();
    QTextCharFormat cellFormat = cell.format();
    if ( background.isValid() ) {
        cellFormat.setBackground( background );
    }
    cellFormat.setVerticalAlignment( toVerticalAlignment( alignment ) );
    cell.setFormat( cellFormat );

    QTextBlockFormat blockFormat = cellCursor.blockFormat();
    blockFormat.setAlignment( alignment );
    blockFormat.setNonBreakableLines( nonBreakableLines );
    builder.setupBlockFormat( blockFormat );

    cellCursor.setBlockFormat( blockFormat );

    const bool hasIcon = !cellDecoration.isNull();
    const bool iconAfterText = decorationAlignment.isValid() && ( decorationAlignment.toInt() & Qt::AlignRight );
    if ( hasIcon && !iconAfterText ) {
        insertDecoration( builder, textDoc );
    }

    QTextCharFormat charFormat = cellCursor.charFormat();
    if ( cellFont.isValid() ) {
        QFont cellQFont = qvariant_cast<QFont>( cellFont );
#if QT_VERSION >= QT_VERSION_CHECK(5, 3, 0)
        charFormat.setFont( cellQFont, QTextCharFormat::FontPropertiesSpecifiedOnly );
#else
        charFormat.setFont( cellQFont );
#endif
    } else {
        charFormat.setFont( builder.defaultFont() );
    }
    if ( foreground.isValid() )
        charFormat.setForeground( foreground );
    cellCursor.setCharFormat( charFormat );

    if ( hasIcon && !iconAfterText ) {
        cellCursor.insertText( QChar::fromLatin1( ' ' ) ); // spacing between icon and text
    }

    //qDebug() << cellText;
    if (cellText.startsWith(QLatin1String("<qt>")) || cellText.startsWith(QLatin1String("<html>")))
        cellCursor.insertHtml( cellText );
    else
        cellCursor.insertText( cellText );

    if ( hasIcon && iconAfterText ) {
        cellCursor.insertText( QChar::fromLatin1( ' ' ) ); // spacing between icon and text
        insertDecoration( builder, textDoc );
    }

    if ( span.width() > 1 || span.height() > 1 )
        textTable->mergeCells( cell.row(), cell.column(), span.height(), span.width() );
}
Exemplo n.º 4
0
void NotesWindow::setVisible(bool visible)
{
    if (ui->textEdit->document()->isEmpty()) {
        qSort(m_notes);
        QTextCursor cursor = ui->textEdit->textCursor();
        foreach (const NoteText &note, m_notes) {
            //cursor.insertText(s_separator);
            cursor.insertHtml(QStringLiteral("<hr>"));
            cursor.insertBlock();
            cursor.setBlockFormat(QTextBlockFormat());
            cursor.insertHtml(note.htmlHeader());
            cursor.setBlockFormat(QTextBlockFormat());
            cursor.insertBlock();
            cursor.insertBlock();
            if (note.isHtml())
                cursor.insertHtml(note.text());
            else
                cursor.insertText(note.text());
        }
Exemplo n.º 5
0
void MainWindow::on_insertHtml_clicked()
{
    QTextEdit *pEdit = textEditor.editor;
    QTextCursor cursor = pEdit->textCursor();

    InsertHtmlDialog dlg(this);
    if(dlg.exec() != QDialog::Accepted)
        return;
    cursor.insertHtml(dlg.htmlText());
}
Exemplo n.º 6
0
void dlgIRC::slot_joined(QString nick, QString chan )
{
    const QString _t = QTime::currentTime().toString();
    QString t = tr("<font color=#008800>[%1] %2 has joined the channel.</font>").arg(_t).arg(nick);
    QTextCursor cur = irc->textCursor();
    cur.movePosition(QTextCursor::End);
    cur.insertBlock();
    cur.insertHtml(t);
    irc->verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
    nickList->addItem( nick );
}
Exemplo n.º 7
0
void dlgIRC::slot_parted(QString nick, QString chan, QString msg )
{
    const QString _t = QTime::currentTime().toString();
    QString t = tr("<font color=#888800>[%1] %2 has left the channel.</font>").arg(_t).arg(nick);
    QTextCursor cur = irc->textCursor();
    cur.movePosition(QTextCursor::End);
    cur.insertBlock();
    cur.insertHtml(t);
    irc->verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
    nickList->clear();
    session->sendCommand( IrcCommand::createNames( "#mudlet" ) );
}
Exemplo n.º 8
0
void ChatTextEdit::addEmoji(QString emojiName)
{
    if (isEmojiWidgetOpen && Client::autoCloseEmoji)
        closeEmojiWidget();

    QTextCursor cursor = textCursor();

    QString html = "<img src=\"/usr/share/yappari/icons/32x32/" + emojiName +".png\" />";

    cursor.insertHtml(html);
    setFocus();
}
Exemplo n.º 9
0
void DisplayText::_insertText(const QString text, const QString bg)
{
    QString tt = text.mid(0,_maxDisplayedCharacters); //truncate to max display chars
    QString s = "<table border=0 cellspacing=0 width=100%><tr><td bgcolor=\"" +
                bg + "\"><pre>" + tt + "</pre></td></tr></table>";

    QTextCursor cursor = textCursor();
    cursor.movePosition(QTextCursor::End);
    QTextBlockFormat bf = cursor.blockFormat();
    bf.setBackground(QBrush(QColor(bg)));
    cursor.insertHtml(s);
    this->setTextCursor(cursor);
}
Exemplo n.º 10
0
void ChatMessageArea::setHtml(const QString& html) {
    // Create format with updated line height
    QTextBlockFormat format;
    format.setLineHeight(CHAT_MESSAGE_LINE_HEIGHT, QTextBlockFormat::ProportionalHeight);

    // Possibly a bug in QT, the format won't take effect if `insertHtml` is used first.  Inserting a space and deleting
    // it after ensures the format is applied.
    QTextCursor cursor = textCursor();
    cursor.setBlockFormat(format);
    cursor.insertText(" ");
    cursor.insertHtml(html);
    cursor.setPosition(0);
    cursor.deleteChar();
}
Exemplo n.º 11
0
void GroupItem::setText()
{
    document()->clear();
    prepareGeometryChange();
    QTextCursor cursor = textCursor();
    cursor.movePosition (QTextCursor::End);
    // TODO add style sheet
    QString html = "<div id='GroupItem'>" +
                   QString::fromUtf8 (groupName) + "</div>";
    if (not showChildItems)
    {
        html.append ("<span id='itemCount'> (" +
                     QString::number (childItems().size()) + ")</span>");
    }
    cursor.insertHtml (html);
    setTextCursor (cursor);
}
Exemplo n.º 12
0
/*!
    \fn IRenderizador::hacerInforme()
 */
void IRenderizador::hacerInforme()
{
 QTextCursor *cursor = new QTextCursor( _doc );
 cursor->movePosition( QTextCursor::End );
 // cargar la cabecera
 cursor->insertHtml( cargarCabecera() );
 // Pongo la fecha del informe
 cursor->insertText( QString( "Fecha: %1.\n" ).arg( QDate::currentDate().toString( "dd/MM/yyyy" ) ) );
 // Establecimiento en cuestion
 QSqlQuery *colaAuxiliar = new QSqlQuery();
 colaAuxiliar->exec( QString("SELECT nombre FROM car_establecimientos WHERE id_establecimiento = '%1'").arg( _idEstablecimiento ) );
 if( colaAuxiliar->next() )
 {
 	cursor->insertText( QString( "Establecimiento:  %1\n" ).arg( colaAuxiliar->record().value(0).toString() ) );
 }
 else
 { qDebug( "Error al ejecutar la cola de nombre de establecimiento" ); }
 // Busco las caravanas que estan en ese establecimiento
 colaAuxiliar->exec( QString( "SELECT codigo FROM car_caravana WHERE id_caravana IN (  SELECT id_caravana FROM car_carv_tri WHERE id_tri IN (  SELECT id_tri FROM car_tri WHERE ( id_estab_origen = '%1' OR id_estab_destino = '%1' ) AND razon IN ( 2, 3 ) ) )" ).arg( _idEstablecimiento ) );
 if( colaAuxiliar->size() == 0 )
 {
   cursor->movePosition( QTextCursor::End );
   cursor->insertText( "\n\nNo existen resultados" );
 }
 else
 {
	// Genero la tabla
	cursor->movePosition( QTextCursor::End );
	tabla = cursor->insertTable( 1, 2 );
	QTextTableFormat formatoTabla = tabla->format();
	formatoTabla.setHeaderRowCount(1);
	tabla->setFormat( formatoTabla );
	tabla->cellAt( 0,0 ).firstCursorPosition().insertHtml( "#Num" );
	tabla->cellAt( 0,1 ).firstCursorPosition().insertHtml( "#Caravana" );
	while( colaAuxiliar->next() )
	{
		int pos = tabla->rows();
		tabla->insertRows( pos, 1 );
		tabla->cellAt( pos, 0 ).firstCursorPosition().insertHtml( QString( "%L1" ).arg( pos ) );
		tabla->cellAt( pos, 1 ).firstCursorPosition().insertHtml( colaAuxiliar->record().value(0).toString() );
	}
 } // fin else cola != 0
 delete colaAuxiliar;
 delete cursor;
 return;
}
Exemplo n.º 13
0
void dlgIRC::irc_gotMsg( QString a, QString b, QString c )
{
    qDebug()<<"a<"<<a<<"> b<"<<b<<">"<<" c<"<<c<<">";
    mudlet::self()->getHostManager()->postIrcMessage( a, b, c );
    c.replace("<","&#60;");
    c.replace(">","&#62;");
    const QString _t = QTime::currentTime().toString();

    QRegExp rx("(http://[^ ]*)");
    QStringList list;
    int pos = 0;

    while( (pos = rx.indexIn(c, pos)) != -1)
    {
        QString _l = "<a href=";
        _l.append( rx.cap(1) );
        _l.append(" >");
        c.insert(pos,_l);
        pos += (rx.matchedLength()*2)+9;
        c.insert(pos,"< /a>");
        pos += 5;
    }

    const QString msg = c;
    const QString n = a;
    QString t;
    if( b == mNick )
        t = tr("<font color=#a5a5a5>[%1] </font>msg from <font color=#ff0000>%2</font><font color=#ff0000>: %3</font>").arg(_t).arg(n).arg(msg);
    else if( a == mNick )
        t = tr("<font color=#a5a5a5>[%1] </font><font color=#00aaaa>%2</font><font color=#004400>: %3</font>").arg(_t).arg(n).arg(msg);
    else
        t = tr("<font color=#a5a5a5>[%1] </font><font color=#0000ff>%2</font><font color=#000000>: %3</font>").arg(_t).arg(n).arg(msg);


    QString hi = QString("<font color=#aa00aa>%1</font>").arg(mNick);
    t.replace(mNick, hi);
    QTextCursor cur = irc->textCursor();
    cur.movePosition(QTextCursor::End);
    cur.insertBlock();
    cur.insertHtml(t);
    irc->verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}
Exemplo n.º 14
0
void ConsoleLog::appendToLog(QString message)
{
    bool scrollToBottom = false;

    if(_log->verticalScrollBar()->value() == _log->verticalScrollBar()->maximum())
    {
        scrollToBottom = true;
    }

    QTextBlockFormat format;
    format.setLineHeight(30, 0);

    QTextCursor cursor = _log->textCursor();
    cursor.setBlockFormat(format);
    int pos = cursor.position();
    cursor.setPosition(_log->toPlainText().length());
    cursor.insertHtml(message + "<br/><br/><br/>");
    cursor.setPosition(pos);

    if(scrollToBottom) _log->verticalScrollBar()->setValue(_log->verticalScrollBar()->maximum());
}
Exemplo n.º 15
0
void dlgIRC::irc_gotMsg2( QString a, QStringList c )
{
    QString m = c.join(" ");
    m.replace("<","&#60;");
    m.replace(">","&#62;");
    const QString _t = QTime::currentTime().toString();

    QRegExp rx("(http://[^ ]*)");
    QStringList list;

    int pos = 0;

    while( (pos = rx.indexIn(m, pos)) != -1)
    {
        QString _l = "<a href=";
        _l.append( rx.cap(1) );
        _l.append(" >");
        m.insert(pos,_l);
        pos += (rx.matchedLength()*2)+9;
        m.insert(pos,"< /a>");
        pos += 5;
    }

    const QString msg = m;
    const QString n = a;
    QString t;
    if( msg.contains( mNick ) )
        t = tr("<font color=#a5a5a5>[%1] </font><font color=#ff0000>%2</font><font color=#000000>: %3</font>").arg(_t).arg(n).arg(msg);
    else
        t = tr("<font color=#a5a5a5>[%1] </font><font color=#0000ff>%2</font><font color=#000000>: %3</font>").arg(_t).arg(n).arg(msg);

    //QString t = tr("<font color=#aaaaaa>[%1] </font><font color=#ff0000>%2</font><font color=#000000>: %3</font>").arg(_t).arg(n).arg(msg);
    QTextCursor cur = irc->textCursor();
    cur.movePosition(QTextCursor::End);
    cur.insertBlock();
    cur.insertHtml(t);
    irc->verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}
Exemplo n.º 16
0
ResultItem* TextResultItem::updateFromResult(Cantor::Result* result)
{
    switch(result->type()) {
    case Cantor::TextResult::Type:
        {
            QTextCursor cursor = textCursor();
            cursor.movePosition(QTextCursor::Start);
            cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
            QString html = result->toHtml();
            if (html.isEmpty())
                cursor.removeSelectedText();
            else
                cursor.insertHtml(html);
            return this;
        }
    case Cantor::LatexResult::Type:
        setLatex(dynamic_cast<Cantor::LatexResult*>(result));
        return this;
    default:
        deleteLater();
        return create(parentEntry(), result);
    }
}
Exemplo n.º 17
0
// Вставка MIME данных
void EditorTextArea::insertFromMimeData(const QMimeData *source)
{
    QTextCursor cursor = this->textCursor();
    QTextDocument *document = this->document();

// Вставка картинки
    if(source->hasImage())
    {
        QImage image=qvariant_cast<QImage>(source->imageData());

        // Картинка будет хранится в ресурсах во внутреннем формате
        // без потери качества, поэтому затем при записи
        // легко сохраняется в PNG формат. Чтобы избежать путаницы,
        // сразу имя ресурса картинки задается как PNG файл
        QString imageName="image"+QString::number(rand())+".png";

        document->addResource(QTextDocument::ImageResource, QUrl(imageName), image);
        cursor.insertImage(imageName);
        return;
    }

    if(source->hasHtml())
    {
        QString html=qvariant_cast<QString>(source->html());
        cursor.insertHtml(html);
        return;
    }

    if(source->hasText())
    {
        QString text=qvariant_cast<QString>(source->text());
        cursor.insertText(text);
        return;
    }

}
Exemplo n.º 18
0
void DocBlock::addWebLink(QUrl url)
{
    myTextItem->setTextInteractionFlags(Qt::TextSelectableByKeyboard);
    docType = WebLink;

    // add web icon
    QTextCursor cursor = QTextCursor(myTextItem->document());
    cursor.document()->setPlainText(" ");
    cursor.insertImage(QImage(":/weblink.png"));

    path = url.toString();
    QString str = path;

    if (str.lastIndexOf("/") > 7)
        str = str.left(str.lastIndexOf("/"));

    QString html = "<a href=\""+path+"\">"+str+"</a>";
    cursor.insertHtml(html);

    if (arrow != 0)
        arrow->setColor(getHoverColor());

    updateBlock(false);
}
Exemplo n.º 19
0
void CDiaryEdit::draw(QTextDocument& doc)
{
    CDiaryEditLock lock(this);
    QFontMetrics fm(QFont(font().family(),10));

    bool hasGeoCaches = false;
    int cnt;
    int w = doc.textWidth();
    int pointSize = ((10 * (w - 2 * ROOT_FRAME_MARGIN)) / (CHAR_PER_LINE *  fm.width("X")));

    if(pointSize == 0) return;

    doc.setUndoRedoEnabled(false);

    QFont f = textEdit->font();
    f.setPointSize(pointSize);
    textEdit->setFont(f);

    QTextCharFormat fmtCharHeading1;
    fmtCharHeading1.setFont(f);
    fmtCharHeading1.setFontWeight(QFont::Black);
    fmtCharHeading1.setFontPointSize(f.pointSize() + 8);

    QTextCharFormat fmtCharHeading2;
    fmtCharHeading2.setFont(f);
    fmtCharHeading2.setFontWeight(QFont::Black);
    fmtCharHeading2.setFontPointSize(f.pointSize() + 4);

    QTextCharFormat fmtCharStandard;
    fmtCharStandard.setFont(f);

    QTextCharFormat fmtCharHeader;
    fmtCharHeader.setFont(f);
    fmtCharHeader.setBackground(Qt::darkBlue);
    fmtCharHeader.setFontWeight(QFont::Bold);
    fmtCharHeader.setForeground(Qt::white);

    QTextBlockFormat fmtBlockStandard;
    fmtBlockStandard.setTopMargin(10);
    fmtBlockStandard.setBottomMargin(10);
    fmtBlockStandard.setAlignment(Qt::AlignJustify);

    QTextFrameFormat fmtFrameStandard;
    fmtFrameStandard.setTopMargin(5);
    fmtFrameStandard.setBottomMargin(5);
    fmtFrameStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN);

    QTextFrameFormat fmtFrameRoot;
    fmtFrameRoot.setTopMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setBottomMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setLeftMargin(ROOT_FRAME_MARGIN);
    fmtFrameRoot.setRightMargin(ROOT_FRAME_MARGIN);

    QTextTableFormat fmtTableStandard;
    fmtTableStandard.setBorder(1);
    fmtTableStandard.setBorderBrush(Qt::black);
    fmtTableStandard.setCellPadding(4);
    fmtTableStandard.setCellSpacing(0);
    fmtTableStandard.setHeaderRowCount(1);
    fmtTableStandard.setTopMargin(10);
    fmtTableStandard.setBottomMargin(20);
    fmtTableStandard.setWidth(w - 2 * ROOT_FRAME_MARGIN);

    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::FixedLength, 32);
    constraints << QTextLength(QTextLength::VariableLength, 50);
    constraints << QTextLength(QTextLength::VariableLength, 100);
    fmtTableStandard.setColumnWidthConstraints(constraints);

    doc.rootFrame()->setFrameFormat(fmtFrameRoot);
    QTextCursor cursor = doc.rootFrame()->firstCursorPosition();

    cursor.insertText(diary.getName(), fmtCharHeading1);
    cursor.setCharFormat(fmtCharStandard);
    cursor.setBlockFormat(fmtBlockStandard);

    diary.diaryFrame = cursor.insertFrame(fmtFrameStandard);
    {
        QTextCursor cursor1(diary.diaryFrame);

        cursor1.setCharFormat(fmtCharStandard);
        cursor1.setBlockFormat(fmtBlockStandard);

        if(diary.getComment().isEmpty())
        {
            cursor1.insertText(tr("Add your own text here..."));
        }
        else
        {
            cursor1.insertHtml(diary.getComment());
        }
        cursor.setPosition(cursor1.position()+1);
    }

    if(!diary.getWpts().isEmpty())
    {
        QList<CWpt*>& wpts = diary.getWpts();
        cursor.insertText(tr("Waypoints"),fmtCharHeading2);

        QTextTable * table = cursor.insertTable(wpts.count()+1, eMax, fmtTableStandard);
        diary.tblWpt = table;
        table->cellAt(0,eSym).setFormat(fmtCharHeader);
        table->cellAt(0,eInfo).setFormat(fmtCharHeader);
        table->cellAt(0,eComment).setFormat(fmtCharHeader);

        table->cellAt(0,eInfo).firstCursorPosition().insertText(tr("Info"));
        table->cellAt(0,eComment).firstCursorPosition().insertText(tr("Comment"));

        cnt = 1;
        qSort(wpts.begin(), wpts.end(), qSortWptLessTime);

        foreach(CWpt * wpt, wpts)
        {

            table->cellAt(cnt,eSym).firstCursorPosition().insertImage(wpt->getIcon().toImage().scaledToWidth(16, Qt::SmoothTransformation));
            table->cellAt(cnt,eInfo).firstCursorPosition().insertText(wpt->getName() + "\n" + wpt->getInfo(), fmtCharStandard);

            QTextCursor c = table->cellAt(cnt,eComment).firstCursorPosition();
            c.setCharFormat(fmtCharStandard);
            c.setBlockFormat(fmtBlockStandard);
            c.insertHtml(wpt->getComment());

            if(wpt->isGeoCache())
            {
                hasGeoCaches = true;
            }
            cnt++;
        }
Exemplo n.º 20
0
void CargaUniformeConstante::crearReporte(QTextEdit *textEdit)
{
    QTextCursor c = textEdit->document()->rootFrame()->lastCursorPosition();
    c.insertHtml(description());
}
Exemplo n.º 21
0
//Lecture des tableaux
bool OpenDocument::contenu_tableaux(QDomElement e, QTextCursor &curseur){
    //Création de l'instance d'erreur
    ErrorManager instance_erreur;
    QList<QStringList> full_table;

    QDomNode enfants = e.firstChild();
    while(!enfants.isNull()){
        if(enfants.isElement()){
            QDomElement type = enfants.toElement();
            //On parcours le type d'élément

            //Table-column ne sert à rien.  L'important, c'est table-row et table-cell
            /*if(type.tagName() == "table:table-column"){//Tout roule
                QDomNode ligne = type.firstChildElement("table:table-row");
                QDomElement elem_ligne = ligne.toElement();
                QMessageBox::critical(0, "t", elem_ligne.tagName());
                if(elem_ligne.tagName() == "table:table-row"){
                    QMessageBox::information(0, "t", "On z'y est!");
                }
                //QMessageBox::information(0, "col", "<col></col>");
            }*/
            if(type.tagName() == "table:table-row"){
                if(!type.hasChildNodes()){
                    instance_erreur.Erreur_msg(tr("ODT : aucune cellule détectée dans le tableau"), QMessageBox::Ignore);
                    return false;
                }
                //NADA
                else{
                    //Si on a trouvé du contenu
                    QDomNode node_cell = type.firstChildElement("table:table-cell");
                    while(!node_cell.isNull()){
                        //Normalement, ce sont de simples paragraphes, donc on les envoie à la fonction de lecture des paragraphes
                        contenu_paragraphe(node_cell.firstChild().toElement(), curseur, false, false, true);
                        node_cell = node_cell.nextSibling();
                    }
                    //Si on est ici, c'est qu'on a fini de lire la ligne du tableau -> on l'insère dans la QList
                    full_table.append(ligne_tableau);
                    //On vide la QStringList
                    ligne_tableau.clear();
                }
            }
        }
        //On passe au suivant (sinon, boucle infinie, ouille!)
        enfants = enfants.nextSibling();
    }
    //Si on est ici, c'est que le tableau est rempli.
    //On le fourgue dans le curseur et hop, à l'affichage
    //HA!  Ça a marché du premier coup!!!  Je m'améliore :D
    //On insère le tableau en HTML comme ça on gère en même temps les anomalies de cases (cases soudées/divisées)
    QString mon_tableau = "<table border=\"1\">";
    for(int i=0; i<full_table.size(); i++){
        mon_tableau.append("<tr>");
        for(int j=0; j<full_table.at(i).size(); j++){
            mon_tableau.append("<td>");
            mon_tableau.append(full_table.at(i).at(j));
            mon_tableau.append("</td>");
        }
        mon_tableau.append("</tr>");
    }
    //On ferme le tableau et on l'insère
    mon_tableau.append("</table>");
    curseur.insertHtml(mon_tableau);
    return true;
}
Exemplo n.º 22
0
void dlgIRC::irc_gotMsg3( QString a, uint code, QStringList c )
{
    qDebug()<<"code="<<code<<" list="<<c;
    if( code == Irc::RPL_TOPIC && c.size()>2 )
    {
        QString m = c.join(" ");
        m.replace("<","&#60;");
        m.replace(">","&#62;");
        const QString _t = QTime::currentTime().toString();

        QRegExp rx("(http://[^ ]*)");
        QStringList list;

        int pos = 0;

        while( (pos = rx.indexIn(m, pos)) != -1)
        {
            QString _l = "<a href=";
            _l.append( rx.cap(1) );
            _l.append(" >");
            m.insert(pos,_l);
            pos += (rx.matchedLength()*2)+9;
            m.insert(pos,"< /a>");
            pos += 5;
        }

        const QString msg = m;
        const QString n = a;
        QString t = tr("<font color=#00aaaa><br>INFO: supported commands: /nick and /msg <br><font color=#0000ff>CHANNEL TOPIC:</font><font color=#00aa00>: %1</font>").arg(msg);
        QTextCursor cur = irc->textCursor();
        cur.movePosition(QTextCursor::End);
        cur.insertBlock();
        t.replace(mNick, "");
        cur.insertHtml(t);
    }
    else if( code == Irc::RPL_NAMREPLY && c.size()>=3 )
    {
        QString nicks = c[3];
        QStringList nList = nicks.split(" ");
        nickList->clear();
        for( int i=0; i<nList.size(); i++ )
        {
            nickList->addItem( nList[i]);
        }
    }
    else if( code == Irc::ERR_NICKNAMEINUSE )
    {
        QString m = c.join(" ");
        if( m.contains( "name is already in use" ) )
        {
            mNick.append("_");
            session->setNickName( mNick );
            irc_gotMsg( "", "", "You have changed your nick." );
        }
    }
    else if( code == Irc::RPL_ENDOFNAMES )
        return;
    else
    {
        irc_gotMsg2("", c.replaceInStrings(mNick, "") );
    }
    irc->verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);
}
Exemplo n.º 23
0
bool ChatTextEdit::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent *keyEvent = (QKeyEvent *) event;

        if (keyEvent->key() == Qt::Key_Up)
        {
            // Key up
            QTextCursor cursor = textCursor();
            int pos = cursor.position();
            bool sel = keyEvent->modifiers() == Qt::ShiftModifier;
            cursor.movePosition(QTextCursor::Up, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor));

            if (pos == cursor.position())
                cursor.movePosition(QTextCursor::Start, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor));

            setTextCursor(cursor);

            return true;
        }
        else  if (keyEvent->key() == Qt::Key_Down)
        {
            // Key down
            QTextCursor cursor = textCursor();
            int pos = cursor.position();
            bool sel = keyEvent->modifiers() == Qt::ShiftModifier;
            cursor.movePosition(QTextCursor::Down, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor));

            if (pos == cursor.position())
                cursor.movePosition(QTextCursor::End, (sel ? QTextCursor::KeepAnchor : QTextCursor::MoveAnchor));

            setTextCursor(cursor);
            return true;
        }
        else if (keyEvent->nativeScanCode() == 36)
        {
            // Return pressed
            if (Client::enterIsSend && !(keyEvent->modifiers() & Qt::ShiftModifier))
            {
                isComposing = false;
                emit returnPressed();
                return true;
            }
        }
        else if (keyEvent->nativeScanCode() == 54 &&
                 keyEvent->modifiers() == Qt::ControlModifier)
        {
            // Copy
            QTextCursor cursor = textCursor();
            if (cursor.hasSelection())
            {
                QTextDocumentFragment selection = cursor.selection();
                QClipboard *clipboard = QApplication::clipboard();
                clipboard->setText(Utilities::htmlToWAText(selection.toHtml()));

                QMaemo5InformationBox::information(this,"Copied");
                return true;
            }
        }
        else if (keyEvent->nativeScanCode() == 55 &&
                 keyEvent->modifiers() == Qt::ControlModifier)
        {
            // Paste event
            QTextCursor cursor = textCursor();
            QClipboard *clipboard = QApplication::clipboard();

            cursor.insertHtml(Utilities::WATextToHtml(clipboard->text(),32,false));

            return true;
        }
        else if (!isComposing)
        {
            isComposing = true;
            emit composing();
        }
        else
        {
            lastKeyPressed = QDateTime::currentMSecsSinceEpoch();
            composingTimer.start(2000);
        }
    }
    else if (event->type() == QEvent::InputMethod)
    {
        QInputMethodEvent *inputEvent = (QInputMethodEvent *) event;

        //Utilities::logData("Commit String: '" + inputEvent->commitString() + "'");
        if (inputEvent->commitString() == "\n" && Client::enterIsSend)
        {
            // Let's hide the keyboard if it was shown
            QTimer::singleShot(0,this,SLOT(closeKB()));
            isComposing = false;
            emit returnPressed();
            return true;
        }
    }

    return QTextEdit::eventFilter(obj,event);
}
Exemplo n.º 24
0
void HistoryWindow::on_dateTreeWidget_currentItemChanged(QTreeWidgetItem *dayItem, QTreeWidgetItem *)
{
	QTreeWidgetItem *monthItem = dayItem ? dayItem->parent() : nullptr;
	if (!dayItem || !monthItem)
		return;

	if (dayItem->data(0, Qt::UserRole).type() != QVariant::Date)
		return;
	if (monthItem->data(0, Qt::UserRole).type() != QVariant::Date)
		return;

	auto contactIndex = ui.fromComboBox->currentIndex();
	auto contactInfo = ui.fromComboBox->itemData(contactIndex).value<History::ContactInfo>();
	auto date = dayItem->data(0, Qt::UserRole).toDate();
	QDateTime from(date, QTime(0, 0));
	QDateTime to(date, QTime(23, 59, 59, 999));
	int count = std::numeric_limits<int>::max();

	history()->read(contactInfo, from, to, count).connect(this, [this, contactInfo, date] (const MessageList &messages) {
		int contactIndex = ui.fromComboBox->currentIndex();
		auto currentContactInfo = ui.fromComboBox->itemData(contactIndex).value<History::ContactInfo>();
		if (!(currentContactInfo == contactInfo))
			return;

		QTextDocument *doc = ui.historyLog->document();
		doc->setParent(0);
		ui.historyLog->setDocument(0);
		doc->clear();
		QTextCursor cursor = QTextCursor(doc);
		QTextCharFormat defaultFont = cursor.charFormat();
		QTextCharFormat serviceFont = cursor.charFormat();
		serviceFont.setForeground(Qt::darkGreen);
		serviceFont.setFontWeight(QFont::Bold);
		QTextCharFormat incomingFont = cursor.charFormat();
		incomingFont.setForeground(Qt::red);
		incomingFont.setFontWeight(QFont::Bold);
		QTextCharFormat outgoingFont = cursor.charFormat();
		outgoingFont.setForeground(Qt::blue);
		outgoingFont.setFontWeight(QFont::Bold);
		const QString serviceMessageTitle = tr("Service message");
		const QString resultString = QStringLiteral("<span style='background: #ffff00'>\\1</span>");
		cursor.beginEditBlock();

		Account *account = findAccount(contactInfo);
		ChatUnit *unit = findContact(contactInfo);

		QString accountNickname = account ? account->name() : contactInfo.account;
		QString fromNickname = unit ? unit->title() : contactInfo.contact;
		int in_count = 0;
		int out_count = 0;

		for (const Message &message : messages) {
			bool service = message.property("service", false);
			QDateTime time = message.time();
			bool incoming = message.isIncoming();
			QString historyMessage = message.html();
			QString sender = message.property("senderName", incoming ? fromNickname : accountNickname);

			incoming ? in_count++ : out_count++;
			if (service) {
				cursor.setCharFormat(serviceFont);
				cursor.insertText(serviceMessageTitle);
			} else {
				cursor.setCharFormat(incoming ? incomingFont : outgoingFont);
				cursor.insertText(sender);
			}
			cursor.insertText(QStringLiteral(" (")
							  % time.toString(QStringLiteral("dd.MM.yyyy hh:mm:ss"))
							  % QStringLiteral(")"));
			cursor.setCharFormat(defaultFont);
			cursor.insertText(QStringLiteral("\n"));
			if (m_search_word.isEmpty()) {
				cursor.insertHtml(historyMessage);
				cursor.insertText(QStringLiteral("\n"));
			} else {
				cursor.insertHtml(historyMessage.replace(m_search, resultString));
				cursor.insertText(QStringLiteral("\n"));
			}
		}
		cursor.endEditBlock();
		doc->setParent(ui.historyLog);
		ui.historyLog->setDocument(doc);
		if (m_search_word.isEmpty())
			ui.historyLog->moveCursor(QTextCursor::End);
		else
			ui.historyLog->find(m_search_word);
		ui.historyLog->verticalScrollBar()->setValue(ui.historyLog->verticalScrollBar()->maximum());

		ui.label_in->setText(tr("In: %L1").arg(in_count));
		ui.label_out->setText(tr("Out: %L1").arg(out_count));
		ui.label_all->setText(tr("All: %L1").arg(in_count + out_count));
	});
}
Exemplo n.º 25
0
///////////////////////////////////////////////////////////////////////////////////
//fin modele-----------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////
void ProduceDoc::fillTable(QList<QVector<QString> > & tableau,
                           QTextTableFormat & tableFormatOrganized,
                           QTextCursor * cursorForFillFunction,
                           QString & thisMonth,
                           QStringList & listSums,
                           int choice,
                           const QString & totalMovementString){
    QList<QVector<QString> > tableauInFonction;
                         tableauInFonction         = tableau;
        int              nbreLignesTableau         = tableauInFonction.size();
        int              nbreColonnesTableau       = TABLE_NAME_OF_ACTS;
        int              sizeOfTable               = nbreLignesTableau*nbreColonnesTableau;
        QTextTableFormat tableFormat               = tableFormatOrganized;
        QTextCursor     *cursortrieinfunction      = cursorForFillFunction;
        QString          thisMonthfonction         = thisMonth;
        QString          type                      = "";
        QStringList      totalSumsList             = listSums;
        QString total;
        /*for (int i = 0; i < totalSumsList.size(); i += 1)
        {
            if (WarnDebugMessage)

              qDebug() << __FILE__ << QString::number(__LINE__) << " totalSumsList =" << totalSumsList[i] ;
            }*/
        if(choice == RECEIPTS_TYPE){
            type = tr("Receipts");
            total = totalSumsList[SUMS_SUM];
                        }
        if(choice == MOVEMENTS_TYPE){
            type = tr("Movements");
            total = totalMovementString;
            }
        QTextBlockFormat centerHead ;
       //centrer                       .setBackground(Qt::yellow) ;
       if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << " thisMonthfonction =" << thisMonthfonction ;
           QString heads = tr("Month of ")+thisMonthfonction+" = "+type;
       if (thisMonthfonction == tr("complete year"))
       {
           heads = tr("Total of ")+thisMonthfonction+" = "+type;
           }
           centerHead                    .setAlignment(Qt::AlignCenter) ;
           cursortrieinfunction         -> insertBlock(centerHead);
           cursortrieinfunction         -> insertHtml("<font size = 6 color = #3300FF><bold><br/>"
                                                      "<br/>"+heads+"<bold>"
                                                      "</font><br/><br/>");
        QTextTableFormat tableFormatDone;
        myFormat(tableFormatDone,m_tablesRecapParameters);
        if (WarnDebugMessage)

              qDebug() << __FILE__ << QString::number(__LINE__) << " thread 10 "   ;
        if(sizeOfTable!= 0){
            if((thisMonthfonction != tr("complete year")) ){
                QTextTable * table = cursortrieinfunction->insertTable(nbreLignesTableau,
                                                                       nbreColonnesTableau,
                                                                       tableFormat);
            for(int i=0 ; i< nbreLignesTableau ; i++){
                QVector<QString> vectorString;
                    vectorString = tableauInFonction[i];
                /*if (WarnDebugMessage)

              qDebug() << __FILE__ << QString::number(__LINE__) << "vectorString size  ="
                                     <<  QString::number(vectorString.size());*/
                QStringList list; // liste des données de la ligne
                /*if (WarnDebugMessage)

              qDebug() << __FILE__ << QString::number(__LINE__) << "nbreColonnesTableau  = "
                         << QString::number(nbreColonnesTableau)  ;*/
                for (int a = 0 ;a < nbreColonnesTableau ; a++){
                    QString str = vectorString[a];
                         list << str;
                         if (WarnDebugMessage)
                         qDebug() << __FILE__ << QString::number(__LINE__) << " str =" << str ;
                   }
                   double s = list[2].toDouble();
                   if(s > 0){
                      for(int j= 0 ; j < nbreColonnesTableau ; j++){
                          QTextTableCell cell    = table->cellAt(i,j);
                          QTextCursor cellCursor = cell.firstCursorPosition();
                          cellCursor             . insertText(list[j]);
                      }
                   }
            }
    QTextBlockFormat centrer ;
       //centrer                       .setBackground(Qt::yellow) ;
       centrer                        .setAlignment(Qt::AlignCenter) ;
       cursortrieinfunction         -> insertBlock(centrer);
       cursortrieinfunction         -> insertText("\n\n");
//----------------insertion fin de table-------------------------------------------
    if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "total  =" << total ;
    table                           -> insertRows(table->rows(),1);
    table                           -> mergeCells(table->rows()-1,0,1,2);//-1 car part de zero
    QTextTableCell cell              = table->cellAt(table->rows()-1,0);
     QTextCursor cellCursor          = cell.firstCursorPosition();
     QString totalMonth = QString("<html><font size = 4 color = #FF0000><bold>%1 %2 <bold></font></html>")
                          .arg(tr("Total of "),thisMonthfonction);
     cellCursor                       .insertHtml(totalMonth);
    QTextTableCell cell2             = table->cellAt(table->rows()-1,2);
     QTextCursor cellCursor2         = cell2.firstCursorPosition();
     table                          -> mergeCells(table->rows()-1,2,1,3);
     cellCursor2                      .insertText(total);
    cursortrieinfunction            -> movePosition(QTextCursor::End,QTextCursor::MoveAnchor,1);

    QTextBlockFormat centrer1 ;
       //centrer1                       .setBackground(Qt::yellow) ;
       centrer1                        .setForeground(Qt::red) ;
       centrer1                        .setAlignment(Qt::AlignCenter);
       QString headAccumulation = tr("Accumulation of ")+type+" "+tr("of")+" "+thisMonthfonction;
       cursortrieinfunction          -> insertBlock(centrer1);
       cursortrieinfunction          -> insertHtml ("<font size = 6 color = #3300FF><bold><br/>"
                                                    "<br/>"+headAccumulation+"<bold></font>"
                                                    "<br/><br/>");
    }
    if (WarnDebugMessage)

              qDebug() << __FILE__ << QString::number(__LINE__) << " thread 12 "   ;
//---------------insertion table recapitulative----------------------------------
//---------------complete year---------------------------------------------------
    QTextTable *tableRecap;
    if(choice == RECEIPTS_TYPE){
        QString esp               = totalSumsList[SUMS_CASH];
        QString chq               = totalSumsList[SUMS_CHECKS];
        QString cb                = totalSumsList[SUMS_CREDITCARDS];
        QString banking           = totalSumsList[SUMS_BANKING];
        QString totalReceipts     = totalSumsList[SUMS_SUM];
        nbreLignesTableau         = int(SUMS_MaxParam) ;
        tableRecap                = cursortrieinfunction->insertTable(nbreLignesTableau,2,tableFormatDone);
        QTextTableCell cell00     = tableRecap->cellAt(0,0);//verify all table
         QTextCursor cellCursor00 = cell00.firstCursorPosition();
         cellCursor00             . insertText(tr("Total Cash"));
        QTextTableCell cell01     = tableRecap->cellAt(0,1);
         QTextCursor cellCursor01 = cell01.firstCursorPosition();
         cellCursor01             . insertText(esp);
        QTextTableCell cell10     = tableRecap->cellAt(1,0);
         QTextCursor cellCursor10 = cell10.firstCursorPosition();
         cellCursor10             . insertText(tr("Total checks"));
        QTextTableCell cell11     = tableRecap->cellAt(1,1);
         QTextCursor cellCursor11 = cell11.firstCursorPosition();
         cellCursor11             . insertText(chq);
        QTextTableCell cell20     = tableRecap->cellAt(2,0);
         QTextCursor cellCursor20 = cell20.firstCursorPosition();
         cellCursor20             . insertText(tr("Total credit cards"));
        QTextTableCell cell21     = tableRecap->cellAt(2,1);
         QTextCursor cellCursor21 = cell21.firstCursorPosition();
         cellCursor21             . insertText(cb);
        QTextTableCell cell30     = tableRecap->cellAt(3,0);
         QTextCursor cellCursor30 = cell30.firstCursorPosition();
         cellCursor30             . insertText(tr("Total bankings"));
        QTextTableCell cell31     = tableRecap->cellAt(3,1);
         QTextCursor cellCursor31 = cell31.firstCursorPosition();
         cellCursor31             . insertText(banking);
            QTextTableCell cell40     = tableRecap->cellAt(4,0);
            QTextCursor cellCursor40  = cell40.firstCursorPosition();
            QString totalReceiptsHtml = QString("<html><font size = 4 color = #FF0000><bold>%1 %2 <bold></font></html>")
                                        .arg(tr("Total of "), tr("receipts"));
            cellCursor40              . insertHtml(totalReceiptsHtml);
            QTextTableCell cell41     = tableRecap->cellAt(4,1);
            QTextCursor cellCursor41  = cell41.firstCursorPosition();
            cellCursor41              . insertText(totalReceipts);
            }
    if(choice == MOVEMENTS_TYPE){
        //nbreLignesTableau = m_typesMovements.size();
        if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << " m_typesMovements.size() =" << QString::number(m_typesMovements.size())  ;
        //int nberLines = nbreLignesTableau +1 ;
        int nberLines = totalSumsList.size();
        if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "nberLines  =" <<  QString::number(nberLines);
        tableRecap                = cursortrieinfunction->insertTable(nberLines,2,tableFormatDone);
        if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "totalSumsList.size = " << QString::number(totalSumsList.size());
        for(int i = 0 ; i < nberLines ; i++){
            if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "i = " << QString::number(i);
            //if(!i < totalSumsList.size()){break;}
            if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "totalSumsList[i] = " << totalSumsList[i];
            QStringList paireDepenseMontant = totalSumsList[i].split("=");
            if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "paireDepenseMontant[1]  =" << paireDepenseMontant[1] ;
            if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "paireDepenseMontant[0]  =" << paireDepenseMontant[0] ;
            QTextTableCell cellDep          = tableRecap->cellAt(i,0);
             QTextCursor cellCursorDep      = cellDep.firstCursorPosition();
             QString paireDepenseMontantLeft = paireDepenseMontant[0];
             if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "paireDepenseMontantLeft  =" << paireDepenseMontantLeft ;
             if (paireDepenseMontantLeft == tr("Total"))
             {

                  if (WarnDebugMessage)
                  qDebug() << __FILE__ << QString::number(__LINE__) << "in total";
                  QString totalInHtml = QString("<html><font size = 4 color = #FF0000><bold>%1<bold></font></html>")
                                       .arg(paireDepenseMontantLeft);
                  cellCursorDep.insertHtml(totalInHtml);
                 }
             else{
                  if (WarnDebugMessage)
                  qDebug() << __FILE__ << QString::number(__LINE__) << "in else";
                  cellCursorDep.insertText(paireDepenseMontantLeft);
                 }
            QTextTableCell cellDep1         = tableRecap->cellAt(i,1);
             QTextCursor cellCursorDep1     = cellDep1.firstCursorPosition();
             cellCursorDep1                 . insertText(paireDepenseMontant[1]);
             if (WarnDebugMessage)
              qDebug() << __FILE__ << QString::number(__LINE__) << "end of for";
        }
    }
    //calculparmois(listforquery,table, un,trenteetquelque);//calcul par type recette et mois
    cursortrieinfunction  ->movePosition(QTextCursor::End,QTextCursor::MoveAnchor,1);
   }
}//end of fillTable
Exemplo n.º 26
0
QTextDocument * Exporter::buildFinalDoc()
{
    //search for checked items :

    QDomDocument domDoc = hub->project()->mainTreeDomDoc();
    QDomElement root = domDoc.documentElement();

    QList<QDomElement> itemList = searchForCheckedItems(root);

    if(itemList.size() == 0)
        return new QTextDocument();


    // set up the progress bar :
    QWidget *progressWidget = new QWidget(this, Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    QHBoxLayout *progressLayout = new QHBoxLayout(progressWidget);
    QProgressBar *progressBar = new QProgressBar(progressWidget);
    int progressValue = 0;

    progressLayout->addWidget(progressBar);
    progressWidget->setLayout(progressLayout);

    progressBar->setMaximum(itemList.size());
    progressBar->setValue(progressValue);
    progressWidget->show();



    //    QString debug;
    //    qDebug() << "itemList" << debug.setNum(itemList->size());

    QTextDocument *textDocument = new QTextDocument(this);
    QTextEdit *edit = new QTextEdit(this);

    textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:12pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}");



    for(int i = 0; i < itemList.size(); ++i){
        QDomElement element = itemList.at(i);
        QTextCursor *tCursor = new QTextCursor(textDocument);

        QTextBlockFormat blockFormatLeft;
        blockFormatLeft.setBottomMargin(0);
        blockFormatLeft.setTopMargin(0);
        blockFormatLeft.setTextIndent(72);
        blockFormatLeft.setLineHeight(200, QTextBlockFormat::ProportionalHeight);
        blockFormatLeft.setAlignment(Qt::AlignJustify);
        QTextCharFormat charFormatLeft;
        charFormatLeft.setFontPointSize(12);
        charFormatLeft.setFontFamily("Courrier");

        QTextBlockFormat blockFormatCenter;
        blockFormatCenter.setAlignment(Qt::AlignCenter);


        if(element.tagName() != "separator"){

            qDebug() << "element name : "+ element.attribute("name");
            MainTextDocument *textDoc = hub->project()->findChild<MainTextDocument *>("textDoc_" + element.attribute("number"));
            MainTextDocument *synDoc = hub->project()->findChild<MainTextDocument *>("synDoc_" + element.attribute("number"));
            MainTextDocument *noteDoc = hub->project()->findChild<MainTextDocument *>("noteDoc_" + element.attribute("number"));

            QTextDocumentFragment textFrag(prepareTextDoc(textDoc));
            QTextDocumentFragment synFrag(prepareSynDoc(synDoc));
            QTextDocumentFragment noteFrag(prepareNoteDoc(noteDoc));

            edit->setDocument(textDocument);




            if(element.tagName() == "book"){
                textDocument->setMetaInformation(QTextDocument::DocumentTitle,element.attribute("name", ""));
                edit->append("<h1>" + element.attribute("name", "") + "</h1>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<h4>" + QDateTime::currentDateTime().toString() + "</h4>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");
                edit->append("<br>");

            }
            if(element.tagName() == "act"){
                edit->append("<br>");
                edit->append("<br>");
                edit->append("<h2>" + element.attribute("name", "") + "</h2>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");

            }
            if(element.tagName() == "chapter"){
                edit->append("<br>");
                edit->append("<br>");
                edit->append("<h2>" + element.attribute("name", "") + "</h2>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");

            }

            if(element.tagName() == "scene" && ui->setSceneTitlesComboBox->currentIndex() != 0){
                QString sceneTitle;
                switch (ui->setSceneTitlesComboBox->currentIndex()){
                case 1:
                    sceneTitle = element.attribute("name", "");
                    break;
                case 2:
                    sceneTitle = "###";
                    break;
                case 3:
                    sceneTitle = "***";
                    break;
                default:
                    sceneTitle = element.attribute("name", "");
                    break;

                }

                edit->append("<br>");
                edit->append("<h3>" + sceneTitle + "</h3>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");

            }

            if(ui->synopsisCheckBox->isChecked() && !synFrag.isEmpty()){
                edit->append("<br>");
                edit->append("<h4>" + tr("Synopsis") + "</h4>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->insertBlock(blockFormatLeft, charFormatLeft);
                tCursor->insertFragment(synFrag);
            }

            if(ui->notesCheckBox->isChecked() && !noteFrag.isEmpty()){
                edit->append("<br>");
                edit->append("<h4>" + tr("Note") + "</h4>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->mergeBlockFormat(blockFormatCenter);
                edit->append("<br>");
                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->insertBlock(blockFormatLeft, charFormatLeft);
                tCursor->insertFragment(noteFrag);
            }

            if(ui->storyCheckBox->isChecked()){
                if((ui->synopsisCheckBox->isChecked() || ui->notesCheckBox->isChecked()) && !textFrag.isEmpty()){
                    tCursor->insertBlock();
                    tCursor->insertHtml("<h4>" + tr("Story") + "</h4>");
                    tCursor->mergeBlockFormat(blockFormatCenter);
                    tCursor->insertBlock();

                }
                tCursor->insertHtml("<br>");
                //                tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
                tCursor->insertBlock(blockFormatLeft, charFormatLeft);
                tCursor->insertFragment(textFrag);
                //                edit->append(textFrag->toHtml());
            }
        }
        else if(element.tagName() == "separator"){
            edit->append("<br>");
            edit->append("<h3>#</h3>");
            tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
            tCursor->mergeBlockFormat(blockFormatCenter);
            edit->append("<br>");
            tCursor->movePosition(QTextCursor::End, QTextCursor::MoveAnchor,1);
            tCursor->mergeBlockFormat(blockFormatLeft);
        }




        progressValue += 1;
        progressBar->setValue(progressValue);

    }
    QRegExp reg("-qt-paragraph-type:.*;|margin-top:.*;|margin-bottom:.*;|margin-left:.*;|margin-right:.*;|-qt-block-indent:.*;|text-indent:.*;|font-family:.*;|font-size:.*;");
    reg.setMinimal(true);
    textDocument->setHtml(textDocument->toHtml().remove(reg));

    //find and change final page css style :

    //textDocument->setDefaultStyleSheet("p, li { white-space: pre-wrap; } p{line-height: 2em; font-family:'Liberation Serif'; font-size:14pt;margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:72px;}");

    //            <style type="text/css">
    //            p, li { white-space: pre-wrap; }
    //            </style>

    //            tCursor
    //            qDebug() << textDocument->toHtml();


    progressWidget->close();

    return textDocument;
}
Exemplo n.º 27
0
/**
 * Adds a log entry
 */
void LogWidget::log(LogType logType, QString text) {
#ifndef INTEGRATION_TESTS
    // return if logging wasn't enabled
    if (!qApp->property("loggingEnabled").toBool()) {
        return;
    }

    QString type = "";
    QColor color = QColor(Qt::black);

    switch (logType) {
        case DebugLogType:
            if (!ui->debugCheckBox->isChecked()) {
                return;
            }
            type = "debug";
            // gray
            color = QColor(98, 98, 98);
            break;
        case InfoLogType:
            if (!ui->infoCheckBox->isChecked()) {
                return;
            }
            type = "info";
            color = QColor(Qt::darkBlue);
            break;
        case WarningLogType:
            if (!ui->warningCheckBox->isChecked()) {
                return;
            }
            type = "warning";
            // orange
            color = QColor(255, 128, 0);
            break;
        case CriticalLogType:
            if (!ui->criticalCheckBox->isChecked()) {
                return;
            }
            type = "critical";
            // light red
            color = QColor(192, 0, 0);
            break;
        case FatalLogType:
            if (!ui->fatalCheckBox->isChecked()) {
                return;
            }
            type = "fatal";
            // lighter red
            color = QColor(210, 0, 0);
            break;
        case StatusLogType:
            if (!ui->statusCheckBox->isChecked()) {
                return;
            }
            type = "status";
            // green
            color = QColor(0, 128, 0);
            break;
        case ScriptingLogType:
            if (!ui->scriptingCheckBox->isChecked()) {
                return;
            }
            type = "scripting";
            // blue
            color = QColor(0, 102, 255);
            break;
        default:
            type = "unknown";
            break;
    }

    QDateTime dateTime = QDateTime::currentDateTime();
//    text.prepend("[" + dateTime.toString("hh:mm:ss") + "] [" + type + "] ");
//    text.append("\n");

    QString html = QString("<div style=\"color: %1\">[%2] [%3] %4</div><br />")
            .arg(color.name(), dateTime.toString("hh:mm:ss"), type,
                 text.toHtmlEscaped());

    QScrollBar *scrollBar = ui->logTextEdit->verticalScrollBar();

    // we want to scroll down later if the scrollbar is near the end bottom
    bool scrollDown = scrollBar->value() >=
            (scrollBar->maximum() - scrollBar->singleStep());

    QTextCursor c = ui->logTextEdit->textCursor();

    // insert the text at the end
    c.movePosition(QTextCursor::End);
    c.insertHtml(html);

    if (scrollDown) {
        // move the text cursor to the end
        ui->logTextEdit->moveCursor(QTextCursor::End);
    }
#else
    Q_UNUSED(logType);
    Q_UNUSED(text);
#endif
}
Exemplo n.º 28
0
void TextZone::insertFromMimeData (const QMimeData *source )
{

    QTextCursor cursor = this->textCursor();

    int bottMargin;
    int textIndent;
    int leftMargin;
    Qt::Alignment textAlignment;
    int textHeight;
    QString fontFamily;

    if(cursor.atStart() == true
            || cursor.position() == 1
            || cursor.position() == 0){
        int defaultIndex = textStyles->defaultStyleIndex();
        bottMargin = textStyles->blockBottomMarginAt(defaultIndex);
        textIndent = textStyles->blockFirstLineIndentAt(defaultIndex);
        leftMargin = textStyles->blockLeftMarginAt(defaultIndex);
        textAlignment = textStyles->blockAlignmentTrueNameAt(defaultIndex);
        textHeight = textStyles->fontSizeAt(defaultIndex);
        fontFamily = textStyles->fontFamilyAt(defaultIndex);
    }
    else{

        bottMargin = cursor.blockFormat().bottomMargin();
        textIndent = cursor.blockFormat().textIndent();
        leftMargin = cursor.blockFormat().leftMargin();
        textAlignment = cursor.blockFormat().alignment();
        textHeight = cursor.charFormat().fontPointSize();
        fontFamily = cursor.charFormat().fontFamily();

    }

    if(source->hasHtml() && !forceCopyWithoutFormatting){

        QByteArray richtext;
        if (source->hasFormat(QLatin1String("text/rtf"))) {
            richtext = source->data(QLatin1String("text/rtf"));
        } else if (source->hasHtml()) {
            richtext = mimeToRtf(source);
        }

        QTextEdit *textEdit = new QTextEdit(0);

        RTF::Reader reader;
        QBuffer buffer(&richtext);
        buffer.open(QIODevice::ReadOnly);
        reader.read(&buffer, textEdit->textCursor());
        buffer.close();

        QString sourceString = textEdit->toHtml();
        sourceString.remove(QChar::ReplacementCharacter);
        sourceString.remove(QChar::ObjectReplacementCharacter);
        sourceString.remove(QChar::Null);



        //htmlText
        QTextDocument *document = new QTextDocument;
        document->setHtml(Utils::parseHtmlText(sourceString));
        QTextBlockFormat blockFormat;
        blockFormat.setBottomMargin(bottMargin);
        blockFormat.setTextIndent(textIndent);
        blockFormat.setLeftMargin(leftMargin);
        blockFormat.setAlignment(textAlignment);
        blockFormat.setRightMargin(0);
        QTextCharFormat charFormat;
        charFormat.setFontPointSize(textHeight);
        charFormat.setFontFamily(fontFamily);

        charFormat.setBackground(QBrush(Qt::NoBrush));
        charFormat.setForeground(QBrush(Qt::NoBrush));
        charFormat.setAnchor(false);
        charFormat.setUnderlineStyle(QTextCharFormat::NoUnderline);
        charFormat.setFontStrikeOut(false);

        QTextCursor *tCursor = new QTextCursor(document);
        tCursor->movePosition(QTextCursor::Start, QTextCursor::MoveAnchor,1);
        tCursor->movePosition(QTextCursor::End, QTextCursor::KeepAnchor,1);

        tCursor->mergeCharFormat(charFormat);
        tCursor->mergeBlockFormat(blockFormat);

        QTextCursor cursor = this->textCursor();
        cursor.insertHtml(document->toHtml("utf-8"));
        qDebug() << "insertFromMimeData Html";

    }
    else if(source->hasText() || forceCopyWithoutFormatting){
        QTextDocument *document = new QTextDocument;
        document->setPlainText(qvariant_cast<QString>(source->text()));

        QTextBlockFormat blockFormat;
        blockFormat.setBottomMargin(bottMargin);
        blockFormat.setTextIndent(textIndent);
        blockFormat.setLeftMargin(leftMargin);
        blockFormat.setAlignment(textAlignment);
        blockFormat.setRightMargin(0);
        QTextCharFormat charFormat;
        charFormat.setFontPointSize(textHeight);
        charFormat.setFontFamily(fontFamily);
        charFormat.clearForeground();
        charFormat.setBackground(QBrush(Qt::NoBrush));
        charFormat.setForeground(QBrush(Qt::NoBrush));
        charFormat.setAnchor(false);
        charFormat.setUnderlineStyle(QTextCharFormat::NoUnderline);
        charFormat.setFontStrikeOut(false);

        QTextCursor *tCursor = new QTextCursor(document);
        tCursor->movePosition(QTextCursor::Start, QTextCursor::MoveAnchor,1);
        tCursor->movePosition(QTextCursor::End, QTextCursor::KeepAnchor,1);

        tCursor->mergeCharFormat(charFormat);
        tCursor->mergeBlockFormat(blockFormat);

        QTextCursor cursor = this->textCursor();
        cursor.insertHtml(document->toHtml("utf-8"));
        qDebug() << "insertFromMimeData plainText";

    }


}
Exemplo n.º 29
0
//Lecture des paragraphes
bool OpenDocument::contenu_paragraphe(QDomElement e, QTextCursor &curseur, bool puces, bool h_item, bool tableau){
    ErrorManager instance_erreur;
    p_current++;
    case_tableau = "";
    //On change la QProgressBar
    //chargement->

    QString nom_style = e.attribute("text:style-name", "default");
    QTextCharFormat format = cree_bloc_format(nom_style);

    //On récupère le format de bloc
    QTextBlockFormat format_bloc = cree_bloc_format2(nom_style);
    //On ajoute un marginTop de 5 pour plus de lisibilité
    format_bloc.setTopMargin(2);

    //Style spécifique aux puces
    if(puces || h_item){
        int id_style = -1;
        for(int i=0; i<styles.size(); i++){
            //On parcourt les styles
            if(id_style >= 0){
                break;
            }
            for(int j=0; j<styles.at(i).size(); j++){
                //On rentre dans le QMultiMap
                if(puces){
                    if(styles.at(i).value("style-puces") == nom_style){
                        id_style = i;
                        //On sort de la boucle
                        break;
                    }
                }
                else{
                    //Ce ne peut être que le "h_item" sinon la boucle ne se déclencherait pas
                    if(styles.at(i).value("style-h") == nom_style){
                        id_style = i;
                        //On se casse
                        break;
                    }
                }
            }
        }
        if(id_style != -1){
            //On merge le style
            format.merge(cree_bloc_format(styles.at(id_style).value("style-puces")));
        }
    }

    //On applique le format au curseur
    curseur.setCharFormat(format);
    if(!tableau){
        curseur.beginEditBlock();
    }
    curseur.setBlockCharFormat(format);
    curseur.setBlockFormat(format_bloc);

    if(puces){
        contenu_puce.append("<li>");
        //On vérifie la taille
        int taille = format.fontPointSize();
        if(taille == 0){
            //Il y a eu un bug lors de la sélection du style, on applique la taille par défaut
            format.setFontPointSize(12);
        }
    }

    //Maintenant on lit les <span>
    QDomNode enfants = e.firstChild();
    while(!enfants.isNull()){
        if(enfants.isElement()){
            QDomElement type = enfants.toElement();

            //On parcours le type d'élément
            if(type.tagName() == "text:span"){
                traite_span(format, curseur, type, puces, tableau);
            }
            else if(type.tagName() == "text:a"){ //Il s'agit d'un lien
                traite_lien(curseur, type, format);
            }
            else if(type.tagName() == "text:line-break"){

            }
            else if(type.tagName() == "text:s"){
                curseur.insertText(QString(" "));
            }
            else if(type.tagName() == "text:tab"){
                curseur.insertText(QString("    "));
            }
            else if(type.tagName() == "draw:frame"){
                QDomNode enfants_image = type.firstChild();
                QString style_image = type.attribute("draw:style-name");
                if(enfants_image.toElement().tagName() == "draw:image"){
                    if(!traite_image(curseur, enfants_image.toElement(), style_image)){
                        instance_erreur.Erreur_msg(tr("ODT : Erreur lors de la lecture des images (return false)"), QMessageBox::Ignore);
                    }
                }
            }
            else if(type.tagName() == "text:list"){
                if(!contenu_puces(type, curseur)){
                    instance_erreur.Erreur_msg(tr("ODT : Une erreur est survenue lors de la lecture d'une liste à puces; elle ne sera pas affichée"), QMessageBox::Warning);
                }
                else{
                    QTextCursor curseur(document);
                    curseur.movePosition(QTextCursor::End);
                    curseur.movePosition(QTextCursor::PreviousBlock);
                    curseur.insertHtml(contenu_puce);
                    contenu_puce = "";
                }
            }
            else if(type.tagName() == "text:soft-page-break"){

            }
            else{
                instance_erreur.Erreur_msg(tr("ODT: Type de contenu non supporté : %1").arg(type.tagName()), QMessageBox::Ignore);
            }
        }
        else if(enfants.isText()){
            //On gére le texte
            if(!puces && !tableau){
                curseur.insertText(enfants.nodeValue(), format);
            }
            else if(tableau){
               case_tableau.append(enfants.nodeValue());
            }
            else{
                //Insertion du contenu des puces si on est dans un "p"
                //On récupère le style par défaut
                QTextDocument *temp = new QTextDocument;
                QTextCursor curseur(temp);
                curseur.insertText(enfants.nodeValue(), format);
                contenu_puce.append(nettoye_code(temp->toHtml()));
                delete temp;
            }

        }
        else{
            instance_erreur.Erreur_msg(tr("ODT : type de données non supporté"), QMessageBox::Ignore);
        }
        enfants = enfants.nextSibling();
    }

    //On a fini la boucle OU il n'y avait pas de <span>

    //On récupère le contenu
    if(!puces && !tableau){
        curseur.insertText("\n");
    }
    if(puces){
        contenu_puce.append("</li>");
    }
    if(!tableau){
        curseur.endEditBlock();
    }
    if(tableau){
        ligne_tableau.append(case_tableau);
    }
    //std::cout << e.text().toStdString() << std::endl;
    return true;
}