| 1 | /* |
| 2 | * Copyright (C) 2020 Damir Porobic <[email protected]> |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation; either version 2 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program; if not, write to the Free Software |
| 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, |
| 17 | * Boston, MA 02110-1301, USA. |
| 18 | */ |
| 19 | |
| 20 | #include "CopyAsDataUriOperation.h" |
| 21 | |
| 22 | CopyAsDataUriOperation::CopyAsDataUriOperation( |
| 23 | QImage image, |
| 24 | const QSharedPointer<IClipboard> &clipboardService, |
| 25 | const QSharedPointer<INotificationService> ¬ificationService, |
| 26 | const QSharedPointer<IConfig> &config) : |
| 27 | mImage(std::move(image)), |
| 28 | mClipboardService(clipboardService), |
| 29 | mNotificationService(notificationService), |
| 30 | mConfig(config) |
| 31 | { |
| 32 | } |
| 33 | |
| 34 | bool CopyAsDataUriOperation::execute() |
| 35 | { |
| 36 | QByteArray byteArray; |
| 37 | QBuffer buffer(&byteArray); |
| 38 | buffer.open(QIODevice::WriteOnly); |
| 39 | auto isSaved = mImage.save(&buffer, mConfig->saveFormat().toLatin1()); |
| 40 | buffer.close(); |
| 41 | |
| 42 | if (isSaved) { |
| 43 | QByteArray output = "data:image/" + mConfig->saveFormat().toLatin1() +";base64,"; |
| 44 | output.append(byteArray.toBase64()); |
| 45 | mClipboardService->setText(output); |
| 46 | notifySuccess(); |
| 47 | } else { |
| 48 | notifyFailure(); |
| 49 | } |
| 50 | |
| 51 | return isSaved; |
| 52 | } |
| 53 | |
| 54 | void CopyAsDataUriOperation::notifyFailure() const |
| 55 | { |
| 56 | auto title = tr("Failed to copy to clipboard"); |
| 57 | auto message = tr("Failed to copy to clipboard as base64 encoded image."); |
| 58 | notify(title, message, NotificationTypes::Warning); |
| 59 | } |
| 60 | |
| 61 | void CopyAsDataUriOperation::notifySuccess() const |
| 62 | { |
| 63 | auto title = tr("Copied to clipboard"); |
| 64 | auto message = tr("Copied to clipboard as base64 encoded image."); |
| 65 | notify(title, message, NotificationTypes::Information); |
| 66 | } |
| 67 | |
| 68 | void CopyAsDataUriOperation::notify(const QString &title, const QString &message, NotificationTypes type) const |
| 69 | { |
| 70 | NotifyOperation operation(title, message, type, mNotificationService, mConfig); |
| 71 | operation.execute(); |
| 72 | } |