FreeCAD

Форк
0
/
QGISVGTemplate.cpp 
238 строк · 8.6 Кб
1
/***************************************************************************
2
 *   Copyright (c) 2012-2014 Luke Parry <l.parry@warwick.ac.uk>            *
3
 *                                                                         *
4
 *   This file is part of the FreeCAD CAx development system.              *
5
 *                                                                         *
6
 *   This library is free software; you can redistribute it and/or         *
7
 *   modify it under the terms of the GNU Library General Public           *
8
 *   License as published by the Free Software Foundation; either          *
9
 *   version 2 of the License, or (at your option) any later version.      *
10
 *                                                                         *
11
 *   This library  is distributed in the hope that it will be useful,      *
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14
 *   GNU Library General Public License for more details.                  *
15
 *                                                                         *
16
 *   You should have received a copy of the GNU Library General Public     *
17
 *   License along with this library; see the file COPYING.LIB. If not,    *
18
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
19
 *   Suite 330, Boston, MA  02111-1307, USA                                *
20
 *                                                                         *
21
 ***************************************************************************/
22

23
#include "PreCompiled.h"
24
#ifndef _PreComp_
25
# include <QDomDocument>
26
# include <QFile>
27
# include <QGraphicsColorizeEffect>
28
# include <QGraphicsEffect>
29
# include <QGraphicsSvgItem>
30
# include <QPen>
31
# include <QSvgRenderer>
32
# include <QRegularExpression>
33
# include <QRegularExpressionMatch>
34
#endif// #ifndef _PreComp_
35

36
#include <App/Application.h>
37
#include <Base/Console.h>
38
#include <Base/Parameter.h>
39
#include <Base/Tools.h>
40

41
#include <Mod/TechDraw/App/DrawSVGTemplate.h>
42
#include <Mod/TechDraw/App/DrawUtil.h>
43
#include <Mod/TechDraw/App/XMLQuery.h>
44

45
#include "QGISVGTemplate.h"
46
#include "PreferencesGui.h"
47
#include "QGSPage.h"
48
#include "Rez.h"
49
#include "TemplateTextField.h"
50
#include "ZVALUE.h"
51

52

53
using namespace TechDrawGui;
54
using namespace TechDraw;
55

56
QGISVGTemplate::QGISVGTemplate(QGSPage* scene) : QGITemplate(scene), firstTime(true)
57
{
58

59
    m_svgItem = new QGraphicsSvgItem(this);
60
    m_svgRender = new QSvgRenderer();
61

62
    m_svgItem->setSharedRenderer(m_svgRender);
63

64
    m_svgItem->setFlags(QGraphicsItem::ItemClipsToShape);
65
    m_svgItem->setCacheMode(QGraphicsItem::NoCache);
66

67
    addToGroup(m_svgItem);
68

69
    m_svgItem->setZValue(ZVALUE::SVGTEMPLATE);
70
    setZValue(ZVALUE::SVGTEMPLATE);
71
}
72

73
QGISVGTemplate::~QGISVGTemplate() { delete m_svgRender; }
74

75
void QGISVGTemplate::openFile(const QFile& file) { Q_UNUSED(file); }
76

77
void QGISVGTemplate::load(const QByteArray& svgCode)
78
{
79
    m_svgRender->load(svgCode);
80

81
    QSize size = m_svgRender->defaultSize();
82
    m_svgItem->setSharedRenderer(m_svgRender);
83

84
    if (firstTime) {
85
        createClickHandles();
86
        firstTime = false;
87
    }
88

89
    //convert from pixels or mm or inches in svg file to mm page size
90
    TechDraw::DrawSVGTemplate* tmplte = getSVGTemplate();
91
    double xaspect, yaspect;
92
    xaspect = tmplte->getWidth() / static_cast<double>(size.width());
93
    yaspect = tmplte->getHeight() / static_cast<double>(size.height());
94

95
    QTransform qtrans;
96
    qtrans.translate(0.0, Rez::guiX(-tmplte->getHeight()));
97
    qtrans.scale(Rez::guiX(xaspect), Rez::guiX(yaspect));
98
    m_svgItem->setTransform(qtrans);
99

100
    if (Preferences::lightOnDark()) {
101
        QColor color = PreferencesGui::getAccessibleQColor(QColor(Qt::black));
102
        QGraphicsColorizeEffect* colorizeEffect = new QGraphicsColorizeEffect();
103
        colorizeEffect->setColor(color);
104
        m_svgItem->setGraphicsEffect(colorizeEffect);
105
    }
106
    else {
107
        //remove and delete any existing graphics effect
108
        if (m_svgItem->graphicsEffect()) {
109
            m_svgItem->setGraphicsEffect(nullptr);
110
        }
111
    }
112
}
113

114
TechDraw::DrawSVGTemplate* QGISVGTemplate::getSVGTemplate()
115
{
116
    if (pageTemplate && pageTemplate->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) {
117
        return static_cast<TechDraw::DrawSVGTemplate*>(pageTemplate);
118
    }
119
    else {
120
        return nullptr;
121
    }
122
}
123

