Dialog.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/EventLoop.h>
  8. #include <LibGUI/Dialog.h>
  9. #include <LibGUI/Event.h>
  10. #include <LibGfx/Palette.h>
  11. namespace GUI {
  12. Dialog::Dialog(Window* parent_window, ScreenPosition screen_position)
  13. : Window(parent_window)
  14. , m_screen_position(screen_position)
  15. {
  16. set_window_mode(WindowMode::Blocking);
  17. }
  18. Dialog::ExecResult Dialog::exec()
  19. {
  20. VERIFY(!m_event_loop);
  21. m_event_loop = make<Core::EventLoop>();
  22. switch (m_screen_position) {
  23. case ScreenPosition::DoNotPosition:
  24. break;
  25. case ScreenPosition::CenterWithinParent:
  26. if (auto parent = find_parent_window(); parent && parent->is_visible()) {
  27. center_within(*parent);
  28. constrain_to_desktop();
  29. break;
  30. }
  31. [[fallthrough]];
  32. case ScreenPosition::Center:
  33. center_on_screen();
  34. break;
  35. }
  36. show();
  37. auto result = m_event_loop->exec();
  38. m_event_loop = nullptr;
  39. dbgln("{}: Event loop returned with result {}", *this, result);
  40. remove_from_parent();
  41. return static_cast<ExecResult>(result);
  42. }
  43. void Dialog::done(ExecResult result)
  44. {
  45. Window::close();
  46. if (!m_event_loop)
  47. return;
  48. m_result = result;
  49. on_done(m_result);
  50. dbgln("{}: Quit event loop with result {}", *this, to_underlying(result));
  51. m_event_loop->quit(to_underlying(result));
  52. }
  53. void Dialog::event(Core::Event& event)
  54. {
  55. if (event.type() == Event::KeyDown) {
  56. auto& key_event = static_cast<KeyEvent&>(event);
  57. if (key_event.key() == KeyCode::Key_Escape) {
  58. done(ExecResult::Cancel);
  59. event.accept();
  60. return;
  61. }
  62. }
  63. Window::event(event);
  64. }
  65. void Dialog::close()
  66. {
  67. done(ExecResult::Cancel);
  68. }
  69. }