/*----------------------------------------------------------------------------- * eventmanager.cpp * Copyright (C) 2003, 2004, 2005 Akito Nozaki * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include #include #include NAMESPACE_TANOSHI { EventManager::EventManager() : _poller(new PollerPoll) { _poller->init(); _events.clear(); _id = 100; } EventManager::~EventManager() { delete _poller; } void EventManager::addEvent(Event *event) { if(event->id() == 0) event->setId(++_id); if(event->fd()) { if(_poller->getMask(event->fd()) == ENOENT) { PollerEvent *p = _poller->add(event->fd(), event->events()); p->eventReady.connect( sigc::mem_fun(this, &EventManager::poller_dataReady)); } else { _poller->setMask(event->fd(), event->events()); } } _events[event->id()] = event; } void EventManager::removeEvent(Event *event) { EventData::iterator find = _events.find(event->id()); if(find != _events.end()) { if((*find).second->fd()) _poller->del( (*find).second->fd() ); _events.erase(find); } } void EventManager::poller_dataReady(int fd, short revent) { _fdtorevent[fd] = revent; } void EventManager::processEvent() { while(_eventqueue.size()) { int id = _eventqueue.front(); _eventqueue.pop(); EventData::iterator find = _events.find(id); if(find != _events.end()) { if(_fdtorevent.find((*find).second->fd()) != _fdtorevent.end()) (*find).second->setRevents(_fdtorevent[(*find).second->fd()]); else (*find).second->setRevents(0); (*find).second->event((*find).second); } } } void EventManager::sleep() { _sleep = -1; // get events sleep time!! EventData::iterator end = _events.end(); for(EventData::iterator i = _events.begin(); i != end; i++) { int sleep = (*i).second->sleep(); _eventqueue.push((*i).first); if(sleep >= 0) { if(_sleep == -1) _sleep = sleep; else if(_sleep > sleep) _sleep = sleep; } } _fdtorevent.clear(); _poller->waitAndExecEvents(_sleep); } bool EventManager::event(Event *e) { if(e->id() != _id) return false; processEvent(); return true; } }