8b5842689346348bf6188062103f4610244e7219
[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
29 #ifdef Q_WS_MAEMO_5
30 #include <QtMaemo5/QMaemo5InformationBox>
31 #endif // Q_WS_MAEMO_5
32
33 #include "common.h"
34 #include "facebookservice/facebookauthentication.h"
35 #include "friendlistpanel.h"
36 #include "logindialog.h"
37 #include "map/mapview.h"
38 #include "settingsdialog.h"
39 #include "userinfopanel.h"
40 #include "zoombuttonpanel.h"
41
42 #include "mainwindow.h"
43
44 #include <QtGui/QX11Info>
45 #include <X11/Xlib.h>
46 #include <X11/Xatom.h>
47
48 // values for setting screen size in desktop matching N900 screen size
49 const int N900_APP_WIDTH = 800;
50 const int N900_APP_HEIGHT = 449;
51
52 MainWindow::MainWindow(QWidget *parent)
53     : QMainWindow(parent),
54     m_drawOwnLocationCrosshair(false),
55     m_loggedIn(false),
56     m_refresh(false),
57     m_email(),    
58     m_password(),
59     m_loginUrl(),
60     m_webView(0)
61 {
62     qDebug() << __PRETTY_FUNCTION__;
63
64     buildMap();
65
66     // build main layout
67     QHBoxLayout *layout = new QHBoxLayout;
68     layout->addWidget(m_mapView);
69     layout->setMargin(0);
70     setCentralWidget(new QWidget());
71     centralWidget()->setLayout(layout);
72
73     buildFriendListPanel();
74     buildUserInfoPanel();
75
76     createMenus();
77     setWindowTitle(tr("Situare"));
78
79     // set stacking order of widgets
80     m_zoomButtonPanel->stackUnder(m_userPanel);
81     m_osmLicense->stackUnder(m_zoomButtonPanel);
82     m_ownLocationCrosshair->stackUnder(m_osmLicense);
83     m_mapView->stackUnder(m_ownLocationCrosshair);
84
85     this->toggleProgressIndicator(true);
86
87     grabZoomKeys(true);
88
89     // set screen size in desktop matching N900 screen size
90     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
91 }
92
93 MainWindow::~MainWindow()
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     grabZoomKeys(false);
98
99     if(m_webView)
100         delete m_webView;
101 }
102
103 void MainWindow::buildFriendListPanel()
104 {
105     qDebug() << __PRETTY_FUNCTION__;
106
107     m_friendsListPanel = new FriendListPanel(this);
108     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
109
110     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
111
112     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
113             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
114
115     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
116             this, SIGNAL(findFriend(QPointF)));
117
118     connect(m_mapView, SIGNAL(viewResized(QSize)),
119             m_friendsListPanel, SLOT(screenResized(QSize)));
120
121     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
122             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
123
124     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
125             m_friendsListPanelSidebar, SLOT(reDrawSidebar(int, int)));
126 }
127
128 void MainWindow::buildManualLocationCrosshair()
129 {
130     qDebug() << __PRETTY_FUNCTION__;
131
132     m_ownLocationCrosshair = new QLabel(this);
133     QPixmap crosshairImage(":/res/images/sight.png");
134     m_ownLocationCrosshair->setPixmap(crosshairImage);
135     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
136     m_ownLocationCrosshair->hide();
137     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
138
139     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
140             this, SLOT(drawOwnLocationCrosshair(int, int)));
141 }
142
143 void MainWindow::buildMap()
144 {
145     qDebug() << __PRETTY_FUNCTION__;
146
147     m_mapView = new MapView(this);
148
149     buildZoomButtonPanel();
150
151     m_ownLocationCrosshair = 0;
152     buildOsmLicense();
153     buildManualLocationCrosshair();
154
155     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
156             this, SIGNAL(mapViewScrolled(QPoint)));
157
158     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
159             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
160
161     connect(m_mapView, SIGNAL(viewResized(QSize)),
162             this, SIGNAL(mapViewResized(QSize)));
163
164     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
165              this, SLOT(setViewPortSize(int, int)));
166
167     connect(this, SIGNAL(zoomLevelChanged(int)),
168             m_mapView, SLOT(setZoomLevel(int)));
169
170     connect(m_mapView, SIGNAL(viewZoomFinished()),
171             this, SIGNAL(viewZoomFinished()));
172 }
173
174 void MainWindow::buildOsmLicense()
175 {
176     qDebug() << __PRETTY_FUNCTION__;
177
178     m_osmLicense = new QLabel(this);
179     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
180     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
181     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
182     m_osmLicense->setFont(QFont("Nokia Sans", 9));
183     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
184                          m_osmLicense->fontMetrics().height());
185
186     connect(m_mapView, SIGNAL(viewResized(QSize)),
187             this, SLOT(drawOsmLicense(QSize)));
188 }
189
190 void MainWindow::buildUserInfoPanel()
191 {
192     qDebug() << __PRETTY_FUNCTION__;
193
194     m_userPanel = new UserInfoPanel(this);
195     m_userPanelSidebar = new PanelSideBar(this, LEFT);
196
197     m_userPanelSidebar->stackUnder(m_friendsListPanel);
198     m_userPanel->stackUnder(m_userPanelSidebar);
199
200     connect(m_userPanel, SIGNAL(findUser(QPointF)),
201             this, SIGNAL(findUser(QPointF)));
202
203     connect(this, SIGNAL(userLocationReady(User*)),
204             m_userPanel, SLOT(userDataReceived(User*)));
205
206     connect(m_userPanel, SIGNAL(requestReverseGeo()),
207             this, SIGNAL(requestReverseGeo()));
208
209     connect(this, SIGNAL(reverseGeoReady(QString)),
210             m_userPanel, SIGNAL(reverseGeoReady(QString)));
211
212     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
213             this, SIGNAL(statusUpdate(QString,bool)));
214
215     connect(m_userPanel, SIGNAL(refreshUserData()),
216             this, SIGNAL(refreshUserData()));
217
218     connect(m_mapView, SIGNAL(viewResized(QSize)),
219             m_userPanel, SLOT(screenResized(QSize)));
220 }
221
222 void MainWindow::buildZoomButtonPanel()
223 {
224     qDebug() << __PRETTY_FUNCTION__;
225
226     m_zoomButtonPanel = new ZoomButtonPanel(this);
227
228     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
229             this, SIGNAL(zoomIn()));
230
231     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
232             this, SIGNAL(zoomOut()));
233
234     connect(this, SIGNAL(zoomLevelChanged(int)),
235             m_zoomButtonPanel, SLOT(resetButtons()));
236
237     connect(this, SIGNAL(maxZoomLevelReached()),
238             m_zoomButtonPanel, SLOT(disableZoomInButton()));
239
240     connect(this, SIGNAL(minZoomLevelReached()),
241             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
242
243     connect(m_mapView, SIGNAL(viewResized(QSize)),
244             m_zoomButtonPanel, SLOT(screenResized(QSize)));
245 }
246
247 void MainWindow::createMenus()
248 {
249     qDebug() << __PRETTY_FUNCTION__;
250
251     // login/logout
252     m_loginAct = new QAction(tr("Login"), this);
253     connect(m_loginAct, SIGNAL(triggered()),
254             this, SIGNAL(loginActionPressed()));
255
256     // settings
257     m_toSettingsAct = new QAction(tr("Settings"), this);
258     connect(m_toSettingsAct, SIGNAL(triggered()),
259         this, SLOT(openSettingsDialog()));
260
261     // GPS
262     m_gpsToggleAct = new QAction(tr("GPS"), this);
263     m_gpsToggleAct->setCheckable(true);
264
265     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
266             this, SIGNAL(gpsTriggered(bool)));
267
268     // automatic centering
269     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
270     m_autoCenteringAct->setCheckable(true);
271     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
272         this, SIGNAL(autoCenteringTriggered(bool)));
273
274     // build the actual menu
275     m_viewMenu = menuBar()->addMenu(tr("Main"));
276     m_viewMenu->addAction(m_loginAct);
277     m_viewMenu->addAction(m_toSettingsAct);
278     m_viewMenu->addAction(m_gpsToggleAct);
279     m_viewMenu->addAction(m_autoCenteringAct);
280     m_viewMenu->setObjectName(tr("Menu"));
281 }
282
283 void MainWindow::drawOsmLicense(const QSize &size)
284 {
285     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
286
287     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
288                        - PANEL_PEEK_AMOUNT,
289                        size.height() - m_osmLicense->fontMetrics().height());
290
291 }
292
293 void MainWindow::drawOwnLocationCrosshair(int width, int height)
294 {
295     qDebug() << __PRETTY_FUNCTION__;
296
297     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
298         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
299                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
300     }
301 }
302
303 void MainWindow::gpsError(const QString &message)
304 {
305     qDebug() << __PRETTY_FUNCTION__;
306
307     showMaemoInformationBox(message);
308 }
309
310 void MainWindow::gpsTimeout()
311 {
312     qDebug() << __PRETTY_FUNCTION__;
313
314     showMaemoInformationBox(tr("GPS timeout"));
315 }
316
317 void MainWindow::grabZoomKeys(bool grab)
318 {
319     qDebug() << __PRETTY_FUNCTION__;
320
321 #ifdef Q_WS_MAEMO_5
322     // Can't grab keys unless we have a window id
323     if (!winId())
324         return;
325
326     unsigned long val = (grab) ? 1 : 0;
327     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
328     if (!atom)
329         return;
330
331     XChangeProperty (QX11Info::display(),
332                      winId(),
333                      atom,
334                      XA_INTEGER,
335                      32,
336                      PropModeReplace,
337                      reinterpret_cast<unsigned char *>(&val),
338                      1);
339 #else
340     Q_UNUSED(grab);
341 #endif // Q_WS_MAEMO_5
342 }
343
344 void MainWindow::keyPressEvent(QKeyEvent* event)
345 {
346     qDebug() << __PRETTY_FUNCTION__;
347
348     switch (event->key()) {
349     case Qt::Key_F7:
350         event->accept();
351         emit zoomIn();
352         break;
353
354     case Qt::Key_F8:
355         event->accept();
356         emit zoomOut();
357         break;
358     }
359     QWidget::keyPressEvent(event);
360 }
361
362 void MainWindow::loadDone(bool done)
363 {
364     qDebug() << __PRETTY_FUNCTION__;
365
366     // for the first time the login page is opened, we need to refresh it to get cookies working
367     if(m_refresh) {
368         m_webView->reload();
369         m_refresh = false;
370     }
371
372     if (done)
373     {
374         QWebFrame* frame = m_webView->page()->currentFrame();
375         if (frame!=NULL)
376         {
377             // set email box
378             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
379
380             foreach (QWebElement element, emailCollection) {
381                 element.setAttribute("value", m_email.toAscii());
382             }
383             // set password box
384             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
385             foreach (QWebElement element, passwordCollection) {
386                 element.setAttribute("value", m_password.toAscii());
387             }
388             // find connect button
389             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
390             foreach (QWebElement element, buttonCollection)
391             {
392                 QPoint pos(element.geometry().center());
393
394                 // send a mouse click event to the web page
395                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
396                                    Qt::NoModifier);
397                 QApplication::sendEvent(m_webView->page(), &event0);
398                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
399                                    Qt::NoModifier);
400                 QApplication::sendEvent(m_webView->page(), &event1);
401             }
402         }
403     }
404 }
405
406 void MainWindow::loggedIn(bool logged)
407 {
408     qDebug() << __PRETTY_FUNCTION__;
409
410     m_loggedIn = logged;
411
412     if(logged) {
413         m_loginAct->setText(tr("Logout"));
414     }
415     else {
416         m_loginAct->setText(tr("Login"));
417     }
418     showPanels(m_loggedIn);
419 }
420
421 void MainWindow::loginDialogDone(const QString &email, const QString &password)
422 {
423     qDebug() << __PRETTY_FUNCTION__;
424
425     m_email = email;
426     m_password = password;
427 }
428
429 void MainWindow::loginFailed()
430 {
431     qDebug() << __PRETTY_FUNCTION__;
432
433     m_email.clear();
434     m_password.clear();
435
436     toggleProgressIndicator(false);
437
438 #ifdef Q_WS_MAEMO_5
439     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
440                                        QMaemo5InformationBox::NoTimeout);
441
442 #endif // Q_WS_MAEMO_5
443
444     if(!m_email.isEmpty()) {
445         m_loginDialog->setEmailField(m_email);
446     }
447
448     if(m_loginDialog->exec() != QDialog::Accepted) {
449         // if login dialog was canceled we need to stop processing webview
450         // stop and disconnect m_webView;
451         m_webView->stop();
452         disconnect(m_webView, SIGNAL(loadFinished(bool)),
453                    this, SLOT(loadDone(bool)));
454         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
455                    this, SLOT(updateCredentials(const QUrl &)));
456
457         emit cancelLoginProcess();
458     }
459     else {
460         // re-load login page for webview
461         toggleProgressIndicator(true);
462         m_webView->load(m_loginUrl);
463     }
464 }
465
466 void MainWindow::openSettingsDialog()
467 {
468     qDebug() << __PRETTY_FUNCTION__;
469
470     SettingsDialog *dialog = new SettingsDialog(this);
471     if(!m_loggedIn) {
472         dialog->disableSituareSettings();
473     }
474     dialog->show();
475 }
476
477 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
478 {
479     qDebug() << __PRETTY_FUNCTION__;
480
481     m_autoCenteringAct->setChecked(enabled);
482 }
483
484 void MainWindow::setGPSButtonEnabled(bool enabled)
485 {
486     qDebug() << __PRETTY_FUNCTION__;
487
488     m_gpsToggleAct->setChecked(enabled);
489     setOwnLocationCrosshairVisibility(!enabled);
490     m_autoCenteringAct->setVisible(enabled);
491 }
492
493 void MainWindow::setMapViewScene(QGraphicsScene *scene)
494 {
495     qDebug() << __PRETTY_FUNCTION__;
496
497     m_mapView->setScene(scene);
498 }
499
500 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
501 {
502     qDebug() << __PRETTY_FUNCTION__;
503
504     if (visibility) {
505         m_ownLocationCrosshair->show();
506         m_drawOwnLocationCrosshair = true;
507         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
508     }
509     else {
510         m_ownLocationCrosshair->hide();
511         m_drawOwnLocationCrosshair = false;
512     }
513 }
514
515 void MainWindow::setUsername(const QString &username)
516 {
517     qDebug() << __PRETTY_FUNCTION__;
518     m_email = username;
519 }
520
521 void MainWindow::setViewPortSize(int width, int height)
522 {
523     qDebug() << __PRETTY_FUNCTION__;
524
525     m_viewPortWidth = width;
526     m_viewPortHeight = height;
527 }
528
529 void MainWindow::showMaemoInformationBox(const QString &message)
530 {
531     qDebug() << __PRETTY_FUNCTION__;
532
533 #ifdef Q_WS_MAEMO_5
534     QMaemo5InformationBox::information(this, message, QMaemo5InformationBox::DefaultTimeout);
535 #else
536     Q_UNUSED(message);
537 #endif
538 }
539
540 void MainWindow::showPanels(bool show)
541 {
542     qDebug() << __PRETTY_FUNCTION__;
543     if(show) {
544         m_friendsListPanel->show();
545         m_friendsListPanelSidebar->show();
546         m_userPanel->show();
547         m_userPanelSidebar->show();
548     }
549     else {
550         m_friendsListPanel->closePanel();
551         m_friendsListPanel->hide();
552         m_friendsListPanelSidebar->hide();
553         m_userPanel->closePanel();
554         m_userPanel->hide();
555         m_userPanelSidebar->hide();
556     }
557 }
558
559 void MainWindow::startLoginProcess(const QUrl &url)
560 {
561     qDebug() << __PRETTY_FUNCTION__;
562
563     m_loginUrl = url;
564     m_webView = new QWebView;
565     m_loginDialog = new LoginDialog(this);
566
567     connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
568             this, SIGNAL(updateCredentials(QUrl)));
569     connect(m_webView, SIGNAL(loadFinished(bool)),
570             this, SLOT(loadDone(bool)));
571
572     connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
573             this, SLOT(loginDialogDone(QString,QString)));
574
575     m_webView->hide();
576
577     emit fetchUsernameFromSettings();
578
579     if(!m_email.isEmpty()) {
580         m_loginDialog->setEmailField(m_email);
581     }
582
583     if(m_loginDialog->exec() != QDialog::Accepted) {
584         // if login dialog was canceled we need to stop processing webview
585         // stop and disconnect m_webView;
586         m_webView->stop();
587         disconnect(m_webView, SIGNAL(loadFinished(bool)),
588                    this, SLOT(loadDone(bool)));
589         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
590                    this, SLOT(updateCredentials(const QUrl &)));
591
592         emit cancelLoginProcess();
593     }
594     else {
595         m_webView->load(m_loginUrl);
596         toggleProgressIndicator(true);
597         m_refresh = true;
598     }
599 }
600
601 void MainWindow::toggleProgressIndicator(bool value)
602 {
603     qDebug() << __PRETTY_FUNCTION__;
604
605 #ifdef Q_WS_MAEMO_5
606     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
607 #else
608     Q_UNUSED(value);
609 #endif // Q_WS_MAEMO_5
610 }
611
612 const QString MainWindow::username()
613 {
614     qDebug() << __PRETTY_FUNCTION__;
615     return m_email;
616 }