cppscripts/statustime.cpp

75 lines
1.7 KiB
C++
Executable File

// Print date and time for i3 status bar.
/* i3blocks config:
* [time]
* command=statustime
* interval=persist
* markup=pango
*/
#include <fmt/chrono.h>
#include <fmt/core.h>
#include <chrono>
#include <csignal>
#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;
}
}
}
int main()
{
using fmt::format;
using std::cout;
using std::endl;
using clock = std::chrono::system_clock;
using std::chrono::minutes;
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);
try
{
while (true)
{
const auto now{clock::now()};
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);
}
}
catch (const std::exception &e)
{
cout << R"(<span color="red">Time script crashed.</span>)" << endl;
std::cerr << e.what() << '\n';
return 33;
}
}