From 48a338b1321d9e169c73b71c01cd2f9ba00f9c53 Mon Sep 17 00:00:00 2001 From: ConfuSomu Date: Sat, 1 Jun 2024 18:05:30 -0400 Subject: Implement Recent files list and menu --- src/recent_files.cpp | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/recent_files.cpp (limited to 'src/recent_files.cpp') diff --git a/src/recent_files.cpp b/src/recent_files.cpp new file mode 100644 index 0000000..2382f1a --- /dev/null +++ b/src/recent_files.cpp @@ -0,0 +1,70 @@ +#include "recent_files.h" +#include + +RecentFiles::RecentFiles(unsigned int size, bool force_empty) : size(size) { + if (not force_empty) + list = settings_interface.read_setting("ui/recent_files").value(); +} + +RecentFiles::~RecentFiles() { + if (has_list_changed) { + settings_interface.write_setting("ui/recent_files", list); + settings_interface.commit(); + } +} + +RecentFiles::QMenuPtr RecentFiles::create_menu(const QString& title, QWidget* parent) { + if (menu) return menu; + + menu = std::make_shared(title, parent); + generate_menu_actions(); + + return menu; +} + +void RecentFiles::generate_menu_actions() { + menu->clear(); + + if (not list.isEmpty()) { + int i = 1; + for (const QString& path : list) { + Action* action = new Action(QStringLiteral("&%1. %2").arg(i++).arg(QFileInfo(path).fileName())); + action->file_path = path; + menu->addAction(action); + } + } else { + Action* action = new Action(QWidget::tr("No recent files")); + action->setStatusTip(QWidget::tr("To view recent files, open a file")); + action->setEnabled(false); + menu->addAction(action); + } +} + +void RecentFiles::add_file(const QString& path) { + if (not list.contains(path)) { + list.prepend(path); + if (list.size() > size) +#if (QT_VERSION >= QT_VERSION_CHECK(6,0,0)) + list.resize(size); +#else + do list.removeLast(); + while (list.size() > size); +#endif + has_list_changed = true; + generate_menu_actions(); + } +} + +const QStringList& RecentFiles::get_files() { + return list; +} + +void RecentFiles::clear() { + list.empty(); +} + +RecentFiles::Action::Action(const QString &text, QObject *parent) : QAction(text, parent) { + connect(this, &QAction::triggered, this, [=](bool checked) { + emit this->chosen_file(file_path); + }); +} -- cgit v1.2.3-54-g00ecf