Merge branch 'master' into settings_auto_update
[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
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtGui>
27 #include <QtWebKit>
28 #include <QtAlgorithms>
29
30 #include "common.h"
31 #include "facebookservice/facebookauthentication.h"
32 #include "friendlistpanel.h"
33 #include "logindialog.h"
34 #include "map/mapview.h"
35 #include "settingsdialog.h"
36 #include "userinfopanel.h"
37 #include "zoombuttonpanel.h"
38
39 #include "mainwindow.h"
40
41 // These MUST BE HERE, compiling for Maemo fails if moved
42 #ifdef Q_WS_MAEMO_5
43 #include <QtMaemo5/QMaemo5InformationBox>
44 #include <QtGui/QX11Info>
45 #include <X11/Xatom.h>
46 #include <X11/Xlib.h>
47 #endif // Q_WS_MAEMO_5
48
49 // values for setting screen size in desktop matching N900 screen size
50 const int N900_APP_WIDTH = 800;
51 const int N900_APP_HEIGHT = 449;
52
53 MainWindow::MainWindow(QWidget *parent)
54     : QMainWindow(parent),
55     m_drawOwnLocationCrosshair(false),
56     m_errorShown(false),
57     m_loggedIn(false),
58     m_refresh(false),
59     m_ownLocationCrosshair(0),
60     m_email(),    
61     m_password(),
62     m_fullScreenButton(0),
63     m_webView(0),
64     m_cookieJar(0)
65 {
66     qDebug() << __PRETTY_FUNCTION__;
67
68     buildMap();
69
70     // build main layout
71     QHBoxLayout *layout = new QHBoxLayout;
72     layout->addWidget(m_mapView);
73     layout->setMargin(0);
74     setCentralWidget(new QWidget());
75     centralWidget()->setLayout(layout);
76
77     buildFriendListPanel();
78     buildUserInfoPanel();
79
80     m_settingsDialog = new SettingsDialog(this);
81     m_settingsDialog->hide();
82     connect(m_settingsDialog, SIGNAL(enableAutomaticLocationUpdate(bool,int)),
83             this, SIGNAL(enableAutomaticLocationUpdate(bool,int)));
84
85     createMenus();
86     setWindowTitle(tr("Situare"));
87
88     // set stacking order of widgets
89     m_zoomButtonPanel->stackUnder(m_userPanel);
90     if(m_fullScreenButton) {
91         m_fullScreenButton->stackUnder(m_zoomButtonPanel);
92         m_osmLicense->stackUnder(m_fullScreenButton);
93     } else
94         m_osmLicense->stackUnder(m_zoomButtonPanel);
95     m_ownLocationCrosshair->stackUnder(m_osmLicense);
96     m_mapView->stackUnder(m_ownLocationCrosshair);
97
98     this->toggleProgressIndicator(true);
99
100     grabZoomKeys(true);
101
102     // set screen size in desktop matching N900 screen size
103     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
104 }
105
106 MainWindow::~MainWindow()
107 {
108     qDebug() << __PRETTY_FUNCTION__;
109
110     grabZoomKeys(false);
111
112     if(m_webView)
113         delete m_webView;
114
115     qDeleteAll(m_queue.begin(), m_queue.end());
116     m_queue.clear();
117
118     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
119     m_error_queue.clear();
120 }
121
122 void MainWindow::automaticLocationUpdateEnabled(bool enabled)
123 {
124     m_settingsDialog->setAutomaticLocationUpdateSettings(enabled);
125 }
126
127 void MainWindow::buildFullScreenButton()
128 {
129     qDebug() << __PRETTY_FUNCTION__;
130 #ifdef Q_WS_MAEMO_5
131     m_fullScreenButton = new QToolButton(this);
132     m_fullScreenButton->setIcon(QIcon::fromTheme(QLatin1String("general_fullsize")));
133     m_fullScreenButton->setFixedSize(m_fullScreenButton->sizeHint());
134     connect(m_fullScreenButton, SIGNAL(clicked()),
135             this, SLOT(toggleFullScreen()));
136 #endif // Q_WS_MAEMO_5
137
138 }
139
140 void MainWindow::buildFriendListPanel()
141 {
142     qDebug() << __PRETTY_FUNCTION__;
143
144     m_friendsListPanel = new FriendListPanel(this);
145     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
146
147     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
148
149     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
150             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
151
152     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
153             this, SIGNAL(findFriend(QPointF)));
154
155     connect(m_mapView, SIGNAL(viewResized(QSize)),
156             m_friendsListPanel, SLOT(screenResized(QSize)));
157
158     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
159             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
160
161     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
162             m_friendsListPanelSidebar, SLOT(reDrawSidebar(int, int)));
163 }
164
165 void MainWindow::buildInformationBox(const QString &message, bool modal)
166 {
167     qDebug() << __PRETTY_FUNCTION__;
168
169 #ifdef Q_WS_MAEMO_5
170     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
171     QLabel *label = new QLabel(msgBox);
172     label->setAlignment(Qt::AlignCenter);
173     label->setText(message);
174     msgBox->setWidget(label);
175
176     if(modal) {
177         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
178     } else {
179         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
180     }
181 #else
182     QMessageBox *msgBox = new QMessageBox(this);
183     msgBox->button(QMessageBox::Ok);
184     msgBox->setText(message);
185     msgBox->setModal(modal);
186 #endif
187
188     queueDialog(msgBox);
189 }
190
191 void MainWindow::buildManualLocationCrosshair()
192 {
193     qDebug() << __PRETTY_FUNCTION__;
194
195     m_ownLocationCrosshair = new QLabel(this);
196     QPixmap crosshairImage(":/res/images/sight.png");
197     m_ownLocationCrosshair->setPixmap(crosshairImage);
198     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
199     m_ownLocationCrosshair->hide();
200     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
201
202     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
203             this, SLOT(drawOwnLocationCrosshair(int, int)));
204 }
205
206 void MainWindow::buildMap()
207 {
208     qDebug() << __PRETTY_FUNCTION__;
209
210     m_mapView = new MapView(this);
211
212     buildZoomButtonPanel();
213     buildOsmLicense();
214     buildManualLocationCrosshair();
215     buildFullScreenButton();
216
217     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
218             this, SIGNAL(mapViewScrolled(QPoint)));
219
220     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
221             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
222
223     connect(m_mapView, SIGNAL(viewResized(QSize)),
224             this, SIGNAL(mapViewResized(QSize)));
225
226     connect(m_mapView, SIGNAL(viewResized(QSize)),
227             this, SLOT(drawFullScreenButton(QSize)));
228
229     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
230              this, SLOT(setViewPortSize(int, int)));
231
232     connect(this, SIGNAL(zoomLevelChanged(int)),
233             m_mapView, SLOT(setZoomLevel(int)));
234
235     connect(m_mapView, SIGNAL(viewZoomFinished()),
236             this, SIGNAL(viewZoomFinished()));
237 }
238
239 void MainWindow::buildOsmLicense()
240 {
241     qDebug() << __PRETTY_FUNCTION__;
242
243     m_osmLicense = new QLabel(this);
244     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
245     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
246     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
247     m_osmLicense->setFont(QFont("Nokia Sans", 9));
248     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
249                          m_osmLicense->fontMetrics().height());
250
251     connect(m_mapView, SIGNAL(viewResized(QSize)),
252             this, SLOT(drawOsmLicense(QSize)));
253 }
254
255 void MainWindow::buildUserInfoPanel()
256 {
257     qDebug() << __PRETTY_FUNCTION__;
258
259     m_userPanel = new UserInfoPanel(this);
260     m_userPanelSidebar = new PanelSideBar(this, LEFT);
261
262     m_userPanelSidebar->stackUnder(m_friendsListPanel);
263     m_userPanel->stackUnder(m_userPanelSidebar);
264
265     connect(m_userPanel, SIGNAL(findUser(QPointF)),
266             this, SIGNAL(findUser(QPointF)));
267
268     connect(this, SIGNAL(userLocationReady(User*)),
269             m_userPanel, SLOT(userDataReceived(User*)));
270
271     connect(m_userPanel, SIGNAL(requestReverseGeo()),
272             this, SIGNAL(requestReverseGeo()));
273
274     connect(this, SIGNAL(reverseGeoReady(QString)),
275             m_userPanel, SIGNAL(reverseGeoReady(QString)));
276
277     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
278             this, SIGNAL(statusUpdate(QString,bool)));
279
280     connect(m_userPanel, SIGNAL(refreshUserData()),
281             this, SIGNAL(refreshUserData()));
282
283     connect(m_mapView, SIGNAL(viewResized(QSize)),
284             m_userPanel, SLOT(screenResized(QSize)));
285
286     connect(this, SIGNAL(updateWasSuccessful()),
287             m_userPanel, SIGNAL(updateWasSuccessful()));
288
289     connect(this, SIGNAL(messageSendingFailed(QString)),
290             m_userPanel, SIGNAL(messageSendingFailed(QString)));
291
292     connect(m_userPanel, SIGNAL(notificateUpdateFailing(QString)),
293             this, SIGNAL(notificateUpdateFailing(QString)));
294 }
295
296 void MainWindow::buildWebView()
297 {
298     qDebug() << __PRETTY_FUNCTION__;
299
300     if(!m_webView) {
301         m_webView = new QWebView;
302
303         if(!m_cookieJar)
304             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
305
306         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
307
308         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
309                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
310         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
311                 this, SIGNAL(updateCredentials(QUrl)));
312         connect(m_webView, SIGNAL(loadFinished(bool)),
313                 this, SLOT(loadDone(bool)));
314
315         m_webView->hide();
316     }
317 }
318
319 void MainWindow::buildZoomButtonPanel()
320 {
321     qDebug() << __PRETTY_FUNCTION__;
322
323     m_zoomButtonPanel = new ZoomButtonPanel(this);
324
325     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
326             this, SIGNAL(zoomIn()));
327
328     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
329             this, SIGNAL(zoomOut()));
330
331     connect(this, SIGNAL(zoomLevelChanged(int)),
332             m_zoomButtonPanel, SLOT(resetButtons()));
333
334     connect(this, SIGNAL(maxZoomLevelReached()),
335             m_zoomButtonPanel, SLOT(disableZoomInButton()));
336
337     connect(this, SIGNAL(minZoomLevelReached()),
338             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
339
340     connect(m_mapView, SIGNAL(viewResized(QSize)),
341             m_zoomButtonPanel, SLOT(screenResized(QSize)));
342 }
343
344 void MainWindow::clearCookieJar()
345 {
346     qDebug() << __PRETTY_FUNCTION__;
347
348     buildWebView();
349
350     if(!m_cookieJar) {
351         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
352     }
353     QList<QNetworkCookie> emptyList;
354     emptyList.clear();
355
356     m_cookieJar->setAllCookies(emptyList);
357     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
358 }
359
360 void MainWindow::createMenus()
361 {
362     qDebug() << __PRETTY_FUNCTION__;
363
364     // login/logout
365     m_loginAct = new QAction(tr("Login"), this);
366     connect(m_loginAct, SIGNAL(triggered()),
367             this, SIGNAL(loginActionPressed()));
368
369     // settings
370     m_toSettingsAct = new QAction(tr("Settings"), this);
371     connect(m_toSettingsAct, SIGNAL(triggered()),
372         this, SLOT(openSettingsDialog()));
373
374     // GPS
375     m_gpsToggleAct = new QAction(tr("GPS"), this);
376     m_gpsToggleAct->setCheckable(true);
377
378     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
379             this, SIGNAL(gpsTriggered(bool)));
380
381     // automatic centering
382     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
383     m_autoCenteringAct->setCheckable(true);
384     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
385         this, SIGNAL(autoCenteringTriggered(bool)));
386
387     // build the actual menu
388     m_viewMenu = menuBar()->addMenu(tr("Main"));
389     m_viewMenu->addAction(m_loginAct);
390     m_viewMenu->addAction(m_toSettingsAct);
391     m_viewMenu->addAction(m_gpsToggleAct);
392     m_viewMenu->addAction(m_autoCenteringAct);
393     m_viewMenu->setObjectName(tr("Menu"));
394 }
395
396 void MainWindow::dialogFinished(int status)
397 {
398     qDebug() << __PRETTY_FUNCTION__;
399
400     QDialog *dialog = m_queue.takeFirst();
401     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
402     if(loginDialog) {
403         if(status != 0) {
404             buildWebView();
405             loginDialog->userInput(m_email, m_password);
406
407             QStringList urlParts;
408             urlParts.append(FACEBOOK_LOGINBASE);
409             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
410             urlParts.append(INTERVAL1);
411             urlParts.append(SITUARE_LOGIN_SUCCESS);
412             urlParts.append(INTERVAL2);
413             urlParts.append(SITUARE_LOGIN_FAILURE);
414             urlParts.append(FACEBOOK_LOGIN_ENDING);
415
416             emit saveUsername(m_email);
417             m_refresh = true;
418             m_webView->load(QUrl(urlParts.join(EMPTY)));
419             toggleProgressIndicator(true);
420         } else {
421             emit cancelLoginProcess();
422         }
423     }
424
425     dialog->deleteLater();
426
427     if(!m_error_queue.isEmpty() && m_errorShown == false) {
428         showErrorInformationBox();
429     } else {
430         if(!m_queue.isEmpty()) {
431             showInformationBox();
432         }
433     }
434 }
435
436 void MainWindow::drawFullScreenButton(const QSize &size)
437 {
438     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
439
440     if(m_fullScreenButton) {
441         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
442                                  - PANEL_PEEK_AMOUNT,
443                                  size.height() - m_fullScreenButton->size().height());
444     }
445 }
446
447 void MainWindow::drawOsmLicense(const QSize &size)
448 {
449     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
450
451     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
452                        - PANEL_PEEK_AMOUNT,
453                        size.height() - m_osmLicense->fontMetrics().height());
454 }
455
456 void MainWindow::drawOwnLocationCrosshair(int width, int height)
457 {
458     qDebug() << __PRETTY_FUNCTION__;
459
460     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
461         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
462                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
463     }
464 }
465
466 void MainWindow::errorDialogFinished(int status)
467 {
468     qDebug() << __PRETTY_FUNCTION__;
469
470     qDebug() << status;
471     QDialog *dialog = m_error_queue.takeFirst();
472
473     dialog->deleteLater();
474     m_errorShown = false;
475
476     if(!m_error_queue.isEmpty())
477         showErrorInformationBox();
478     else if(!m_queue.isEmpty())
479         showInformationBox();
480 }
481
482 void MainWindow::gpsTimeout()
483 {
484     qDebug() << __PRETTY_FUNCTION__;
485
486     buildInformationBox(tr("GPS timeout"));
487 }
488
489 void MainWindow::grabZoomKeys(bool grab)
490 {
491     qDebug() << __PRETTY_FUNCTION__;
492
493 #ifdef Q_WS_MAEMO_5
494     // Can't grab keys unless we have a window id
495     if (!winId())
496         return;
497
498     unsigned long val = (grab) ? 1 : 0;
499     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
500     if (!atom)
501         return;
502
503     XChangeProperty (QX11Info::display(),
504                      winId(),
505                      atom,
506                      XA_INTEGER,
507                      32,
508                      PropModeReplace,
509                      reinterpret_cast<unsigned char *>(&val),
510                      1);
511 #else
512     Q_UNUSED(grab);
513 #endif // Q_WS_MAEMO_5
514 }
515
516 void MainWindow::keyPressEvent(QKeyEvent* event)
517 {
518     qDebug() << __PRETTY_FUNCTION__;
519
520     switch (event->key()) {
521     case Qt::Key_F7:
522         event->accept();
523         emit zoomIn();
524         break;
525
526     case Qt::Key_F8:
527         event->accept();
528         emit zoomOut();
529         break;
530     }
531     QWidget::keyPressEvent(event);
532 }
533
534 void MainWindow::loadCookies()
535 {
536     qDebug() << __PRETTY_FUNCTION__;
537
538     QSettings settings(DIRECTORY_NAME, FILE_NAME);
539
540     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
541
542     if(!list.isEmpty()) {
543         QList<QNetworkCookie> cookieList;
544         for(int i=0;i<list.count();i++) {
545             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
546         }
547
548         if(!m_cookieJar)
549                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
550
551         m_cookieJar->setAllCookies(cookieList);
552         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
553
554     }
555 }
556
557 void MainWindow::loadDone(bool done)
558 {
559     qDebug() << __PRETTY_FUNCTION__;
560
561     // for the first time the login page is opened, we need to refresh it to get cookies working
562     if(m_refresh) {
563         m_webView->reload();
564         m_refresh = false;
565     }
566
567     if (done)
568     {
569         QWebFrame* frame = m_webView->page()->currentFrame();
570         if (frame!=NULL)
571         {
572             // set email box
573             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
574
575             foreach (QWebElement element, emailCollection) {
576                 element.setAttribute("value", m_email.toAscii());
577             }
578             // set password box
579             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
580             foreach (QWebElement element, passwordCollection) {
581                 element.setAttribute("value", m_password.toAscii());
582             }
583             // find connect button
584             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
585             foreach (QWebElement element, buttonCollection)
586             {
587                 QPoint pos(element.geometry().center());
588
589                 // send a mouse click event to the web page
590                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
591                                    Qt::NoModifier);
592                 QApplication::sendEvent(m_webView->page(), &event0);
593                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
594                                    Qt::NoModifier);
595                 QApplication::sendEvent(m_webView->page(), &event1);
596             }
597         }
598     }
599 }
600
601 void MainWindow::loggedIn(bool logged)
602 {
603     qDebug() << __PRETTY_FUNCTION__;
604
605     m_loggedIn = logged;
606
607     if(logged) {
608         m_loginAct->setText(tr("Logout"));
609     } else {
610         clearCookieJar();
611         m_email.clear();
612         m_password.clear();
613
614         m_loginAct->setText(tr("Login"));
615     }
616     updateItemVisibility(m_loggedIn);
617 }
618
619 void MainWindow::loginFailed()
620 {
621     qDebug() << __PRETTY_FUNCTION__;
622
623     clearCookieJar();
624
625     toggleProgressIndicator(false);
626
627     startLoginProcess();
628 }
629
630 void MainWindow::loginUsingCookies()
631 {
632     qDebug() << __PRETTY_FUNCTION__;
633
634     buildWebView();
635     loadCookies();
636     
637     QStringList urlParts;
638     urlParts.append(FACEBOOK_LOGINBASE);
639     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
640     urlParts.append(INTERVAL1);
641     urlParts.append(SITUARE_LOGIN_SUCCESS);
642     urlParts.append(INTERVAL2);
643     urlParts.append(SITUARE_LOGIN_FAILURE);
644     urlParts.append(FACEBOOK_LOGIN_ENDING);
645
646     m_webView->load(QUrl(urlParts.join(EMPTY)));
647
648 }
649
650 void MainWindow::openSettingsDialog()
651 {
652     qDebug() << __PRETTY_FUNCTION__;
653
654     m_settingsDialog->enableSituareSettings(m_gpsToggleAct->isChecked() && m_loggedIn);
655     m_settingsDialog->show();
656 }
657
658 void MainWindow::requestAutomaticLocationUpdateSettings()
659 {
660     qDebug() << __PRETTY_FUNCTION__;
661
662     m_settingsDialog->emitAutomaticLocationUpdateSettings();
663 }
664
665 void MainWindow::queueDialog(QDialog *dialog)
666 {
667     qDebug() << __PRETTY_FUNCTION__;
668
669     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
670     if(dialog->isModal()) {
671         m_error_queue.append(dialog);
672     } else {
673         m_queue.append(dialog);
674     }
675
676     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
677     if(m_error_queue.count() == 1 && m_errorShown == false)
678         showErrorInformationBox();
679     else if(m_queue.count() == 1 && m_errorShown == false)
680         showInformationBox();
681 }
682
683 void MainWindow::saveCookies()
684 {
685     qDebug() << __PRETTY_FUNCTION__;
686
687     if(!m_cookieJar)
688         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
689
690     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
691     QStringList list;
692
693     for(int i=0;i<cookieList.count();i++) {
694         QNetworkCookie cookie = cookieList.at(i);
695         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
696         list.append(QString(byteArray));
697     }
698     list.removeDuplicates();
699
700     QSettings settings(DIRECTORY_NAME, FILE_NAME);
701     settings.setValue(COOKIES, list);
702 }
703
704 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
705 {
706     qDebug() << __PRETTY_FUNCTION__;
707
708     m_autoCenteringAct->setChecked(enabled);
709 }
710
711 void MainWindow::setGPSButtonEnabled(bool enabled)
712 {
713     qDebug() << __PRETTY_FUNCTION__;
714
715     m_gpsToggleAct->setChecked(enabled);
716
717     if(m_loggedIn)
718         setOwnLocationCrosshairVisibility(!enabled);
719
720     m_autoCenteringAct->setVisible(enabled);
721 }
722
723 void MainWindow::setMapViewScene(QGraphicsScene *scene)
724 {
725     qDebug() << __PRETTY_FUNCTION__;
726
727     m_mapView->setScene(scene);
728 }
729
730 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
731 {
732     qDebug() << __PRETTY_FUNCTION__;
733
734     if (visibility) {
735         m_ownLocationCrosshair->show();
736         m_drawOwnLocationCrosshair = true;
737         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
738     } else {
739         m_ownLocationCrosshair->hide();
740         m_drawOwnLocationCrosshair = false;
741     }
742 }
743
744 void MainWindow::setUsername(const QString &username)
745 {
746     qDebug() << __PRETTY_FUNCTION__;
747
748     m_email = username;
749 }
750
751 void MainWindow::setViewPortSize(int width, int height)
752 {
753     qDebug() << __PRETTY_FUNCTION__;
754
755     m_viewPortWidth = width;
756     m_viewPortHeight = height;
757 }
758
759 bool MainWindow::showEnableAutomaticUpdateLocationDialog()
760 {
761     QMessageBox msgBox(QMessageBox::Question, tr("Automatic location update"),
762                        tr("Are you sure you want to enable automatic location update?"),
763                        QMessageBox::Ok | QMessageBox::Cancel, 0);
764     msgBox.button(QMessageBox::Ok)->setText(tr("Ok"));
765     qWarning() << __PRETTY_FUNCTION__;
766     int ret = msgBox.exec();
767     qWarning() << __PRETTY_FUNCTION__;
768     if (ret == QMessageBox::Ok)
769         return true;
770     else
771         return false;
772 }
773
774 void MainWindow::toggleFullScreen()
775 {
776     qDebug() << __PRETTY_FUNCTION__;
777
778     if(windowState() == Qt::WindowNoState)
779         showFullScreen();
780     else
781         showNormal();
782 }
783
784 void MainWindow::showErrorInformationBox()
785 {
786     qDebug() << __PRETTY_FUNCTION__;
787
788     if(m_error_queue.count()) {
789         m_errorShown = true;
790         QDialog *dialog = m_error_queue.first();
791         connect(dialog, SIGNAL(finished(int)),
792                 this, SLOT(errorDialogFinished(int)));
793         dialog->show();
794     }
795 }
796
797 void MainWindow::showInformationBox()
798 {
799     qDebug() << __PRETTY_FUNCTION__;
800
801     if(m_queue.count()) {
802         QDialog *dialog = m_queue.first();
803         connect(dialog, SIGNAL(finished(int)),
804                 this, SLOT(dialogFinished(int)));
805         dialog->show();
806     }
807 }
808
809 void MainWindow::startLoginProcess()
810 {
811     qDebug() << __PRETTY_FUNCTION__;
812
813     LoginDialog *loginDialog = new LoginDialog();
814
815     emit fetchUsernameFromSettings();
816
817     loginDialog->clearTextFields();
818
819     if(!m_email.isEmpty())
820         loginDialog->setEmailField(m_email);
821
822     queueDialog(loginDialog);
823 }
824
825 void MainWindow::toggleProgressIndicator(bool value)
826 {
827     qDebug() << __PRETTY_FUNCTION__;
828
829 #ifdef Q_WS_MAEMO_5
830     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
831 #else
832     Q_UNUSED(value);
833 #endif // Q_WS_MAEMO_5
834 }
835
836 void MainWindow::updateItemVisibility(bool show)
837 {
838     qDebug() << __PRETTY_FUNCTION__;
839     
840     if(show) {
841         m_friendsListPanel->show();
842         m_friendsListPanelSidebar->show();
843         m_userPanel->show();
844         m_userPanelSidebar->show();
845
846         if(m_drawOwnLocationCrosshair) {
847             m_ownLocationCrosshair->show();
848             setGPSButtonEnabled(false);
849             emit gpsTriggered(false);
850         }
851     } else {
852         m_friendsListPanel->closePanel();
853         m_friendsListPanel->hide();
854         m_friendsListPanelSidebar->hide();
855         m_userPanel->closePanel();
856         m_userPanel->hide();
857         m_userPanelSidebar->hide();
858         m_ownLocationCrosshair->hide();       
859     }
860 }
861
862 const QString MainWindow::username()
863 {
864     qDebug() << __PRETTY_FUNCTION__;
865     
866     return m_email;
867 }
868
869 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
870 {
871     qDebug() << __PRETTY_FUNCTION__;
872
873     if(reply->error()) {
874         qDebug() << reply->error() << reply->errorString();
875         toggleProgressIndicator(false);
876     }
877 }
878