1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 17:27:35 +00:00

LibGUI: Add GUI::MessageBox::ask_about_unsaved_changes()

This is a static helper function for asking the user what they want to
do about unsaved changes. It behaves as a standard Yes/No/Cancel box
with text and buttons tailored to the typical unsaved changes use case.
This commit is contained in:
Andreas Kling 2022-01-04 17:08:45 +01:00
parent 3f597c70b4
commit 8e336d3404
2 changed files with 33 additions and 6 deletions

View file

@ -1,9 +1,10 @@
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/LexicalPath.h>
#include <LibGUI/BoxLayout.h>
#include <LibGUI/Button.h>
#include <LibGUI/ImageWidget.h>
@ -26,6 +27,25 @@ int MessageBox::show_error(Window* parent_window, StringView text)
return show(parent_window, text, "Error", GUI::MessageBox::Type::Error, GUI::MessageBox::InputType::OK);
}
int MessageBox::ask_about_unsaved_changes(Window* parent_window, StringView path)
{
String text;
if (path.is_empty())
text = "Save changes to untitled document before closing?";
else
text = String::formatted("Save changes to '{}' before closing?", LexicalPath::basename(path));
auto box = MessageBox::construct(parent_window, text, "Unsaved changes", Type::Warning, InputType::YesNoCancel);
if (parent_window)
box->set_icon(parent_window->icon());
box->m_yes_button->set_text(path.is_empty() ? "Save As..." : "Save");
box->m_no_button->set_text("Close");
box->m_cancel_button->set_text("Cancel");
return box->exec();
}
MessageBox::MessageBox(Window* parent_window, StringView text, StringView title, Type type, InputType input_type)
: Dialog(parent_window)
, m_text(text)
@ -119,7 +139,7 @@ void MessageBox::build()
constexpr int button_width = 80;
int button_count = 0;
auto add_button = [&](String label, Dialog::ExecResult result) {
auto add_button = [&](String label, Dialog::ExecResult result) -> GUI::Button& {
auto& button = button_container.add<Button>();
button.set_fixed_width(button_width);
button.set_text(label);
@ -127,17 +147,18 @@ void MessageBox::build()
done(result);
};
++button_count;
return button;
};
button_container.layout()->add_spacer();
if (should_include_ok_button())
add_button("OK", Dialog::ExecOK);
m_ok_button = add_button("OK", Dialog::ExecOK);
if (should_include_yes_button())
add_button("Yes", Dialog::ExecYes);
m_yes_button = add_button("Yes", Dialog::ExecYes);
if (should_include_no_button())
add_button("No", Dialog::ExecNo);
m_no_button = add_button("No", Dialog::ExecNo);
if (should_include_cancel_button())
add_button("Cancel", Dialog::ExecCancel);
m_cancel_button = add_button("Cancel", Dialog::ExecCancel);
button_container.layout()->add_spacer();
int width = (button_count * button_width) + ((button_count - 1) * button_container.layout()->spacing()) + 32;