polybar/include/drawtypes/animation.hpp

87 lines
2.2 KiB
C++
Raw Normal View History

#pragma once
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
#include "common.hpp"
#include "components/config.hpp"
#include "drawtypes/label.hpp"
#include "utils/mixins.hpp"
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
LEMONBUDDY_NS
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
namespace drawtypes {
class animation : public non_copyable_mixin<animation> {
public:
explicit animation(int framerate_ms) : m_framerate_ms(framerate_ms) {}
explicit animation(vector<icon_t>&& frames, int framerate_ms)
: m_frames(forward<decltype(frames)>(frames))
, m_framerate_ms(framerate_ms)
, m_framecount(m_frames.size())
, m_lastupdate(chrono::system_clock::now()) {}
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
void add(icon_t&& frame) {
m_frames.emplace_back(forward<decltype(frame)>(frame));
m_framecount = m_frames.size();
}
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
icon_t get() {
tick();
return m_frames[m_frame];
}
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
int framerate() {
return m_framerate_ms;
}
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
operator bool() {
return !m_frames.empty();
}
2016-05-19 14:41:06 +00:00
2016-06-15 03:32:35 +00:00
protected:
vector<icon_t> m_frames;
int m_framerate_ms = 1000;
int m_frame = 0;
int m_framecount = 0;
chrono::system_clock::time_point m_lastupdate;
void tick() {
auto now = chrono::system_clock::now();
auto diff = chrono::duration_cast<chrono::milliseconds>(now - m_lastupdate);
if (diff.count() < m_framerate_ms)
return;
if (++m_frame >= m_framecount)
m_frame = 0;
m_lastupdate = now;
}
2016-05-19 14:41:06 +00:00
};
2016-10-25 05:10:03 +00:00
using animation_t = shared_ptr<animation>;
/**
* Create an animation by loading values
* from the configuration
*/
inline auto load_animation(
2016-06-15 03:32:35 +00:00
const config& conf, string section, string name = "animation", bool required = true) {
vector<icon_t> vec;
vector<string> frames;
name = string_util::ltrim(string_util::rtrim(name, '>'), '<');
if (required)
frames = conf.get_list<string>(section, name);
else
frames = conf.get_list<string>(section, name, {});
for (size_t i = 0; i < frames.size(); i++)
2016-06-15 03:32:35 +00:00
vec.emplace_back(forward<icon_t>(
2016-10-25 05:10:03 +00:00
load_optional_icon(conf, section, name + "-" + to_string(i), frames[i])));
2016-06-15 03:32:35 +00:00
auto framerate = conf.get<int>(section, name + "-framerate", 1000);
2016-06-15 03:32:35 +00:00
return animation_t{new animation(move(vec), framerate)};
}
2016-05-19 14:41:06 +00:00
}
2016-06-15 03:32:35 +00:00
LEMONBUDDY_NS_END