File: SvgCssHelper.cpp

package info (click to toggle)
calligra 1%3A2.4.4-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 290,028 kB
  • sloc: cpp: 1,105,019; xml: 24,940; ansic: 11,807; python: 8,457; perl: 2,792; sh: 1,507; yacc: 1,307; ruby: 1,248; sql: 903; lex: 455; makefile: 89
file content (696 lines) | stat: -rw-r--r-- 20,710 bytes parent folder | download
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
687
688
689
690
691
692
693
694
695
696
/* This file is part of the KDE project
 * Copyright (C) 2009 Jan Hambrecht <jaham@gmx.net>
 *
 * 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 "SvgCssHelper.h"
#include <KoXmlReader.h>
#include <KDebug>
#include <QPair>
#include <QStack>

/// Token types used for tokenizing complex selectors
enum CssTokenType {
    SelectorToken,  ///< a selector token
    CombinatorToken ///< a combinator token
};

/// A token used for tokenizing complex selectors
typedef QPair<CssTokenType, QString> CssToken;

/// Selector base class, merely an interface
class CssSelectorBase
{
public:
    virtual ~CssSelectorBase() {}
    /// Matches the given element
    virtual bool match(const KoXmlElement &) = 0;
    /// Returns string representation of selector
    virtual QString toString() const { return QString(); }
    /**
     * Returns priority of selector
     * see http://www.w3.org/TR/1998/REC-CSS2-19980512/cascade.html#specificity
     */
    virtual int priority() { return 0; }
};

/// Universal selector, matching anything
class UniversalSelector : public CssSelectorBase
{
public:
    virtual bool match(const KoXmlElement &)
    {
        // matches always
        return true;
    }
    virtual QString toString() const
    {
        return "*";
    }
};

/// Type selector, matching the type of an element
class TypeSelector : public CssSelectorBase
{
public:
    TypeSelector(const QString &type)
    : m_type(type)
    {
    }
    virtual bool match(const KoXmlElement &e)
    {
        return e.tagName() == m_type;
    }
    virtual QString toString() const
    {
        return m_type;
    }
    virtual int priority()
    {
        return 1;
    }

private:
    QString m_type;
};

/// Id selectdor, matching the id attribute
class IdSelector : public CssSelectorBase
{
public:
    IdSelector(const QString &id)
    : m_id(id)
    {
        if (id.startsWith('#'))
            m_id = id.mid(1);
    }
    virtual bool match(const KoXmlElement &e)
    {
        return e.attribute("id") == m_id;
    }
    virtual QString toString() const
    {
        return '#'+m_id;
    }
    virtual int priority()
    {
        return 100;
    }
private:
    QString m_id;
};

/// Attribute selector, matching existence or content of attributes
class AttributeSelector : public CssSelectorBase
{
public:
    AttributeSelector(const QString &attribute)
    : m_type(Unknown)
    {
        QString pattern = attribute;
        if (pattern.startsWith('['))
            pattern.remove(0,1);
        if (pattern.endsWith(']'))
            pattern.remove(pattern.length()-1,1);
        int equalPos = pattern.indexOf('=');
        if (equalPos == -1) {
            m_type = Exists;
            m_attribute = pattern;
        } else if (equalPos > 0){
            if (pattern[equalPos-1] == '~') {
                m_attribute = pattern.left(equalPos-1);
                m_type = InList;
            } else if(pattern[equalPos-1] == '|') {
                m_attribute = pattern.left(equalPos-1) + '-';
                m_type = StartsWith;
            } else {
                m_attribute = pattern.left(equalPos);
                m_type = Equals;
            }
            m_value = pattern.mid(equalPos+1);
            if (m_value.startsWith('\"'))
                m_value.remove(0,1);
            if (m_value.endsWith('\"'))
                m_value.remove(m_value.length()-1,1);
        }
    }

