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