Exemplo n.º 1
0
void LrcEditor::addTag(const QString &attr, const QString &value)
{
	// ignore empty value
	if (value.isEmpty())
		return ;

	QRegExp exp("^\\[" + attr + ":.*\\][\\s]{0,}$");
	QString  newValue = "[" + attr + ":" + value + "]";
	bool found = false;

	for (auto it = document()->begin(); it != document()->end(); it = it.next())
	{
		if (exp.indexIn(it.text()) >= 0)
		{
			found = true;
			qDebug() << "found tag at line: " << it.blockNumber() << qPrintable(it.text());

			if (it.text().trimmed() != newValue)
			{
				QTextCursor cursor(it);
				cursor.beginEditBlock();

				cursor.select(QTextCursor::LineUnderCursor);
				cursor.removeSelectedText();
				cursor.insertText(newValue);

				cursor.endEditBlock();
			}

			// we assume there's only one
			break;
		}
	}

	if (!found)
	{
		QTextCursor cursor = textCursor();
		cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
		cursor.insertText(newValue + m_charNewLine);
	}
}
Exemplo n.º 2
0
FindResult replace(QTextCursor &cursor, QTextDocument const &document,
                   ReplaceQuery const &query)
{
	cursor.setPosition(cursor.selectionStart(), QTextCursor::MoveAnchor);
	FindResult result = find(cursor, document, true, query);

	if((result == FindResult::Found) && cursor.hasSelection())
	{
		cursor.beginEditBlock();
		int start = cursor.selectionStart();
		int length = query.replaceValue.length();

		cursor.insertText(query.replaceValue);
		cursor.setPosition(start, QTextCursor::MoveAnchor);
		cursor.movePosition(QTextCursor::NextCharacter,
		                    QTextCursor::KeepAnchor, length);
		cursor.endEditBlock();
	}

	return result;
}
Exemplo n.º 3
0
/* Add beam, in JBEAM edit widget at text cursor position */
void JBEAM_TextBox::JBEAM_AddBeam()
{
    QString beamline;
    this->str_addIndent(&beamline, 3);
    beamline+= "[\"" + CurrentNodeBeam->TempBeam.Node1Name + '"';
    beamline+= ", ";
    beamline+= '"' + CurrentNodeBeam->TempBeam.Node2Name + '"';
    beamline+=("],\n");
    QTextCursor textcursor = this->textCursor();
    if(JBEAM_BeamCursor >= 0)
    {
        textcursor.setPosition(JBEAM_BeamCursor);
    }

    for(int i=0; i<CurrentNodeBeam->TempBeam.comments.size();i++)
    {
        JBEAM_AddComment(JBEAM_BeamCursor, CurrentNodeBeam->TempBeam.comments.ReadComment(i));
    }
    textcursor.insertText(beamline);
    this->setTextCursor(textcursor);
}
Exemplo n.º 4
0
void CodeEditor::keyPressEvent(QKeyEvent *e)
{
    if ((codeCompleter) && codeCompleter->popup()->isVisible() && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Backtab || e->key() == Qt::Key_Escape|| e->key() == Qt::Key_Return || e->key() == Qt::Key_Tab))
    {
        e->ignore();
        return;
    }
    else if (e->key() == Qt::Key_Tab)
    {
        QTextCursor cur = textCursor();
        cur.beginEditBlock();
        cur.insertText("\t");
        cur.endEditBlock();
        setTextCursor(cur);
        e->ignore();
        return;
    }
    else if (e->key() == Qt::Key_D && (e->modifiers() & Qt::ControlModifier)){
        deleteLine();
    } else if (e->key() == Qt::Key_Up && (e->modifiers() & Qt::AltModifier)){
        copyLineUp();
    }else if (e->key() == Qt::Key_Up && (e->modifiers() & Qt::ControlModifier)) {
        moveLineUp();
    } else if (e->key() == Qt::Key_Down && (e->modifiers() & Qt::AltModifier)){
        copyLineDown();
    }else if (e->key() == Qt::Key_Down && (e->modifiers() & Qt::ControlModifier)){
        moveLineDown();
    }else if (e->key() == Qt::Key_Space &&(e->modifiers() & Qt::ControlModifier)){
        popupSuggestions();

    }else if (e->key() == Qt::Key_3 && (e->modifiers() & Qt::ControlModifier)){
        toggleComments();
    }else if(e->key() == Qt::Key_Period){
         popupSuggestions();
         QTextEdit::keyPressEvent(e);
    }else
        QTextEdit::keyPressEvent(e);


}
Exemplo n.º 5
0
void DocBlock::setFolded(bool fold)
{
    if (fold == folded) return; //! do nothing

    folded = fold;

    if (fold)
    {
        backup = myTextItem->document()->clone();

        if (docType == Image)
        {
            QTextCursor cursor = QTextCursor(myTextItem->document());
            cursor.document()->setPlainText(" ");
            cursor.insertImage(QImage(":/image.png"));
            cursor.insertText(QFileInfo(path).fileName());
        }
        else
        {
            QString cue = myTextItem->toPlainText();
            int index = cue.indexOf("\n");
            cue.truncate(qMin(8, index));
            cue.append(" ...");
            myTextItem->setPlainText(cue);
            myTextItem->setTextInteractionFlags(Qt::TextEditable | Qt::TextSelectableByKeyboard);
        }

    }
    else
    {
        Q_ASSERT(backup != 0);
        myTextItem->setDocument(backup);

        if (!docType == Text)
            myTextItem->setTextInteractionFlags(Qt::NoTextInteraction);

        backup = 0;
    }
    updateBlock();
}
Exemplo n.º 6
0
void CodeEdit::keyPressEvent(QKeyEvent *event)
{
	QPlainTextEdit::keyPressEvent(event);

	if((event->key() == Qt::Key_Return) || (event->key() == Qt::Key_Enter)) {
		if(blockCount() == 1)
			return;

		QString indent;
		const QString prevLine = textCursor().block().previous().text();
		for(int i = 0; i < prevLine.size(); ++i) {
			if(!prevLine[i].isSpace())
				break;

			indent += prevLine[i];
		}

		QTextCursor cursor = textCursor();
		cursor.insertText(indent);
		setTextCursor(cursor);
	}
}
Exemplo n.º 7
0
void Matrix::exportRasterImage(const QString& fileName, int quality, int dpi)
{
	if (!dpi)
		dpi = logicalDpiX();

	QImage image = d_matrix_model->renderImage();
	int dpm = (int)ceil(100.0/2.54*dpi);
	image.setDotsPerMeterX(dpm);
	image.setDotsPerMeterY(dpm);
	if (fileName.endsWith(".odf")){
		QTextDocument *document = new QTextDocument();
		QTextCursor cursor = QTextCursor(document);
		cursor.movePosition(QTextCursor::End);
		cursor.insertText(objectName());
		cursor.insertBlock();
		cursor.insertImage(image);

		QTextDocumentWriter writer(fileName);
		writer.write(document);
	} else
		image.save(fileName, 0, quality);
}
Exemplo n.º 8
0
void PlainTextEditor::indentOrUnindent( bool doIndent )
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();

    // Indent or unindent the selected lines
    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin( anchor, pos );
    int end = qMax( anchor, pos );

    QTextDocument* doc = document();
    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock( end -1 ).next();

    for ( QTextBlock block = startBlock; block != endBlock; block = block.next() ) {
        QString text = block.text();

        if ( doIndent ) {
            const int indentPosition = firstNonSpace( text );
            cursor.setPosition( block.position() +indentPosition );
            cursor.insertText( QString( IndentSize, QLatin1Char( ' ' ) ) );
        } else {
            const int indentPosition = firstNonSpace( text );
            const int targetColumn = indentedColumn( columnAt( text, indentPosition ), false );
            cursor.setPosition( block.position() +indentPosition );
            cursor.setPosition( block.position() +targetColumn, QTextCursor::KeepAnchor );
            cursor.removeSelectedText();
        }
    }

    // Reselect the selected lines
    cursor.setPosition( startBlock.position() );
    cursor.setPosition( endBlock.previous().position(), QTextCursor::KeepAnchor );
    cursor.movePosition( QTextCursor::EndOfBlock, QTextCursor::KeepAnchor );

    cursor.endEditBlock();
    setTextCursor( cursor );
}
Exemplo n.º 9
0
void SqlTextEdit::insertCompletion(const QString& completion)
{
    if (m_Completer->widget() != this)
        return;
    QTextCursor tc = textCursor();
    int extra = completion.length() - m_Completer->completionPrefix().length();
    tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);

    // slight workaround for a field completion without any completionPrefix
    // eg. "tablename.;" if you would select a field completion and hit enter
    // without this workaround the text would be inserted after the ';'
    // because endofword moves to the end of the line
    // or we have no competionprefix at all (CTRL+SPACE) without text
    // under cursor
    if(tc.selectedText() == "." || m_Completer->completionPrefix().isEmpty())
        tc.movePosition(QTextCursor::Right);
    else
        tc.movePosition(QTextCursor::EndOfWord);

    tc.insertText(completion.right(extra));
    setTextCursor(tc);
}
Exemplo n.º 10
0
// 
// Replace text if doreplace is true, otherwise only do "find next"
// Returns true if the find next failed (end of document)
//
bool MibEditor::Replace(bool doreplace)
{
    QTextCursor tc;

    ff = 0;
    find_string = replace_uid.comboFind->currentText(); 
    if (!find_strings.contains(find_string))
        find_strings.append(find_string);
    replace_string = replace_uid.comboReplace->currentText();
    if (!replace_strings.contains(replace_string))
            replace_strings.append(replace_string);

    if (replace_uid.checkWords->isChecked())
        ff |= QTextDocument::FindWholeWords;
    if (replace_uid.checkCase->isChecked())
        ff |= QTextDocument::FindCaseSensitively;
    if (replace_uid.checkBackward->isChecked())
        ff |= QTextDocument::FindBackward;

    tc = s->MainUI()->MIBFile->textCursor();
    if(doreplace && !tc.isNull() && tc.hasSelection() && 
       (tc.selectedText().compare(find_string, 
                                  (replace_uid.checkCase->isChecked()?
                                  Qt::CaseSensitive:Qt::CaseInsensitive))==0))
        tc.insertText(replace_uid.comboReplace->currentText());

    tc = s->MainUI()->MIBFile->document()->find(find_string,
                                                s->MainUI()->MIBFile->textCursor(),
                                                ff);

    if (!tc.isNull())
    {
        s->MainUI()->MIBFile->setTextCursor(tc);
        tc.select(QTextCursor::WordUnderCursor);
    }

    return (tc.isNull()?true:false);
}
Exemplo n.º 11
0
void ScriptingWidget::addOutputText(const QString& strMessage, bool error, bool processEvents)
{
   if (strMessage.isEmpty() == false)
   {
      QTextCharFormat newTextFormat = currentCharFormat();
      if (error)
      {
         newTextFormat.setFont(mErrorFont);
         newTextFormat.setForeground(QBrush(mErrorColor));
      }
      else
      {
         newTextFormat.setFont(mOutputFont);
         newTextFormat.setForeground(QBrush(mOutputColor));
      }
      QTextCursor cursor = textCursor();
      cursor.clearSelection();
      if (mExecutingCommand)
      {
         cursor.movePosition(QTextCursor::End);
      }
      else
      {
         int pos = std::max(mCommandStartPos - mPrompt.size(), 0);
         cursor.setPosition(pos);
         mCommandStartPos += strMessage.size();
      }
      cursor.insertText(strMessage, newTextFormat);
      if (mExecutingCommand)
      {
         setTextCursor(cursor);
      }
      if (processEvents)
      {
         QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
      }
   }
}
void SpellCheckerCore::replaceWordsInCurrentEditor( const WordList& wordsToReplace, const QString& replacementWord )
{
  if( wordsToReplace.count() == 0 ) {
    Q_ASSERT( wordsToReplace.count() != 0 );
    return;
  }
  if( d->currentEditor == nullptr ) {
    Q_ASSERT( d->currentEditor != nullptr );
    return;
  }
  TextEditor::TextEditorWidget* editorWidget = qobject_cast<TextEditor::TextEditorWidget*>( d->currentEditor->widget() );
  if( editorWidget == nullptr ) {
    Q_ASSERT( editorWidget != nullptr );
    return;
  }

  QTextCursor cursor = editorWidget->textCursor();
  /* Iterate the words and replace all one by one */
  for( const Word& wordToReplace: wordsToReplace ) {
    editorWidget->gotoLine( int32_t( wordToReplace.lineNumber ), int32_t( wordToReplace.columnNumber ) - 1 );
    int wordStartPos = editorWidget->textCursor().position();
    editorWidget->gotoLine( int32_t( wordToReplace.lineNumber ), int32_t( wordToReplace.columnNumber ) + wordToReplace.length - 1 );
    int wordEndPos = editorWidget->textCursor().position();

    cursor.beginEditBlock();
    cursor.setPosition( wordStartPos );
    cursor.setPosition( wordEndPos, QTextCursor::KeepAnchor );
    cursor.removeSelectedText();
    cursor.insertText( replacementWord );
    cursor.endEditBlock();
  }
  /* If more than one suggestion was replaced, show a notification */
  if( wordsToReplace.count() > 1 ) {
    Utils::FadingIndicator::showText( editorWidget,
                                      tr( "%1 occurrences replaced." ).arg( wordsToReplace.count() ),
                                      Utils::FadingIndicator::SmallText );
  }
}
Exemplo n.º 13
0
void SourceEdit::keyPressEvent(QKeyEvent * event)
{
    QTextEdit::keyPressEvent(event);
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
    {
        QTextCursor cursor = this->textCursor();
        QTextBlock prevBlock = cursor.block().previous();
        if (prevBlock.isValid()) {
            QString text = prevBlock.text();
            QString indentStr("");
            for (int n = 0; text[n].isSpace(); n++)
                indentStr += text[n];

            // increase indent
            text = text.trimmed();
            QRegExp rx("^(if|else|while|for).*");
            if (text.endsWith('{') || rx.exactMatch(text))
                indentStr += '\t';
            cursor.insertText(indentStr);
        }
    }
    else if (event->key() == Qt::Key_BraceRight)
    {
        // decrease indent
        QTextCursor cursor = this->textCursor();
        cursor.movePosition(QTextCursor::Left);
        if (cursor.block().text().endsWith("\t}"))
            cursor.deletePreviousChar();
    }
    else if (event->key() == Qt::Key_BraceLeft)
    {
        // decrease indent
        QTextCursor cursor = this->textCursor();
        cursor.movePosition(QTextCursor::Left);
        if (cursor.block().text().endsWith("\t{"))
            cursor.deletePreviousChar();		
    }
}
Exemplo n.º 14
0
void Terminal::doPrintStdout(const QString &message, QColor color)
{
    logMessage("Terminal::doPrintStdout()");

    if (!message.trimmed().isEmpty())
    {
        // format
        QTextCharFormat format;
        format.setForeground(color);

        // cursor
        QTextCursor cursor = txtOutput->textCursor();
        cursor.movePosition(QTextCursor::End);
        cursor.beginEditBlock();
        cursor.insertText(message, format);
        cursor.endEditBlock();

        // output
        txtOutput->setTextCursor(cursor);
        txtOutput->ensureCursorVisible();
        QApplication::processEvents();
    }
}
Exemplo n.º 15
0
void CodeEditor::unindent()
{
    QTextCursor cur = textCursor();

    const int selStart = cur.selectionStart();
    const int selEnd = cur.selectionEnd();
    Q_ASSERT( selStart <= selEnd );

    QTextBlock b = document()->findBlock( selStart );
    cur.beginEditBlock();
    do
    {
        const int indent = _indents(b);
        if( indent > 0 )
        {
            cur.setPosition( b.position() );
            cur.setPosition( _indentToPos( b, indent ), QTextCursor::KeepAnchor );
            cur.insertText( QString( indent - 1, QChar('\t') ) );
        }
        b = b.next();
    }while( b.isValid() && b.position() < selEnd );
    cur.endEditBlock();
}
Exemplo n.º 16
0
UserFunctionDialog::UserFunctionDialog(QWidget *parent,const QString& formula)
:QDialog(parent)
{
  m_uiForm.setupUi(this);
  connect(m_uiForm.lstCategory,SIGNAL(currentTextChanged(const QString&)),this,SLOT(selectCategory(const QString&)));
  connect(m_uiForm.lstFunction,SIGNAL(currentTextChanged(const QString&)),this,SLOT(selectFunction(const QString&)));
  connect(m_uiForm.btnSave,SIGNAL(clicked()),this,SLOT(saveFunction()));
  connect(m_uiForm.btnRemove,SIGNAL(clicked()),this,SLOT(removeCurrentFunction()));
  connect(m_uiForm.btnAdd,SIGNAL(clicked()),this,SLOT(addExpression()));
  connect(m_uiForm.btnUse,SIGNAL(clicked()),this,SLOT(accept()));
  connect(m_uiForm.btnCancel,SIGNAL(clicked()),this,SLOT(reject()));
  connect(m_uiForm.teUserFunction,SIGNAL(textChanged()),this,SLOT(updateFunction()));
  m_uiForm.teUserFunction->installEventFilter(this);

  loadFunctions();
  updateCategories();
  if ( !formula.isEmpty() )
  {
    QRect rect = m_uiForm.teUserFunction->cursorRect();
    QTextCursor cursor = m_uiForm.teUserFunction->cursorForPosition(rect.topLeft());
    cursor.insertText(formula);
    //updateFunction();
  }
}
Exemplo n.º 17
0
void OpenedFile::replaceLine(const int line_number, const QString &new_line)
{
    QString old_text;
    QString new_text = new_line;
    QTextCursor parsingCursor = textCursor();
    int space_count = 0;

    parsingCursor.setPosition(0);

    while(parsingCursor.blockNumber() != line_number)
    {
        parsingCursor.movePosition(QTextCursor::Down);
    }

    parsingCursor.movePosition(QTextCursor::StartOfLine);
    parsingCursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);

    old_text = parsingCursor.selectedText();

    while(old_text.startsWith(" "))
    {
        old_text.remove(0,1);
        space_count++;
    }

    while(space_count>0)
    {
        new_text.prepend(" ");
        space_count--;
    }
    new_text.remove(".0000");
    parsingCursor.insertText(new_text);
    parsingCursor.clearSelection();

    setTextCursor(parsingCursor);
}
Exemplo n.º 18
0
bool KReplaceStrategy::foundMatch(QTextCursor &cursor, FindDirection *findDirection)
{
    bool replace = true;
    if ((m_dialog->options() & KReplaceDialog::PromptOnReplace) != 0) {
        findDirection->select(cursor);
        // TODO: not only Yes and No, but Yes, No, All and Cancel
        int value = KMessageBox::questionYesNo(m_dialog->parentWidget(),
                                               i18n("Replace %1 with %2?", m_dialog->pattern(), m_dialog->replacement()));
        if (value != KMessageBox::Yes) {
            replace = false;
        }
    }

    if (replace) {
        cursor.insertText(m_dialog->replacement());
        ++m_replaced;
        int pos = cursor.position() + m_dialog->replacement().length();;
        if (cursor.document()->characterCount() <= pos)
            return false;
        cursor.setPosition(pos);
    }

    return true;
}
Exemplo n.º 19
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.º 20
0
void TestChangeTrackedDelete::testDeleteSelection()
{
    TextTool *textTool = new TextTool(new MockCanvas);
    KoTextEditor *textEditor = textTool->textEditor();
    QVERIFY(textEditor);
    QTextDocument *document = textEditor->document();
    KTextDocumentLayout *layout = qobject_cast<KTextDocumentLayout*>(document->documentLayout());
    QTextCursor *cursor = textEditor->cursor();
    cursor->insertText("Hello World");
    cursor->setPosition(2);
    cursor->setPosition(8, QTextCursor::KeepAnchor);
    ChangeTrackedDeleteCommand *delCommand = new ChangeTrackedDeleteCommand(ChangeTrackedDeleteCommand::NextChar, textTool);
    textEditor->addCommand(delCommand);
    QCOMPARE(document->characterAt(2).unicode(), (ushort)(QChar::ObjectReplacementCharacter));
    // This is wierd. Without this loop present the succeeding call to inlineTextObject returs NULL. Why ??????
    for (int i=0; i<document->characterCount(); i++) {
        cursor->setPosition(i);
    }
    cursor->setPosition(3);
    KDeleteChangeMarker *testMarker = dynamic_cast<KDeleteChangeMarker*>(layout->inlineTextObjectManager()->inlineTextObject(*cursor));
    QTextDocumentFragment deleteData =  KTextDocument(document).changeTracker()->elementById(testMarker->changeId())->deleteData();
    QCOMPARE(deleteData.toPlainText(), QString("llo Wo"));
    delete textTool;
}
Exemplo n.º 21
0
void CodeEditor::completeText(const QString &text)
{
    textCursor().beginEditBlock();
    QTextCursor editingTextCursor = textCursor();

    editingTextCursor.setPosition(textCursor().selectionEnd());

    editingTextCursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
    editingTextCursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor);
    if(editingTextCursor.selectedText().contains('-'))
    {
        editingTextCursor.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor);
    }
    else
    {
        editingTextCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
    }
    editingTextCursor.removeSelectedText();

    editingTextCursor.insertText(text);
    setTextCursor(editingTextCursor);

    textCursor().endEditBlock();
}
Exemplo n.º 22
0
int GenericCodeEditor::replaceAll( const QRegExp &expr, const QString &replacement, QTextDocument::FindFlags options )
{
    mSearchSelections.clear();
    updateExtraSelections();

    if(expr.isEmpty()) return 0;

    int replacements = 0;
    bool caps = expr.patternSyntax() != QRegExp::FixedString;

    QTextDocument *doc = QPlainTextEdit::document();
    QTextBlock block = doc->begin();
    QTextCursor cursor;

    QTextCursor(doc).beginEditBlock();

    while (block.isValid())
    {
        int blockPos = block.position();
        int offset = 0;
        while(findInBlock(doc, block, expr, offset, options, cursor))
        {
            QString rstr = replacement;
            if(caps)
                rstr = resolvedReplacement(rstr, expr);
            cursor.insertText(rstr);
            ++replacements;
            offset = cursor.selectionEnd() - blockPos;
        }
        block = block.next();
    }

    QTextCursor(doc).endEditBlock();

    return replacements;
}
Exemplo n.º 23
0
void PrintView::createPage() const
{
    QTextCursor cursor(ui->textEdit->textCursor());

    QTextCharFormat format(cursor.charFormat());
    format.setFontFamily("Times");

    QTextCharFormat boldFormat = format;
    boldFormat.setFontWeight(QFont::Bold);

    unsigned int numOfTasks = numOfOpenTasks();

    if(!numOfTasks)
    {
        cursor.insertText(tr("There are currently no open tasks."), format);

        return;
    }
    else
    {
        cursor.insertText(tr("Open tasks as of %1\n\n").arg(QDateTime::currentDateTime().toString()), format);
    }

    // sort tasks ascending according to their due dates
    QVector<Task*> allTasksCp = *allTasks;
    qSort(allTasksCp.begin(), allTasksCp.end(), TaskLessThan);

    QTextTableFormat tableFormat;
    tableFormat.setCellPadding(10.);
    tableFormat.setCellSpacing(0.);
    tableFormat.setHeaderRowCount(1);

    int rows = numOfTasks + 1/*allTasks.size()+1*/, columns = 6;
    QTextTable *table = cursor.insertTable(rows, columns, tableFormat);

    QTextTableCell cell;
    QTextCursor cellCursor;

    for (int column=0; column<columns; ++column)
    {
        cell = table->cellAt(0, column);
        cellCursor = cell.firstCursorPosition();

        switch(column)
        {
        case 0:
            cellCursor.insertText(tr("Due date"), boldFormat);
            break;

        case 1:
            cellCursor.insertText(tr("Title"), boldFormat);
            break;

        case 2:
            cellCursor.insertText(tr("Description"), boldFormat);
            break;

        case 3:
            cellCursor.insertText(tr("Category"), boldFormat);
            break;

        case 4:
            cellCursor.insertText(tr("Location"), boldFormat);
            break;

        case 5:
            cellCursor.insertText(tr("Done"), boldFormat);
            break;
        }
    }

    int actualRow = 0;

    // as radio buttons they are exclusive, therefore we don't need a flag for the third 'all' option
    bool showWeek = ui->radioButton_week->isChecked();
    bool showMonth = ui->radioButton_month->isChecked();

    for (int row=0; row<allTasksCp.size(); ++row)
    {
        if(allTasksCp.at(row)->done())
        {
            continue;
        }

        if(showWeek)
        {
            if(allTasksCp.at(row)->dueDate()>QDateTime::currentDateTime().addDays(7))
            {
                continue;
            }
        }
        else if(showMonth)
        {
            if(allTasksCp.at(row)->dueDate()>QDateTime::currentDateTime().addDays(30))
            {
                continue;
            }
        }

        for (int column=0; column<columns; ++column)
        {
            cell = table->cellAt(actualRow+1, column);
            cellCursor = cell.firstCursorPosition();

            switch(column)
            {
            case 0:
                cellCursor.insertText(allTasksCp.at(row)->dueDate().toString(), format);
                break;

            case 1:
                cellCursor.insertText(allTasksCp.at(row)->title(), format);
                break;

            case 2:
                cellCursor.insertText(allTasksCp.at(row)->description(), format);
                break;

            case 3:
                cellCursor.insertText(allTasksCp.at(row)->category(), format);
                break;

            case 4:
                cellCursor.insertText(allTasksCp.at(row)->location(), format);
                break;
            }
        }

        ++actualRow;
    }
}
Exemplo n.º 24
0
//! [5]
void MainWindow::insertCalendar()
{
    editor->clear();
    QTextCursor cursor = editor->textCursor();
    cursor.beginEditBlock();

    QDate date(selectedDate.year(), selectedDate.month(), 1);
//! [5]

//! [6]
    QTextTableFormat tableFormat;
    tableFormat.setAlignment(Qt::AlignHCenter);
    tableFormat.setBackground(QColor("#e0e0e0"));
    tableFormat.setCellPadding(2);
    tableFormat.setCellSpacing(4);
//! [6] //! [7]
    QVector<QTextLength> constraints;
    constraints << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14)
                << QTextLength(QTextLength::PercentageLength, 14);
    tableFormat.setColumnWidthConstraints(constraints);
