Exemple #1
0
    QwtRichTextDocument( const QString &text, int flags, const QFont &font )
    {
        setUndoRedoEnabled( false );
        setDefaultFont( font );
        setHtml( text );

        // make sure we have a document layout
        ( void )documentLayout();

        QTextOption option = defaultTextOption();
        if ( flags & Qt::TextWordWrap )
            option.setWrapMode( QTextOption::WordWrap );
        else
            option.setWrapMode( QTextOption::NoWrap );

        option.setAlignment( ( Qt::Alignment ) flags );
        setDefaultTextOption( option );

        QTextFrame *root = rootFrame();
        QTextFrameFormat fm = root->frameFormat();
        fm.setBorder( 0 );
        fm.setMargin( 0 );
        fm.setPadding( 0 );
        fm.setBottomMargin( 0 );
        fm.setLeftMargin( 0 );
        root->setFrameFormat( fm );

        adjustSize();
    }
Exemple #2
0
            text_writer( docEdit& e ) : edit( e ) {
                QTextCursor cursor = edit.textCursor();
                cursor.movePosition( QTextCursor::Start );
                mainFrame = cursor.currentFrame();

                plainFormat = cursor.charFormat();
                plainFormat.setFontPointSize( 10 );

                paragraphFormat = plainFormat;
                paragraphFormat.setFontPointSize( 12 );

                headingFormat = plainFormat;
                headingFormat.setFontWeight( QFont::Bold );
                headingFormat.setFontPointSize( 16 );

                empasisFormat = plainFormat;
                empasisFormat.setFontItalic( true );

                tagFormat = plainFormat;
                tagFormat.setForeground( QColor( "#990000" ) );
                tagFormat.setFontUnderline( true );
                
                underlineFormat = plainFormat;
                underlineFormat.setFontUnderline( true );

                frameFormat.setBorderStyle( QTextFrameFormat::BorderStyle_Inset );
                frameFormat.setBorder( 1 );
                frameFormat.setMargin( 10 );
                frameFormat.setPadding( 4 );
            }
Exemple #3
0
void QLabelPrivate::ensureTextLayouted() const
{
    if (!textLayoutDirty)
        return;
    ensureTextPopulated();
    if (control) {
        QTextDocument *doc = control->document();
        QTextOption opt = doc->defaultTextOption();

        opt.setAlignment(QFlag(this->align));

        if (this->align & Qt::TextWordWrap)
            opt.setWrapMode(QTextOption::WordWrap);
        else
            opt.setWrapMode(QTextOption::ManualWrap);

        doc->setDefaultTextOption(opt);

        QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        doc->rootFrame()->setFrameFormat(fmt);
        doc->setTextWidth(documentRect().width());
    }
    textLayoutDirty = false;
}
/*! Append a new message to the current session and scroll to the end of the message protocol and
    returns true if the action was successful. The \a messageColor defines the color of the message
    box and should be provided as a full-color (no dimming required) color, as it is automatically
    adjusted for the border and background.
*/
bool QwcPrivateMessager::appendMessageToCurrentSession(QTextDocument *document, const QString message, const QColor messageColor)
{
    if (!document) { return false; }

    QTextCursor cursor = document->rootFrame()->lastCursorPosition();
    cursor.movePosition(QTextCursor::StartOfBlock);

    QTextFrameFormat frameFormat;
    frameFormat.setPadding(4);
    frameFormat.setBackground(messageColor.lighter(190));
    frameFormat.setMargin(0);
    frameFormat.setBorder(2);
    frameFormat.setBorderBrush(messageColor.lighter(150));
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Outset);

    // Title
    QTextCharFormat backupCharFormat = cursor.charFormat();

    QTextCharFormat newCharFormat;
    newCharFormat.setFontPointSize(9);

    QTextBlockFormat headerFormat;
    headerFormat.setAlignment(Qt::AlignHCenter);
    cursor.insertBlock(headerFormat);
    cursor.setCharFormat(newCharFormat);
    cursor.insertText(QDateTime::currentDateTime().toString());

    QTextFrame *frame = cursor.insertFrame(frameFormat);
    cursor.setCharFormat(backupCharFormat);
    frame->firstCursorPosition().insertText(message);

    return true;
}
QTextFrame *QTextDocumentPrivate::rootFrame() const
{
    if (!rtFrame) {
        QTextFrameFormat defaultRootFrameFormat;
        defaultRootFrameFormat.setMargin(DefaultRootFrameMargin);
        rtFrame = qobject_cast<QTextFrame *>(const_cast<QTextDocumentPrivate *>(this)->createObject(defaultRootFrameFormat));
    }
    return rtFrame;
}
Exemple #6
0
 /*!
  * \author Anders Fernström
  * \date 2006-03-02
  *
  * \brief set the chapter counter
  */
 void InputCell::setChapterCounter( QString number )
 {
   chaptercounter_->selectAll();
   chaptercounter_->setPlainText( number );
   chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight );
   QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat();
   format.setMargin( style_.textFrameFormat()->margin() +
     style_.textFrameFormat()->border() +
     style_.textFrameFormat()->padding()  );
   chaptercounter_->document()->rootFrame()->setFrameFormat( format );
 }
