Added Message class.
[situare] / src / ui / mainwindow.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6       Kaj Wallin - kaj.wallin@ixonos.com
7       Jussi Laitinen - jussi.laitinen@ixonos.com
8       Sami Rämö - sami.ramo@ixonos.com
9       Ville Tiensuu - ville.tiensuu@ixonos.com
10       Katri Kaikkonen - katri.kaikkonen@ixonos.com
11
12    Situare is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License
14    version 2 as published by the Free Software Foundation.
15
16    Situare is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with Situare; if not, write to the Free Software
23    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
24    USA.
25 */
26
27 #include <QAction>
28 #include <QApplication>
29 #include <QMenuBar>
30 #include <QMessageBox>
31 #include <QtAlgorithms>
32 #include <QtWebKit>
33
34 ///< @todo sort
35 #include "facebookservice/facebookauthentication.h"
36 #include "map/mapcommon.h"
37 #include "map/mapview.h"
38 #include "common.h"
39 #include "error.h"
40 #include "friendlistpanel.h"
41 #include "fullscreenbutton.h"
42 #include "indicatorbuttonpanel.h"
43 #include "logindialog.h"
44 #include "mapscale.h"
45 #include "meetpeoplepanel.h"
46 #include "panelcommon.h"
47 #include "routingpanel.h"
48 #include "tabbedpanel.h"
49 #include "searchdialog.h"
50 #include "settingsdialog.h"
51 #include "userinfopanel.h"
52 #include "zoombuttonpanel.h"
53
54
55 #include "mainwindow.h"
56
57 // These MUST BE HERE, compiling for Maemo fails if moved
58 #ifdef Q_WS_MAEMO_5
59 #include <QtMaemo5/QMaemo5InformationBox>
60 #include <QtGui/QX11Info>
61 #include <X11/Xatom.h>
62 #include <X11/Xlib.h>
63 #endif // Q_WS_MAEMO_5
64
65 #if defined(Q_WS_MAEMO_5) & defined(ARMEL)
66 #include "ossoabookdialog.h"
67 #endif
68
69 MainWindow::MainWindow(QWidget *parent)
70     : QMainWindow(parent),
71       m_errorShown(false),
72       m_loggedIn(false),
73       m_refresh(false),
74       m_mapCenterHorizontalShifting(0),
75       m_progressIndicatorCount(0),
76       m_crosshair(0),
77       m_email(), ///< @todo WTF?!?!?!?
78       m_password(),
79       m_webView(0),
80       m_fullScreenButton(0),
81       m_indicatorButtonPanel(0),
82       m_mapScale(0),
83       m_cookieJar(0)
84 {
85     qDebug() << __PRETTY_FUNCTION__;
86
87     buildMap();
88
89     // map view is the only widget which size & location is handled automatically by the system
90     // default functionality
91     setCentralWidget(m_mapView);
92
93     buildPanels();
94
95     createMenus();
96     setWindowTitle(tr("Situare"));
97
98     // set stacking order of widgets (from top to bottom)
99     // m_tabbedPanel is the topmost one
100     if (m_fullScreenButton) {
101         m_fullScreenButton->stackUnder(m_tabbedPanel);
102         m_crosshair->stackUnder(m_fullScreenButton);
103     } else {
104         m_crosshair->stackUnder(m_tabbedPanel);
105     }
106     m_zoomButtonPanel->stackUnder(m_crosshair);
107     m_indicatorButtonPanel->stackUnder(m_zoomButtonPanel);
108     m_osmLicense->stackUnder(m_indicatorButtonPanel);
109     m_mapScale->stackUnder(m_osmLicense);
110     m_mapView->stackUnder(m_mapScale);
111
112     grabZoomKeys(true);
113
114     // Set default screen size
115     resize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT);
116 #ifdef Q_WS_MAEMO_5
117     setAttribute(Qt::WA_Maemo5StackedWindow);
118 #endif
119 }
120
121 MainWindow::~MainWindow()
122 {
123     qDebug() << __PRETTY_FUNCTION__;
124
125     grabZoomKeys(false);
126
127     if(m_webView)
128         delete m_webView;
129
130     qDeleteAll(m_queue.begin(), m_queue.end());
131     m_queue.clear();
132
133     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
134     m_error_queue.clear();
135 }
136
137 void MainWindow::automaticUpdateDialogFinished(int result)
138 {
139     qDebug() << __PRETTY_FUNCTION__;
140
141     if (result == QMessageBox::Yes) {
142         readAutomaticLocationUpdateSettings();
143     } else {
144         QSettings settings(DIRECTORY_NAME, FILE_NAME);
145         settings.setValue(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false);
146         readAutomaticLocationUpdateSettings();
147     }
148
149     m_automaticUpdateLocationDialog->deleteLater();
150 }
151
152 void MainWindow::buildCrosshair()
153 {
154     qDebug() << __PRETTY_FUNCTION__;
155
156     m_crosshair = new QLabel(this);
157     QPixmap crosshairImage(":/res/images/sight.png");
158     m_crosshair->setPixmap(crosshairImage);
159     m_crosshair->setFixedSize(crosshairImage.size());
160     m_crosshair->hide();
161     m_crosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
162
163     connect(m_mapView, SIGNAL(viewResized(QSize)),
164             this, SLOT(moveCrosshair()));
165
166     connect(m_mapView, SIGNAL(horizontalShiftingChanged(int)),
167             this, SLOT(mapCenterHorizontalShiftingChanged(int)));
168 }
169
170 void MainWindow::buildFriendListPanel()
171 {
172     qDebug() << __PRETTY_FUNCTION__;
173
174     m_friendsListPanel = new FriendListPanel(this);
175
176     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
177             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
178
179     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
180             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
181
182     connect(m_friendsListPanel, SIGNAL(findFriend(GeoCoordinate)),
183             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
184
185     connect(this, SIGNAL(friendImageReady(User*)),
186             m_friendsListPanel, SLOT(friendImageReady(User*)));
187
188     connect(m_friendsListPanel, SIGNAL(routeToFriend(const GeoCoordinate&)),
189             this, SIGNAL(routeTo(const GeoCoordinate&)));
190
191     connect(m_friendsListPanel, SIGNAL(requestContactDialog(const QString &)),
192             this, SIGNAL(requestContactDialog(const QString &)));
193 }
194
195 void MainWindow::buildFullScreenButton()
196 {
197     qDebug() << __PRETTY_FUNCTION__;
198
199 #ifdef Q_WS_MAEMO_5
200     m_fullScreenButton = new FullScreenButton(this);
201
202     if (m_fullScreenButton) {
203         connect(m_fullScreenButton, SIGNAL(clicked()),
204                 this, SLOT(toggleFullScreen()));
205
206         connect(qApp, SIGNAL(showFullScreenButton()),
207                 m_fullScreenButton, SLOT(invoke()));
208     }
209 #endif // Q_WS_MAEMO_5
210 }
211
212 void MainWindow::buildIndicatorButtonPanel()
213 {
214     qDebug() << __PRETTY_FUNCTION__;
215
216     m_indicatorButtonPanel = new IndicatorButtonPanel(this);
217
218     connect(m_indicatorButtonPanel, SIGNAL(autoCenteringTriggered(bool)),
219         this, SIGNAL(autoCenteringTriggered(bool)));
220
221     connect(m_mapView, SIGNAL(viewResized(QSize)),
222             m_indicatorButtonPanel, SLOT(screenResized(QSize)));
223
224     connect(this, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
225             m_indicatorButtonPanel, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
226
227     connect(m_indicatorButtonPanel, SIGNAL(draggingModeTriggered()),
228             this, SIGNAL(draggingModeTriggered()));
229 }
230
231 void MainWindow::buildInformationBox(const QString &message, bool modal)
232 {
233     qDebug() << __PRETTY_FUNCTION__;
234
235     QString errorMessage = message;
236
237 #ifdef Q_WS_MAEMO_5
238
239     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
240
241     if(modal) {
242         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
243         // extra line changes are needed to make error notes broader
244         errorMessage.prepend("\n");
245         errorMessage.append("\n");
246     } else {
247         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
248     }
249     QLabel *label = new QLabel(msgBox);
250     label->setAlignment(Qt::AlignCenter);
251     label->setText(errorMessage);
252     msgBox->setWidget(label);
253 #else
254     QMessageBox *msgBox = new QMessageBox(this);
255     msgBox->button(QMessageBox::Ok);
256     msgBox->setText(errorMessage);
257     msgBox->setModal(modal);
258 #endif
259
260     queueDialog(msgBox);
261 }
262
263 void MainWindow::buildMap()
264 {
265     qDebug() << __PRETTY_FUNCTION__;
266
267     m_mapView = new MapView(this);
268
269     buildZoomButtonPanel();
270     buildOsmLicense();
271     buildCrosshair();
272     buildFullScreenButton();
273     buildIndicatorButtonPanel();
274     buildMapScale();
275
276     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate)),
277             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
278
279     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
280             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
281
282     connect(m_mapView, SIGNAL(viewResized(QSize)),
283             this, SIGNAL(mapViewResized(QSize)));
284
285     connect(m_mapView, SIGNAL(viewResized(QSize)),
286             this, SLOT(drawFullScreenButton(QSize)));
287
288     connect(m_mapView, SIGNAL(viewResized(QSize)),
289             this, SLOT(drawMapScale(QSize)));
290
291     connect(m_mapView, SIGNAL(viewResized(QSize)),
292              this, SLOT(moveCrosshair()));
293
294     connect(this, SIGNAL(zoomLevelChanged(int)),
295             m_mapView, SLOT(setZoomLevel(int)));
296
297     connect(m_mapView, SIGNAL(viewZoomFinished()),
298             this, SIGNAL(viewZoomFinished()));
299
300     connect(m_mapView, SIGNAL(zoomIn()),
301             this, SIGNAL(zoomIn()));
302 }
303
304 void MainWindow::buildMapScale()
305 {
306     m_mapScale = new MapScale(this);
307     connect(this, SIGNAL(newMapResolution(qreal)),
308             m_mapScale, SLOT(updateMapResolution(qreal)));
309 }
310
311 void MainWindow::buildMeetPeoplePanel()
312 {
313     m_meetPeoplePanel = new MeetPeoplePanel(this);
314
315     connect(this, SIGNAL(friendImageReady(User*)),
316             m_meetPeoplePanel, SLOT(friendImageReady(User*)));
317
318     connect(this, SIGNAL(interestingPeopleReceived(QList<User*>&)),
319             m_meetPeoplePanel, SLOT(populateInterestingPeopleListView(QList<User*>&)));
320 }
321
322 void MainWindow::buildOsmLicense()
323 {
324     qDebug() << __PRETTY_FUNCTION__;
325
326     m_osmLicense = new QLabel(this);
327     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
328     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
329     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
330     m_osmLicense->setFont(QFont("Nokia Sans", 9));
331     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
332                          m_osmLicense->fontMetrics().height());
333
334     connect(m_mapView, SIGNAL(viewResized(QSize)),
335             this, SLOT(drawOsmLicense(QSize)));
336 }
337
338 void MainWindow::buildPanels()
339 {
340     qDebug() << __PRETTY_FUNCTION__;
341
342     buildUserInfoPanel();
343     buildFriendListPanel();
344     buildRoutingPanel();
345     buildMeetPeoplePanel();
346
347     m_tabbedPanel = new TabbedPanel(this);
348     m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png"));
349     m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png"));
350     m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
351     m_tabbedPanel->addTab(m_meetPeoplePanel, QIcon(":/res/images/meet_people.png"));
352
353     connect(m_mapView, SIGNAL(viewResized(QSize)),
354             m_tabbedPanel, SLOT(resizePanel(QSize)));
355
356     connect(m_friendsListPanel, SIGNAL(showPanelRequested(QWidget*)),
357             m_tabbedPanel, SLOT(showPanel(QWidget*)));
358
359     connect(m_routingPanel, SIGNAL(showPanelRequested(QWidget*)),
360             m_tabbedPanel, SLOT(showPanel(QWidget*)));
361
362     connect(m_tabbedPanel, SIGNAL(panelClosed()),
363             m_friendsListPanel, SLOT(anyPanelClosed()));
364
365     connect(m_tabbedPanel, SIGNAL(panelOpened()),
366             m_friendsListPanel, SLOT(anyPanelOpened()));
367
368     connect(m_tabbedPanel, SIGNAL(panelClosed()),
369             m_routingPanel, SLOT(clearListsSelections()));
370
371     connect(m_tabbedPanel, SIGNAL(panelClosed()),
372             m_mapView, SLOT(disableCenterShift()));
373
374     connect(m_tabbedPanel, SIGNAL(panelOpened()),
375             m_mapView, SLOT(enableCenterShift()));
376 }
377
378 void MainWindow::buildRoutingPanel()
379 {
380     qDebug() << __PRETTY_FUNCTION__;
381
382     m_routingPanel = new RoutingPanel(this);
383
384     connect(this, SIGNAL(locationDataParsed(const QList<Location>&)),
385             m_routingPanel, SLOT(populateLocationListView(const QList<Location>&)));
386
387     connect(m_routingPanel, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
388             this, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
389
390     connect(m_routingPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
391             this, SIGNAL(routeTo(const GeoCoordinate&)));
392
393     connect(this, SIGNAL(routeParsed(Route&)),
394             m_routingPanel, SLOT(setRoute(Route&)));
395
396     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
397             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
398
399     connect(m_routingPanel, SIGNAL(requestSearchLocation()),
400             this, SLOT(startLocationSearch()));
401
402     connect(m_routingPanel, SIGNAL(clearRoute()),
403             this, SIGNAL(clearRoute()));
404 }
405
406 void MainWindow::buildUserInfoPanel()
407 {
408     qDebug() << __PRETTY_FUNCTION__;
409
410     m_userInfoPanel = new UserInfoPanel(this);
411
412     connect(this, SIGNAL(userLocationReady(User*)),
413             m_userInfoPanel, SLOT(userDataReceived(User*)));
414
415     connect(this, SIGNAL(reverseGeoReady(QString)),
416             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
417
418     connect(this, SIGNAL(clearUpdateLocationDialogData()),
419             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
420
421     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
422             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
423
424     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
425             this, SIGNAL(requestReverseGeo()));
426
427     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
428             this, SIGNAL(statusUpdate(QString,bool)));
429
430     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
431             this, SIGNAL(refreshUserData()));
432
433     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
434             this, SLOT(buildInformationBox(QString, bool)));
435 }
436
437 void MainWindow::buildWebView()
438 {
439     qDebug() << __PRETTY_FUNCTION__;
440
441     if(!m_webView) {
442         m_webView = new QWebView;
443
444         if(!m_cookieJar)
445             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
446
447         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
448
449         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
450                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
451         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
452                 this, SIGNAL(updateCredentials(QUrl)));
453         connect(m_webView, SIGNAL(loadFinished(bool)),
454                 this, SLOT(loadDone(bool)));
455
456         m_webView->hide();
457     }
458 }
459
460 void MainWindow::buildZoomButtonPanel()
461 {
462     qDebug() << __PRETTY_FUNCTION__;
463
464     m_zoomButtonPanel = new ZoomButtonPanel(this);
465
466     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
467             this, SIGNAL(zoomIn()));
468
469     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
470             this, SIGNAL(zoomOut()));
471
472     connect(this, SIGNAL(zoomLevelChanged(int)),
473             m_zoomButtonPanel, SLOT(resetButtons()));
474
475     connect(this, SIGNAL(maxZoomLevelReached()),
476             m_zoomButtonPanel, SLOT(disableZoomInButton()));
477
478     connect(this, SIGNAL(minZoomLevelReached()),
479             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
480
481     connect(m_mapView, SIGNAL(viewResized(QSize)),
482             m_zoomButtonPanel, SLOT(screenResized(QSize)));
483
484     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
485             this, SIGNAL(draggingModeTriggered()));
486 }
487
488 void MainWindow::clearCookieJar()
489 {
490     qDebug() << __PRETTY_FUNCTION__;
491
492     buildWebView();
493
494     m_webView->stop();
495
496     if(!m_cookieJar) {
497         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
498     }
499     QList<QNetworkCookie> emptyList;
500     emptyList.clear();
501
502     m_cookieJar->setAllCookies(emptyList);
503     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
504 }
505
506 void MainWindow::createMenus()
507 {
508     qDebug() << __PRETTY_FUNCTION__;
509
510     // login/logout
511     m_loginAct = new QAction(tr("Login"), this);
512     connect(m_loginAct, SIGNAL(triggered()),
513             this, SIGNAL(loginActionPressed()));
514
515     // settings
516     m_toSettingsAct = new QAction(tr("Settings"), this);
517     connect(m_toSettingsAct, SIGNAL(triggered()),
518         this, SLOT(openSettingsDialog()));
519
520     // GPS
521     m_gpsToggleAct = new QAction(tr("GPS"), this);
522     m_gpsToggleAct->setCheckable(true);
523
524     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
525             this, SIGNAL(gpsTriggered(bool)));
526
527     // build the actual menu
528     m_viewMenu = menuBar()->addMenu(tr("Main"));
529     m_viewMenu->addAction(m_loginAct);
530     m_viewMenu->addAction(m_toSettingsAct);
531     m_viewMenu->addAction(m_gpsToggleAct);
532     m_viewMenu->setObjectName(tr("Menu"));
533 }
534
535 void MainWindow::dialogFinished(int status)
536 {
537     qDebug() << __PRETTY_FUNCTION__;
538
539     QDialog *dialog = m_queue.takeFirst();
540     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
541     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
542     if(loginDialog) {
543         if(status != 0) {
544             buildWebView();
545             loginDialog->userInput(m_email, m_password);
546
547             QStringList urlParts;
548             urlParts.append(FACEBOOK_LOGINBASE);
549             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
550             urlParts.append(INTERVAL1);
551             urlParts.append(SITUARE_LOGIN_SUCCESS);
552             urlParts.append(INTERVAL2);
553             urlParts.append(SITUARE_LOGIN_FAILURE);
554             urlParts.append(FACEBOOK_LOGIN_ENDING);
555
556             emit saveUsername(m_email);
557             m_refresh = true;
558             m_webView->load(QUrl(urlParts.join(EMPTY)));
559             toggleProgressIndicator(true);
560         } else {
561             emit cancelLoginProcess();
562         }
563     } else if(searchDialog) {
564         if(status != 0) {
565             emit searchForLocation(searchDialog->input());
566         }
567     }
568
569     dialog->deleteLater();
570
571     if(!m_error_queue.isEmpty() && m_errorShown == false) {
572         showErrorInformationBox();
573     } else {
574         if(!m_queue.isEmpty()) {
575             showInformationBox();
576         }
577     }
578 }
579
580 void MainWindow::drawFullScreenButton(const QSize &size)
581 {
582     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
583
584     if (m_fullScreenButton) {
585         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
586                                  size.height() - m_fullScreenButton->size().height());
587     }
588 }
589
590 void MainWindow::drawMapScale(const QSize &size)
591 {
592     qDebug() << __PRETTY_FUNCTION__;
593
594     const int LEFT_SCALE_MARGIN = 10;
595     const int BOTTOM_SCALE_MARGIN = 2;
596
597     m_mapScale->move(LEFT_SCALE_MARGIN,
598                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
599 }
600
601 void MainWindow::drawOsmLicense(const QSize &size)
602 {
603     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
604
605     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
606                        - PANEL_BAR_WIDTH,
607                        size.height() - m_osmLicense->fontMetrics().height());
608 }
609
610 void MainWindow::errorDialogFinished(int status)
611 {
612     qDebug() << __PRETTY_FUNCTION__;
613
614     qDebug() << status;
615     QDialog *dialog = m_error_queue.takeFirst();
616
617     dialog->deleteLater();
618     m_errorShown = false;
619
620     if(!m_error_queue.isEmpty())
621         showErrorInformationBox();
622     else if(!m_queue.isEmpty())
623         showInformationBox();
624 }
625
626 void MainWindow::gpsTimeout()
627 {
628     qDebug() << __PRETTY_FUNCTION__;
629
630     buildInformationBox(tr("GPS timeout"));
631 }
632
633 void MainWindow::grabZoomKeys(bool grab)
634 {
635     qDebug() << __PRETTY_FUNCTION__;
636
637 #ifdef Q_WS_MAEMO_5
638     // Can't grab keys unless we have a window id
639     if (!winId())
640         return;
641
642     unsigned long val = (grab) ? 1 : 0;
643     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
644     if (!atom)
645         return;
646
647     XChangeProperty (QX11Info::display(),
648                      winId(),
649                      atom,
650                      XA_INTEGER,
651                      32,
652                      PropModeReplace,
653                      reinterpret_cast<unsigned char *>(&val),
654                      1);
655 #else
656     Q_UNUSED(grab);
657 #endif // Q_WS_MAEMO_5
658 }
659
660 void MainWindow::keyPressEvent(QKeyEvent* event)
661 {
662     qDebug() << __PRETTY_FUNCTION__;
663
664     switch (event->key()) {
665     case Qt::Key_F7:
666         event->accept();
667         emit zoomIn();
668         break;
669
670     case Qt::Key_F8:
671         event->accept();
672         emit zoomOut();
673         break;
674     }
675     QWidget::keyPressEvent(event);
676 }
677
678 void MainWindow::loadCookies()
679 {
680     qDebug() << __PRETTY_FUNCTION__;
681
682     QSettings settings(DIRECTORY_NAME, FILE_NAME);
683
684     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
685
686     if(!list.isEmpty()) {
687         QList<QNetworkCookie> cookieList;
688         for(int i=0;i<list.count();i++) {
689             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
690         }
691
692         if(!m_cookieJar)
693                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
694
695         m_cookieJar->setAllCookies(cookieList);
696         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
697     }
698 }
699
700 void MainWindow::loadDone(bool done)
701 {
702     qDebug() << __PRETTY_FUNCTION__;
703
704     // for the first time the login page is opened, we need to refresh it to get cookies working
705     if(m_refresh) {
706         m_webView->reload();
707         m_refresh = false;
708     }
709
710     if (done)
711     {
712         QWebFrame* frame = m_webView->page()->currentFrame();
713         if (frame!=NULL)
714         {
715             // set email box
716             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
717
718             foreach (QWebElement element, emailCollection) {
719                 element.setAttribute("value", m_email.toAscii());
720             }
721             // set password box
722             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
723             foreach (QWebElement element, passwordCollection) {
724                 element.setAttribute("value", m_password.toAscii());
725             }
726             // find connect button
727             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
728             foreach (QWebElement element, buttonCollection)
729             {
730                 QPoint pos(element.geometry().center());
731
732                 // send a mouse click event to the web page
733                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
734                                    Qt::NoModifier);
735                 QApplication::sendEvent(m_webView->page(), &event0);
736                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
737                                    Qt::NoModifier);
738                 QApplication::sendEvent(m_webView->page(), &event1);
739             }
740         }
741     }
742 }
743
744 void MainWindow::loggedIn(bool logged)
745 {
746     qDebug() << __PRETTY_FUNCTION__;
747
748     m_loggedIn = logged;
749
750     if(logged) {
751         m_loginAct->setText(tr("Logout"));
752     } else {
753         clearCookieJar();
754         m_email.clear();
755         m_password.clear();
756
757         m_loginAct->setText(tr("Login"));
758     }
759     updateItemVisibility();
760 }
761
762 void MainWindow::loginFailed()
763 {
764     qDebug() << __PRETTY_FUNCTION__;
765
766     clearCookieJar();
767     startLoginProcess();
768 }
769
770 bool MainWindow::loginState()
771 {
772     qDebug() << __PRETTY_FUNCTION__;
773
774     return m_loggedIn;
775 }
776
777 void MainWindow::loginUsingCookies()
778 {
779     qDebug() << __PRETTY_FUNCTION__;
780
781     toggleProgressIndicator(true);
782
783     buildWebView();
784     loadCookies();
785
786     QStringList urlParts;
787     urlParts.append(FACEBOOK_LOGINBASE);
788     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
789     urlParts.append(INTERVAL1);
790     urlParts.append(SITUARE_LOGIN_SUCCESS);
791     urlParts.append(INTERVAL2);
792     urlParts.append(SITUARE_LOGIN_FAILURE);
793     urlParts.append(FACEBOOK_LOGIN_ENDING);
794
795     m_webView->load(QUrl(urlParts.join(EMPTY)));
796
797 }
798
799 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
800 {
801     m_mapCenterHorizontalShifting = shifting;
802     moveCrosshair();
803 }
804
805 void MainWindow::moveCrosshair()
806 {
807     qDebug() << __PRETTY_FUNCTION__;
808
809     if (m_crosshair) {
810         int mapHeight = m_mapView->size().height();
811         int mapWidth = m_mapView->size().width();
812         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
813                           - m_mapCenterHorizontalShifting,
814                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
815     }
816 }
817
818 void MainWindow::openSettingsDialog()
819 {
820     qDebug() << __PRETTY_FUNCTION__;
821
822     SettingsDialog *settingsDialog = new SettingsDialog(this);
823     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
824     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
825
826     settingsDialog->show();
827 }
828
829 void MainWindow::queueDialog(QDialog *dialog)
830 {
831     qDebug() << __PRETTY_FUNCTION__;
832
833     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
834     if(dialog->isModal()) {
835         m_error_queue.append(dialog);
836     } else {
837         m_queue.append(dialog);
838     }
839
840     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
841     if(m_error_queue.count() == 1 && m_errorShown == false)
842         showErrorInformationBox();
843     else if(m_queue.count() == 1 && m_errorShown == false)
844         showInformationBox();
845 }
846
847 void MainWindow::readAutomaticLocationUpdateSettings()
848 {
849     qDebug() << __PRETTY_FUNCTION__;
850
851     QSettings settings(DIRECTORY_NAME, FILE_NAME);
852     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
853     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
854                                       .toTime();
855
856     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
857         QTime time;
858         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
859     } else {
860         emit enableAutomaticLocationUpdate(false);
861     }
862 }
863
864 void MainWindow::saveCookies()
865 {
866     qDebug() << __PRETTY_FUNCTION__;
867
868     if(!m_cookieJar)
869         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
870
871     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
872     QStringList list;
873
874     for(int i=0;i<cookieList.count();i++) {
875         QNetworkCookie cookie = cookieList.at(i);
876         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
877         list.append(QString(byteArray));
878     }
879     list.removeDuplicates();
880
881     QSettings settings(DIRECTORY_NAME, FILE_NAME);
882     settings.setValue(COOKIES, list);
883 }
884
885 void MainWindow::setCrosshairVisibility(bool visibility)
886 {
887     qDebug() << __PRETTY_FUNCTION__;
888
889     if (visibility) {
890         m_crosshair->show();
891         moveCrosshair();
892     } else {
893         m_crosshair->hide();
894     }
895 }
896
897 void MainWindow::setGPSButtonEnabled(bool enabled)
898 {
899     qDebug() << __PRETTY_FUNCTION__;
900
901     m_gpsToggleAct->setChecked(enabled);
902 }
903
904 void MainWindow::setIndicatorButtonEnabled(bool enabled)
905 {
906     qDebug() << __PRETTY_FUNCTION__;
907
908     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
909 }
910
911 void MainWindow::setMapViewScene(QGraphicsScene *scene)
912 {
913     qDebug() << __PRETTY_FUNCTION__;
914
915     m_mapView->setScene(scene);
916 }
917
918 void MainWindow::settingsDialogAccepted()
919 {
920     qDebug() << __PRETTY_FUNCTION__;
921
922     readAutomaticLocationUpdateSettings();
923 }
924
925 void MainWindow::setUsername(const QString &username)
926 {
927     qDebug() << __PRETTY_FUNCTION__;
928
929     m_email = username;
930 }
931
932 void MainWindow::showContactDialog(const QString &guid)
933 {
934     qDebug() << __PRETTY_FUNCTION__ << guid;
935
936 #if defined(Q_WS_MAEMO_5) & defined(ARMEL)
937     OssoABookDialog::showContactDialog(guid);
938 #endif
939 }
940
941 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
942 {
943     qDebug() << __PRETTY_FUNCTION__;
944
945     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
946                                                       tr("Automatic location update"), text,
947                                                       QMessageBox::Yes | QMessageBox::No |
948                                                       QMessageBox::Cancel, this);
949     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
950             this, SLOT(automaticUpdateDialogFinished(int)));
951
952     m_automaticUpdateLocationDialog->show();
953 }
954
955 void MainWindow::showErrorInformationBox()
956 {
957     qDebug() << __PRETTY_FUNCTION__;
958
959     if(m_error_queue.count()) {
960         m_errorShown = true;
961         QDialog *dialog = m_error_queue.first();
962         connect(dialog, SIGNAL(finished(int)),
963                 this, SLOT(errorDialogFinished(int)));
964         dialog->show();
965     }
966 }
967
968 void MainWindow::showInformationBox()
969 {
970     qDebug() << __PRETTY_FUNCTION__;
971
972     if(m_queue.count()) {
973         QDialog *dialog = m_queue.first();
974         connect(dialog, SIGNAL(finished(int)),
975                 this, SLOT(dialogFinished(int)));
976         dialog->show();
977     }
978 }
979
980 void MainWindow::showPanels()
981 {
982     qDebug() << __PRETTY_FUNCTION__;
983
984 ///< @todo check how this is called and can this method be removed
985
986 //    if(m_loggedIn) {
987 //        if(!m_friendsListPanel->isVisible()) {
988 //            m_friendsListPanel->show();
989 //            m_friendsListPanelSidebar->show();
990 //        }
991
992 //        if(!m_userPanel->isVisible()) {
993 //            m_userPanel->show();
994 //            m_userPanelSidebar->show();
995 //        }
996 //    }
997 }
998
999 void MainWindow::startLocationSearch()
1000 {
1001     qDebug() << __PRETTY_FUNCTION__;
1002
1003     SearchDialog *searchDialog = new SearchDialog();
1004     queueDialog(searchDialog);
1005 }
1006
1007 void MainWindow::startLoginProcess()
1008 {
1009     qDebug() << __PRETTY_FUNCTION__;
1010
1011     LoginDialog *loginDialog = new LoginDialog();
1012
1013     emit fetchUsernameFromSettings();
1014
1015     loginDialog->clearTextFields();
1016
1017     if(!m_email.isEmpty())
1018         loginDialog->setEmailField(m_email);
1019
1020     queueDialog(loginDialog);
1021 }
1022
1023 void MainWindow::toggleFullScreen()
1024 {
1025     qDebug() << __PRETTY_FUNCTION__;
1026
1027     if(windowState() == Qt::WindowNoState)
1028         showFullScreen();
1029     else
1030         showNormal();
1031 }
1032
1033 void MainWindow::toggleProgressIndicator(bool value)
1034 {
1035     qDebug() << __PRETTY_FUNCTION__;
1036
1037 #ifdef Q_WS_MAEMO_5
1038     if(value) {
1039         m_progressIndicatorCount++;
1040         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1041     } else {
1042         if(m_progressIndicatorCount > 0)
1043             m_progressIndicatorCount--;
1044
1045         if(m_progressIndicatorCount == 0)
1046             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1047     }
1048 #else
1049     Q_UNUSED(value);
1050 #endif // Q_WS_MAEMO_5
1051 }
1052
1053 void MainWindow::updateItemVisibility()
1054 {
1055     qDebug() << __PRETTY_FUNCTION__;
1056
1057 ///< @todo can this be removed?
1058
1059 //    if(!m_loggedIn) {
1060 //        m_friendsListPanel->closePanel();
1061 //        m_friendsListPanel->hide();
1062 //        m_friendsListPanelSidebar->hide();
1063
1064 //        m_userPanel->closePanel();
1065 //        m_userPanel->hide();
1066 //        m_userPanelSidebar->hide();
1067 //    }
1068 }
1069
1070 const QString MainWindow::username()
1071 {
1072     qDebug() << __PRETTY_FUNCTION__;
1073
1074     return m_email;
1075 }
1076
1077 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1078 {
1079     qDebug() << __PRETTY_FUNCTION__;
1080
1081     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1082     // qwebview starts to load a new page while the current page loading is not finished
1083     if(reply->error() != QNetworkReply::OperationCanceledError &&
1084        reply->error() != QNetworkReply::NoError) {
1085         emit error(ErrorContext::NETWORK, reply->error());
1086     }
1087 }