File indexing completed on 2024-12-01 04:36:37

0001 /*
0002    SPDX-FileCopyrightText: 2020-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "delegateutil.h"
0008 #include "ruqolawidgets_debug.h"
0009 #include <KLocalizedString>
0010 #include <KMessageBox>
0011 #include <KRecentDirs>
0012 
0013 #include <QFileDialog>
0014 #include <QMimeDatabase>
0015 #include <QStandardPaths>
0016 #include <QUrl>
0017 
0018 #include <KFileWidget>
0019 
0020 QString DelegateUtil::querySaveFileName(QWidget *parent, const QString &title, const QUrl &fileToSave)
0021 {
0022     QString fileClass;
0023     const QUrl startUrl = KFileWidget::getStartUrl(QUrl(QStringLiteral("kfiledialog:///saveattachment")), fileClass);
0024     const auto info = QFileInfo(fileToSave.path());
0025     auto fileName = info.fileName();
0026     if (fileToSave.isLocalFile() && info.exists() && info.suffix().isEmpty()) {
0027         // guess a proper file suffix if none is given
0028         [&]() {
0029             QFile file(info.absoluteFilePath());
0030             if (!file.open(QIODevice::ReadOnly)) {
0031                 return;
0032             }
0033             QMimeDatabase mimeDb;
0034             const auto mime = mimeDb.mimeTypeForFileNameAndData(fileName, &file);
0035             if (!mime.isValid()) {
0036                 return;
0037             }
0038             const auto suffix = mime.preferredSuffix();
0039             if (!suffix.isEmpty()) {
0040                 fileName += QLatin1Char('.') + suffix;
0041             }
0042         }();
0043     }
0044     QUrl localUrl;
0045     localUrl.setPath(startUrl.path() + QLatin1Char('/') + fileName);
0046     const QString fileStr = QFileDialog::getSaveFileName(parent, title, localUrl.toString());
0047 
0048     if (!fileClass.isEmpty() && !fileStr.isEmpty()) {
0049         KRecentDirs::add(fileClass, fileStr);
0050     }
0051     return fileStr;
0052 }
0053 
0054 void DelegateUtil::saveFile(QWidget *parentWidget, const QString &filePath, const QString &title)
0055 {
0056     const auto file = DelegateUtil::querySaveFileName(parentWidget, title, QUrl::fromLocalFile(filePath));
0057     if (!file.isEmpty()) {
0058         if (QFile::exists(file) && !QFile::remove(file)) { // copy() doesn't overwrite
0059             qCWarning(RUQOLAWIDGETS_LOG) << "Impossible to remove : " << file;
0060         }
0061         QFile sourceFile(filePath);
0062         if (!sourceFile.copy(file)) {
0063             KMessageBox::error(parentWidget, sourceFile.errorString(), i18n("Error saving file"));
0064         }
0065     }
0066 }