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