Exemple #7
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 获取文档对象
    QTextDocument *document = ui->textEdit->document();

    // 获取根框架
    QTextFrame *rootFrame = document->rootFrame();

    // 创建框架格式
    QTextFrameFormat format;
    // 边界颜色
    format.setBorderBrush(Qt::red);
    // 边界宽度
    format.setBorder(3);
    // 框架使用格式
    rootFrame->setFrameFormat(format);

    QTextFrameFormat frameFormat;
    // 设置背景颜色
    frameFormat.setBackground(Qt::lightGray);
    // 设置边距
    frameFormat.setMargin(10);
    // 设置填衬
    frameFormat.setPadding(5);
    frameFormat.setBorder(2);
    frameFormat.setBorderStyle(QTextFrameFormat::BorderStyle_Dotted); //设置边框样式

    // 获取光标
    QTextCursor cursor = ui->textEdit->textCursor();
    // 在光标处插入框架
    cursor.insertFrame(frameFormat);

   //以下是5.2.2节内容
    QAction *action_textFrame = new QAction(tr("框架"),this);
    connect(action_textFrame,SIGNAL(triggered()),this,SLOT(showTextFrame()));
    // 在工具栏添加动作
    ui->mainToolBar->addAction(action_textFrame);

    QAction *action_textBlock = new QAction(tr("文本块"),this);
    connect(action_textBlock,SIGNAL(triggered()),this,SLOT(showTextBlock()));
    ui->mainToolBar->addAction(action_textBlock);

    QAction *action_font = new QAction(tr("字体"),this);
    // 设置动作可以被选中
    action_font->setCheckable(true);
    connect(action_font,SIGNAL(toggled(bool)),this,SLOT(setTextFont(bool)));
    ui->mainToolBar->addAction(action_font);
}
Exemple #8
0
QTextDocument* Converter::convert( const QString &fileName )
{
    Document *textDocument = new Document( fileName );

    textDocument->setPageSize(QSizeF( 600, 800 ));

    QTextFrameFormat frameFormat;
    frameFormat.setMargin( 20 );

    QTextFrame *rootFrame = textDocument->rootFrame();
    rootFrame->setFrameFormat( frameFormat );

    emit addMetaData( Okular::DocumentInfo::MimeType, "text/plain" );

    return textDocument;
}
Exemple #9
0
/*
QSize PsiTipLabel::sizeForWidth(int w) const
{
    QRect br;

    int hextra = 2 * margin;
    int vextra = hextra;

    if (isRichText) {
        hextra = 1;
        vextra = 1;
    }

    PsiRichText::ensureTextLayouted(doc, w);
    const qreal oldTextWidth = doc->textWidth();

    doc->adjustSize();
    br = QRect(QPoint(0, 0), doc->size().toSize());
    doc->setTextWidth(oldTextWidth);

    QFontMetrics fm(font());
    QSize extra(hextra + 1, vextra);

    // Make it look good with the default ToolTip font on Mac, which has a small descent.
    if (fm.descent() == 2 && fm.ascent() >= 11)
        vextra++;

    const QSize contentsSize(br.width() + hextra, br.height() + vextra);
    return contentsSize;
}
*/
QSize PsiTipLabel::sizeHint() const
{
    QTextFrameFormat fmt = doc->rootFrame()->frameFormat();
    fmt.setMargin(0);
    doc->rootFrame()->setFrameFormat(fmt);
    // PsiRichText::ensureTextLayouted(doc, -1);

    doc->adjustSize();
    // br = QRect(QPoint(0, 0), doc->size().toSize());
    // this way helps to fight empty space on the right:
    QSize docSize = QSize(static_cast<int>(doc->idealWidth()), doc->size().toSize().height());

    QFontMetrics fm(font());
    QSize extra(2*margin + 2, 2*margin + 1);    // "+" for tip's frame
    // Make it look good with the default ToolTip font on Mac, which has a small descent.
    if (fm.descent() == 2 && fm.ascent() >= 11)
        ++extra.rheight();

    return docSize + extra;
}
  /*!
     * \class TextCursorChangeMargin
   * \author Anders Fernström
   * \date 2005-11-03
   * \date 2005-11-07 (update)
     *
     * \brief Command for changing margin
   *
   * 2005-11-07 AF, implemented the function
     */
  void TextCursorChangeMargin::execute()
  {
    QTextEdit *editor = document()->getCursor()->currentCell()->textEdit();

    if( editor )
    {
      QTextFrameFormat format = editor->document()->rootFrame()->frameFormat();
      format.setMargin( margin_ );
      editor->document()->rootFrame()->setFrameFormat( format );

      // create a rule for the margin
      QString ruleValue;
      ruleValue.setNum( margin_ );
      Rule *rule = new Rule( "OMNotebook_Margin", ruleValue );
      document()->getCursor()->currentCell()->addRule( rule );

      // update the cells style
      document()->getCursor()->currentCell()->style()->textFrameFormat()->setMargin( margin_ );
    }
  }
