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