/* * This file is part of smolbote. It's copyrighted by the contributors recorded * in the version control history of the file, available from its original * location: https://library.iserlohn-fortress.net/aqua/smolbote.git * * SPDX-License-Identifier: GPL-3.0 */ #include "sessiondialog.h" #include "../browser.h" #include "../util.h" #include "configuration.h" #include "session_json.hpp" #include "ui_sessiondialog.h" #include #include #include #include SessionDialog::SessionDialog(QWidget *parent) : QDialog(parent) , create_window_str(QObject::tr("Create a new window")) , ui(new Ui::SessionDialog) { ui->setupUi(this); auto *browser = qobject_cast(qApp); Q_CHECK_PTR(browser); Configuration conf; for(const QString &path : Util::files(conf.value("session.path").value(), { "*.json" })) { ui->listWidget->addItem(path); } ui->listWidget->addItem(create_window_str); connect(ui->listWidget, &QListWidget::currentItemChanged, this, [this](QListWidgetItem *currentItem, QListWidgetItem * /*previousItem*/) { ui->delete_toolButton->setEnabled(currentItem->text() != create_window_str); }); connect(ui->open_toolButton, &QToolButton::clicked, this, [this]() { const QString filename = QFileDialog::getOpenFileName(this, tr("Select Session file"), QDir::homePath(), tr("JSON (*.json)")); if(!filename.isEmpty()) { ui->listWidget->addItem(filename); ui->listWidget->setCurrentRow(ui->listWidget->count() - 1); accept(); } }); connect(ui->delete_toolButton, &QToolButton::clicked, this, [this]() { const auto path = ui->listWidget->currentItem()->text(); if(path != create_window_str) { QFile(path).remove(); delete ui->listWidget->currentItem(); } }); accepted_connection = connect(this, &SessionDialog::accepted, this, [this, browser]() { const auto path = ui->listWidget->currentItem()->text(); if(path != create_window_str) { openSession(path); } else { browser->open({}); } }); connect(ui->search, &QLineEdit::textEdited, this, &SessionDialog::search); } SessionDialog::~SessionDialog() { delete ui; } std::optional> SessionDialog::pickSession() { disconnect(accepted_connection); if(this->exec() == QDialog::Rejected) { return std::nullopt; } const auto path = ui->listWidget->currentItem()->text(); if(path != create_window_str) { QFile json(path); if(json.open(QIODevice::ReadOnly | QIODevice::Text)) { JsonSession session(json.readAll()); return session.get(); } } return std::nullopt; } void SessionDialog::search(const QString &text) { for(int i = 0; i < ui->listWidget->count(); ++i) { auto *item = ui->listWidget->item(i); item->setHidden(!item->text().contains(text)); } } void SessionDialog::openSession(const QString &filename) { auto *browser = qobject_cast(qApp); QFile json(filename); if(json.open(QIODevice::ReadOnly | QIODevice::Text) && browser != nullptr) { JsonSession session(json.readAll()); browser->open(session.get()); } }