QImage KoStyleThumbnailer::thumbnail(KoCharacterStyle *characterStyle, KoParagraphStyle *paragraphStyle, QSize size, bool recreateThumbnail, KoStyleThumbnailerFlags flags)
{
    if ((flags & UseStyleNameText)  && (!characterStyle || characterStyle->name().isNull())) {
        return QImage();
    } else if ((! (flags & UseStyleNameText)) && d->thumbnailText.isEmpty()) {
        return QImage();
    }
    else if (characterStyle == 0) {
        return QImage();
    }

    if (!size.isValid() || size.isNull()) {
        size = d->defaultSize;
    }
    QString imageKey = "c_" + QString::number(reinterpret_cast<unsigned long>(characterStyle)) + "_"
                     + "p_" + QString::number(reinterpret_cast<unsigned long>(paragraphStyle)) + "_"
                     + QString::number(size.width()) + "_" + QString::number(size.height());

    if (!recreateThumbnail && d->thumbnailCache.object(imageKey)) {
        return QImage(*(d->thumbnailCache.object(imageKey)));
    }

    QImage *im = new QImage(size.width(), size.height(), QImage::Format_ARGB32_Premultiplied);
    im->fill(QColor(Qt::transparent).rgba());

    QTextCursor cursor(d->thumbnailHelperDocument);
    QTextCharFormat format;
    // Default to black as text color, to match what KoTextLayoutArea::paint(...)
    // does, setting solid black if no brush is set. Otherwise the UI text color
    // would be used, which might be too bright with dark UI color schemes
    format.setForeground(QColor(Qt::black));
    KoCharacterStyle *characterStyleClone = characterStyle->clone();
    characterStyleClone->applyStyle(format);
    cursor.select(QTextCursor::Document);
    cursor.setBlockFormat(QTextBlockFormat());
    cursor.setBlockCharFormat(QTextCharFormat());
    cursor.setCharFormat(QTextCharFormat());

    if (paragraphStyle) {
        KoParagraphStyle *paragraphStyleClone = paragraphStyle->clone();
       // paragraphStyleClone->KoCharacterStyle::applyStyle(format);
        QTextBlock block = cursor.block();
        paragraphStyleClone->applyStyle(block, true);
        delete paragraphStyleClone;
        paragraphStyleClone = 0;
    }

    if (flags & UseStyleNameText) {
        cursor.insertText(characterStyleClone->name(), format);
    } else {
        cursor.insertText(d->thumbnailText, format);
    }

    layoutThumbnail(size, im, flags);

    d->thumbnailCache.insert(imageKey, im);
    delete characterStyleClone;
    return QImage(*im);
}
Exemplo n.º 2
0
void MainWindow::on_m_stress_triggered()
{
    off_ct = true;
    if (ui->m_stress->isChecked())
        on_m_proccessing_triggered();
    else
    {
        QTextCursor cur(ui->textEdit->document());
        QString word;
        QChar end_of_buf;
        QString wrong_char = "?!., ;:\'\"\\/+><@#~`$%^&*(){}|\n\r\t\a\?";
        fake_text = ui->textEdit->toHtml();
        progress->setMaximum(ui->textEdit->toPlainText().length());
        progress->setValue(0);
        while (cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor))
        {
            progress->setValue(progress->value()+1);
            word = cur.selectedText();
            end_of_buf = word[word.length()-1];
            if (wrong_char.contains(end_of_buf) || end_of_buf.unicode()==8233)
            {
                QTextCursor cur2 (ui->textEdit->document());
                cur2.setPosition(cur.position());
                cur2.movePosition(QTextCursor::PreviousCharacter);
                if (cur2.charFormat().foreground().color()!=QColor("red") && cur2.charFormat().foreground().color()!=QColor("blue"))
                {
                    cur.clearSelection();
                    word.clear();
                    continue;
                }
                word = cur.selectedText();
                cur.removeSelectedText();
                cur.insertText(word,QTextCharFormat());
                cur.clearSelection();
            }
        }
        if (!cur.selectedText().isEmpty())
        {
            QTextCursor cur2 (ui->textEdit->document());
            if (cur2.charFormat().foreground().color()==QColor("red") || cur2.charFormat().foreground().color()==QColor("blue"))
            {
                word = cur.selectedText();
                cur.removeSelectedText();
                cur.insertText(word,QTextCharFormat());
            }
        }
        tpl = ui->textEdit->toPlainText().length();
        refresh_ur(false);
        oper_stack.insert(oper_stack.begin(),1,
                  oper_info(1,1,1,
                  fake_text,ui->textEdit->toHtml()  ));
        fake_text = ui->textEdit->toHtml();
    }
    off_ct = false;
}
Exemplo n.º 3
0
void tst_QCalendarWidget::resetTextFormat()
{
    QCalendarWidget calendar;
    QTextCharFormat format;
    format.setFontItalic(true);
    format.setForeground(Qt::green);

    const QDate date(1984, 10, 20);
    calendar.setDateTextFormat(date, format);

    calendar.setDateTextFormat(QDate(), QTextCharFormat());
    QCOMPARE(calendar.dateTextFormat(date), QTextCharFormat());
}
QImage KoStyleThumbnailer::thumbnail(KoParagraphStyle *style, QSize size, bool recreateThumbnail, KoStyleThumbnailerFlags flags)
{
    if ((flags & UseStyleNameText)  && (!style || style->name().isNull())) {
        return QImage();
    } else if ((! (flags & UseStyleNameText)) && d->thumbnailText.isEmpty()) {
        return QImage();
    }

    if (!size.isValid() || size.isNull()) {
        size = d->defaultSize;
    }
    QString imageKey = "p_" + QString::number(reinterpret_cast<unsigned long>(style)) + "_" + QString::number(size.width()) + "_" + QString::number(size.height());

    if (!recreateThumbnail && d->thumbnailCache.object(imageKey)) {
        return QImage(*(d->thumbnailCache.object(imageKey)));
    }

    QImage *im = new QImage(size.width(), size.height(), QImage::Format_ARGB32_Premultiplied);
    im->fill(QColor(Qt::transparent).rgba());

    KoParagraphStyle *clone = style->clone();
    //TODO: make the following real options
    //we ignore these properties when the thumbnail would not be sufficient to preview properly the whole paragraph with margins.
    clone->setMargin(QTextLength(QTextLength::FixedLength, 0));
    clone->setPadding(0);
    //
    QTextCursor cursor(d->thumbnailHelperDocument);
    cursor.select(QTextCursor::Document);
    cursor.setBlockFormat(QTextBlockFormat());
    cursor.setBlockCharFormat(QTextCharFormat());
    cursor.setCharFormat(QTextCharFormat());
    QTextBlock block = cursor.block();
    clone->applyStyle(block, true);

    QTextCharFormat format;
    // Default to black as text color, to match what KoTextLayoutArea::paint(...)
    // does, setting solid black if no brush is set. Otherwise the UI text color
    // would be used, which might be too bright with dark UI color schemes
    format.setForeground(QColor(Qt::black));
    clone->KoCharacterStyle::applyStyle(format);
    if (flags & UseStyleNameText) {
        cursor.insertText(clone->name(), format);
    } else {
        cursor.insertText(d->thumbnailText, format);
    }
    layoutThumbnail(size, im, flags);

    d->thumbnailCache.insert(imageKey, im);
    delete clone;
    return QImage(*im);
}
void OrganiseFormat::SyntaxHighlighter::highlightBlock(const QString& text) {
  const bool light = QApplication::palette().color(QPalette::Base).value() > 128;
  const QRgb block_color = light ? kBlockColorLight : kBlockColorDark;
  const QRgb valid_tag_color = light ? kValidTagColorLight : kValidTagColorDark;
  const QRgb invalid_tag_color = light ? kInvalidTagColorLight : kInvalidTagColorDark;

  QRegExp tag_regexp(kTagPattern);
  QRegExp block_regexp(kBlockPattern);

  QTextCharFormat block_format;
  block_format.setBackground(QColor(block_color));

  // Reset formatting
  setFormat(0, text.length(), QTextCharFormat());

  // Blocks
  int pos = 0;
  while ((pos = block_regexp.indexIn(text, pos)) != -1) {
    setFormat(pos, block_regexp.matchedLength(), block_format);

    pos += block_regexp.matchedLength();
  }

  // Tags
  pos = 0;
  while ((pos = tag_regexp.indexIn(text, pos)) != -1) {
    QTextCharFormat f = format(pos);
    f.setForeground(QColor(OrganiseFormat::kKnownTags.contains(tag_regexp.cap(1))
                           ? valid_tag_color : invalid_tag_color));

    setFormat(pos, tag_regexp.matchedLength(), f);
    pos += tag_regexp.matchedLength();
  }
}
Exemplo n.º 6
0
QString Formats::name(const QTextCharFormat &format) const
{
    if (format == QTextCharFormat())
        return "Default format";
    else if (format == m_keywordFormat)
        return "Keyword";
    else if (format == m_dataTypeFormat)
        return "Data type format";
    else if (format == m_decimalFormat)
        return "Decimal format";
    else if (format == m_baseNFormat)
        return "Base N format";
    else if (format == m_floatFormat)
        return "Float format";
    else if (format == m_charFormat)
        return "Char format";
    else if (format == m_stringFormat)
        return "String format";
    else if (format == m_commentFormat)
        return "Comment format";
    else if (format == m_alertFormat)
        return "Alert format";
    else if (format == m_errorFormat)
        return "Error format";
    else if (format == m_functionFormat)
        return "Function format";
    else if (format == m_regionMarkerFormat)
        return "Region Marker format";
    else if (format == m_othersFormat)
        return "Others format";
    else
        return "Unidentified format";
}
Exemplo n.º 7
0
void tst_QTextFormat::toFormat()
{
    {
        QTextFormat fmt = QTextFrameFormat();
        QCOMPARE(fmt.toFrameFormat().type(), int(QTextFormat::FrameFormat));
    }

    {
        QTextFormat fmt = QTextTableFormat();
        QCOMPARE(fmt.toTableFormat().type(), int(QTextFormat::FrameFormat));
        QCOMPARE(fmt.toTableFormat().objectType(), int(QTextFormat::TableObject));
    }

    {
        QTextFormat fmt = QTextBlockFormat();
        QCOMPARE(fmt.toBlockFormat().type(), int(QTextFormat::BlockFormat));
    }

    {
        QTextFormat fmt = QTextCharFormat();
        QCOMPARE(fmt.toCharFormat().type(), int(QTextFormat::CharFormat));
    }

    {
        QTextFormat fmt = QTextListFormat();
        QCOMPARE(fmt.toListFormat().type(), int(QTextFormat::ListFormat));
    }
}
Exemplo n.º 8
0
QTextCharFormat QTextEditProto::currentCharFormat() const
{
  QTextEdit *item = qscriptvalue_cast<QTextEdit*>(thisObject());
  if (item)
    return item->currentCharFormat();
  return QTextCharFormat();
}
Exemplo n.º 9
0
void ChatWidget::sendChat()
{
	QTextEdit *chatWidget = ui->chatTextEdit;

	if (chatWidget->toPlainText().isEmpty()) {
		// nothing to send
		return;
	}

	QString text;
	RsHtml::optimizeHtml(chatWidget, text);
	std::wstring msg = text.toStdWString();

	if (msg.empty()) {
		// nothing to send
		return;
	}

#ifdef CHAT_DEBUG
	std::cout << "ChatWidget:sendChat " << std::endl;
#endif

	if (rsMsgs->sendPrivateChat(peerId, msg)) {
		QDateTime currentTime = QDateTime::currentDateTime();
		addChatMsg(false, name, currentTime, currentTime, QString::fromStdWString(msg), TYPE_NORMAL);
	}

	chatWidget->clear();
	// workaround for Qt bug - http://bugreports.qt.nokia.com/browse/QTBUG-2533
	// QTextEdit::clear() does not reset the CharFormat if document contains hyperlinks that have been accessed.
	chatWidget->setCurrentCharFormat(QTextCharFormat ());
}
Exemplo n.º 10
0
/*!
    Returns the text fragment's character format.

    \sa text()
*/
QTextCharFormat QTextFragment::charFormat() const
{
    if (!p || !n)
        return QTextCharFormat();
    const QTextFragmentData *data = p->fragmentMap().fragment(n);
    return p->formatCollection()->charFormat(data->format);
}
Exemplo n.º 11
0
void FriendsDialog::sendMsg()
{
    QTextEdit *lineWidget = ui.lineEdit;

    if (lineWidget->toPlainText().isEmpty()) {
        // nothing to send
        return;
    }

    QString text;
    RsHtml::optimizeHtml(lineWidget, text);
    std::wstring message = text.toStdWString();

#ifdef FRIENDS_DEBUG
    std::string msg(message.begin(), message.end());
    std::cerr << "FriendsDialog::sendMsg(): " << msg << std::endl;
#endif

    rsMsgs->sendPublicChat(message);
    ui.lineEdit->clear();
    // workaround for Qt bug - http://bugreports.qt.nokia.com/browse/QTBUG-2533
    // QTextEdit::clear() does not reset the CharFormat if document contains hyperlinks that have been accessed.
    ui.lineEdit->setCurrentCharFormat(QTextCharFormat ());

    /* redraw send list */
    insertSendList();
}
Exemplo n.º 12
0
void Console::moveToEndOfCommandLine()
{
    QTextCursor cur(document()->lastBlock());
    cur.movePosition(QTextCursor::EndOfBlock);
    cur.setCharFormat(QTextCharFormat());
    setTextCursor(cur);
}
Exemplo n.º 13
0
QTextCharFormat BaseObjectView::getFontStyle(const QString &id)
{
	if(font_config.count(id))
		return(font_config[id]);
	else
		return(QTextCharFormat());
}
Exemplo n.º 14
0
void SpellCheckerWindow::on_clearButton_clicked()
{
    std::cerr << "# clearButton clicked" << std::endl;

    QTextCursor cur (ui->textEdit->document ());
    cur.movePosition (QTextCursor::End, QTextCursor::KeepAnchor);
    cur.setCharFormat (QTextCharFormat());
}
Exemplo n.º 15
0
	void ChatHistoryWidget::UpdateDates ()
	{
		Ui_.Calendar_->setDateTextFormat (QDate (), QTextCharFormat ());

		if (CurrentEntry_.isEmpty ())
			return;

		Core::Instance ()->GetDaysForSheet (CurrentAccount_, CurrentEntry_,
				Ui_.Calendar_->yearShown (), Ui_.Calendar_->monthShown ());
	}
