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