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