Exemplo n.º 16
0
void Console::insertCompletion(const QString& text)
{
    if (!m_completer) return;
    QTextCursor cur = textCursor();
    cur.select(QTextCursor::WordUnderCursor);
    if (cur.selectedText().compare(m_completer->completionPrefix(), Qt::CaseInsensitive) == 0) {
        cur.removeSelectedText();
        cur.setCharFormat(QTextCharFormat());
        cur.insertText(text);
        setTextCursor(cur);
    }
}
Exemplo n.º 17
0
void DevHighlighter::reformatBlock(QTextBlock& block)
{
	previous = block.previous();

	formatChanges.fill(QTextCharFormat(), block.length() - 1);
	highlightBlock(block);
	applyFormatChanges(block);
	
	previous = QTextBlock();
	
	doc->markContentsDirty(block.position(), block.length());
}
void QDeclarativeTextLayout::draw(QPainter *painter, const QPointF &p)
{
    QPainterPrivate *priv = QPainterPrivate::get(painter);

    bool paintEngineSupportsTransformations = priv->extended &&
                                              (priv->extended->type() == QPaintEngine::OpenGL2 ||
                                               priv->extended->type() == QPaintEngine::OpenVG ||
                                               priv->extended->type() == QPaintEngine::OpenGL);

    if (!paintEngineSupportsTransformations || !priv->state->matrix.isAffine()) {
        QTextLayout::draw(painter, p);
        return;
    }

    prepare();

    int itemCount = d->items.count();

    if (p != d->position) {
        QFixed fx = QFixed::fromReal(p.x());
        QFixed fy = QFixed::fromReal(p.y());
        QFixed oldX = QFixed::fromReal(d->position.x());
        QFixed oldY = QFixed::fromReal(d->position.y());
        for (int item = 0; item < itemCount; ++item) {
            QStaticTextItem &textItem = d->items[item];

            for (int ii = 0; ii < textItem.numGlyphs; ++ii) {
                textItem.glyphPositions[ii].x += fx - oldX;
                textItem.glyphPositions[ii].y += fy - oldY;
            }
            textItem.userDataNeedsUpdate = true;
        }

        d->position = p;
    }

    QPen oldPen = priv->state->pen;
    QColor currentColor = oldPen.color();
    for (int ii = 0; ii < itemCount; ++ii) {
        QStaticTextItem &item = d->items[ii];
        if (item.color.isValid() && currentColor != item.color) {
            painter->setPen(item.color);
            currentColor = item.color;
        }
        priv->extended->drawStaticTextItem(&item);

        qt_draw_decoration_for_glyphs(painter, item.glyphs, item.glyphPositions,
                                      item.numGlyphs, item.fontEngine(), painter->font(),
                                      QTextCharFormat());
    }
    if (currentColor != oldPen.color())
        painter->setPen(oldPen);
}
Exemplo n.º 19
0
void QTextDocumentPrivate::init()
{
    rtFrame = 0;
    framesDirty = false;

    bool undoState = undoEnabled;
    undoEnabled = false;
    initialBlockCharFormatIndex = formats.indexForFormat(QTextCharFormat());
    insertBlock(0, formats.indexForFormat(QTextBlockFormat()), formats.indexForFormat(QTextCharFormat()));
    undoEnabled = undoState;
    modified = false;
    modifiedState = 0;
}
Exemplo n.º 20
0
void WareSrcMsgViewer::writeMessage(const openfluid::waresdev::WareSrcMsgParser::WareSrcMsg& Msg)
{
  QTextCursor Cursor = textCursor();

  Cursor.setCharFormat(m_FormatByMsgType.value(Msg.m_Type, QTextCharFormat()));

  if (Msg.m_LineNb > 0)
    m_MessagesByBlockNumber.insert(Cursor.blockNumber(), Msg);

  Cursor.insertText(QString::fromUtf8(Msg.m_OriginalMsgLine));

  ensureCursorVisible();
}
Exemplo n.º 21
0
void OcrEngine::addWord(const QString &word, const OcrWordData &data)
{
    if (m_ocrDialog->verboseDebug())
    {
        kDebug() << "word" << word << "len" << word.length()
                 << "rect" << data.property(OcrWordData::Rectangle)
                 << "alts" << data.property(OcrWordData::Alternatives);
    }

    if (!m_cursor->atBlockStart()) m_cursor->insertText(" ", QTextCharFormat());
    m_cursor->insertText(word, data);
    ++m_wordCount;
}
Exemplo n.º 22
0
void Console::prepareCommandLine()
{
    QTextCursor cur(document()->lastBlock());
    cur.movePosition(QTextCursor::EndOfBlock);
    cur.insertBlock();

    QTextCharFormat fmt;
    fmt.setForeground(QBrush(m_prefixColor));
    fmt.setFont(m_prefixFont);
    cur.setCharFormat(fmt);
    cur.insertText(m_prefix);
    cur.setCharFormat(QTextCharFormat());
    setTextCursor(cur);
}
Exemplo n.º 23
0
	void ChatHistoryWidget::handleGotDaysForSheet (const QString& accountId,
			const QString& entryId, int year, int month, const QList<int>& days)
	{
		if (accountId != CurrentAccount_ ||
			entryId != CurrentEntry_ ||
			year != Ui_.Calendar_->yearShown () ||
			month != Ui_.Calendar_->monthShown ())
			return;

		Ui_.Calendar_->setDateTextFormat (QDate (), QTextCharFormat ());

		QTextCharFormat fmt;
		fmt.setFontWeight (QFont::Bold);
		Q_FOREACH (int day, days)
			Ui_.Calendar_->setDateTextFormat (QDate (year, month, day), fmt);
	}
