summaryrefslogtreecommitdiffstats
path: root/kdecore/svgicons/ksvgiconengine.cpp
blob: dd54e99be4fbfbff369353dc19f66be30ac2404b (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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*
    Copyright (C) 2002 Nikolas Zimmermann <wildfox@kde.org>
    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 <tqdom.h>
#include <tqfile.h>
#include <tqcolor.h>
#include <tqimage.h>
#include <tqwmatrix.h>
#include <tqregexp.h>

#include <kmdcodec.h>

#include <zlib.h>

#include "ksvgiconpainter.h"
#include "ksvgiconengine.h"

class KSVGIconEngineHelper
{
public:
	KSVGIconEngineHelper(KSVGIconEngine *engine)
	{
		m_engine = engine;
	}

	~KSVGIconEngineHelper()
	{
	}

	double toPixel(const TQString &s, bool hmode)
	{
		return m_engine->painter()->toPixel(s, hmode);
	}

	ArtGradientStop *parseGradientStops(TQDomElement element, int &offsets)
	{
		if (!element.hasChildNodes())
			return 0;

		TQValueList<ArtGradientStop> stopList;

		float oldOffset = -1, newOffset = -1;
		for(TQDomNode node = element.firstChild(); !node.isNull(); node = node.nextSibling())
		{
			TQDomElement element = node.toElement();

			oldOffset = newOffset;
			TQString temp = element.attribute("offset");

			if(temp.contains("%"))
			{
				temp = temp.left(temp.length() - 1);
				newOffset = temp.toFloat() / 100.0;
			}
			else
				newOffset = temp.toFloat();

			// Spec  skip double offset specifications
			if(oldOffset == newOffset)
				continue;

			offsets++;
			stopList.append(ArtGradientStop());

			ArtGradientStop &stop = stopList.last();

			stop.offset = newOffset;

			TQString parseOpacity;
			TQString parseColor;

			if(element.hasAttribute("stop-opacity"))
				parseOpacity = element.attribute("stop-opacity");

			if(element.hasAttribute("stop-color"))
				parseColor = element.attribute("stop-color");

			if(parseOpacity.isEmpty() || parseColor.isEmpty())
			{
				TQString style = element.attribute("style");

				TQStringList substyles = TQStringList::split(';', style);
				for(TQStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it)
				{
					TQStringList substyle = TQStringList::split(':', (*it));
					TQString command = substyle[0];
					TQString params = substyle[1];
					command = command.stripWhiteSpace();
					params = params.stripWhiteSpace();

					if(command == "stop-color")
					{
						parseColor = params;

						if(!parseOpacity.isEmpty())
							break;
					}
					else if(command == "stop-opacity")
					{
						parseOpacity = params;

						if(!parseColor.isEmpty())
							break;
					}
				}
			}

			// Parse color using KSVGIconPainter (which uses Qt)
			// Supports all svg-needed color formats
			TQColor qStopColor = m_engine->painter()->parseColor(parseColor);

			// Convert in a libart suitable form
			Q_UINT32 stopColor = m_engine->painter()->toArtColor(qStopColor);

			int opacity = m_engine->painter()->parseOpacity(parseOpacity);

			Q_UINT32 rgba = (stopColor << 8) | opacity;
			Q_UINT32 r, g, b, a;

			// Convert from separated to premultiplied alpha
			a = rgba & 0xff;
			r = (rgba >> 24) * a + 0x80;
			r = (r + (r >> 8)) >> 8;
			g = ((rgba >> 16) & 0xff) * a + 0x80;
			g = (g + (g >> 8)) >> 8;
			b = ((rgba >> 8) & 0xff) * a + 0x80;
			b = (b + (b >> 8)) >> 8;

			stop.color[0] = ART_PIX_MAX_FROM_8(r);
			stop.color[1] = ART_PIX_MAX_FROM_8(g);
			stop.color[2] = ART_PIX_MAX_FROM_8(b);
			stop.color[3] = ART_PIX_MAX_FROM_8(a);
		}

		if (stopList.isEmpty())
			return 0;

		ArtGradientStop *stops = new ArtGradientStop[stopList.count()];

		TQValueList<ArtGradientStop>::iterator it = stopList.begin();
		TQValueList<ArtGradientStop>::iterator end = stopList.end();

		for (int i = 0; it != end; ++i, ++it)
			stops[i] = *it;

		return stops;
	}

	TQPointArray parsePoints(TQString points)
	{
		if(points.isEmpty())
			return TQPointArray();

		points = points.simplifyWhiteSpace();

		if(points.contains(",,") || points.contains(", ,"))
			return TQPointArray();

		points.replace(',', ' ');
		points.replace('\r', TQString::null);
		points.replace('\n', TQString::null);

		points = points.simplifyWhiteSpace();

		TQStringList pointList = TQStringList::split(' ', points);

		TQPointArray array(pointList.count() / 2);
		int i = 0;

		for(TQStringList::Iterator it = pointList.begin(); it != pointList.end(); it++)
		{
			float x = (*(it++)).toFloat();
			float y = (*(it)).toFloat();

			array.setPoint(i, static_cast<int>(x), static_cast<int>(y));
			i++;
		}

		return array;
	}

	void parseTransform(const TQString &transform)
	{
		// Combine new and old matrix
		TQWMatrix matrix = m_engine->painter()->parseTransform(transform);

		TQWMatrix *current = m_engine->painter()->worldMatrix();
		*current = matrix * *current;
	}

	void parseCommonAttributes(TQDomNode &node)
	{
		// Set important default attributes
		m_engine->painter()->setFillColor("black");
		m_engine->painter()->setStrokeColor("none");
		m_engine->painter()->setStrokeDashArray("");
		m_engine->painter()->setStrokeWidth(1);
		m_engine->painter()->setJoinStyle("");
		m_engine->painter()->setCapStyle("");
	//	m_engine->painter()->setFillOpacity(255, true);
	//	m_engine->painter()->setStrokeOpacity(255, true);

		// Collect parent node's attributes
		TQPtrList<TQDomNamedNodeMap> applyList;
		applyList.setAutoDelete(true);

		TQDomNode shape = node.parentNode();
		for(; !shape.isNull() ; shape = shape.parentNode())
			applyList.prepend(new TQDomNamedNodeMap(shape.attributes()));

		// Apply parent attributes
		for(TQDomNamedNodeMap *map = applyList.first(); map != 0; map = applyList.next())
		{
			TQDomNamedNodeMap attr = *map;

			for(unsigned int i = 0; i < attr.count(); i++)
			{
				TQString name, value;

				name = attr.item(i).nodeName().lower();
				value = attr.item(i).nodeValue();

				if(name == "transform")
					parseTransform(value);
				else if(name == "style")
					parseStyle(value);
				else
					parsePA(name, value);
			}
		}

		// Apply local attributes
		TQDomNamedNodeMap attr = node.attributes();

		for(unsigned int i = 0; i < attr.count(); i++)
		{
			TQDomNode current = attr.item(i);

			if(current.nodeName().lower() == "transform")
				parseTransform(current.nodeValue());
			else if(current.nodeName().lower() == "style")
				parseStyle(current.nodeValue());
			else
				parsePA(current.nodeName().lower(), current.nodeValue());
		}
	}

	bool handleTags(TQDomElement element, bool paint)
	{
		if(element.attribute("display") == "none")
			return false;
		if(element.tagName() == "linearGradient")
		{
			ArtGradientLinear *gradient = new ArtGradientLinear();

			int offsets = -1;
			gradient->stops = parseGradientStops(element, offsets);
			gradient->n_stops = offsets + 1;

			TQString spread = element.attribute("spreadMethod");
			if(spread == "repeat")
				gradient->spread = ART_GRADIENT_REPEAT;
			else if(spread == "reflect")
				gradient->spread = ART_GRADIENT_REFLECT;
			else
				gradient->spread = ART_GRADIENT_PAD;

			m_engine->painter()->addLinearGradient(element.attribute("id"), gradient);
			m_engine->painter()->addLinearGradientElement(gradient, element);
			return true;
		}
		else if(element.tagName() == "radialGradient")
		{
			ArtGradientRadial *gradient = new ArtGradientRadial();

			int offsets = -1;
			gradient->stops = parseGradientStops(element, offsets);
			gradient->n_stops = offsets + 1;

			m_engine->painter()->addRadialGradient(element.attribute("id"), gradient);
			m_engine->painter()->addRadialGradientElement(gradient, element);
			return true;
		}

		if(!paint)
			return true;

		// TODO: Default attribute values
		if(element.tagName() == "rect")
		{
			double x = toPixel(element.attribute("x"), true);
			double y = toPixel(element.attribute("y"), false);
			double w = toPixel(element.attribute("width"), true);
			double h = toPixel(element.attribute("height"), false);

			double rx = 0.0;
			double ry = 0.0;

			if(element.hasAttribute("rx"))
				rx = toPixel(element.attribute("rx"), true);

			if(element.hasAttribute("ry"))
				ry = toPixel(element.attribute("ry"), false);

			m_engine->painter()->drawRectangle(x, y, w, h, rx, ry);
		}
		else if(element.tagName() == "switch")
		{
			TQDomNode iterate = element.firstChild();

			while(!iterate.isNull())
			{
				// Reset matrix
				m_engine->painter()->setWorldMatrix(new TQWMatrix(m_initialMatrix));

				// Parse common attributes, style / transform
				parseCommonAttributes(iterate);

				if(handleTags(iterate.toElement(), true))
					return true;
				iterate = iterate.nextSibling();
			}
			return true;
		}
		else if(element.tagName() == "g" || element.tagName() == "defs")
		{
			TQDomNode iterate = element.firstChild();

			while(!iterate.isNull())
			{
				// Reset matrix
				m_engine->painter()->setWorldMatrix(new TQWMatrix(m_initialMatrix));

				// Parse common attributes, style / transform
				parseCommonAttributes(iterate);

				handleTags(iterate.toElement(), (element.tagName() == "defs") ? false : true);
				iterate = iterate.nextSibling();
			}
			return true;
		}
		else if(element.tagName() == "line")
		{
			double x1 = toPixel(element.attribute("x1"), true);
			double y1 = toPixel(element.attribute("y1"), false);
			double x2 = toPixel(element.attribute("x2"), true);
			double y2 = toPixel(element.attribute("y2"), false);

			m_engine->painter()->drawLine(x1, y1, x2, y2);
			return true;
		}
		else if(element.tagName() == "circle")
		{
			double cx = toPixel(element.attribute("cx"), true);
			double cy = toPixel(element.attribute("cy"), false);

			double r = toPixel(element.attribute("r"), true); // TODO: horiz correct?

			m_engine->painter()->drawEllipse(cx, cy, r, r);
			return true;
		}
		else if(element.tagName() == "ellipse")
		{
			double cx = toPixel(element.attribute("cx"), true);
			double cy = toPixel(element.attribute("cy"), false);

			double rx = toPixel(element.attribute("rx"), true);
			double ry = toPixel(element.attribute("ry"), false);

			m_engine->painter()->drawEllipse(cx, cy, rx, ry);
			return true;
		}
		else if(element.tagName() == "polyline")
		{
			TQPointArray polyline = parsePoints(element.attribute("points"));
			m_engine->painter()->drawPolyline(polyline);
			return true;
		}
		else if(element.tagName() == "polygon")
		{
			TQPointArray polygon = parsePoints(element.attribute("points"));
			m_engine->painter()->drawPolygon(polygon);
			return true;
		}
		else if(element.tagName() == "path")
		{
			bool filled = true;

			if(element.hasAttribute("fill") && element.attribute("fill").contains("none"))
				filled = false;

			if(element.attribute("style").contains("fill") && element.attribute("style").stripWhiteSpace().contains("fill:none"))
				filled = false;

			m_engine->painter()->drawPath(element.attribute("d"), filled);
			return true;
		}
		else if(element.tagName() == "image")
		{
			double x = toPixel(element.attribute("x"), true);
			double y = toPixel(element.attribute("y"), false);
			double w = toPixel(element.attribute("width"), true);
			double h = toPixel(element.attribute("height"), false);

			TQString href = element.attribute("xlink:href");

			TQImage image;
			if(href.startsWith("data:"))
			{
				// Get input
				TQCString input = href.remove(TQRegExp("^data:image/.*;base64,")).utf8();

				// Decode into 'output'
				TQByteArray output;
				KCodecs::base64Decode(input, output);

				// Display
				image.loadFromData(output);
			}
			else
				image.load(href);

			if (!image.isNull())
			{
				// Scale, if needed
				if(image.width() != (int) w || image.height() != (int) h)
					image = image.smoothScale((int) w, (int) h, TQImage_ScaleFree);

				m_engine->painter()->drawImage(x, y, image);
			}

			return true;
		}
		return false;
	}

	void parseStyle(const TQString &style)
	{
		TQStringList substyles = TQStringList::split(';', style);
		for(TQStringList::Iterator it = substyles.begin(); it != substyles.end(); ++it)
		{
			TQStringList substyle = TQStringList::split(':', (*it));
			TQString command = substyle[0];
			TQString params = substyle[1];
			command = command.stripWhiteSpace();
			params = params.stripWhiteSpace();

			parsePA(command, params);
		}
	}

	void parsePA(const TQString &command, const TQString &value)
	{
		if(command == "stroke-width") // TODO: horiz:false correct?
			m_engine->painter()->setStrokeWidth(toPixel(value, false));
		else if(command == "stroke-miterlimit")
			m_engine->painter()->setStrokeMiterLimit(value);
		else if(command == "stroke-linecap")
			m_engine->painter()->setCapStyle(value);
		else if(command == "stroke-linejoin")
			m_engine->painter()->setJoinStyle(value);
		else if(command == "stroke-dashoffset")
			m_engine->painter()->setStrokeDashOffset(value);
		else if(command == "stroke-dasharray" && value != "none")
			m_engine->painter()->setStrokeDashArray(value);
		else if(command == "stroke")
			m_engine->painter()->setStrokeColor(value);
		else if(command == "fill")
			m_engine->painter()->setFillColor(value);
		else if(command == "fill-rule")
			m_engine->painter()->setFillRule(value);
		else if(command == "fill-opacity" || command == "stroke-opacity" || command == "opacity")
		{
			if(command == "fill-opacity")
				m_engine->painter()->setFillOpacity(value);
			else if(command == "stroke-value")
				m_engine->painter()->setStrokeOpacity(value);
			else
			{
				m_engine->painter()->setOpacity(value);
				m_engine->painter()->setFillOpacity(value);
				m_engine->painter()->setStrokeOpacity(value);
			}
		}
	}

private:
	friend class KSVGIconEngine;

	KSVGIconEngine *m_engine;
	TQWMatrix m_initialMatrix;
};

struct KSVGIconEngine::Private
{
	KSVGIconPainter *painter;
	KSVGIconEngineHelper *helper;

	double width;
	double height;
};

KSVGIconEngine::KSVGIconEngine() : d(new Private())
{
	d->painter = 0;
	d->helper = new KSVGIconEngineHelper(this);

	d->width = 0.0;
	d->height = 0.0;
}

KSVGIconEngine::~KSVGIconEngine()
{
	if(d->painter)
		delete d->painter;

	delete d->helper;

	delete d;
}

bool KSVGIconEngine::load(int width, int height, const TQString &path)
{
	TQDomDocument svgDocument("svg");
	TQFile file(path);

	if(path.right(3).upper() == "SVG")
	{
		// Open SVG Icon
		if(!file.open(IO_ReadOnly))
			return false;

		svgDocument.setContent(&file);
	}
	else // SVGZ
	{
		gzFile svgz = gzopen(path.latin1(), "ro");
		if(!svgz)
			return false;

		TQString data;
		bool done = false;

		TQCString buffer(1024);
		int length = 0;

		while(!done)
		{
			int ret = gzread(svgz, buffer.data() + length, 1024);
			if(ret == 0)
				done = true;
			else if(ret == -1)
				return false;
			else {
				buffer.resize(buffer.size()+1024);
				length += ret;
			}
		}

		gzclose(svgz);

		svgDocument.setContent(buffer);
	}

	if(svgDocument.isNull())
		return false;

	// Check for root element
	TQDomNode rootNode = svgDocument.namedItem("svg");
	if(rootNode.isNull() || !rootNode.isElement())
		return false;

	// Detect width and height
	TQDomElement rootElement = rootNode.toElement();

	// Create icon painter
	d->painter = new KSVGIconPainter(width, height);

	d->width = width; // this sets default for no width -> 100% case
	if(rootElement.hasAttribute("width"))
		d->width = d->helper->toPixel(rootElement.attribute("width"), true);

	d->height = height; // this sets default for no height -> 100% case
	if(rootElement.hasAttribute("height"))
		d->height = d->helper->toPixel(rootElement.attribute("height"), false);

	// Create icon painter
	d->painter->setDrawWidth(static_cast<int>(d->width));
	d->painter->setDrawHeight(static_cast<int>(d->height));

	// Set viewport clipping rect
	d->painter->setClippingRect(0, 0, width, height);

	// Apply viewbox
	if(rootElement.hasAttribute("viewBox"))
	{
		TQStringList points = TQStringList::split(' ', rootElement.attribute("viewBox").simplifyWhiteSpace());

		float w = points[2].toFloat();
		float h = points[3].toFloat();

		double vratiow = width / w;
		double vratioh = height / h;

		d->width = w;
		d->height = h;

		d->painter->worldMatrix()->scale(vratiow, vratioh);
	}
	else
	{
		// Fit into 'width' and 'height'
		// FIXME: Use an aspect ratio
		double ratiow = width / d->width;
		double ratioh = height / d->height;

		d->painter->worldMatrix()->scale(ratiow, ratioh);
	}

	TQWMatrix initialMatrix = *d->painter->worldMatrix();
	d->helper->m_initialMatrix = initialMatrix;

	// Apply transform
	if(rootElement.hasAttribute("transform"))
		d->helper->parseTransform(rootElement.attribute("transform"));

	// Go through all elements
	TQDomNode svgNode = rootElement.firstChild();
	while(!svgNode.isNull())
	{
		TQDomElement svgChild = svgNode.toElement();
		if(!svgChild.isNull())
		{
			d->helper->parseCommonAttributes(svgNode);
			d->helper->handleTags(svgChild, true);
		}

		svgNode = svgNode.nextSibling();

		// Reset matrix
		d->painter->setWorldMatrix(new TQWMatrix(initialMatrix));
	}

	d->painter->finish();

	return true;
}

KSVGIconPainter *KSVGIconEngine::painter()
{
	return d->painter;
}

TQImage *KSVGIconEngine::image()
{
	return d->painter->image();
}

double KSVGIconEngine::width()
{
	return d->width;
}

double KSVGIconEngine::height()
{
	return d->height;
}

// vim:ts=4:noet