aboutsummaryrefslogtreecommitdiff
path: root/src/win/gui/GodWindow.cpp
blob: 7bce83a3d7fd55b2cbbc52af01f066fc306d0832 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "cru/win/gui/GodWindow.hpp"

#include "cru/common/Logger.hpp"
#include "cru/win/gui/Exception.hpp"
#include "cru/win/gui/UiApplication.hpp"
#include "cru/win/gui/WindowClass.hpp"

namespace cru::platform::gui::win {
constexpr auto god_window_class_name = L"GodWindowClass";

LRESULT CALLBACK GodWndProc(HWND hWnd, UINT uMsg, WPARAM wParam,
                            LPARAM lParam) {
  const auto app = WinUiApplication::GetInstance();

  if (app) {
    LRESULT result;
    auto god_window = app->GetGodWindow();
    if (god_window != nullptr) {
      const auto handled = god_window->HandleGodWindowMessage(
          hWnd, uMsg, wParam, lParam, &result);
      if (handled) return result;
    }
  }
  return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}

GodWindow::GodWindow(WinUiApplication* application) {
  application_ = application;

  const auto h_instance = application->GetInstanceHandle();

  god_window_class_ = std::make_unique<WindowClass>(god_window_class_name,
                                                    GodWndProc, h_instance);

  hwnd_ = CreateWindowEx(0, god_window_class_name, L"", 0, CW_USEDEFAULT,
                         CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                         HWND_MESSAGE, nullptr, h_instance, nullptr);

  if (hwnd_ == nullptr)
    throw Win32Error(::GetLastError(), "Failed to create god window.");
}

GodWindow::~GodWindow() {
  if (!::DestroyWindow(hwnd_)) {
    // Although this could be "safely" ignore.
    log::TagWarn(log_tag, u"Failed to destroy god window.");
  }
}

bool GodWindow::HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param,
                                       LPARAM l_param, LRESULT* result) {
  WindowNativeMessageEventArgs args(
      WindowNativeMessage{hwnd, msg, w_param, l_param});
  message_event_.Raise(args);

  if (args.IsHandled()) {
    *result = args.GetResult();
    return true;
  }

  return false;
}
}  // namespace cru::platform::gui::win