2018-08-08 23:54:58 +02:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <chrono>
|
|
|
|
#include <ctime>
|
|
|
|
#include <functional>
|
|
|
|
#include <condition_variable>
|
|
|
|
#include <thread>
|
2018-08-19 13:39:57 +02:00
|
|
|
#include <gtkmm.h>
|
2018-08-08 23:54:58 +02:00
|
|
|
|
|
|
|
namespace waybar::chrono {
|
|
|
|
|
2018-08-18 17:54:20 +02:00
|
|
|
using namespace std::chrono;
|
2018-08-08 23:54:58 +02:00
|
|
|
|
2018-08-18 17:54:20 +02:00
|
|
|
using clock = std::chrono::system_clock;
|
|
|
|
using duration = clock::duration;
|
|
|
|
using time_point = std::chrono::time_point<clock, duration>;
|
2018-08-08 23:54:58 +02:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace waybar::util {
|
|
|
|
|
2018-08-18 17:54:20 +02:00
|
|
|
struct SleeperThread {
|
|
|
|
SleeperThread() = default;
|
2018-08-08 23:54:58 +02:00
|
|
|
|
2018-08-18 17:54:20 +02:00
|
|
|
SleeperThread(std::function<void()> func)
|
2018-12-09 10:49:28 +01:00
|
|
|
: do_run_(true), thread_{[this, func] {
|
|
|
|
while (do_run_) func();
|
2018-08-18 17:54:20 +02:00
|
|
|
}}
|
2018-08-19 13:39:57 +02:00
|
|
|
{}
|
2018-08-18 17:54:20 +02:00
|
|
|
|
|
|
|
SleeperThread& operator=(std::function<void()> func)
|
|
|
|
{
|
2018-12-09 10:49:28 +01:00
|
|
|
do_run_ = true;
|
2018-08-19 13:39:57 +02:00
|
|
|
thread_ = std::thread([this, func] {
|
2018-12-09 10:49:28 +01:00
|
|
|
while (do_run_) func();
|
2018-08-18 17:54:20 +02:00
|
|
|
});
|
|
|
|
return *this;
|
|
|
|
}
|
|
|
|
|
2018-12-28 01:03:29 +01:00
|
|
|
bool isRunning() const
|
2018-12-09 10:49:28 +01:00
|
|
|
{
|
|
|
|
return do_run_;
|
|
|
|
}
|
2018-08-18 17:54:20 +02:00
|
|
|
|
|
|
|
auto sleep_for(chrono::duration dur)
|
|
|
|
{
|
2018-08-19 13:39:57 +02:00
|
|
|
auto lock = std::unique_lock(mutex_);
|
|
|
|
return condvar_.wait_for(lock, dur);
|
2018-08-18 17:54:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
auto sleep_until(chrono::time_point time)
|
|
|
|
{
|
2018-08-19 13:39:57 +02:00
|
|
|
auto lock = std::unique_lock(mutex_);
|
|
|
|
return condvar_.wait_until(lock, time);
|
2018-08-18 17:54:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
auto wake_up()
|
|
|
|
{
|
2018-08-19 13:39:57 +02:00
|
|
|
condvar_.notify_all();
|
2018-08-18 17:54:20 +02:00
|
|
|
}
|
|
|
|
|
2018-09-18 23:15:37 +02:00
|
|
|
auto stop()
|
2018-08-18 17:54:20 +02:00
|
|
|
{
|
2018-08-19 13:39:57 +02:00
|
|
|
do_run_ = false;
|
|
|
|
condvar_.notify_all();
|
2018-08-18 17:54:20 +02:00
|
|
|
}
|
|
|
|
|
2018-09-18 23:15:37 +02:00
|
|
|
~SleeperThread()
|
|
|
|
{
|
|
|
|
stop();
|
2018-12-18 17:30:54 +01:00
|
|
|
if (thread_.joinable()) {
|
|
|
|
thread_.detach();
|
|
|
|
}
|
2018-09-18 23:15:37 +02:00
|
|
|
}
|
|
|
|
|
2018-08-18 17:54:20 +02:00
|
|
|
private:
|
2018-12-09 10:49:28 +01:00
|
|
|
bool do_run_ = false;
|
2018-08-19 13:39:57 +02:00
|
|
|
std::thread thread_;
|
|
|
|
std::condition_variable condvar_;
|
|
|
|
std::mutex mutex_;
|
2018-08-18 17:54:20 +02:00
|
|
|
};
|
2018-08-08 23:54:58 +02:00
|
|
|
|
|
|
|
}
|