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