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