diff --git a/cmake/qet_compilation_vars.cmake b/cmake/qet_compilation_vars.cmake index 0ac2f64..777e946 100644 --- a/cmake/qet_compilation_vars.cmake +++ b/cmake/qet_compilation_vars.cmake @@ -29,6 +29,7 @@ set(QET_COMPONENTS set(QET_PRIVATE_LIBRARIES Qt::PrintSupport Qt::Gui + Qt::GuiPrivate # Required for QPdfEngine::drawHyperlink (PDF internal links) Qt::Xml Qt::Svg Qt::Sql diff --git a/qelectrotech.pro b/qelectrotech.pro index 41ff332..fb2fedb 100644 --- a/qelectrotech.pro +++ b/qelectrotech.pro @@ -230,7 +230,11 @@ RESOURCES += qelectrotech.qrc TRANSLATIONS += lang/*.ts # Modules Qt utilises par l'application -QT += xml svg network sql widgets printsupport concurrent KWidgetsAddons KCoreAddons +QT += xml svg network sql widgets printsupport concurrent KWidgetsAddons KCoreAddons gui-private + +# Private Qt GUI headers (needed for QPdfEngine::drawHyperlink) +# gui-private should add this automatically, but some distros need it explicit +INCLUDEPATH += $$[QT_INSTALL_HEADERS]/QtGui/$$[QT_VERSION]/QtGui # UI DESIGNER FILES AND GENERATION SOURCES FILES FORMS += $$files(sources/richtext/*.ui) \ diff --git a/sources/print/projectprintwindow.cpp b/sources/print/projectprintwindow.cpp index 7eb7a55..3a25804 100644 --- a/sources/print/projectprintwindow.cpp +++ b/sources/print/projectprintwindow.cpp @@ -21,9 +21,16 @@ #include "../qeticons.h" #include "../qetproject.h" #include "../qetversion.h" +#include "../qetgraphicsitem/crossrefitem.h" +#include "../qetgraphicsitem/dynamicelementtextitem.h" +#include "../qetgraphicsitem/elementtextitemgroup.h" #include "ui_projectprintwindow.h" +// Private Qt PDF engine for drawHyperlink() — not public API, stable since Qt4 +// Requires QT += gui-private in qelectrotech.pro +#include + #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove # include #else @@ -37,6 +44,9 @@ #include #include #include +#include +#include +#include /** * @brief ProjectPrintWindow::ProjectPrintWindow @@ -188,6 +198,217 @@ ProjectPrintWindow::~ProjectPrintWindow() * @brief ProjectPrintWindow::requestPaint * @param slot called when m_preview emit paintRequested */ +/** + * @brief ProjectPrintWindow::pdfConvertUriToGoTo + * Post-processes a Qt-generated PDF to replace URI link annotations + * (file:///path/to/file.pdf#page=N) with native PDF GoTo actions + * ([pageObj 0 R /Fit]). This makes cross-reference links work in all + * PDF viewers regardless of where the file is stored. + * + * The function: + * 1. Reads the PDF as raw bytes. + * 2. Collects page object numbers in document order by scanning for + * objects that contain "/Type /Page" (but not "/Type /Pages"). + * 3. Replaces every annotation action block + * /S /URI\n/URI (file://...#page=N) + * with + * /S /GoTo\n/D [ 0 R /Fit] + * 4. Rebuilds the cross-reference table (offsets change because the + * replacement strings have different lengths). + * 5. Writes the result back to the same file. + * + * The function is intentionally conservative: if any step fails (file + * not found, malformed PDF, no URI annotations) it returns silently + * without corrupting the file. + */ +static void pdfConvertUriToGoTo(const QString &pdfPath) +{ + // --- 1. Read raw bytes --- + QFile f(pdfPath); + if (!f.open(QIODevice::ReadOnly)) return; + QByteArray data = f.readAll(); + f.close(); + + // --- 2. Collect page object numbers in document order --- + // We scan for "N 0 obj" followed somewhere (within ~512 bytes) by + // "/Type /Page" but NOT "/Type /Pages". + QVector pageObjs; + { + const QByteArray objMarker = " 0 obj"; + const QByteArray pageType = "/Type /Page"; + const QByteArray pagesType = "/Type /Pages"; + int pos = 0; + while ((pos = data.indexOf(objMarker, pos)) != -1) { + // Find the start of the object number (walk back to newline or start) + int numStart = pos - 1; + while (numStart > 0 && data[numStart-1] != '\n' && data[numStart-1] != '\r') + --numStart; + QByteArray numStr = data.mid(numStart, pos - numStart).trimmed(); + bool ok = false; + int objNum = numStr.toInt(&ok); + if (!ok) { ++pos; continue; } + + // Look ahead for /Type /Page (not /Pages) + int searchEnd = qMin(pos + 512, data.size()); + int typePos = data.indexOf(pageType, pos); + if (typePos != -1 && typePos < searchEnd) { + // Make sure it's not /Pages + int after = typePos + pageType.size(); + bool isPages = (after < data.size() && data[after] == 's'); + if (!isPages) + pageObjs.append(objNum); + } + ++pos; + } + } + + if (pageObjs.isEmpty()) return; // nothing to do + + // --- 3. Replace URI annotations with GoTo --- + // Pattern (Qt always writes exactly this): + // /S /URI\n/URI (file:///...#page=N)\n + // or (older patches without file://): + // /S /URI\n/URI (page=N)\n + bool changed = false; + { + // We do a manual scan to handle variable-length replacements. + QByteArray out; + out.reserve(data.size()); + + const QByteArray sUri = "/S /URI\n/URI ("; + const QByteArray sGoTo = "/S /GoTo\n/D ["; + int pos = 0; + + while (pos < data.size()) { + int found = data.indexOf(sUri, pos); + if (found == -1) { + out.append(data.mid(pos)); + break; + } + + // Copy everything up to the match + out.append(data.mid(pos, found - pos)); + + // Find closing ')' of the URI value + int uriStart = found + sUri.size(); + int closeParen = data.indexOf(')', uriStart); + if (closeParen == -1) { + // Malformed — copy rest verbatim + out.append(data.mid(found)); + pos = data.size(); + break; + } + + QByteArray uriVal = data.mid(uriStart, closeParen - uriStart); + + // Extract page number: look for #page=N or bare page=N + int pageNum = -1; + int hashPos = uriVal.lastIndexOf("#page="); + if (hashPos != -1) { + pageNum = uriVal.mid(hashPos + 6).toInt(); + } else if (uriVal.startsWith("page=")) { + pageNum = uriVal.mid(5).toInt(); + } + + if (pageNum >= 1 && pageNum <= pageObjs.size()) { + // Valid page reference — emit GoTo action + int pageObjNum = pageObjs[pageNum - 1]; + QByteArray goTo = sGoTo + + QByteArray::number(pageObjNum) + + " 0 R /Fit]"; + out.append(goTo); + changed = true; + } else { + // Unknown page — keep original URI + out.append(sUri); + out.append(uriVal); + out.append(')'); + } + + pos = closeParen + 1; // skip past ')' + } + + if (!changed) return; // nothing was replaced + data = out; + } + + // --- 4. Rebuild xref table --- + // Find start of existing xref (last occurrence) + int xrefStart = data.lastIndexOf("\nxref\n"); + if (xrefStart == -1) xrefStart = data.lastIndexOf("\nxref "); + if (xrefStart == -1) return; // malformed PDF + ++xrefStart; // skip the leading '\n' + + QByteArray body = data.left(xrefStart); + + // Collect all object offsets from the body + QMap offsets; // objNum -> byte offset + { + const QByteArray objMarker = " 0 obj"; + int pos = 0; + while ((pos = body.indexOf(objMarker, pos)) != -1) { + int numStart = pos - 1; + while (numStart > 0 && body[numStart-1] != '\n' && body[numStart-1] != '\r') + --numStart; + QByteArray numStr = body.mid(numStart, pos - numStart).trimmed(); + bool ok = false; + int objNum = numStr.toInt(&ok); + if (ok && objNum > 0) + offsets[objNum] = numStart; + ++pos; + } + } + + if (offsets.isEmpty()) return; + + int maxObj = offsets.lastKey(); + + // Build xref table + QByteArray xref; + xref += "xref\n"; + xref += "0 " + QByteArray::number(maxObj + 1) + "\n"; + xref += "0000000000 65535 f \n"; + for (int i = 1; i <= maxObj; ++i) { + if (offsets.contains(i)) { + xref += QByteArray::number(offsets[i]).rightJustified(10, '0') + + " 00000 n \n"; + } else { + xref += "0000000000 65535 f \n"; + } + } + + // Find trailer dict from the original xref section + int trailerPos = data.indexOf("trailer", xrefStart); + int trailerEnd = -1; + if (trailerPos != -1) { + trailerEnd = data.indexOf("%%EOF", trailerPos); + if (trailerEnd != -1) trailerEnd += 5; + } + + QByteArray trailer; + if (trailerPos != -1 && trailerEnd != -1) + trailer = data.mid(trailerPos, trailerEnd - trailerPos); + else + trailer = "trailer\n<<>>\n%%EOF"; + + int newXrefOffset = body.size(); + + QByteArray result; + result.reserve(body.size() + xref.size() + trailer.size() + 30); + result += body; + result += xref; + result += trailer; + result += "\nstartxref\n"; + result += QByteArray::number(newXrefOffset); + result += "\n%%EOF\n"; + + // --- 5. Write back --- + QFile out(pdfPath); + if (!out.open(QIODevice::WriteOnly | QIODevice::Truncate)) return; + out.write(result); + out.close(); +} + void ProjectPrintWindow::requestPaint() { #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) @@ -214,13 +435,39 @@ void ProjectPrintWindow::requestPaint() return; } + // Build diagram -> first physical PDF page number map (1-based) + // Must be done before the print loop since page numbers depend on order + QMap diagramPageMap; + { + int pageNum = 1; + for (auto diagram : selectedDiagram()) { + diagramPageMap.insert(diagram, pageNum); + // Each diagram may span multiple pages if not fit_page + if (!ui->m_fit_in_page_cb->isChecked()) { + auto option = exportProperties(); + bool full_page = m_printer->fullPage(); + int h = horizontalPagesCount(diagram, option, full_page); + int v = verticalPagesCount(diagram, option, full_page); + pageNum += h * v; + } else { + pageNum += 1; + } + } + } + bool first = true; QPainter painter(m_printer); for (auto diagram : selectedDiagram()) { first ? first = false : m_printer->newPage(); - printDiagram(diagram, ui->m_fit_in_page_cb->isChecked(), &painter, m_printer); + printDiagram(diagram, ui->m_fit_in_page_cb->isChecked(), &painter, m_printer, diagramPageMap); } + // painter destructor flushes and closes the PDF file here + + // Convert URI annotations to native GoTo links so the PDF works + // in all viewers without depending on the file path. + if (m_printer->outputFormat() == QPrinter::PdfFormat) + pdfConvertUriToGoTo(m_printer->outputFileName()); } /** @@ -230,7 +477,7 @@ void ProjectPrintWindow::requestPaint() * @param fit_page * @param printer */ -void ProjectPrintWindow::printDiagram(Diagram *diagram, bool fit_page, QPainter *painter, QPrinter *printer) +void ProjectPrintWindow::printDiagram(Diagram *diagram, bool fit_page, QPainter *painter, QPrinter *printer, const QMap &diagramPageMap) { ////Prepare the print//// @@ -317,6 +564,116 @@ void ProjectPrintWindow::printDiagram(Diagram *diagram, bool fit_page, QPainter } } + ////Inject PDF cross-reference links//// + if (printer->outputFormat() == QPrinter::PdfFormat && fit_page) { + auto *pdfEngine = dynamic_cast(painter->paintEngine()); + if (pdfEngine) { + + // QGraphicsScene::render() fait save()/restore() : worldTransform() + // est revenu a l'identite ici. On reconstruit DONC explicitement la + // transform appliquee par : + // diagram->render(painter, QRectF(), diagram_rect, KeepAspectRatio) + // cible vide => painter->viewport() ; source = diagram_rect ; centre. + const QRectF target = QRectF(painter->viewport()); + const QRectF source = QRectF(diagram_rect); // meme source que render() + + // render() ANCRE en haut-gauche (pas de centrage) : + // translate(target.topLeft) . scale(s,s) . translate(-source.topLeft) + // On reproduit EXACTEMENT ca — surtout PAS de (target-source*s)/2. + const qreal s = qMin(target.width() / source.width(), + target.height() / source.height()); + + QTransform fit; + fit.translate(target.x(), target.y()); + fit.scale(s, s); + fit.translate(-source.x(), -source.y()); // scene -> pixels device + + // IMPORTANT : QPdfEngine::drawHyperlink() applique lui-meme + // pageMatrix() (echelle 72/resolution + inversion de Y + marges). + // On lui passe donc le rectangle en PIXELS DEVICE, sans aucune + // conversion en points ni flip de notre cote. + const QRectF pageBounds(0, 0, target.width(), target.height()); + + auto injectLink = [&](const QRectF &sceneRect, int targetPage) { + if (targetPage < 1) return; + const QRectF devRect = fit.mapRect(sceneRect); + if (!devRect.isValid() || !pageBounds.intersects(devRect)) return; + QUrl url = QUrl::fromLocalFile(printer->outputFileName()); + url.setFragment(QString("page=%1").arg(targetPage)); + pdfEngine->drawHyperlink(devRect, url); + }; + + for (auto *item : diagram->items()) { + + // --- CrossRefItem links --- + if (auto *xref = dynamic_cast(item)) { + for (auto it = xref->hoveredContactsMap().begin(); + it != xref->hoveredContactsMap().end(); ++it) + { + Element *targetElmt = it.key(); + if (!targetElmt || !targetElmt->diagram()) continue; + int targetPage = diagramPageMap.value(targetElmt->diagram(), -1); + // it.value() est en coords LOCALES du CrossRefItem -> scene + injectLink(xref->mapRectToScene(it.value()), targetPage); + } + continue; + } + + // --- Folio report links (DynamicElementTextItem) --- + if (auto *deti = dynamic_cast(item)) { + Element *parent = deti->parentElement(); + if (!parent) continue; + + // (a) Report element : label -> linked report on another folio + if (parent->linkType() & Element::AllReport) { + if (parent->linkedElements().isEmpty()) continue; + + bool showsLabel = + (deti->textFrom() == DynamicElementTextItem::ElementInfo + && deti->infoName() == QLatin1String("label")) || + (deti->textFrom() == DynamicElementTextItem::CompositeText + && deti->compositeText().contains(QStringLiteral("%{label}"))); + if (!showsLabel) continue; + + Element *targetElmt = parent->linkedElements().first(); + if (!targetElmt || !targetElmt->diagram()) continue; + int targetPage = diagramPageMap.value(targetElmt->diagram(), -1); + + injectLink(deti->mapRectToScene(deti->boundingRect()), targetPage); + continue; + } + + // (b) Slave element : the "(folio-pos)" text -> master element + if (parent->linkType() == Element::Slave) { + QGraphicsTextItem *sx = deti->slaveXrefItem(); + Element *master = deti->masterElement(); + if (sx && master && master->diagram()) { + int targetPage = diagramPageMap.value(master->diagram(), -1); + injectLink(sx->mapRectToScene(sx->boundingRect()), targetPage); + } + continue; + } + continue; + } + + // --- Slave cross-reference carried by a grouped text --- + if (auto *grp = dynamic_cast(item)) { + Element *parent = grp->parentElement(); + if (!parent || parent->linkType() != Element::Slave) continue; + if (parent->linkedElements().isEmpty()) continue; + QGraphicsTextItem *sx = grp->slaveXrefItem(); + if (!sx) continue; + Element *master = parent->linkedElements().first(); + if (!master || !master->diagram()) continue; + int targetPage = diagramPageMap.value(master->diagram(), -1); + injectLink(sx->mapRectToScene(sx->boundingRect()), targetPage); + continue; + } + } + } + } + ////PDF links end//// + ////Print is finished, restore diagram and graphics item properties for (auto view : diagram->views()) { view->setInteractive(true); diff --git a/sources/print/projectprintwindow.h b/sources/print/projectprintwindow.h index f48c018..8585c20 100644 --- a/sources/print/projectprintwindow.h +++ b/sources/print/projectprintwindow.h @@ -21,6 +21,7 @@ #include "../exportproperties.h" #include +#include #include namespace Ui { @@ -79,7 +80,7 @@ class ProjectPrintWindow : public QMainWindow private: void requestPaint(); - void printDiagram(Diagram *diagram, bool fit_page, QPainter *painter, QPrinter *printer); + void printDiagram(Diagram *diagram, bool fit_page, QPainter *painter, QPrinter *printer, const QMap &diagramPageMap = {}); QRect diagramRect(Diagram *diagram, const ExportProperties &option) const; int horizontalPagesCount(Diagram *diagram, const ExportProperties &option, bool full_page) const; int verticalPagesCount(Diagram *diagram, const ExportProperties &option, bool full_page) const; diff --git a/sources/qetgraphicsitem/crossrefitem.cpp b/sources/qetgraphicsitem/crossrefitem.cpp index d1bd2ac..343e455 100644 --- a/sources/qetgraphicsitem/crossrefitem.cpp +++ b/sources/qetgraphicsitem/crossrefitem.cpp @@ -928,7 +928,7 @@ QRectF CrossRefItem::drawContact(QPainter &painter, int flags, Element *elmt, in bounding_rect = bounding_rect.united(text_rect); if (m_update_map) - m_hovered_contacts_map.insert(elmt, bounding_rect); + m_hovered_contacts_map.insert(elmt, text_rect); ++m_drawed_contacts; } @@ -1012,7 +1012,7 @@ QRectF CrossRefItem::drawContact(QPainter &painter, int flags, Element *elmt, in bounding_rect = bounding_rect.united(text_rect); if (m_update_map) - m_hovered_contacts_map.insert(elmt, bounding_rect); + m_hovered_contacts_map.insert(elmt, text_rect); //a switch contact take place of two normal contact m_drawed_contacts += 2; @@ -1044,7 +1044,7 @@ QRectF CrossRefItem::drawContact(QPainter &painter, int flags, Element *elmt, in bounding_rect = bounding_rect.united(text_rect); if (m_update_map) - m_hovered_contacts_map.insert(elmt, bounding_rect); + m_hovered_contacts_map.insert(elmt, text_rect); ++m_drawed_contacts; } return bounding_rect; diff --git a/sources/qetgraphicsitem/crossrefitem.h b/sources/qetgraphicsitem/crossrefitem.h index 927e465..57e1fb2 100644 --- a/sources/qetgraphicsitem/crossrefitem.h +++ b/sources/qetgraphicsitem/crossrefitem.h @@ -126,6 +126,12 @@ class CrossRefItem : public QGraphicsObject ElementTextItemGroup *m_group = nullptr; QList m_slave_connection; QList m_update_connection; + + public: + /// Returns the map of linked elements and their clickable rects (local coords). + /// Used by the PDF export to inject hyperlink annotations. + const QMultiMap &hoveredContactsMap() const + { return m_hovered_contacts_map; } }; #endif // CROSSREFITEM_H diff --git a/sources/qetgraphicsitem/dynamicelementtextitem.h b/sources/qetgraphicsitem/dynamicelementtextitem.h index 73e49ba..f31096b 100644 --- a/sources/qetgraphicsitem/dynamicelementtextitem.h +++ b/sources/qetgraphicsitem/dynamicelementtextitem.h @@ -86,6 +86,9 @@ class DynamicElementTextItem : public DiagramTextItem void fromXml(const QDomElement &dom_elmt) override; Element *parentElement() const; + /// PDF export: slave cross-reference text item ("(folio-pos)") and its master target. + QGraphicsTextItem *slaveXrefItem() const { return m_slave_Xref_item; } + Element *masterElement() const { return m_master_element.data(); } ElementTextItemGroup *parentGroup() const; Element *elementUseForInfo() const; void refreshLabelConnection(); diff --git a/sources/qetgraphicsitem/elementtextitemgroup.h b/sources/qetgraphicsitem/elementtextitemgroup.h index e9e51cc..842ba50 100644 --- a/sources/qetgraphicsitem/elementtextitemgroup.h +++ b/sources/qetgraphicsitem/elementtextitemgroup.h @@ -76,6 +76,8 @@ class ElementTextItemGroup : public QObject, public QGraphicsItemGroup QList texts() const; Diagram *diagram() const; Element *parentElement() const; + /// PDF export: slave cross-reference text item of the group, if any. + QGraphicsTextItem *slaveXrefItem() const { return m_slave_Xref_item; } QDomElement toXml(QDomDocument &dom_document) const; void fromXml(QDomElement &dom_element);