This repository has been archived on 2019-08-01. You can view files and clone it, but cannot push or open issues or pull requests.
ncurses-poll/examples/with-timer.cpp

72 lines
1.9 KiB
C++

//
// examples/with-timer.cpp
//
// A simple example for ncurses-poll in which user input is displayed
// on the first line, while the current timestamp on the second, which
// is refreshed once per second.
//
// @author CismonX <admin@cismon.net>
//
#include "ncurses-poll.hpp"
#include <boost/asio/yield.hpp>
struct my_session {
int chr = 0;
int num_chr = 0;
boost::asio::deadline_timer timer;
my_session(ncurses_poll<my_session>* ncp) : timer(*ncp->get_io_context()) {}
};
using boost::system::error_code;
using ncp = ncurses_poll<my_session>;
using callback = std::function<void(const boost::system::error_code&, ncp*)>;
void tick(const error_code&, ncp*);
inline void defer(ncp* poll) {
poll->session()->timer.expires_from_now(boost::posix_time::seconds(1));
poll->session()->timer.async_wait(boost::bind(tick, boost::asio::placeholders::error, poll));
}
void tick(const error_code& ec, ncp* poll) {
if (ec) {
return;
}
poll->on_writable([](const error_code& ec, ncp* poll) {
if (ec) {
return;
}
mvaddstr(1, 0, std::to_string(std::time(nullptr)).c_str());
refresh();
defer(poll);
});
}
int main() {
boost::asio::io_context io_context;
ncp poll(io_context);
poll.init();
callback cb = [&cb](const error_code& ec, ncp* poll) {
if (!ec) reenter(poll->coro) for (;;) {
poll->session()->chr = getch() | A_UNDERLINE;
yield poll->on_writable(cb);
mvaddch(0, poll->session()->num_chr++, poll->session()->chr);
refresh();
yield poll->on_readable(cb);
}
};
poll.on_writable([&cb](const error_code& ec, ncp* poll) {
if (!ec) {
curs_set(0);
cbreak();
noecho();
refresh();
poll->on_readable(cb);
}
});
defer(&poll);
io_context.run();
}