layer_tiles.cpp 10.8 KB
Newer Older
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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
#include <QThread>
#include <QCoreApplication>
#include <QPainter>
#include <QSettings>
#include "layer_tiles.h"
#include "tilesviewer.h"
namespace QTVOSM{
	/*!
	 \brief in this constructor, some initial approach will be token.

	 \fn layer_tiles::layer_tiles
	 \param parent	parent objects
	*/
	layer_tiles::layer_tiles(QObject *parent) :
		QObject(parent)
	{
		m_bActive = false;
		m_bVisible = false;
		m_pViewer = 0;
		//!1,Create thread object for download. download will be hold in different threads/
		m_downloader = new urlDownloader(0);
		m_downloadThread = new QThread(this);
		m_downloader->moveToThread(m_downloadThread);
		m_downloadThread->start();
		//!2,init basic cache and server site.if user does not give address, default set to "http://localhost/osm/%1/%2/%3.png"
		this->m_strLocalCache = "/OSMCache";
		this->m_strServerURL = "http://c.tile.openstreetmap.org/%1/%2/%3.png";
		m_bconnected = false;
		m_propPage = 0;
		//!3, init the Drag position, for mouse drag and explore.
		this->m_nStartPosX = this->m_nStartPosY = -1;
		m_name = QString("%1").arg((quint64)this);
	}
	void layer_tiles::setServerUrl(QString url)
	{
		m_strServerURL = url;
		QSettings settings(QCoreApplication::applicationFilePath()+".ini",QSettings::IniFormat);
		settings.setValue(QString("settings/ServerURL_%1").arg(get_name()),m_strServerURL);
		emit svrurlChanged(url);
	}

	void layer_tiles::setLocalCache(QString cache)
	{
		m_strLocalCache = cache;
		QSettings settings(QCoreApplication::applicationFilePath()+".ini",QSettings::IniFormat);
		settings.setValue(QString("settings/LocalCache_%1").arg(get_name()), m_strLocalCache);
		emit cacheChanged(cache);
	}

	/*!
	 \brief When the tileviewer enter its paint_event function, this callback will be called.

	 \fn layer_tiles::cb_paintEvent
	 \param pImage	the In-mem image for paint .
	*/
	void layer_tiles::cb_paintEvent( QPainter * pPainter )
	{
		if (!m_pViewer || m_bVisible==false) return;
		//!1,We should first calculate current windows' position, centerx,centery, in pixcel.
		double nCenter_X ,nCenter_Y;
		//!2,if the CV_PercentageToPixel returns true, painting will begin.
		if (true==m_pViewer->CV_Pct2World(
					m_pViewer->centerX(),
					m_pViewer->centerY(),
					&nCenter_X,&nCenter_Y))
		{
			int sz_whole_idx = 1<<m_pViewer->level();
			//!2.1 get current center tile idx, in tile count.(tile is 256x256)
			int nCenX = nCenter_X/256;
			int nCenY = nCenter_Y/256;
			//!2.2 calculate current left top tile idx
			int nCurrLeftX = floor((nCenter_X-m_pViewer->width()/2)/256.0);
			int nCurrTopY = floor((nCenter_Y-m_pViewer->height()/2)/256.0);
			//!2.3 calculate current right bottom idx
			int nCurrRightX = ceil((nCenter_X+m_pViewer->width()/2)/256.0);
			int nCurrBottomY = ceil((nCenter_Y+m_pViewer->height()/2)/256.0);

			//!2.4 draw images
			bool needreg = false;
			int reg_left = sz_whole_idx,reg_right = -1,reg_bottom = -1,reg_top = sz_whole_idx;
			//!2.5 a repeat from tileindx left to right.
			for (int col = nCurrLeftX;col<=nCurrRightX;col++)
			{
				//!2.5.1 a repeat from tileindx top to bottom.
				for (int row = nCurrTopY;row<=nCurrBottomY;row++)
				{
					QImage image_source;
					int req_row = row, req_col = col;
					if (row<0 || row>=sz_whole_idx)
						continue;
					if (col>=sz_whole_idx)
						req_col = col % sz_whole_idx;
					if (col<0)
						req_col = (col + (1-col/sz_whole_idx)*sz_whole_idx) % sz_whole_idx;
					//!2.5.2 call getTileImage to query the image .
					if (false==this->getTileImage(m_pViewer->level(),req_col,req_row,image_source))
					{
						needreg = true;
						if (reg_left>=req_col) reg_left = req_col;
						if (reg_right<=req_col) reg_right = req_col;
						if (reg_top>=req_row) reg_top = req_row;
						if (reg_bottom<=req_row) reg_bottom = req_row;
					}
					else
					{
						//bitblt
						int nTileOffX = (col-nCenX)*256;
						int nTileOffY = (row-nCenY)*256;
						//0,0 lefttop offset
						int zero_offX = int(nCenter_X+0.5) % 256;
						int zero_offY = int(nCenter_Y+0.5) % 256;
						//bitblt cood
						int tar_x = m_pViewer->width()/2-zero_offX+nTileOffX;
						int tar_y = m_pViewer->height()/2-zero_offY+nTileOffY;
						//bitblt
						pPainter->drawImage(tar_x,tar_y,image_source);
					}
				}
			}
			//!2.6 if some image is not exists in local cache, tried to download
			if (needreg==true)
				RegImages(reg_left,reg_right,reg_top,reg_bottom,m_pViewer->level());
		}

	}
	layer_tiles::~layer_tiles()
	{
		m_downloadThread->quit();
		m_downloadThread->wait();
		m_downloader->deleteLater();
		if (!m_propPage)
			m_propPage->deleteLater();
	}

