Merged logout implementation to new refactored master
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8        Ville Tiensuu - ville.tiensuu@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 <QtAlgorithms>
26 #include <QDebug>
27 #include <QNetworkAccessManager>
28 #include <QString>
29 #include <QStringList>
30 #include <QUrl>
31 #include <QHash>
32 #include <QHashIterator>
33 #include <QRect>
34
35 #include "frienditemshandler.h"
36 #include "gpslocationitem.h"
37 #include "mapcommon.h"
38 #include "mapfetcher.h"
39 #include "mapscene.h"
40 #include "maptile.h"
41 #include "ownlocationitem.h"
42
43 #include "mapengine.h"
44
45 MapEngine::MapEngine(QObject *parent)
46     : QObject(parent),
47       m_autoCenteringEnabled(false),
48       m_zoomedIn(false),
49       m_zoomLevel(DEFAULT_ZOOM_LEVEL),
50       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
51       m_lastManualPosition(QPoint(0, 0)),
52       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
53 {
54     qDebug() << __PRETTY_FUNCTION__;
55
56     m_mapScene = new MapScene(this);
57
58     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
59     connect(this, SIGNAL(fetchImage(int, int, int)),
60             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
61     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
62             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
63
64     m_ownLocation = new OwnLocationItem();
65     m_ownLocation->hide(); // hide until first location info is received
66     m_mapScene->addItem(m_ownLocation);
67
68     m_gpsLocationItem = new GPSLocationItem();
69     m_mapScene->addItem(m_gpsLocationItem);
70
71     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
72     connect(this, SIGNAL(zoomLevelChanged(int)),
73             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
74
75     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
76             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
77 }
78
79 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
80 {
81     qDebug() << __PRETTY_FUNCTION__;
82
83     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
84     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
85     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
86     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
87     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
88
89     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
90
91     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
92 }
93
94 QPointF MapEngine::centerGeoCoordinate()
95 {
96     qDebug() << __PRETTY_FUNCTION__;
97
98     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
99 }
100
101 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
102 {
103     qDebug() << __PRETTY_FUNCTION__;
104
105     qreal longitude = latLonCoordinate.x();
106     qreal latitude = latLonCoordinate.y();
107
108     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
109         return QPoint(UNDEFINED, UNDEFINED);
110     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
111         return QPoint(UNDEFINED, UNDEFINED);
112
113     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
114
115     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
116     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
117                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
118
119     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
120 }
121
122 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
123 {
124     qDebug() << __PRETTY_FUNCTION__;
125
126     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
127     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
128     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
129
130     tileFactor = 1 << zoomLevel;
131     double longitude = xFactor / tileFactor * 360.0 - 180;
132
133     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
134     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
135
136     return QPointF(longitude, latitude);
137 }
138
139 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
140 {
141     qDebug() << __PRETTY_FUNCTION__;
142
143     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
144     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
145     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
146
147     return QPoint(x, y);
148 }
149
150 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
151 {
152     qDebug() << __PRETTY_FUNCTION__;
153
154     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
155     int x = tileNumber.x() * TILE_SIZE_X * pow;
156     int y = tileNumber.y() * TILE_SIZE_Y * pow;
157
158     return QPoint(x, y);
159 }
160
161 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
162 {
163     if (isAutoCenteringEnabled()) {
164         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
165
166         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
167                                       m_lastManualPosition.y() / zoomFactor);
168
169         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
170                                       sceneCoordinate.y() / zoomFactor);
171
172         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
173             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
174             return true;
175     }
176
177     return false;
178 }
179
180 void MapEngine::getTiles(QPoint sceneCoordinate)
181 {
182     qDebug() << __PRETTY_FUNCTION__;
183
184     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
185     updateViewTilesSceneRect();
186
187     int topLeftX = m_viewTilesGrid.topLeft().x();
188     int topLeftY = m_viewTilesGrid.topLeft().y();
189     int bottomRightX = m_viewTilesGrid.bottomRight().x();
190     int bottomRightY = m_viewTilesGrid.bottomRight().y();
191
192     int tileMaxVal = tileMaxValue(m_zoomLevel);
193
194     for (int x = topLeftX; x <= bottomRightX; ++x) {
195         for (int y = topLeftY; y <= bottomRightY; ++y) {
196
197             int tileX = x;
198             int tileY = y;
199
200             if (tileX < 0)
201                 tileX += tileMaxVal;
202             else if (tileX > tileMaxVal)
203                 tileX -= tileMaxVal;
204
205             if (tileY < 0)
206                 tileY += tileMaxVal;
207             else if (tileY > tileMaxVal)
208                 tileY -= tileMaxVal;
209
210             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
211                 emit fetchImage(m_zoomLevel, tileX, tileY);
212         }
213     }
214 }
215
216 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
217 {
218     qDebug() << __PRETTY_FUNCTION__;
219
220     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
221
222     if (m_autoCenteringEnabled)
223         setViewLocation(position);
224 }
225
226 void MapEngine::init()
227 {
228     qDebug() << __PRETTY_FUNCTION__;
229
230     emit zoomLevelChanged(m_zoomLevel);
231     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
232 }
233
234 bool MapEngine::isAutoCenteringEnabled()
235 {
236     return m_autoCenteringEnabled;
237 }
238
239 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
240 {
241     qDebug() << __PRETTY_FUNCTION__;
242
243     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
244     QPoint temp = m_centerTile;
245     m_centerTile = centerTile;
246
247     return (centerTile != temp);
248 }
249
250 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
251 {
252     qDebug() << __PRETTY_FUNCTION__;
253
254     QString hashKey = tilePath(zoomLevel, x, y);
255     if (!m_mapScene->isTileInScene(hashKey)) {
256
257         MapTile *mapTile = new MapTile();
258         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
259         mapTile->setTileNumber(QPoint(x, y));
260         mapTile->setPixmap(image);
261
262         m_mapScene->addTile(mapTile, hashKey);
263
264         m_mapScene->enqueueRemoveStackedTiles(mapTile);
265    }
266 }
267
268 void MapEngine::receiveOwnLocation(User *user)
269 {
270     qDebug() << __PRETTY_FUNCTION__;
271
272     if(user) {
273         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
274         if (m_ownLocation->pos().toPoint() != newPosition) {
275             m_ownLocation->setPos(newPosition);
276         }
277
278         if (!m_ownLocation->isVisible())
279             m_ownLocation->show();
280     }
281     else {
282         m_ownLocation->hide();
283     }
284 }
285
286 QGraphicsScene* MapEngine::scene()
287 {
288     qDebug() << __PRETTY_FUNCTION__;
289
290     return m_mapScene;
291 }
292
293 void MapEngine::setAutoCentering(bool enabled)
294 {
295     m_autoCenteringEnabled = enabled;
296 }
297
298 void MapEngine::setGPSEnabled(bool enabled)
299 {
300     m_gpsLocationItem->setEnabled(enabled);
301 }
302
303 void MapEngine::setLocation(QPoint sceneCoordinate)
304 {
305     qDebug() << __PRETTY_FUNCTION__;
306
307     if (disableAutoCentering(sceneCoordinate))
308         emit mapScrolledManually();
309
310     m_sceneCoordinate = sceneCoordinate;
311     emit locationChanged(m_sceneCoordinate);
312
313     if (isCenterTileChanged(sceneCoordinate)) {
314         getTiles(sceneCoordinate);
315         m_mapScene->removeOutOfViewTiles();
316     }
317 }
318
319 void MapEngine::setViewLocation(QPointF latLonCoordinate)
320 {
321     qDebug() << __PRETTY_FUNCTION__;
322
323     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
324
325     m_lastManualPosition = sceneCoordinate;
326
327     setLocation(sceneCoordinate);
328 }
329
330 int MapEngine::tileMaxValue(int zoomLevel)
331 {
332     qDebug() << __PRETTY_FUNCTION__;
333
334     return (1 << zoomLevel) - 1;
335 }
336
337 QString MapEngine::tilePath(int zoomLevel, int x, int y)
338 {
339     qDebug() << __PRETTY_FUNCTION__;
340
341     QString tilePathString(QString::number(zoomLevel) + "/");
342     tilePathString.append(QString::number(x) + "/");
343     tilePathString.append(QString::number(y));
344
345     return tilePathString;
346 }
347
348 void MapEngine::updateViewTilesSceneRect()
349 {
350     qDebug() << __PRETTY_FUNCTION__;
351
352     const QPoint ONE_TILE = QPoint(1, 1);
353     const QPoint ONE_PIXEL = QPoint(1, 1);
354
355     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
356     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
357     // of the last tile.
358     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
359                                                             m_viewTilesGrid.bottomRight()
360                                                              + ONE_TILE) - ONE_PIXEL;
361
362     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
363 }
364
365 void MapEngine::viewResized(const QSize &size)
366 {
367     qDebug() << __PRETTY_FUNCTION__;
368
369     m_viewSize = size;
370     emit locationChanged(m_sceneCoordinate);
371     getTiles(m_sceneCoordinate);
372     m_mapScene->removeOutOfViewTiles();
373 }
374
375 void MapEngine::viewZoomFinished()
376 {
377     qDebug() << __PRETTY_FUNCTION__;
378
379     if (m_zoomedIn) {
380         m_zoomedIn = false;
381         m_mapScene->removeOutOfViewTiles();
382     }
383
384     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
385         emit maxZoomLevelReached();
386     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
387         emit minZoomLevelReached();
388 }
389
390 void MapEngine::zoomIn()
391 {
392     qDebug() << __PRETTY_FUNCTION__;
393
394     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
395         m_zoomLevel++;
396         m_zoomedIn = true;
397         emit zoomLevelChanged(m_zoomLevel);
398
399         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
400
401         getTiles(m_sceneCoordinate);
402     }
403 }
404
405 void MapEngine::zoomOut()
406 {
407     qDebug() << __PRETTY_FUNCTION__;
408
409     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
410         m_zoomLevel--;
411         emit zoomLevelChanged(m_zoomLevel);
412
413         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
414
415         getTiles(m_sceneCoordinate);
416     }
417 }