1
0
mirror of git://projects.qi-hardware.com/gmenu2x.git synced 2024-07-02 18:54:31 +03:00
gmenu2x/src/clock.cpp

110 lines
2.0 KiB
C++
Raw Normal View History

2013-07-22 06:54:09 +03:00
#include "clock.h"
2013-07-22 06:54:09 +03:00
#include "debug.h"
#include "inputmanager.h"
#include <sys/time.h>
2013-07-22 06:54:09 +03:00
static void notify()
2013-07-22 06:54:09 +03:00
{
SDL_UserEvent e = {
.type = SDL_USEREVENT,
.code = REPAINT_MENU,
.data1 = NULL,
.data2 = NULL,
};
/* Inject an user event, that will be handled as a "repaint"
* event by the InputManager */
SDL_PushEvent((SDL_Event *) &e);
}
extern "C" Uint32 clockCallbackFunc(Uint32 timeout, void *d);
class Clock::Forwarder {
static unsigned int clockCallbackFunc(Clock *clock, unsigned int timeout)
{
return clock->clockCallback(timeout);
}
friend Uint32 clockCallbackFunc(Uint32 timeout, void *d);
};
extern "C" Uint32 clockCallbackFunc(Uint32 timeout, void *d)
2013-07-22 06:54:09 +03:00
{
return Clock::Forwarder::clockCallbackFunc(static_cast<Clock *>(d), timeout);
}
2013-07-22 06:54:09 +03:00
unsigned int Clock::clockCallback(unsigned int timeout)
{
unsigned int now_ticks = SDL_GetTicks();
if (now_ticks > timeout_startms + timeout + 1000) {
2013-07-22 06:54:09 +03:00
DEBUG("Suspend occured, restarting timer\n");
timeout_startms = now_ticks;
2013-07-22 06:54:09 +03:00
return timeout;
}
resetTimer();
2013-07-22 06:54:09 +03:00
notify();
return 60000;
}
std::string Clock::getTime(bool is24)
2013-07-22 06:54:09 +03:00
{
char buf[9];
int h = hours;
bool pm = hours >= 12;
if (!is24 && pm)
h -= 12;
sprintf(buf, "%02i:%02i%s", h, minutes, is24 ? "" : (pm ? "pm" : "am"));
return std::string(buf);
2013-07-22 06:54:09 +03:00
}
int Clock::update()
2013-07-22 06:54:09 +03:00
{
struct timeval tv;
struct tm result;
gettimeofday(&tv, NULL);
localtime_r(&tv.tv_sec, &result);
minutes = result.tm_min;
hours = result.tm_hour;
DEBUG("Time updated: %02i:%02i\n", hours, minutes);
return result.tm_sec;
}
void Clock::resetTimer()
2013-07-22 06:54:09 +03:00
{
SDL_RemoveTimer(timer);
timer = NULL;
int secs = update();
addTimer((60 - secs) * 1000);
}
void Clock::addTimer(int timeout)
{
if (timeout < 1000 || timeout > 60000)
timeout = 60000;
timeout_startms = SDL_GetTicks();
timer = SDL_AddTimer(timeout, clockCallbackFunc, this);
2013-07-22 06:54:09 +03:00
if (timer == NULL)
ERROR("Could not initialize SDLTimer: %s\n", SDL_GetError());
}
Clock::Clock()
2013-07-22 06:54:09 +03:00
{
tzset();
int sec = update();
addTimer((60 - sec) * 1000);
}
Clock::~Clock()
{
SDL_RemoveTimer(timer);
}