aboutsummaryrefslogtreecommitdiff
path: root/CruUI/timer.cpp
blob: 5eb803c7877b6c4b56f91b05281265abebca75bb (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
97
#include "timer.h"

namespace cru
{
	TimerManager* TimerManager::instance_ = nullptr;

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

	TimerManager::TimerManager()
	{
		instance_ = this;
	}

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

	UINT_PTR TimerManager::CreateTimer(const UINT microseconds, const bool loop, const TimerAction & action)
	{
		auto id = ::SetTimer(nullptr, 0, microseconds, nullptr);
		if (loop)
			map_[id] = action;
		else
			map_[id] = [this, action, id]() {
				action();
				this->KillTimer(id);
			};

		return id;
	}

	void TimerManager::KillTimer(const UINT_PTR id)
	{
		const auto find_result = map_.find(id);
		if (find_result != map_.cend())
		{
			::KillTimer(nullptr, id);
			map_.erase(find_result);
		}
	}

	std::optional<TimerAction> TimerManager::GetAction(const UINT_PTR id)
	{
		auto find_result = map_.find(id);
		if (find_result == map_.cend())
			return std::nullopt;
		return find_result->second;
	}

	class TimerTaskImpl : public ITimerTask
	{
	public:
		explicit TimerTaskImpl(UINT_PTR id);
	    TimerTaskImpl(const TimerTaskImpl& other) = delete;
	    TimerTaskImpl(TimerTaskImpl&& other) = delete;
	    TimerTaskImpl& operator=(const TimerTaskImpl& other) = delete;
	    TimerTaskImpl& operator=(TimerTaskImpl&& other) = delete;
		~TimerTaskImpl() override = default;

		void Cancel() override;

	private:
		UINT_PTR id_;
	};

	TimerTaskImpl::TimerTaskImpl(const UINT_PTR id)
		: id_(id)
	{

	}

    void TimerTaskImpl::Cancel()
	{
		TimerManager::GetInstance()->KillTimer(id_);
	}

	inline UINT SecondToMicroSecond(const double seconds)
	{
		return static_cast<UINT>(seconds * 1000);
	}

	std::shared_ptr<ITimerTask> SetTimeout(const double seconds, const TimerAction & action)
	{
		auto id = TimerManager::GetInstance()->CreateTimer(SecondToMicroSecond(seconds), false, action);
		return std::make_shared<TimerTaskImpl>(id);
	}

	std::shared_ptr<ITimerTask> SetInterval(const double seconds, const TimerAction & action)
	{
		auto id = TimerManager::GetInstance()->CreateTimer(SecondToMicroSecond(seconds), true, action);
		return std::make_shared<TimerTaskImpl>(id);
	}
}