Finished implementing zoom button drag feature
[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(viewResized(QSize)),
121             m_zoomButtonPanel, SLOT(screenResized(QSize)));
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     QSettings settings(DIRECTORY_NAME, FILE_NAME);
241     m_zoomButtonPanel->move(settings.value(ZOOMPANEL_POSITION,
242                                            QPoint(ZOOM_BUTTON_PANEL_POSITION_X,
243                                                   ZOOM_BUTTON_PANEL_POSITION_Y)).toPoint());
244 }
245
246 void MainWindow::createMenus()
247 {
248     qDebug() << __PRETTY_FUNCTION__;
249
250     // settings
251     m_toSettingsAct = new QAction(tr("Settings"), this);
252     m_toSettingsAct->setObjectName(tr("Settings"));
253     connect(m_toSettingsAct, SIGNAL(triggered()),
254         this, SLOT(openSettingsDialog()));
255
256     // GPS
257     m_gpsToggleAct = new QAction(tr("GPS"), this);
258     m_gpsToggleAct->setCheckable(true);
259
260     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
261             this, SIGNAL(gpsTriggered(bool)));
262
263     // automatic centering
264     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
265     m_autoCenteringAct->setCheckable(true);
266     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
267         this, SIGNAL(autoCenteringTriggered(bool)));
268
269     // build the actual menu
270     m_viewMenu = menuBar()->addMenu(tr("Main"));
271     m_viewMenu->addAction(m_toSettingsAct);
272     m_viewMenu->addAction(m_gpsToggleAct);
273     m_viewMenu->addAction(m_autoCenteringAct);
274     m_viewMenu->setObjectName(tr("Menu"));
275 }
276
277 void MainWindow::drawOsmLicense(const QSize &size)
278 {
279     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
280
281     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE) - PANEL_PEEK_AMOUNT,
282                         size.height() - m_osmLicense->fontMetrics().height());
283
284 }
285
286 void MainWindow::drawOwnLocationCrosshair(int width, int height)
287 {
288     qDebug() << __PRETTY_FUNCTION__;
289
290     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
291         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
292                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
293     }
294 }
295
296 void MainWindow::gpsError(const QString &message)
297 {
298     qDebug() << __PRETTY_FUNCTION__;
299
300     showMaemoInformationBox(message);
301 }
302
303 void MainWindow::gpsTimeout()
304 {
305     qDebug() << __PRETTY_FUNCTION__;
306
307     showMaemoInformationBox(tr("GPS timeout"));
308 }
309
310 void MainWindow::grabZoomKeys(bool grab)
311 {
312     qDebug() << __PRETTY_FUNCTION__;
313
314 #ifdef Q_WS_MAEMO_5
315     // Can't grab keys unless we have a window id
316     if (!winId())
317         return;
318
319     unsigned long val = (grab) ? 1 : 0;
320     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
321     if (!atom)
322         return;
323
324     XChangeProperty (QX11Info::display(),
325                      winId(),
326                      atom,
327                      XA_INTEGER,
328                      32,
329                      PropModeReplace,
330                      reinterpret_cast<unsigned char *>(&val),
331                      1);
332 #else
333     Q_UNUSED(grab);
334 #endif // Q_WS_MAEMO_5
335 }
336
337 void MainWindow::keyPressEvent(QKeyEvent* event)
338 {
339     qDebug() << __PRETTY_FUNCTION__;
340
341     switch (event->key()) {
342     case Qt::Key_F7:
343         event->accept();
344         emit zoomIn();
345         break;
346
347     case Qt::Key_F8:
348         event->accept();
349         emit zoomOut();
350         break;
351     }
352     QWidget::keyPressEvent(event);
353 }
354
355 void MainWindow::loadDone(bool done)
356 {
357     qDebug() << __PRETTY_FUNCTION__;
358
359     // for the first time the login page is opened, we need to refresh it to get cookies working
360     if(m_refresh) {
361         m_webView->reload();
362         m_refresh = false;
363     }
364
365     if (done)
366     {
367         QWebFrame* frame = m_webView->page()->currentFrame();
368         if (frame!=NULL)
369         {
370             // set email box
371             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
372
373             foreach (QWebElement element, emailCollection) {
374                 element.setAttribute("value", m_email.toAscii());
375             }
376             // set password box
377             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
378             foreach (QWebElement element, passwordCollection) {
379                 element.setAttribute("value", m_password.toAscii());
380             }
381             // find connect button
382             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
383             foreach (QWebElement element, buttonCollection)
384             {
385                 QPoint pos(element.geometry().center());
386
387                 // send a mouse click event to the web page
388                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
389                                    Qt::NoModifier);
390                 QApplication::sendEvent(m_webView->page(), &event0);
391                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
392                                    Qt::NoModifier);
393                 QApplication::sendEvent(m_webView->page(), &event1);
394             }
395         }
396     }
397 }
398
399 void MainWindow::loginDialogDone(const QString &email, const QString &password)
400 {
401     qDebug() << __PRETTY_FUNCTION__;
402
403     m_email = email;
404     m_password = password;
405 }
406
407 void MainWindow::loginFailed()
408 {
409     qDebug() << __PRETTY_FUNCTION__;
410
411     m_email.clear();
412     m_password.clear();
413
414     toggleProgressIndicator(false);
415
416 #ifdef Q_WS_MAEMO_5
417     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
418                                        QMaemo5InformationBox::NoTimeout);
419
420 #endif // Q_WS_MAEMO_5
421
422     if(!m_email.isEmpty()) {
423         m_loginDialog->setEmailField(m_email);
424     }
425
426     if(m_loginDialog->exec() != QDialog::Accepted) {
427         // if login dialog was canceled we need to stop processing webview
428         // stop and disconnect m_webView;
429         m_webView->stop();
430         disconnect(m_webView, SIGNAL(loadFinished(bool)),
431                    this, SLOT(loadDone(bool)));
432         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
433                    this, SLOT(updateCredentials(const QUrl &)));
434
435         emit cancelLoginProcess();
436     }
437     else {
438         // re-load login page for webview
439         toggleProgressIndicator(true);
440         m_webView->load(m_loginUrl);
441     }
442 }
443
444 void MainWindow::openSettingsDialog()
445 {
446     qDebug() << __PRETTY_FUNCTION__;
447
448     SettingsDialog *dialog = new SettingsDialog(this);
449     dialog->show();
450 }
451
452 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
453 {
454     qDebug() << __PRETTY_FUNCTION__;
455
456     m_autoCenteringAct->setChecked(enabled);
457 }
458
459 void MainWindow::setGPSButtonEnabled(bool enabled)
460 {
461     qDebug() << __PRETTY_FUNCTION__;
462
463     m_gpsToggleAct->setChecked(enabled);
464     setOwnLocationCrosshairVisibility(!enabled);
465     m_autoCenteringAct->setVisible(enabled);
466 }
467
468 void MainWindow::setMapViewScene(QGraphicsScene *scene)
469 {
470     qDebug() << __PRETTY_FUNCTION__;
471
472     m_mapView->setScene(scene);
473 }
474
475 void MainWindow::setUsername(const QString &username)
476 {
477     qDebug() << __PRETTY_FUNCTION__;
478     m_email = username;
479 }
480
481 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
482 {
483     qDebug() << __PRETTY_FUNCTION__;
484
485     if (visibility) {
486         m_ownLocationCrosshair->show();
487         m_drawOwnLocationCrosshair = true;
488         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
489     }
490     else {
491         m_ownLocationCrosshair->hide();
492         m_drawOwnLocationCrosshair = false;
493     }
494 }
495
496 void MainWindow::setViewPortSize(int width, int height)
497 {
498     qDebug() << __PRETTY_FUNCTION__;
499
500     m_viewPortWidth = width;
501     m_viewPortHeight = height;
502 }
503
504 void MainWindow::showMaemoInformationBox(const QString &message)
505 {
506     qDebug() << __PRETTY_FUNCTION__;
507
508 #ifdef Q_WS_MAEMO_5
509     QMaemo5InformationBox::information(this, message, QMaemo5InformationBox::DefaultTimeout);
510 #else
511     Q_UNUSED(message);
512 #endif
513 }
514
515 void MainWindow::startLoginProcess(const QUrl &url)
516 {
517     qDebug() << __PRETTY_FUNCTION__;
518
519     m_loginUrl = url;
520     m_webView = new QWebView;
521     m_loginDialog = new LoginDialog(this);
522
523     connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
524             this, SIGNAL(updateCredentials(QUrl)));
525     connect(m_webView, SIGNAL(loadFinished(bool)),
526             this, SLOT(loadDone(bool)));
527
528     connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
529             this, SLOT(loginDialogDone(QString,QString)));
530
531     m_webView->hide();
532
533     emit fetchUsernameFromSettings();
534
535     if(!m_email.isEmpty()) {
536         m_loginDialog->setEmailField(m_email);
537     }
538
539     if(m_loginDialog->exec() != QDialog::Accepted) {
540         // if login dialog was canceled we need to stop processing webview
541         // stop and disconnect m_webView;
542         m_webView->stop();
543         disconnect(m_webView, SIGNAL(loadFinished(bool)),
544                    this, SLOT(loadDone(bool)));
545         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
546                    this, SLOT(updateCredentials(const QUrl &)));
547
548         emit cancelLoginProcess();
549     }
550     else {
551         m_webView->load(m_loginUrl);
552         toggleProgressIndicator(true);
553         m_refresh = true;
554     }
555 }
556
557 void MainWindow::toggleProgressIndicator(bool value)
558 {
559     qDebug() << __PRETTY_FUNCTION__;
560
561 #ifdef Q_WS_MAEMO_5
562     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
563 #else
564     Q_UNUSED(value);
565 #endif // Q_WS_MAEMO_5
566 }
567
568 const QString MainWindow::username()
569 {
570     qDebug() << __PRETTY_FUNCTION__;
571     return m_email;
572 }