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