summaryrefslogtreecommitdiff
path: root/src/ui/View.h
blob: 4ca512a8d47efbfe04dd96e460fab293b1437896 (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
#pragma once

#include <memory>

#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui.h"

class ViewManager;

// A single screen of the UI, swapped in through the ViewManager.
class View {
public:
    virtual ~View() = default;

    virtual void Init() {}
    virtual void Update() {}
    virtual void Render() = 0;

    void InternalInit(const std::shared_ptr<ViewManager>& manager) {
        // Weak to avoid a cycle: the ViewManager owns the View.
        this->mManager = manager;
        this->Init();
    }

protected:
    std::shared_ptr<ViewManager> Manager() const {
        return mManager.lock();
    }

private:
    std::weak_ptr<ViewManager> mManager;
};

// Owns the active View and drives its per-frame Update/Render.
class ViewManager : public std::enable_shared_from_this<ViewManager> {
public:
    void SetView(const std::shared_ptr<View>& view) {
        mCurrent = view;
        if (mCurrent != nullptr) {
            mCurrent->InternalInit(shared_from_this());
        }
    }

    const std::shared_ptr<View>& Current() const {
        return mCurrent;
    }

    void Render() {
        if (mCurrent != nullptr) {
            mCurrent->Update();
            mCurrent->Render();
        }
    }

private:
    std::shared_ptr<View> mCurrent = nullptr;
};