Exemplo n.º 24
0
void QSyntaxHighlighterPrivate::reformatBlock(QTextBlock block)
{
    Q_Q(QSyntaxHighlighter);

    Q_ASSERT_X(!currentBlock.isValid(), "QSyntaxHighlighter::reformatBlock()", "reFormatBlock() called recursively");

    currentBlock = block;
    QTextBlock previous = block.previous();

    formatChanges.fill(QTextCharFormat(), block.length() - 1);
    q->highlightBlock(block.text());
    applyFormatChanges();

    doc->markContentsDirty(block.position(), block.length());

    currentBlock = QTextBlock();
}
Exemplo n.º 25
0
void Document::setRichText(bool rich_text)
{
	// Get new file name
	m_old_states[m_text->document()->availableUndoSteps()] = qMakePair(m_filename, m_rich_text);
	if (!m_filename.isEmpty()) {
		QString filename = m_filename;
		int suffix_index = filename.lastIndexOf(QChar('.'));
		int file_index = filename.lastIndexOf(QChar('/'));
		if (suffix_index > file_index) {
			filename.chop(filename.length() - suffix_index);
		}
                filename.append(rich_text ? ".proseup" : ".txt");
		QString selected;
		m_filename = QFileDialog::getSaveFileName(window(), tr("Save File As"), filename, fileFilter(filename), &selected);
		if (!m_filename.isEmpty()) {
			m_filename = fileNameWithExtension(m_filename, selected);
			clearIndex();
		} else {
			findIndex();
		}
	}

	// Set file type
	m_rich_text = rich_text;
	m_text->setAcceptRichText(m_rich_text);

	// Always remove formatting to have something to undo
	QTextCursor cursor(m_text->document());
	cursor.beginEditBlock();
	cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
	cursor.setBlockFormat(QTextBlockFormat());
	cursor.setCharFormat(QTextCharFormat());
        cleanUpDocument();
	cursor.endEditBlock();
	m_old_states[m_text->document()->availableUndoSteps()] = qMakePair(m_filename, m_rich_text);

	// Save file
	if (!m_filename.isEmpty()) {
		save();
		updateState();
		m_text->document()->setModified(false);
	}
	emit changedName();
	emit formattingEnabled(m_rich_text);
}
Exemplo n.º 26
0
// NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
//       until you _really_ know what you do!
QTextCharFormat UiStyle::format(quint32 ftype, quint32 label_) const {
  if(ftype == Invalid)
    return QTextCharFormat();

  quint64 label = (quint64)label_ << 32;

  // check if we have exactly this format readily cached already
  QTextCharFormat fmt = cachedFormat(ftype, label_);
  if(fmt.properties().count())
    return fmt;

  mergeFormat(fmt, ftype, label & Q_UINT64_C(0xffff000000000000));

  for(quint64 mask = Q_UINT64_C(0x0000000100000000); mask <= (quint64)Selected << 32; mask <<=1) {
    if(label & mask)
      mergeFormat(fmt, ftype, mask | Q_UINT64_C(0xffff000000000000));
  }

  setCachedFormat(fmt, ftype, label_);
  return fmt;
}
QTextCharFormat DeveloperEditor::getDayFormat(const ExceptDayData *dayData)
{
  if( !dayData )
    return QTextCharFormat();
  
  QTextCharFormat exceptDayFormat;
  
  exceptDayFormat.setUnderlineStyle( QTextCharFormat::SingleUnderline );
  exceptDayFormat.setFontWeight(QFont::Bold);
  
  switch( dayData->dayType ) 
  {
    case ExceptDayType::HOLIDAYS: exceptDayFormat.setForeground( QBrush(Qt::blue) ); break;
    
    case ExceptDayType::SICKLIST: exceptDayFormat.setForeground( QBrush(Qt::darkYellow) ); break;
    
    default:  exceptDayFormat.setForeground( QBrush( dayData->isWorking ? Qt::black : Qt::red) ); break;
  }
  
  return exceptDayFormat;
}
Exemplo n.º 28
0
QByteArray QGithubMarkdown::write(QTextDocument *source)
{
	QStringList output;
	bool wasInList = false;
	bool inCodeBlock = false;
	auto endCodeBlock = [&]()
	{
		if (inCodeBlock)
		{
			output.append("```\n");
		}
		inCodeBlock = false;
	};
	auto formatForPos = [&](const QTextBlock &block, const int pos) -> QTextCharFormat
	{
		for (const auto fmtRange : block.textFormats())
		{
			if (fmtRange.start <= pos && pos <= (fmtRange.start + fmtRange.length))
			{
				return fmtRange.format;
			}
		}
		Q_ASSERT(false);
		return QTextCharFormat();
	};
	auto blockToMarkdown = [&](const QTextBlock &block, const int offset = 0) -> QString
	{
		QString out;
		bool inBold = false;
		bool inItalic = false;
		QString currentLink;
		for (int i = offset; i < block.text().size(); ++i)
		{
			const QChar c = block.text().at(i);
			const QTextCharFormat fmt = formatForPos(block, i);
			if (fmt.fontItalic() != inItalic)
			{
				out.insert(out.size() - 1, '_');
				inItalic = !inItalic;
			}
			if ((fmt.fontWeight() == QFont::Bold) != inBold)
			{
				out.insert(out.size() - 1, "**");
				inBold = !inBold;
			}
			if (fmt.anchorHref().isEmpty() && !currentLink.isNull())
			{
				out.insert(out.size() - 1, "](" + currentLink + ")");
			}
			else if (!fmt.anchorHref().isEmpty() && currentLink.isNull())
			{
				out.insert(out.size() - 1, "[");
				currentLink = fmt.anchorHref();
			}
			// FIXME images
			out.append(c);
		}
		return out;
	};
	for (QTextBlock block = source->begin(); block != source->end(); block = block.next())
	{
		// heading
		if (block.charFormat().toolTip() == block.text())
		{
			endCodeBlock();
			output.append(QString(sizeMap.key(block.charFormat().fontPointSize()), '#') + " " + block.text() + "\n");
		}
		else
		{
			// list
			if (QTextList *list = block.textList())
			{
				endCodeBlock();
				const QString indent = QString((list->format().indent()-1) * 2, ' ');
				if (list->format().style() == QTextListFormat::ListDisc)
				{
					output.append(indent + "* " + blockToMarkdown(block));
				}
				else
				{
					output.append(indent + QString::number(list->itemNumber(block) + 1) + ". " + blockToMarkdown(block));
				}
				wasInList = true;
			}
			else
			{
				if (wasInList)
				{
					output.append("");
					wasInList = false;
				}
				if (block.charFormat().fontFamily() == "Monospace")
				{
					if (!inCodeBlock)
					{
						inCodeBlock = true;
						output.insert(output.size() - 1, "```");
					}
					output.append(block.text().remove("\n"));
				}
				else
				{
					endCodeBlock();
					output.append(blockToMarkdown(block) + "\n");
				}
			}
		}
	}
	QString string = output.join("\n");
	return string.trimmed().toUtf8();
}
Exemplo n.º 29
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();
}
Exemplo n.º 30
0
void Console::applyFormatCode(QTextCursor& cur, unsigned int code)
{
    QTextCharFormat fmt = cur.charFormat();

    switch(code) {
    // reset format
    case 0: {
        cur.setCharFormat(QTextCharFormat()); return;
    }

    // font styles
    case 1: fmt.setFontWeight(QFont::Bold); break;
    case 2: fmt.setFontWeight(QFont::Light); break;
    case 3: fmt.setFontItalic(true); break;
    case 4: fmt.setFontUnderline(true); break;
    case 9: fmt.setFontStrikeOut(true); break;
    case 22: fmt.setFontWeight(QFont::Normal); break;
    case 23: fmt.setFontItalic(false); break;
    case 24: fmt.setFontUnderline(false); break;
    case 29: fmt.setFontStrikeOut(false); break;

    // low foreground color
    case 30:
    case 31:
    case 32:
    case 33:
    case 34:
    case 35:
    case 36:
    case 37:
       fmt.setForeground(ansiColorsDark[code-30]); break;

    // default foreground color
    case 39: fmt.setForeground(Qt::black); break;

    // low background color
    case 40:
    case 41:
    case 42:
    case 43:
    case 44:
    case 45:
    case 46:
    case 47:
        fmt.setBackground(ansiColorsNormal[code-40]); break;

    // default background color
    case 49: fmt.setBackground(Qt::white); break;

    // overline style
    case 53: fmt.setFontOverline(true); break;
    case 55: fmt.setFontOverline(false); break;

    // high foreground color
    case 90:
    case 91:
    case 92:
    case 93:
    case 94:
    case 95:
    case 96:
    case 97:
        fmt.setForeground(ansiColorsBright[code-90]); break;

    // high background color
    case 100:
    case 101:
    case 102:
    case 103:
    case 104:
    case 105:
    case 106:
    case 107:
        fmt.setBackground(ansiColorsBright[code-100]); break;

    default: return;
    }

    cur.setCharFormat(fmt);
}