//! [7]

//! [8]
    QTextTable *table = cursor.insertTable(1, 7, tableFormat);
//! [8]

//! [9]
    QTextFrame *frame = cursor.currentFrame();
    QTextFrameFormat frameFormat = frame->frameFormat();
    frameFormat.setBorder(1);
    frame->setFrameFormat(frameFormat);
//! [9]

//! [10]
    QTextCharFormat format = cursor.charFormat();
    format.setFontPointSize(fontSize);

    QTextCharFormat boldFormat = format;
    boldFormat.setFontWeight(QFont::Bold);

    QTextCharFormat highlightedFormat = boldFormat;
    highlightedFormat.setBackground(Qt::yellow);
//! [10]

//! [11]
    for (int weekDay = 1; weekDay <= 7; ++weekDay) {
        QTextTableCell cell = table->cellAt(0, weekDay-1);
//! [11] //! [12]
        QTextCursor cellCursor = cell.firstCursorPosition();
        cellCursor.insertText(QString("%1").arg(QDate::longDayName(weekDay)),
                              boldFormat);
    }
//! [12]

//! [13]
    table->insertRows(table->rows(), 1);
//! [13]

    while (date.month() == selectedDate.month()) {
        int weekDay = date.dayOfWeek();
        QTextTableCell cell = table->cellAt(table->rows()-1, weekDay-1);
        QTextCursor cellCursor = cell.firstCursorPosition();

        if (date == QDate::currentDate())
            cellCursor.insertText(QString("%1").arg(date.day()), highlightedFormat);
        else
            cellCursor.insertText(QString("%1").arg(date.day()), format);

        date = date.addDays(1);
        if (weekDay == 7 && date.month() == selectedDate.month())
            table->insertRows(table->rows(), 1);
    }

    cursor.endEditBlock();
