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