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