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