| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- #include <algorithm>
- #include <chrono>
- #include <cstdio>
- #include <ctime>
- #include <functional>
- #include <iostream>
- #include <memory>
- #include <ncurses.h>
- #include <string>
- #include <thread>
- #include <unistd.h>
- #include <vector>
- /*
- todo
- figure out namespaces, using, and auto
- formalize timer struct
- read about std function and std bind
- try to do with objects / classes instead
- centralize into event sender and subscriber
- */
- /*
- find a way to eject timer
- find a way to group timers into an object
- */
- struct mysecondsdisplay {
- int intervalcount = 10;
- void myupdatedisplay() {
- intervalcount -= 1;
- mvprintw(intervalcount, intervalcount, "hello %d", intervalcount);
- if (intervalcount < 1) {
- intervalcount = 10;
- }
- }
- };
- // calls callbackfunc on specified interval based on accumulated deltatime
- class timer {
- public:
- std::string name;
- std::function<void()> callbackfunc;
- timer(std::string name, size_t interval_input, std::function<void()> callback)
- : name(name), callbackfunc(callback), time_interval(interval_input) {}
- // callbackfunc once enough time has accumulated
- void updatetime(double DeltaTime) {
- accumulator += DeltaTime;
- if (accumulator >= time_interval) {
- accumulator -= time_interval;
- callbackfunc();
- }
- }
- private:
- double accumulator = 0;
- double time_interval = 1; // only display every 1 seconds
- };
- // manage collection of timers
- class timermanager {
- std::vector<std::unique_ptr<timer>> timers;
- public:
- void addtimer(std::unique_ptr<timer> input_timer) {
- timers.push_back(std::move(input_timer)); }
- void updatetimers(double dtime) {
- for (auto &mytimer : timers) {
- mytimer->updatetime(dtime);
- mvprintw(12, 0, "updated timer %s", mytimer->name.c_str());
- };
- refresh();
- }
- };
- int main() {
- initscr();
- nodelay(stdscr, FALSE);
- refresh();
- // printf("verification\n");
- auto starttime = std::chrono::system_clock::now(); // initial starttime
- mysecondsdisplay secdisp;
- auto clocktimer = std::make_unique<timer>("secondsprinter", 1, [&]() { secdisp.myupdatedisplay(); });
- timermanager mytimermanager;
- mytimermanager.addtimer(std::move(clocktimer));
-
- mvprintw(5, 5, "timer added");
- // calculate delta between current and previous time
- while (true) {
- auto currenttime = std::chrono::system_clock::now();
- std::chrono::duration<double> myDeltaTime = currenttime - starttime;
- double dtime = myDeltaTime.count();
- // mvprintw(11, 11, "dtime: %f", dtime);
- // clocktimer.updatetime(dtime);
- mytimermanager.updatetimers(dtime);
- starttime = currenttime;
- std::this_thread::sleep_for(std::chrono::milliseconds(500));
- }
- getch();
- endwin();
- return 0;
- }
|