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