cppscripts/statustime.cpp

75 lines
1.7 KiB
C++
Raw Normal View History

2021-08-05 16:08:40 +02:00
// Print date and time for i3 status bar.
2021-08-23 13:18:29 +02:00
/* i3blocks config:
* [time]
* command=statustime
* interval=persist
* markup=pango
*/
2021-08-05 16:08:40 +02:00
#include <fmt/chrono.h>
#include <fmt/core.h>
#include <chrono>
#include <csignal>
2021-08-05 16:08:40 +02:00
#include <exception>
#include <iostream>
#include <locale>
#include <thread>
void signal_handler(int signum)
{
switch (signum)
{
case SIGTERM:
case SIGINT:
{
std::cout << R"(<span color="red">Time script terminated.</span>)"
<< std::endl;
std::exit(signum); // NOLINT(concurrency-mt-unsafe)
break;
}
default:
{
break;
}
}
}
2021-08-05 16:08:40 +02:00
int main()
{
using fmt::format;
using std::cout;
using std::endl;
using clock = std::chrono::system_clock;
using std::chrono::minutes;
2021-08-05 16:08:40 +02:00
using namespace std::chrono_literals;
// Set explicitly, because LC_TIME is en_DK.UTF-8.
std::locale::global(std::locale("de_DE.UTF-8"));
std::signal(SIGINT, signal_handler);
std::signal(SIGTERM, signal_handler);
2021-08-05 16:08:40 +02:00
try
{
while (true)
{
const auto now{clock::now()};
2021-08-05 16:08:40 +02:00
cout << format(R"(<b><span color="orange">{0:%A}</span></b>, )"
R"({0:%Y-%m-%d} )"
R"(<span color="lightcyan">{0:%H:%M}</span>)",
now)
<< endl; // NOTE: Don't forget that we need to flush! 😊
const auto next_minute{std::chrono::floor<minutes>(now + 1min)};
std::this_thread::sleep_until(next_minute);
2021-08-05 16:08:40 +02:00
}
}
catch (const std::exception &e)
2021-08-05 16:08:40 +02:00
{
cout << R"(<span color="red">Time script crashed.</span>)" << endl;
std::cerr << e.what() << '\n';
2021-08-05 16:08:40 +02:00
return 33;
}
}