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