Merge pull request #1324 from bhangart/fix/dxf-wrapped-text

Export wrapped texts to DXF line by line
This commit is contained in:
Laurent Trinques
2026-10-06 16:25:53 +02:00
committed by GitHub
6 changed files with 335 additions and 1 deletions
+3 -1
View File
@@ -35,6 +35,7 @@
#include "qetgraphicsitem/independenttextitem.h"
#include "qetgraphicsitem/qetshapeitem.h"
#include "qetgraphicsitem/terminal.h"
#include "textlines.h"
#include <QGraphicsSimpleTextItem>
#include <QSet>
@@ -358,7 +359,8 @@ void DxfExport::write(Diagram *diagram, int width, int height,
qreal y = dti->scenePos().y()
- ydir * fontSize * 1.8
- xdir * fontSize * 0.9;
QStringList lines = dti -> toPlainText().split('\n');
//As drawn: a text with a width is wrapped
QStringList lines = TextLines::layoutLines(dti -> document());
qreal offset = fontSize * 1.6;
foreach (QString line, lines) {
if (line.size() > 0 && line != "_" )
+79
View File
@@ -0,0 +1,79 @@
/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TEXTLINES_H
#define TEXTLINES_H
#include <QStringList>
#include <QTextBlock>
#include <QTextDocument>
#include <QTextLayout>
namespace TextLines
{
/**
@return the lines of document as they are laid out: a paragraph
wrapped to the width of the text gives several lines. For the
exports that write a text line by line (DXF).
A paragraph that is not wrapped gives exactly its line of
toPlainText().split('\n'), as these exports wrote before: trailing
spaces are kept, and non-breaking spaces become plain spaces. In a
wrapped paragraph, the lines lose their trailing spaces (the one a
line was broken at, and a line made only of spaces becomes empty).
*/
inline QStringList layoutLines(const QTextDocument *document)
{
document->size(); //Lay the document out
QStringList lines;
for (QTextBlock block = document->begin() ; block.isValid() ; block = block.next())
{
const QString text = block.text();
const QTextLayout *layout = block.layout();
const int count = layout ? layout->lineCount() : 0;
if (count == 0) {
lines << QString(text).replace(QChar::Nbsp, QLatin1Char(' '));
continue;
}
//Wrapped: a line ends without a line break typed by the user
bool wrapped = false;
for (int i = 0 ; i < count - 1 ; ++i) {
const QTextLine line = layout->lineAt(i);
const int end = line.textStart() + line.textLength();
if (end == 0 || text.at(end - 1) != QChar::LineSeparator)
wrapped = true;
}
for (int i = 0 ; i < count ; ++i)
{
const QTextLine line = layout->lineAt(i);
QString part = text.mid(line.textStart(), line.textLength());
if (part.endsWith(QChar::LineSeparator))
part.chop(1); //A line break typed by the user (Shift+Enter)
if (wrapped) {
while (!part.isEmpty() && part.back().isSpace())
part.chop(1);
}
lines << part.replace(QChar::Nbsp, QLatin1Char(' '));
}
}
return lines;
}
}
#endif // TEXTLINES_H
+18
View File
@@ -104,6 +104,14 @@ add_test(NAME tst_textgrid COMMAND tst_textgrid)
target_include_directories(tst_textgrid PRIVATE ${QET_DIR}/sources)
target_link_libraries(tst_textgrid PRIVATE Qt::Test)
# textlines.h is header-only: the lines of a text as they are laid out,
# for the exports that write a text line by line.
add_executable(tst_textlines tst_textlines.cpp)
add_test(NAME tst_textlines COMMAND tst_textlines)
set_tests_properties(tst_textlines PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
target_include_directories(tst_textlines PRIVATE ${QET_DIR}/sources)
target_link_libraries(tst_textlines PRIVATE Qt::Test Qt::Gui)
# elementviewgrid.h is header-only: the symbol editor's snap step at each
# zoom (bugtracker #112), tested without an editor window.
add_executable(tst_elementviewgrid tst_elementviewgrid.cpp)
@@ -427,6 +435,16 @@ target_compile_definitions(tst_wiringlistexport PRIVATE
"QET_TEST_BINARY_PATH=\"$<TARGET_FILE:qelectrotech>\""
"QET_EXAMPLES_DIR=\"${QET_DIR}/examples\"")
# --export-dxf writes a wrapped symbol text line by line, as it is drawn.
add_executable(
tst_dxfwrappedtext
tst_dxfwrappedtext.cpp)
add_test(NAME tst_dxfwrappedtext COMMAND tst_dxfwrappedtext)
add_dependencies(tst_dxfwrappedtext qelectrotech)
target_link_libraries(tst_dxfwrappedtext PRIVATE Qt::Test)
target_compile_definitions(tst_dxfwrappedtext PRIVATE
"QET_TEST_BINARY_PATH=\"$<TARGET_FILE:qelectrotech>\"")
# --export-pdf puts an A3 folio on an A3 page whichever way it is turned:
# QPageSize matches standard sheets upright only, so a wide folio is matched
# upright and turned. fixtures/pdf_page_a3.qet has one folio each way.
@@ -0,0 +1,60 @@
<project title="DXF wrapped texts" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7b10}" version="0.200.1">
<properties>
<property name="saveddate" show="1">10/2/26</property>
<property name="saveddate-eu" show="1">02-10-2026</property>
<property name="saveddate-us" show="1">2026-10-02</property>
<property name="savedfilename" show="1">dxf_wrapped_text</property>
<property name="savedtime" show="1">18:39</property>
</properties>
<usage enabled="true" time_spent="0"/>
<newdiagrams>
<border cols="17" colsize="60" displaycols="true" displayrows="true" rows="8" rowsize="80"/>
<inset author="" auto_page_num="" date="null" displayAt="bottom" filename="" folio="" indexrev="" locmach="" plant="" title="" version=""/>
<conductors bicolor="false" bus="" cable="" color2="#000000" condsize="1" conductor_color="" conductor_section="" dash-size="1" displaytext="1" formula="" function="" horizontal-alignment="AlignBottom" horizrotatetext="0" num="_" numsize="7" onetextperfolio="0" tension_protocol="" text_color="#000000" type="multi" vertical-alignment="AlignRight" vertirotatetext="270"/>
<report label="%f-%l%c"/>
<xrefs>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="coil" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="commutator" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="plc" xrefpos="AlignBottom"/>
<xref delayprefix="" displayhas="cross" master_label="%f-%l%c" offset="0" powerprefix="" showallconfiguredslaves="false" showpowerctc="true" showterminalname="true" slave_label="(%f-%l%c)" slave_offset="0" snapto="label" switchprefix="" type="protection" xrefpos="AlignBottom"/>
</xrefs>
<conductors_autonums auto_break_conductors="false" current_autonum="" freeze_new_conductors="false"/>
<folio_autonums/>
<element_autonums current_autonum="" freeze_new_elements="false"/>
<guides/>
</newdiagrams>
<diagram author="" auto_page_num="" cols="17" colsize="60" date="null" displayAt="bottom" displaycols="true" displayrows="true" filename="" folio="" freezeNewConductor="false" freezeNewElement="false" height="660" indexrev="" locmach="" order="1" plant="" rows="8" rowsize="80" title="" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7a01}" version="0.200.1-dev">
<defaultconductor bicolor="false" bus="" cable="" color2="#000000" condsize="1" conductor_color="" conductor_section="" dash-size="1" displaytext="1" formula="" function="" horizontal-alignment="AlignBottom" horizrotatetext="0" num="_" numsize="7" onetextperfolio="0" tension_protocol="" text_color="#000000" type="multi" vertical-alignment="AlignRight" vertirotatetext="270"/>
<elements>
<element freezeLabel="false" is_movable="1" orientation="0" prefix="" type="embed://import/wrap.elmt" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7a02}" x="300" y="300" z="10">
<terminals/>
<inputs/>
<dynamic_texts>
<dynamic_elmt_text Halignment="AlignLeft" Valignment="AlignTop" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" frame="false" keep_visual_rotation="true" rotation="0" rotation_point_center="false" text_from="UserText" text_width="70" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7b01}" x="0" y="10"><text>WrapAlpha WrapBeta WrapGamma WrapDelta WrapEpsilon</text></dynamic_elmt_text>
<dynamic_elmt_text Halignment="AlignLeft" Valignment="AlignTop" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" frame="false" keep_visual_rotation="true" rotation="0" rotation_point_center="false" text_from="UserText" text_width="-1" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7b02}" x="0" y="60"><text>LineAlpha LineBeta LineGamma LineDelta LineEpsilon</text></dynamic_elmt_text>
</dynamic_texts>
<texts_groups/>
</element>
</elements>
</diagram>
<collection>
<category name="import">
<names>
<name lang="en">Imported elements</name>
</names>
<element name="wrap.elmt">
<definition height="80" hotspot_x="10" hotspot_y="10" link_type="simple" type="element" version="0.100.0" width="120">
<uuid uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7a05}"/>
<names>
<name lang="en">Wrapped symbol text</name>
</names>
<description>
<line antialias="false" end1="none" end2="none" length1="1.5" length2="1.5" style="line-style:normal;line-weight:normal;filling:none;color:black" x1="0" x2="10" y1="0" y2="0"/>
<dynamic_text Halignment="AlignLeft" Valignment="AlignTop" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" frame="false" keep_visual_rotation="true" rotation="0" z="2" text_from="UserText" text_width="70" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7b01}" x="0" y="10"><text>WrapAlpha WrapBeta WrapGamma WrapDelta WrapEpsilon</text></dynamic_text>
<dynamic_text Halignment="AlignLeft" Valignment="AlignTop" font="Liberation Sans,9,-1,5,50,0,0,0,0,0,Regular" frame="false" keep_visual_rotation="true" rotation="0" z="3" text_from="UserText" text_width="-1" uuid="{5b0f5e1c-8a43-4c1e-9e57-3f0d0f0a7b02}" x="0" y="60"><text>LineAlpha LineBeta LineGamma LineDelta LineEpsilon</text></dynamic_text>
</description>
</definition>
</element>
</category>
</collection>
</project>
+60
View File
@@ -0,0 +1,60 @@
/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtTest>
#include <QProcess>
#include <QTemporaryDir>
/**
--export-dxf writes a symbol text wrapped to its width line by line,
as it is drawn, rather than as one long line. A text without a width
is still written on one line.
*/
class tst_dxfwrappedtext : public QObject
{
Q_OBJECT
private slots:
void wrappedLines()
{
const QString project = QFINDTESTDATA("fixtures/dxf_wrapped_text.qet");
QVERIFY2(!project.isEmpty(), "fixture project not found");
QTemporaryDir dir;
QVERIFY(dir.isValid());
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert(QStringLiteral("QT_QPA_PLATFORM"), QStringLiteral("offscreen"));
QProcess proc;
proc.setProcessEnvironment(env);
proc.start(QStringLiteral(QET_TEST_BINARY_PATH), {QStringLiteral("--export-dxf"), project, dir.path()});
QVERIFY2(proc.waitForFinished(60000), "--export-dxf timed out");
QCOMPARE(proc.exitCode(), 0);
QFile file(dir.filePath(QStringLiteral("01_diagram.dxf")));
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
const QStringList values = QString::fromUtf8(file.readAll()).split(QLatin1Char('\n'));
//One text entity per word of the text 70 px wide...
for (const QString &word : {QStringLiteral("WrapAlpha"), QStringLiteral("WrapGamma"), QStringLiteral("WrapEpsilon")})
QVERIFY2(values.contains(word), qPrintable(word));
//...one for the whole text without a width
QVERIFY(values.contains(QStringLiteral("LineAlpha LineBeta LineGamma LineDelta LineEpsilon")));
}
};
QTEST_APPLESS_MAIN(tst_dxfwrappedtext)
#include "tst_dxfwrappedtext.moc"
+115
View File
@@ -0,0 +1,115 @@
/*
Copyright 2006-2026 The QElectroTech Team
This file is part of QElectroTech.
QElectroTech is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
QElectroTech 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with QElectroTech. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtTest>
#include <QTextDocument>
#include <QTextOption>
#include "textlines.h"
class tst_textlines : public QObject
{
Q_OBJECT
private slots:
// A text without a width gives its own lines.
void unwrappedTextGivesItsLines()
{
QTextDocument document(QStringLiteral("Motor protection\nswitch Q12"));
QCOMPARE(TextLines::layoutLines(&document),
QStringList({QStringLiteral("Motor protection"), QStringLiteral("switch Q12")}));
}
// A text without a width gives exactly the lines the DXF export wrote
// before, toPlainText().split('\n'): trailing spaces and tabs kept,
// non-breaking spaces as plain spaces, <br> as a line break.
void unwrappedTextIsUnchanged_data()
{
QTest::addColumn<QString>("html");
QTest::newRow("trailing spaces") << QStringLiteral("K1 \nswitch\t");
QTest::newRow("non-breaking spaces") << QStringLiteral("<p>K1&nbsp;&nbsp;24V&nbsp;DC</p>");
QTest::newRow("line break") << QStringLiteral("<p>Wiper to 6<br>contacts</p>");
QTest::newRow("paragraphs") << QStringLiteral("<p>relais voyant </p><p> preventa</p>");
QTest::newRow("empty") << QString();
}
void unwrappedTextIsUnchanged()
{
QFETCH(QString, html);
QTextDocument document;
if (Qt::mightBeRichText(html))
document.setHtml(html);
else
document.setPlainText(html);
QCOMPARE(TextLines::layoutLines(&document),
document.toPlainText().split(QLatin1Char('\n')));
}
// A text wrapped to its width gives one line per drawn line, without
// the space the line was broken at.
void wrappedTextGivesTheDrawnLines()
{
QTextDocument document(QStringLiteral("Motor protection switch Q12"));
QTextOption option = document.defaultTextOption();
option.setWrapMode(QTextOption::WordWrap);
document.setDefaultTextOption(option);
document.setTextWidth(1);
QCOMPARE(TextLines::layoutLines(&document),
QStringList({QStringLiteral("Motor"), QStringLiteral("protection"),
QStringLiteral("switch"), QStringLiteral("Q12")}));
}
// A wrapped paragraph has no trailing spaces left, even on its last
// line: tabs and spaces that wrap to a line of their own (as in the
// affuteuse_250h example) give an empty line, which is not written but
// still keeps the line spacing.
void wrappedTextHasNoTrailingSpaces()
{
QTextDocument document(QStringLiteral("\tMotor\t\t "));
QTextOption option = document.defaultTextOption();
option.setWrapMode(QTextOption::WordWrap);
document.setDefaultTextOption(option);
document.setTextWidth(80);
const QStringList lines = TextLines::layoutLines(&document);
QVERIFY(lines.size() > 1);
QVERIFY(lines.contains(QStringLiteral("Motor")));
for (const QString &line : lines)
QVERIFY2(line.isEmpty() || !line.back().isSpace(), qPrintable(line));
}
// Non-breaking spaces also become plain spaces in a wrapped text.
void wrappedTextHasPlainSpaces()
{
QTextDocument document;
document.setHtml(QStringLiteral("<p>K1&nbsp;24V and more words</p>"));
QTextOption option = document.defaultTextOption();
option.setWrapMode(QTextOption::WordWrap);
document.setDefaultTextOption(option);
document.setTextWidth(1);
const QStringList lines = TextLines::layoutLines(&document);
QCOMPARE(lines.first(), QStringLiteral("K1 24V"));
for (const QString &line : lines)
QVERIFY(!line.contains(QChar::Nbsp));
}
};
QTEST_MAIN(tst_textlines)
#include "tst_textlines.moc"