qmlprinter.cpp 12.7 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 50
  SubItemStrategy strategy;
/*
51 52 53 54
  PrintStrategy strategy = [](QQuickItem* root, ItemList& items, ItemList& masterItems) {
      items.push_back({ root, QVariantMap() });
      return true;
  };
Michael Winkelmann's avatar
Michael Winkelmann committed
55
*/
56 57 58 59 60
  return printItems(printer,rootItem,strategy);
}

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

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

69
  for (size_t i = 0; i < items.size(); ++i) {
70

71 72 73 74 75 76 77 78
      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);
            }
      }
79

80 81
      // Paint current slide
      paintItem(items.at(i), &painter);
Michael Winkelmann's avatar
Michael Winkelmann committed
82

83 84 85 86
      // 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
87
      changePrinterOrientation(printer,
88 89
                               int(items.at(next).item->width()),
                               int(items.at(next).item->height()));
Michael Winkelmann's avatar
Michael Winkelmann committed
90
      printer.newPage();
91
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
92 93
  }
  return true;
94 95
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
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
117
void QmlPrinter::paintItem(QQuickItem *item, QQuickWindow *window,
118
                           QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
119 120 121 122 123 124 125 126 127 128 129 130 131
  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());
  }

132

Michael Winkelmann's avatar
Michael Winkelmann committed
133 134 135 136 137 138 139 140 141 142
  // 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
143
        for (QQuickItem *children : listViewChildren) {
Michael Winkelmann's avatar
Michael Winkelmann committed
144
          paintItem(children, window, painter);
145
        }
Michael Winkelmann's avatar
Michael Winkelmann committed
146 147 148 149 150 151 152 153 154 155 156 157 158
      }
    }
  } 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 {
159

Michael Winkelmann's avatar
Michael Winkelmann committed
160
      // Fallback to screen capture if we are unable to parse the data
161
      QRectF rect(0,0,item->width(),item->height());
Michael Winkelmann's avatar
Michael Winkelmann committed
162
      if (window != nullptr) {
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        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;
            });
          drawChildren = false;
        } else {
          ready = true;
          drawChildren = false;
        }

        while(!ready) { qGuiApp->processEvents(); }


//        windowImage.save(QString(item->metaObject()->className()) + ".jpg");
Michael Winkelmann's avatar
Michael Winkelmann committed
183
      }
184
   //   drawChildren = false;
185
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
186
  }
187

Michael Winkelmann's avatar
Michael Winkelmann committed
188
  if (drawChildren) {
189

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

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

Michael Winkelmann's avatar
Michael Winkelmann committed
199
  painter->restore();
200 201
}

202 203 204 205 206 207 208 209
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
210
void QmlPrinter::paintQQuickCanvasItem(QQuickItem *item, QQuickWindow *window,
211
                                       QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
212 213 214
  // No point in continuing as we are unable to grab the image
  if (window == nullptr)
    return;
215

Michael Winkelmann's avatar
Michael Winkelmann committed
216 217 218
  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());
219 220
}

221
void QmlPrinter::paintQQuickRectangle(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  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);
  }
}
246

247
void QmlPrinter::paintQQuickText(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
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 290 291
  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);
}
292

293
void QmlPrinter::paintQQuickImage(QQuickItem *item, QPainter *painter) const {
Michael Winkelmann's avatar
Michael Winkelmann committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  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());
318
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
319 320 321 322 323 324 325 326
    if (sourceRect.height() > rect.height()) {
      rect.setHeight(sourceRect.height());
    } else {
      sourceRect.setHeight(rect.height());
    }
  } break;
  }
  painter->drawImage(rect, image, sourceRect);
327 328
}

Michael Winkelmann's avatar
Michael Winkelmann committed
329 330 331 332 333 334 335
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;
336 337
}

Michael Winkelmann's avatar
Michael Winkelmann committed
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 374 375
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());
376
    }
Michael Winkelmann's avatar
Michael Winkelmann committed
377 378 379 380 381 382 383 384 385 386 387 388
    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();
389
}
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

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();
}

StackLayoutStrategy::StackLayoutStrategy(const QVariantMap & options) :
    m_options(options)
{

}

bool StackLayoutStrategy::operator()(QQuickItem *rootItem,
                                     ItemList & items,
                                     ItemList & masterItems)
{

}