summaryrefslogtreecommitdiff
path: root/qmapwatchlet/mapview.cpp
blob: 3a0e902f525673731ab347e1935819ec51347134 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#include <QtCore/QDebug>
#include <QtGui/QMainWindow>
#include <QtGui/QLabel>
#include <QtLocation/QGeoMapData>
#include <QtLocation/QGraphicsGeoMap>
#include <QtLocation/QGeoSearchManager>
#include "qmapwatchletplugin.h"
#include "mapview.h"

QTM_USE_NAMESPACE
using namespace sowatch;

MapView::MapView(QDeclarativeItem *parent) :
    QDeclarativeItem(parent),
    _enabled(false),
    _arrow(SOWATCH_QML_DIR "/qmapwatchlet/arrow.png"),
    _mapData(0),
    _posSource(QGeoPositionInfoSource::createDefaultSource(this)),
    _searchArea(0), _searchReply(0)
{
	QGeoServiceProvider *provider = QMapWatchletPlugin::geoServiceProvider();
	if (!provider) {
		qWarning() << "No geo service provider for map watchlet!";
	}

	QGeoMappingManager *manager = provider->mappingManager();
	_mapData = manager->createMapData();

	if (_mapData) {
		_mapData->init();
		_mapData->setMapType(QGraphicsGeoMap::StreetMap);

		_mapData->setZoomLevel(12);

		connect(_mapData, SIGNAL(zoomLevelChanged(qreal)), SIGNAL(zoomLevelChanged()));
		connect(_mapData, SIGNAL(updateMapDisplay(QRectF)), SLOT(handleMapChanged(QRectF)));
	} else {
		qWarning() << "No mapdata!";
	}

	if (_posSource) {
		connect(_posSource, SIGNAL(positionUpdated(QGeoPositionInfo)),
				SLOT(handlePositionUpdate(QGeoPositionInfo)));
		_posSource->lastKnownPosition();
	} else {
		qWarning() << "No position source for moving map!";
	}

	setFlag(QGraphicsItem::ItemHasNoContents, false);
}

MapView::~MapView()
{
	delete _mapData;
	delete _searchReply;
	delete _searchArea;
}

bool MapView::updateEnabled() const
{
	return _enabled;
}

void MapView::setUpdateEnabled(bool enabled)
{
	if (_posSource && _enabled != enabled) {
		if (enabled) {
			qDebug() << "Start position updates";
			_posSource->startUpdates();
		} else {
			qDebug() << "Stop position updates";
			_posSource->stopUpdates();
		}
		_enabled = enabled;

		emit updateEnabledChanged();
	}

}

int MapView::updateInterval() const
{
	if (_posSource) {
		return _posSource->updateInterval();
	} else {
		return 0;
	}
}

void MapView::setUpdateInterval(int msec)
{
	if (_posSource) {
		_posSource->setUpdateInterval(msec);
		emit updateIntervalChanged();
	}
}

qreal MapView::zoomLevel() const
{
	if (_mapData) {
		return _mapData->zoomLevel();
	} else {
		return -1.0;
	}
}

void MapView::setZoomLevel(qreal level)
{
	if (_mapData) {
		_mapData->setZoomLevel(level);
		qDebug() << "new zoom level" << level;
	}
}

QString MapView::currentLocationName() const
{
	return _posName;
}

