Files
yourls-ui/clipboardresultdialog.h
T
2026-10-01 12:21:40 -04:00

61 lines
2.1 KiB
C++

#ifndef CLIPBOARDRESULTDIALOG_H
#define CLIPBOARDRESULTDIALOG_H
#include <QClipboard>
#include <QDialog>
#include <QEvent>
#include <QGuiApplication>
#include <QLabel>
#include <QTimer>
#include <QUrl>
#ifndef QT_NO_DEBUG
#include <QDebug>
#endif
// Keep the result window focused while taking ownership of the clipboard.
class ClipboardResultDialog : public QDialog {
public:
ClipboardResultDialog(const QUrl &url, bool requiresFocus, QWidget *parent = nullptr)
: QDialog(parent), m_text(url.toString(QUrl::FullyEncoded)),
m_requiresFocus(requiresFocus), m_status(new QLabel(this)) {
m_status->setText(QStringLiteral("Activate this window to copy the short URL."));
m_status->setWordWrap(true);
}
QLabel *copyStatusLabel() const { return m_status; }
bool copyShortUrl() {
if (m_requiresFocus && !isActiveWindow())
return false;
auto *clipboard = QGuiApplication::clipboard();
clipboard->setText(m_text, QClipboard::Clipboard);
const bool copied = clipboard->text(QClipboard::Clipboard) == m_text && (!QGuiApplication::platformName().startsWith(QStringLiteral("wayland")) || clipboard->ownsClipboard());
m_status->setText(copied ? QStringLiteral("Short URL copied to clipboard.")
: QStringLiteral("Could not copy the short URL. Click OK to retry."));
#ifndef QT_NO_DEBUG
qDebug() << "[clipboard] short URL write, active:" << isActiveWindow()
<< "owns clipboard:" << clipboard->ownsClipboard() << "verified:" << copied;
#endif
return copied;
}
protected:
void changeEvent(QEvent *event) override {
QDialog::changeEvent(event);
if (event->type() == QEvent::ActivationChange && isActiveWindow()) {
// Let Qt finish processing the focus event and its Wayland input serial.
QTimer::singleShot(0, this, [this]() {
if (isActiveWindow())
copyShortUrl();
});
}
}
private:
QString m_text;
bool m_requiresFocus;
QLabel *m_status;
};
#endif// CLIPBOARDRESULTDIALOG_H