File indexing completed on 2024-10-06 12:53:59

0001 // SPDX-FileCopyrightText: 2019 Black Hat <bhat@encom.eu.org>
0002 // SPDX-License-Identifier: GPL-3.0-only
0003 
0004 #include "clipboard.h"
0005 
0006 #include <QClipboard>
0007 #include <QDateTime>
0008 #include <QDir>
0009 #include <QFileInfo>
0010 #include <QGuiApplication>
0011 #include <QImage>
0012 #include <QMimeData>
0013 #include <QRegularExpression>
0014 #include <QStandardPaths>
0015 #include <QUrl>
0016 
0017 Clipboard::Clipboard(QObject *parent)
0018     : QObject(parent)
0019     , m_clipboard(QGuiApplication::clipboard())
0020 {
0021     connect(m_clipboard, &QClipboard::changed, this, &Clipboard::imageChanged);
0022 }
0023 
0024 bool Clipboard::hasImage() const
0025 {
0026     return !image().isNull();
0027 }
0028 
0029 QImage Clipboard::image() const
0030 {
0031     return m_clipboard->image();
0032 }
0033 
0034 QString Clipboard::saveImage(QString localPath) const
0035 {
0036     QString imageDir(QStringLiteral("%1/screenshots").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)));
0037 
0038     if (!QDir().exists(imageDir)) {
0039         QDir().mkdir(imageDir);
0040     }
0041 
0042     if (localPath.isEmpty()) {
0043         localPath = QStringLiteral("file://%1/%2.png").arg(imageDir, QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd-hh-mm-ss")));
0044     }
0045     QUrl url(localPath);
0046     if (!url.isLocalFile()) {
0047         return {};
0048     }
0049     auto image = this->image();
0050 
0051     if (image.isNull()) {
0052         return {};
0053     }
0054 
0055     if (image.save(url.toLocalFile())) {
0056         return localPath;
0057     } else {
0058         return {};
0059     }
0060 }
0061 
0062 void Clipboard::saveText(QString message)
0063 {
0064     static QRegularExpression re(QStringLiteral("<[^>]*>"));
0065     auto *mimeData = new QMimeData; // ownership is transferred to clipboard
0066     mimeData->setHtml(message);
0067     mimeData->setText(message.replace(re, QString()));
0068     m_clipboard->setMimeData(mimeData);
0069 }
0070 
0071 void Clipboard::setImage(const QUrl &url)
0072 {
0073     if (url.isLocalFile()) {
0074         QImage img(url.path());
0075         auto *mimeData = new QMimeData;
0076         mimeData->setImageData(img);
0077         if (!img.isNull()) {
0078             m_clipboard->setMimeData(mimeData);
0079         }
0080     }
0081 }
0082 
0083 #include "moc_clipboard.cpp"