Added unit tests.
[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>&,QList<User>&)),
349             m_meetPeoplePanel, SLOT(populateInterestingPeopleListView(QList<User>&,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     connect(m_meetPeoplePanel, SIGNAL(requestShowFriend(QList<QString>)),
364             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
365 }
366
367 void MainWindow::buildMessagePanel()
368 {
369     qDebug() << __PRETTY_FUNCTION__;
370
371     m_messagePanel = new MessagePanel(this);
372
373     connect(this, SIGNAL(messagesReceived(QList<Message>&, QList<Message>&)),
374             m_messagePanel, SLOT(populateMessageListView(QList<Message>&, QList<Message>&)));
375
376     connect(m_messagePanel, SIGNAL(requestMessages()),
377             this, SIGNAL(requestMessages()));
378
379     connect(this, SIGNAL(friendImageReady(QString,QPixmap)),
380             m_messagePanel, SLOT(setImage(QString,QPixmap)));
381
382     connect(m_messagePanel, SIGNAL(requestRemoveMessage(QString)),
383             this, SIGNAL(requestRemoveMessage(QString)));
384
385     connect(m_messagePanel, SIGNAL(findFriend(GeoCoordinate)),
386             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
387
388     connect(m_messagePanel, SIGNAL(requestMessageDialog(QPair<QString, QString>)),
389             this, SIGNAL(requestMessageDialog(QPair<QString, QString>)));
390 }
391
392 void MainWindow::buildOsmLicense()
393 {
394     qDebug() << __PRETTY_FUNCTION__;
395
396     m_osmLicense = new QLabel(this);
397     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
398     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
399     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
400     m_osmLicense->setFont(QFont("Nokia Sans", 9));
401     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
402                          m_osmLicense->fontMetrics().height());
403
404     connect(m_mapView, SIGNAL(viewResized(QSize)),
405             this, SLOT(drawOsmLicense(QSize)));
406 }
407
408 void MainWindow::buildPanels()
409 {
410     qDebug() << __PRETTY_FUNCTION__;
411
412     buildUserInfoPanel();
413     buildFriendListPanel();
414     buildLocationSearchPanel();
415     buildRoutingPanel();
416     buildMeetPeoplePanel();
417     buildMessagePanel();
418
419     m_tabbedPanel = new TabbedPanel(this);
420
421     //Save Situare related tab indexes so tabs can be enabled/disabled when logged in/out
422     m_situareTabsIndexes.append(
423             m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png")));
424     m_situareTabsIndexes.append(
425             m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png")));
426
427 //    m_tabbedPanel->addTab(m_locationSearchPanel, QIcon(":/res/images/location_search.png"));
428 //    m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
429     m_situareTabsIndexes.append(
430             m_tabbedPanel->addTab(m_meetPeoplePanel, QIcon(":/res/images/meet_people.png")));
431     m_situareTabsIndexes.append(
432             m_tabbedPanel->addTab(m_messagePanel, QIcon(":/res/images/message.png")));
433
434     connect(m_mapView, SIGNAL(viewResized(QSize)),
435             m_tabbedPanel, SLOT(resizePanel(QSize)));
436
437     connect(m_friendsListPanel, SIGNAL(openPanelRequested(QWidget*)),
438             m_tabbedPanel, SLOT(openPanel(QWidget*)));
439
440     connect(m_routingPanel, SIGNAL(openPanelRequested(QWidget*)),
441             m_tabbedPanel, SLOT(openPanel(QWidget*)));
442
443     connect(m_tabbedPanel, SIGNAL(panelClosed()),
444             m_friendsListPanel, SLOT(anyPanelClosed()));
445
446     connect(m_tabbedPanel, SIGNAL(panelOpened()),
447             m_friendsListPanel, SLOT(anyPanelOpened()));
448
449     connect(m_tabbedPanel, SIGNAL(panelClosed()),
450             m_routingPanel, SLOT(clearListsSelections()));
451
452     connect(m_tabbedPanel, SIGNAL(panelClosed()),
453             m_mapView, SLOT(disableCenterShift()));
454
455     connect(m_tabbedPanel, SIGNAL(panelOpened()),
456             m_mapView, SLOT(enableCenterShift()));
457
458     connect(m_tabbedPanel, SIGNAL(panelClosed()),
459             m_userInfoPanel, SIGNAL(collapse()));
460
461     connect(m_tabbedPanel, SIGNAL(currentChanged(int)),
462             m_userInfoPanel, SIGNAL(collapse()));
463
464     connect(m_tabbedPanel, SIGNAL(panelClosed()),
465             m_meetPeoplePanel, SLOT(anyPanelClosed()));
466
467     connect(m_tabbedPanel, SIGNAL(panelClosed()),
468             m_messagePanel, SLOT(anyPanelClosed()));
469
470     // signals for showing and hiding list item context buttons
471     connect(m_userInfoPanel, SIGNAL(listItemSelectionChanged(bool)),
472             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
473
474     connect(m_friendsListPanel, SIGNAL(listItemSelectionChanged(bool)),
475             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
476
477     connect(m_locationSearchPanel, SIGNAL(listItemSelectionChanged(bool)),
478             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
479
480     connect(m_routingPanel, SIGNAL(listItemSelectionChanged(bool)),
481             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
482
483     connect(m_meetPeoplePanel, SIGNAL(listItemSelectionChanged(bool)),
484             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
485
486     connect(m_messagePanel, SIGNAL(listItemSelectionChanged(bool)),
487             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
488 }
489
490 void MainWindow::buildRoutingPanel()
491 {
492     qDebug() << __PRETTY_FUNCTION__;
493
494     m_routingPanel = new RoutingPanel(this);
495
496     connect(m_routingPanel, SIGNAL(routeToCursor()),
497             this, SIGNAL(routeToCursor()));
498
499     connect(this, SIGNAL(routeParsed(Route&)),
500             m_routingPanel, SLOT(setRoute(Route&)));
501
502     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
503             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
504
505     connect(m_routingPanel, SIGNAL(clearRoute()),
506             this, SIGNAL(clearRoute()));
507 }
508
509 void MainWindow::buildUserInfoPanel()
510 {
511     qDebug() << __PRETTY_FUNCTION__;
512
513     m_userInfoPanel = new UserInfoPanel(this);
514
515     connect(this, SIGNAL(userLocationReady(User*)),
516             m_userInfoPanel, SLOT(userDataReceived(User*)));
517
518     connect(this, SIGNAL(reverseGeoReady(QString)),
519             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
520
521     connect(this, SIGNAL(clearUpdateLocationDialogData()),
522             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
523
524     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
525             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
526
527     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
528             this, SIGNAL(requestReverseGeo()));
529
530     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
531             this, SIGNAL(statusUpdate(QString,bool)));
532
533     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
534             this, SIGNAL(refreshUserData()));
535
536     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
537             this, SLOT(buildInformationBox(QString, bool)));
538
539     connect(this, SIGNAL(userImageReady(QString,QPixmap)),
540             m_userInfoPanel, SLOT(setImage(QString,QPixmap)));
541
542     connect(m_userInfoPanel, SIGNAL(addTags(QStringList)),
543             this, SIGNAL(addTags(QStringList)));
544
545     connect(m_userInfoPanel, SIGNAL(removeTags(QStringList)),
546             this, SIGNAL(removeTags(QStringList)));
547
548     connect(this, SIGNAL(popularTagsReceived(QHash<QString,QString>&)),
549             m_userInfoPanel, SLOT(populatePopularTags(QHash<QString,QString>&)));
550
551     connect(m_userInfoPanel, SIGNAL(requestPopularTags()),
552             this, SIGNAL(requestPopularTags()));
553 }
554
555 void MainWindow::buildWebView()
556 {
557     qDebug() << __PRETTY_FUNCTION__;
558
559     if(!m_webView) {
560         m_webView = new QWebView;
561
562         if(!m_cookieJar)
563             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
564
565         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
566
567         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
568                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
569         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
570                 this, SIGNAL(updateCredentials(QUrl)));
571         connect(m_webView, SIGNAL(loadFinished(bool)),
572                 this, SLOT(loadDone(bool)));
573
574         //Remove
575         connect(m_webView->page()->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
576                 this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
577
578         m_webView->hide();
579     }
580 }
581
582 void MainWindow::buildZoomButtonPanel()
583 {
584     qDebug() << __PRETTY_FUNCTION__;
585
586     m_zoomButtonPanel = new ZoomButtonPanel(this);
587
588     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
589             this, SIGNAL(zoomIn()));
590
591     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
592             this, SIGNAL(zoomOut()));
593
594     connect(this, SIGNAL(zoomLevelChanged(int)),
595             m_zoomButtonPanel, SLOT(resetButtons()));
596
597     connect(this, SIGNAL(maxZoomLevelReached()),
598             m_zoomButtonPanel, SLOT(disableZoomInButton()));
599
600     connect(this, SIGNAL(minZoomLevelReached()),
601             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
602
603     connect(m_mapView, SIGNAL(viewResized(QSize)),
604             m_zoomButtonPanel, SLOT(screenResized(QSize)));
605
606     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
607             this, SIGNAL(draggingModeTriggered()));
608 }
609
610 void MainWindow::clearCookieJar()
611 {
612     qDebug() << __PRETTY_FUNCTION__;
613
614     buildWebView();
615
616     m_webView->stop();
617
618     if(!m_cookieJar) {
619         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
620     }
621     QList<QNetworkCookie> emptyList;
622     emptyList.clear();
623
624     m_cookieJar->setAllCookies(emptyList);
625     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
626 }
627
628 void MainWindow::createMenus()
629 {
630     qDebug() << __PRETTY_FUNCTION__;
631
632     // login/logout
633     m_loginAct = new QAction(tr("Login"), this);
634     connect(m_loginAct, SIGNAL(triggered()),
635             this, SIGNAL(loginActionPressed()));
636
637     // settings
638     m_toSettingsAct = new QAction(tr("Settings"), this);
639     connect(m_toSettingsAct, SIGNAL(triggered()),
640         this, SLOT(openSettingsDialog()));
641
642     // GPS
643     m_gpsToggleAct = new QAction(tr("GPS"), this);
644     m_gpsToggleAct->setCheckable(true);
645
646     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
647             this, SIGNAL(gpsTriggered(bool)));
648
649     // build the actual menu
650     m_viewMenu = menuBar()->addMenu(tr("Main"));
651     m_viewMenu->addAction(m_loginAct);
652     m_viewMenu->addAction(m_toSettingsAct);
653     m_viewMenu->addAction(m_gpsToggleAct);
654     m_viewMenu->setObjectName(tr("Menu"));
655 }
656
657 void MainWindow::dialogFinished(int status)
658 {
659     qDebug() << __PRETTY_FUNCTION__;
660
661     QDialog *dialog = m_queue.takeFirst();
662     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
663     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
664     MessageDialog *messageDialog = qobject_cast<MessageDialog *>(dialog);
665     if(loginDialog) {
666         if(status != 0) {
667             buildWebView();
668             loginDialog->userInput(m_email, m_password);
669
670             QStringList urlParts;
671             urlParts.append(FACEBOOK_LOGINBASE);
672             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
673             urlParts.append(INTERVAL1);
674             urlParts.append(SITUARE_LOGIN_SUCCESS);
675             urlParts.append(INTERVAL2);
676             urlParts.append(SITUARE_LOGIN_FAILURE);
677             urlParts.append(FACEBOOK_LOGIN_ENDING);
678
679             emit saveUsername(m_email);
680             m_refresh = true;
681             m_webView->load(QUrl(urlParts.join(EMPTY)));
682             toggleProgressIndicator(true);
683         } else {
684             emit cancelLoginProcess();
685         }
686     } else if(searchDialog) {
687         if(status != 0) {
688             if (searchDialog->type() == SearchDialog::Location)
689                 emit searchForLocation(searchDialog->input());
690             else if (searchDialog->type() == SearchDialog::PeopleTag)
691                 emit requestSearchPeopleByTag(searchDialog->input());
692         }
693     }
694     else if (messageDialog) {
695         if (status != 0)
696             emit sendMessage(messageDialog->input().first, messageDialog->input().second,
697                              messageDialog->isAddCoordinatesSelected());
698     }
699
700     dialog->deleteLater();
701
702     if(!m_error_queue.isEmpty() && m_errorShown == false) {
703         showErrorInformationBox();
704     } else {
705         if(!m_queue.isEmpty()) {
706             showInformationBox();
707         }
708     }
709 }
710
711 void MainWindow::drawFullScreenButton(const QSize &size)
712 {
713     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
714
715     if (m_fullScreenButton) {
716         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
717                                  size.height() - m_fullScreenButton->size().height());
718     }
719 }
720
721 void MainWindow::drawMapScale(const QSize &size)
722 {
723     qDebug() << __PRETTY_FUNCTION__;
724
725     const int LEFT_SCALE_MARGIN = 10;
726     const int BOTTOM_SCALE_MARGIN = 2;
727
728     m_mapScale->move(LEFT_SCALE_MARGIN,
729                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
730 }
731
732 void MainWindow::drawOsmLicense(const QSize &size)
733 {
734     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
735
736     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
737                        - PANEL_BAR_WIDTH,
738                        size.height() - m_osmLicense->fontMetrics().height());
739 }
740
741 void MainWindow::errorDialogFinished(int status)
742 {
743     qDebug() << __PRETTY_FUNCTION__;
744
745     qDebug() << status;
746     QDialog *dialog = m_error_queue.takeFirst();
747
748     dialog->deleteLater();
749     m_errorShown = false;
750
751     if(!m_error_queue.isEmpty())
752         showErrorInformationBox();
753     else if(!m_queue.isEmpty())
754         showInformationBox();
755 }
756
757 void MainWindow::gpsTimeout()
758 {
759     qDebug() << __PRETTY_FUNCTION__;
760
761     buildInformationBox(tr("GPS timeout"));
762 }
763
764 void MainWindow::grabZoomKeys(bool grab)
765 {
766     qDebug() << __PRETTY_FUNCTION__;
767
768 #ifdef Q_WS_MAEMO_5
769     // Can't grab keys unless we have a window id
770     if (!winId())
771         return;
772
773     unsigned long val = (grab) ? 1 : 0;
774     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
775     if (!atom)
776         return;
777
778     XChangeProperty (QX11Info::display(),
779                      winId(),
780                      atom,
781                      XA_INTEGER,
782                      32,
783                      PropModeReplace,
784                      reinterpret_cast<unsigned char *>(&val),
785                      1);
786 #else
787     Q_UNUSED(grab);
788 #endif // Q_WS_MAEMO_5
789 }
790
791 void MainWindow::keyPressEvent(QKeyEvent* event)
792 {
793     qDebug() << __PRETTY_FUNCTION__;
794
795     switch (event->key()) {
796     case Qt::Key_F7:
797         event->accept();
798         emit zoomIn();
799         break;
800
801     case Qt::Key_F8:
802         event->accept();
803         emit zoomOut();
804         break;
805     }
806     QWidget::keyPressEvent(event);
807 }
808
809 void MainWindow::loadCookies()
810 {
811     qDebug() << __PRETTY_FUNCTION__;
812
813     QSettings settings(DIRECTORY_NAME, FILE_NAME);
814
815     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
816
817     if(!list.isEmpty()) {
818         QList<QNetworkCookie> cookieList;
819         for(int i=0;i<list.count();i++) {
820             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
821         }
822
823         if(!m_cookieJar)
824                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
825
826         m_cookieJar->setAllCookies(cookieList);
827         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
828     }
829 }
830
831 void MainWindow::loadDone(bool done)
832 {
833     qDebug() << __PRETTY_FUNCTION__;
834
835     // for the first time the login page is opened, we need to refresh it to get cookies working
836     if(m_refresh) {
837         m_webView->reload();
838         m_refresh = false;
839     }
840
841     if (done)
842     {
843         QWebFrame* frame = m_webView->page()->currentFrame();
844         if (frame!=NULL)
845         {
846             // set email box
847             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
848
849             foreach (QWebElement element, emailCollection) {
850                 element.setAttribute("value", m_email.toAscii());
851             }
852             // set password box
853             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
854             foreach (QWebElement element, passwordCollection) {
855                 element.setAttribute("value", m_password.toAscii());
856             }
857             // find connect button
858             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
859             foreach (QWebElement element, buttonCollection)
860             {
861                 QPoint pos(element.geometry().center());
862
863                 // send a mouse click event to the web page
864                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
865                                    Qt::NoModifier);
866                 QApplication::sendEvent(m_webView->page(), &event0);
867                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
868                                    Qt::NoModifier);
869                 QApplication::sendEvent(m_webView->page(), &event1);
870             }
871         }
872     }
873 }
874
875 void MainWindow::loggedIn(bool logged)
876 {
877     qDebug() << __PRETTY_FUNCTION__;
878
879     m_loggedIn = logged;
880
881     if(logged) {
882         m_loginAct->setText(tr("Logout"));
883     } else {
884         clearCookieJar();
885         m_email.clear();
886         m_password.clear();
887
888         m_loginAct->setText(tr("Login"));
889         m_userInfoPanel->showUserInfo(false);
890     }
891     updateItemVisibility();
892 }
893
894 void MainWindow::loginFailed()
895 {
896     qDebug() << __PRETTY_FUNCTION__;
897
898     clearCookieJar();
899     startLoginProcess();
900 }
901
902 bool MainWindow::loginState()
903 {
904     qDebug() << __PRETTY_FUNCTION__;
905
906     return m_loggedIn;
907 }
908
909 void MainWindow::loginUsingCookies()
910 {
911     qDebug() << __PRETTY_FUNCTION__;
912
913     toggleProgressIndicator(true);
914
915     buildWebView();
916     loadCookies();
917
918     QStringList urlParts;
919     urlParts.append(FACEBOOK_LOGINBASE);
920     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
921     urlParts.append(INTERVAL1);
922     urlParts.append(SITUARE_LOGIN_SUCCESS);
923     urlParts.append(INTERVAL2);
924     urlParts.append(SITUARE_LOGIN_FAILURE);
925     urlParts.append(FACEBOOK_LOGIN_ENDING);
926
927     m_webView->load(QUrl(urlParts.join(EMPTY)));
928
929 }
930
931 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
932 {
933     m_mapCenterHorizontalShifting = shifting;
934     moveCrosshair();
935 }
936
937 void MainWindow::moveCrosshair()
938 {
939     qDebug() << __PRETTY_FUNCTION__;
940
941     if (m_crosshair) {
942         int mapHeight = m_mapView->size().height();
943         int mapWidth = m_mapView->size().width();
944         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
945                           - m_mapCenterHorizontalShifting,
946                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
947     }
948 }
949
950 void MainWindow::openSettingsDialog()
951 {
952     qDebug() << __PRETTY_FUNCTION__;
953
954     SettingsDialog *settingsDialog = new SettingsDialog(this);
955     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
956     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
957
958     settingsDialog->show();
959 }
960
961 void MainWindow::queueDialog(QDialog *dialog)
962 {
963     qDebug() << __PRETTY_FUNCTION__;
964
965     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
966     if(dialog->isModal()) {
967         m_error_queue.append(dialog);
968     } else {
969         m_queue.append(dialog);
970     }
971
972     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
973     if(m_error_queue.count() == 1 && m_errorShown == false)
974         showErrorInformationBox();
975     else if(m_queue.count() == 1 && m_errorShown == false)
976         showInformationBox();
977 }
978
979 void MainWindow::readAutomaticLocationUpdateSettings()
980 {
981     qDebug() << __PRETTY_FUNCTION__;
982
983     QSettings settings(DIRECTORY_NAME, FILE_NAME);
984     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
985     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
986                                       .toTime();
987
988     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
989         QTime time;
990         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
991     } else {
992         emit enableAutomaticLocationUpdate(false);
993     }
994 }
995
996 void MainWindow::saveCookies()
997 {
998     qDebug() << __PRETTY_FUNCTION__;
999
1000     if(!m_cookieJar)
1001         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
1002
1003     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
1004     QStringList list;
1005
1006     for(int i=0;i<cookieList.count();i++) {
1007         QNetworkCookie cookie = cookieList.at(i);
1008         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
1009         list.append(QString(byteArray));
1010     }
1011     list.removeDuplicates();
1012
1013     QSettings settings(DIRECTORY_NAME, FILE_NAME);
1014     settings.setValue(COOKIES, list);
1015 }
1016
1017 void MainWindow::setCrosshairVisibility(bool visibility)
1018 {
1019     qDebug() << __PRETTY_FUNCTION__;
1020
1021     if (visibility) {
1022         m_crosshair->show();
1023         moveCrosshair();
1024     } else {
1025         m_crosshair->hide();
1026     }
1027 }
1028
1029 void MainWindow::setGPSButtonEnabled(bool enabled)
1030 {
1031     qDebug() << __PRETTY_FUNCTION__;
1032
1033     m_gpsToggleAct->setChecked(enabled);
1034 }
1035
1036 void MainWindow::setIndicatorButtonEnabled(bool enabled)
1037 {
1038     qDebug() << __PRETTY_FUNCTION__;
1039
1040     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
1041 }
1042
1043 void MainWindow::setMapViewScene(QGraphicsScene *scene)
1044 {
1045     qDebug() << __PRETTY_FUNCTION__;
1046
1047     m_mapView->setScene(scene);
1048 }
1049
1050 void MainWindow::settingsDialogAccepted()
1051 {
1052     qDebug() << __PRETTY_FUNCTION__;
1053
1054     readAutomaticLocationUpdateSettings();
1055 }
1056
1057 void MainWindow::setUsername(const QString &username)
1058 {
1059     qDebug() << __PRETTY_FUNCTION__;
1060
1061     m_email = username;
1062 }
1063
1064 void MainWindow::showContactDialog(const QString &guid)
1065 {
1066     qDebug() << __PRETTY_FUNCTION__;
1067
1068 #if defined(Q_WS_MAEMO_5) & defined(ARMEL)
1069     OssoABookDialog::showContactDialog(guid);
1070 #else
1071     Q_UNUSED(guid);
1072     buildInformationBox(tr("Contact dialog works only on phone!"), true);
1073 #endif
1074 }
1075
1076 void MainWindow::showMessageDialog(const QPair<QString, QString> &receiver)
1077 {
1078     qDebug() << __PRETTY_FUNCTION__;
1079
1080     MessageDialog *messageDialog = new MessageDialog(receiver.first, receiver.second);
1081     queueDialog(messageDialog);
1082 }
1083
1084 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
1085 {
1086     qDebug() << __PRETTY_FUNCTION__;
1087
1088     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
1089                                                       tr("Automatic location update"), text,
1090                                                       QMessageBox::Yes | QMessageBox::No |
1091                                                       QMessageBox::Cancel, this);
1092     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
1093             this, SLOT(automaticUpdateDialogFinished(int)));
1094
1095     m_automaticUpdateLocationDialog->show();
1096 }
1097
1098 void MainWindow::showErrorInformationBox()
1099 {
1100     qDebug() << __PRETTY_FUNCTION__;
1101
1102     if(m_error_queue.count()) {
1103         m_errorShown = true;
1104         QDialog *dialog = m_error_queue.first();
1105         connect(dialog, SIGNAL(finished(int)),
1106                 this, SLOT(errorDialogFinished(int)));
1107         dialog->show();
1108     }
1109 }
1110
1111 void MainWindow::showInformationBox()
1112 {
1113     qDebug() << __PRETTY_FUNCTION__;
1114
1115     if(m_queue.count()) {
1116         QDialog *dialog = m_queue.first();
1117         connect(dialog, SIGNAL(finished(int)),
1118                 this, SLOT(dialogFinished(int)));
1119         dialog->show();
1120     }
1121 }
1122
1123 void MainWindow::startLocationSearch()
1124 {
1125     qDebug() << __PRETTY_FUNCTION__;
1126
1127     SearchDialog *searchDialog = new SearchDialog(SearchDialog::Location);
1128     queueDialog(searchDialog);
1129 }
1130
1131 void MainWindow::startPeopleSearch()
1132 {
1133     qDebug() << __PRETTY_FUNCTION__;
1134
1135     SearchDialog *searchDialog = new SearchDialog(SearchDialog::PeopleTag);
1136     queueDialog(searchDialog);
1137 }
1138
1139 void MainWindow::startLoginProcess()
1140 {
1141     qDebug() << __PRETTY_FUNCTION__;
1142
1143     LoginDialog *loginDialog = new LoginDialog();
1144
1145     emit fetchUsernameFromSettings();
1146
1147     loginDialog->clearTextFields();
1148
1149     if(!m_email.isEmpty())
1150         loginDialog->setEmailField(m_email);
1151
1152     queueDialog(loginDialog);
1153 }
1154
1155 void MainWindow::toggleFullScreen()
1156 {
1157     qDebug() << __PRETTY_FUNCTION__;
1158
1159     if(windowState() == Qt::WindowNoState)
1160         showFullScreen();
1161     else
1162         showNormal();
1163 }
1164
1165 void MainWindow::toggleProgressIndicator(bool value)
1166 {
1167     qDebug() << __PRETTY_FUNCTION__;
1168
1169 #ifdef Q_WS_MAEMO_5
1170     if(value) {
1171         m_progressIndicatorCount++;
1172         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1173     } else {
1174         if(m_progressIndicatorCount > 0)
1175             m_progressIndicatorCount--;
1176
1177         if(m_progressIndicatorCount == 0)
1178             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1179     }
1180 #else
1181     Q_UNUSED(value);
1182 #endif // Q_WS_MAEMO_5
1183 }
1184
1185 void MainWindow::updateItemVisibility()
1186 {
1187     qDebug() << __PRETTY_FUNCTION__;
1188
1189     m_tabbedPanel->setTabsEnabled(m_situareTabsIndexes, m_loggedIn);
1190 }
1191
1192 const QString MainWindow::username()
1193 {
1194     qDebug() << __PRETTY_FUNCTION__;
1195
1196     return m_email;
1197 }
1198
1199 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1200 {
1201     qDebug() << __PRETTY_FUNCTION__;
1202
1203     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1204     // qwebview starts to load a new page while the current page loading is not finished
1205     if(reply->error() != QNetworkReply::OperationCanceledError &&
1206        reply->error() != QNetworkReply::NoError) {
1207         emit error(ErrorContext::NETWORK, reply->error());
1208     }
1209 }
1210
1211 //REMOVE THIS
1212 void MainWindow::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
1213 {
1214     qWarning() << __PRETTY_FUNCTION__;
1215
1216     reply->ignoreSslErrors();
1217 }