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