//! [14]
    setWindowTitle(tr("Calendar for %1 %2"
        ).arg(QDate::longMonthName(selectedDate.month())
        ).arg(selectedDate.year()));
}
Exemplo n.º 25
0
	void readInlineText(const QString &data)
	{
		QString line = data;
		// remove all but one space on the front
		{
			bool startedWithSpace = line.startsWith(' ');
			line = line.remove(QRegularExpression("^ *"));
			if (startedWithSpace)
			{
				line = " " + line;
			}
		}
		// inline code
		{
			QRegularExpression exp("`(.*)`");
			QRegularExpressionMatch match = exp.match(line);
			while (match.hasMatch())
			{
				codeSections.append(match.captured(1));
				line.replace(match.capturedStart(), match.capturedLength(), QString("$${{%1}}$$").arg(codeSections.size() - 1));
				match = exp.match(line);
			}
		}
		// link and image
		{
			QRegularExpression exp("(\\!?)\\[(.*)\\]\\((.*)\\)");
			QRegularExpressionMatch match = exp.match(line);
			while (match.hasMatch())
			{
				if (match.captured(1) == "!")
				{
					// FIXME this no work
					htmlSections.append(QString("<img src=\"%1\" alt=\"%2\"/>").arg(match.captured(3), match.captured(2)));
				}
				else
				{
					htmlSections.append(QString("<a href=\"%1\">%2</a>").arg(match.captured(3), match.captured(2)));
				}
				line.replace(match.capturedStart(), match.capturedLength(), QString("$$[[%1]]$$").arg(htmlSections.size() - 1));
				match = exp.match(line);
			}
		}
		QTextCharFormat fmt;
		int numStarsOrUnderscores = 0;
		QChar last = 0;
		for (const QChar &c : line)
		{
			if (last != c)
			{
				// bold
				if (numStarsOrUnderscores == 2)
				{
					if (fmt.fontWeight() == QFont::Normal)
					{
						fmt.setFontWeight(QFont::Bold);
					}
					else
					{
						fmt.setFontWeight(QFont::Normal);
					}
				}
				// italic
				else if (numStarsOrUnderscores == 1)
				{
					fmt.setFontItalic(!fmt.fontItalic());
				}
				numStarsOrUnderscores = 0;
				cursor.setCharFormat(fmt);
			}
			last = c;
			if (c == '*' || c == '_')
			{
				numStarsOrUnderscores++;
			}
			else
			{
				cursor.insertText(c);
			}
		}
	}
