PDFViewer: Perform standard error handling when opening files

The previous implementation of open_file had a lambda that was used to
inspect the call of ErrorOr-returning calls. This was a non-standard way
of doing this though, as the more usual and clearer way is to have an
inner function that returns ErrorOr, then handle any incoming errors on
the top level function.

This commit adds a try_open_file function, where all the logic occurs,
and all the failure-producing steps are simplied TRY'ed. The top level
open_file function takes that result and does what the lambda previously
did: showing a message box with the actual error.
This commit is contained in:
Rodrigo Tobar 2022-12-17 12:15:22 +08:00 committed by Andreas Kling
parent 5049b103c0
commit cb2cf6de99
Notes: sideshowbarker 2024-07-17 03:03:44 +09:00
2 changed files with 16 additions and 20 deletions

View file

@ -336,35 +336,28 @@ void PDFViewerWidget::initialize_toolbar(GUI::Toolbar& toolbar)
void PDFViewerWidget::open_file(Core::File& file)
{
window()->set_title(DeprecatedString::formatted("{} - PDF Viewer", file.filename()));
auto handle_error = [&](auto&& maybe_error) {
auto maybe_error = try_open_file(file);
if (maybe_error.is_error()) {
auto error = maybe_error.release_error();
warnln("{}", error.message());
GUI::MessageBox::show_error(nullptr, "Failed to load the document."sv);
return true;
}
return false;
};
}
PDF::PDFErrorOr<void> PDFViewerWidget::try_open_file(Core::File& file)
{
window()->set_title(DeprecatedString::formatted("{} - PDF Viewer", file.filename()));
m_buffer = file.read_all();
auto maybe_document = PDF::Document::create(m_buffer);
if (handle_error(maybe_document))
return;
auto document = maybe_document.release_value();
auto document = TRY(PDF::Document::create(m_buffer));
if (auto sh = document->security_handler(); sh && !sh->has_user_password()) {
// FIXME: Prompt the user for a password
VERIFY_NOT_REACHED();
}
if (handle_error(document->initialize()))
return;
if (handle_error(m_viewer->set_document(document)))
return;
TRY(document->initialize());
TRY(m_viewer->set_document(document));
m_total_page_label->set_text(DeprecatedString::formatted("of {}", document->get_page_count()));
@ -391,4 +384,6 @@ void PDFViewerWidget::open_file(Core::File& file)
m_sidebar->set_visible(false);
m_sidebar_open = false;
}
return {};
}

View file

@ -32,6 +32,7 @@ private:
PDFViewerWidget();
void initialize_toolbar(GUI::Toolbar&);
PDF::PDFErrorOr<void> try_open_file(Core::File&);
RefPtr<PDFViewer> m_viewer;
RefPtr<SidebarWidget> m_sidebar;