    virtual bool match(const KoXmlElement &e)
    {
        switch(m_type) {
            case Exists:
                return e.hasAttribute(m_attribute);
                break;
            case Equals:
                return e.attribute(m_attribute) == m_value;
                break;
            case InList:
                {
                    QStringList tokens = e.attribute(m_attribute).split(' ', QString::SkipEmptyParts);
                    return tokens.contains(m_value);
                }
                break;
            case StartsWith:
                return e.attribute(m_attribute).startsWith(m_value);
                break;
            default:
                return false;
        }
    }
    virtual QString toString() const
    {
        QString str('[');
        str += m_attribute;
        if (m_type == Equals) {
            str += '=';
        } else if (m_type == InList) {
            str += "~=";
        } else if (m_type == StartsWith) {
            str += "|=";
        }
        str += m_value;
        str += ']';
        return str;
    }
    virtual int priority()
    {
        return 10;
    }

private:
    enum MatchType {
        Unknown,   ///< unknown    -> error state
        Exists,    ///< [att]      -> attribute exists
        Equals,    ///< [att=val]  -> attribute value matches exactly val
        InList,    ///< [att~=val] -> attribute is whitespace separated list where one is val
        StartsWith ///< [att|=val] -> attribute starts with val-
    };
    QString m_attribute;
    QString m_value;
    MatchType m_type;
};

/// Pseudo-class selector
class PseudoClassSelector : public CssSelectorBase
{
public:
    PseudoClassSelector(const QString &pseudoClass)
    : m_pseudoClass(pseudoClass)
    {
    }

    virtual bool match(const KoXmlElement &e)
    {
        if (m_pseudoClass == ":first-child") {
            KoXmlNode parent = e.parentNode();
            if (parent.isNull()) {
                return false;
            }
            KoXmlNode firstChild = parent.firstChild();
            while(!firstChild.isElement() || firstChild.isNull()) {
                firstChild = firstChild.nextSibling();
            }
            return firstChild == e;
        } else {
            return false;
        }
    }
    virtual QString toString() const
    {
        return m_pseudoClass;
    }
    virtual int priority()
    {
        return 10;
    }

private:
    QString m_pseudoClass;
};

/// A simple selector, i.e. a type/universal selector followed by attribute, id or pseudo-class selectors
class CssSimpleSelector : public CssSelectorBase
{
public:
    CssSimpleSelector(const QString &token)
    : m_token(token)
    {
        compile();
    }
    virtual ~CssSimpleSelector()
    {
        qDeleteAll(m_selectors);
    }

    virtual bool match(const KoXmlElement &e)
    {
        foreach(CssSelectorBase *s, m_selectors) {
            if (!s->match(e))
                return false;
        }

        return true;
    }

    QString toString() const
    {
        QString str;
        foreach(CssSelectorBase *s, m_selectors) {
            str += s->toString();
        }
        return str;
    }
    virtual int priority()
    {
        int p = 0;
        foreach(CssSelectorBase *s, m_selectors) {
            p += s->priority();
        }
        return p;
    }

private:
    void compile()
    {
        if (m_token == "*") {
            m_selectors.append(new UniversalSelector());
            return;
        }

        enum {
            Start,
            Finish,
            Bad,
            InType,
            InId,
            InAttribute,
            InClassAttribute,
            InPseudoClass,
        } state;

        // add terminator to string
        QString expr = m_token + QChar();
        QChar ch;
        int i = 0;
        state = Start;

        QString token;
        QString sep("#[:.");
        // split into base selectors
        while((state != Finish) && (state != Bad) && (i < expr.length())) {
            QChar ch = expr[i];
            switch(state) {
                case Start:
                    token += ch;
                    if (ch == '#')
                        state = InId;
                    else if (ch == '[')
                        state = InAttribute;
                    else if (ch == ':')
                        state = InPseudoClass;
                    else if (ch == '.')
                        state = InClassAttribute;
                    else if (ch != '*')
                        state = InType;
                    break;
                case InAttribute:
                    if (ch.isNull()) {
                        // reset state and token string
                        state = Finish;
                        token.clear();
                        continue;
                    } else {
                        token += ch;
                        if (ch == ']') {
                            m_selectors.append(new AttributeSelector(token));
                            state = Start;
                            token.clear();
                        }
                    }
                    break;
                case InType:
                case InId:
                case InClassAttribute:
                case InPseudoClass:
                    // are we at the start of the next selector or even finished?
                    if (sep.contains(ch) || ch.isNull()) {
                        if (state == InType)
                            m_selectors.append(new TypeSelector(token));
                        else if (state == InId)
                            m_selectors.append(new IdSelector(token));
                        else if ( state == InClassAttribute)
                            m_selectors.append(new AttributeSelector("[class~="+token.mid(1)+']'));
                        else if (state == InPseudoClass) {
                            m_selectors.append(new PseudoClassSelector(token));
                        }
                        // reset state and token string
                        state = ch.isNull() ? Finish : Start;
                        token.clear();
                        continue;
                    } else {
                        // append character to current token
                        if (!ch.isNull())
                            token += ch;
                    }
                    break;
                case Bad:
                default:
                    break;
            }
            i++;
        }
    }