Exemplo n.º 26
0
void KoTextLoader::loadBody(const KoXmlElement &bodyElem, QTextCursor &cursor)
{
    const QTextBlockFormat defaultBlockFormat = cursor.blockFormat();
    const QTextCharFormat defaultCharFormat = cursor.charFormat();

    const QTextDocument *document = cursor.block().document();
    d->styleManager = KoTextDocument(document).styleManager();
    Q_ASSERT(d->styleManager);

    d->changeTracker = KoTextDocument(document).changeTracker();
//    if (!d->changeTracker)
//        d->changeTracker = dynamic_cast<KoChangeTracker *>(d->context.dataCenterMap().value("ChangeTracker"));
//    Q_ASSERT(d->changeTracker);

    kDebug(32500) << "text-style:" << KoTextDebug::textAttributes( cursor.blockCharFormat() );
#if 0
    if ((document->isEmpty()) && (d->styleManager)) {
        QTextBlock block = cursor.block();
        d->styleManager->defaultParagraphStyle()->applyStyle(block);
    }
#endif

    startBody(KoXml::childNodesCount(bodyElem));
    KoXmlElement tag;
    bool usedParagraph = false; // set to true if we found a tag that used the paragraph, indicating that the next round needs to start a new one.
    forEachElement(tag, bodyElem) {
        if (! tag.isNull()) {
            const QString localName = tag.localName();
            if (tag.namespaceURI() == KoXmlNS::text) {
                if (usedParagraph)
                    cursor.insertBlock(defaultBlockFormat, defaultCharFormat);
                usedParagraph = true;
                if (d->changeTracker && localName == "tracked-changes") {
                    d->changeTracker->loadOdfChanges(tag);
                    usedParagraph = false;
                } else if (d->changeTracker && localName == "change-start") {
                    loadChangedRegion(tag, cursor);
                    usedParagraph = false;
                } else if (d->changeTracker && localName == "change-end") {
                    d->currentChangeId = 0;
                    usedParagraph = false;
                } else if (localName == "p") {    // text paragraph
                    loadParagraph(tag, cursor);
                } else if (localName == "h") {  // heading
                    loadHeading(tag, cursor);
                } else if (localName == "unordered-list" || localName == "ordered-list" // OOo-1.1
                           || localName == "list" || localName == "numbered-paragraph") {  // OASIS
                    loadList(tag, cursor);
                } else if (localName == "section") {  // Temporary support (###TODO)
                    loadSection(tag, cursor);
                } else {
                    KoVariable *var = KoVariableRegistry::instance()->createFromOdf(tag, d->context);

                    if (var) {
                        KoTextDocumentLayout *layout = dynamic_cast<KoTextDocumentLayout*>(cursor.block().document()->documentLayout());
                        if (layout) {
                            KoInlineTextObjectManager *textObjectManager = layout->inlineTextObjectManager();
                            if (textObjectManager) {
                                KoVariableManager *varManager = textObjectManager->variableManager();
                                if (varManager) {
                                    textObjectManager->insertInlineObject(cursor, var);
                                }
                            }
                        }
                    } else {
                        usedParagraph = false;
                        kWarning(32500) << "unhandled text:" << localName;
                    }
                }
            } else if (tag.namespaceURI() == KoXmlNS::draw) {
                loadShape(tag, cursor);
            } else if (tag.namespaceURI() == KoXmlNS::table) {
                if (localName == "table") {
                    loadTable(tag, cursor);
                } else {
                    kWarning(32500) << "unhandled table:" << localName;
                }
#if 0 // TODO commented out for now
                if (localName == "table") {
                    cursor.insertText("\n");
                    cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1);
                    QTextTable *tbl = cursor.insertTable(1, 1);
                    int rows = 0;
                    int columns = 0;
                    kDebug(32500) << "Table inserted";
                    KoXmlElement tblTag;
                    forEachElement(tblTag, tag) {
                        if (! tblTag.isNull()) {
                            const QString tblLocalName = tblTag.localName();
                            if (tblTag.namespaceURI() == KoXmlNS::table) {
                                if (tblLocalName == "table-column") {
                                    // Do some parsing with the column, see §8.2.1, ODF 1.1 spec
                                    int repeatColumn = tblTag.attributeNS(KoXmlNS::table, "number-columns-repeated", "1").toInt();
                                    columns = columns + repeatColumn;
                                    if (rows > 0)
                                        tbl->resize(rows, columns);
                                    else
                                        tbl->resize(1, columns);
                                } else if (tblLocalName == "table-row") {
                                    // Lot of work to do here...
                                    rows++;
                                    if (columns > 0)
                                        tbl->resize(rows, columns);
                                    else
                                        tbl->resize(rows, 1);
                                    // Added a row
                                    int currentCell = 0;
                                    KoXmlElement rowTag;
                                    forEachElement(rowTag, tblTag) {
                                        if (!rowTag.isNull()) {
                                            const QString rowLocalName = rowTag.localName();
                                            if (rowTag.namespaceURI() == KoXmlNS::table) {
                                                if (rowLocalName == "table-cell") {
                                                    // Ok, it's a cell...
                                                    const int currentRow = tbl->rows() - 1;
                                                    QTextTableCell cell = tbl->cellAt(currentRow, currentCell);
                                                    if (cell.isValid()) {
                                                        cursor = cell.firstCursorPosition();
                                                        loadBody(context, rowTag, cursor);
                                                    } else
                                                        kDebug(32500) << "Invalid table-cell row=" << currentRow << " column=" << currentCell;
                                                    currentCell++;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    cursor = tbl->lastCursorPosition();
                    cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 1);
                } else {
                    kWarning(32500) << "KoTextLoader::loadBody unhandled table::" << localName;
                }
#endif
            }
Exemplo n.º 27
0
void ChatView::appendMessage(QString message, QString sender, UserLevelFlags userLevel, bool playerBold)
{
	bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
	bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
	QTextCursor cursor = prepareBlock(sameSender);
	lastSender = sender;
	
	if (showTimestamps && !sameSender) {
		QTextCharFormat timeFormat;
		timeFormat.setForeground(Qt::black);
		cursor.setCharFormat(timeFormat);
		cursor.insertText(QDateTime::currentDateTime().toString("[hh:mm] "));
	}
	
	QTextCharFormat senderFormat;
	if (tabSupervisor && tabSupervisor->getUserInfo() && (sender == QString::fromStdString(tabSupervisor->getUserInfo()->name()))) {
		senderFormat.setFontWeight(QFont::Bold);
		senderFormat.setForeground(Qt::red);
	} else {
		senderFormat.setForeground(Qt::blue);
		if (playerBold)
			senderFormat.setFontWeight(QFont::Bold);
	}
	senderFormat.setAnchor(true);
	senderFormat.setAnchorHref("user://" + QString::number(userLevel) + "_" + sender);
	if (!sameSender) {
		if (!sender.isEmpty()) {
			const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
			cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel).toImage(), QString::number(pixelSize) + "_" + QString::number((int) userLevel));
			cursor.insertText(" ");
		}
		cursor.setCharFormat(senderFormat);
		if (!sender.isEmpty())
			sender.append(": ");
		cursor.insertText(sender);
	} else
		cursor.insertText("    ");
	
	QTextCharFormat messageFormat;
	if (sender.isEmpty())
		messageFormat.setForeground(Qt::darkGreen);
	cursor.setCharFormat(messageFormat);
	
	int from = 0, index = 0;
	while ((index = message.indexOf('[', from)) != -1) {
		cursor.insertText(message.left(index));
		message = message.mid(index);
		if (message.isEmpty())
			break;
		
		if (message.startsWith("[card]")) {
			message = message.mid(6);
			int closeTagIndex = message.indexOf("[/card]");
			QString cardName = message.left(closeTagIndex);
			if (closeTagIndex == -1)
				message.clear();
			else
				message = message.mid(closeTagIndex + 7);
			
			QTextCharFormat tempFormat = messageFormat;
			tempFormat.setForeground(Qt::blue);
			tempFormat.setAnchor(true);
			tempFormat.setAnchorHref("card://" + cardName);
			
			cursor.setCharFormat(tempFormat);
			cursor.insertText(cardName);
			cursor.setCharFormat(messageFormat);
		} else if (message.startsWith("[url]")) {
			message = message.mid(5);
			int closeTagIndex = message.indexOf("[/url]");
			QString url = message.left(closeTagIndex);
			if (closeTagIndex == -1)
				message.clear();
			else
				message = message.mid(closeTagIndex + 6);
			
			if (!url.contains("://"))
				url.prepend("http://");
			
			QTextCharFormat tempFormat = messageFormat;
			tempFormat.setForeground(Qt::blue);
			tempFormat.setAnchor(true);
			tempFormat.setAnchorHref(url);
			
			cursor.setCharFormat(tempFormat);
			cursor.insertText(url);
			cursor.setCharFormat(messageFormat);
		} else
			from = 1;
	}
	if (!message.isEmpty())
		cursor.insertText(message);
	
	if (atBottom)
		verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
Exemplo n.º 28
0
void Utils::unCommentSelection(QPlainTextEdit *edit, CommentFlag flag, const CommentDefinition &definition)
{
    if (!definition.hasSingleLineStyle() && !definition.hasMultiLineStyle())
        return;

    QTextCursor cursor = edit->textCursor();
    QTextDocument *doc = cursor.document();

    if (!cursor.hasSelection() && (flag == BlockComment) ) {
        if (definition.hasMultiLineStyle()) {
            cursor.beginEditBlock();
            cursor.insertText(definition.multiLineStart());
            cursor.insertText(definition.multiLineEnd());
            cursor.movePosition(QTextCursor::Left,QTextCursor::MoveAnchor,definition.multiLineEnd().length());
            cursor.endEditBlock();
            edit->setTextCursor(cursor);
            return;
        }
    }

    cursor.beginEditBlock();

    int pos = cursor.position();
    int anchor = cursor.anchor();
    int start = qMin(anchor, pos);
    int end = qMax(anchor, pos);
    bool anchorIsStart = (anchor == start);

    QTextBlock startBlock = doc->findBlock(start);
    QTextBlock endBlock = doc->findBlock(end);

    if (end > start && endBlock.position() == end) {
        --end;
        endBlock = endBlock.previous();
    }

    bool doMultiLineStyleUncomment = false;
    bool doMultiLineStyleComment = false;
    bool doSingleLineStyleUncomment = false;

    bool hasSelection = cursor.hasSelection();
    int firstSpacesOffset = -1;

    if (hasSelection && definition.hasMultiLineStyle()) {

        QString startText = startBlock.text();
        int startPos = start - startBlock.position();
        const int multiLineStartLength = definition.multiLineStart().length();
        bool hasLeadingCharacters = !startText.left(startPos).trimmed().isEmpty();

        if (startPos >= multiLineStartLength
            && isComment(startText,
                         startPos - multiLineStartLength,
                         definition,
                         &CommentDefinition::multiLineStart)) {
            startPos -= multiLineStartLength;
            start -= multiLineStartLength;
        }

        bool hasSelStart = (startPos <= startText.length() - multiLineStartLength
                            && isComment(startText,
                                         startPos,
                                         definition,
                                         &CommentDefinition::multiLineStart));

        QString endText = endBlock.text();
        int endPos = end - endBlock.position();
        const int multiLineEndLength = definition.multiLineEnd().length();
        bool hasTrailingCharacters =
                !endText.left(endPos).remove(definition.singleLine()).trimmed().isEmpty()
                && !endText.mid(endPos).trimmed().isEmpty();

        if (endPos <= endText.length() - multiLineEndLength
            && isComment(endText, endPos, definition, &CommentDefinition::multiLineEnd)) {
            endPos += multiLineEndLength;
            end += multiLineEndLength;
        }

        bool hasSelEnd = (endPos >= multiLineEndLength
                          && isComment(endText,
                                       endPos - multiLineEndLength,
                                       definition,
                                       &CommentDefinition::multiLineEnd));

        doMultiLineStyleUncomment = hasSelStart && hasSelEnd;
        doMultiLineStyleComment = !doMultiLineStyleUncomment
                                  && (hasLeadingCharacters
                                      || hasTrailingCharacters
                                      || !definition.hasSingleLineStyle()
                                      || (flag == BlockComment));
    } else if (!hasSelection && !definition.hasSingleLineStyle()) {

        QString text = startBlock.text().trimmed();
        doMultiLineStyleUncomment = text.startsWith(definition.multiLineStart())
                                    && text.endsWith(definition.multiLineEnd());
        doMultiLineStyleComment = !doMultiLineStyleUncomment && !text.isEmpty();

        start = startBlock.position();
        end = endBlock.position() + endBlock.length() - 1;

        if (doMultiLineStyleUncomment) {
            int offset = 0;
            text = startBlock.text();
            const int length = text.length();
            while (offset < length && text.at(offset).isSpace())
                ++offset;
            start += offset;
        }
    }

    if (flag == SingleComment) {
        if (doMultiLineStyleComment) {
            doMultiLineStyleComment = false;
        }
    }

    if (doMultiLineStyleUncomment) {
        cursor.setPosition(end);
        cursor.movePosition(QTextCursor::PreviousCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineEnd().length());
        cursor.removeSelectedText();
        cursor.setPosition(start);
        cursor.movePosition(QTextCursor::NextCharacter,
                            QTextCursor::KeepAnchor,
                            definition.multiLineStart().length());
        cursor.removeSelectedText();
    } else if (doMultiLineStyleComment) {
        cursor.setPosition(end);
        cursor.insertText(definition.multiLineEnd());
        cursor.setPosition(start);
        cursor.insertText(definition.multiLineStart());
    } else {
        endBlock = endBlock.next();
        doSingleLineStyleUncomment = true;
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            QString text = block.text().trimmed();
            if (!text.isEmpty() && !text.startsWith(definition.singleLine())) {
                doSingleLineStyleUncomment = false;
                break;
            }
        }
        if (!hasSelection && cursor.block().text().isEmpty()) {
            doSingleLineStyleUncomment = false;
        }
        const int singleLineLength = definition.singleLine().length();
        for (QTextBlock block = startBlock; block != endBlock; block = block.next()) {
            if (doSingleLineStyleUncomment) {
                QString text = block.text();
                int i = 0;
                while (i <= text.size() - singleLineLength) {
                    if (isComment(text, i, definition, &CommentDefinition::singleLine)) {
                        cursor.setPosition(block.position() + i);
                        cursor.movePosition(QTextCursor::NextCharacter,
                                            QTextCursor::KeepAnchor,
                                            singleLineLength);
                        if (definition.isAfterWhiteSpacesAddSpace()) {
                            if (i < text.size()-singleLineLength) {
                                if (text.at(i+singleLineLength) == 0x0020) {
                                    cursor.movePosition(QTextCursor::NextCharacter,QTextCursor::KeepAnchor,1);
                                }
                            }
                        }
                        cursor.removeSelectedText();
                        break;
                    }
                    if (!text.at(i).isSpace())
                        break;
                    ++i;
                }
            } else {
                QString text = block.text();
                foreach(QChar c, text) {
                    if (!c.isSpace()) {
                        if (definition.isAfterWhiteSpaces()) {
                            int offset = text.indexOf(c);
                            if (firstSpacesOffset != -1 && offset > firstSpacesOffset) {
                                offset = firstSpacesOffset;
                            }
                            cursor.setPosition(block.position() + offset);
                        } else {
                            cursor.setPosition(block.position());
                        }
                        if (firstSpacesOffset == -1) {
                            firstSpacesOffset = cursor.position()-cursor.block().position();
                        }
                        if (definition.isAfterWhiteSpaces() && definition.isAfterWhiteSpacesAddSpace()) {
                            cursor.insertText(definition.singleLine()+" ");
                        } else {
                            cursor.insertText(definition.singleLine());
                        }
                        break;
                    }
                }
            }
        }
    }

    // adjust selection when commenting out
    if (hasSelection && !doMultiLineStyleUncomment && !doSingleLineStyleUncomment) {
        cursor = edit->textCursor();
        if (!doMultiLineStyleComment)
            start = startBlock.position(); // move the comment into the selection
        int lastSelPos = anchorIsStart ? cursor.position() : cursor.anchor();
        if (anchorIsStart) {
            cursor.setPosition(start);
            cursor.setPosition(lastSelPos, QTextCursor::KeepAnchor);
        } else {
            cursor.setPosition(lastSelPos);
            cursor.setPosition(start, QTextCursor::KeepAnchor);
        }
        edit->setTextCursor(cursor);
    }

    cursor.endEditBlock();
}
void ClientSessionData::print(QTextCursor &cursor)
{      
    cursor.insertText("\n\tFee: " + fee);
    cursor.insertText("\n\tIncome: " + income);
    cursor.insertText("\n\tPaid: ");
    if(paid)
        cursor.insertText("Yes");
    else
        cursor.insertText("No");
    cursor.insertText("\tAt Table: ");
    if(atTable)
        cursor.insertText("Yes");
    else
        cursor.insertText("No");
    cursor.insertText("\n\tSupport: " + QString::number(support));
    cursor.insertText("\n\tAttorney said they would attend: ");
    if(attySaidAttend)
        cursor.insertText("Yes");
    else
        cursor.insertText("No");
    cursor.insertText("\n\tAttorney did attend: ");
    if(attyDidAttend)
        cursor.insertText("Yes");
    else
        cursor.insertText("No");
    cursor.insertText("\n");

}
Exemplo n.º 30
0
void QGithubMarkdown::read(const QByteArray &markdown, QTextDocument *target)
{
	doc = target;
	doc->clear();
	cursor = QTextCursor(doc);
	cursor.beginEditBlock();
	const QList<Token> tokens = tokenize(clean(QString::fromUtf8(markdown)));
	const QList<Paragraph> paragraphs = paragraphize(tokens);
	const auto paralists = listize(paragraphs);
	//std::for_each(paragraphs.begin(), paragraphs.end(), [](const Paragraph &item){qDebug() << item;});
	bool firstBlock = true;
	for (const auto paralist : paralists)
	{
		auto insertTokens = [&](const QList<Token> &tokens, const QTextCharFormat &format, const bool isCode)
		{
			QTextCharFormat fmt(format);
			QTextCharFormat codeFmt(format);
			codeFmt.setFontFamily("Monospace");
			QListIterator<Token> iterator(tokens);
			while (iterator.hasNext())
			{
				const Token token = iterator.next();
				if (isCode)
				{
					cursor.insertText(token.source);
				}
				else
				{
					if (token.type == Token::Bold)
					{
						if (fmt.fontWeight() == QFont::Bold)
						{
							fmt.setFontWeight(QFont::Normal);
						}
						else
						{
							fmt.setFontWeight(QFont::Bold);
						}
					}
					else if (token.type == Token::Italic)
					{
						fmt.setFontItalic(!fmt.fontItalic());
					}
					else if (token.type == Token::InlineCodeDelimiter)
					{
						while (iterator.hasNext())
						{
							const Token next = iterator.next();
							if (next.type == Token::InlineCodeDelimiter)
							{
								break;
							}
							else
							{
								cursor.insertText(token.source, codeFmt);
							}
						}
					}
					else if (token.type == Token::Character)
					{
						cursor.insertText(token.content.toChar(), fmt);
					}
					else
					{
						cursor.insertText(token.source, fmt);
					}
				}
			}
		};

		if (paralist.second.indent == -1)
		{
			const Paragraph paragraph = paralist.first;
			QTextCharFormat charFmt;
			QTextBlockFormat blockFmt;
			blockFmt.setBottomMargin(5.0f);
			if (Paragraph::FirstHeading <= paragraph.type && paragraph.type <= Paragraph::LastHeading)
			{
				charFmt.setFontPointSize(sizeMap[paragraph.type]);
			}
			else if (paragraph.type == Paragraph::Quote)
			{
				blockFmt.setIndent(1);
			}
			else if (paragraph.type == Paragraph::Code)
			{
				blockFmt.setNonBreakableLines(true);
				charFmt.setFontFamily("Monospace");
			}

			if (!firstBlock)
			{
				cursor.insertBlock();
			}
			else
			{
				firstBlock = false;
			}
			cursor.setBlockFormat(blockFmt);
			cursor.block().setUserState(paragraph.type);
			insertTokens(paragraph.tokens, charFmt, paragraph.type == Paragraph::Code);
		}
		else
		{
			const List list = paralist.second;
			qDebug() << "##########################" << list.indent << list.ordered;
			std::for_each(list.paragraphs.begin(), list.paragraphs.end(), [](const Paragraph &item){qDebug() << item;});
			cursor.setBlockFormat(QTextBlockFormat());
			cursor.setBlockCharFormat(QTextCharFormat());
			QTextListFormat listFormat;
			listFormat.setStyle(list.ordered ? QTextListFormat::ListDecimal : QTextListFormat::ListDisc);
			listFormat.setIndent(list.indent);
			QTextList *l = cursor.insertList(listFormat);
			qDebug() << "inserting list" << list.indent;
			bool firstBlock = true;
			for (const Paragraph &paragraph : list.paragraphs)
			{
				if (firstBlock)
				{
					firstBlock = false;
				}
				else
				{
					cursor.insertBlock();
					qDebug() << "inserting block";
				}
				insertTokens(paragraph.tokens, QTextCharFormat(), false);
				qDebug() << l->count();
				l->add(cursor.block());
				qDebug() << l->count();
				qDebug() << "inserting characters";
			}
		}
	}
	cursor.endEditBlock();
	qDebug() << doc->toHtml();
}