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