Spreadsheet: Prompt user before closing with unsaved changes

This commit is contained in:
Xavier Cooney 2020-12-22 16:15:15 +11:00 committed by Andreas Kling
parent 23febb9d8e
commit 5f58fe1643
6 changed files with 44 additions and 1 deletions

View file

@ -163,8 +163,10 @@ void Sheet::update()
// Grab a copy as updates might insert cells into the table.
for (auto& it : m_cells) {
if (it.value->dirty())
if (it.value->dirty()) {
cells_copy.append(it.value);
m_workbook.set_dirty(true);
}
}
for (auto& cell : cells_copy)

View file

@ -31,6 +31,7 @@
#include <LibCore/File.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/FilePicker.h>
#include <LibGUI/Label.h>
#include <LibGUI/Menu.h>
#include <LibGUI/MessageBox.h>
@ -216,6 +217,33 @@ void SpreadsheetWidget::load(const StringView& filename)
setup_tabs(m_workbook->sheets());
}
bool SpreadsheetWidget::request_close()
{
if (!m_workbook->dirty())
return true;
auto result = GUI::MessageBox::show(window(), "The spreadsheet has been modified. Would you like to save?", "Unsaved changes", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNoCancel);
if (result == GUI::MessageBox::ExecYes) {
if (current_filename().is_empty()) {
String name = "workbook";
Optional<String> save_path = GUI::FilePicker::get_save_filepath(window(), name, "sheets");
if (!save_path.has_value())
return false;
save(save_path.value());
} else {
save(current_filename());
}
return true;
}
if (result == GUI::MessageBox::ExecNo)
return true;
return false;
}
void SpreadsheetWidget::add_sheet()
{
StringBuilder name;

View file

@ -41,6 +41,7 @@ public:
void save(const StringView& filename);
void load(const StringView& filename);
bool request_close();
void add_sheet();
void add_sheet(NonnullRefPtr<Sheet>&&);

View file

@ -183,6 +183,7 @@ Result<bool, String> Workbook::save(const StringView& filename)
}
set_filename(filename);
set_dirty(false);
return true;
}

View file

@ -42,6 +42,8 @@ public:
const String& current_filename() const { return m_current_filename; }
bool set_filename(const String& filename);
bool dirty() { return m_dirty; }
void set_dirty(bool dirty) { m_dirty = dirty; }
bool has_sheets() const { return !m_sheets.is_empty(); }
@ -70,6 +72,7 @@ private:
WorkbookObject* m_workbook_object { nullptr };
String m_current_filename;
bool m_dirty { false };
};
}

View file

@ -114,9 +114,17 @@ int main(int argc, char* argv[])
app_menu.add_separator();
app_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) {
if (!spreadsheet_widget.request_close())
return;
app->quit(0);
}));
window->on_close_request = [&]() -> GUI::Window::CloseRequestDecision {
if (spreadsheet_widget.request_close())
return GUI::Window::CloseRequestDecision::Close;
return GUI::Window::CloseRequestDecision::StayOpen;
};
auto& file_menu = menubar->add_menu("File");
file_menu.add_action(GUI::CommonActions::make_open_action([&](auto&) {
Optional<String> load_path = GUI::FilePicker::get_open_filepath(window);