Merge branch 'master' into dev_local
[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( 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 //      qDebug() << "Engine::checkStatusOfAllRooms()";
108         // iterate trough on the rooms
109         for (int i = 0; i < iConfiguration->rooms().count(); i++)
110         {
111                 // and check the status
112                 roomStatusInfoNeeded(iConfiguration->rooms().at(i) );
113         }
114 }
115
116 int Engine::indexOfMeetingAt(Room *aRoom, QDateTime aAt)
117 {
118 //      qDebug() << "Engine::indexOfMeetingAt( Room *, QDateTime )";
119         for ( int i = 0; i < iMeetings.count(); i++ )
120         {
121                 // exchange server ensures that there is only one meeting in a room at a specified time
122                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt() <= aAt && iMeetings.at( i )->endsAt() >= aAt)
123                 {
124                         return i;
125                 }
126         }
127         return -1;
128 }
129
130 int Engine::indexOfMeetingAfter(Room *aRoom, QDateTime aAfter)
131 {
132 //      qDebug() << "Engine::indexOfMeetingAfter( Room *, QDateTime )";
133         // seeks for the next meeting on the SAME DAY
134         int min = -1;
135         for (int i = 0; i < iMeetings.count(); i++)
136         {
137                 // if the meeting is in the same room, on the same day but after the specified time
138                 if (aRoom->equals(iMeetings.at( i )->room() ) && iMeetings.at( i )->startsAt().date() == aAfter.date() && iMeetings.at( i )->startsAt() > aAfter)
139                 {
140                         // if there was not any meeting find yet or the previously found is a later one then the (i)th
141                         if (min == -1 || iMeetings.at( min )->startsAt() > iMeetings.at( i )->startsAt() )
142                         {
143                                 min = i;
144                         }
145                 }
146         }
147         return min;
148 }
149
150 void Engine::roomStatusInfoNeeded(Room *aRoom)
151 {
152 //      qDebug() << "Engine::roomStatusInfoNeeded( Room * )";
153         if ( aRoom == 0 )
154         {
155                 return;
156         }
157
158         int indexOfCurrentMeeting = indexOfMeetingAt(aRoom, iClock->datetime() );
159         int indexOfNextMeeting = indexOfMeetingAfter(aRoom, iClock->datetime() );
160
161         // if there is no meeting, then status is Free; otherwise Busy
162         Room::Status status = (indexOfCurrentMeeting == -1 ) ? Room::FreeStatus : Room::BusyStatus;
163         // if room is Busy, then check end time, otherwise...
164         QTime until = (status == Room::BusyStatus ) ? iMeetings.at( indexOfCurrentMeeting )->endsAt().time() :
165         // ...if there is meeting following on the same day then check end time, otherwise end is the of the working day
166         ( ( indexOfNextMeeting != -1 ) ? iMeetings.at( indexOfNextMeeting )->startsAt().time() : Engine::endOfTheDay );
167
168         //currently works only for deafult room
169 //      if( aRoom->equals( *(defaultRoom() ) ) )
170 //              iWindowManager->roomStatusChanged( aRoom, status, until );
171 }
172
173 /*
174 void Engine::fetchMeetings()
175 {
176         qDebug() << "Engine::fetchMeetings for " << iCurrentRoom;
177         QDateTime from( iWindowManager->weeklyView()->beginnigOfShownWeek() );
178         QDateTime to( from.addDays( 7 ) );
179         // fetchMeetings( from, to, iWindowManager->weeklyView()->currentRoom() );
180         // Signal is connected to the currentRoomChanged slot which keeps the iCurrentRoom up to date
181         fetchMeetings( from, to, iCurrentRoom );
182 }
183 */
184
185 void Engine::fetchMeetingDetails( Meeting *aMeeting )
186 {
187         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
188 /*      iWindowManager->showProgressBar(tr("Please Wait"), true);
189         iWindowManager->updateProgressBar(tr("Fetching Meeting Details...") );
190         connect(iWindowManager, 
191         SIGNAL( progressBarCancelled() ), this, 
192         SLOT( fetchMeetingDetailsCancelled() ));
193         iCommunication->fetchMeetingDetails( *aMeeting); */
194         iCommunication->fetchMeetingDetails( *aMeeting );
195 }
196
197 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
198 {
199         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
200         // TODO: should check if this week's meetings were fetched
201         if( iCommunicationFailed || !iCurrentWeekFetched )
202         {
203                 iCurrentWeekFetched = true;
204                 iCommunicationFailed = false;
205                 iUIManager->connectionEstablished();
206         }
207
208         for ( int i = 0; i < iMeetings.count(); ++i ) 
209         {
210                 Meeting* m = iMeetings.takeAt( i );
211                 delete m;
212         }
213         iMeetings.clear();
214         for ( int i = 0; i < aMeetings.count(); ++i ) {
215                 Meeting* m = new Meeting( *( aMeetings.at( i ) ) );
216                 iMeetings.append( m );
217         }
218
219         // refresh room status info
220         roomStatusInfoNeeded( defaultRoom() );
221 }
222
223 void Engine::errorHandler( int aCode, const QString &aAddInfo )
224 {       
225         if( aCode >= 100 && aCode < 150 )
226         {
227                 iCommunicationFailed = true;
228                 if ( iUIManager != 0 ) iUIManager->connectionLost();
229         }
230         if ( iWindowManager != 0 )
231         {
232                 iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
233         }
234 }
235
236 void Engine::fetchMeetings( const QDateTime &aFrom, const QDateTime &aUntil, const Room *aIn )
237 {
238         qDebug()
239                         << "Engine::fetchMeetings( const QDateTime &, const QDateTime &, const Room * )";
240         iCommunication->fetchMeetings(aFrom, aUntil, *aIn);
241 }
242
243 void Engine::cancelFetchMeetingDetails()
244 {
245         iCommunication->cancelFetchMeetingDetails();
246 }
247
248 void Engine::shownWeekChanged( QDate aFrom )
249 {
250         qDebug() << "[Engine::shownWeekChanged] <Invoked>";
251         QDateTime from( aFrom );
252         QDateTime to( aFrom.addDays( 7 ), QTime( 23, 59 ) );
253         qDebug() << "[Engine::shownWeekChanged] <From " << aFrom.toString( "d.m. h:mm" ) << " to " << to.toString( "d.m. h:mm" ) << ">";
254         iCommunication->fetchMeetings( from, to, *defaultRoom() );
255 //      fetchMeetings( from, to, iWindowManager->weeklyView()->currentRoom() );
256 }
257
258 void Engine::changeDeviceMode()
259 {
260         connect( iDevice, SIGNAL( changeModeFailed() ), this, SLOT( changeModeFailed() ) );
261         iAutoRefresh->stop(); // Stop the meeting update
262         iDevice->changeMode();
263 }
264
265 void Engine::changeModeFailed()
266 {
267         qDebug() << "Engine::progressBarCancelled()";
268         iAutoRefresh->start(); //we start the metting updating
269 }
270
271 void Engine::initUserInterface()
272 {
273         qDebug() << "[Engine::initUserInterface] <Invoked>";
274         
275         // Initialize the window manager and connect what ever signals can be connected
276         iWindowManager = new WindowManager;
277         // Create the UIManager which internally handles most of the UI actions
278         iUIManager = new UIManager( this, iWindowManager );
279         
280         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
281         connect( iWindowManager, SIGNAL( previousViewRestored() ), iUIManager, SLOT( previousViewRestored() ) );
282         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
283         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
284         
285         // Show the UI
286         iWindowManager->setWindowState( Qt::WindowMaximized );
287         iWindowManager->show();
288         iUIManager->showMainView();
289         
290         // This triggers the meeting fetching
291         iUIManager->currentRoomChanged( this->iCurrentRoom );
292         
293         qDebug() << "[Engine::initUserInterface] <Finished>";
294 }
295
296 void Engine::handleViewEvent()
297 {
298         if ( iIdleTimeCounter != 0 && iIdleTimeCounter->isActive())
299         {
300                 // Restart the idle time counter when view event is received
301                 iIdleTimeCounter->stop();
302                 iIdleTimeCounter->start();
303         }
304 }
305
306 void Engine::initConfiguration()
307 {
308         iConfiguration = Configuration::instance();
309         if ( iConfiguration == 0 )
310         {
311                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
312         }
313         iCurrentRoom = iConfiguration->defaultRoom();
314 }
315
316 void Engine::connectSignals()
317 {
318         // Connect engine objects signals to UIManager
319         connect( iClock, SIGNAL( tick( QDateTime ) ), iUIManager, SLOT( updateTime( QDateTime ) ) );
320         connect( iIdleTimeCounter, SIGNAL( timeout() ) , iUIManager, SLOT( roomStatusIndicatorRequested() ) );
321         
322         iUIManager->connectDeviceManager( iDevice );
323         iUIManager->connectCommunicationManager( iCommunication );
324 }
325
326 void Engine::initCommunication()
327 {
328         // initialize communication
329         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
330         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
331                         this, SLOT( errorHandler( int ) ) );
332         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
333                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
334 }
335
336 void Engine::initDevice()
337 {
338         // create device manager
339         iDevice = new DeviceManager( iConfiguration->startupSettings() );
340         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
341         iDevice->initDeviceManager();
342 }
343
344 void Engine::dialogActivated()
345 {
346         if ( iIdleTimeCounter != 0 )
347         {
348                 iIdleTimeCounter->stop();
349         }
350 }
351
352 void Engine::dialogDeactivated()
353 {
354         if ( iIdleTimeCounter != 0 )
355         {
356                 iIdleTimeCounter->start();
357         }
358 }
359
360 void Engine::previousViewRestored()
361 {
362         if ( iIdleTimeCounter != 0 )
363         {
364                 iIdleTimeCounter->start();
365         }
366 }
367
368 void Engine::stopIdleTimeCounter()
369 {
370         if ( iIdleTimeCounter != 0 )
371         {
372                 iIdleTimeCounter->stop();
373         }
374 }
375
376 void Engine::startIdleTimeCounter()
377 {
378         if ( iIdleTimeCounter != 0 )
379         {
380                 iIdleTimeCounter->start();
381         }
382 }
383
384 void Engine::currentRoomChanged(Room *aRoom)
385 {
386         qDebug() << "[Engine::currentRoomChanged] <invoked>";
387         iCurrentRoom = aRoom;
388 }