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