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