124
void QGISVGTemplate::draw()
125
{
126
    TechDraw::DrawSVGTemplate* tmplte = getSVGTemplate();
127
    if (!tmplte) {
128
        throw Base::RuntimeError("Template Feature not set for QGISVGTemplate");
129
    }
130
    QString templateSvg = tmplte->processTemplate();
131
    load(templateSvg.toUtf8());
132
}
133

134
void QGISVGTemplate::updateView(bool update)
135
{
136
    Q_UNUSED(update);
137
    draw();
138
}
139

140
void QGISVGTemplate::createClickHandles()
141
{
142
    TechDraw::DrawSVGTemplate* svgTemplate = getSVGTemplate();
143
    if (svgTemplate->isRestoring()) {
144
        //the embedded file is not available yet, so just return
145
        return;
146
    }
147

148
    QString templateFilename(QString::fromUtf8(svgTemplate->PageResult.getValue()));
149

150
    if (templateFilename.isEmpty()) {
151
        return;
152
    }
153

154
    QFile file(templateFilename);
155
    if (!file.open(QIODevice::ReadOnly)) {
156
        Base::Console().Error(
157
            "QGISVGTemplate::createClickHandles - error opening template file %s\n",
158
            svgTemplate->PageResult.getValue());
159
        return;
160
    }
161

162
    QDomDocument templateDocument;
163
    if (!templateDocument.setContent(&file)) {
164
        Base::Console().Message("QGISVGTemplate::createClickHandles - xml loading error\n");
165
        return;
166
    }
167
    file.close();
168

169
    //TODO: Find location of special fields (first/third angle) and make graphics items for them
170

171
    double editClickBoxSize = Rez::guiX(PreferencesGui::templateClickBoxSize());
172
    QColor editClickBoxColor = PreferencesGui::templateClickBoxColor();
173

174
    auto textMap = svgTemplate->EditableTexts.getValues();
175

176
    TechDraw::XMLQuery query(templateDocument);
177

178
    // XPath query to select all <text> nodes with "freecad:editable" attribute
179
    query.processItems(QString::fromUtf8("declare default element namespace \"" SVG_NS_URI "\"; "
180
                                         "declare namespace freecad=\"" FREECAD_SVG_NS_URI "\"; "
181
                                         "//text[@" FREECAD_ATTR_EDITABLE "]"),
182
                       [&](QDomElement& textElement) -> bool {
183
        QString name = textElement.attribute(QString::fromUtf8(FREECAD_ATTR_EDITABLE));
184
        double x = Rez::guiX(
185
            textElement.attribute(QString::fromUtf8("x"), QString::fromUtf8("0.0")).toDouble());
186
        double y = Rez::guiX(
187
            textElement.attribute(QString::fromUtf8("y"), QString::fromUtf8("0.0")).toDouble());
188
        if (name.isEmpty()) {
189
            Base::Console().Warning(
190
                "QGISVGTemplate::createClickHandles - no name for editable text at %f, %f\n", x, y);
191
            return true;
192
        }
193
        std::string itemText = textMap[Base::Tools::toStdString(name)];
194

195
        // default box size
196
        double textHeight = editClickBoxSize;
197
        double charWidth = textHeight * 0.6;
198
        QString style = textElement.attribute(QString::fromUtf8("style"));
199
        if (!style.isEmpty()) {
200
            QRegularExpression rxFontSize(QString::fromUtf8("font-size:([0-9]*\\.?[0-9]*)px;"));
201
            QRegularExpression rxAnchor(QString::fromUtf8("text-anchor:(middle);"));
202
            QRegularExpressionMatch match;
203

204
            int pos{0};
205
            pos = style.indexOf(rxFontSize, pos, &match);
206
            if (pos != -1) {
207
                textHeight = match.captured(1).toDouble() * 10.0;
208
            }
209
            charWidth = textHeight * 0.6;
210
            pos = 0;
211
            pos = style.indexOf(rxAnchor, pos, &match);
212
            if (pos != -1) {
213
                x = x - itemText.length() * charWidth / 2;
214
            }
215
        }
216
        double textLength = itemText.length() * charWidth;
217
        textLength = std::max(charWidth, textLength);
218
        auto item(new TemplateTextField(this, svgTemplate, name.toStdString()));
219

220
        double pad = 1.0;
221
        double top = Rez::guiX(-svgTemplate->getHeight()) + y - textHeight - pad;
222
        double bottom = top + textHeight + 2.0 * pad;
223
        double left = x - pad;
224
        item->setRectangle(QRectF(left, top,
225
                      textLength + 2.0 * pad, textHeight + 2.0 * pad));
226
        item->setLine(QPointF( left, bottom),
227
                      QPointF(left + textLength + 2.0 * pad, bottom));
228
        item->setLineColor(editClickBoxColor);
229

230
        item->setZValue(ZVALUE::SVGTEMPLATE + 1);
231
        addToGroup(item);
232

233
        textFields.push_back(item);
234
        return true;
235
    });
236
}
237

238
#include <Mod/TechDraw/Gui/moc_QGISVGTemplate.cpp>
239

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.