File indexing completed on 2024-04-28 15:26:47

0001 /* -*- c++ -*-
0002     SPDX-FileCopyrightText: 2000 Waldo Bastian <bastian@kde.org>
0003 
0004     SPDX-License-Identifier: BSD-2-Clause
0005 */
0006 
0007 #include "krecentdirs.h"
0008 #include <KConfig>
0009 #include <KConfigGroup>
0010 #include <KSharedConfig>
0011 #include <QDebug>
0012 
0013 static constexpr int s_maxDirHistory = 3;
0014 
0015 static KConfigGroup recentdirs_readList(QString &key, QStringList &result)
0016 {
0017     KConfigGroup cg(KSharedConfig::openConfig(), QStringLiteral("Recent Dirs"));
0018     if ((key.length() < 2) || (key[0] != QLatin1Char(':'))) {
0019         key = QStringLiteral(":default");
0020     }
0021     if (key[1] == QLatin1Char(':')) {
0022 #if KIOFILEWIDGETS_BUILD_DEPRECATED_SINCE(5, 95)
0023         qWarning() << "Using KRecentDirs with a global config file is deprecated. Remove the second colon to use the application-local file."
0024                    << "The requested key was" << key;
0025         key.remove(0, 2);
0026         cg = KConfigGroup(KSharedConfig::openConfig(QStringLiteral("krecentdirsrc")), QString());
0027 #endif
0028     } else {
0029         key.remove(0, 1);
0030     }
0031 
0032     result = cg.readPathEntry(key, QStringList());
0033     if (result.isEmpty()) {
0034         result.append(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
0035     }
0036     return cg;
0037 }
0038 
0039 QStringList KRecentDirs::list(const QString &fileClass)
0040 {
0041     QString key = fileClass;
0042     QStringList result;
0043     recentdirs_readList(key, result).sync();
0044     return result;
0045 }
0046 
0047 QString KRecentDirs::dir(const QString &fileClass)
0048 {
0049     const QStringList result = list(fileClass);
0050     return result[0];
0051 }
0052 
0053 void KRecentDirs::add(const QString &fileClass, const QString &directory)
0054 {
0055     QString key = fileClass;
0056     QStringList result;
0057     KConfigGroup config = recentdirs_readList(key, result);
0058     // make sure the dir is first in history
0059     result.removeAll(directory);
0060     result.prepend(directory);
0061     if (result.size() > s_maxDirHistory) {
0062         result.erase(result.begin() + s_maxDirHistory, result.end());
0063     }
0064 
0065     config.writePathEntry(key, result);
0066     config.sync();
0067 }