c7aad8b12f81d2c5b750c30661312922f3007f04
[qtmeetings] / src / BusinessLogic / Engine.cpp
1 #include "Engine.h"
2 #include "Room.h"
3 #include "Meeting.h"
4 #include "ConnectionSettings.h"
5 #include "Configuration.h"
6 #include "DisplaySettings.h"
7 #include "CommunicationManager.h"
8 // #include "DeviceManager.h"
9 #include "Clock.h"
10 #include "ErrorMapper.h"
11 #include "UIManager.h"
12
13 #include <QApplication>
14 #include <QTimer>
15 #include <QList>
16 #include <QtDebug>
17
18 QTime Engine::endOfTheDay = QTime( 23, 59, 0, 0); // end of the day is 11:59pm
19 const int IDLE_TIME_MULTIPLIER = 60000; // Multiplies milliseconds to minutes
20
21 // Macro to help deleting objects. This could be global.
22 #define QT_DELETE(X) \
23         if ( X != 0 ) \
24         { \
25                 delete X; \
26                 X = 0; \
27         }
28
29
30 Engine::Engine() :
31                 iClock( 0 ), iConfiguration( 0 ), iCommunication( 0 ),
32                 iWindowManager( 0 ), iUIManager( 0 )
33 {
34         qDebug() << "Engine::Engine()";
35         iCommunicationFailed = false;
36         iCurrentWeekFetched = false;
37         
38         initConfiguration();
39         initDevice();
40         initCommunication();
41         initUserInterface();
42         
43         //initialize idle time counter
44         iIdleTimeCounter = new QTimer();
45         iIdleTimeCounter->setSingleShot( true);
46         iIdleTimeCounter->setInterval(IDLE_TIME_MULTIPLIER * iConfiguration->displaySettings()->screensaver() );
47         iIdleTimeCounter->start();
48
49         // create application clock
50         iClock = new Clock;
51         connect( iClock, SIGNAL( tick( QDateTime ) ), this, SLOT( tick( QDateTime )/*checkStatusOfAllRooms()*/ ) );
52         // connect( iClock, SIGNAL( tick( QDateTime ) ), iWindowManager, SLOT( distributeDateTimeInfo( QDateTime ) ) );
53
54         // Create auto refresh timer
55         iAutoRefresh = new QTimer;
56         iAutoRefresh->setInterval(iConfiguration->connectionSettings()->refreshInterval() * 1000);
57         iAutoRefresh->start();
58         connect( iAutoRefresh, SIGNAL( timeout() ), iAutoRefresh, SLOT( start() ) );
59         // connect( iAutoRefresh, SIGNAL( timeout() ), this, SLOT( fetchMeetings() ) );
60         
61         if( iDevice->currentOperationMode() == DeviceManager::KioskMode )
62         {
63                 iWindowManager->setFullscreen();
64         }
65
66         connectSignals();
67         
68         // QTimer::singleShot( 0, this, SLOT( fetchMeetings() ) );
69
70         // TODO: continue implementation
71 }
72
73 Engine::~Engine()
74 {
75         qDebug() << "Engine::~Engine()";
76         while ( !iMeetings.isEmpty() )
77                 delete iMeetings.takeFirst();
78         
79         if ( iIdleTimeCounter != 0 )
80         {
81                 iIdleTimeCounter->stop();
82                 delete iIdleTimeCounter;
83                 iIdleTimeCounter = 0;
84         }
85         QT_DELETE( iClock );
86         QT_DELETE( iDevice );
87
88         QT_DELETE( iUIManager );
89         QT_DELETE( iWindowManager );
90 }
91
92 void Engine::closeApplication()
93 {
94         qDebug() << "Engine::closeApplication()";
95         // closes application after 1 second
96         QTimer::singleShot( 1000, QApplication::instance(), SLOT( quit() ));
97 }
98
99 Room* Engine::defaultRoom()
100 {
101         qDebug() << "Engine::defaultRoom()";
102         return iConfiguration->defaultRoom();
103 }
104
105 void Engine::checkStatusOfAllRooms()
106 {
107         // TODO: Check if date has changed
108         //      qDebug() << "Engine::checkStatusOfAllRooms()";
109         // iterate trough on the rooms
110         for (int i = 0; i < iConfiguration->rooms().count(); i++)
111         {
112                 // and check the status
113                 roomStatusInfoNeeded( iConfiguration->rooms().at(i) );
114         }
115 }
116
117 int Engine::indexOfMeetingAt(Room *aRoom, QDateTime aAt)
118 {
119 //      qDebug() << "Engine::indexOfMeetingAt( Room *, QDateTime )";
120         for ( int i = 0; i < iMeetings.count(); i++ )
121         {
122                 // exchange server ensures that there is only one meeting in a room at a specified time
123                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt() <= aAt && iMeetings.at( i )->endsAt() >= aAt)
124                 {
125                         return i;
126                 }
127         }
128         return -1;
129 }
130
131 int Engine::indexOfMeetingAfter(Room *aRoom, QDateTime aAfter)
132 {
133 //      qDebug() << "Engine::indexOfMeetingAfter( Room *, QDateTime )";
134         // seeks for the next meeting on the SAME DAY
135         int min = -1;
136         for (int i = 0; i < iMeetings.count(); i++)
137         {
138                 // if the meeting is in the same room, on the same day but after the specified time
139                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt().date() == aAfter.date() && iMeetings.at( i )->startsAt() > aAfter)
140                 {
141                         // if there was not any meeting find yet or the previously found is a later one then the (i)th
142                         if (min == -1 || iMeetings.at( min )->startsAt() > iMeetings.at( i )->startsAt() )
143                         {
144                                 min = i;
145                         }
146                 }
147         }
148         return min;
149 }
150
151 void Engine::roomStatusInfoNeeded(Room *aRoom)
152 {
153 //      qDebug() << "Engine::roomStatusInfoNeeded( Room * )";
154         if ( aRoom == 0 )
155         {
156                 return;
157         }
158
159         int indexOfCurrentMeeting = indexOfMeetingAt(aRoom, iClock->datetime() );
160         int indexOfNextMeeting = indexOfMeetingAfter(aRoom, iClock->datetime() );
161
162         // if there is no meeting, then status is Free; otherwise Busy
163         Room::Status status = (indexOfCurrentMeeting == -1 ) ? Room::FreeStatus : Room::BusyStatus;
164         // if room is Busy, then check end time, otherwise...
165         QTime until = (status == Room::BusyStatus ) ? iMeetings.at( indexOfCurrentMeeting )->endsAt().time() :
166         // ...if there is meeting following on the same day then check end time, otherwise end is the of the working day
167         ( ( indexOfNextMeeting != -1 ) ? iMeetings.at( indexOfNextMeeting )->startsAt().time() : Engine::endOfTheDay );
168
169         //currently works only for default room
170         if ( aRoom->equals( *(iCurrentRoom) ) )
171         {
172                 emit roomStatusChanged( status, until );
173         }
174 }
175
176 void Engine::fetchMeetingDetails( Meeting *aMeeting )
177 {
178         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
179         iCommunication->fetchMeetingDetails( *aMeeting );
180 }
181
182 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
183 {
184         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
185         // TODO: should check if this week's meetings were fetched
186         if( iCommunicationFailed || !iCurrentWeekFetched )
187         {
188                 iCurrentWeekFetched = true;
189                 iCommunicationFailed = false;
190                 iUIManager->connectionEstablished();
191         }
192
193         for ( int i = 0; i < iMeetings.count(); ++i ) 
194         {
195                 // TODO: Check if these are current week's meetings and do not overwrite those
196                 Meeting* m = iMeetings.takeAt( i );
197                 delete m;
198         }
199         iMeetings.clear();
200         for ( int i = 0; i < aMeetings.count(); ++i ) {
201                 Meeting* m = new Meeting( *( aMeetings.at( i ) ) );
202                 iMeetings.append( m );
203         }
204
205         // refresh room status info
206         roomStatusInfoNeeded( iCurrentRoom /*defaultRoom()*/ );
207 }
208
209 void Engine::errorHandler( int aCode, const QString &aAddInfo )
210 {       
211         if( aCode >= 100 && aCode < 150 )
212         {
213                 iCommunicationFailed = true;
214                 if ( iUIManager != 0 ) iUIManager->connectionLost();
215         }
216         if ( iWindowManager != 0 )
217         {
218                 iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
219         }
220 }
221
222 void Engine::fetchMeetings( const int aWeek, const int aYear, const Room *aIn )
223 {
224         qDebug()
225                         << "Engine::fetchMeetings( const int aWeek, const int aYear, const Room * )";
226         iCommunication->fetchMeetings(aWeek, aYear, *aIn);
227 }
228
229 void Engine::cancelFetchMeetingDetails()
230 {
231         iCommunication->cancelFetchMeetingDetails();
232 }
233
234 void Engine::shownWeekChanged( QDate aFrom )
235 {
236         qDebug() << "[Engine::shownWeekChanged] <Invoked>";
237         iCommunication->fetchMeetings( aFrom.weekNumber(), aFrom.year(), *iCurrentRoom/*defaultRoom()*/ );
238 }
239
240 void Engine::changeDeviceMode()
241 {
242         connect( iDevice, SIGNAL( changeModeFailed() ), this, SLOT( changeModeFailed() ) );
243         iAutoRefresh->stop(); // Stop the meeting update
244         iDevice->changeMode();
245 }
246
247 void Engine::changeModeFailed()
248 {
249         qDebug() << "Engine::progressBarCancelled()";
250         iAutoRefresh->start(); //we start the metting updating
251 }
252
253 void Engine::initUserInterface()
254 {
255         qDebug() << "[Engine::initUserInterface] <Invoked>";
256         
257         // Initialize the window manager and connect what ever signals can be connected
258         iWindowManager = new WindowManager;
259         // Create the UIManager which internally handles most of the UI actions
260         iUIManager = new UIManager( this, iWindowManager );
261         
262         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
263         connect( iWindowManager, SIGNAL( previousViewRestored() ), iUIManager, SLOT( previousViewRestored() ) );
264         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
265         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
266         
267         // Show the UI
268         iWindowManager->setWindowState( Qt::WindowMaximized );
269         iWindowManager->show();
270         iUIManager->showMainView();
271         
272         // This triggers the meeting fetching
273         iUIManager->currentRoomChanged( this->iCurrentRoom );
274         
275         qDebug() << "[Engine::initUserInterface] <Finished>";
276 }
277
278 void Engine::handleViewEvent()
279 {
280         if ( iIdleTimeCounter != 0 && iIdleTimeCounter->isActive())
281         {
282                 // Restart the idle time counter when view event is received
283                 iIdleTimeCounter->stop();
284                 iIdleTimeCounter->start();
285         }
286 }
287
288 void Engine::initConfiguration()
289 {
290         iConfiguration = Configuration::instance();
291         if ( iConfiguration == 0 )
292         {
293                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
294         }
295         iCurrentRoom = iConfiguration->defaultRoom();
296 }
297
298 void Engine::connectSignals()
299 {
300         // Connect engine objects signals to UIManager
301         connect( iClock, SIGNAL( tick( QDateTime ) ), iUIManager, SLOT( updateTime( QDateTime ) ) );
302         connect( iIdleTimeCounter, SIGNAL( timeout() ) , iUIManager, SLOT( roomStatusIndicatorRequested() ) );
303         
304         iUIManager->connectDeviceManager( iDevice );
305         iUIManager->connectCommunicationManager( iCommunication );
306 }
307
308 void Engine::initCommunication()
309 {
310         // initialize communication
311         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
312         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
313                         this, SLOT( errorHandler( int ) ) );
314         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
315                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
316 }
317
318 void Engine::initDevice()
319 {
320         // create device manager
321         iDevice = new DeviceManager( iConfiguration->startupSettings() );
322         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
323         iDevice->initDeviceManager();
324 }
325
326 void Engine::dialogActivated()
327 {
328         if ( iIdleTimeCounter != 0 )
329         {
330                 iIdleTimeCounter->stop();
331         }
332 }
333
334 void Engine::dialogDeactivated()
335 {
336         if ( iIdleTimeCounter != 0 )
337         {
338                 iIdleTimeCounter->start();
339         }
340 }
341
342 void Engine::previousViewRestored()
343 {
344         if ( iIdleTimeCounter != 0 )
345         {
346                 iIdleTimeCounter->start();
347         }
348 }
349
350 void Engine::stopIdleTimeCounter()
351 {
352         if ( iIdleTimeCounter != 0 )
353         {
354                 iIdleTimeCounter->stop();
355         }
356 }
357
358 void Engine::startIdleTimeCounter()
359 {
360         if ( iIdleTimeCounter != 0 )
361         {
362                 iIdleTimeCounter->start();
363         }
364 }
365
366 void Engine::currentRoomChanged(Room *aRoom)
367 {
368         qDebug() << "[Engine::currentRoomChanged] <invoked>";
369         iCurrentRoom = aRoom;
370         roomStatusInfoNeeded( iCurrentRoom );
371 }
372
373 void Engine::tick( QDateTime aCurrentDateTime )
374 {
375         // Called once every second
376         checkStatusOfAllRooms();
377         if( aCurrentDateTime.date() !=  iCurrentDate)
378         {
379                 // Check if week has changed and fetch meetings for this week
380                 if( aCurrentDateTime.date().weekNumber() != iCurrentDate.weekNumber()
381                         || aCurrentDateTime.date().year() != iCurrentDate.year() )
382                 {
383                         qDebug() << "[Engine::tick] detected week change, fetching meetings";
384                         fetchMeetings( aCurrentDateTime.date().weekNumber(), aCurrentDateTime.date().year(), iCurrentRoom );
385                 }
386         }
387         iCurrentDate = aCurrentDateTime.date();
388 }