Merge branch 'master' of https://git.maemo.org/projects/qtmeetings
[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( *(iCurrentRoom) ) )
170         {
171                 emit roomStatusChanged( status, until );
172         }
173 }
174
175 void Engine::fetchMeetingDetails( Meeting *aMeeting )
176 {
177         qDebug() << "Engine::fetchMeetingDetails( Meeting* )";
178         iCommunication->fetchMeetingDetails( *aMeeting );
179 }
180
181 void Engine::meetingsFetched( const QList<Meeting*> &aMeetings )
182 {
183         qDebug() << "Engine::meetingsFetched( const QList<Meeting*> & )";
184         // TODO: should check if this week's meetings were fetched
185         if( iCommunicationFailed || !iCurrentWeekFetched )
186         {
187                 iCurrentWeekFetched = true;
188                 iCommunicationFailed = false;
189                 iUIManager->connectionEstablished();
190         }
191
192         for ( int i = 0; i < iMeetings.count(); ++i ) 
193         {
194                 Meeting* m = iMeetings.takeAt( i );
195                 delete m;
196         }
197         iMeetings.clear();
198         for ( int i = 0; i < aMeetings.count(); ++i ) {
199                 Meeting* m = new Meeting( *( aMeetings.at( i ) ) );
200                 iMeetings.append( m );
201         }
202
203         // refresh room status info
204         roomStatusInfoNeeded( iCurrentRoom /*defaultRoom()*/ );
205 }
206
207 void Engine::errorHandler( int aCode, const QString &aAddInfo )
208 {       
209         if( aCode >= 100 && aCode < 150 )
210         {
211                 iCommunicationFailed = true;
212                 if ( iUIManager != 0 ) iUIManager->connectionLost();
213         }
214         if ( iWindowManager != 0 )
215         {
216                 iWindowManager->error( ErrorMapper::codeToString( aCode, aAddInfo ) );
217         }
218 }
219
220 void Engine::fetchMeetings( const QDateTime &aFrom, const QDateTime &aUntil, const Room *aIn )
221 {
222         qDebug()
223                         << "Engine::fetchMeetings( const QDateTime &, const QDateTime &, const Room * )";
224         iCommunication->fetchMeetings(aFrom, aUntil, *aIn);
225 }
226
227 void Engine::cancelFetchMeetingDetails()
228 {
229         iCommunication->cancelFetchMeetingDetails();
230 }
231
232 void Engine::shownWeekChanged( QDate aFrom )
233 {
234         qDebug() << "[Engine::shownWeekChanged] <Invoked>";
235         QDateTime from( aFrom );
236         QDateTime to( aFrom.addDays( 7 ), QTime( 23, 59 ) );
237         qDebug() << "[Engine::shownWeekChanged] <From " << aFrom.toString( "d.m. h:mm" ) << " to " << to.toString( "d.m. h:mm" ) << ">";
238         iCommunication->fetchMeetings( from, to, *iCurrentRoom/*defaultRoom()*/ );
239 }
240
241 void Engine::changeDeviceMode()
242 {
243         connect( iDevice, SIGNAL( changeModeFailed() ), this, SLOT( changeModeFailed() ) );
244         iAutoRefresh->stop(); // Stop the meeting update
245         iDevice->changeMode();
246 }
247
248 void Engine::changeModeFailed()
249 {
250         qDebug() << "Engine::progressBarCancelled()";
251         iAutoRefresh->start(); //we start the metting updating
252 }
253
254 void Engine::initUserInterface()
255 {
256         qDebug() << "[Engine::initUserInterface] <Invoked>";
257         
258         // Initialize the window manager and connect what ever signals can be connected
259         iWindowManager = new WindowManager;
260         // Create the UIManager which internally handles most of the UI actions
261         iUIManager = new UIManager( this, iWindowManager );
262         
263         connect( iWindowManager, SIGNAL( eventDetected() ), this, SLOT( handleViewEvent() ) );
264         connect( iWindowManager, SIGNAL( previousViewRestored() ), iUIManager, SLOT( previousViewRestored() ) );
265         connect( iWindowManager, SIGNAL( dialogActivated() ), this, SLOT( dialogActivated() ) );
266         connect( iWindowManager, SIGNAL( dialogDeactivated() ), this, SLOT( dialogDeactivated() ) );
267         
268         // Show the UI
269         iWindowManager->setWindowState( Qt::WindowMaximized );
270         iWindowManager->show();
271         iUIManager->showMainView();
272         
273         // This triggers the meeting fetching
274         iUIManager->currentRoomChanged( this->iCurrentRoom );
275         
276         qDebug() << "[Engine::initUserInterface] <Finished>";
277 }
278
279 void Engine::handleViewEvent()
280 {
281         if ( iIdleTimeCounter != 0 && iIdleTimeCounter->isActive())
282         {
283                 // Restart the idle time counter when view event is received
284                 iIdleTimeCounter->stop();
285                 iIdleTimeCounter->start();
286         }
287 }
288
289 void Engine::initConfiguration()
290 {
291         iConfiguration = Configuration::instance();
292         if ( iConfiguration == 0 )
293         {
294                 QTimer::singleShot( 0, this, SLOT( closeApplication() ) );
295         }
296         iCurrentRoom = iConfiguration->defaultRoom();
297 }
298
299 void Engine::connectSignals()
300 {
301         // Connect engine objects signals to UIManager
302         connect( iClock, SIGNAL( tick( QDateTime ) ), iUIManager, SLOT( updateTime( QDateTime ) ) );
303         connect( iIdleTimeCounter, SIGNAL( timeout() ) , iUIManager, SLOT( roomStatusIndicatorRequested() ) );
304         
305         iUIManager->connectDeviceManager( iDevice );
306         iUIManager->connectCommunicationManager( iCommunication );
307 }
308
309 void Engine::initCommunication()
310 {
311         // initialize communication
312         iCommunication = new CommunicationManager( *(iConfiguration->connectionSettings()) );
313         connect( iCommunication, SIGNAL( error( int, CommunicationManager::CommunicationType  ) ),
314                         this, SLOT( errorHandler( int ) ) );
315         connect( iCommunication, SIGNAL( meetingsFetched( const QList<Meeting*>& ) ),
316                         this, SLOT( meetingsFetched( const QList<Meeting*>& ) ) );
317 }
318
319 void Engine::initDevice()
320 {
321         // create device manager
322         iDevice = new DeviceManager( iConfiguration->startupSettings() );
323         connect( iDevice, SIGNAL( error( int, const QString& ) ), this, SLOT( errorHandler( int, const QString& ) ) );  
324         iDevice->initDeviceManager();
325 }
326
327 void Engine::dialogActivated()
328 {
329         if ( iIdleTimeCounter != 0 )
330         {
331                 iIdleTimeCounter->stop();
332         }
333 }
334
335 void Engine::dialogDeactivated()
336 {
337         if ( iIdleTimeCounter != 0 )
338         {
339                 iIdleTimeCounter->start();
340         }
341 }
342
343 void Engine::previousViewRestored()
344 {
345         if ( iIdleTimeCounter != 0 )
346         {
347                 iIdleTimeCounter->start();
348         }
349 }
350
351 void Engine::stopIdleTimeCounter()
352 {
353         if ( iIdleTimeCounter != 0 )
354         {
355                 iIdleTimeCounter->stop();
356         }
357 }
358
359 void Engine::startIdleTimeCounter()
360 {
361         if ( iIdleTimeCounter != 0 )
362         {
363                 iIdleTimeCounter->start();
364         }
365 }
366
367 void Engine::currentRoomChanged(Room *aRoom)
368 {
369         qDebug() << "[Engine::currentRoomChanged] <invoked>";
370         iCurrentRoom = aRoom;
371         roomStatusInfoNeeded( iCurrentRoom );
372 }