summaryrefslogtreecommitdiffstats
path: root/ksvg/core/KSVGLoader.cpp
blob: f075d2ff08015bd6ed659061e25af60de1a6f54a (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
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
    Copyright (C) 2001-2003 KSVG Team
    This file is part of the KDE project

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <tqxml.h>
#include <tqfile.h>
#include <tqimage.h>
#include <tqbuffer.h>

#include <kurl.h>
#include <kdebug.h>
#include <tdeio/job.h>
#include <kfilterdev.h>
#include <tdeio/netaccess.h>

#include "SVGDocumentImpl.h"
#include "SVGSVGElementImpl.h"
#include "SVGImageElementImpl.h"

#include "KSVGLoader.moc"

using namespace KSVG;

KSVGLoader::KSVGLoader() : m_data(0)
{
	m_job = 0;
}

KSVGLoader::~KSVGLoader()
{
}

TQString KSVGLoader::loadXML(::KURL url)
{
	TQString tmpFile;
	if(TDEIO::NetAccess::download(url, tmpFile, 0))
	{
		TQIODevice *dev = KFilterDev::deviceForFile(tmpFile, "application/x-gzip", true);
		TQByteArray contents;
		if(dev->open(IO_ReadOnly))
			contents = dev->readAll();
		delete dev;
		TDEIO::NetAccess::removeTempFile(tmpFile);
		return TQString(contents);
	}

	return TQString();
}

void KSVGLoader::getSVGContent(::KURL url)
{
	if(!url.prettyURL().isEmpty())
	{
		if(m_job == 0)
			m_job = TDEIO::get(url, false, false);

		m_job->setAutoErrorHandlingEnabled(true);

		connect(m_job, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)), this, TQT_SLOT(slotData(TDEIO::Job *, const TQByteArray &)));
		connect(m_job, TQT_SIGNAL(result(TDEIO::Job *)), this, TQT_SLOT(slotResult(TDEIO::Job *)));
	}
}

void KSVGLoader::newImageJob(SVGImageElementImpl *image, ::KURL baseURL)
{
	if(image && image->fileName().isEmpty())
	{
		kdDebug(26001) << "Image Element has no URL!" << endl;
		return;
	}

	ImageStreamMap *map = new ImageStreamMap();
	map->data = new TQByteArray();
	map->imageElement = image;

	TDEIO::TransferJob *imageJob = TDEIO::get(::KURL(baseURL, map->imageElement->fileName()), false, false);
	connect(imageJob, TQT_SIGNAL(data(TDEIO::Job *, const TQByteArray &)), this, TQT_SLOT(slotData(TDEIO::Job *, const TQByteArray &)));
	connect(imageJob, TQT_SIGNAL(result(TDEIO::Job *)), this, TQT_SLOT(slotResult(TDEIO::Job *)));

	m_imageJobs.insert(imageJob, map);
}

void KSVGLoader::slotData(TDEIO::Job *job, const TQByteArray &data)
{
	if(job == m_job)
	{
		TQDataStream dataStream(m_data, IO_WriteOnly | IO_Append);
		dataStream.writeRawBytes(data.data(), data.size());
	}
	else
	{
		TQMap<TDEIO::TransferJob *, ImageStreamMap *>::Iterator it;
		for(it = m_imageJobs.begin(); it != m_imageJobs.end(); ++it)
		{
			if(it.key() == job)
			{
				TQDataStream dataStream(*(it.data())->data, IO_WriteOnly | IO_Append);
				dataStream.writeRawBytes(data.data(), data.size());
				break;
			}
		}
	}
}