    QList<CssSelectorBase*> m_selectors;
    QString m_token;
};

/// Complex selector, i.e. a combination of simple selectors
class CssComplexSelector : public CssSelectorBase
{
public:
    CssComplexSelector(const QList<CssToken> &tokens)
    {
        compile(tokens);
    }
    virtual ~CssComplexSelector()
    {
        qDeleteAll(m_selectors);
    }
    QString toString() const
    {
        QString str;
        int selectorCount = m_selectors.count();
        if (selectorCount) {
            for(int i = 0; i < selectorCount-1; ++i) {
                str += m_selectors[i]->toString();
                str += m_combinators[i];
            }
            str += m_selectors.last()->toString();
        }
        return str;
    }

    virtual bool match(const KoXmlElement &e)
    {
        int selectorCount = m_selectors.count();
        int combinatorCount = m_combinators.length();
        // check count of selectors and combinators
        if (selectorCount-combinatorCount != 1)
            return false;

        KoXmlElement currentElement = e;

        // match in reverse order
        for(int i = 0; i < selectorCount; ++i) {
            CssSelectorBase * curr = m_selectors[selectorCount-1-i];
            if (!curr->match(currentElement)) {
                return false;
            }
            // last selector and still there -> rule matched completely
            if(i == selectorCount-1)
                return true;

            CssSelectorBase * next = m_selectors[selectorCount-1-i-1];
            QChar combinator = m_combinators[combinatorCount-1-i];
            if (combinator == ' ') {
                bool matched = false;
                // descendant combinator
                KoXmlNode parent = currentElement.parentNode();
                while(!parent.isNull()) {
                    currentElement = parent.toElement();
                    if (next->match(currentElement)) {
                        matched = true;
                        break;
                    }
                    parent = currentElement.parentNode();
                }
                if(!matched)
                    return false;
            } else if (combinator == '>') {
                // child selector
                KoXmlNode parent = currentElement.parentNode();
                if (parent.isNull())
                    return false;
                KoXmlElement parentElement = parent.toElement();
                if (next->match(parentElement)) {
                    currentElement = parentElement;
                } else {
                    return false;
                }
            } else if (combinator == '+') {
                KoXmlNode neighbor = currentElement.previousSibling();
                while(!neighbor.isNull() && !neighbor.isElement())
                    neighbor = neighbor.previousSibling();
                if (neighbor.isNull() || !neighbor.isElement())
                    return false;
                KoXmlElement neighborElement = neighbor.toElement();
                if (next->match(neighborElement)) {
                    currentElement = neighborElement;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
    virtual int priority()
    {
        int p = 0;
        foreach(CssSelectorBase *s, m_selectors) {
            p += s->priority();
        }
        return p;
    }

private:
    void compile(const QList<CssToken> &tokens)
    {
        foreach(const CssToken &token, tokens) {
            if(token.first == SelectorToken) {
                m_selectors.append(new CssSimpleSelector(token.second));
            } else {
                m_combinators += token.second;
            }
        }
    }

    QString m_combinators;
    QList<CssSelectorBase*> m_selectors;
};

/// A group of selectors (comma separated in css style sheet)
typedef QList<CssSelectorBase*> SelectorGroup;
/// A css rule consisting of group of selectors corresponding to a style
typedef QPair<SelectorGroup, QString> CssRule;

class SvgCssHelper::Private
{
public:
    ~Private()
    {
        foreach(const CssRule &rule, cssRules) {
            qDeleteAll(rule.first);
        }
    }

    SelectorGroup parsePattern(const QString &pattern)
    {
        SelectorGroup group;

        QStringList selectors = pattern.split(',', QString::SkipEmptyParts);
        for (int i = 0; i < selectors.count(); ++i ) {
            CssSelectorBase * selector = compileSelector(selectors[i].simplified());
            if (selector)
                group.append(selector);
        }
        return group;
    }

    QList<CssToken> tokenize(const QString &selector)
    {
        // add terminator to string
        QString expr = selector + QChar();
        QChar lastCh;
        enum {
            Finish,
            Bad,
            InCombinator,
            InSelector
        } state;

        QChar combinator;
        int selectorStart = 0;

        QList<CssToken> tokenList;

        QChar ch = expr[0];
        if (ch.isSpace() || ch == '>' || ch == '+') {
            kWarning(30514) << "selector starting with combinator is not allowed:" << selector;
            return tokenList;
        } else {
            state = InSelector;
            selectorStart = 0;
        }
        int i = 1;

        // split into simple selectors and combinators
        while((state != Finish) && (state != Bad) && (i < expr.length())) {
            QChar ch = expr[i];
            switch(state) {
                case InCombinator:
                    // consume as long as there a combinator characters
                    if( ch == '>' || ch == '+') {
                        if( ! combinator.isSpace() ) {
                            // two non whitespace combinators in sequence are not allowed
                            state = Bad;
                        } else {
                            // switch combinator
                            combinator = ch;
                        }
                    } else if (!ch.isSpace()) {
                        tokenList.append(CssToken(CombinatorToken, combinator));
                        state = InSelector;
                        selectorStart = i;
                        combinator = QChar();
                    }
                    break;
                case InSelector:
                    // consume as long as there a non combinator characters
                    if (ch.isSpace() || ch == '>' || ch == '+') {
                        state = InCombinator;
                        combinator = ch;
                    } else if (ch.isNull()) {
                        state = Finish;
                    }
                    if (state != InSelector) {
                        QString simpleSelector = selector.mid(selectorStart, i-selectorStart);
                        tokenList.append(CssToken(SelectorToken, simpleSelector));
                    }
                    break;
                case Bad:
                default:
                    break;
            }
            i++;
        }

        return tokenList;
    }

    CssSelectorBase * compileSelector(const QString &selector)
    {
        QList<CssToken> tokenList = tokenize(selector);
        if (tokenList.isEmpty())
            return 0;

        if (tokenList.count() == 1) {
            // simple selector
            return new CssSimpleSelector(tokenList.first().second);
        } else if (tokenList.count() > 2) {
            // complex selector
            return new CssComplexSelector(tokenList);
        }
        return 0;
    }

    QMap<QString, QString> cssStyles;
    QList<CssRule> cssRules;
};

SvgCssHelper::SvgCssHelper()
: d(new Private())
{
}

SvgCssHelper::~SvgCssHelper()
{
    delete d;
}

void SvgCssHelper::parseStylesheet(const KoXmlElement &e)
{
    QString data;

    if (e.hasChildNodes()) {
        KoXmlNode c = e.firstChild();
        if (c.isCDATASection()) {
            KoXmlCDATASection cdata = c.toCDATASection();
            data = cdata.data().simplified();
        } else if (c.isText()) {
            KoXmlText text = c.toText();
            data = text.data().simplified();
        }
    }
    if (data.isEmpty())
        return;

    // remove comments
    QRegExp commentExp("\\/\\*.*\\*\\/");
    commentExp.setMinimal(true); // do not match greedy
    data.remove(commentExp);

    QStringList defs = data.split('}', QString::SkipEmptyParts);
    for (int i = 0; i < defs.count(); ++i) {
        QStringList def = defs[i].split('{');
        if( def.count() != 2 )
            continue;
        QString pattern = def[0].simplified();
        if (pattern.isEmpty())
            break;
        QString style = def[1].simplified();
        if (style.isEmpty())
            break;
        QStringList selectors = pattern.split(',', QString::SkipEmptyParts);
        for (int i = 0; i < selectors.count(); ++i ) {
            QString selector = selectors[i].simplified();
            d->cssStyles[selector] = style;
        }
        SelectorGroup group = d->parsePattern(pattern);
        d->cssRules.append(CssRule(group, style));
    }
}

QStringList SvgCssHelper::matchStyles(const KoXmlElement &element) const
{
    QMap<int, QString> prioritizedRules;
    // match rules to element
    foreach(const CssRule &rule, d->cssRules) {
        foreach(CssSelectorBase *s, rule.first) {
            bool matched = s->match(element);
            if (matched)
                prioritizedRules[s->priority()] = rule.second;
        }
    }

    // css style attribute has the priority of 100
    QString styleAttribute = element.attribute("style").simplified();
    if (!styleAttribute.isEmpty())
        prioritizedRules[100] = styleAttribute;

    QStringList cssStyles;
    // add matching styles in correct order to style list
    QMapIterator<int, QString> it(prioritizedRules);
    while (it.hasNext()) {
        it.next();
        cssStyles.append(it.value());
    }

    return cssStyles;
}