qmlprinter.cpp 12.4 KB
Newer Older
1 2
#include "qmlprinter.h"

3
#include <QLoggingCategory>
Michael Winkelmann's avatar
Michael Winkelmann committed
4 5 6 7 8
#include <QAbstractTextDocumentLayout>
#include <QPainter>
#include <QPrinter>
#include <QQuickItem>
#include <QQuickWindow>
9
#include <QtMath>
10 11
#include <QQuickItemGrabResult>
#include <QGuiApplication>
12

13 14
Q_LOGGING_CATEGORY(lc, "qt.qmlprinter")

Michael Winkelmann's avatar
Michael Winkelmann committed
15
QmlPrinter::QmlPrinter() {}
16

17
QmlPrinter::~QmlPrinter() {}
18

Michael Winkelmann's avatar
Michael Winkelmann committed
19 20 21 22 23 24
void QmlPrinter::changePrinterOrientation(QPrinter &printer, const int &width,
                                          const int &height) {
  if (width > height)
    printer.setOrientation(QPrinter::Landscape);
  else
    printer.setOrientation(QPrinter::Portrait);
25
}
26

27 28 29
bool QmlPrinter::printPdf(const QString &location, QQuickItem *rootItem) {
  if (!rootItem) {
      return false;
Michael Winkelmann's avatar
Michael Winkelmann committed
30
  }
31

32 33
  auto width = rootItem->property("width").toInt();
  auto height = rootItem->property("height").toInt();
Michael Winkelmann's avatar
Michael Winkelmann committed
34

35
  QPrinter printer(QPrinter::HighResolution);
Michael Winkelmann's avatar
Michael Winkelmann committed
36 37 38 39
  printer.setOutputFormat(QPrinter::PdfFormat);
  printer.setOutputFileName(location);
  printer.setFullPage(true);
  printer.setPageLayout(QPageLayout(QPageSize(QSize(height, width)),
Michael Winkelmann's avatar
Michael Winkelmann committed
40
                                    QPageLayout::Landscape,
Michael Winkelmann's avatar
Michael Winkelmann committed
41
                                    QMarginsF(0, 0, 0, 0), QPageLayout::Pica));
42
  printer.setResolution(resolution());
Michael Winkelmann's avatar
Michael Winkelmann committed
43 44 45 46

  // Change the printer orientation based on the presentation
  // This needs to be called before the painting is started as it will only take
  // effect after newPage is called (painter.begin() calls this method)
47

Michael Winkelmann's avatar
Michael Winkelmann committed
48
  changePrinterOrientation(printer, width, height);
Michael Winkelmann's avatar
Michael Winkelmann committed
49
  SubItemStrategy strategy;
50 51 52

  ///@todo create other strategies for generating a PDF from a QuickItem,
  ///  e.g. by using
Michael Winkelmann's avatar
Michael Winkelmann committed
53
/*
54 55 56 57
  PrintStrategy strategy = [](QQuickItem* root, ItemList& items, ItemList& masterItems) {
      items.push_back({ root, QVariantMap() });
      return true;
  };
Michael Winkelmann's avatar
Michael Winkelmann committed
58
*/
59 60 61 62 63
  return printItems(printer,rootItem,strategy);
}

bool QmlPrinter::printItems(QPrinter& printer, ItemList const& items,
                            ItemList const& masterItems) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
64 65 66 67 68 69 70

  QPainter painter;
  // It's possible to fail here for example if the file location does not allow
  // writing
  if (!painter.begin(&printer)) {
    return false;
  }
71