void KSVGLoader::slotResult(TDEIO::Job *job)
{
	if(job == m_job)
	{
		if(m_job->error() == 0)
		{
			TQString check = static_cast<TDEIO::TransferJob *>(job)->url().prettyURL();
			if(check.contains(".svgz") || check.contains(".svg.gz"))
			{
				// decode the gzipped svg and emit it
				TQIODevice *dev = KFilterDev::device(TQT_TQIODEVICE(new TQBuffer(m_data)), "application/x-gzip");
				dev->open(IO_ReadOnly);
				emit gotResult(dev);
			}
			else
			{
				m_job = 0;
				emit gotResult(TQT_TQIODEVICE(new TQBuffer(m_data)));
				m_data.resize(0);
			}
		}
	}
	else if(m_postUrlData.job == job)
	{
		// Notify that we're done
		KJS::List callBackArgs;
		callBackArgs.append(*m_postUrlData.status);

		m_postUrlData.status->put(m_postUrlData.exec, KJS::Identifier("success"), KJS::Boolean(true));
		m_postUrlData.callBackFunction->call(m_postUrlData.exec, *m_postUrlData.callBackFunction, callBackArgs);
	}
	else
	{
		TQMap<TDEIO::TransferJob *, ImageStreamMap *>::Iterator it;
		for(it = m_imageJobs.begin(); it != m_imageJobs.end(); ++it)
		{
			if(it.key() == job)
			{
				ImageStreamMap *streamMap = it.data();

				TQBuffer buffer(*(streamMap->data));

				if(buffer.open(IO_ReadOnly))
				{
					const char *imageFormat = TQImageIO::imageFormat(TQT_TQIODEVICE(&buffer));

					if(imageFormat != 0)
					{
						TQImageIO imageIO(&buffer, imageFormat);

						// Gamma correction
						imageIO.setGamma(1/0.45454); 

						if(imageIO.read())
						{
							TQImage *image = new TQImage(imageIO.image());
							image->detach();
							(streamMap->imageElement)->setImage(image);
						}
					}

					buffer.close();
				}

				(streamMap->data)->resize(0);

				m_imageJobs.remove(static_cast<TDEIO::TransferJob *>(job));

				emit imageReady(streamMap->imageElement);
				break;
			}
		}
	}
}

TQString KSVGLoader::getUrl(::KURL url, bool local)
{
	// Security issue: Only retrieve http and https
	if(local || (!url.prettyURL().isEmpty()) && ((url.protocol() == "http") || (url.protocol() == "https")))
		return loadXML(url);

	return TQString();
}

void KSVGLoader::postUrl(::KURL url, const TQByteArray &data, const TQString &mimeType,  KJS::ExecState *exec, KJS::Object &callBackFunction, KJS::Object &status)
{
	TDEIO::TransferJob *job = TDEIO::http_post(url, data, false);
	job->addMetaData("content-type", mimeType);

	m_postUrlData.job = job;
	m_postUrlData.exec = exec;
	m_postUrlData.status = &status;
	m_postUrlData.callBackFunction = &callBackFunction;

	connect(job, TQT_SIGNAL(result(TDEIO::Job *)), TQT_SLOT(slotResult(TDEIO::Job *)));
}

class CharacterDataSearcher : public TQXmlDefaultHandler
{
public:
	CharacterDataSearcher(const TQString &id) : m_id(id) { }

	virtual bool startDocument()
	{
		m_foundCount = 0;
		return true;
	}

	virtual bool startElement(const TQString &, const TQString &, const TQString &qName, const TQXmlAttributes &atts)
	{
		kdDebug(26001) << "CharacterDataSearcher::startElement, qName " << qName << endl;

		int pos = atts.index("id");
		if(pos > -1 && atts.value(pos) == m_id)
		{
			m_foundCount++;
			m_tagFound = qName;
		}

		return true;
	}

	virtual bool endElement(const TQString &, const TQString &, const TQString &qName)
	{
		if(m_tagFound == qName && m_foundCount > 0)
		{
			m_foundCount--;
			if(m_foundCount == 0)
				return false; // done!
		}

		return true;
	}

	virtual bool characters(const TQString &ch)
	{
		kdDebug(26001) << "CharacterDataSearcher::characters, read " << ch.latin1() << endl;

		if(m_tagFound != 0)
			m_result += ch;

		return true;
	}		

	TQString result() { return m_result; }

private:
	TQString m_id, m_result, m_tagFound;
	int m_foundCount;
};

TQString KSVGLoader::getCharacterData(::KURL url, const TQString &id)
{
	TQXmlSimpleReader reader;

	CharacterDataSearcher searcher(id);
	reader.setContentHandler(&searcher);
	reader.setErrorHandler(&searcher);

	TQString s = loadXML(url);

	TQXmlInputSource source;
	source.setData(s);

	reader.parse(&source);

	return searcher.result();
}