void MapView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	Q_UNUSED(widget);
	if (_mapData) {
		// Render to an image first
		const QSize size(_mapData->windowSize().toSize());
		QImage image(size, QImage::Format_RGB32);
		QImage pixmap(size, QImage::Format_MonoLSB);

		const int w = image.width(), h = image.height();
		const int npixels = w * h;
		QScopedArrayPointer<qreal> greys(new qreal[npixels]);

		{
			QPainter p(&image);
			_mapData->paint(&p, option);
		}

		// Convert to a bitmap using some ad-hoc ugly algorithm...
		qreal sum = 0;
		for (int y = 0; y < h; y++) {
			QRgb *l = reinterpret_cast<QRgb*>(image.scanLine(y));
			for (int x = 0; x < w; x++) {
				const int r = qRed(l[x]), g = qGreen(l[x]), b = qBlue(l[x]);
				const qreal grey = r * 0.299f + g * 0.587f + b * 0.114f;

				greys[y * w + x] = grey;

				sum += grey;
			}
		}

		const qreal avg = sum / npixels;
		const qreal thr = avg * 0.9;

		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				// TODO: Optimize
				pixmap.setPixel(x, y, greys[y * w + x] >= thr ? Qt::color1 : Qt::color0);
			}
		}

		// And render into the watch
		painter->drawImage(0, 0, pixmap);

		// Now render the arrow indicator
		const int centerX = size.width() / 2, centerY = size.height() / 2;
		painter->save();
		painter->translate(centerX, centerY);
		if (_pos.hasAttribute(QGeoPositionInfo::Direction)) {
			painter->rotate(_pos.attribute(QGeoPositionInfo::Direction));
		}
		painter->drawImage(-_arrow.width() / 2, -_arrow.height() / 2, _arrow);
		painter->restore();
	}
}

void MapView::updateCurrentLocationName()
{
	if (_searchReply) {
		qDebug() << "Search already in progress";
		return;
	}
	QGeoServiceProvider *provider = QMapWatchletPlugin::geoServiceProvider();
	if (!provider) {
		qWarning() << "No geo service provider for map watchlet!";
	}

	// Lifetime of 'bounds' in call to reverseGeocode() is not specified anywhere.
	// So we keep it "forever" until the next call to reverseGeocode().
	// which is ... now.
	delete _searchArea;

	// Create the new bounds object.
	if (_mapData) {
		_searchArea = new QGeoBoundingBox(_mapData->viewport());
	} else {
		_searchArea = 0;
	}

	_posName.clear();

	qDebug() << "Start request of current location";

	QGeoSearchManager *manager = provider->searchManager();
	_searchReply = manager->reverseGeocode(_pos.coordinate(), _searchArea);
	connect(_searchReply, SIGNAL(finished()),
	        SLOT(handleCurrentLocationNameSearchFinished()));
	connect(_searchReply, SIGNAL(error(QGeoSearchReply::Error,QString)),
	        SLOT(handleCurrentLocationNameSearchError(QGeoSearchReply::Error,QString)));
}

void MapView::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
	Q_UNUSED(oldGeometry);
	if (_mapData) {
		_mapData->setWindowSize(newGeometry.size());
	}
}

void MapView::handlePositionUpdate(const QGeoPositionInfo& info)
{
	_pos = info;
	if (_mapData) {
		_mapData->setCenter(info.coordinate());
	}
}

void MapView::handleMapChanged(const QRectF &rect)
{
	update(rect);
}

void MapView::handleCurrentLocationNameSearchFinished()
{
	if (_searchReply) {
		if (_searchReply->error() == QGeoSearchReply::NoError) {
			QList<QGeoPlace> places = _searchReply->places();
			qDebug() << "Current location name search got " << places.size() << " results";
			foreach (const QGeoPlace& place, places) {
				QGeoAddress address = place.address();
				qDebug() << "  " << address.street() << " - " << address.district() << " - " << address.city();
			}
			if (!places.isEmpty()) {
				QGeoAddress address = places.first().address();
				if (!address.street().isEmpty()) {
					_posName = address.street();
				} else if (!address.district().isEmpty()) {
					_posName = address.district();
				} else if (!address.city().isEmpty()) {
					_posName = address.city();
				} else {
					_posName.clear();
				}
				qDebug() << "Current location name search finished:" << _posName;
				emit currentLocationNameChanged();
			}
		} else {
			qDebug() << "Current location name search finished with error:"
			         << _searchReply->error();
		}
		_searchReply->deleteLater();
		_searchReply = 0;
	}
}

void MapView::handleCurrentLocationNameSearchError(QGeoSearchReply::Error error, const QString &errorString)
{
	qWarning() << "Current location name search error: " << error << errorString;
	if (_searchReply) {
		_searchReply->deleteLater();
		_searchReply = 0;
	}
}