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