Exemple #11
0
  /*!
   * \author Anders Fernström
   * \date 2005-10-27
   * \date 2006-03-02 (update)
   *
   * \brief Set cell style
   *
   * IMPORTANT: User shouldn't be able to change style on inputcells
   * so this function always use "Input" as style.
   *
   * 2005-11-03 AF, updated so the text is selected when the style
   * is changed, after the text is unselected.
   * 2006-03-02 AF, set chapter style
   *
   * \param style The cell style that is to be applyed to the cell
   */
  void InputCell::setStyle(CellStyle style)
  {
    if( style.name() == "Input" )
    {
      Cell::setStyle( style );

      // select all the text
      input_->selectAll();

      // set the new style settings
      input_->setAlignment( (Qt::AlignmentFlag)style_.alignment() );
      input_->mergeCurrentCharFormat( (*style_.textCharFormat()) );
      input_->document()->rootFrame()->setFrameFormat( (*style_.textFrameFormat()) );

      // unselect the text
      QTextCursor cursor(  input_->textCursor() );
      cursor.clearSelection();
      input_->setTextCursor( cursor );

      // 2006-03-02 AF, set chapter counter style
      chaptercounter_->selectAll();
      chaptercounter_->mergeCurrentCharFormat( (*style_.textCharFormat()) );

      QTextFrameFormat format = chaptercounter_->document()->rootFrame()->frameFormat();
      format.setMargin( style_.textFrameFormat()->margin() +
      style_.textFrameFormat()->border() +
      style_.textFrameFormat()->padding()  );
      chaptercounter_->document()->rootFrame()->setFrameFormat( format );

      chaptercounter_->setAlignment( (Qt::AlignmentFlag)Qt::AlignRight );

      cursor = chaptercounter_->textCursor();
      cursor.clearSelection();
      chaptercounter_->setTextCursor( cursor );
    }
    else
    {
      setStyle( "Input" );
    }
  }