72
  for (size_t i = 0; i < items.size(); ++i) {
73

74 75 76 77 78 79 80 81
      auto item = items.at(i).item;
      if (!item->property("noMaster").toBool()) {
           // Paint master slide elements
            for (auto &masterItem : masterItems) {
              masterItem.item->setProperty("slideNumber",int(i+1));
              paintItem(masterItem, &painter);
            }
      }
82

83 84
      // Paint current slide
      paintItem(items.at(i), &painter);
Michael Winkelmann's avatar
Michael Winkelmann committed
85

86 87 88 89
      // We need to lookahead so we can setup the printer orientation for the next
      // item and add a new page to the printer
      size_t next = i + 1;
      if (next < items.size()) {
Michael Winkelmann's avatar
Michael Winkelmann committed
90
      changePrinterOrientation(printer,
91 92
                               int(items.at(next).item->width()),
                               int(items.at(next).item->height()));
Michael Winkelmann's avatar
Michael Winkelmann committed
93
      printer.newPage();
94
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
95 96
  }
  return true;
97 98
}

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
bool QmlPrinter::printItems(QPrinter &printer, QQuickItem *rootItem, PrintStrategy strategy) const
{
  ItemList items, masterItems;
  if (!strategy(rootItem,items,masterItems)) {
    return false;
  }

  return printItems(printer,items,masterItems);

}

int QmlPrinter::resolution() const
{
    return m_options.count("resolution") ? m_options.value("resolution").toInt() : 72;
}

void QmlPrinter::setResolution(int resolution)
{
    m_options["resolution"] = resolution;
}