	bool layer_tiles::cb_mousePressEvent ( QMouseEvent * event )
	{
		if (!m_pViewer || m_bVisible==false || m_bActive==false) return false;
		bool res = false;
		if (event->button()==Qt::LeftButton)
		{
			this->m_nStartPosX = event->pos().x();
			this->m_nStartPosY = event->pos().y();
		}
		else if (event->button()==Qt::RightButton)
		{
			int nOffsetX = event->pos().x()-m_pViewer->width()/2;
			int nOffsetY = event->pos().y()-m_pViewer->height()/2;
			m_pViewer->DragView(-nOffsetX,-nOffsetY);
			res = true;
		}
		return res;
	}

	bool layer_tiles::cb_mouseReleaseEvent ( QMouseEvent * event )
	{
		if (!m_pViewer || m_bVisible==false || m_bActive==false) return false;
		bool res = false;
		if (event->button()==Qt::LeftButton)
		{
			int nOffsetX = event->pos().x()-this->m_nStartPosX;
			int nOffsetY = event->pos().y()-this->m_nStartPosY;
			if (!(nOffsetX ==0 && nOffsetY==0))
			{
				m_pViewer->DragView(nOffsetX,nOffsetY);
				this->m_nStartPosX = this->m_nStartPosY = -1;
				res = true;
			}
		}
		return res;
	}

	bool layer_tiles::cb_mouseMoveEvent(QMouseEvent * /*event*/)
	{
		return false;
	}

	bool layer_tiles::cb_wheelEvent ( QWheelEvent * event )
	{
		if (!m_pViewer || m_bVisible==false || m_bActive==false) return false;
		int nLevel = m_pViewer->level();
		if (event->delta()<0)
		{
			nLevel++;
			if (nLevel>18)
				nLevel=18;
		}
		else if (event->delta()>0)
		{
			nLevel--;
			if (nLevel<0)
				nLevel=0;
		}
		if (nLevel != m_pViewer->level())
			m_pViewer->setLevel(nLevel);
		return true;
	}

	void layer_tiles::cb_resizeEvent ( QResizeEvent * /*event*/)
	{
		if (!m_pViewer || m_bVisible==false) return;
	}

	layer_interface * layer_tiles::load_initial_plugin(QString /*strSLibPath*/,viewer_interface  * viewer)
	{
		m_pViewer = dynamic_cast<tilesviewer *>(viewer);
		if (!m_pViewer)
			return 0;
		connect(m_downloader,SIGNAL(evt_all_taskFinished()),m_pViewer,SLOT(UpdateWindow()));
		//Get Cache Address
		QSettings settings(QCoreApplication::applicationFilePath()+".ini",QSettings::IniFormat);
		m_strServerURL = settings.value(QString("settings/ServerURL_%1").arg(m_name),"http://c.tile.openstreetmap.org/%1/%2/%3.png").toString();
		m_strLocalCache = settings.value(QString("settings/LocalCache_%1").arg(m_name), QCoreApplication::applicationDirPath() +"/OSMCache").toString();
		return this;
	}

