Changed the way how the context buttons are implemented and how they are forwadded...
[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, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
354             this, SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
355
356     connect(m_routingPanel, SIGNAL(routeToLocation(const GeoCoordinate&)),
357             this, SIGNAL(routeTo(const GeoCoordinate&)));
358
359     connect(this, SIGNAL(routeParsed(Route&)),
360             m_routingPanel, SLOT(setRoute(Route&)));
361
362     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
363             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
364
365     connect(m_routingPanel, SIGNAL(requestSearchLocation()),
366             this, SLOT(startLocationSearch()));
367 }
368
369 void MainWindow::buildUserInfoPanel()
370 {
371     qDebug() << __PRETTY_FUNCTION__;
372
373     m_userInfoPanel = new UserInfoPanel(this);
374
375     connect(this, SIGNAL(userLocationReady(User*)),
376             m_userInfoPanel, SLOT(userDataReceived(User*)));
377
378     connect(this, SIGNAL(reverseGeoReady(QString)),
379             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
380
381     connect(this, SIGNAL(clearUpdateLocationDialogData()),
382             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
383
384     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
385             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
386
387     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
388             this, SIGNAL(requestReverseGeo()));
389
390     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
391             this, SIGNAL(statusUpdate(QString,bool)));
392
393     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
394             this, SIGNAL(refreshUserData()));
395
396     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
397             this, SLOT(buildInformationBox(QString, bool)));
398 }
399
400 void MainWindow::buildWebView()
401 {
402     qDebug() << __PRETTY_FUNCTION__;
403
404     if(!m_webView) {
405         m_webView = new QWebView;
406
407         if(!m_cookieJar)
408             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
409
410         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
411
412         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
413                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
414         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
415                 this, SIGNAL(updateCredentials(QUrl)));
416         connect(m_webView, SIGNAL(loadFinished(bool)),
417                 this, SLOT(loadDone(bool)));
418
419         m_webView->hide();
420     }
421 }
422
423 void MainWindow::buildZoomButtonPanel()
424 {
425     qDebug() << __PRETTY_FUNCTION__;
426
427     m_zoomButtonPanel = new ZoomButtonPanel(this);
428
429     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
430             this, SIGNAL(zoomIn()));
431
432     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
433             this, SIGNAL(zoomOut()));
434
435     connect(this, SIGNAL(zoomLevelChanged(int)),
436             m_zoomButtonPanel, SLOT(resetButtons()));
437
438     connect(this, SIGNAL(maxZoomLevelReached()),
439             m_zoomButtonPanel, SLOT(disableZoomInButton()));
440
441     connect(this, SIGNAL(minZoomLevelReached()),
442             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
443
444     connect(m_mapView, SIGNAL(viewResized(QSize)),
445             m_zoomButtonPanel, SLOT(screenResized(QSize)));
446
447     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
448             this, SIGNAL(draggingModeTriggered()));
449 }
450
451 void MainWindow::clearCookieJar()
452 {
453     qDebug() << __PRETTY_FUNCTION__;
454
455     buildWebView();
456
457     m_webView->stop();
458
459     if(!m_cookieJar) {
460         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
461     }
462     QList<QNetworkCookie> emptyList;
463     emptyList.clear();
464
465     m_cookieJar->setAllCookies(emptyList);
466     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
467 }
468
469 void MainWindow::createMenus()
470 {
471     qDebug() << __PRETTY_FUNCTION__;
472
473     // login/logout
474     m_loginAct = new QAction(tr("Login"), this);
475     connect(m_loginAct, SIGNAL(triggered()),
476             this, SIGNAL(loginActionPressed()));
477
478     // settings
479     m_toSettingsAct = new QAction(tr("Settings"), this);
480     connect(m_toSettingsAct, SIGNAL(triggered()),
481         this, SLOT(openSettingsDialog()));
482
483     // GPS
484     m_gpsToggleAct = new QAction(tr("GPS"), this);
485     m_gpsToggleAct->setCheckable(true);
486
487     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
488             this, SIGNAL(gpsTriggered(bool)));
489
490     // build the actual menu
491     m_viewMenu = menuBar()->addMenu(tr("Main"));
492     m_viewMenu->addAction(m_loginAct);
493     m_viewMenu->addAction(m_toSettingsAct);
494     m_viewMenu->addAction(m_gpsToggleAct);
495     m_viewMenu->setObjectName(tr("Menu"));
496 }
497
498 void MainWindow::dialogFinished(int status)
499 {
500     qDebug() << __PRETTY_FUNCTION__;
501
502     QDialog *dialog = m_queue.takeFirst();
503     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
504     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
505     if(loginDialog) {
506         if(status != 0) {
507             buildWebView();
508             loginDialog->userInput(m_email, m_password);
509
510             QStringList urlParts;
511             urlParts.append(FACEBOOK_LOGINBASE);
512             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
513             urlParts.append(INTERVAL1);
514             urlParts.append(SITUARE_LOGIN_SUCCESS);
515             urlParts.append(INTERVAL2);
516             urlParts.append(SITUARE_LOGIN_FAILURE);
517             urlParts.append(FACEBOOK_LOGIN_ENDING);
518
519             emit saveUsername(m_email);
520             m_refresh = true;
521             m_webView->load(QUrl(urlParts.join(EMPTY)));
522             toggleProgressIndicator(true);
523         } else {
524             emit cancelLoginProcess();
525         }
526     } else if(searchDialog) {
527         if(status != 0) {
528             emit searchForLocation(searchDialog->input());
529         }
530     }
531
532     dialog->deleteLater();
533
534     if(!m_error_queue.isEmpty() && m_errorShown == false) {
535         showErrorInformationBox();
536     } else {
537         if(!m_queue.isEmpty()) {
538             showInformationBox();
539         }
540     }
541 }
542
543 void MainWindow::drawFullScreenButton(const QSize &size)
544 {
545     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
546
547     if (m_fullScreenButton) {
548         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
549                                  size.height() - m_fullScreenButton->size().height());
550     }
551 }
552
553 void MainWindow::drawMapScale(const QSize &size)
554 {
555     qDebug() << __PRETTY_FUNCTION__;
556
557     const int LEFT_SCALE_MARGIN = 10;
558     const int BOTTOM_SCALE_MARGIN = 2;
559
560     m_mapScale->move(LEFT_SCALE_MARGIN,
561                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
562 }
563
564 void MainWindow::drawOsmLicense(const QSize &size)
565 {
566     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
567
568     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
569                        - PANEL_BAR_WIDTH,
570                        size.height() - m_osmLicense->fontMetrics().height());
571 }
572
573 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
574 {
575     qDebug() << __PRETTY_FUNCTION__;
576
577     if (m_ownLocationCrosshair != 0) {
578         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
579                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
580     }
581 }
582
583 void MainWindow::errorDialogFinished(int status)
584 {
585     qDebug() << __PRETTY_FUNCTION__;
586
587     qDebug() << status;
588     QDialog *dialog = m_error_queue.takeFirst();
589
590     dialog->deleteLater();
591     m_errorShown = false;
592
593     if(!m_error_queue.isEmpty())
594         showErrorInformationBox();
595     else if(!m_queue.isEmpty())
596         showInformationBox();
597 }
598
599 void MainWindow::gpsTimeout()
600 {
601     qDebug() << __PRETTY_FUNCTION__;
602
603     buildInformationBox(tr("GPS timeout"));
604 }
605
606 void MainWindow::grabZoomKeys(bool grab)
607 {
608     qDebug() << __PRETTY_FUNCTION__;
609
610 #ifdef Q_WS_MAEMO_5
611     // Can't grab keys unless we have a window id
612     if (!winId())
613         return;
614
615     unsigned long val = (grab) ? 1 : 0;
616     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
617     if (!atom)
618         return;
619
620     XChangeProperty (QX11Info::display(),
621                      winId(),
622                      atom,
623                      XA_INTEGER,
624                      32,
625                      PropModeReplace,
626                      reinterpret_cast<unsigned char *>(&val),
627                      1);
628 #else
629     Q_UNUSED(grab);
630 #endif // Q_WS_MAEMO_5
631 }
632
633 void MainWindow::keyPressEvent(QKeyEvent* event)
634 {
635     qDebug() << __PRETTY_FUNCTION__;
636
637     switch (event->key()) {
638     case Qt::Key_F7:
639         event->accept();
640         emit zoomIn();
641         break;
642
643     case Qt::Key_F8:
644         event->accept();
645         emit zoomOut();
646         break;
647     }
648     QWidget::keyPressEvent(event);
649 }
650
651 void MainWindow::loadCookies()
652 {
653     qDebug() << __PRETTY_FUNCTION__;
654
655     QSettings settings(DIRECTORY_NAME, FILE_NAME);
656
657     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
658
659     if(!list.isEmpty()) {
660         QList<QNetworkCookie> cookieList;
661         for(int i=0;i<list.count();i++) {
662             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
663         }
664
665         if(!m_cookieJar)
666                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
667
668         m_cookieJar->setAllCookies(cookieList);
669         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
670     }
671 }
672
673 void MainWindow::loadDone(bool done)
674 {
675     qDebug() << __PRETTY_FUNCTION__;
676
677     // for the first time the login page is opened, we need to refresh it to get cookies working
678     if(m_refresh) {
679         m_webView->reload();
680         m_refresh = false;
681     }
682
683     if (done)
684     {
685         QWebFrame* frame = m_webView->page()->currentFrame();
686         if (frame!=NULL)
687         {
688             // set email box
689             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
690
691             foreach (QWebElement element, emailCollection) {
692                 element.setAttribute("value", m_email.toAscii());
693             }
694             // set password box
695             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
696             foreach (QWebElement element, passwordCollection) {
697                 element.setAttribute("value", m_password.toAscii());
698             }
699             // find connect button
700             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
701             foreach (QWebElement element, buttonCollection)
702             {
703                 QPoint pos(element.geometry().center());
704
705                 // send a mouse click event to the web page
706                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
707                                    Qt::NoModifier);
708                 QApplication::sendEvent(m_webView->page(), &event0);
709                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
710                                    Qt::NoModifier);
711                 QApplication::sendEvent(m_webView->page(), &event1);
712             }
713         }
714     }
715 }
716
717 void MainWindow::loggedIn(bool logged)
718 {
719     qDebug() << __PRETTY_FUNCTION__;
720
721     m_loggedIn = logged;
722
723     if(logged) {
724         m_loginAct->setText(tr("Logout"));
725     } else {
726         clearCookieJar();
727         m_email.clear();
728         m_password.clear();
729
730         m_loginAct->setText(tr("Login"));
731     }
732     updateItemVisibility();
733 }
734
735 void MainWindow::loginFailed()
736 {
737     qDebug() << __PRETTY_FUNCTION__;
738
739     clearCookieJar();
740     startLoginProcess();
741 }
742
743 bool MainWindow::loginState()
744 {
745     qDebug() << __PRETTY_FUNCTION__;
746
747     return m_loggedIn;
748 }
749
750 void MainWindow::loginUsingCookies()
751 {
752     qDebug() << __PRETTY_FUNCTION__;
753
754     toggleProgressIndicator(true);
755
756     buildWebView();
757     loadCookies();
758
759     QStringList urlParts;
760     urlParts.append(FACEBOOK_LOGINBASE);
761     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
762     urlParts.append(INTERVAL1);
763     urlParts.append(SITUARE_LOGIN_SUCCESS);
764     urlParts.append(INTERVAL2);
765     urlParts.append(SITUARE_LOGIN_FAILURE);
766     urlParts.append(FACEBOOK_LOGIN_ENDING);
767
768     m_webView->load(QUrl(urlParts.join(EMPTY)));
769
770 }
771
772 void MainWindow::openSettingsDialog()
773 {
774     qDebug() << __PRETTY_FUNCTION__;
775
776     SettingsDialog *settingsDialog = new SettingsDialog(this);
777     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
778     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
779
780     settingsDialog->show();
781 }
782
783 void MainWindow::readAutomaticLocationUpdateSettings()
784 {
785     qDebug() << __PRETTY_FUNCTION__;
786
787     QSettings settings(DIRECTORY_NAME, FILE_NAME);
788     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
789     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
790                                       .toTime();
791
792     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
793         QTime time;
794         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
795     } else {
796         emit enableAutomaticLocationUpdate(false);
797     }
798 }
799
800 void MainWindow::queueDialog(QDialog *dialog)
801 {
802     qDebug() << __PRETTY_FUNCTION__;
803
804     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
805     if(dialog->isModal()) {
806         m_error_queue.append(dialog);
807     } else {
808         m_queue.append(dialog);
809     }
810
811     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
812     if(m_error_queue.count() == 1 && m_errorShown == false)
813         showErrorInformationBox();
814     else if(m_queue.count() == 1 && m_errorShown == false)
815         showInformationBox();
816 }
817
818 void MainWindow::saveCookies()
819 {
820     qDebug() << __PRETTY_FUNCTION__;
821
822     if(!m_cookieJar)
823         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
824
825     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
826     QStringList list;
827
828     for(int i=0;i<cookieList.count();i++) {
829         QNetworkCookie cookie = cookieList.at(i);
830         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
831         list.append(QString(byteArray));
832     }
833     list.removeDuplicates();
834
835     QSettings settings(DIRECTORY_NAME, FILE_NAME);
836     settings.setValue(COOKIES, list);
837 }
838
839 void MainWindow::setGPSButtonEnabled(bool enabled)
840 {
841     qDebug() << __PRETTY_FUNCTION__;
842
843     m_gpsToggleAct->setChecked(enabled);
844 }
845
846 void MainWindow::setIndicatorButtonEnabled(bool enabled)
847 {
848     qDebug() << __PRETTY_FUNCTION__;
849
850     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
851 }
852
853 void MainWindow::setMapViewScene(QGraphicsScene *scene)
854 {
855     qDebug() << __PRETTY_FUNCTION__;
856
857     m_mapView->setScene(scene);
858 }
859
860 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
861 {
862     qDebug() << __PRETTY_FUNCTION__;
863
864     if (visibility) {
865         m_ownLocationCrosshair->show();
866         drawOwnLocationCrosshair(m_viewPortSize);
867     } else {
868         m_ownLocationCrosshair->hide();
869     }
870 }
871
872 void MainWindow::settingsDialogAccepted()
873 {
874     qDebug() << __PRETTY_FUNCTION__;
875
876     readAutomaticLocationUpdateSettings();
877 }
878
879 void MainWindow::setUsername(const QString &username)
880 {
881     qDebug() << __PRETTY_FUNCTION__;
882
883     m_email = username;
884 }
885
886 void MainWindow::setViewPortSize(const QSize &size)
887 {
888     qDebug() << __PRETTY_FUNCTION__;
889
890     m_viewPortSize = size;
891 }
892
893 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
894 {
895     qDebug() << __PRETTY_FUNCTION__;
896
897     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
898                                                       tr("Automatic location update"), text,
899                                                       QMessageBox::Yes | QMessageBox::No |
900                                                       QMessageBox::Cancel, this);
901     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
902             this, SLOT(automaticUpdateDialogFinished(int)));
903
904     m_automaticUpdateLocationDialog->show();
905 }
906
907 void MainWindow::toggleFullScreen()
908 {
909     qDebug() << __PRETTY_FUNCTION__;
910
911     if(windowState() == Qt::WindowNoState)
912         showFullScreen();
913     else
914         showNormal();
915 }
916
917 void MainWindow::showErrorInformationBox()
918 {
919     qDebug() << __PRETTY_FUNCTION__;
920
921     if(m_error_queue.count()) {
922         m_errorShown = true;
923         QDialog *dialog = m_error_queue.first();
924         connect(dialog, SIGNAL(finished(int)),
925                 this, SLOT(errorDialogFinished(int)));
926         dialog->show();
927     }
928 }
929
930 void MainWindow::showInformationBox()
931 {
932     qDebug() << __PRETTY_FUNCTION__;
933
934     if(m_queue.count()) {
935         QDialog *dialog = m_queue.first();
936         connect(dialog, SIGNAL(finished(int)),
937                 this, SLOT(dialogFinished(int)));
938         dialog->show();
939     }
940 }
941
942 void MainWindow::showPanels()
943 {
944     qDebug() << __PRETTY_FUNCTION__;
945
946 ///< @todo check how this is called and can this method be removed
947
948 //    if(m_loggedIn) {
949 //        if(!m_friendsListPanel->isVisible()) {
950 //            m_friendsListPanel->show();
951 //            m_friendsListPanelSidebar->show();
952 //        }
953
954 //        if(!m_userPanel->isVisible()) {
955 //            m_userPanel->show();
956 //            m_userPanelSidebar->show();
957 //        }
958 //    }
959 }
960
961 void MainWindow::startLocationSearch()
962 {
963     qDebug() << __PRETTY_FUNCTION__;
964
965     SearchDialog *searchDialog = new SearchDialog();
966     queueDialog(searchDialog);
967 }
968
969 void MainWindow::startLoginProcess()
970 {
971     qDebug() << __PRETTY_FUNCTION__;
972
973     LoginDialog *loginDialog = new LoginDialog();
974
975     emit fetchUsernameFromSettings();
976
977     loginDialog->clearTextFields();
978
979     if(!m_email.isEmpty())
980         loginDialog->setEmailField(m_email);
981
982     queueDialog(loginDialog);
983 }
984
985 void MainWindow::toggleProgressIndicator(bool value)
986 {
987     qDebug() << __PRETTY_FUNCTION__;
988
989 #ifdef Q_WS_MAEMO_5
990     if(value) {
991         m_progressIndicatorCount++;
992         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
993     } else {
994         if(m_progressIndicatorCount > 0)
995             m_progressIndicatorCount--;
996
997         if(m_progressIndicatorCount == 0)
998             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
999     }
1000 #else
1001     Q_UNUSED(value);
1002 #endif // Q_WS_MAEMO_5
1003 }
1004
1005 void MainWindow::updateItemVisibility()
1006 {
1007     qDebug() << __PRETTY_FUNCTION__;
1008
1009 ///< @todo can this be removed?
1010
1011 //    if(!m_loggedIn) {
1012 //        m_friendsListPanel->closePanel();
1013 //        m_friendsListPanel->hide();
1014 //        m_friendsListPanelSidebar->hide();
1015
1016 //        m_userPanel->closePanel();
1017 //        m_userPanel->hide();
1018 //        m_userPanelSidebar->hide();
1019 //    }
1020 }
1021
1022 const QString MainWindow::username()
1023 {
1024     qDebug() << __PRETTY_FUNCTION__;
1025
1026     return m_email;
1027 }
1028
1029 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1030 {
1031     qDebug() << __PRETTY_FUNCTION__;
1032
1033     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1034     // qwebview starts to load a new page while the current page loading is not finished
1035     if(reply->error() != QNetworkReply::OperationCanceledError &&
1036        reply->error() != QNetworkReply::NoError) {
1037         emit error(ErrorContext::NETWORK, reply->error());
1038     }
1039 }