aboutsummaryrefslogtreecommitdiff
path: root/CruUI/application.cpp
blob: 3ee7817d29fbeea95fe714899ea14289bfe3c086 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "application.h"

#include "timer.h"
#include "ui/window.h"
#include "graph/graph.h"

namespace cru {
    constexpr int invoke_later_message_id = WM_USER + 2000;

    Application* Application::instance_ = nullptr;

    Application * Application::GetInstance() {
        return instance_;
    }

    Application::Application(HINSTANCE h_instance)
        : h_instance_(h_instance) {

        if (instance_)
            throw std::runtime_error("A application instance already exists.");

        instance_ = this;

        window_manager_ = std::make_unique<ui::WindowManager>();
        graph_manager_ = std::make_unique<graph::GraphManager>();
        timer_manager_ = std::make_unique<TimerManager>();
    }

    Application::~Application()
    {
        instance_ = nullptr;
    }

    int Application::Run()
    {
        MSG msg;

        while (GetMessage(&msg, nullptr, 0, 0))
        {
            if (!HandleThreadMessage(msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);

            }
        }

        return static_cast<int>(msg.wParam);
    }

    void Application::Quit(const int quit_code) {
        ::PostQuitMessage(quit_code);
    }

    bool Application::HandleThreadMessage(const MSG& message)
    {
        if (message.hwnd != nullptr)
            return false;

        switch (message.message)
        {
        case invoke_later_message_id:
        {
            const auto p_action = reinterpret_cast<InvokeLaterAction*>(message.wParam);
            (*p_action)();
            delete p_action;
            return true;
        }
        case WM_TIMER:
        {
            const auto action = timer_manager_->GetAction(static_cast<UINT_PTR>(message.wParam));
            if (action.has_value())
            {
                action.value()();
                return true;
            }
            break;
        }
        default:
            return false;
        }
        return false;
    }

    void InvokeLater(InvokeLaterAction&& action) {
        //copy the action to a safe place
        auto p_action_copy = new InvokeLaterAction(std::move(action));

        PostMessage(
            nullptr,
            invoke_later_message_id,
            reinterpret_cast<WPARAM>(p_action_copy),
            0
        );
    }
}