class SVGFragmentSearcher : public TQXmlDefaultHandler
{
public:
	SVGFragmentSearcher(SVGDocumentImpl *doc, const TQString &id, ::KURL url) : m_id(id), m_url(url), m_doc(doc) { }

	virtual bool startDocument()
	{
		m_result = 0;
		m_currentNode = 0;
		
		return true;
	}

	virtual bool startElement(const TQString &namespaceURI, const TQString &, const TQString &qName, const TQXmlAttributes &attrs)
	{
		kdDebug(26001) << "SVGFragmentSearcher::startElement, namespaceURI " << namespaceURI << ", qName " << qName << endl;
		bool parse = m_result;
		if(!parse)
		{
			int pos = attrs.index("id");
			if(pos > -1 && attrs.value(pos) == m_id)
				parse = true;
		}

		if(parse)
		{
			DOM::Element impl = static_cast<DOM::Document *>(m_doc)->createElementNS(namespaceURI, qName);
			SVGElementImpl *newElement = SVGDocumentImpl::createElement(qName, impl, m_doc);
			newElement->setViewportElement(m_doc->rootElement());

			if(m_currentNode)
				m_currentNode->appendChild(*newElement);
			else
				m_result = newElement;

			TQXmlAttributes newAttrs;

			for(int i = 0; i < attrs.count(); i++)
			{
				TQString name = attrs.localName(i);
				TQString value = attrs.value(i);

				if(name == "id")
				{
					value = "@fragment@" + m_url.prettyURL() + "@" + value;
					m_idMap[value] = newElement;
				}
				else
				if(name == "href")
				{
					value.stripWhiteSpace();

					if(value.startsWith("#"))
					{
						value.remove(0, 1);

						// Convert the id to its mangled version.
						TQString id = "@fragment@" + m_url.prettyURL() + "@" + value;

						if(m_idMap.contains(id))
						{
							// This is a local reference to an element within the fragment.
							// Just convert the href.
							value = id;
						}
						else
						{
							// This is a local reference to an id outside of the fragment.
							// Change it into an absolute href.
							value = m_url.prettyURL() + "#" + value;
						}
					}
				}

				newAttrs.append(attrs.qName(i), attrs.uri(i), attrs.localName(i), value);
			}

			newElement->setAttributes(newAttrs);
			m_currentNode = newElement;
		}

		return true;
	}

	virtual bool endElement(const TQString &, const TQString &, const TQString &)
	{
		if(m_result)
		{
			m_parentNode = m_currentNode->parentNode();
			
			if(m_parentNode.isNull())
				return false; // done!

			m_currentNode = &m_parentNode;
		}

		return true;
	}

	virtual bool characters(const TQString &ch)
	{
		kdDebug(26001) << "SVGFragmentSearcher::characters, read " << ch.latin1() << endl;

		if(m_result)
		{
			SVGElementImpl *element = m_result->ownerDoc()->getElementFromHandle(m_currentNode->handle());
			if(element)
			{
				TQString t = ch;

				SVGLangSpaceImpl *langSpace = dynamic_cast<SVGLangSpaceImpl *>(element);
				if(langSpace)
					t = langSpace->handleText(ch);

				if(!t.isEmpty())
				{
					DOM::Text impl = static_cast<DOM::Document *>(m_result->ownerDoc())->createTextNode(t);
					element->appendChild(impl);
				}
			}
		}

		return true;
	}

	SVGElementImpl *result() { return m_result; }

private:
	TQString m_id;
	::KURL m_url;

	SVGDocumentImpl *m_doc;
	SVGElementImpl *m_result;

	DOM::Node *m_currentNode, m_parentNode;
	TQMap<TQString, SVGElementImpl *> m_idMap;
};

SVGElementImpl *KSVGLoader::getSVGFragment(::KURL url, SVGDocumentImpl *doc, const TQString &id)
{
	TQXmlSimpleReader reader;

	kdDebug(26001) << "getSVGFragment: " << url.prettyURL() << "#" << id << endl;
	SVGFragmentSearcher searcher(doc, id, url);
	reader.setContentHandler(&searcher);
	reader.setErrorHandler(&searcher);

	TQString s = loadXML(url);

	TQXmlInputSource source;
	source.setData(s);

	reader.parse(&source);

	return searcher.result();
}