Skip to content

Commit 996b25c

Browse files
committed
examples/drummachine: add a message in case of fatal error
Before exiting the app in case of a fatal error, display an error message instead of just printing an error in the console. Users may not have access to the console or the output can be redirected. Signed-off-by: Ludovic Desroches <[email protected]> Acked-by: Cyrille Pitchen <[email protected]>
1 parent f5594a5 commit 996b25c

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

examples/drummachine/drummachine.cpp

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,41 @@
99
#include <memory>
1010
#include <string>
1111

12+
static int fatal_error(const std::string& err)
13+
{
14+
std::cerr << err << std::endl;
15+
16+
auto& app = egt::Application::instance();
17+
18+
auto msg = std::make_shared<egt::Label>(err);
19+
msg->border(2);
20+
msg->fill_flags(egt::Theme::FillFlag::solid);
21+
msg->color(egt::Palette::ColorId::border, egt::Palette::red);
22+
msg->color(egt::Palette::ColorId::label_bg, egt::Palette::white);
23+
msg->resize(egt::Application::instance().screen()->size() * 0.75);
24+
25+
egt::Timer err_timer(std::chrono::milliseconds(3000));
26+
err_timer.on_timeout([&app]()
27+
{
28+
app.quit(-1);
29+
});
30+
err_timer.start();
31+
32+
auto win = app.main_window();
33+
/*
34+
* A main window has been already set when this function is called.
35+
* This is why we don't deal with the case there is no main window.
36+
* Sanity check just done to prevent a crash.
37+
*/
38+
if (win)
39+
{
40+
win->add(egt::center(msg));
41+
win->show();
42+
}
43+
44+
return app.run();
45+
}
46+
1247
int main(int argc, char** argv)
1348
{
1449
egt::Application app(argc, argv);
@@ -67,8 +102,7 @@ int main(int argc, char** argv)
67102
}
68103
catch (const std::system_error& e)
69104
{
70-
std::cerr << e.what() << std::endl;
71-
return -1;
105+
return fatal_error(e.what());
72106
}
73107
catch (const std::runtime_error& e)
74108
{
@@ -127,8 +161,7 @@ int main(int argc, char** argv)
127161
const auto sound_devices = egt::SoundEffect::sound_device_list();
128162
if (sound_devices.empty())
129163
{
130-
std::cerr << "No sound device found" << std::endl;
131-
return -1;
164+
return fatal_error("No sound device found");
132165
}
133166

134167
egt::ImageButton speaker(egt::Image("file:speaker.png"), sound_devices[0].card_name());

0 commit comments

Comments
 (0)