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