Debian Codegraph @

utils/fgqcanvas/fgcanvaspath.cpp

raw symbols SCIP
1 //
2 // Copyright (C) 2017 James Turner [email protected]
3 //
4 // This program is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU General Public License as
6 // published by the Free Software Foundation; either version 2 of the
7 // License, or (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but
10 // WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 #include "fgcanvaspath.h"
19
20 #include <cctype>
21
22 #include <QByteArrayList>
23 #include <QPainter>
24 #include <QDebug>
25 #include <QtMath>
26 #include <QPen>
27
28 #include "fgcanvaspaintcontext.h"
29 #include "localprop.h"
30 #include "canvasitem.h"
31
32 #include "private/qtriangulator_p.h" // private QtGui header
33 #include "private/qtriangulatingstroker_p.h" // private QtGui header
34 #include "private/qvectorpath_p.h" // private QtGui header
35
36 #include <QSGGeometry>
37 #include <QSGGeometryNode>
38 #include <QSGFlatColorMaterial>
39
40 class PathQuickItem : public CanvasItem
41 {
42 Q_OBJECT
43
44 Q_PROPERTY(QColor fillColor READ fillColor WRITE setFillColor NOTIFY fillColorChanged)
45 Q_PROPERTY(QPen stroke READ stroke WRITE setStroke NOTIFY strokeChanged)
46
47 public:
48 PathQuickItem(QQuickItem* parent)
49 : CanvasItem(parent)
50 {
51 setFlag(ItemHasContents);
52 }
53
54 void setPath(QPainterPath pp)
55 {
56 m_path = pp;
57
58 QRectF pathBounds = pp.boundingRect();
59 setImplicitSize(pathBounds.width(), pathBounds.height());
60
61 update(); // request a paint node update
62 }
63
64 QSGNode* updateRealPaintNode(QSGNode* oldNode, QQuickItem::UpdatePaintNodeData *) override
65 {
66 if (m_path.isEmpty()) {
67 return nullptr;
68 }
69
70 delete oldNode;
71 QSGGeometryNode* fillGeom = nullptr;
72 QSGGeometryNode* strokeGeom = nullptr;
73
74 if (m_fillColor.isValid()) {
75 // TODO: compute LOD for qTriangulate based on world transform
76 QTransform transform;
77 QTriangleSet triangles = qTriangulate(m_path, transform);
78
79 int indexType = GL_UNSIGNED_SHORT;
80 if (triangles.indices.type() == QVertexIndexVector::UnsignedShort) {
81 // default is fine
82 } else if (triangles.indices.type() == QVertexIndexVector::UnsignedInt) {
83 indexType = GL_UNSIGNED_INT;
84 } else {
85 qFatal("Unsupported triangle index type");
86 }
87
88 QSGGeometry* sgGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(),
89 triangles.vertices.size() >> 1,
90 triangles.indices.size(),
91 indexType);
92
93 sgGeom->setIndexDataPattern(QSGGeometry::StaticPattern);
94 sgGeom->setDrawingMode(GL_TRIANGLES);
95
96 //
97 QSGGeometry::Point2D *points = sgGeom->vertexDataAsPoint2D();
98 for (int v=0; v < triangles.vertices.size(); ) {
99 const float vx = triangles.vertices.at(v++);
100 const float vy = triangles.vertices.at(v++);
101 (points++)->set(vx, vy);
102 }
103
104 if (triangles.indices.type() == QVertexIndexVector::UnsignedShort) {
105 quint16* indices = sgGeom->indexDataAsUShort();
106 ::memcpy(indices, triangles.indices.data(), sizeof(unsigned short) * triangles.indices.size());
107 } else {
108 quint32* indices = sgGeom->indexDataAsUInt();
109 ::memcpy(indices, triangles.indices.data(), sizeof(quint32) * triangles.indices.size());
110 }
111
112 // create the node now, pretty trivial
113 fillGeom = new QSGGeometryNode;
114 fillGeom->setGeometry(sgGeom);
115 fillGeom->setFlag(QSGNode::OwnsGeometry);
116
117 QSGFlatColorMaterial* mat = new QSGFlatColorMaterial();
118 mat->setColor(m_fillColor);
119 fillGeom->setMaterial(mat);
120 fillGeom->setFlag(QSGNode::OwnsMaterial);
121 }
122
123 if (m_stroke.style() != Qt::NoPen) {
124 const QVectorPath& vp = qtVectorPathForPath(m_path);
125 QRectF clipBounds;
126 QTriangulatingStroker ts;
127 QPainter::RenderHints renderHints;
128
129 if (m_stroke.style() == Qt::SolidLine) {
130 ts.process(vp, m_stroke, clipBounds, renderHints);
131 #if 0
132 inline int vertexCount() const { return m_vertices.size(); }
133 inline const float *vertices() const { return m_vertices.data(); }
134
135 #endif
136 } else {
137 QDashedStrokeProcessor dasher;
138 dasher.process(vp, m_stroke, clipBounds, renderHints);
139
140 QVectorPath dashStroke(dasher.points(),
141 dasher.elementCount(),
142 dasher.elementTypes(),
143 renderHints);
144
145 ts.process(dashStroke, m_stroke, clipBounds, renderHints);
146 }
147
148 QSGGeometry* sgGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(),
149 ts.vertexCount() >> 1);
150 sgGeom->setVertexDataPattern(QSGGeometry::StaticPattern);
151 sgGeom->setDrawingMode(GL_TRIANGLE_STRIP);
152
153 QSGGeometry::Point2D *points = sgGeom->vertexDataAsPoint2D();
154 const float* vPtr = ts.vertices();
155 for (int v=0; v < ts.vertexCount(); v += 2) {
156 const float vx = *vPtr++;
157 const float vy = *vPtr++;
158 (points++)->set(vx, vy);
159 }
160
161 // create the node now, pretty trivial
162 strokeGeom = new QSGGeometryNode;
163 strokeGeom->setGeometry(sgGeom);
164 strokeGeom->setFlag(QSGNode::OwnsGeometry);
165
166 QSGFlatColorMaterial* mat = new QSGFlatColorMaterial();
167 mat->setColor(m_stroke.color());
168 strokeGeom->setMaterial(mat);
169 strokeGeom->setFlag(QSGNode::OwnsMaterial);
170 }
171
172 if (fillGeom && strokeGeom) {
173 QSGNode* groupNode = new QSGNode;
174 groupNode->appendChildNode(fillGeom);
175 groupNode->appendChildNode(strokeGeom);
176 return groupNode;
177 } else if (fillGeom) {
178 return fillGeom;
179 }
180
181 return strokeGeom;
182 }
183
184 QColor fillColor() const
185 {
186 return m_fillColor;
187 }
188
189 QPen stroke() const
190 {
191 return m_stroke;
192 }
193
194 public slots:
195 void setFillColor(QColor fillColor)
196 {
197 if (m_fillColor == fillColor)
198 return;
199
200 m_fillColor = fillColor;
201 emit fillColorChanged(fillColor);
202 update();
203 }
204
205 void setStroke(QPen stroke)
206 {
207 if (m_stroke == stroke)
208 return;
209
210 m_stroke = stroke;
211 emit strokeChanged(stroke);
212 update();
213 }
214
215 signals:
216 void fillColorChanged(QColor fillColor);
217
218 void strokeChanged(QPen stroke);
219
220 protected:
221 void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) override
222 {
223 QQuickItem::geometryChanged(newGeometry, oldGeometry);
224 update();
225 }
226
227 QRectF boundingRect() const override
228 {
229 if ((width() == 0.0) || (height() == 0.0)) {
230 return QRectF(0.0, 0.0, implicitWidth(), implicitHeight());
231 }
232
233 return QQuickItem::boundingRect();
234 }
235
236 private:
237 QPainterPath m_path;
238 QColor m_fillColor;
239 QPen m_stroke;
240 };
241
242 static void pathArcSegment(QPainterPath &path,
243 qreal xc, qreal yc,
244 qreal th0, qreal th1,
245 qreal rx, qreal ry, qreal xAxisRotation)
246 {
247 qreal sinTh, cosTh;
248 qreal a00, a01, a10, a11;
249 qreal x1, y1, x2, y2, x3, y3;
250 qreal t;
251 qreal thHalf;
252
253 sinTh = qSin(xAxisRotation * (M_PI / 180.0));
254 cosTh = qCos(xAxisRotation * (M_PI / 180.0));
255
256 a00 = cosTh * rx;
257 a01 = -sinTh * ry;
258 a10 = sinTh * rx;
259 a11 = cosTh * ry;
260
261 thHalf = 0.5 * (th1 - th0);
262 t = (8.0 / 3.0) * qSin(thHalf * 0.5) * qSin(thHalf * 0.5) / qSin(thHalf);
263 x1 = xc + qCos(th0) - t * qSin(th0);
264 y1 = yc + qSin(th0) + t * qCos(th0);
265 x3 = xc + qCos(th1);
266 y3 = yc + qSin(th1);
267 x2 = x3 + t * qSin(th1);
268 y2 = y3 - t * qCos(th1);
269
270 path.cubicTo(a00 * x1 + a01 * y1, a10 * x1 + a11 * y1,
271 a00 * x2 + a01 * y2, a10 * x2 + a11 * y2,
272 a00 * x3 + a01 * y3, a10 * x3 + a11 * y3);
273 }
274
275 // the arc handling code underneath is from XSVG (BSD license)
276 /*
277 * Copyright 2002 USC/Information Sciences Institute
278 *
279 * Permission to use, copy, modify, distribute, and sell this software
280 * and its documentation for any purpose is hereby granted without
281 * fee, provided that the above copyright notice appear in all copies
282 * and that both that copyright notice and this permission notice
283 * appear in supporting documentation, and that the name of
284 * Information Sciences Institute not be used in advertising or
285 * publicity pertaining to distribution of the software without
286 * specific, written prior permission. Information Sciences Institute
287 * makes no representations about the suitability of this software for
288 * any purpose. It is provided "as is" without express or implied
289 * warranty.
290 *
291 * INFORMATION SCIENCES INSTITUTE DISCLAIMS ALL WARRANTIES WITH REGARD
292 * TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
293 * MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL INFORMATION SCIENCES
294 * INSTITUTE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
295 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
296 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
297 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
298 * PERFORMANCE OF THIS SOFTWARE.
299 *
300 */
301 static void pathArc(QPainterPath &path,
302 qreal rx,
303 qreal ry,
304 qreal x_axis_rotation,
305 int large_arc_flag,
306 int sweep_flag,
307 qreal x,
308 qreal y,
309 qreal curx, qreal cury)
310 {
311 qreal sin_th, cos_th;
312 qreal a00, a01, a10, a11;
313 qreal x0, y0, x1, y1, xc, yc;
314 qreal d, sfactor, sfactor_sq;
315 qreal th0, th1, th_arc;
316 int i, n_segs;
317 qreal dx, dy, dx1, dy1, Pr1, Pr2, Px, Py, check;
318
319 rx = qAbs(rx);
320 ry = qAbs(ry);
321
322 sin_th = qSin(x_axis_rotation * (M_PI / 180.0));
323 cos_th = qCos(x_axis_rotation * (M_PI / 180.0));
324
325 dx = (curx - x) / 2.0;
326 dy = (cury - y) / 2.0;
327 dx1 = cos_th * dx + sin_th * dy;
328 dy1 = -sin_th * dx + cos_th * dy;
329 Pr1 = rx * rx;
330 Pr2 = ry * ry;
331 Px = dx1 * dx1;
332 Py = dy1 * dy1;
333 /* Spec : check if radii are large enough */
334 check = Px / Pr1 + Py / Pr2;
335 if (check > 1) {
336 rx = rx * qSqrt(check);
337 ry = ry * qSqrt(check);
338 }
339
340 a00 = cos_th / rx;
341 a01 = sin_th / rx;
342 a10 = -sin_th / ry;
343 a11 = cos_th / ry;
344 x0 = a00 * curx + a01 * cury;
345 y0 = a10 * curx + a11 * cury;
346 x1 = a00 * x + a01 * y;
347 y1 = a10 * x + a11 * y;
348 /* (x0, y0) is current point in transformed coordinate space.
349 (x1, y1) is new point in transformed coordinate space.
350
351 The arc fits a unit-radius circle in this space.
352 */
353 d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
354 sfactor_sq = 1.0 / d - 0.25;
355 if (sfactor_sq < 0) sfactor_sq = 0;
356 sfactor = qSqrt(sfactor_sq);
357 if (sweep_flag == large_arc_flag) sfactor = -sfactor;
358 xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
359 yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
360 /* (xc, yc) is center of the circle. */
361
362 th0 = qAtan2(y0 - yc, x0 - xc);
363 th1 = qAtan2(y1 - yc, x1 - xc);
364
365 th_arc = th1 - th0;
366 if (th_arc < 0 && sweep_flag)
367 th_arc += 2 * M_PI;
368 else if (th_arc > 0 && !sweep_flag)
369 th_arc -= 2 * M_PI;
370
371 n_segs = qCeil(qAbs(th_arc / (M_PI * 0.5 + 0.001)));
372
373 for (i = 0; i < n_segs; i++) {
374 pathArcSegment(path, xc, yc,
375 th0 + i * th_arc / n_segs,
376 th0 + (i + 1) * th_arc / n_segs,
377 rx, ry, x_axis_rotation);
378 }
379 }
380
381 ///////////////////////////////////////////////////////////////////////////////
382
383
384 FGCanvasPath::FGCanvasPath(FGCanvasGroup* pr, LocalProp* prop) :
385 FGCanvasElement(pr, prop)
386 {
387 }
388
389 void FGCanvasPath::dumpElement()
390 {
391 qDebug() << "Path: at " << _propertyRoot->path();
392 }
393
394 void FGCanvasPath::doPaint(FGCanvasPaintContext *context) const
395 {
396 context->painter()->setPen(_stroke);
397
398 switch (_paintType) {
399 case Rect:
400 context->painter()->drawRect(_rect);
401 break;
402 case RoundRect:
403 context->painter()->drawRoundRect(_rect, _roundRectRadius.width(), _roundRectRadius.height());
404 break;
405
406 case Path:
407 context->painter()->drawPath(_painterPath);
408 break;
409 }
410
411 if (isHighlighted()) {
412 context->painter()->setPen(QPen(Qt::red, 1));
413 context->painter()->setBrush(Qt::NoBrush);
414 switch (_paintType) {
415 case Rect:
416 case RoundRect:
417 context->painter()->drawRect(_rect);
418 break;
419
420 case Path:
421 context->painter()->drawRect(_painterPath.boundingRect());
422 break;
423 }
424 }
425
426 }
427
428 void FGCanvasPath::doPolish()
429 {
430 if (_pathDirty) {
431 rebuildPath();
432 if (_quickPath) {
433 _quickPath->setPath(_painterPath);
434 }
435 _pathDirty = false;
436 }
437
438 if (_penDirty) {
439 rebuildPen();
440 if (_quickPath) {
441 _quickPath->setStroke(_stroke);
442 }
443 _penDirty = false;
444 }
445
446 if (_quickPath) {
447 _quickPath->setFillColor(fillColor());
448 }
449 }
450
451 void FGCanvasPath::markStyleDirty()
452 {
453 _penDirty = true;
454 }
455
456 CanvasItem *FGCanvasPath::createQuickItem(QQuickItem *parent)
457 {
458 _quickPath = new PathQuickItem(parent);
459 _quickPath->setPath(_painterPath);
460 _quickPath->setStroke(_stroke);
461 _quickPath->setAntialiasing(true);
462 return _quickPath;
463 }
464
465 CanvasItem *FGCanvasPath::quickItem() const
466 {
467 return _quickPath;
468 }
469
470 void FGCanvasPath::doDestroy()
471 {
472 delete _quickPath;
473 }
474
475 void FGCanvasPath::markPathDirty()
476 {
477 _pathDirty = true;
478 requestPolish();
479 }
480
481 void FGCanvasPath::markStrokeDirty()
482 {
483 _penDirty = true;
484 requestPolish();
485 }
486
487 bool FGCanvasPath::onChildAdded(LocalProp *prop)
488 {
489 if (FGCanvasElement::onChildAdded(prop)) {
490 return true;
491 }
492
493 if ((prop->name() == "cmd") || (prop->name() == "coord") || (prop->name() == "svg")) {
494 connect(prop, &LocalProp::valueChanged, this, &FGCanvasPath::markPathDirty);
495 return true;
496 }
497
498 if (prop->name() == "rect") {
499 _isRect = true;
500 connect(prop, &LocalProp::childAdded, this, &FGCanvasPath::onChildAdded);
501 return true;
502 }
503
504 // handle rect property changes
505 if (prop->parent()->name() == "rect") {
506 connect(prop, &LocalProp::valueChanged, this, &FGCanvasPath::markPathDirty);
507 return true;
508 }
509
510 if (prop->name().startsWith("border-")) {
511 connect(prop, &LocalProp::valueChanged, this, &FGCanvasPath::markPathDirty);
512 return true;
513 }
514
515 if ((prop->name() == "cmd-geo") || (prop->name() == "coord-geo")) {
516 // ignore for now, we let the server-side transform down to cartesian.
517 // if we move that work to client side we could skip sending the cmd/coord data
518 return true;
519 }
520
521 if (prop->name().startsWith("stroke")) {
522 connect(prop, &LocalProp::valueChanged, this, &FGCanvasPath::markStrokeDirty);
523 return true;
524 }
525
526 qWarning() << "path saw unrecognized child:" << prop->name() << prop->index();
527 return false;
528 }
529
530 bool FGCanvasPath::onChildRemoved(LocalProp* prop)
531 {
532 if (FGCanvasElement::onChildRemoved(prop)) {
533 return true;
534 }
535
536 const auto name = prop->name();
537 if (name == "rect") {
538 _isRect = false;
539 markPathDirty();
540 return true;
541 }
542
543 if ((name == "cmd") || (name == "coord") || (name == "svg")) {
544 markPathDirty();
545 return true;
546 }
547
548 if ((name == "cmd-geo") || (name == "coord-geo")) {
549 // ignored
550 return true;
551 }
552
553 if (name.startsWith("stroke")) {
554 markStrokeDirty();
555 return true;
556 }
557
558 return false;
559 }
560
561 typedef enum
562 {
563 PathClose = ( 0 << 1),
564 PathMoveTo = ( 1 << 1),
565 PathLineTo = ( 2 << 1),
566 PathHLineTo = ( 3 << 1),
567 PathVLineTo = ( 4 << 1),
568 PathQuadTo = ( 5 << 1),
569 PathCubicTo = ( 6 << 1),
570 PathSmoothQuadTo = ( 7 << 1),
571 PathSmoothCubicTo = ( 8 << 1),
572 PathShortCCWArc = ( 9 << 1),
573 PathShortCWArc = (10 << 1),
574 PathLongCCWArc = (11 << 1),
575 PathLongCWArc = (12 << 1)
576 } PathCommands;
577
578 static const quint8 CoordsPerCommand[] = {
579 0, /* VG_CLOSE_PATH */
580 2, /* VG_MOVE_TO */
581 2, /* VG_LINE_TO */
582 1, /* VG_HLINE_TO */
583 1, /* VG_VLINE_TO */
584 4, /* VG_QUAD_TO */
585 6, /* VG_CUBIC_TO */
586 2, /* VG_SQUAD_TO */
587 4, /* VG_SCUBIC_TO */
588 5, /* VG_SCCWARC_TO */
589 5, /* VG_SCWARC_TO */
590 5, /* VG_LCCWARC_TO */
591 5 /* VG_LCWARC_TO */
592 };
593
594 void FGCanvasPath::rebuildPath() const
595 {
596 std::vector<float> coords;
597 std::vector<int> commands;
598
599 if (_isRect) {
600 rebuildFromRect(commands, coords);
601 } else if (_propertyRoot->hasChild("svg")) {
602 if (!rebuildFromSVGData(commands, coords)) {
603 qWarning() << "failed to parse SVG path data" << _propertyRoot->value("svg", QVariant());
604 }
605 } else {
606 for (QVariant v : _propertyRoot->valuesOfChildren("coord")) {
607 coords.push_back(v.toFloat());
608 }
609
610 for (QVariant v : _propertyRoot->valuesOfChildren("cmd")) {
611 commands.push_back(v.toInt());
612 }
613 }
614
615 rebuildPathFromCommands(commands, coords);
616 }
617
618 QByteArrayList splitSVGPathData(QByteArray d)
619 {
620 QByteArrayList result;
621 size_t pos = 0;
622 std::string strData(d.data());
623 const char* seperators = "\n\r\t ,";
624 size_t startPos = strData.find_first_not_of(seperators, 0);
625 for(;;)
626 {
627 pos = strData.find_first_of(seperators, startPos);
628 if (pos == std::string::npos) {
629 result.push_back(QByteArray::fromStdString(strData.substr(startPos)));
630 break;
631 }
632 result.push_back(QByteArray::fromStdString(strData.substr(startPos, pos - startPos)));
633 startPos = strData.find_first_not_of(seperators, pos);
634 if (startPos == std::string::npos) {
635 break;
636 }
637 }
638
639 return result;
640 }
641
642 bool hasComplexBorderRadius(const LocalProp* prop)
643 {
644 for (auto childProp : prop->children()) {
645 QByteArray name = childProp->name();
646 if (!name.startsWith("border-") || !name.endsWith("-radius")) {
647 continue;
648 }
649
650 if (name != "border-radius") {
651 return true;
652 }
653 } // of child prop iteration
654
655 return false;
656 }
657
658 bool FGCanvasPath::rebuildFromRect(std::vector<int>& commands, std::vector<float>& coords) const
659 {
660 LocalProp* rectProp = _propertyRoot->getWithPath("rect");
661 if (hasComplexBorderRadius(_propertyRoot)) {
662 // build a full path
663 qWarning() << Q_FUNC_INFO << "implement me";
664 _paintType = Path;
665 } else {
666 float top = rectProp->value("top", 0.0).toFloat();
667 float left = rectProp->value("left", 0.0).toFloat();
668 float width = rectProp->value("width", 0.0).toFloat();
669 float height = rectProp->value("height", 0.0).toFloat();
670
671 if (rectProp->hasChild("right")) {
672 width = rectProp->value("right", 0.0).toFloat() - left;
673 }
674
675 if (rectProp->hasChild("bottom")) {
676 height = rectProp->value("bottom", 0.0).toFloat() - top;
677 }
678
679 _rect = QRectF(left, top, width, height);
680
681 if (_propertyRoot->hasChild("border-radius")) {
682 // round-rect
683 float xR = _propertyRoot->value("border-radius", 0.0).toFloat();
684 float yR = xR;
685 if (_propertyRoot->hasChild("border-radius[1]")) {
686 yR = _propertyRoot->value("border-radius[1]", 0.0).toFloat();
687 }
688
689 _roundRectRadius = QSizeF(xR, yR);
690 _paintType = RoundRect;
691 } else {
692 // simple rect
693 _paintType = Rect;
694 }
695 }
696
697 return true;
698 }
699
700 bool FGCanvasPath::rebuildFromSVGData(std::vector<int>& commands, std::vector<float>& coords) const
701 {
702 QByteArrayList tokens = splitSVGPathData(_propertyRoot->value("svg", QVariant()).toByteArray());
703 PathCommands currentCommand = PathClose;
704 bool isRelative = false;
705 int numCoordsTokens = 0;
706 const int totalTokens = tokens.size();
707
708 for (int index = 0; index < totalTokens; /* no increment */) {
709 const QByteArray& tk = tokens.at(index);
710 if ((tk.length() == 1) && std::isalpha(tk.at(0))) {
711 // new command token
712 const char svgCommand = std::toupper(tk.at(0));
713 isRelative = std::islower(tk.at(0));
714
715 switch (svgCommand) {
716 case 'Z':
717 currentCommand = PathClose;
718 numCoordsTokens = 0;
719 break;
720 case 'M':
721 currentCommand = PathMoveTo;
722 numCoordsTokens = 2;
723 break;
724 case 'L':
725 currentCommand = PathLineTo;
726 numCoordsTokens = 2;
727 break;
728 case 'H':
729 currentCommand = PathHLineTo;
730 numCoordsTokens = 1;
731 break;
732 case 'V':
733 currentCommand = PathVLineTo;
734 numCoordsTokens = 1;
735 break;
736 case 'C':
737 currentCommand = PathCubicTo;
738 numCoordsTokens = 6;
739 break;
740 case 'S':
741 currentCommand = PathSmoothCubicTo;
742 numCoordsTokens = 4;
743 break;
744 case 'Q':
745 currentCommand = PathQuadTo;
746 numCoordsTokens = 4;
747 break;
748 case 'T':
749 currentCommand = PathSmoothQuadTo;
750 numCoordsTokens = 2;
751 break;
752 case 'A':
753 currentCommand = PathShortCWArc;
754 numCoordsTokens = 0; // handled specially below
755 break;
756 default:
757 qWarning() << "unrecognized SVG command" << svgCommand;
758 return false;
759 }
760 ++index;
761 }
762
763 switch (currentCommand) {
764 case PathMoveTo:
765 commands.push_back(PathMoveTo | (isRelative ? 1 : 0));
766 currentCommand = PathLineTo;
767 break;
768
769 case PathClose:
770 case PathLineTo:
771 case PathHLineTo:
772 case PathVLineTo:
773 case PathQuadTo:
774 case PathCubicTo:
775 case PathSmoothQuadTo:
776 case PathSmoothCubicTo:
777 commands.push_back(currentCommand | (isRelative ? 1 : 0));
778 break;
779
780 case PathShortCWArc:
781 case PathShortCCWArc:
782 case PathLongCWArc:
783 case PathLongCCWArc:
784 {
785 // decode the actual arc type
786 coords.push_back(tokens.at(index++).toFloat()); // rx
787 coords.push_back(tokens.at(index++).toFloat()); // ry
788 coords.push_back(tokens.at(index++).toFloat()); // x-axis rotation
789
790 const bool isLargeArc = (tokens.at(index++).toInt() != 0); // large-angle
791 const bool isCCW = (tokens.at(index++).toInt() != 0); // sweep-flag
792 if (isLargeArc) {
793 commands.push_back(isCCW ? PathLongCCWArc : PathLongCWArc);
794 } else {
795 commands.push_back(isCCW ? PathShortCCWArc : PathShortCWArc);
796 }
797
798 if (isRelative) {
799 commands.back() |= 1;
800 }
801
802 coords.push_back(tokens.at(index++).toFloat());
803 coords.push_back(tokens.at(index++).toFloat());
804 break;
805 }
806
807 default:
808 qWarning() << "invalid path command";
809 return false;
810 } // of current command switch
811
812 // copy over tokens according to the active command.
813 if (index + numCoordsTokens > totalTokens) {
814 qWarning() << "insufficent remaining tokens for SVG command" << currentCommand;
815 qWarning() << index << numCoordsTokens << totalTokens;
816 return false;
817 }
818
819 for (int c = 0; c < numCoordsTokens; ++c) {
820 coords.push_back(tokens.at(index + c).toFloat());
821 }
822
823 index += numCoordsTokens;
824 } // of tokens iteration
825
826 return true;
827 }
828
829 void FGCanvasPath::rebuildPathFromCommands(const std::vector<int>& commands, const std::vector<float>& coords) const
830 {
831 QPainterPath newPath;
832 const float* coord = coords.data();
833 QPointF lastControlPoint; // for smooth cubics / quadric
834 size_t currentCoord = 0;
835
836 for (int cmd : commands) {
837 bool isRelative = cmd & 0x1;
838 const int op = cmd & ~0x1;
839 const int cmdIndex = op >> 1;
840 const qreal baseX = isRelative ? newPath.currentPosition().x() : 0.0f;
841 const qreal baseY = isRelative ? newPath.currentPosition().y() : 0.0f;
842
843 if ((currentCoord + CoordsPerCommand[cmdIndex]) > coords.size()) {
844 qWarning() << "insufficient path data" << currentCoord << cmdIndex << CoordsPerCommand[cmdIndex] << coords.size();
845 break;
846 }
847
848 switch (op) {
849 case PathClose:
850 newPath.closeSubpath();
851 break;
852 case PathMoveTo:
853 newPath.moveTo(coord[0] + baseX, coord[1] + baseY);
854 break;
855 case PathLineTo:
856 newPath.lineTo(coord[0] + baseX, coord[1] + baseY);
857 break;
858 case PathHLineTo:
859 newPath.lineTo(coord[0] + baseX, newPath.currentPosition().y());
860 break;
861 case PathVLineTo:
862 newPath.lineTo(newPath.currentPosition().x(), coord[0] + baseY);
863 break;
864 case PathQuadTo:
865 newPath.quadTo(coord[0] + baseX, coord[1] + baseY,
866 coord[2] + baseX, coord[3] + baseY);
867 lastControlPoint = QPointF(coord[0] + baseX, coord[1] + baseY);
868 break;
869 case PathCubicTo:
870 newPath.cubicTo(coord[0] + baseX, coord[1] + baseY,
871 coord[2] + baseX, coord[3] + baseY,
872 coord[4] + baseX, coord[5] + baseY);
873 lastControlPoint = QPointF(coord[2] + baseX, coord[3] + baseY);
874 break;
875
876 case PathSmoothQuadTo: {
877 QPointF smoothControlPoint = (newPath.currentPosition() - lastControlPoint) * 2.0;
878 newPath.quadTo(smoothControlPoint.x(), smoothControlPoint.y(),
879 coord[0] + baseX, coord[1] + baseY);
880 lastControlPoint = smoothControlPoint;
881 break;
882 }
883
884 case PathSmoothCubicTo: {
885 QPointF smoothControlPoint = (newPath.currentPosition() - lastControlPoint) * 2.0;
886 newPath.cubicTo(smoothControlPoint.x(), smoothControlPoint.y(),
887 coord[0] + baseX, coord[1] + baseY,
888 coord[2] + baseX, coord[3] + baseY);
889 lastControlPoint = QPointF(coord[0] + baseX, coord[1] + baseY);
890 break;
891 }
892
893 #if 0
894 qreal rx,
895 qreal ry,
896 qreal x_axis_rotation,
897 int large_arc_flag,
898 int sweep_flag,
899 qreal x,
900 qreal y,
901 qreal curx, qreal cury)
902 #endif
903 case PathLongCCWArc:
904 case PathLongCWArc:
905 pathArc(newPath, coord[0], coord[1], coord[2],
906 true, (op == PathLongCCWArc),
907 coord[3] + baseX, coord[4] + baseY,
908 newPath.currentPosition().x(), newPath.currentPosition().y());
909 break;
910
911 case PathShortCCWArc:
912 case PathShortCWArc:
913 pathArc(newPath, coord[0], coord[1], coord[2],
914 false, (op == PathShortCCWArc),
915 coord[3] + baseX, coord[4] + baseY,
916 newPath.currentPosition().x(), newPath.currentPosition().y());
917 break;
918
919 default:
920 qWarning() << "uhandled path command type:" << cmdIndex;
921 }
922
923 if ((op < PathQuadTo) || (op > PathSmoothCubicTo)) {
924 lastControlPoint = newPath.currentPosition();
925 }
926
927 coord += CoordsPerCommand[cmdIndex];
928 currentCoord += CoordsPerCommand[cmdIndex];
929 } // of commands iteration
930
931 // qDebug() << _propertyRoot->path() << "path" << newPath;
932 _painterPath = newPath;
933 }
934
935 static Qt::PenCapStyle qtCapFromCanvas(QString s)
936 {
937 if (s.isEmpty() || (s == "butt")) {
938 return Qt::FlatCap;
939 } else if (s == "round") {
940 return Qt::RoundCap;
941 } else if (s == "square") {
942 return Qt::SquareCap;
943 } else {
944 qDebug() << Q_FUNC_INFO << s;
945 }
946 return Qt::FlatCap;
947 }
948
949 static Qt::PenJoinStyle qtJoinFromCanvas(QString s)
950 {
951 if (s.isEmpty() || (s == "miter")) {
952 return Qt::MiterJoin;
953 } else if (s == "round") {
954 return Qt::RoundJoin;
955 } else {
956 qDebug() << Q_FUNC_INFO << s;
957 }
958 return Qt::MiterJoin;
959 }
960
961 static QVector<qreal> qtPenDashesFromCanvas(QString s, double penWidth)
962 {
963 QVector<qreal> result;
964 Q_FOREACH(QString v, s.split(',')) {
965 result.push_back(v.toFloat() / penWidth);
966 }
967
968 // https://developer.mozilla.org/en/docs/Web/SVG/Attribute/stroke-dasharray
969 // odd number = double it
970 if ((result.size() % 2) == 1) {
971 result += result;
972 }
973 return result;
974 }
975
976 void FGCanvasPath::rebuildPen() const
977 {
978 QPen p;
979
980 QVariant strokeColor = getCascadedStyle("stroke");
981 p.setColor(parseColorValue(strokeColor));
982
983 p.setWidthF(getCascadedStyle("stroke-width", 1.0).toFloat());
984 p.setCapStyle(qtCapFromCanvas(_propertyRoot->value("stroke-linecap", QString()).toString()));
985 p.setJoinStyle(qtJoinFromCanvas(_propertyRoot->value("stroke-linejoin", QString()).toString()));
986
987 QString dashArray = _propertyRoot->value("stroke-dasharray", QVariant()).toString();
988 if (!dashArray.isEmpty() && (dashArray != "none")) {
989 p.setDashPattern(qtPenDashesFromCanvas(dashArray, p.widthF()));
990 }
991
992 _stroke = p;
993 }
994
995 #include "fgcanvaspath.moc"