00001 /* 00002 * Copyright (c) 2010 Soren Dreijer 00003 * Licensed under the simplified BSD license. 00004 * See Documentation/Licenses/BSD-simplified.txt for more information. 00005 */ 00006 00007 #pragma once 00008 00009 #include <vector> 00010 #include <boost/thread/mutex.hpp> 00011 #include <boost/thread/condition_variable.hpp> 00012 00013 #include "Swiften/EventLoop/EventLoop.h" 00014 00015 // DESCRIPTION: 00016 // 00017 // All interaction with Swiften should happen on the same thread, such as the main GUI thread, 00018 // since the library isn't thread-safe. 00019 // For applications that don't have a main loop, such as WPF and MFC applications, we need a 00020 // different approach to process events from Swiften. 00021 // 00022 // The SingleThreadedEventLoop class implements an event loop that can be used from such applications. 00023 // 00024 // USAGE: 00025 // 00026 // Spawn a new thread in the desired framework and call SingleThreadedEventLoop::waitForEvents(). The method 00027 // blocks until a new event has arrived at which time it'll return, or until the wait is canceled 00028 // at which time it throws EventLoopCanceledException. 00029 // 00030 // When a new event has arrived and SingleThreadedEventLoop::waitForEvents() returns, the caller should then 00031 // call SingleThreadedEventLoop::handleEvents() on the main GUI thread. For WPF applications, for instance, 00032 // the Dispatcher class can be used to execute the call on the GUI thread. 00033 // 00034 00035 namespace Swift { 00036 class SingleThreadedEventLoop : public EventLoop { 00037 public: 00038 class EventLoopCanceledException : public std::exception { }; 00039 00040 public: 00041 SingleThreadedEventLoop(); 00042 ~SingleThreadedEventLoop(); 00043 00044 // Blocks while waiting for new events and returns when new events are available. 00045 // Throws EventLoopCanceledException when the wait is canceled. 00046 void waitForEvents(); 00047 void handleEvents(); 00048 void stop(); 00049 00050 virtual void post(const Event& event); 00051 00052 private: 00053 bool shouldShutDown_; 00054 std::vector<Event> events_; 00055 boost::mutex eventsMutex_; 00056 boost::condition_variable eventsAvailable_; 00057 }; 00058 }