Michael Winkelmann's avatar
Michael Winkelmann committed
120
void QmlPrinter::paintItem(QQuickItem *item, QQuickWindow *window,
121
                           QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
122 123 124 125 126 127 128 129 130 131 132 133 134
  if (!item || !item->isVisible())
    return;

  bool drawChildren = true;

  painter->save();
  painter->setMatrix(transformMatrix(item));
  painter->setMatrixEnabled(true);
  if (item->clip()) {
    painter->setClipping(true);
    painter->setClipRect(item->clipRect());
  }

135

Michael Winkelmann's avatar
Michael Winkelmann committed
136 137 138 139 140 141 142 143 144 145
  // This is a bit special case as we need to use childItems instead of children
  if (inherits(item->metaObject(), "QQuickListView")) {
    drawChildren = false;
    QList<QQuickItem *> childItems = item->childItems();
    if (childItems.length() > 0) {
      // First item is the QML ListView
      QQuickItem *listView = childItems.at(0);
      if (listView != nullptr) {
        // Draw the child items of the QML ListView
        QList<QQuickItem *> listViewChildren = listView->childItems();
Michael Winkelmann's avatar
Michael Winkelmann committed
146
        for (QQuickItem *children : listViewChildren) {
Michael Winkelmann's avatar
Michael Winkelmann committed
147
          paintItem(children, window, painter);
148
        }
Michael Winkelmann's avatar
Michael Winkelmann committed
149 150 151 152 153 154 155 156 157 158 159 160 161
      }
    }
  } else if (item->flags().testFlag(QQuickItem::ItemHasContents)) {

    if (inherits(item->metaObject(), "QQuickRectangle")) {
      paintQQuickRectangle(item, painter);
    } else if (inherits(item->metaObject(), "QQuickText")) {
      paintQQuickText(item, painter);
    } else if (inherits(item->metaObject(), "QQuickImage")) {
      paintQQuickImage(item, painter);
    } else if (inherits(item->metaObject(), "QQuickCanvasItem")) {
      paintQQuickCanvasItem(item, window, painter);
    } else {
162

Michael Winkelmann's avatar
Michael Winkelmann committed
163
      // Fallback to screen capture if we are unable to parse the data
164
      QRectF rect(0,0,item->width(),item->height());
Michael Winkelmann's avatar
Michael Winkelmann committed
165
      if (window != nullptr) {
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        auto imageGrabResult = item->grabToImage(rect.size().toSize());

        bool ready = false;

        if (imageGrabResult) {
            QObject::connect( imageGrabResult.data(), &QQuickItemGrabResult::ready,
                              [&]() {
                painter->drawImage(rect, imageGrabResult->image(), rect);
                ready = true;
            });
        } else {
          ready = true;
        }

        while(!ready) { qGuiApp->processEvents(); }
Michael Winkelmann's avatar
Michael Winkelmann committed
181
      }
182
      drawChildren = false;
183
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
184
  }
185

Michael Winkelmann's avatar
Michael Winkelmann committed
186
  if (drawChildren) {
187

Michael Winkelmann's avatar
Michael Winkelmann committed
188 189 190 191
    auto items = item->childItems();
    std::sort(items.begin(), items.end(), [](QQuickItem *lhs, QQuickItem *rhs) {
      return lhs->z() < rhs->z();
    });
192

Michael Winkelmann's avatar
Michael Winkelmann committed
193 194 195
    for (auto item : items)
      paintItem(item, window, painter);
  }
196

Michael Winkelmann's avatar
Michael Winkelmann committed
197
  painter->restore();
198 199
}

200 201 202 203 204 205 206 207
void QmlPrinter::paintItem(const ItemWithProperties& item, QPainter *painter) const {
    auto& props = item.properties;
    for (const auto& key : props.keys()) {
        item.item->setProperty(key.toStdString().c_str(),props.value(key));
    }
    paintItem(item.item,item.item->window(),painter);
}

Michael Winkelmann's avatar
Michael Winkelmann committed
208
void QmlPrinter::paintQQuickCanvasItem(QQuickItem *item, QQuickWindow *window,
209
                                       QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
210 211 212
  // No point in continuing as we are unable to grab the image
  if (window == nullptr)
    return;
213

Michael Winkelmann's avatar
Michael Winkelmann committed
214 215 216
  const QRect rect(0, 0, int(item->width()), int(item->height()));
  QImage image = window->grabWindow();
  painter->drawImage(0, 0, image, 0, 0, rect.width(), rect.height());
217 218
}

219
void QmlPrinter::paintQQuickRectangle(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  const QRectF rect(0, 0, item->width(), item->height());

  const QColor color = item->property("color").value<QColor>();
  const QObject *border = item->property("border").value<QObject *>();
  const qreal borderWidth = border->property("width").value<qreal>();
  const QColor borderColor = border->property("color").value<QColor>();
  const qreal radius = item->property("radius").value<qreal>();
  const qreal opacity = item->property("opacity").value<qreal>();

  painter->setBrush(color);
  painter->setOpacity(opacity);

  if (borderWidth > 0.0 && !(borderWidth == 1.0 && borderColor == QColor(Qt::black))) {
    painter->setPen(QPen(borderColor, borderWidth));
  } else {
    painter->setPen(Qt::NoPen);
  }

  if (radius > 0.0) {
    painter->drawRoundedRect(rect, radius, radius);
  } else {
    painter->drawRect(rect);
  }
}
244

245
void QmlPrinter::paintQQuickText(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
  const QRectF rect(0, 0, item->width(), item->height());
  const QFont font = item->property("font").value<QFont>();
  const QString text = item->property("text").value<QString>();
  const QColor color = item->property("color").value<QColor>();
  const int wrapMode = item->property("wrapMode").value<int>();
  int textFormat = item->property("textFormat").value<int>();
  const int horizontalAlignment =
      item->property("horizontalAlignment").value<int>();
  const int verticalAlignment =
      item->property("verticalAlignment").value<int>();

  QTextOption textOption;
  textOption.setWrapMode(QTextOption::WrapMode(wrapMode));
  textOption.setAlignment(
      static_cast<Qt::Alignment>(horizontalAlignment | verticalAlignment));

  QFontMetrics fm(font);

  textFormat = Qt::RichText;
  if (textFormat == Qt::AutoText) {
    textFormat = Qt::mightBeRichText(text) ? 4 : Qt::PlainText;
  }

  QTextDocument document;
  document.setPageSize(item->size());
  document.setDocumentMargin(0.0);
  document.setUseDesignMetrics(true);
  document.setTextWidth(rect.width());
  document.setDefaultTextOption(textOption);
  document.setDefaultFont(font);

  if (textFormat == Qt::PlainText)
    document.setPlainText(text);
  else
    document.setHtml(text);

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

  QAbstractTextDocumentLayout *layout = document.documentLayout();
  painter->translate(rect.topLeft());
  painter->setRenderHint(QPainter::Antialiasing, true);
  layout->draw(painter, context);
}
290

291
void QmlPrinter::paintQQuickImage(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  const QUrl url = item->property("source").value<QUrl>();
  const int fillMode = item->property("fillMode").value<int>();

  QImage image(url.toLocalFile());

  QRectF rect(0, 0, item->width(), item->height());
  QRectF sourceRect(0, 0, image.width(), image.height());

  switch (fillMode) {
  default:
    qWarning() << "QuickItemPainter::paintQuickImage unimplemented fill mode: "
               << fillMode;
    break;
  case 0: // Image.Stretch
    break;
  case 1: { // Image.PreserveAspectFit
    QSizeF size = sourceRect.size();
    size.scale(rect.width(), rect.height(), Qt::KeepAspectRatio);
  } break;
  case 6: { // Image.Pad
    if (sourceRect.width() > rect.width()) {
      rect.setWidth(sourceRect.width());
    } else {
      sourceRect.setWidth(rect.width());
316
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
317 318 319 320 321 322 323 324
    if (sourceRect.height() > rect.height()) {
      rect.setHeight(sourceRect.height());
    } else {
      sourceRect.setHeight(rect.height());
    }
  } break;
  }
  painter->drawImage(rect, image, sourceRect);
325 326
}

Michael Winkelmann's avatar
Michael Winkelmann committed
327 328 329 330 331 332 333
bool QmlPrinter::inherits(const QMetaObject *metaObject, const QString &name) {
  if (metaObject->className() == name) {
    return true;
  } else if (metaObject->superClass()) {
    return inherits(metaObject->superClass(), name);
  }
  return false;
334 335
}

Michael Winkelmann's avatar
Michael Winkelmann committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
QMatrix QmlPrinter::transformMatrix(QQuickItem *item) {

  QTransform t;
  if (item->parentItem())
    t = QTransform(transformMatrix(item->parentItem()));

  t.translate(item->x(), item->y());

  auto transforms = item->transform();
  auto tCount = transforms.count(&transforms);

  if (!tCount) {
    QMatrix4x4 m(t);
    for (int ii = tCount - 1; ii >= 0; --ii)
      transforms.at(&transforms, ii)->applyTo(&m);
    t = m.toTransform();
  }

  auto computeTransformOrigin = [](QQuickItem *item) {
    switch (item->transformOrigin()) {
    case QQuickItem::TopLeft:
      return QPointF(0, 0);
    case QQuickItem::Top:
      return QPointF(item->width() / 2., 0);
    case QQuickItem::TopRight:
      return QPointF(item->width(), 0);
    case QQuickItem::Left:
      return QPointF(0, item->height() / 2.);
    case QQuickItem::Center:
      return QPointF(item->width() / 2., item->height() / 2.);
    case QQuickItem::Right:
      return QPointF(item->width(), item->height() / 2.);
    case QQuickItem::BottomLeft:
      return QPointF(0, item->height());
    case QQuickItem::Bottom:
      return QPointF(item->width() / 2., item->height());
    case QQuickItem::BottomRight:
      return QPointF(item->width(), item->height());
374
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
375 376 377 378 379 380 381 382 383 384 385 386
    return QPointF(0.0,0.0);
  };

  if (item->scale() != 1. || item->rotation() != 0.) {
    QPointF tp = computeTransformOrigin(item);
    t.translate(tp.x(), tp.y());
    t.scale(item->scale(), item->scale());
    t.rotate(item->rotation());
    t.translate(-tp.x(), -tp.y());
  }

  return t.toAffine();
387
}
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

bool SubItemStrategy::operator()(QQuickItem *rootItem, ItemList &items, ItemList &masterItems)
{
  rootItem->setProperty(
      "allowDelay",
      QVariant(false)); // Disable partial reveals on slide pages

  for (auto &item : rootItem->childItems()) {
    if (item->property("isMaster").toBool()) {
      masterItems.push_back({item, QVariantMap()});
    } else {
        if (item->metaObject()->className() != QStringLiteral("QQuickRepeater"))
            items.push_back({item, QVariantMap()});
    }
  }
  return !items.empty();
}