Exemple #12
0
QTextDocument* Converter::convert( const QString &fileName )
{
  MobiDocument* newDocument=new MobiDocument(fileName);
  if (!newDocument->mobi()->isValid()) {
    emit error(i18n("Error while opening the Mobipocket document."), -1);
    delete newDocument;
    return NULL;
  }
  if (newDocument->mobi()->hasDRM()) {
    emit error(i18n("This book is protected by DRM and can be displayed only on designated device"), -1);
    delete newDocument;
    return NULL;
  }
  
  handleMetadata(newDocument->mobi()->metadata());
  newDocument->setPageSize(QSizeF(600, 800));

  QTextFrameFormat frameFormat;
  frameFormat.setMargin( 20 );
  QTextFrame *rootFrame = newDocument->rootFrame();
  rootFrame->setFrameFormat( frameFormat ); 
  QMap<QString,QPair<int,int> > links;
  QMap<QString,QTextBlock> targets;

  // go over whole document and add all <a> tags to links or targets map
  for (QTextBlock it = newDocument->begin(); it != newDocument->end(); it = it.next()) 
   for (QTextBlock::iterator fit=it.begin(); !fit.atEnd(); ++fit) {
    QTextFragment frag=fit.fragment();
    QTextCharFormat format=frag.charFormat();
    if (!format.isAnchor()) continue;
    //link
    if (!format.anchorHref().isEmpty()) links[format.anchorHref()]=
      QPair<int,int>(frag.position(), frag.position()+frag.length());
    if (!format.anchorNames().isEmpty()) {
      // link targets
      Q_FOREACH(const QString& name, format.anchorNames()) 
	targets['#'+name]=it;
    }
  }
Exemple #13
0
QTextDocument *TalkablePainter::createDescriptionDocument(const QString &text, int width, QColor color) const
{
    QString description = Qt::escape(text).replace(
        '\n', Configuration->showMultiLineDescription() ? QStringLiteral("<br/>") : QStringLiteral(" "));

    QTextDocument *const doc = new QTextDocument();

    doc->setDefaultFont(Configuration->descriptionFont());
    if (color.isValid())
        doc->setDefaultStyleSheet(QString("* { color: %1; }").arg(color.name()));

    doc->setHtml(QString("<span>%1</span>").arg(description));

    QTextOption opt = doc->defaultTextOption();
    opt.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    doc->setDefaultTextOption(opt);

    QTextFrameFormat frameFormat = doc->rootFrame()->frameFormat();
    frameFormat.setMargin(0);
    doc->rootFrame()->setFrameFormat(frameFormat);

    doc->setTextWidth(width);
    return doc;
}
Exemple #14
0
void TextPrinter::print(QPrinter *printer)
{
    if (!printer || !tempdoc_) return;

    tempdoc_->setUseDesignMetrics(true);
    tempdoc_->documentLayout()->setPaintDevice(printer);
    tempdoc_->setPageSize(contentRect(printer).size());
    // dump existing margin (if any)
    QTextFrameFormat fmt = tempdoc_->rootFrame()->frameFormat();
    fmt.setMargin(0);
    tempdoc_->rootFrame()->setFrameFormat(fmt);

    // to iterate through pages we have to worry about
    // copies, collation, page range, and print order

    // get num copies
    int doccopies;
    int pagecopies;
    if (printer->collateCopies()) {
        doccopies = 1;
        pagecopies = printer->numCopies();
    } else {
        doccopies = printer->numCopies();
        pagecopies = 1;
    }

    // get page range
    int firstpage = printer->fromPage();
    int lastpage = printer->toPage();
    if (firstpage == 0 && lastpage == 0) { // all pages
        firstpage = 1;
        lastpage = tempdoc_->pageCount();
    }

    // print order
    bool ascending = true;
    if (printer->pageOrder() == QPrinter::LastPageFirst) {
        int tmp = firstpage;
        firstpage = lastpage;
        lastpage = tmp;
        ascending = false;
    }

    // loop through and print pages
    QPainter painter(printer);
    painter.setRenderHints(QPainter::Antialiasing |
                           QPainter::TextAntialiasing |
                           QPainter::SmoothPixmapTransform, true);
    for (int dc=0; dc<doccopies; dc++) {
        int pagenum = firstpage;
        while (true) {
            for (int pc=0; pc<pagecopies; pc++) {
                if (printer->printerState() == QPrinter::Aborted ||
                    printer->printerState() == QPrinter::Error) {
                    return;
                }
                // print page
                paintPage(&painter, tempdoc_, pagenum);
                if (pc < pagecopies-1) printer->newPage();
            }
            if (pagenum == lastpage) break;
            if (ascending) pagenum++;
            else           pagenum--;
            printer->newPage();
        }

        if (dc < doccopies-1) printer->newPage();
    }
}
void RichTextDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption(&opt, index);

    if (!opt.text.contains(QLatin1Char('<'))) {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();

    QString text = opt.text;
    opt.text.clear();
    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, opt.widget);

    QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, opt.widget);

    QString key = QLatin1String("RichTextDelegate-") + text;
    QPixmap pm;
    if (!QPixmapCache::find(key, &pm)) {
        m_doc->setDefaultFont(opt.font);

        QTextOption textOpt = m_doc->defaultTextOption();
        textOpt.setAlignment(QStyle::visualAlignment(opt.direction, opt.displayAlignment));
        bool wrapText = opt.features & QStyleOptionViewItemV2::WrapText;
        textOpt.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);
        textOpt.setTextDirection(opt.direction);
        m_doc->setDefaultTextOption(textOpt);

        QTextFrameFormat fmt = m_doc->rootFrame()->frameFormat();
        fmt.setMargin(0);
        m_doc->rootFrame()->setFrameFormat(fmt);

        m_doc->setTextWidth(textRect.width());
        m_doc->setHtml(text);

        QAbstractTextDocumentLayout::PaintContext context;
        context.palette = opt.palette;
        context.palette.setColor(QPalette::Text, context.palette.light().color());

        pm = QPixmap(m_doc->size().width(), m_doc->size().height());
        pm.fill(Qt::transparent);
        QPainter pmPainter(&pm);
        m_doc->documentLayout()->draw(&pmPainter, context);

        QPixmapCache::insert(key, pm);
    }

    int hDelta = textRect.width() - pm.width();
    int vDelta = textRect.height() - pm.height();
    int x = textRect.left();
    int y = textRect.top();

    if (opt.displayAlignment & Qt::AlignVCenter)
        y += vDelta / 2;
    else if (opt.displayAlignment & Qt::AlignBottom)
        y += vDelta;

    if (opt.displayAlignment & Qt::AlignHCenter)
        x += hDelta / 2;
    else if (opt.displayAlignment & Qt::AlignRight)
        x += hDelta;

    painter->drawPixmap(x, y, pm);
}
MainWindow::MainWindow()
{
    QMenu *fileMenu = new QMenu(tr("&File"));

    QAction *saveAction = fileMenu->addAction(tr("&Save..."));
    saveAction->setShortcut(tr("Ctrl+S"));

    QAction *quitAction = fileMenu->addAction(tr("E&xit"));
    quitAction->setShortcut(tr("Ctrl+Q"));

    menuBar()->addMenu(fileMenu);
    editor = new QTextEdit();

    QTextCursor cursor(editor->textCursor());
    cursor.movePosition(QTextCursor::Start); 

    QTextFrame *mainFrame = cursor.currentFrame();
    
    QTextCharFormat plainCharFormat;
    QTextCharFormat boldCharFormat;
    boldCharFormat.setFontWeight(QFont::Bold);
/*  main frame
//! [0]
    QTextFrame *mainFrame = cursor.currentFrame();
    cursor.insertText(...);
//! [0]
*/
    cursor.insertText("Text documents are represented by the "
                      "QTextDocument class, rather than by QString objects. "
                      "Each QTextDocument object contains information about "
                      "the document's internal representation, its structure, "
                      "and keeps track of modifications to provide undo/redo "
                      "facilities. This approach allows features such as the "
                      "layout management to be delegated to specialized "
                      "classes, but also provides a focus for the framework.",
                      plainCharFormat);

//! [1]
    QTextFrameFormat frameFormat;
    frameFormat.setMargin(32);
    frameFormat.setPadding(8);
    frameFormat.setBorder(4);
//! [1]
    cursor.insertFrame(frameFormat);

/*  insert frame
//! [2]
    cursor.insertFrame(frameFormat);
    cursor.insertText(...);
//! [2]
*/
    cursor.insertText("Documents are either converted from external sources "
                      "or created from scratch using Qt. The creation process "
                      "can done by an editor widget, such as QTextEdit, or by "
                      "explicit calls to the Scribe API.", boldCharFormat);

    cursor = mainFrame->lastCursorPosition();
/*  last cursor
//! [3]
    cursor = mainFrame->lastCursorPosition();
    cursor.insertText(...);
//! [3]
*/
    cursor.insertText("There are two complementary ways to visualize the "
                      "contents of a document: as a linear buffer that is "
                      "used by editors to modify the contents, and as an "
                      "object hierarchy containing structural information "
                      "that is useful to layout engines. In the hierarchical "
                      "model, the objects generally correspond to visual "
                      "elements such as frames, tables, and lists. At a lower "
                      "level, these elements describe properties such as the "
                      "style of text used and its alignment. The linear "
                      "representation of the document is used for editing and "
                      "manipulation of the document's contents.",
                      plainCharFormat);


    connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile()));
    connect(quitAction, SIGNAL(triggered()), this, SLOT(close()));

    setCentralWidget(editor);
    setWindowTitle(tr("Text Document Frames"));
}
Exemple #17
0
bool Converter::convertTable( const QDomElement &element )
{
  /**
   * Find out dimension of the table
   */
  int rowCounter = 0;
  int columnCounter = 0;

  QQueue<QDomNode> nodeQueue;
  enqueueNodeList( nodeQueue, element.childNodes() );
  while ( !nodeQueue.isEmpty() ) {
    QDomElement el = nodeQueue.dequeue().toElement();
    if ( el.isNull() )
      continue;

    if ( el.tagName() == QLatin1String( "table-row" ) ) {
      rowCounter++;

      int counter = 0;
      QDomElement columnElement = el.firstChildElement();
      while ( !columnElement.isNull() ) {
        if ( columnElement.tagName() == QLatin1String( "table-cell" ) ) {
          counter++;
        }
        columnElement = columnElement.nextSiblingElement();
      }

      columnCounter = qMax( columnCounter, counter );
    } else if ( el.tagName() == QLatin1String( "table-header-rows" ) ) {
      enqueueNodeList( nodeQueue, el.childNodes() );
    }
  }

  /**
   * Create table
   */
  QTextTable *table = mCursor->insertTable( rowCounter, columnCounter );
  mCursor->movePosition( QTextCursor::End );

  /**
   * Fill table
   */
  nodeQueue.clear();
  enqueueNodeList( nodeQueue, element.childNodes() );

  QTextTableFormat tableFormat;

  rowCounter = 0;
  while ( !nodeQueue.isEmpty() ) {
    QDomElement el = nodeQueue.dequeue().toElement();
    if ( el.isNull() )
      continue;

    if ( el.tagName() == QLatin1String( "table-row" ) ) {

      int columnCounter = 0;
      QDomElement columnElement = el.firstChildElement();
      while ( !columnElement.isNull() ) {
        if ( columnElement.tagName() == QLatin1String( "table-cell" ) ) {
          const StyleFormatProperty property = mStyleInformation->styleProperty( columnElement.attribute( QStringLiteral("style-name") ) );

          QTextBlockFormat format;
          property.applyTableCell( &format );

          QDomElement paragraphElement = columnElement.firstChildElement();
          while ( !paragraphElement.isNull() ) {
            if ( paragraphElement.tagName() == QLatin1String( "p" ) ) {
              QTextTableCell cell = table->cellAt( rowCounter, columnCounter );
              // Insert a frame into the cell and work on that, so we can handle
              // different parts of the cell having different block formatting
              QTextCursor cellCursor = cell.lastCursorPosition();
              QTextFrameFormat frameFormat;
              frameFormat.setMargin( 1 ); // TODO: this shouldn't be hard coded
              QTextFrame *frame = cellCursor.insertFrame( frameFormat );
              QTextCursor frameCursor = frame->firstCursorPosition();
              frameCursor.setBlockFormat( format );

              if ( !convertParagraph( &frameCursor, paragraphElement, format ) )
                return false;
            } else if ( paragraphElement.tagName() == QLatin1String( "list" ) ) {
              QTextTableCell cell = table->cellAt( rowCounter, columnCounter );
              // insert a list into the cell
              QTextCursor cellCursor = cell.lastCursorPosition();
              if ( !convertList( &cellCursor, paragraphElement ) ) {
                return false;
              }
            }

            paragraphElement = paragraphElement.nextSiblingElement();
          }
          columnCounter++;
        }
        columnElement = columnElement.nextSiblingElement();
      }

      rowCounter++;
    } else if ( el.tagName() == QLatin1String( "table-column" ) ) {
      const StyleFormatProperty property = mStyleInformation->styleProperty( el.attribute( QStringLiteral("style-name") ) );
      const QString tableColumnNumColumnsRepeated = el.attribute( QStringLiteral("number-columns-repeated"), QStringLiteral("1") );
      int numColumnsToApplyTo = tableColumnNumColumnsRepeated.toInt();
      for (int i = 0; i < numColumnsToApplyTo; ++i) {
        property.applyTableColumn( &tableFormat );
      }
    }
  }

  table->setFormat( tableFormat );

  return true;
}
Exemple #18
0
Okular::Document::OpenResult Converter::convertWithPassword( const QString &fileName, const QString &password )
{
  Document oooDocument( fileName );
  if ( !oooDocument.open( password ) ) {
    if ( !oooDocument.anyFileEncrypted() )
        emit error( oooDocument.lastErrorString(), -1 );
    return oooDocument.anyFileEncrypted() ? Okular::Document::OpenNeedsPassword : Okular::Document::OpenError;
  }

  mTextDocument = new QTextDocument;
  mCursor = new QTextCursor( mTextDocument );

  /**
   * Create the dom of the content
   */
  QXmlSimpleReader reader;

  QXmlInputSource source;
  source.setData( oooDocument.content() );

  QString errorMsg;
  QDomDocument document;
  if ( !document.setContent( &source, &reader, &errorMsg ) ) {
    if ( !oooDocument.anyFileEncrypted() )
      emit error( i18n( "Invalid XML document: %1", errorMsg ), -1 );
    delete mCursor;
    return oooDocument.anyFileEncrypted() ? Okular::Document::OpenNeedsPassword : Okular::Document::OpenError;
  }

  mStyleInformation = new StyleInformation();

  /**
   * Read the style properties, so the are available when
   * parsing the content.
   */
  StyleParser styleParser( &oooDocument, document, mStyleInformation );
  if ( !styleParser.parse() ) {
    if ( !oooDocument.anyFileEncrypted() )
      emit error( i18n( "Unable to read style information" ), -1 );
    delete mCursor;
    return oooDocument.anyFileEncrypted() ? Okular::Document::OpenNeedsPassword : Okular::Document::OpenError;
  }

  /**
   * Add all images of the document to resource framework
   */
  const QMap<QString, QByteArray> images = oooDocument.images();
  QMapIterator<QString, QByteArray> it( images );
  while ( it.hasNext() ) {
    it.next();

    mTextDocument->addResource( QTextDocument::ImageResource, QUrl( it.key() ), QImage::fromData( it.value() ) );
  }

  /**
   * Set the correct page size
   */
  const QString masterLayout = mStyleInformation->masterPageName();
  const PageFormatProperty property = mStyleInformation->pageProperty( masterLayout );

  const QSizeF dpi = Okular::Utils::realDpi(nullptr);
  int pageWidth = qRound(property.width() / 72.0 * dpi.width());
  int pageHeight = qRound(property.height() / 72.0 * dpi.height());

  if ( pageWidth == 0 )
      pageWidth = 600;
  if ( pageHeight == 0 )
      pageHeight = 800;

  mTextDocument->setPageSize( QSize( pageWidth, pageHeight ) );

  QTextFrameFormat frameFormat;
  frameFormat.setMargin( qRound( property.margin() ) );

  QTextFrame *rootFrame = mTextDocument->rootFrame();
  rootFrame->setFrameFormat( frameFormat );

  /**
   * Parse the content of the document
   */
  const QDomElement documentElement = document.documentElement();

  QDomElement element = documentElement.firstChildElement();
  while ( !element.isNull() ) {
    if ( element.tagName() == QLatin1String( "body" ) ) {
      if ( !convertBody( element ) ) {
        if ( !oooDocument.anyFileEncrypted() )
          emit error( i18n( "Unable to convert document content" ), -1 );
        delete mCursor;
        return oooDocument.anyFileEncrypted() ? Okular::Document::OpenNeedsPassword : Okular::Document::OpenError;
      }
    }

    element = element.nextSiblingElement();
  }

  MetaInformation::List metaInformation = mStyleInformation->metaInformation();
  for ( int i = 0; i < metaInformation.count(); ++i ) {
    emit addMetaData( metaInformation[ i ].key(),
                      metaInformation[ i ].value(),
                      metaInformation[ i ].title() );
  }

  delete mCursor;
  delete mStyleInformation;
  mStyleInformation = 0;

  setDocument( mTextDocument );
  return Okular::Document::OpenSuccess;
}
Exemple #19
0
XmlConsole::XmlConsole(Client* client, QWidget *parent) :
	QWidget(parent),
	m_ui(new Ui::XmlConsole),
	m_client(client),	m_filter(0x1f)
{
	m_ui->setupUi(this);

    m_client->addXmlStreamHandler(this);

	QPalette pal = palette();
	pal.setColor(QPalette::Base, Qt::black);
	pal.setColor(QPalette::Text, Qt::white);
	m_ui->xmlBrowser->viewport()->setPalette(pal);
	QTextDocument *doc = m_ui->xmlBrowser->document();
	doc->setDocumentLayout(new QPlainTextDocumentLayout(doc));
	doc->clear();

	QTextFrameFormat format = doc->rootFrame()->frameFormat();
	format.setBackground(QColor(Qt::black));
	format.setMargin(0);
	doc->rootFrame()->setFrameFormat(format);
	QMenu *menu = new QMenu(m_ui->filterButton);
	menu->setSeparatorsCollapsible(false);
	menu->addSeparator()->setText(tr("Filter"));
	QActionGroup *group = new QActionGroup(menu);
	QAction *disabled = group->addAction(menu->addAction(tr("Disabled")));
	disabled->setCheckable(true);
	disabled->setData(Disabled);
	QAction *jid = group->addAction(menu->addAction(tr("By JID")));
	jid->setCheckable(true);
	jid->setData(ByJid);
	QAction *xmlns = group->addAction(menu->addAction(tr("By namespace uri")));
	xmlns->setCheckable(true);
	xmlns->setData(ByXmlns);
	QAction *attrb = group->addAction(menu->addAction(tr("By all attributes")));
	attrb->setCheckable(true);
	attrb->setData(ByAllAttributes);
	disabled->setChecked(true);
	connect(group, SIGNAL(triggered(QAction*)), this, SLOT(onActionGroupTriggered(QAction*)));
	menu->addSeparator()->setText(tr("Visible stanzas"));
	group = new QActionGroup(menu);
	group->setExclusive(false);
	QAction *iq = group->addAction(menu->addAction(tr("Information query")));
	iq->setCheckable(true);
	iq->setData(XmlNode::Iq);
	iq->setChecked(true);
	QAction *message = group->addAction(menu->addAction(tr("Message")));
	message->setCheckable(true);
	message->setData(XmlNode::Message);
	message->setChecked(true);
	QAction *presence = group->addAction(menu->addAction(tr("Presence")));
	presence->setCheckable(true);
	presence->setData(XmlNode::Presence);
	presence->setChecked(true);
	QAction *custom = group->addAction(menu->addAction(tr("Custom")));
	custom->setCheckable(true);
	custom->setData(XmlNode::Custom);
	custom->setChecked(true);
	connect(group, SIGNAL(triggered(QAction*)), this, SLOT(onActionGroupTriggered(QAction*)));
	m_ui->filterButton->setMenu(menu);
	m_stackBracketsColor = QColor(0x666666);
	m_stackIncoming.bodyColor = QColor(0xbb66bb);
	m_stackIncoming.tagColor = QColor(0x006666);
	m_stackIncoming.attributeColor = QColor(0x009933);
	m_stackIncoming.paramColor = QColor(0xcc0000);
	m_stackOutgoing.bodyColor = QColor(0x999999);
	m_stackOutgoing.tagColor = QColor(0x22aa22);
	m_stackOutgoing.attributeColor = QColor(0xffff33);
	m_stackOutgoing.paramColor = QColor(0xdd8811);

	QAction *action = new QAction(tr("Close"),this);
	action->setSoftKeyRole(QAction::NegativeSoftKey);
	connect(action, SIGNAL(triggered()), SLOT(close()));
	addAction(action);
}
Exemple #20
0
void DTipDialog::setupGUI()
{
    setWindowTitle(tr("Tip of day"));

    int h,s,v;
    QColor baseColor = palette().base().color();
    baseColor.getHsv(&h,&s,&v);
    baseColor.setHsv(h, int(s*(71/76.0)), int(v*(67/93.0)));
// 	baseColor.setHsv(h, int(s*(10/6.0)), int(v*(93/99.0)));

    QVBoxLayout *layout = new QVBoxLayout(this);

    m_textArea = new QTextBrowser;

    QTextFrameFormat format = m_textArea->document()->rootFrame()->frameFormat();
    format.setMargin(15);
    format.setBorder(5);
    m_textArea->document()->rootFrame()->setFrameFormat(format);

    m_textArea->setWordWrapMode( QTextOption::WrapAtWordBoundaryOrAnywhere );
    m_textArea->setFrameStyle(QFrame::NoFrame | QFrame::Plain);
    m_textArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );

    QPalette pal = m_textArea->palette();

    pal.setBrush(QPalette::Base, baseColor);

    m_textArea->setPalette(pal);

    layout->addWidget(m_textArea);

    layout->addWidget(new KSeparator);

    QHBoxLayout *buttonLayout = new QHBoxLayout;

    m_showOnStart = new QCheckBox(tr("show on start"));
    buttonLayout->addWidget(m_showOnStart);
    connect(m_showOnStart, SIGNAL(clicked()), this, SLOT(setShowOnStart()));

    buttonLayout->addStretch(1);

    QPushButton *prevTip = new QPushButton(tr("Previous tip"));
    buttonLayout->addWidget(prevTip);
    connect(prevTip, SIGNAL(clicked()), this, SLOT(showPrevTip()));

    QPushButton *nextTip = new QPushButton(tr("Next tip"));
    buttonLayout->addWidget(nextTip);
    connect(nextTip, SIGNAL(clicked()), this, SLOT(showNextTip()));

    QPushButton *close = new QPushButton(tr("close"));
    buttonLayout->addWidget(close);
    connect(close, SIGNAL(clicked()), this, SLOT(accept()));


    layout->addLayout(buttonLayout);

    setAttribute(Qt::WA_DeleteOnClose, true);

    DCONFIG->beginGroup("TipOfDay");
    m_showOnStart->setChecked(qvariant_cast<bool>(DCONFIG->value("ShowOnStart", true ) ));

    showNextTip();
}
Exemple #21
0
QTextDocument* Converter::convert(const QString &fileName)
{
    firstTime = true;
    Document oooDocument(fileName);
    if (!oooDocument.open())
    {
        return 0;
    }
    m_TextDocument = new QTextDocument;
    m_Cursor = new QTextCursor(m_TextDocument);

    /**
     * Create the dom of the content
     */
    QXmlSimpleReader reader;

    QXmlInputSource source;
    source.setData(oooDocument.content());
    QString errorMsg;
    QDomDocument document;
    if (!document.setContent(&source, &reader, &errorMsg))
    {
        setError(QString("Invalid XML document: %1").arg(errorMsg), -1);
        delete m_Cursor;
        return m_TextDocument;
    }

    /**
     * Read the style properties, so the are available when
     * parsing the content.
     */

    m_StyleInformation = new StyleInformation();

    if (oooDocument.content().size() == 0)
    {
        setError("Empty document", -1);
    }

    StyleParser styleParser(&oooDocument, document, m_StyleInformation);
    if (!styleParser.parse())
    {
        setError("Unable to read style information", -1);
        delete m_Cursor;
        return 0;
    }

    /**
    * Add all images of the document to resource framework
    */

    QMap<QString, QByteArray> imageLIST = oooDocument.images();
    QMapIterator<QString, QByteArray> it(imageLIST);
    while (it.hasNext())
    {
        it.next();
        m_TextDocument->addResource(QTextDocument::ImageResource, QUrl(it.key()), QImage::fromData(it.value()));
    }

    /**
     * Set the correct page size
     */

    const QString masterLayout = m_StyleInformation->masterPageName();

    if (m_StyleInformation->pagePropertyExists(masterLayout))
    {
        const int DPX = 231; /// im.logicalDpiX(); // 231
        const int DPY = 231; // im.logicalDpiY(); // 231
        const int A4Width = MM_TO_POINT(210); /// A4 210 x297 mm
        const int A4Height = MM_TO_POINT(297);

        const PageFormatProperty property = m_StyleInformation->pageProperty(masterLayout);
        int pageWidth = qRound(property.width() / 72.0 * DPX);
        if (pageWidth < 1) {
            pageWidth = A4Width;
        }
        int pageHeight = qRound(property.height() / 72.0 * DPY);
        if (pageHeight < 1) {
            pageHeight = A4Height;
        }
        m_TextDocument->setPageSize(QSize(pageWidth, pageHeight));

        QTextFrameFormat frameFormat;
        frameFormat.setMargin(qRound(property.margin()));

        QTextFrame *rootFrame = m_TextDocument->rootFrame();
        rootFrame->setFrameFormat(frameFormat);
    }

    /**
     * Parse the content of the document
     */
    const QDomElement documentElement = document.documentElement();

    QDomElement element = documentElement.firstChildElement();
    while (!element.isNull())
    {
        if (element.tagName() == QLatin1String("body"))
        {
            if (!convertBody(element))
            {
                setError("Unable to convert document content", -1);
                delete m_Cursor;
                return 0;
            }
        }

        element = element.nextSiblingElement();
    }

    return m_TextDocument;
}