Destroy login browser after successfully logged in
[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 FacebookLoginBrowser* 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     return 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         m_webView->hide();
497     }
498 }
499
500 void MainWindow::buildZoomButtonPanel()
501 {
502     qDebug() << __PRETTY_FUNCTION__;
503
504     m_zoomButtonPanel = new ZoomButtonPanel(this);
505
506     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
507             this, SIGNAL(zoomIn()));
508
509     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
510             this, SIGNAL(zoomOut()));
511
512     connect(this, SIGNAL(zoomLevelChanged(int)),
513             m_zoomButtonPanel, SLOT(resetButtons()));
514
515     connect(this, SIGNAL(maxZoomLevelReached()),
516             m_zoomButtonPanel, SLOT(disableZoomInButton()));
517
518     connect(this, SIGNAL(minZoomLevelReached()),
519             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
520
521     connect(m_mapView, SIGNAL(viewResized(QSize)),
522             m_zoomButtonPanel, SLOT(screenResized(QSize)));
523
524     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
525             this, SIGNAL(draggingModeTriggered()));
526 }
527
528 void MainWindow::clearCookieJar()
529 {
530     qDebug() << __PRETTY_FUNCTION__;
531
532     buildWebView();
533
534     m_webView->stop();
535
536     if(!m_cookieJar) {
537         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
538     }
539     QList<QNetworkCookie> emptyList;
540     emptyList.clear();
541
542     m_cookieJar->setAllCookies(emptyList);
543     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
544 }
545
546 void MainWindow::createMenus()
547 {
548     qDebug() << __PRETTY_FUNCTION__;
549
550     // login/logout
551     m_loginAct = new QAction(tr("Login"), this);
552     connect(m_loginAct, SIGNAL(triggered()),
553             this, SIGNAL(loginActionPressed()));
554
555     // settings
556     m_toSettingsAct = new QAction(tr("Settings"), this);
557     connect(m_toSettingsAct, SIGNAL(triggered()),
558         this, SLOT(openSettingsDialog()));
559
560     // GPS
561     m_gpsToggleAct = new QAction(tr("GPS"), this);
562     m_gpsToggleAct->setCheckable(true);
563
564     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
565             this, SIGNAL(gpsTriggered(bool)));
566
567     // build the actual menu
568     m_viewMenu = menuBar()->addMenu(tr("Main"));
569     m_viewMenu->addAction(m_loginAct);
570     m_viewMenu->addAction(m_toSettingsAct);
571     m_viewMenu->addAction(m_gpsToggleAct);
572     m_viewMenu->setObjectName(tr("Menu"));
573 }
574
575 void MainWindow::destroyFacebookLoginBrowser()
576 {
577     qWarning() << __PRETTY_FUNCTION__;
578
579     m_facebookLoginBrowser->hide();
580     m_facebookLoginBrowser->disconnect();
581     m_facebookLoginBrowser->deleteLater();
582     m_facebookLoginBrowser = 0;
583 }
584
585 void MainWindow::dialogFinished(int status)
586 {
587     qDebug() << __PRETTY_FUNCTION__;
588
589     QDialog *dialog = m_queue.takeFirst();
590     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
591     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
592     if(loginDialog) {
593         if(status != 0) {
594             buildWebView();
595             loginDialog->userInput(m_email, m_password);
596
597             QStringList urlParts;
598             urlParts.append(FACEBOOK_LOGINBASE);
599             urlParts.append(API_KEY_PARAMETER_NAME);
600             urlParts.append(API_KEY);
601             urlParts.append(INTERVAL1);
602             urlParts.append(SITUARE_LOGIN_SUCCESS);
603             urlParts.append(INTERVAL2);
604             urlParts.append(SITUARE_LOGIN_FAILURE);
605             urlParts.append(FACEBOOK_LOGIN_ENDING);
606
607             emit saveUsername(m_email);
608             m_refresh = true;
609             m_webView->load(QUrl(urlParts.join(EMPTY)));
610             toggleProgressIndicator(true);
611         } else {
612             emit cancelLoginProcess();
613         }
614     } else if(searchDialog) {
615         if(status != 0) {
616             emit searchForLocation(searchDialog->input());
617         }
618     }
619
620     dialog->deleteLater();
621
622     if(!m_error_queue.isEmpty() && m_errorShown == false) {
623         showErrorInformationBox();
624     } else {
625         if(!m_queue.isEmpty()) {
626             showInformationBox();
627         }
628     }
629 }
630
631 void MainWindow::drawFullScreenButton(const QSize &size)
632 {
633     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
634
635     if (m_fullScreenButton) {
636         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
637                                  size.height() - m_fullScreenButton->size().height());
638     }
639 }
640
641 void MainWindow::drawMapScale(const QSize &size)
642 {
643     qDebug() << __PRETTY_FUNCTION__;
644
645     const int LEFT_SCALE_MARGIN = 10;
646     const int BOTTOM_SCALE_MARGIN = 2;
647
648     m_mapScale->move(LEFT_SCALE_MARGIN,
649                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
650 }
651
652 void MainWindow::drawOsmLicense(const QSize &size)
653 {
654     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
655
656     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
657                        - PANEL_BAR_WIDTH,
658                        size.height() - m_osmLicense->fontMetrics().height());
659 }
660
661 void MainWindow::errorDialogFinished(int status)
662 {
663     qDebug() << __PRETTY_FUNCTION__;
664
665     qDebug() << status;
666     QDialog *dialog = m_error_queue.takeFirst();
667
668     dialog->deleteLater();
669     m_errorShown = false;
670
671     if(!m_error_queue.isEmpty())
672         showErrorInformationBox();
673     else if(!m_queue.isEmpty())
674         showInformationBox();
675 }
676
677 void MainWindow::gpsTimeout()
678 {
679     qDebug() << __PRETTY_FUNCTION__;
680
681     buildInformationBox(tr("GPS timeout"));
682 }
683
684 void MainWindow::grabZoomKeys(bool grab)
685 {
686     qDebug() << __PRETTY_FUNCTION__;
687
688 #ifdef Q_WS_MAEMO_5
689     // Can't grab keys unless we have a window id
690     if (!winId())
691         return;
692
693     unsigned long val = (grab) ? 1 : 0;
694     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
695     if (!atom)
696         return;
697
698     XChangeProperty (QX11Info::display(),
699                      winId(),
700                      atom,
701                      XA_INTEGER,
702                      32,
703                      PropModeReplace,
704                      reinterpret_cast<unsigned char *>(&val),
705                      1);
706 #else
707     Q_UNUSED(grab);
708 #endif // Q_WS_MAEMO_5
709 }
710
711 void MainWindow::keyPressEvent(QKeyEvent* event)
712 {
713     qDebug() << __PRETTY_FUNCTION__;
714
715     switch (event->key()) {
716     case Qt::Key_F7:
717         event->accept();
718         emit zoomIn();
719         break;
720
721     case Qt::Key_F8:
722         event->accept();
723         emit zoomOut();
724         break;
725     }
726     QWidget::keyPressEvent(event);
727 }
728
729 void MainWindow::loadCookies()
730 {
731     qDebug() << __PRETTY_FUNCTION__;
732
733     QSettings settings(DIRECTORY_NAME, FILE_NAME);
734
735     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
736
737     if(!list.isEmpty()) {
738         QList<QNetworkCookie> cookieList;
739         for(int i=0;i<list.count();i++) {
740             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
741         }
742
743         if(!m_cookieJar)
744                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
745
746         m_cookieJar->setAllCookies(cookieList);
747         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
748     }
749 }
750
751 void MainWindow::loadDone(bool done)
752 {
753     qDebug() << __PRETTY_FUNCTION__;
754
755     // for the first time the login page is opened, we need to refresh it to get cookies working
756     if(m_refresh) {
757         m_webView->reload();
758         m_refresh = false;
759     }
760
761     if (done)
762     {
763         QWebFrame* frame = m_webView->page()->currentFrame();
764         if (frame!=NULL)
765         {
766             // set email box
767             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
768
769             foreach (QWebElement element, emailCollection) {
770                 element.setAttribute("value", m_email.toAscii());
771             }
772             // set password box
773             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
774             foreach (QWebElement element, passwordCollection) {
775                 element.setAttribute("value", m_password.toAscii());
776             }
777             // find connect button
778             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
779             foreach (QWebElement element, buttonCollection)
780             {
781                 QPoint pos(element.geometry().center());
782
783                 // send a mouse click event to the web page
784                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
785                                    Qt::NoModifier);
786                 QApplication::sendEvent(m_webView->page(), &event0);
787                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
788                                    Qt::NoModifier);
789                 QApplication::sendEvent(m_webView->page(), &event1);
790             }
791         }
792     }
793 }
794
795 void MainWindow::loggedIn(bool logged)
796 {
797     qDebug() << __PRETTY_FUNCTION__;
798
799     m_loggedIn = logged;
800
801     if(logged) {
802         m_loginAct->setText(tr("Logout"));
803     } else {
804         clearCookieJar();
805         m_email.clear();
806         m_password.clear();
807
808         m_loginAct->setText(tr("Login"));
809         m_userInfoPanel->showUserInfo(false);
810     }
811     updateItemVisibility();
812 }
813
814 void MainWindow::loginFailed()
815 {
816     qDebug() << __PRETTY_FUNCTION__;
817
818     clearCookieJar();
819     startLoginProcess();
820 }
821
822 bool MainWindow::loginState()
823 {
824     qDebug() << __PRETTY_FUNCTION__;
825
826     return m_loggedIn;
827 }
828
829 void MainWindow::loginUsingCookies()
830 {
831     qDebug() << __PRETTY_FUNCTION__;
832
833     toggleProgressIndicator(true);
834
835     buildWebView();
836     loadCookies();
837
838     QStringList urlParts;
839     urlParts.append(FACEBOOK_LOGINBASE);
840     urlParts.append(API_KEY_PARAMETER_NAME);
841     urlParts.append(API_KEY);
842     urlParts.append(INTERVAL1);
843     urlParts.append(SITUARE_LOGIN_SUCCESS);
844     urlParts.append(INTERVAL2);
845     urlParts.append(SITUARE_LOGIN_FAILURE);
846     urlParts.append(FACEBOOK_LOGIN_ENDING);
847
848     m_webView->load(QUrl(urlParts.join(EMPTY)));
849
850 }
851
852 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
853 {
854     m_mapCenterHorizontalShifting = shifting;
855     moveCrosshair();
856 }
857
858 void MainWindow::moveCrosshair()
859 {
860     qDebug() << __PRETTY_FUNCTION__;
861
862     if (m_crosshair) {
863         int mapHeight = m_mapView->size().height();
864         int mapWidth = m_mapView->size().width();
865         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
866                           - m_mapCenterHorizontalShifting,
867                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
868     }
869 }
870
871 void MainWindow::openSettingsDialog()
872 {
873     qDebug() << __PRETTY_FUNCTION__;
874
875     SettingsDialog *settingsDialog = new SettingsDialog(this);
876     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
877     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
878
879     settingsDialog->show();
880 }
881
882 void MainWindow::queueDialog(QDialog *dialog)
883 {
884     qDebug() << __PRETTY_FUNCTION__;
885
886     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
887     if(dialog->isModal()) {
888         m_error_queue.append(dialog);
889     } else {
890         m_queue.append(dialog);
891     }
892
893     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
894     if(m_error_queue.count() == 1 && m_errorShown == false)
895         showErrorInformationBox();
896     else if(m_queue.count() == 1 && m_errorShown == false)
897         showInformationBox();
898 }
899
900 void MainWindow::readAutomaticLocationUpdateSettings()
901 {
902     qDebug() << __PRETTY_FUNCTION__;
903
904     QSettings settings(DIRECTORY_NAME, FILE_NAME);
905     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
906     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
907                                       .toTime();
908
909     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
910         QTime time;
911         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
912     } else {
913         emit enableAutomaticLocationUpdate(false);
914     }
915 }
916
917 void MainWindow::saveCookies()
918 {
919     qDebug() << __PRETTY_FUNCTION__;
920
921     if(!m_cookieJar)
922         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
923
924     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
925     QStringList list;
926
927     for(int i=0;i<cookieList.count();i++) {
928         QNetworkCookie cookie = cookieList.at(i);
929         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
930         list.append(QString(byteArray));
931     }
932     list.removeDuplicates();
933
934     QSettings settings(DIRECTORY_NAME, FILE_NAME);
935     settings.setValue(COOKIES, list);
936 }
937
938 void MainWindow::setCrosshairVisibility(bool visibility)
939 {
940     qDebug() << __PRETTY_FUNCTION__;
941
942     if (visibility) {
943         m_crosshair->show();
944         moveCrosshair();
945     } else {
946         m_crosshair->hide();
947     }
948 }
949
950 void MainWindow::setGPSButtonEnabled(bool enabled)
951 {
952     qDebug() << __PRETTY_FUNCTION__;
953
954     m_gpsToggleAct->setChecked(enabled);
955 }
956
957 void MainWindow::setIndicatorButtonEnabled(bool enabled)
958 {
959     qDebug() << __PRETTY_FUNCTION__;
960
961     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
962 }
963
964 void MainWindow::setMapViewScene(QGraphicsScene *scene)
965 {
966     qDebug() << __PRETTY_FUNCTION__;
967
968     m_mapView->setScene(scene);
969 }
970
971 void MainWindow::settingsDialogAccepted()
972 {
973     qDebug() << __PRETTY_FUNCTION__;
974
975     readAutomaticLocationUpdateSettings();
976 }
977
978 void MainWindow::setUsername(const QString &username)
979 {
980     qDebug() << __PRETTY_FUNCTION__;
981
982     m_email = username;
983 }
984
985 void MainWindow::showContactDialog(const QString &guid)
986 {
987     qDebug() << __PRETTY_FUNCTION__;
988
989 #if defined(Q_WS_MAEMO_5) & defined(ARMEL)
990     OssoABookDialog::showContactDialog(guid);
991 #else
992     Q_UNUSED(guid);
993     buildInformationBox(tr("Contact dialog works only on phone!"), true);
994 #endif
995 }
996
997 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
998 {
999     qDebug() << __PRETTY_FUNCTION__;
1000
1001     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
1002                                                       tr("Automatic location update"), text,
1003                                                       QMessageBox::Yes | QMessageBox::No |
1004                                                       QMessageBox::Cancel, this);
1005     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
1006             this, SLOT(automaticUpdateDialogFinished(int)));
1007
1008     m_automaticUpdateLocationDialog->show();
1009 }
1010
1011 void MainWindow::showErrorInformationBox()
1012 {
1013     qDebug() << __PRETTY_FUNCTION__;
1014
1015     if(m_error_queue.count()) {
1016         m_errorShown = true;
1017         QDialog *dialog = m_error_queue.first();
1018         connect(dialog, SIGNAL(finished(int)),
1019                 this, SLOT(errorDialogFinished(int)));
1020         dialog->show();
1021     }
1022 }
1023
1024 void MainWindow::showInformationBox()
1025 {
1026     qDebug() << __PRETTY_FUNCTION__;
1027
1028     if(m_queue.count()) {
1029         QDialog *dialog = m_queue.first();
1030         connect(dialog, SIGNAL(finished(int)),
1031                 this, SLOT(dialogFinished(int)));
1032         dialog->show();
1033     }
1034 }
1035
1036 void MainWindow::startLocationSearch()
1037 {
1038     qDebug() << __PRETTY_FUNCTION__;
1039
1040     SearchDialog *searchDialog = new SearchDialog();
1041     queueDialog(searchDialog);
1042 }
1043
1044 void MainWindow::startLoginProcess()
1045 {
1046     qDebug() << __PRETTY_FUNCTION__;
1047
1048     LoginDialog *loginDialog = new LoginDialog();
1049
1050     emit fetchUsernameFromSettings();
1051
1052     loginDialog->clearTextFields();
1053
1054     if(!m_email.isEmpty())
1055         loginDialog->setEmailField(m_email);
1056
1057     queueDialog(loginDialog);
1058 }
1059
1060 void MainWindow::toggleFullScreen()
1061 {
1062     qDebug() << __PRETTY_FUNCTION__;
1063
1064     if(windowState() == Qt::WindowNoState)
1065         showFullScreen();
1066     else
1067         showNormal();
1068 }
1069
1070 void MainWindow::toggleProgressIndicator(bool value)
1071 {
1072     qDebug() << __PRETTY_FUNCTION__;
1073
1074 #ifdef Q_WS_MAEMO_5
1075     if(value) {
1076         m_progressIndicatorCount++;
1077         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1078     } else {
1079         if(m_progressIndicatorCount > 0)
1080             m_progressIndicatorCount--;
1081
1082         if(m_progressIndicatorCount == 0)
1083             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1084     }
1085 #else
1086     Q_UNUSED(value);
1087 #endif // Q_WS_MAEMO_5
1088 }
1089
1090 void MainWindow::updateItemVisibility()
1091 {
1092     qDebug() << __PRETTY_FUNCTION__;
1093
1094     m_tabbedPanel->setTabsEnabled(m_situareTabsIndexes, m_loggedIn);
1095 }
1096
1097 const QString MainWindow::username()
1098 {
1099     qDebug() << __PRETTY_FUNCTION__;
1100
1101     return m_email;
1102 }
1103
1104 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1105 {
1106     qDebug() << __PRETTY_FUNCTION__;
1107
1108     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1109     // qwebview starts to load a new page while the current page loading is not finished
1110     if(reply->error() != QNetworkReply::OperationCanceledError &&
1111        reply->error() != QNetworkReply::NoError) {
1112         emit error(ErrorContext::NETWORK, reply->error());
1113     }
1114 }