	QWidget * layer_tiles::load_prop_window()
	{
		if (!m_propPage)
			m_propPage = new layer_tiles_page(this,0);
		return m_propPage;
	}

	void layer_tiles::cb_levelChanged(int /*nLevel*/)
	{
		if (!m_pViewer || m_bVisible==false) return;
	}

	/*!
	 \brief Get a single tile PNG from web service. return false if error occurred.

	 \fn layer_tiles::getTileImage
	 \param nLevel current level
	 \param nX	current col
	 \param nY	current row
	 \param image	the image object to hold the result data
	 \return bool	succeed when ok.
	*/
	bool layer_tiles::getTileImage(int nLevel,int nX,int nY,QImage & image)
	{
		if (!m_pViewer || m_bVisible==false) return true;
		QString strVal = m_strLocalCache;
		strVal += '/';
		strVal += m_name;
		strVal += '/';
		strVal += QString::number(nLevel,10);
		strVal += '/';
		strVal += QString::number(nX,10);
		strVal += '/';
		strVal += QString::number(nY,10);
		strVal += ".png";

		bool res = true;
		if (res)
		{
			QByteArray array_out;
			QFile file(strVal);
			if (file.open(QIODevice::ReadOnly)==true)
			{
				array_out = file.readAll();
				image = QImage::fromData(array_out);
				if (image.isNull()==true)
					res = false;
			}
			else
				res = false;
		}
		return res;

	}

	void layer_tiles::UpdateLayer()
	{
		m_pViewer->update();
	}


	/*!
	 \brief connectToTilesServer will set connect flag to true.
	 notice that a connected tile means that it will try to doanload new tile images from
	 remote server, with no swearing for succeed doanload.
	 ther will be one event fired in this method.

	 \fn layer_tiles::connectToTilesServer
	 \param bconnected	return current status
	*/
	void layer_tiles::connectToTilesServer(bool bconnected)
	{
		this->m_bconnected = bconnected;
		if (!m_pViewer) return;
		m_pViewer->update();
		emit connected(m_bconnected);
		//! 1. source=MAIN_MAP,  destin = ALL, msg = CONNECTION
		if (this->is_active())
		{
			QMap<QString, QVariant> map_evt;
			map_evt["source"] = "MAIN_MAP";
			map_evt["destin"] = "ALL";
			map_evt["name"] = "CONNECTION";
			double tlat, tlon;
			m_pViewer->centerLLA(&tlat,&tlon);
			map_evt["main_lat"] = tlat;
			map_evt["main_lon"] = tlon;
			map_evt["nLevel"] = m_pViewer->level();
			map_evt["status"] =m_bconnected?"CONNECTED":"CLOSED";
			m_pViewer->post_event(map_evt);
		}
	}


	/*!
	 \brief RegImages will download images from tile address.

	 \fn layer_tiles::RegImages
	 \param nLeft	Left col (x) tile id og this level nLevel
	 \param nRight	Right col (x) tile id og this level nLevel
	 \param nTop	Top row (y) tile id og this level nLevel
	 \param nBottom	Bottom row (y) tile id og this level nLevel
	 \param nLevel	current level. In osm, nlevel often take 0~18
	 \return bool	succeeded.
	*/
	bool layer_tiles::RegImages(int nLeft,int nRight,int nTop,int nBottom,int nLevel)
	{
		if (!m_pViewer || m_bVisible==false) return true;
		if (m_bconnected==false)
			return true;
		for (int nX = nLeft; nX <=nRight ; ++nX)
		{
			for (int nY = nTop; nY <= nBottom ; ++nY)
			{
				QString LFix;
				QString strSourceUrl, strDestinDir, strFileName;
				LFix += '/';
				LFix += QString::number(nLevel,10);
				LFix += '/';
				LFix += QString::number(nX,10);
				strDestinDir = m_strLocalCache + "/" + m_name + "/" + LFix;
				LFix += '/';
				LFix += QString::number(nY,10);
				LFix += ".png";
				strFileName = QString::number(nY,10);
				strFileName += ".png";
				strSourceUrl = m_strServerURL.arg(nLevel).arg(nX).arg(nY);

				this->m_downloader->addDownloadUrl(strSourceUrl,strDestinDir,strFileName);
			}
		}
		return true;
	}
	QVector< tag_download_tasks >  layer_tiles::current_tasks()
	{
		if (m_downloader)
			return m_downloader->current_tasks();
		else
			return QVector< tag_download_tasks >();
	}
}