From 12443fa1382894b2dcc4224dc004a3e23dd08b3b Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:31:51 +0100 Subject: [PATCH 1/2] PUBLISH publishes a sheet list (.dsd): the sheets of many drawings into one PDF, a bookmark per sheet PUBLISH (and -PUBLISH) with a .dsd path reads the sheet list AutoCAD's and BricsCAD's PUBLISH save, and publishes its sheets in its order: - each [DWF6Sheet:] names a drawing (DWG=, relative to the list's folder), a layout (Layout=, Model for model space) and optionally a named page setup of the drawing (Setup=); - [Target] Type=6 writes one PDF (DWF=), Type=5 a PDF per sheet, named after it, in the OUT= folder; other targets are refused; - [PdfOptions] CreateBookmarks=FALSE leaves the bookmarks out. The drawings open one at a time through the OPEN a script uses: rows queued at the front of the script queue, with PUBLISHNEXT between two drawings. So each sheet plots exactly as it does from its own drawing, with its own page setup, from the command line, a script or --batch (where no drawing needs to be open). A drawing that is already open is plotted as it is and stays open; one opened for the list takes no edit lease, so it leaves no lock file beside the drawing, and is closed unsaved once its sheets are plotted. Each sheet is reported with its paper size or the reason it was not published; the other sheets publish all the same, and a batch run ends with status 1. The PDF is written as the drawings go (io::pdf_publish): each drawing's rendered pages and what they use are renumbered into the output file at once; the page tree, a flat bookmark per sheet that opens its whole page, and the layer list follow at the end, and the file replaces the target only when it is complete. Layers of the same name are one optional-content group across all drawings, so a viewer's layer panel lists each once. Memory holds one drawing at a time: a real-world set of 471 sheets (A2 and A0) publishes in 20 s at 0.9 GB peak, the same as one EXPORTPDF per drawing, and every page renders identical to it. Print All's page loop takes a page setup beside each layout (plot_layout_pages) and no longer forces paper space onto Model. The new messages are in every locale's catalog; the PUBLISH wiki page describes the typed forms and sheet lists. --- docs/wiki/commands/PUBLISH.md | 30 +- locales/ar-SA/opencadstudio.ftl | 10 + locales/bg-BG/opencadstudio.ftl | 10 + locales/cs-CZ/opencadstudio.ftl | 10 + locales/de-DE/opencadstudio.ftl | 10 + locales/el-GR/opencadstudio.ftl | 10 + locales/en-US/opencadstudio.ftl | 10 + locales/es-ES/opencadstudio.ftl | 10 + locales/fi-FI/opencadstudio.ftl | 10 + locales/fr-FR/opencadstudio.ftl | 10 + locales/hi-IN/opencadstudio.ftl | 10 + locales/hu-HU/opencadstudio.ftl | 10 + locales/it-IT/opencadstudio.ftl | 10 + locales/ja-JP/opencadstudio.ftl | 10 + locales/ko-KR/opencadstudio.ftl | 10 + locales/lo-LA/opencadstudio.ftl | 10 + locales/nl-NL/opencadstudio.ftl | 10 + locales/pl-PL/opencadstudio.ftl | 10 + locales/pt-BR/opencadstudio.ftl | 10 + locales/ru-RU/opencadstudio.ftl | 10 + locales/tr-TR/opencadstudio.ftl | 10 + locales/vi-VN/opencadstudio.ftl | 10 + locales/zh-CN/opencadstudio.ftl | 10 + locales/zh-TW/opencadstudio.ftl | 10 + src/app/commands/display.rs | 12 + src/app/commands/mod.rs | 10 + src/app/mod.rs | 7 + src/app/sheet_publish.rs | 538 ++++++++++++++++++++++++ src/app/update/file/open.rs | 7 + src/app/update/file/plot.rs | 29 +- src/io/dsd.rs | 338 +++++++++++++++ src/io/mod.rs | 4 + src/io/pdf_export.rs | 22 +- src/io/pdf_publish.rs | 723 ++++++++++++++++++++++++++++++++ src/locale_catalog.rs | 10 + 35 files changed, 1942 insertions(+), 18 deletions(-) create mode 100644 src/app/sheet_publish.rs create mode 100644 src/io/dsd.rs create mode 100644 src/io/pdf_publish.rs diff --git a/docs/wiki/commands/PUBLISH.md b/docs/wiki/commands/PUBLISH.md index 462d23a099..2c0491c1da 100644 --- a/docs/wiki/commands/PUBLISH.md +++ b/docs/wiki/commands/PUBLISH.md @@ -1,7 +1,31 @@ --- -summary: Same as `PRINTALL`: outputs several paper layouts at once to one multi-page PDF or to the printer. -related: PRINTALL, PLOT, PAGESETUP -web: Print opens a PDF of the chosen layouts in a browser tab, for the browser's print dialog; there are no system printers. +summary: Same as `PRINTALL`: outputs several paper layouts at once to one multi-page PDF or to the printer. With a sheet list (.dsd) it publishes the sheets of many drawings into one PDF with a bookmark per sheet. +related: PRINTALL, PLOT, PAGESETUP, SCRIPT +web: Print opens a PDF of the chosen layouts in a browser tab, for the browser's print dialog; there are no system printers. Sheet lists are not available. --- `PUBLISH` opens the same dialog as [`PRINTALL`](PRINTALL-Command). See that page for the steps. + +## Typed forms +- `PUBLISH [sheet names…]` publishes layouts of the current drawing into one PDF without the dialog: the named ones, or all paper layouts. +- `PUBLISH ` (also `-PUBLISH`) publishes a sheet list: the sheets of as many drawings as it names, in its order. Put the path in quotes if it contains spaces. + +## Sheet lists +A sheet list is the `.dsd` file AutoCAD's and BricsCAD's PUBLISH save. Each `[DWF6Sheet:]` section is one sheet: +- `DWG=` the drawing (a relative path starts from the sheet list's folder), +- `Layout=` the layout, or `Model` for model space, +- `Setup=` optionally a named page setup of the drawing to plot with instead of the layout's own. + +`[Target]` says where the sheets go: +- `Type=6` – one PDF, the file named by `DWF=`, +- `Type=5` – a PDF per sheet, named after the sheet, in the folder named by `OUT=`. + +`[PdfOptions] CreateBookmarks=FALSE` leaves out the bookmarks. Other keys are ignored. + +## Notes +- Every sheet plots with its own page setup, as it does from its own drawing. +- The PDF has a bookmark per sheet, titled with the sheet's name, that opens the whole page. Layers of the same name are one layer of the PDF across all sheets. +- The drawings are opened one at a time and closed again without saving; they leave no lock file. A drawing that is already open is published as it is and stays open. +- The PDF is written while the drawings are opened, so a set of thousands of sheets does not have to fit in memory. It replaces the file only when it is complete. +- Each sheet is reported on the command line with its paper size, or with the reason it could not be published; the other sheets are published all the same. +- Unattended: `OpenCADStudio --batch publish.scr` with the row `PUBLISH "set.dsd"` needs no open drawing. Plot transparency follows [`PLOTTRANSPARENCYOVERRIDE`](PLOTTRANSPARENCYOVERRIDE-System-Variable). diff --git a/locales/ar-SA/opencadstudio.ftl b/locales/ar-SA/opencadstudio.ftl index cb48f19ef8..bb3b6a56db 100644 --- a/locales/ar-SA/opencadstudio.ftl +++ b/locales/ar-SA/opencadstudio.ftl @@ -6664,6 +6664,16 @@ plot = .via-the-pdf-application = عبر تطبيق PDF .direct-print = طباعة مباشرة .y-mm = Y (مم) + .publish-no-folder = PUBLISH: المجلد __ocs_fmt_0__ غير موجود. + .publish-not-opened = تعذر فتح الرسم. + .publish-drawing-missing = لم يتم العثور على الرسم __ocs_fmt_0__. + .publish-no-layout = لا يحتوي الرسم على تخطيط باسم '__ocs_fmt_0__'. + .publish-foreign-setup = إعداد الصفحة '__ocs_fmt_0__' مأخوذ من رسم آخر (__ocs_fmt_1__)؛ لا تُدعم إلا إعدادات الصفحة الخاصة بالرسم نفسه. + .publish-no-setup = لا يحتوي الرسم على إعداد صفحة باسم '__ocs_fmt_0__'. + .publish-start = جارٍ نشر __ocs_fmt_0__ ورقة من __ocs_fmt_1__ إلى __ocs_fmt_2__ + .publish-done = تم النشر: __ocs_fmt_0__ __ocs_fmt_1__ صفحة، __ocs_fmt_2__ بايت، __ocs_fmt_3__ ث + .publish-done-files = تم النشر: __ocs_fmt_0__ ملف PDF إلى __ocs_fmt_1__، __ocs_fmt_2__ ث + .publish-failed-count = PUBLISH: لم يتم نشر __ocs_fmt_0__ ورقة. manage = .about = حول diff --git a/locales/bg-BG/opencadstudio.ftl b/locales/bg-BG/opencadstudio.ftl index 390d0b0ca0..44b93d75e5 100644 --- a/locales/bg-BG/opencadstudio.ftl +++ b/locales/bg-BG/opencadstudio.ftl @@ -6652,6 +6652,16 @@ plot = .via-the-pdf-application = чрез PDF приложението .direct-print = директен печат .y-mm = Y (мм) + .publish-no-folder = PUBLISH: папката __ocs_fmt_0__ не съществува. + .publish-not-opened = чертежът не можа да бъде отворен. + .publish-drawing-missing = чертежът __ocs_fmt_0__ не е намерен. + .publish-no-layout = чертежът няма оформление с име „__ocs_fmt_0__“. + .publish-foreign-setup = настройката на страницата „__ocs_fmt_0__“ е от друг чертеж (__ocs_fmt_1__); поддържат се само настройките на страницата на самия чертеж. + .publish-no-setup = чертежът няма настройка на страницата с име „__ocs_fmt_0__“. + .publish-start = Публикуване на листове (__ocs_fmt_0__) от __ocs_fmt_1__ в __ocs_fmt_2__ + .publish-done = Публикувано: __ocs_fmt_0__ страници: __ocs_fmt_1__, байта: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Публикувано: PDF файлове: __ocs_fmt_0__ в __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: непубликувани листове: __ocs_fmt_0__. manage = .about = Относно diff --git a/locales/cs-CZ/opencadstudio.ftl b/locales/cs-CZ/opencadstudio.ftl index fff8b10eb9..cd7e9d4b92 100644 --- a/locales/cs-CZ/opencadstudio.ftl +++ b/locales/cs-CZ/opencadstudio.ftl @@ -6654,6 +6654,16 @@ plot = .via-the-pdf-application = přes aplikaci PDF .direct-print = přímý tisk .y-mm = Y (mm) + .publish-no-folder = PUBLISH: složka __ocs_fmt_0__ neexistuje. + .publish-not-opened = výkres se nepodařilo otevřít. + .publish-drawing-missing = výkres __ocs_fmt_0__ nebyl nalezen. + .publish-no-layout = výkres nemá rozvržení s názvem „__ocs_fmt_0__“. + .publish-foreign-setup = nastavení stránky „__ocs_fmt_0__“ pochází z jiného výkresu (__ocs_fmt_1__); podporována jsou jen nastavení stránky samotného výkresu. + .publish-no-setup = výkres nemá nastavení stránky s názvem „__ocs_fmt_0__“. + .publish-start = Publikování listů (__ocs_fmt_0__) z __ocs_fmt_1__ do __ocs_fmt_2__ + .publish-done = Publikováno: __ocs_fmt_0__ stran: __ocs_fmt_1__, bajtů: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Publikováno: souborů PDF: __ocs_fmt_0__ do __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: nepublikované listy: __ocs_fmt_0__. manage = .about = O aplikaci diff --git a/locales/de-DE/opencadstudio.ftl b/locales/de-DE/opencadstudio.ftl index 7930ff4a21..ebefa2b2d3 100644 --- a/locales/de-DE/opencadstudio.ftl +++ b/locales/de-DE/opencadstudio.ftl @@ -6650,6 +6650,16 @@ plot = .via-the-pdf-application = über die PDF-Anwendung .direct-print = Direktdruck .y-mm = Y (mm) + .publish-no-folder = PUBLISH: Der Ordner __ocs_fmt_0__ existiert nicht. + .publish-not-opened = die Zeichnung konnte nicht geöffnet werden. + .publish-drawing-missing = Zeichnung __ocs_fmt_0__ nicht gefunden. + .publish-no-layout = die Zeichnung hat kein Layout „__ocs_fmt_0__“. + .publish-foreign-setup = Seiteneinrichtung „__ocs_fmt_0__“ stammt aus einer anderen Zeichnung (__ocs_fmt_1__); nur Seiteneinrichtungen der Zeichnung selbst werden unterstützt. + .publish-no-setup = die Zeichnung hat keine Seiteneinrichtung „__ocs_fmt_0__“. + .publish-start = Veröffentliche __ocs_fmt_0__ Blatt/Blätter aus __ocs_fmt_1__ nach __ocs_fmt_2__ + .publish-done = Veröffentlicht: __ocs_fmt_0__ __ocs_fmt_1__ Seite(n), __ocs_fmt_2__ Bytes, __ocs_fmt_3__ s + .publish-done-files = Veröffentlicht: __ocs_fmt_0__ PDF-Datei(en) nach __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ Blatt/Blätter wurden nicht veröffentlicht. manage = .about = Über diff --git a/locales/el-GR/opencadstudio.ftl b/locales/el-GR/opencadstudio.ftl index 94b9197387..f9210264d7 100644 --- a/locales/el-GR/opencadstudio.ftl +++ b/locales/el-GR/opencadstudio.ftl @@ -6652,6 +6652,16 @@ plot = .via-the-pdf-application = μέσω της εφαρμογής PDF .direct-print = απευθείας εκτύπωση .y-mm = Y (mm) + .publish-no-folder = PUBLISH: ο φάκελος __ocs_fmt_0__ δεν υπάρχει. + .publish-not-opened = δεν ήταν δυνατό να ανοίξει το σχέδιο. + .publish-drawing-missing = το σχέδιο __ocs_fmt_0__ δεν βρέθηκε. + .publish-no-layout = το σχέδιο δεν έχει διάταξη με όνομα «__ocs_fmt_0__». + .publish-foreign-setup = η ρύθμιση σελίδας «__ocs_fmt_0__» προέρχεται από άλλο σχέδιο (__ocs_fmt_1__)· υποστηρίζονται μόνο οι ρυθμίσεις σελίδας του ίδιου του σχεδίου. + .publish-no-setup = το σχέδιο δεν έχει ρύθμιση σελίδας με όνομα «__ocs_fmt_0__». + .publish-start = Δημοσίευση φύλλων (__ocs_fmt_0__) από __ocs_fmt_1__ σε __ocs_fmt_2__ + .publish-done = Δημοσιεύτηκε: __ocs_fmt_0__ σελίδες: __ocs_fmt_1__, byte: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Δημοσιεύτηκε: αρχεία PDF: __ocs_fmt_0__ σε __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: φύλλα που δεν δημοσιεύτηκαν: __ocs_fmt_0__. manage = .about = Σχετικά diff --git a/locales/en-US/opencadstudio.ftl b/locales/en-US/opencadstudio.ftl index dc54809ecb..8dba2d10eb 100644 --- a/locales/en-US/opencadstudio.ftl +++ b/locales/en-US/opencadstudio.ftl @@ -6653,6 +6653,16 @@ plot = .via-the-pdf-application = via the PDF application .direct-print = direct print .y-mm = Y (mm) + .publish-no-folder = PUBLISH: the folder __ocs_fmt_0__ does not exist. + .publish-not-opened = the drawing could not be opened. + .publish-drawing-missing = drawing __ocs_fmt_0__ not found. + .publish-no-layout = the drawing has no layout named '__ocs_fmt_0__'. + .publish-foreign-setup = page setup '__ocs_fmt_0__' comes from another drawing (__ocs_fmt_1__); only the drawing's own page setups are supported. + .publish-no-setup = the drawing has no page setup named '__ocs_fmt_0__'. + .publish-start = Publishing __ocs_fmt_0__ sheet(s) from __ocs_fmt_1__ to __ocs_fmt_2__ + .publish-done = Published: __ocs_fmt_0__ __ocs_fmt_1__ page(s), __ocs_fmt_2__ bytes, __ocs_fmt_3__ s + .publish-done-files = Published: __ocs_fmt_0__ PDF file(s) to __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ sheet(s) were not published. manage = .about = About diff --git a/locales/es-ES/opencadstudio.ftl b/locales/es-ES/opencadstudio.ftl index 176bc37245..0297179f44 100644 --- a/locales/es-ES/opencadstudio.ftl +++ b/locales/es-ES/opencadstudio.ftl @@ -6652,6 +6652,16 @@ plot = .via-the-pdf-application = a través de la aplicación PDF .direct-print = impresión directa .y-mm = Y (mm) + .publish-no-folder = PUBLISH: la carpeta __ocs_fmt_0__ no existe. + .publish-not-opened = no se pudo abrir el dibujo. + .publish-drawing-missing = no se encontró el dibujo __ocs_fmt_0__. + .publish-no-layout = el dibujo no tiene ninguna presentación llamada «__ocs_fmt_0__». + .publish-foreign-setup = la configuración de página «__ocs_fmt_0__» procede de otro dibujo (__ocs_fmt_1__); solo se admiten las configuraciones de página del propio dibujo. + .publish-no-setup = el dibujo no tiene ninguna configuración de página llamada «__ocs_fmt_0__». + .publish-start = Publicando __ocs_fmt_0__ hoja(s) de __ocs_fmt_1__ en __ocs_fmt_2__ + .publish-done = Publicado: __ocs_fmt_0__ __ocs_fmt_1__ página(s), __ocs_fmt_2__ bytes, __ocs_fmt_3__ s + .publish-done-files = Publicado: __ocs_fmt_0__ archivo(s) PDF en __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ hoja(s) no se publicaron. manage = .about = Acerca de diff --git a/locales/fi-FI/opencadstudio.ftl b/locales/fi-FI/opencadstudio.ftl index 455c0cd254..5309d1e6cc 100644 --- a/locales/fi-FI/opencadstudio.ftl +++ b/locales/fi-FI/opencadstudio.ftl @@ -6651,6 +6651,16 @@ plot = .via-the-pdf-application = PDF-sovelluksen kautta .direct-print = suoratulostus .y-mm = Y (mm) + .publish-no-folder = PUBLISH: kansiota __ocs_fmt_0__ ei ole. + .publish-not-opened = piirustusta ei voitu avata. + .publish-drawing-missing = piirustusta __ocs_fmt_0__ ei löytynyt. + .publish-no-layout = piirustuksessa ei ole asettelua nimeltä ”__ocs_fmt_0__”. + .publish-foreign-setup = sivuasetus ”__ocs_fmt_0__” on toisesta piirustuksesta (__ocs_fmt_1__); vain piirustuksen omia sivuasetuksia tuetaan. + .publish-no-setup = piirustuksessa ei ole sivuasetusta nimeltä ”__ocs_fmt_0__”. + .publish-start = Julkaistaan arkkeja (__ocs_fmt_0__) luettelosta __ocs_fmt_1__ kohteeseen __ocs_fmt_2__ + .publish-done = Julkaistu: __ocs_fmt_0__ sivuja: __ocs_fmt_1__, tavuja: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Julkaistu: PDF-tiedostoja: __ocs_fmt_0__ kansioon __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: julkaisematta jäi arkkeja: __ocs_fmt_0__. manage = .about = Tietoja diff --git a/locales/fr-FR/opencadstudio.ftl b/locales/fr-FR/opencadstudio.ftl index d429b0c958..64ff630f91 100644 --- a/locales/fr-FR/opencadstudio.ftl +++ b/locales/fr-FR/opencadstudio.ftl @@ -6653,6 +6653,16 @@ plot = .via-the-pdf-application = via l'application PDF .direct-print = impression directe .y-mm = Y (mm) + .publish-no-folder = PUBLISH : le dossier __ocs_fmt_0__ n’existe pas. + .publish-not-opened = le dessin n’a pas pu être ouvert. + .publish-drawing-missing = dessin __ocs_fmt_0__ introuvable. + .publish-no-layout = le dessin n’a pas de présentation nommée « __ocs_fmt_0__ ». + .publish-foreign-setup = la mise en page « __ocs_fmt_0__ » provient d’un autre dessin (__ocs_fmt_1__) ; seules les mises en page du dessin lui-même sont prises en charge. + .publish-no-setup = le dessin n’a pas de mise en page nommée « __ocs_fmt_0__ ». + .publish-start = Publication de __ocs_fmt_0__ feuille(s) de __ocs_fmt_1__ vers __ocs_fmt_2__ + .publish-done = Publié : __ocs_fmt_0__ __ocs_fmt_1__ page(s), __ocs_fmt_2__ octets, __ocs_fmt_3__ s + .publish-done-files = Publié : __ocs_fmt_0__ fichier(s) PDF dans __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH : __ocs_fmt_0__ feuille(s) n’ont pas été publiées. manage = .about = À propos diff --git a/locales/hi-IN/opencadstudio.ftl b/locales/hi-IN/opencadstudio.ftl index d12a6b1cc5..66de6fb732 100644 --- a/locales/hi-IN/opencadstudio.ftl +++ b/locales/hi-IN/opencadstudio.ftl @@ -6640,6 +6640,16 @@ plot = .via-the-pdf-application = PDF एप्लिकेशन के माध्यम से .direct-print = सीधी प्रिंटिंग .y-mm = Y (मिमी) + .publish-no-folder = PUBLISH: फ़ोल्डर __ocs_fmt_0__ मौजूद नहीं है। + .publish-not-opened = ड्रॉइंग खोली नहीं जा सकी। + .publish-drawing-missing = ड्रॉइंग __ocs_fmt_0__ नहीं मिली। + .publish-no-layout = ड्रॉइंग में '__ocs_fmt_0__' नाम का कोई लेआउट नहीं है। + .publish-foreign-setup = पेज सेटअप '__ocs_fmt_0__' किसी दूसरी ड्रॉइंग (__ocs_fmt_1__) से है; केवल ड्रॉइंग के अपने पेज सेटअप समर्थित हैं। + .publish-no-setup = ड्रॉइंग में '__ocs_fmt_0__' नाम का कोई पेज सेटअप नहीं है। + .publish-start = __ocs_fmt_1__ से __ocs_fmt_0__ शीट __ocs_fmt_2__ पर प्रकाशित की जा रही हैं + .publish-done = प्रकाशित: __ocs_fmt_0__ __ocs_fmt_1__ पेज, __ocs_fmt_2__ बाइट, __ocs_fmt_3__ सेकंड + .publish-done-files = प्रकाशित: __ocs_fmt_0__ PDF फ़ाइलें __ocs_fmt_1__ में, __ocs_fmt_2__ सेकंड + .publish-failed-count = PUBLISH: __ocs_fmt_0__ शीट प्रकाशित नहीं हुईं। manage = .about = के बारे में diff --git a/locales/hu-HU/opencadstudio.ftl b/locales/hu-HU/opencadstudio.ftl index fec832325f..b31cde42bb 100644 --- a/locales/hu-HU/opencadstudio.ftl +++ b/locales/hu-HU/opencadstudio.ftl @@ -6635,6 +6635,16 @@ plot = .via-the-pdf-application = a PDF-alkalmazáson keresztül .direct-print = közvetlen nyomtatás .y-mm = Y (mm) + .publish-no-folder = PUBLISH: a(z) __ocs_fmt_0__ mappa nem létezik. + .publish-not-opened = a rajzot nem sikerült megnyitni. + .publish-drawing-missing = a(z) __ocs_fmt_0__ rajz nem található. + .publish-no-layout = a rajzban nincs „__ocs_fmt_0__” nevű elrendezés. + .publish-foreign-setup = a(z) „__ocs_fmt_0__” oldalbeállítás másik rajzból származik (__ocs_fmt_1__); csak a rajz saját oldalbeállításai támogatottak. + .publish-no-setup = a rajzban nincs „__ocs_fmt_0__” nevű oldalbeállítás. + .publish-start = Lapok közzététele (__ocs_fmt_0__): __ocs_fmt_1__ → __ocs_fmt_2__ + .publish-done = Közzétéve: __ocs_fmt_0__ oldalak: __ocs_fmt_1__, bájt: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Közzétéve: PDF-fájlok: __ocs_fmt_0__ ide: __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: nem közzétett lapok: __ocs_fmt_0__. manage = .about = Névjegy diff --git a/locales/it-IT/opencadstudio.ftl b/locales/it-IT/opencadstudio.ftl index 7c044cfd69..14aa32fd65 100644 --- a/locales/it-IT/opencadstudio.ftl +++ b/locales/it-IT/opencadstudio.ftl @@ -6651,6 +6651,16 @@ plot = .via-the-pdf-application = tramite l'applicazione PDF .direct-print = stampa diretta .y-mm = Y (mm) + .publish-no-folder = PUBLISH: la cartella __ocs_fmt_0__ non esiste. + .publish-not-opened = impossibile aprire il disegno. + .publish-drawing-missing = disegno __ocs_fmt_0__ non trovato. + .publish-no-layout = il disegno non ha un layout denominato «__ocs_fmt_0__». + .publish-foreign-setup = l'impostazione pagina «__ocs_fmt_0__» proviene da un altro disegno (__ocs_fmt_1__); sono supportate solo le impostazioni pagina del disegno stesso. + .publish-no-setup = il disegno non ha un'impostazione pagina denominata «__ocs_fmt_0__». + .publish-start = Pubblicazione di __ocs_fmt_0__ fogli da __ocs_fmt_1__ in __ocs_fmt_2__ + .publish-done = Pubblicato: __ocs_fmt_0__ __ocs_fmt_1__ pagine, __ocs_fmt_2__ byte, __ocs_fmt_3__ s + .publish-done-files = Pubblicato: __ocs_fmt_0__ file PDF in __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ fogli non sono stati pubblicati. manage = .about = Informazioni diff --git a/locales/ja-JP/opencadstudio.ftl b/locales/ja-JP/opencadstudio.ftl index 2f16e285c2..cf1f68c9dc 100644 --- a/locales/ja-JP/opencadstudio.ftl +++ b/locales/ja-JP/opencadstudio.ftl @@ -6640,6 +6640,16 @@ plot = .via-the-pdf-application = PDF アプリケーション経由 .direct-print = 直接印刷 .y-mm = Y(mm) + .publish-no-folder = PUBLISH: フォルダー __ocs_fmt_0__ が存在しません。 + .publish-not-opened = 図面を開けませんでした。 + .publish-drawing-missing = 図面 __ocs_fmt_0__ が見つかりません。 + .publish-no-layout = 図面に「__ocs_fmt_0__」という名前のレイアウトがありません。 + .publish-foreign-setup = ページ設定「__ocs_fmt_0__」は別の図面 (__ocs_fmt_1__) のものです。図面自身のページ設定のみサポートされます。 + .publish-no-setup = 図面に「__ocs_fmt_0__」という名前のページ設定がありません。 + .publish-start = __ocs_fmt_1__ の __ocs_fmt_0__ シートを __ocs_fmt_2__ にパブリッシュしています + .publish-done = パブリッシュ完了: __ocs_fmt_0__ __ocs_fmt_1__ ページ、__ocs_fmt_2__ バイト、__ocs_fmt_3__ 秒 + .publish-done-files = パブリッシュ完了: PDF ファイル __ocs_fmt_0__ 個を __ocs_fmt_1__ に、__ocs_fmt_2__ 秒 + .publish-failed-count = PUBLISH: __ocs_fmt_0__ シートがパブリッシュされませんでした。 manage = .about = バージョン情報 diff --git a/locales/ko-KR/opencadstudio.ftl b/locales/ko-KR/opencadstudio.ftl index 0ef5484334..bcc707c4d1 100644 --- a/locales/ko-KR/opencadstudio.ftl +++ b/locales/ko-KR/opencadstudio.ftl @@ -6651,6 +6651,16 @@ plot = .via-the-pdf-application = PDF 응용 프로그램 경유 .direct-print = 직접 인쇄 .y-mm = Y (mm) + .publish-no-folder = PUBLISH: __ocs_fmt_0__ 폴더가 없습니다. + .publish-not-opened = 도면을 열 수 없습니다. + .publish-drawing-missing = 도면 __ocs_fmt_0__을(를) 찾을 수 없습니다. + .publish-no-layout = 도면에 '__ocs_fmt_0__'(이)라는 배치가 없습니다. + .publish-foreign-setup = 페이지 설정 '__ocs_fmt_0__'은(는) 다른 도면(__ocs_fmt_1__)의 것입니다. 도면 자체의 페이지 설정만 지원됩니다. + .publish-no-setup = 도면에 '__ocs_fmt_0__'(이)라는 페이지 설정이 없습니다. + .publish-start = __ocs_fmt_1__의 시트 __ocs_fmt_0__개를 __ocs_fmt_2__(으)로 게시하는 중 + .publish-done = 게시됨: __ocs_fmt_0__ __ocs_fmt_1__페이지, __ocs_fmt_2__바이트, __ocs_fmt_3__초 + .publish-done-files = 게시됨: PDF 파일 __ocs_fmt_0__개를 __ocs_fmt_1__에, __ocs_fmt_2__초 + .publish-failed-count = PUBLISH: 시트 __ocs_fmt_0__개가 게시되지 않았습니다. manage = .about = 소개 diff --git a/locales/lo-LA/opencadstudio.ftl b/locales/lo-LA/opencadstudio.ftl index 588e0575f4..8c0a40a829 100644 --- a/locales/lo-LA/opencadstudio.ftl +++ b/locales/lo-LA/opencadstudio.ftl @@ -6653,6 +6653,16 @@ plot = .via-the-pdf-application = ຜ່ານແອັບພລິເຄຊັນ PDF .direct-print = ພິມໂດຍກົງ .y-mm = Y (ມມ) + .publish-no-folder = PUBLISH: ບໍ່ມີໂຟນເດີ __ocs_fmt_0__. + .publish-not-opened = ບໍ່ສາມາດເປີດແບບແຕ້ມໄດ້. + .publish-drawing-missing = ບໍ່ພົບແບບແຕ້ມ __ocs_fmt_0__. + .publish-no-layout = ແບບແຕ້ມບໍ່ມີເລເອົາຕ໌ຊື່ '__ocs_fmt_0__'. + .publish-foreign-setup = ການຕັ້ງຄ່າໜ້າເຈ້ຍ '__ocs_fmt_0__' ມາຈາກແບບແຕ້ມອື່ນ (__ocs_fmt_1__); ຮອງຮັບສະເພາະການຕັ້ງຄ່າໜ້າເຈ້ຍຂອງແບບແຕ້ມເອງ. + .publish-no-setup = ແບບແຕ້ມບໍ່ມີການຕັ້ງຄ່າໜ້າເຈ້ຍຊື່ '__ocs_fmt_0__'. + .publish-start = ກຳລັງເຜີຍແຜ່ __ocs_fmt_0__ ແຜ່ນຈາກ __ocs_fmt_1__ ໄປທີ່ __ocs_fmt_2__ + .publish-done = ເຜີຍແຜ່ແລ້ວ: __ocs_fmt_0__ __ocs_fmt_1__ ໜ້າ, __ocs_fmt_2__ ໄບຕ໌, __ocs_fmt_3__ ວິ + .publish-done-files = ເຜີຍແຜ່ແລ້ວ: __ocs_fmt_0__ ໄຟລ໌ PDF ໄປທີ່ __ocs_fmt_1__, __ocs_fmt_2__ ວິ + .publish-failed-count = PUBLISH: __ocs_fmt_0__ ແຜ່ນບໍ່ໄດ້ເຜີຍແຜ່. manage = .about = ກ່ຽວກັບ diff --git a/locales/nl-NL/opencadstudio.ftl b/locales/nl-NL/opencadstudio.ftl index c271a0ffd0..ee1260345e 100644 --- a/locales/nl-NL/opencadstudio.ftl +++ b/locales/nl-NL/opencadstudio.ftl @@ -6650,6 +6650,16 @@ plot = .via-the-pdf-application = via de PDF-toepassing .direct-print = rechtstreeks afdrukken .y-mm = Y (mm) + .publish-no-folder = PUBLISH: de map __ocs_fmt_0__ bestaat niet. + .publish-not-opened = de tekening kon niet worden geopend. + .publish-drawing-missing = tekening __ocs_fmt_0__ niet gevonden. + .publish-no-layout = de tekening heeft geen layout met de naam '__ocs_fmt_0__'. + .publish-foreign-setup = paginaconfiguratie '__ocs_fmt_0__' komt uit een andere tekening (__ocs_fmt_1__); alleen de eigen paginaconfiguraties van de tekening worden ondersteund. + .publish-no-setup = de tekening heeft geen paginaconfiguratie met de naam '__ocs_fmt_0__'. + .publish-start = __ocs_fmt_0__ blad(en) uit __ocs_fmt_1__ publiceren naar __ocs_fmt_2__ + .publish-done = Gepubliceerd: __ocs_fmt_0__ __ocs_fmt_1__ pagina('s), __ocs_fmt_2__ bytes, __ocs_fmt_3__ s + .publish-done-files = Gepubliceerd: __ocs_fmt_0__ PDF-bestand(en) naar __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ blad(en) zijn niet gepubliceerd. manage = .about = Over diff --git a/locales/pl-PL/opencadstudio.ftl b/locales/pl-PL/opencadstudio.ftl index 54ead348fe..59b9d2a973 100644 --- a/locales/pl-PL/opencadstudio.ftl +++ b/locales/pl-PL/opencadstudio.ftl @@ -6651,6 +6651,16 @@ plot = .via-the-pdf-application = przez aplikację PDF .direct-print = wydruk bezpośredni .y-mm = Y (mm) + .publish-no-folder = PUBLISH: folder __ocs_fmt_0__ nie istnieje. + .publish-not-opened = nie można otworzyć rysunku. + .publish-drawing-missing = nie znaleziono rysunku __ocs_fmt_0__. + .publish-no-layout = rysunek nie ma układu o nazwie „__ocs_fmt_0__”. + .publish-foreign-setup = ustawienia strony „__ocs_fmt_0__” pochodzą z innego rysunku (__ocs_fmt_1__); obsługiwane są tylko ustawienia strony samego rysunku. + .publish-no-setup = rysunek nie ma ustawień strony o nazwie „__ocs_fmt_0__”. + .publish-start = Publikowanie arkuszy (__ocs_fmt_0__) z __ocs_fmt_1__ do __ocs_fmt_2__ + .publish-done = Opublikowano: __ocs_fmt_0__ stron: __ocs_fmt_1__, bajtów: __ocs_fmt_2__, __ocs_fmt_3__ s + .publish-done-files = Opublikowano: plików PDF: __ocs_fmt_0__ w __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: nieopublikowane arkusze: __ocs_fmt_0__. manage = .about = O diff --git a/locales/pt-BR/opencadstudio.ftl b/locales/pt-BR/opencadstudio.ftl index 724a2d8e75..77345d95fb 100644 --- a/locales/pt-BR/opencadstudio.ftl +++ b/locales/pt-BR/opencadstudio.ftl @@ -6652,6 +6652,16 @@ plot = .via-the-pdf-application = pelo aplicativo de PDF .direct-print = impressão direta .y-mm = Y (mm) + .publish-no-folder = PUBLISH: a pasta __ocs_fmt_0__ não existe. + .publish-not-opened = não foi possível abrir o desenho. + .publish-drawing-missing = desenho __ocs_fmt_0__ não encontrado. + .publish-no-layout = o desenho não tem um layout chamado "__ocs_fmt_0__". + .publish-foreign-setup = a configuração de página "__ocs_fmt_0__" vem de outro desenho (__ocs_fmt_1__); só são suportadas as configurações de página do próprio desenho. + .publish-no-setup = o desenho não tem uma configuração de página chamada "__ocs_fmt_0__". + .publish-start = Publicando __ocs_fmt_0__ folha(s) de __ocs_fmt_1__ em __ocs_fmt_2__ + .publish-done = Publicado: __ocs_fmt_0__ __ocs_fmt_1__ página(s), __ocs_fmt_2__ bytes, __ocs_fmt_3__ s + .publish-done-files = Publicado: __ocs_fmt_0__ arquivo(s) PDF em __ocs_fmt_1__, __ocs_fmt_2__ s + .publish-failed-count = PUBLISH: __ocs_fmt_0__ folha(s) não foram publicadas. manage = .about = Sobre diff --git a/locales/ru-RU/opencadstudio.ftl b/locales/ru-RU/opencadstudio.ftl index 7a54621915..c7497eeba2 100644 --- a/locales/ru-RU/opencadstudio.ftl +++ b/locales/ru-RU/opencadstudio.ftl @@ -6653,6 +6653,16 @@ plot = .via-the-pdf-application = через приложение PDF .direct-print = прямая печать .y-mm = Y (мм) + .publish-no-folder = PUBLISH: папка __ocs_fmt_0__ не существует. + .publish-not-opened = не удалось открыть чертёж. + .publish-drawing-missing = чертёж __ocs_fmt_0__ не найден. + .publish-no-layout = в чертеже нет листа с именем «__ocs_fmt_0__». + .publish-foreign-setup = параметры страницы «__ocs_fmt_0__» взяты из другого чертежа (__ocs_fmt_1__); поддерживаются только параметры страницы самого чертежа. + .publish-no-setup = в чертеже нет параметров страницы с именем «__ocs_fmt_0__». + .publish-start = Публикация листов (__ocs_fmt_0__) из __ocs_fmt_1__ в __ocs_fmt_2__ + .publish-done = Опубликовано: __ocs_fmt_0__ страниц: __ocs_fmt_1__, байт: __ocs_fmt_2__, __ocs_fmt_3__ с + .publish-done-files = Опубликовано: PDF-файлов: __ocs_fmt_0__ в __ocs_fmt_1__, __ocs_fmt_2__ с + .publish-failed-count = PUBLISH: не опубликовано листов: __ocs_fmt_0__. manage = .about = О программе diff --git a/locales/tr-TR/opencadstudio.ftl b/locales/tr-TR/opencadstudio.ftl index 7c877e3b6d..46802f5368 100644 --- a/locales/tr-TR/opencadstudio.ftl +++ b/locales/tr-TR/opencadstudio.ftl @@ -6592,6 +6592,16 @@ plot = .via-the-pdf-application = PDF uygulaması üzerinden .direct-print = doğrudan yazdırma .y-mm = Y (mm) + .publish-no-folder = PUBLISH: __ocs_fmt_0__ klasörü yok. + .publish-not-opened = çizim açılamadı. + .publish-drawing-missing = __ocs_fmt_0__ çizimi bulunamadı. + .publish-no-layout = çizimde '__ocs_fmt_0__' adlı bir düzen yok. + .publish-foreign-setup = '__ocs_fmt_0__' sayfa yapısı başka bir çizimden geliyor (__ocs_fmt_1__); yalnızca çizimin kendi sayfa yapıları desteklenir. + .publish-no-setup = çizimde '__ocs_fmt_0__' adlı bir sayfa yapısı yok. + .publish-start = __ocs_fmt_1__ listesindeki __ocs_fmt_0__ pafta __ocs_fmt_2__ hedefine yayımlanıyor + .publish-done = Yayımlandı: __ocs_fmt_0__ __ocs_fmt_1__ sayfa, __ocs_fmt_2__ bayt, __ocs_fmt_3__ sn + .publish-done-files = Yayımlandı: __ocs_fmt_0__ PDF dosyası __ocs_fmt_1__ klasörüne, __ocs_fmt_2__ sn + .publish-failed-count = PUBLISH: __ocs_fmt_0__ pafta yayımlanmadı. manage = .about = Hakkında diff --git a/locales/vi-VN/opencadstudio.ftl b/locales/vi-VN/opencadstudio.ftl index aa1b577eb5..9b420b7a66 100644 --- a/locales/vi-VN/opencadstudio.ftl +++ b/locales/vi-VN/opencadstudio.ftl @@ -6659,6 +6659,16 @@ plot = .via-the-pdf-application = thông qua ứng dụng PDF .direct-print = in trực tiếp .y-mm = Y (mm) + .publish-no-folder = PUBLISH: thư mục __ocs_fmt_0__ không tồn tại. + .publish-not-opened = không thể mở bản vẽ. + .publish-drawing-missing = không tìm thấy bản vẽ __ocs_fmt_0__. + .publish-no-layout = bản vẽ không có bố cục tên '__ocs_fmt_0__'. + .publish-foreign-setup = thiết lập trang '__ocs_fmt_0__' đến từ một bản vẽ khác (__ocs_fmt_1__); chỉ hỗ trợ các thiết lập trang của chính bản vẽ. + .publish-no-setup = bản vẽ không có thiết lập trang tên '__ocs_fmt_0__'. + .publish-start = Đang xuất bản __ocs_fmt_0__ tờ từ __ocs_fmt_1__ sang __ocs_fmt_2__ + .publish-done = Đã xuất bản: __ocs_fmt_0__ __ocs_fmt_1__ trang, __ocs_fmt_2__ byte, __ocs_fmt_3__ giây + .publish-done-files = Đã xuất bản: __ocs_fmt_0__ tệp PDF vào __ocs_fmt_1__, __ocs_fmt_2__ giây + .publish-failed-count = PUBLISH: __ocs_fmt_0__ tờ chưa được xuất bản. manage = .about = Giới thiệu diff --git a/locales/zh-CN/opencadstudio.ftl b/locales/zh-CN/opencadstudio.ftl index c9af3317e6..1b6c782d70 100644 --- a/locales/zh-CN/opencadstudio.ftl +++ b/locales/zh-CN/opencadstudio.ftl @@ -6635,6 +6635,16 @@ plot = .via-the-pdf-application = 通过 PDF 应用程序 .direct-print = 直接打印 .y-mm = Y (毫米) + .publish-no-folder = PUBLISH:文件夹 __ocs_fmt_0__ 不存在。 + .publish-not-opened = 无法打开图形。 + .publish-drawing-missing = 未找到图形 __ocs_fmt_0__。 + .publish-no-layout = 图形中没有名为“__ocs_fmt_0__”的布局。 + .publish-foreign-setup = 页面设置“__ocs_fmt_0__”来自另一个图形(__ocs_fmt_1__);仅支持图形自身的页面设置。 + .publish-no-setup = 图形中没有名为“__ocs_fmt_0__”的页面设置。 + .publish-start = 正在将 __ocs_fmt_1__ 中的 __ocs_fmt_0__ 张图纸发布到 __ocs_fmt_2__ + .publish-done = 已发布:__ocs_fmt_0__ __ocs_fmt_1__ 页,__ocs_fmt_2__ 字节,__ocs_fmt_3__ 秒 + .publish-done-files = 已发布:__ocs_fmt_0__ 个 PDF 文件到 __ocs_fmt_1__,__ocs_fmt_2__ 秒 + .publish-failed-count = PUBLISH:__ocs_fmt_0__ 张图纸未发布。 manage = .about = 关于 diff --git a/locales/zh-TW/opencadstudio.ftl b/locales/zh-TW/opencadstudio.ftl index 26d7ee5bc8..4947b112e6 100644 --- a/locales/zh-TW/opencadstudio.ftl +++ b/locales/zh-TW/opencadstudio.ftl @@ -6647,6 +6647,16 @@ plot = .via-the-pdf-application = 透過 PDF 應用程式 .direct-print = 直接列印 .y-mm = Y (公釐) + .publish-no-folder = PUBLISH:資料夾 __ocs_fmt_0__ 不存在。 + .publish-not-opened = 無法開啟圖面。 + .publish-drawing-missing = 找不到圖面 __ocs_fmt_0__。 + .publish-no-layout = 圖面中沒有名為「__ocs_fmt_0__」的配置。 + .publish-foreign-setup = 頁面設定「__ocs_fmt_0__」來自另一個圖面(__ocs_fmt_1__);僅支援圖面本身的頁面設定。 + .publish-no-setup = 圖面中沒有名為「__ocs_fmt_0__」的頁面設定。 + .publish-start = 正在將 __ocs_fmt_1__ 中的 __ocs_fmt_0__ 張圖紙發佈到 __ocs_fmt_2__ + .publish-done = 已發佈:__ocs_fmt_0__ __ocs_fmt_1__ 頁,__ocs_fmt_2__ 位元組,__ocs_fmt_3__ 秒 + .publish-done-files = 已發佈:__ocs_fmt_0__ 個 PDF 檔案到 __ocs_fmt_1__,__ocs_fmt_2__ 秒 + .publish-failed-count = PUBLISH:__ocs_fmt_0__ 張圖紙未發佈。 manage = .about = 關於 diff --git a/src/app/commands/display.rs b/src/app/commands/display.rs index 53a16c3084..5789638c04 100644 --- a/src/app/commands/display.rs +++ b/src/app/commands/display.rs @@ -1179,6 +1179,11 @@ impl OpenCADStudio { "PRINTALL" | "PUBLISH" => { return Some(Task::done(Message::PrintAllOpen)); } + // A sheet list PUBLISH's step between two drawings. + #[cfg(not(target_arch = "wasm32"))] + crate::app::sheet_publish::NEXT_STEP => { + return Some(self.sheet_publish_step()); + } // PRINTERS — what the system reports about printing, on the // command line: the default printer, every printer it lists (or // why it could not), and how a plot will reach them. The report @@ -1259,6 +1264,13 @@ impl OpenCADStudio { .split_once(char::is_whitespace) .map(|(_, rest)| rest.trim()) .unwrap_or(""); + // PUBLISH : the sheets of a sheet list, from every + // drawing it names. + #[cfg(not(target_arch = "wasm32"))] + if crate::io::dsd::is_sheet_list_path(rest) { + let path = std::path::PathBuf::from(rest.trim_matches('"')); + return Some(self.start_sheet_publish(&path)); + } let (path_text, sheet_text) = if let Some(stripped) = rest.strip_prefix('"') { match stripped.split_once('"') { Some((path, tail)) => (path, tail.trim()), diff --git a/src/app/commands/mod.rs b/src/app/commands/mod.rs index 5196473e82..556c69a521 100644 --- a/src/app/commands/mod.rs +++ b/src/app/commands/mod.rs @@ -992,7 +992,17 @@ pub fn start_allowed(cmd: &str) -> bool { // opens the drawings it works on by path, and EXIT answers its save // questions from any tab. let verb = cmd.split_whitespace().next().unwrap_or(""); + // A sheet list PUBLISH opens the drawings it names; PUBLISHNEXT is its + // step between two of them. + let sheet_list = verb == "PUBLISHNEXT" + || matches!(verb, "PUBLISH" | "-PUBLISH") + && cmd + .trim_end() + .trim_end_matches('"') + .to_ascii_lowercase() + .ends_with(".dsd"); is_spacemouse_command(cmd) + || sheet_list || matches!(verb, "OPEN" | "SCRIPT" | "SCR" | "FILEDIA" | "SDI" | "EXIT") || matches!( cmd, diff --git a/src/app/mod.rs b/src/app/mod.rs index a4c093f21c..94ba034183 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -72,6 +72,8 @@ pub(crate) mod filter_dialog; mod find_replace; pub(crate) mod text_match; mod geographic_location; +#[cfg(not(target_arch = "wasm32"))] +mod sheet_publish; pub(crate) mod helpers; mod history; mod layer_filter_store; @@ -2279,6 +2281,9 @@ pub(super) struct OpenCADStudio { /// cannot mark a newer document state clean or redirect its path. #[cfg(not(target_arch = "wasm32"))] active_save_jobs: std::collections::HashMap, + /// The sheet list PUBLISH is working through, between its script steps. + #[cfg(not(target_arch = "wasm32"))] + sheet_publish: Option>, #[cfg(not(target_arch = "wasm32"))] save_job_serial: u64, /// Destination leases held while Save As workers are active. @@ -3414,6 +3419,8 @@ impl OpenCADStudio { #[cfg(not(target_arch = "wasm32"))] active_save_jobs: std::collections::HashMap::new(), #[cfg(not(target_arch = "wasm32"))] + sheet_publish: None, + #[cfg(not(target_arch = "wasm32"))] save_job_serial: 0, #[cfg(not(target_arch = "wasm32"))] pending_save_leases: std::collections::HashMap::new(), diff --git a/src/app/sheet_publish.rs b/src/app/sheet_publish.rs new file mode 100644 index 0000000000..5c2ece0197 --- /dev/null +++ b/src/app/sheet_publish.rs @@ -0,0 +1,538 @@ +//! PUBLISH from a sheet list (`.dsd`): the sheets of many drawings, in the +//! list's order, into one PDF with a bookmark per sheet, or into a PDF per +//! sheet. +//! +//! The drawings open one at a time through the OPEN a script uses — rows +//! queued at the front of the script queue — so each sheet plots exactly as +//! it does from its own drawing. A drawing that is already open is plotted +//! as it is. One opened for the job takes no edit lease and is closed +//! unsaved once its sheets are plotted. The PDF is written as the drawings +//! go, so memory holds one drawing at a time. + +use crate::app::{Message, OpenCADStudio}; +use crate::io::dsd::{Sheet, SheetList, Target}; +use iced::Task; +use std::path::{Path, PathBuf}; + +/// The script row that plots the drawing just opened and opens the next. +pub(crate) const NEXT_STEP: &str = "PUBLISHNEXT"; + +/// A sheet list being published. +pub(in crate::app) struct SheetPublish { + list: SheetList, + /// The PDF's title: the sheet list's name. + title: String, + /// The next sheet to publish. + next: usize, + /// The multi-sheet PDF being written. + pdf: Option, + /// The drawing opened for sheets `start..end`, plotted at the next step. + opening: Option<(PathBuf, usize, usize)>, + /// The tab that was active when the job began, active again at its end. + return_tab: u64, + published: usize, + failed: usize, + started: std::time::Instant, +} + +impl OpenCADStudio { + /// `PUBLISH `: publish the sheet list at `path`. + pub(in crate::app) fn start_sheet_publish(&mut self, path: &Path) -> Task { + // A job a cancelled script left behind ends here, and takes its + // unfinished file with it. + self.sheet_publish = None; + let list = match crate::io::dsd::read(path) { + Ok(list) => list, + Err(error) => { + self.command_line + .push_error(crate::tf!("PUBLISH: {error}").as_ref()); + return Task::none(); + } + }; + let pdf = match &list.target { + Target::MultiSheetPdf(out) => match crate::io::pdf_publish::PublishPdf::create(out) { + Ok(pdf) => Some(pdf), + Err(error) => { + self.command_line + .push_error(crate::tf!("PUBLISH: {error}").as_ref()); + return Task::none(); + } + }, + Target::SingleSheetPdfs(folder) => { + if !folder.is_dir() { + self.command_line.push_error( + crate::tf!("PUBLISH: the folder {} does not exist.", folder.display()) + .as_ref(), + ); + return Task::none(); + } + None + } + }; + let target = match &list.target { + Target::MultiSheetPdf(out) => out.display().to_string(), + Target::SingleSheetPdfs(folder) => folder.display().to_string(), + }; + self.command_line.push_output( + crate::tf!( + "Publishing {} sheet(s) from {} to {target}", + list.sheets.len(), + path.display() + ) + .as_ref(), + ); + let title = path + .file_stem() + .map(|stem| stem.to_string_lossy().into_owned()) + .unwrap_or_default(); + self.sheet_publish = Some(Box::new(SheetPublish { + list, + title, + next: 0, + pdf, + opening: None, + return_tab: self.tabs[self.active_tab].id, + published: 0, + failed: 0, + started: std::time::Instant::now(), + })); + self.script_queue.push_front(NEXT_STEP.to_string()); + if self.script_running { + Task::none() + } else { + Task::done(Message::ScriptPump) + } + } + + /// Whether `path` is the drawing a sheet list is opening only to plot it. + pub(in crate::app) fn opened_for_publish(&self, path: &Path) -> bool { + let Some((opening, _, _)) = self + .sheet_publish + .as_ref() + .and_then(|job| job.opening.as_ref()) + else { + return false; + }; + opening == path + || std::fs::canonicalize(opening) + .ok() + .zip(std::fs::canonicalize(path).ok()) + .is_some_and(|(a, b)| a == b) + } + + /// The step between drawings: plot the drawing opened for the job and + /// close it, then plot what is open already, open the next drawing, or + /// finish the PDF. + pub(in crate::app) fn sheet_publish_step(&mut self) -> Task { + let Some(mut job) = self.sheet_publish.take() else { + return Task::none(); + }; + let mut tasks = Vec::new(); + if let Some((path, start, end)) = job.opening.take() { + match self.tab_showing(&path) { + Some(idx) => { + self.active_tab = idx; + self.publish_drawing_sheets(&mut job, start, end); + let id = self.tabs[idx].id; + // Plotting stamps the plot date into fields; nothing of + // it is saved. + self.tabs[idx].dirty = false; + tasks.push(self.update(Message::TabClose(id))); + } + None => self.fail_sheets( + &mut job, + start..end, + &crate::t!("the drawing could not be opened."), + ), + } + } + let count = job.list.sheets.len(); + while job.next < count { + let start = job.next; + let drawing = job.list.sheets[start].drawing.clone(); + let end = (start..count) + .find(|&k| job.list.sheets[k].drawing != drawing) + .unwrap_or(count); + job.next = end; + if !drawing.is_file() { + let reason = crate::tf!("drawing {} not found.", drawing.display()); + self.fail_sheets(&mut job, start..end, &reason); + continue; + } + if let Some(idx) = self.tab_showing(&drawing) { + let active = self.active_tab; + self.active_tab = idx; + self.publish_drawing_sheets(&mut job, start, end); + self.active_tab = active; + continue; + } + job.opening = Some((drawing.clone(), start, end)); + self.script_queue.push_front(NEXT_STEP.to_string()); + self.script_queue + .push_front(format!("OPEN \"{}\"", drawing.display())); + self.sheet_publish = Some(job); + return Task::batch(tasks); + } + let return_tab = job.return_tab; + self.finish_sheet_publish(job); + if let Some(idx) = self.tabs.iter().position(|tab| tab.id == return_tab) { + if idx != self.active_tab { + tasks.push(self.update(Message::TabSwitch(idx))); + } + } + Task::batch(tasks) + } + + /// Plot sheets `start..end` of the job from the active drawing and add + /// them to the output. + fn publish_drawing_sheets(&mut self, job: &mut SheetPublish, start: usize, end: usize) { + self.stamp_plot_fields(); + // Print All's "same settings for every layout" is not the sheet + // list's: each sheet plots with its own page setup. + let settings_override = std::mem::replace(&mut self.print_all_settings_override, false); + let count = job.list.sheets.len(); + let mut pages = Vec::new(); + let mut titles = Vec::new(); + for k in start..end { + let sheet = &job.list.sheets[k]; + match self.sheet_page(sheet) { + Ok(page) => { + self.command_line.push_output( + crate::tf!( + " [{}/{count}] {}: {:.1}×{:.1} mm", + k + 1, + sheet.name, + page.paper_w, + page.paper_h + ) + .as_ref(), + ); + pages.push(page); + titles.push(sheet.name.clone()); + } + Err(error) => { + job.failed += 1; + self.command_line.push_error( + crate::tf!(" [{}/{count}] {}: {error}", k + 1, sheet.name).as_ref(), + ); + } + } + } + self.print_all_settings_override = settings_override; + if pages.is_empty() { + return; + } + let style = self.dialog_plot_style(&self.plot_dialog); + match &job.list.target { + Target::MultiSheetPdf(_) => { + let Some(pdf) = job.pdf.as_mut() else { + return; + }; + match crate::io::pdf_export::render_pdf_document(&pages, style.as_ref()) + .and_then(|doc| pdf.append(doc, &titles)) + { + Ok(appended) => job.published += appended, + Err(error) => { + job.failed += pages.len(); + self.command_line + .push_error(crate::tf!("PUBLISH: {error}").as_ref()); + } + } + } + Target::SingleSheetPdfs(folder) => { + for (page, title) in pages.iter().zip(&titles) { + let path = folder.join(crate::io::dsd::sheet_file_name(title)); + match crate::io::pdf_export::export_plot_pdf_pages( + std::slice::from_ref(page), + &path, + style.as_ref(), + ) { + Ok(()) => job.published += 1, + Err(error) => { + job.failed += 1; + self.command_line.push_error( + crate::tf!("PUBLISH: {}: {error}", path.display()).as_ref(), + ); + } + } + } + } + } + } + + /// The page of one sheet of the active drawing. + fn sheet_page(&mut self, sheet: &Sheet) -> Result { + let scene = &self.tabs[self.active_tab].scene; + let layout = scene + .layout_names() + .into_iter() + .find(|name| name.eq_ignore_ascii_case(&sheet.layout)) + .ok_or_else(|| { + crate::tf!("the drawing has no layout named '{}'.", sheet.layout).into_owned() + })?; + let setup = match sheet.setup.as_deref() { + None => None, + Some(setup) => { + // A page setup imported from another drawing is written + // `name|drawing`. + let (name, source) = match setup.split_once('|') { + Some((name, source)) => (name.trim(), Some(source.trim())), + None => (setup, None), + }; + if let Some(source) = source.filter(|source| !source.is_empty()) { + let same = std::fs::canonicalize(source).ok() + == std::fs::canonicalize(&sheet.drawing).ok(); + if !same { + return Err(crate::tf!( + "page setup '{name}' comes from another drawing ({source}); \ + only the drawing's own page setups are supported." + ) + .into_owned()); + } + } + Some(scene.page_setup_get(name).ok_or_else(|| { + crate::tf!("the drawing has no page setup named '{name}'.").into_owned() + })?) + } + }; + self.plot_layout_pages(&[(layout, setup)])? + .pop() + .ok_or_else(|| crate::t!("Nothing to publish: no page could be built.").into_owned()) + } + + /// Report `sheets` of the job as not published. + fn fail_sheets( + &mut self, + job: &mut SheetPublish, + sheets: std::ops::Range, + reason: &str, + ) { + let count = job.list.sheets.len(); + for k in sheets { + job.failed += 1; + self.command_line.push_error( + crate::tf!( + " [{}/{count}] {}: {error}", + k + 1, + job.list.sheets[k].name, + error = reason + ) + .as_ref(), + ); + } + } + + /// Write the end of the PDF and report what was published. + fn finish_sheet_publish(&mut self, mut job: Box) { + let seconds = job.started.elapsed().as_secs_f64(); + let failed = job.failed; + match (job.pdf.take(), &job.list.target) { + (Some(pdf), Target::MultiSheetPdf(out)) => { + let pages = pdf.page_count(); + match pdf.finish(&job.title, job.list.bookmarks) { + Ok(bytes) => self.command_line.push_output( + crate::tf!( + "Published: {} {pages} page(s), {bytes} bytes, {seconds:.1} s", + out.display() + ) + .as_ref(), + ), + Err(error) => self + .command_line + .push_error(crate::tf!("PUBLISH: {error}").as_ref()), + } + } + (_, target) => { + let folder = match target { + Target::SingleSheetPdfs(folder) => folder.display().to_string(), + Target::MultiSheetPdf(out) => out.display().to_string(), + }; + self.command_line.push_output( + crate::tf!( + "Published: {} PDF file(s) to {folder}, {seconds:.1} s", + job.published + ) + .as_ref(), + ); + } + } + if failed > 0 { + self.command_line + .push_error(crate::tf!("PUBLISH: {failed} sheet(s) were not published.").as_ref()); + } + } +} + +#[cfg(test)] +mod tests { + use crate::app::OpenCADStudio; + use std::path::{Path, PathBuf}; + + /// A drawing with a line in model space, saved as DXF at `path`. + fn drawing(path: &Path) { + let mut doc = document::Document::new(); + let line = document::entities::Line::from_points( + document::types::Vector3::new(0.0, 0.0, 0.0), + document::types::Vector3::new(100.0, 50.0, 0.0), + ); + doc.add_entity(document::EntityType::Line(line)).unwrap(); + std::fs::write( + path, + crate::io::save_to_bytes(&doc, "dxf", doc.version).unwrap(), + ) + .unwrap(); + } + + fn sheet(name: &str, drawing: &Path, layout: &str) -> String { + format!( + "[DWF6Sheet:{name}]\nDWG={}\nLayout={layout}\nSetup=\nHas Plot Port=0\n", + drawing.display() + ) + } + + /// Bookmark titles of the PDF at `path`, in order, with the page number + /// each opens. + fn bookmarks(path: &Path) -> Vec<(String, u32)> { + let doc = lopdf::Document::load(path).unwrap(); + let numbers: std::collections::HashMap = doc + .get_pages() + .into_iter() + .map(|(number, id)| (id, number)) + .collect(); + let catalog = doc.catalog().unwrap(); + let Ok(outlines) = catalog + .get(b"Outlines") + .and_then(lopdf::Object::as_reference) + else { + return Vec::new(); + }; + let mut item = doc + .get_dictionary(outlines) + .unwrap() + .get(b"First") + .and_then(lopdf::Object::as_reference) + .ok(); + let mut titles = Vec::new(); + while let Some(id) = item { + let dict = doc.get_dictionary(id).unwrap(); + let bytes = dict.get(b"Title").unwrap().as_str().unwrap(); + let title = match bytes.strip_prefix(&[0xFE, 0xFF]) { + Some(utf16) => String::from_utf16( + &utf16 + .chunks(2) + .map(|pair| u16::from_be_bytes([pair[0], pair[1]])) + .collect::>(), + ) + .unwrap(), + None => String::from_utf8(bytes.to_vec()).unwrap(), + }; + let page = dict.get(b"Dest").unwrap().as_array().unwrap()[0] + .as_reference() + .unwrap(); + titles.push((title, numbers[&page])); + item = dict.get(b"Next").and_then(lopdf::Object::as_reference).ok(); + } + titles + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ocs-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// A batch run publishes a sheet list from no open drawing: the sheets + /// of both drawings in list order, one bookmark each; sheets that cannot + /// be plotted are reported and the rest still publish. The drawings are + /// closed again and leave no lock file behind. + #[test] + fn a_sheet_list_publishes_the_sheets_of_many_drawings_into_one_pdf() { + let dir = temp_dir("publish-list"); + let (a, b) = (dir.join("a.dxf"), dir.join("sub b.dxf")); + drawing(&a); + drawing(&b); + let out = dir.join("set.pdf"); + let list = dir.join("set.dsd"); + std::fs::write( + &list, + [ + "[DWF6Version]\nVer=1\n".to_string(), + sheet("0001 - Erstes Blatt", &a, "Layout1"), + sheet("0002 - Übersicht", &b, "Layout1"), + sheet("0003 - Model", &b, "Model"), + sheet("0004 - Missing", &dir.join("missing.dxf"), "Layout1"), + sheet("0005 - No layout", &a, "Nope"), + sheet("0006 - Again", &a, "Model"), + format!("[Target]\nType=6\nDWF={}\n", out.display()), + "[PdfOptions]\nCreateBookmarks=TRUE\n".to_string(), + ] + .concat(), + ) + .unwrap(); + let mut app = OpenCADStudio::new_for_test(); + let status = app.run_batch(&format!("-PUBLISH \"{}\"\n", list.display()), &[]); + assert_eq!(status, 1, "two sheets fail"); + let output: Vec = app + .command_line + .history + .iter() + .map(|entry| entry.text.clone()) + .collect(); + assert_eq!( + bookmarks(&out), + vec![ + ("0001 - Erstes Blatt".to_string(), 1), + ("0002 - Übersicht".to_string(), 2), + ("0003 - Model".to_string(), 3), + ("0006 - Again".to_string(), 4), + ], + "{output:#?}" + ); + assert!( + app.tabs.iter().all(|tab| tab.is_start), + "the drawings are closed" + ); + let left: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.contains("lock") || name.starts_with('.')) + .collect(); + assert!(left.is_empty(), "{left:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Typed at the command line: a drawing that is already open is + /// published as it is and stays open; single-sheet output writes a PDF + /// per sheet named after it. + #[test] + fn an_open_drawing_stays_open_and_single_sheet_lists_write_a_pdf_per_sheet() { + let dir = temp_dir("publish-single"); + let a = dir.join("a.dxf"); + drawing(&a); + let list = dir.join("single.dsd"); + std::fs::write( + &list, + [ + sheet("A: one", &a, "Layout1"), + sheet("A two", &a, "Model"), + "[Target]\nType=5\nOUT=.\n".to_string(), + ] + .concat(), + ) + .unwrap(); + let mut app = OpenCADStudio::new_for_test(); + app.script_queue + .push_back(format!("OPEN \"{}\"", a.display())); + let task = app.update(crate::app::Message::ScriptPump); + app.drive_headless_task(task).unwrap(); + assert!(!app.script_running); + let task = app.dispatch_command(&format!("PUBLISH \"{}\"", list.display())); + app.drive_headless_task(task).unwrap(); + assert!(app.sheet_publish.is_none(), "the job ran to its end"); + assert!(dir.join("A_ one.pdf").is_file()); + assert!(dir.join("A two.pdf").is_file()); + assert_eq!(app.tabs.iter().filter(|tab| !tab.is_start).count(), 1); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/app/update/file/open.rs b/src/app/update/file/open.rs index 9fe7ee2211..91f422911b 100644 --- a/src/app/update/file/open.rs +++ b/src/app/update/file/open.rs @@ -159,6 +159,13 @@ impl OpenCADStudio { ); } self.tabs[i].disk_fingerprint = loaded_fingerprint.or(current_fingerprint); + // A drawing a sheet list opens only to plot it is closed unsaved + // right after: it leaves no lock file beside the drawing. + if self.opened_for_publish(path) { + self.tabs[i].edit_lease = None; + self.tabs[i].edit_lock_conflict = false; + return; + } match crate::io::edit_lock::EditLease::acquire(path) { Ok(lease) => { if let Some(warning) = lease.platform_warning() { diff --git a/src/app/update/file/plot.rs b/src/app/update/file/plot.rs index a2f2bc9950..33f554d3b2 100644 --- a/src/app/update/file/plot.rs +++ b/src/app/update/file/plot.rs @@ -1354,16 +1354,24 @@ impl OpenCADStudio { pub(in crate::app) fn print_all_pages(&mut self) -> Result, String> { self.stamp_plot_fields(); let available = self.tabs[self.active_tab].scene.layout_names(); - let selected: Vec = self + let selected: Vec<(String, Option)> = self .print_all_layouts .iter() .filter(|(name, checked)| *checked && available.contains(name)) - .map(|(name, _)| name.clone()) + .map(|(name, _)| (name.clone(), None)) .collect(); if selected.is_empty() { return Err(crate::t!("Select at least one layout.").into_owned()); } + self.plot_layout_pages(&selected) + } + /// The pages of `sheets` in the active drawing, each layout plotted with + /// its own page setup or with the page setup given beside it. + pub(in crate::app) fn plot_layout_pages( + &mut self, + sheets: &[(String, Option)], + ) -> Result, String> { let i = self.active_tab; let original_layout = self.tabs[i].scene.current_layout.clone(); let original_viewport = self.tabs[i].scene.active_viewport; @@ -1386,12 +1394,14 @@ impl OpenCADStudio { .print_all_settings_override .then(|| original_style.clone()); let result = (|| { - let mut pages = Vec::with_capacity(selected.len()); - for name in selected { - let page_setup = self.tabs[i] - .scene - .plot_settings_for(&name) - .ok_or_else(|| crate::tf!("Layout '{name}' has no page setup.").into_owned())?; + let mut pages = Vec::with_capacity(sheets.len()); + for (name, setup) in sheets { + let page_setup = match setup { + Some(setup) => setup.clone(), + None => self.tabs[i].scene.plot_settings_for(name).ok_or_else(|| { + crate::tf!("Layout '{name}' has no page setup.").into_owned() + })?, + }; { let scene = &mut self.tabs[i].scene; scene.current_layout = name.clone(); @@ -1403,7 +1413,8 @@ impl OpenCADStudio { self.active_plot_style = override_style.clone().flatten(); self.plot_window = original_window; } else { - self.plot_dialog.paper_space = true; + // A sheet list can name model space. + self.plot_dialog.paper_space = name != "Model"; self.plot_window = None; self.plot_dialog.window = None; self.load_plotsettings_into_dialog(&page_setup); diff --git a/src/io/dsd.rs b/src/io/dsd.rs new file mode 100644 index 0000000000..4fde36ab31 --- /dev/null +++ b/src/io/dsd.rs @@ -0,0 +1,338 @@ +//! Sheet lists (`.dsd`): the drawing set description AutoCAD's and +//! BricsCAD's PUBLISH save and `-PUBLISH` reads. +//! +//! A sheet list is an INI file. Every `[DWF6Sheet:]` section is one +//! sheet, in publishing order: `DWG` names the drawing, `Layout` the layout +//! (`Model` for model space), `Setup` an optional named page setup to plot it +//! with instead of the layout's own. `[Target]` says where the sheets go — +//! `Type=6` one multi-sheet PDF at `DWF`, `Type=5` a PDF per sheet in the +//! `OUT` folder — and `[PdfOptions] CreateBookmarks` whether the PDF gets a +//! bookmark per sheet, titled with the sheet's name. + +use std::path::{Path, PathBuf}; + +/// One sheet of a sheet list. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Sheet { + /// The sheet's name: the bookmark title, and the file name of a + /// single-sheet PDF. + pub name: String, + /// The drawing, resolved against the sheet list's folder. + pub drawing: PathBuf, + /// The layout to plot; `Model` is model space. + pub layout: String, + /// A named page setup of the drawing to plot with instead of the + /// layout's own page setup. + pub setup: Option, +} + +/// Where a sheet list publishes to. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Target { + /// `Type=6`: every sheet into one PDF. + MultiSheetPdf(PathBuf), + /// `Type=5`: a PDF per sheet, named after the sheet, in this folder. + SingleSheetPdfs(PathBuf), +} + +/// A sheet list read from a `.dsd` file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SheetList { + pub sheets: Vec, + pub target: Target, + /// `[PdfOptions] CreateBookmarks`: a bookmark per sheet (the default). + pub bookmarks: bool, +} + +/// Whether `path` names a sheet list. +pub fn is_sheet_list_path(path: &str) -> bool { + path.trim() + .trim_matches('"') + .to_ascii_lowercase() + .ends_with(".dsd") +} + +/// Read the sheet list at `path`; relative drawing and output paths are +/// taken from its folder. +pub fn read(path: &Path) -> Result { + let bytes = std::fs::read(path) + .map_err(|error| format!("Cannot read sheet list {}: {error}", path.display()))?; + let base = path.parent().unwrap_or_else(|| Path::new(".")); + parse(&decode(&bytes), base) +} + +/// The text of a sheet list file. AutoCAD writes them in the system's ANSI +/// code page or as Unicode with a byte-order mark; text that is not UTF-8 +/// and has no mark is read as Windows-1252. +pub fn decode(bytes: &[u8]) -> String { + if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) { + return String::from_utf8_lossy(rest).into_owned(); + } + if let Some(rest) = bytes.strip_prefix(&[0xFF, 0xFE]) { + return encoding_rs::UTF_16LE + .decode_without_bom_handling(rest) + .0 + .into_owned(); + } + if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) { + return encoding_rs::UTF_16BE + .decode_without_bom_handling(rest) + .0 + .into_owned(); + } + match std::str::from_utf8(bytes) { + Ok(text) => text.to_string(), + Err(_) => encoding_rs::WINDOWS_1252 + .decode_without_bom_handling(bytes) + .0 + .into_owned(), + } +} + +/// Parse sheet list text; `base` is the folder relative paths start from. +pub fn parse(text: &str, base: &Path) -> Result { + let mut sheets: Vec = Vec::new(); + let mut target_type: Option = None; + let mut target_file = String::new(); + let mut target_folder = String::new(); + let mut bookmarks = true; + // The section the following keys belong to. + enum Section { + Sheet, + Target, + PdfOptions, + Other, + } + let mut section = Section::Other; + for raw in text.lines() { + let line = raw.trim(); + if line.is_empty() || line.starts_with(';') { + continue; + } + if let Some(header) = line + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + { + section = if let Some(name) = strip_prefix_ignore_case(header, "DWF6Sheet:") { + sheets.push(Sheet { + name: name.to_string(), + drawing: PathBuf::new(), + layout: String::new(), + setup: None, + }); + Section::Sheet + } else if header.eq_ignore_ascii_case("Target") { + Section::Target + } else if header.eq_ignore_ascii_case("PdfOptions") { + Section::PdfOptions + } else { + Section::Other + }; + continue; + } + let Some((key, value)) = line.split_once('=') else { + continue; + }; + let (key, value) = (key.trim(), value.trim()); + match section { + Section::Sheet => { + let sheet = sheets.last_mut().expect("a sheet section is open"); + if key.eq_ignore_ascii_case("DWG") { + sheet.drawing = resolve(value, base); + } else if key.eq_ignore_ascii_case("Layout") { + sheet.layout = value.to_string(); + } else if key.eq_ignore_ascii_case("Setup") && !value.is_empty() { + sheet.setup = Some(value.to_string()); + } + } + Section::Target => { + if key.eq_ignore_ascii_case("Type") { + target_type = Some(value.to_string()); + } else if key.eq_ignore_ascii_case("DWF") { + target_file = value.to_string(); + } else if key.eq_ignore_ascii_case("OUT") { + target_folder = value.to_string(); + } + } + Section::PdfOptions => { + if key.eq_ignore_ascii_case("CreateBookmarks") { + bookmarks = !value.eq_ignore_ascii_case("FALSE") && value != "0"; + } + } + Section::Other => {} + } + } + if sheets.is_empty() { + return Err("The sheet list names no sheets.".into()); + } + for sheet in &sheets { + if sheet.drawing.as_os_str().is_empty() { + return Err(format!("Sheet \"{}\" names no drawing (DWG=).", sheet.name)); + } + if sheet.layout.is_empty() { + return Err(format!( + "Sheet \"{}\" names no layout (Layout=).", + sheet.name + )); + } + } + let target = match target_type.as_deref() { + Some("6") if !target_file.is_empty() => Target::MultiSheetPdf(resolve(&target_file, base)), + Some("6") => return Err("The sheet list names no PDF file (DWF= in [Target]).".into()), + Some("5") => Target::SingleSheetPdfs(if target_folder.is_empty() { + base.to_path_buf() + } else { + resolve(&target_folder, base) + }), + Some(other) => { + return Err(format!( + "The sheet list publishes to target type {other}; only PDF \ + (Type=5 single-sheet, Type=6 multi-sheet) is supported." + )) + } + None => return Err("The sheet list has no [Target] Type.".into()), + }; + Ok(SheetList { + sheets, + target, + bookmarks, + }) +} + +fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> { + text.get(..prefix.len()) + .filter(|head| head.eq_ignore_ascii_case(prefix)) + .map(|_| &text[prefix.len()..]) +} + +/// A path from the sheet list, relative ones taken from `base`. A list +/// written on Windows separates with backslashes; elsewhere they become +/// slashes unless the path exists as written. +fn resolve(value: &str, base: &Path) -> PathBuf { + let value = value.trim_matches('"'); + let path = PathBuf::from(value); + #[cfg(not(windows))] + let path = if value.contains('\\') && !base.join(&path).exists() { + PathBuf::from(value.replace('\\', "/")) + } else { + path + }; + if path.is_absolute() { + path + } else { + base.join(path) + } +} + +/// A file name for a single-sheet PDF: the sheet's name with the characters +/// file systems refuse replaced. +pub fn sheet_file_name(sheet: &str) -> String { + let name: String = sheet + .chars() + .map(|c| match c { + '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_', + c if c.is_control() => '_', + c => c, + }) + .collect(); + let name = name.trim().trim_end_matches('.'); + if name.is_empty() { + "sheet.pdf".to_string() + } else { + format!("{name}.pdf") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The layout openCirt writes for BricsCAD's PUBLISH (sections and keys + /// as its PUBLISH dialog saves them). + const LIST: &str = "[DWF6Version]\nVer=1\n[DWF6MinorVersion]\nMinorVer=1\n\ + [DWF6Sheet:0001 - Cover]\nDWG=/set/a.dwg\nLayout=A2\nSetup=\n\ + OriginalSheetPath=/set/a.dwg\nHas Plot Port=0\nHas3DDWF=0\n\ + [DWF6Sheet:0002 - Übersicht]\nDWG=sub/b.dwg\nLayout=Model\nSetup=PDF A3\n\ + [Target]\nType=6\nDWF=/out/set.pdf\nOUT=/out\nLocationType=2\n\ + [SheetSet Properties]\nIncludeLayer=FALSE\n\ + [PdfOptions]\nExportHyperlinks=TRUE\nCreateBookmarks=TRUE\n"; + + #[test] + fn sheets_keep_their_order_names_layouts_and_setups() { + let list = parse(LIST, Path::new("/base")).unwrap(); + assert_eq!( + list.sheets, + vec![ + Sheet { + name: "0001 - Cover".into(), + drawing: "/set/a.dwg".into(), + layout: "A2".into(), + setup: None, + }, + Sheet { + name: "0002 - Übersicht".into(), + drawing: "/base/sub/b.dwg".into(), + layout: "Model".into(), + setup: Some("PDF A3".into()), + }, + ] + ); + assert_eq!(list.target, Target::MultiSheetPdf("/out/set.pdf".into())); + assert!(list.bookmarks); + } + + #[test] + fn single_sheet_target_and_bookmarks_off() { + let text = LIST + .replace("Type=6", "Type=5") + .replace("CreateBookmarks=TRUE", "CreateBookmarks=FALSE"); + let list = parse(&text, Path::new("/base")).unwrap(); + assert_eq!(list.target, Target::SingleSheetPdfs("/out".into())); + assert!(!list.bookmarks); + } + + #[test] + fn other_targets_and_incomplete_sheets_are_refused() { + let plotter = LIST.replace("Type=6", "Type=0"); + assert!(parse(&plotter, Path::new("/")) + .unwrap_err() + .contains("target type 0")); + let no_file = LIST.replace("DWF=/out/set.pdf", "DWF="); + assert!(parse(&no_file, Path::new("/")) + .unwrap_err() + .contains("DWF=")); + let no_layout = LIST.replace("Layout=A2", "Layout="); + assert!(parse(&no_layout, Path::new("/")) + .unwrap_err() + .contains("0001 - Cover")); + assert!(parse("[Target]\nType=6\nDWF=x.pdf\n", Path::new("/")).is_err()); + } + + #[test] + fn unicode_and_ansi_files_read_alike() { + let text = "[DWF6Sheet:Übersicht]"; + let utf8_bom = [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat(); + let mut utf16 = vec![0xFF, 0xFE]; + utf16.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + let ansi = encoding_rs::WINDOWS_1252.encode(text).0.into_owned(); + for bytes in [text.as_bytes().to_vec(), utf8_bom, utf16, ansi] { + assert_eq!(decode(&bytes), text); + } + } + + #[cfg(not(windows))] + #[test] + fn windows_separators_become_slashes() { + let text = LIST.replace("DWG=sub/b.dwg", "DWG=sub\\b.dwg"); + let list = parse(&text, Path::new("/base")).unwrap(); + assert_eq!(list.sheets[1].drawing, PathBuf::from("/base/sub/b.dwg")); + } + + #[test] + fn sheet_names_make_file_names() { + assert_eq!(sheet_file_name("0001 - A/B: C?"), "0001 - A_B_ C_.pdf"); + assert_eq!(sheet_file_name(" .. "), "sheet.pdf"); + assert!(is_sheet_list_path("\"/x/Set.DSD\"")); + assert!(!is_sheet_list_path("/x/set.pdf")); + } +} diff --git a/src/io/mod.rs b/src/io/mod.rs index a5ae881240..822757a372 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -12,6 +12,8 @@ pub mod edit_lock; // inside is wasm-only. pub mod brep_build; pub mod crs; +#[cfg(not(target_arch = "wasm32"))] +pub mod dsd; pub mod dwf_export; pub mod fbx; pub mod file_association; @@ -30,6 +32,8 @@ pub mod ole_embed; pub mod paper_catalog; pub mod patterns; pub mod pdf_export; +#[cfg(not(target_arch = "wasm32"))] +pub mod pdf_publish; pub mod picture_import; pub mod plot; pub mod plot_device; diff --git a/src/io/pdf_export.rs b/src/io/pdf_export.rs index 5e37635890..c6ee0da1a0 100644 --- a/src/io/pdf_export.rs +++ b/src/io/pdf_export.rs @@ -500,6 +500,21 @@ fn render_pdf_bytes_impl( plot_style: Option<&PlotStyleTable>, include_geopdf: bool, ) -> Result, String> { + let mut lo = render_pdf_document(pages, plot_style)?; + let precise = if include_geopdf { + crate::io::geopdf_export::apply_metadata(&mut lo, pages)? + } else { + Vec::new() + }; + crate::io::geopdf_export::save_document(&mut lo, &precise) +} + +/// Render pages to a PDF document not yet serialised, without geospatial +/// metadata: the sheet-list PUBLISH appends it to the set it is writing. +pub(crate) fn render_pdf_document( + pages: &[PdfPageInput], + plot_style: Option<&PlotStyleTable>, +) -> Result { // A style the table lacks plots with Normal here; the automation export // checks `validate_plot_styles` up front and refuses instead. let mut doc = PdfDocument::new("Open CAD Studio Export"); @@ -553,12 +568,7 @@ fn render_pdf_bytes_impl( } } } - let precise = if include_geopdf { - crate::io::geopdf_export::apply_metadata(&mut lo, pages)? - } else { - Vec::new() - }; - crate::io::geopdf_export::save_document(&mut lo, &precise) + Ok(lo) } fn append_pdf_page( diff --git a/src/io/pdf_publish.rs b/src/io/pdf_publish.rs new file mode 100644 index 0000000000..41b020586f --- /dev/null +++ b/src/io/pdf_publish.rs @@ -0,0 +1,723 @@ +//! One PDF from many drawings, written as it goes: the sheet-list PUBLISH +//! appends each drawing's rendered pages and forgets them, so a set of +//! thousands of sheets never sits in memory at once. +//! +//! Each appended document's pages and everything they use are renumbered +//! into the output file at once. The page tree, the bookmarks — one per +//! sheet, in sheet order, each opening its whole page — and the layer list +//! are written when the set is finished. Layers of the same name share one +//! optional-content group across all drawings, so a viewer's layer panel +//! lists each layer once and hides it on every sheet. + +use lopdf::{Dictionary, Object, ObjectId, Stream, StringFormat}; +use std::collections::HashMap; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// A multi-sheet PDF being written. +pub struct PublishPdf { + out: std::io::BufWriter, + temp_path: PathBuf, + path: PathBuf, + finished: bool, + /// Bytes written so far: the offset the next object starts at. + offset: u64, + /// File offset of each object, by object number - 1. + xref: Vec, + /// The page tree root, numbered up front so pages can name their parent. + pages_id: u32, + pages: Vec, + /// Bookmark title and page of each sheet. + bookmarks: Vec<(String, u32)>, + /// Optional-content group of each layer name, in first-seen order. + layers: Vec, + layer_ids: HashMap, u32>, +} + +impl PublishPdf { + /// Start a PDF that replaces `path` once it is finished. + pub fn create(path: &Path) -> Result { + let temp_path = super::save_temp_path(path); + let file = std::fs::File::create(&temp_path) + .map_err(|error| format!("Cannot create {}: {error}", temp_path.display()))?; + let mut pdf = Self { + out: std::io::BufWriter::with_capacity(1 << 20, file), + temp_path, + path: path.to_path_buf(), + finished: false, + offset: 0, + xref: Vec::new(), + pages_id: 0, + pages: Vec::new(), + bookmarks: Vec::new(), + layers: Vec::new(), + layer_ids: HashMap::new(), + }; + // A binary comment tells transfer tools the file is not text. + pdf.write(b"%PDF-1.7\n%\xE2\xE3\xCF\xD3\n")?; + pdf.pages_id = pdf.reserve(); + Ok(pdf) + } + + /// Pages written so far. + pub fn page_count(&self) -> usize { + self.pages.len() + } + + /// Append every page of `doc` in order, the page at index `i` bookmarked + /// with `titles[i]`. Returns the number of pages appended. + pub fn append(&mut self, mut doc: lopdf::Document, titles: &[String]) -> Result { + doc.compress(); + let pages: Vec = doc.get_pages().into_values().collect(); + // The drawing's layers: its optional-content groups by name. + let mut layer_of: HashMap> = HashMap::new(); + if let Ok(groups) = doc + .catalog() + .and_then(|catalog| catalog.get(b"OCProperties")) + .and_then(|properties| match properties { + Object::Reference(id) => doc.get_dictionary(*id), + other => other.as_dict(), + }) + .and_then(|properties| properties.get(b"OCGs")) + .and_then(Object::as_array) + { + for group in groups { + let Ok(id) = group.as_reference() else { + continue; + }; + let name = doc + .get_dictionary(id) + .and_then(|group| group.get(b"Name")) + .and_then(Object::as_str) + .map(<[u8]>::to_vec) + .unwrap_or_default(); + layer_of.insert(id, name); + } + } + // Each page as it leaves its page tree: with what it inherits, and + // the output tree as its parent. + let mut page_dicts: HashMap = HashMap::new(); + for &id in &pages { + let Ok(page) = doc.get_dictionary(id) else { + continue; + }; + let mut page = page.clone(); + inherit_page_attributes(&doc, id, &mut page); + page.remove(b"Parent"); + page_dicts.insert(id, page); + } + // Number everything the pages use. + let mut renumber: HashMap = HashMap::new(); + let mut order: Vec = Vec::new(); + let mut stack: Vec = pages.iter().rev().copied().collect(); + while let Some(id) = stack.pop() { + if renumber.contains_key(&id) { + continue; + } + if let Some(name) = layer_of.get(&id) { + if let Some(&shared) = self.layer_ids.get(name) { + renumber.insert(id, shared); + continue; + } + let shared = self.reserve(); + self.layer_ids.insert(name.clone(), shared); + self.layers.push(shared); + renumber.insert(id, shared); + } else { + let number = self.reserve(); + renumber.insert(id, number); + } + order.push(id); + if let Some(page) = page_dicts.get(&id) { + for (_, value) in page.iter().rev() { + collect_references(value, &mut stack); + } + } else if let Ok(object) = doc.get_object(id) { + collect_references(object, &mut stack); + } + } + let first_page = self.pages.len(); + for &id in &order { + let mut object = match page_dicts.remove(&id) { + Some(page) => Object::Dictionary(page), + // A dangling reference still gets an object, so the + // renumbered file stays consistent. + None => doc.get_object(id).cloned().unwrap_or(Object::Null), + }; + remap(&mut object, &renumber); + if pages.contains(&id) { + if let Object::Dictionary(page) = &mut object { + page.set("Parent", Object::Reference((self.pages_id, 0))); + } + } + self.write_object(renumber[&id], &object)?; + } + for (index, id) in pages.iter().enumerate() { + let number = renumber[id]; + self.pages.push(number); + if let Some(title) = titles.get(index) { + self.bookmarks.push((title.clone(), number)); + } + } + Ok(self.pages.len() - first_page) + } + + /// Write the page tree, the bookmarks (unless `bookmarks` is false), the + /// layer list and the cross-reference table, then move the file into + /// place. Returns its size in bytes. + pub fn finish(mut self, title: &str, bookmarks: bool) -> Result { + if self.pages.is_empty() { + return Err("No sheet could be published.".into()); + } + let kids: Vec = self + .pages + .iter() + .map(|&page| Object::Reference((page, 0))) + .collect(); + let count = kids.len() as i64; + let pages = Dictionary::from_iter([ + ("Type", Object::Name(b"Pages".to_vec())), + ("Kids", Object::Array(kids)), + ("Count", Object::Integer(count)), + ]); + self.write_object(self.pages_id, &Object::Dictionary(pages))?; + + let mut catalog = Dictionary::from_iter([ + ("Type", Object::Name(b"Catalog".to_vec())), + ("Pages", Object::Reference((self.pages_id, 0))), + ]); + if bookmarks && !self.bookmarks.is_empty() { + let outlines = self.write_bookmarks()?; + catalog.set("Outlines", Object::Reference((outlines, 0))); + catalog.set("PageMode", Object::Name(b"UseOutlines".to_vec())); + } + if !self.layers.is_empty() { + let groups: Vec = self + .layers + .iter() + .map(|&group| Object::Reference((group, 0))) + .collect(); + let defaults = Dictionary::from_iter([ + ("Order", Object::Array(groups.clone())), + ("ON", Object::Array(groups.clone())), + ("RBGroups", Object::Array(Vec::new())), + ]); + catalog.set( + "OCProperties", + Dictionary::from_iter([ + ("OCGs", Object::Array(groups)), + ("D", Object::Dictionary(defaults)), + ]), + ); + } + let catalog_id = self.reserve(); + self.write_object(catalog_id, &Object::Dictionary(catalog))?; + let info = Dictionary::from_iter([ + ("Title", text_string(title)), + ("Producer", Object::string_literal("Open CAD Studio")), + ]); + let info_id = self.reserve(); + self.write_object(info_id, &Object::Dictionary(info))?; + + let xref_offset = self.offset; + let mut table = format!("xref\n0 {}\n0000000000 65535 f \n", self.xref.len() + 1); + for offset in &self.xref { + table.push_str(&format!("{offset:010} 00000 n \n")); + } + let id = file_id(&self.path, self.pages.len(), xref_offset); + table.push_str(&format!( + "trailer\n<<{id}>]>>\n\ + startxref\n{xref_offset}\n%%EOF\n", + self.xref.len() + 1 + )); + self.write(table.as_bytes())?; + self.out + .flush() + .map_err(|error| format!("Failed to write PDF data: {error}"))?; + self.out + .get_ref() + .sync_all() + .map_err(|error| format!("Failed to write PDF data: {error}"))?; + super::replace_save_file(&self.temp_path, &self.path, false) + .map_err(|error| format!("Failed to replace PDF file: {error}"))?; + self.finished = true; + Ok(self.offset) + } + + /// The outline root and one item per sheet, flat and in sheet order. + fn write_bookmarks(&mut self) -> Result { + let root = self.reserve(); + let items: Vec = (0..self.bookmarks.len()).map(|_| self.reserve()).collect(); + let bookmarks = std::mem::take(&mut self.bookmarks); + for (index, (title, page)) in bookmarks.iter().enumerate() { + let mut item = Dictionary::from_iter([ + ("Title", text_string(title)), + ("Parent", Object::Reference((root, 0))), + ( + "Dest", + Object::Array(vec![ + Object::Reference((*page, 0)), + Object::Name(b"Fit".to_vec()), + ]), + ), + ]); + if index > 0 { + item.set("Prev", Object::Reference((items[index - 1], 0))); + } + if let Some(next) = items.get(index + 1) { + item.set("Next", Object::Reference((*next, 0))); + } + self.write_object(items[index], &Object::Dictionary(item))?; + } + let outlines = Dictionary::from_iter([ + ("Type", Object::Name(b"Outlines".to_vec())), + ("First", Object::Reference((items[0], 0))), + ("Last", Object::Reference((items[items.len() - 1], 0))), + ("Count", Object::Integer(items.len() as i64)), + ]); + self.write_object(root, &Object::Dictionary(outlines))?; + Ok(root) + } + + /// The next object number; its offset is recorded when it is written. + fn reserve(&mut self) -> u32 { + self.xref.push(0); + self.xref.len() as u32 + } + + fn write_object(&mut self, number: u32, object: &Object) -> Result<(), String> { + self.xref[number as usize - 1] = self.offset; + let mut bytes = format!("{number} 0 obj\n").into_bytes(); + serialize(&mut bytes, object); + bytes.extend_from_slice(b"\nendobj\n"); + self.write(&bytes) + } + + fn write(&mut self, bytes: &[u8]) -> Result<(), String> { + self.out + .write_all(bytes) + .map_err(|error| format!("Failed to write PDF data: {error}"))?; + self.offset += bytes.len() as u64; + Ok(()) + } +} + +impl Drop for PublishPdf { + /// A set that is dropped unfinished leaves no partial file behind. + fn drop(&mut self) { + if !self.finished { + let _ = std::fs::remove_file(&self.temp_path); + } + } +} + +/// Queue the objects `object` references. +fn collect_references(object: &Object, stack: &mut Vec) { + match object { + Object::Reference(id) => stack.push(*id), + Object::Array(items) => { + for item in items.iter().rev() { + collect_references(item, stack); + } + } + // Reversed onto the stack, so objects are numbered in the order + // they are named. + Object::Dictionary(dict) => { + for (_, value) in dict.iter().rev() { + collect_references(value, stack); + } + } + Object::Stream(stream) => { + for (_, value) in stream.dict.iter().rev() { + collect_references(value, stack); + } + } + _ => {} + } +} + +/// Copy the attributes a page inherits from its page tree onto the page, as +/// it leaves that tree. +fn inherit_page_attributes(doc: &lopdf::Document, page_id: ObjectId, page: &mut Dictionary) { + let mut parent = page.get(b"Parent").and_then(Object::as_reference).ok(); + let mut seen = vec![page_id]; + while let Some(id) = parent.filter(|id| !seen.contains(id)) { + seen.push(id); + let Ok(node) = doc.get_dictionary(id) else { + break; + }; + for key in [&b"Resources"[..], b"MediaBox", b"CropBox", b"Rotate"] { + if !page.has(key) { + if let Ok(value) = node.get(key) { + page.set(key.to_vec(), value.clone()); + } + } + } + parent = node.get(b"Parent").and_then(Object::as_reference).ok(); + } +} + +/// Point every reference in `object` at its number in the output. +fn remap(object: &mut Object, renumber: &HashMap) { + match object { + Object::Reference(id) => { + // Everything reachable from the pages was numbered. + match renumber.get(id) { + Some(&number) => *id = (number, 0), + None => *object = Object::Null, + } + } + Object::Array(items) => { + for item in items { + remap(item, renumber); + } + } + Object::Dictionary(dict) => { + for (_, value) in dict.iter_mut() { + remap(value, renumber); + } + } + Object::Stream(stream) => { + for (_, value) in stream.dict.iter_mut() { + remap(value, renumber); + } + } + _ => {} + } +} + +/// A PDF text string: plain ASCII as it is, anything else as UTF-16BE with +/// its byte-order mark. +fn text_string(text: &str) -> Object { + if text.bytes().all(|byte| (0x20..0x7F).contains(&byte)) { + Object::String(text.as_bytes().to_vec(), StringFormat::Literal) + } else { + let mut bytes = vec![0xFE, 0xFF]; + bytes.extend(text.encode_utf16().flat_map(u16::to_be_bytes)); + Object::String(bytes, StringFormat::Hexadecimal) + } +} + +/// A file identifier from the output path, its size and its page count. +fn file_id(path: &Path, pages: usize, size: u64) -> String { + use std::hash::{Hash, Hasher}; + let mut first = std::collections::hash_map::DefaultHasher::new(); + path.hash(&mut first); + pages.hash(&mut first); + size.hash(&mut first); + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|time| time.as_nanos()) + .unwrap_or_default() + .hash(&mut first); + let a = first.finish(); + a.hash(&mut first); + let b = first.finish(); + format!("{a:016X}{b:016X}") +} + +/// Write `object` in PDF syntax. +fn serialize(out: &mut Vec, object: &Object) { + match object { + Object::Null => out.extend_from_slice(b"null"), + Object::Boolean(value) => out.extend_from_slice(if *value { b"true" } else { b"false" }), + Object::Integer(value) => out.extend_from_slice(value.to_string().as_bytes()), + // Rust prints floats without exponents, as PDF requires. + Object::Real(value) if value.is_finite() => { + out.extend_from_slice(value.to_string().as_bytes()) + } + Object::Real(_) => out.push(b'0'), + Object::Name(name) => serialize_name(out, name), + Object::String(text, StringFormat::Literal) => { + out.push(b'('); + for &byte in text { + match byte { + b'(' | b')' | b'\\' => out.extend_from_slice(&[b'\\', byte]), + b'\r' => out.extend_from_slice(b"\\r"), + _ => out.push(byte), + } + } + out.push(b')'); + } + Object::String(text, StringFormat::Hexadecimal) => { + out.push(b'<'); + for byte in text { + out.extend_from_slice(format!("{byte:02X}").as_bytes()); + } + out.push(b'>'); + } + Object::Array(items) => { + out.push(b'['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(b' '); + } + serialize(out, item); + } + out.push(b']'); + } + Object::Dictionary(dict) => serialize_dictionary(out, dict), + Object::Stream(Stream { dict, content, .. }) => { + let mut dict = dict.clone(); + dict.set("Length", Object::Integer(content.len() as i64)); + serialize_dictionary(out, &dict); + out.extend_from_slice(b"\nstream\n"); + out.extend_from_slice(content); + out.extend_from_slice(b"\nendstream"); + } + Object::Reference((number, generation)) => { + out.extend_from_slice(format!("{number} {generation} R").as_bytes()) + } + } +} + +fn serialize_dictionary(out: &mut Vec, dict: &Dictionary) { + out.extend_from_slice(b"<<"); + for (key, value) in dict.iter() { + serialize_name(out, key); + out.push(b' '); + serialize(out, value); + } + out.extend_from_slice(b">>"); +} + +/// A name with white space, delimiters and bytes outside `!`..`~` written as +/// `#xx` escapes. +fn serialize_name(out: &mut Vec, name: &[u8]) { + out.push(b'/'); + for &byte in name { + if b" \t\n\r\x0C()<>[]{}/%#".contains(&byte) || !(33..=126).contains(&byte) { + out.extend_from_slice(format!("#{byte:02X}").as_bytes()); + } else { + out.push(byte); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A one-page document of `width` × `height` points whose page uses the + /// layers `layers`. + fn sheet(width: i64, height: i64, layers: &[&str]) -> lopdf::Document { + let mut doc = lopdf::Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let mut groups = Vec::new(); + let mut properties = Dictionary::new(); + for (index, name) in layers.iter().enumerate() { + let group = doc.add_object(Dictionary::from_iter([ + ("Type", Object::Name(b"OCG".to_vec())), + ("Name", Object::string_literal(*name)), + ])); + groups.push(Object::Reference(group)); + properties.set(format!("L{index}"), Object::Reference(group)); + } + let content = doc.add_object(Stream::new( + Dictionary::new(), + b"/OC /L0 BDC 0 0 m 10 10 l S EMC".to_vec(), + )); + // Resources and the sheet size come from the page tree, as a page may + // inherit them. + let page = doc.add_object(Dictionary::from_iter([ + ("Type", Object::Name(b"Page".to_vec())), + ("Parent", Object::Reference(pages_id)), + ("Contents", Object::Reference(content)), + ])); + doc.objects.insert( + pages_id, + Object::Dictionary(Dictionary::from_iter([ + ("Type", Object::Name(b"Pages".to_vec())), + ("Kids", Object::Array(vec![Object::Reference(page)])), + ("Count", Object::Integer(1)), + ( + "MediaBox", + Object::Array(vec![0.into(), 0.into(), width.into(), height.into()]), + ), + ( + "Resources", + Object::Dictionary(Dictionary::from_iter([( + "Properties", + Object::Dictionary(properties), + )])), + ), + ])), + ); + let catalog = doc.add_object(Dictionary::from_iter([ + ("Type", Object::Name(b"Catalog".to_vec())), + ("Pages", Object::Reference(pages_id)), + ( + "OCProperties", + Object::Dictionary(Dictionary::from_iter([("OCGs", Object::Array(groups))])), + ), + ])); + doc.trailer.set("Root", Object::Reference(catalog)); + doc + } + + fn title(item: &Dictionary) -> String { + let bytes = item.get(b"Title").and_then(Object::as_str).unwrap(); + match bytes.strip_prefix(&[0xFE, 0xFF]) { + Some(utf16) => String::from_utf16( + &utf16 + .chunks(2) + .map(|pair| u16::from_be_bytes([pair[0], pair[1]])) + .collect::>(), + ) + .unwrap(), + None => String::from_utf8(bytes.to_vec()).unwrap(), + } + } + + #[test] + fn drawings_become_one_pdf_with_a_bookmark_per_sheet_and_shared_layers() { + let dir = std::env::temp_dir().join(format!("ocs-publish-pdf-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("set.pdf"); + let mut pdf = PublishPdf::create(&path).unwrap(); + assert_eq!( + pdf.append(sheet(1191, 842, &["0", "Walls"]), &["0001 - A3".into()]) + .unwrap(), + 1 + ); + assert_eq!( + pdf.append( + sheet(842, 595, &["Walls", "Doors"]), + &["0002 - Übersicht".into()] + ) + .unwrap(), + 1 + ); + assert!(!path.exists(), "the PDF appears only when finished"); + let size = pdf.finish("Set", true).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().len(), size); + + let doc = lopdf::Document::load(&path).unwrap(); + let pages: Vec = doc.get_pages().into_values().collect(); + assert_eq!(pages.len(), 2); + let boxes: Vec> = pages + .iter() + .map(|&id| { + let page = doc.get_dictionary(id).unwrap(); + page.get(b"MediaBox") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|v| v.as_i64().unwrap()) + .collect() + }) + .collect(); + assert_eq!(boxes, vec![vec![0, 0, 1191, 842], vec![0, 0, 842, 595]]); + + let catalog = doc.catalog().unwrap(); + assert_eq!( + catalog.get(b"PageMode").unwrap().as_name().unwrap(), + b"UseOutlines" + ); + let outlines = doc + .get_dictionary(catalog.get(b"Outlines").unwrap().as_reference().unwrap()) + .unwrap(); + assert_eq!(outlines.get(b"Count").unwrap().as_i64().unwrap(), 2); + let mut item_id = outlines.get(b"First").unwrap().as_reference().ok(); + let mut seen = Vec::new(); + while let Some(id) = item_id { + let item = doc.get_dictionary(id).unwrap(); + let dest = item.get(b"Dest").unwrap().as_array().unwrap(); + seen.push((title(item), dest[0].as_reference().unwrap())); + item_id = item.get(b"Next").and_then(Object::as_reference).ok(); + } + assert_eq!( + seen, + vec![ + ("0001 - A3".to_string(), pages[0]), + ("0002 - Übersicht".to_string(), pages[1]) + ] + ); + + // "Walls" is one group for both sheets; each page's properties name + // groups the catalog lists. + let properties = catalog.get(b"OCProperties").unwrap().as_dict().unwrap(); + let groups: Vec = properties + .get(b"OCGs") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|g| g.as_reference().unwrap()) + .collect(); + let names: Vec> = groups + .iter() + .map(|&g| { + doc.get_dictionary(g) + .unwrap() + .get(b"Name") + .unwrap() + .as_str() + .unwrap() + .to_vec() + }) + .collect(); + assert_eq!( + names, + vec![b"0".to_vec(), b"Walls".to_vec(), b"Doors".to_vec()] + ); + for &page in &pages { + let page = doc.get_dictionary(page).unwrap(); + let resources = page.get(b"Resources").unwrap().as_dict().unwrap(); + for (_, group) in resources + .get(b"Properties") + .unwrap() + .as_dict() + .unwrap() + .iter() + { + assert!(groups.contains(&group.as_reference().unwrap())); + } + assert_eq!( + page.get(b"Parent").unwrap().as_reference().unwrap(), + catalog.get(b"Pages").unwrap().as_reference().unwrap() + ); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn without_bookmarks_and_unfinished_sets_leave_no_file() { + let dir = std::env::temp_dir().join(format!("ocs-publish-pdf2-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("set.pdf"); + let mut pdf = PublishPdf::create(&path).unwrap(); + pdf.append(sheet(100, 100, &[]), &[]).unwrap(); + drop(pdf); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + + let mut pdf = PublishPdf::create(&path).unwrap(); + pdf.append(sheet(100, 100, &["0"]), &["x".into()]).unwrap(); + pdf.finish("Set", false).unwrap(); + let doc = lopdf::Document::load(&path).unwrap(); + assert!(doc.catalog().unwrap().get(b"Outlines").is_err()); + assert_eq!(doc.get_pages().len(), 1); + assert!(PublishPdf::create(&path) + .unwrap() + .finish("Set", true) + .is_err()); + assert!(path.exists(), "a failed set keeps the previous file"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn names_and_strings_are_escaped() { + let mut out = Vec::new(); + serialize( + &mut out, + &Object::Array(vec![ + Object::Name(b"A B#".to_vec()), + Object::string_literal("a(b)\\c\r"), + Object::Real(0.5), + Object::Real(f32::NAN), + ]), + ); + assert_eq!(out, b"[/A#20B#23 (a\\(b\\)\\\\c\\r) 0.5 0]".to_vec()); + } +} diff --git a/src/locale_catalog.rs b/src/locale_catalog.rs index ae57c29cf4..f52c132d33 100644 --- a/src/locale_catalog.rs +++ b/src/locale_catalog.rs @@ -6873,6 +6873,16 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static "Layout '{name}' has no page setup." => Some(("common", "layout-name-has-no-page-setup")), "Layout '{name}' plot style table '{}' is not loaded." => Some(("common", "layout-name-plot-style-table-is-not-loaded")), "Layout '{name}' plot area is empty." => Some(("common", "layout-name-plot-area-is-empty")), + "PUBLISH: the folder {} does not exist." => Some(("plot", "publish-no-folder")), + "the drawing could not be opened." => Some(("plot", "publish-not-opened")), + "drawing {} not found." => Some(("plot", "publish-drawing-missing")), + "the drawing has no layout named '{}'." => Some(("plot", "publish-no-layout")), + "page setup '{name}' comes from another drawing ({source}); only the drawing's own page setups are supported." => Some(("plot", "publish-foreign-setup")), + "the drawing has no page setup named '{name}'." => Some(("plot", "publish-no-setup")), + "Publishing {} sheet(s) from {} to {target}" => Some(("plot", "publish-start")), + "Published: {} {pages} page(s), {bytes} bytes, {seconds:.1} s" => Some(("plot", "publish-done")), + "Published: {} PDF file(s) to {folder}, {seconds:.1} s" => Some(("plot", "publish-done-files")), + "PUBLISH: {failed} sheet(s) were not published." => Some(("plot", "publish-failed-count")), "Exported {} layouts to {}" => Some(("common", "exported-layouts-to")), "Export failed: {error}" => Some(("common", "export-failed-error")), "Sent {} layouts to printer: {printer}" => Some(("common", "sent-layouts-to-printer-printer")), From 6f19ed88cbddcbdd8223914eeeb3e44d032cf029 Mon Sep 17 00:00:00 2001 From: Oliver Hagmann <268387159+ohagmann@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:14:52 +0100 Subject: [PATCH 2/2] PDF export carries hyperlinks; in a published set a link to a sheet opens its page The PDF export dropped every hyperlink. Now an object's hyperlink becomes a link annotation over the object on the page, as the reference application exports them: - the links of the plotted layout's own objects and of the model-space objects a viewport of the layout shows, on layers that plot; block members and attributes take no part (the reference application exports none of theirs either); - the area is the object's plotted ink; an object that plots none - a text of spaces fitted over a table row, the way a table of contents links its rows - covers its own extent (a fit or aligned text from 0.226 of its height below the baseline to 0.834 above, as the reference application sizes it); through a viewport the area is mapped onto the sheet and cut to the viewport; on the page it follows the plot's rotation, scale and window; - a web or mail address opens as a URI; a file address as a relative reference or a file: URI, %-escaped. A link to a page written into the same file opens that page, through a named destination (catalog /Names /Dests), so it can point forward: - PUBLISH of a sheet list names every sheet's page (OcsSheet000001, ...) and resolves each link against the list: the drawing (relative to HYPERLINKBASE or the drawing's folder, with Windows separators when needed) and its named location as a layout, also the layout of a `view,layout` location; without a matching layout the drawing's first sheet. Names are written at the end of the set, after all pages; - an export of several layouts of one drawing (EXPORTPDF ... ALL, Print All, PUBLISH ) links a location naming one of those layouts to its page. On a real-world set of 471 sheets with ten table-of-contents pages whose 189 rows carry such links, every row opens the page its page number names, the same as the reference application's own publish of that set; the set publishes in the same time and memory as before. --- src/app/sheet_publish.rs | 209 ++++++++++++- src/app/update/file/mod.rs | 2 + src/app/update/file/plot.rs | 220 +++++++++++++- src/app/update/file/plot_link_tests.rs | 94 ++++++ src/io/pdf_export.rs | 402 +++++++++++++++++++++++++ src/io/pdf_publish.rs | 62 +++- src/io/plot.rs | 85 ++++++ 7 files changed, 1064 insertions(+), 10 deletions(-) create mode 100644 src/app/update/file/plot_link_tests.rs diff --git a/src/app/sheet_publish.rs b/src/app/sheet_publish.rs index 5c2ece0197..286ce81226 100644 --- a/src/app/sheet_publish.rs +++ b/src/app/sheet_publish.rs @@ -30,11 +30,45 @@ pub(in crate::app) struct SheetPublish { opening: Option<(PathBuf, usize, usize)>, /// The tab that was active when the job began, active again at its end. return_tab: u64, + /// The destination name of each sheet's page, by its drawing and layout + /// (lower case), and of a drawing's first sheet: what links open. + destinations: std::collections::HashMap<(PathBuf, String), String>, + first_destinations: std::collections::HashMap, published: usize, failed: usize, started: std::time::Instant, } +/// The destination name of the page of sheet `index` (0-based); in order, +/// as a name tree lists them. +fn sheet_destination(index: usize) -> String { + format!("OcsSheet{:06}", index + 1) +} + +/// `path` as the file system resolves it, so that two spellings of a drawing +/// compare equal; as it is when it does not exist. +fn canonical(path: &Path) -> PathBuf { + std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) +} + +impl SheetPublish { + /// The page `link` opens in the PDF: the sheet of its drawing (this + /// sheet's `drawing` for a link without an address) and named location, + /// or the drawing's first sheet when the link names no layout of it. + fn link_destination(&self, link: &crate::io::plot::PlotLink, drawing: &Path) -> Option { + let target = canonical(&link.drawing(Some(drawing))?); + for layout in link.layout_candidates() { + if let Some(name) = self + .destinations + .get(&(target.clone(), layout.to_lowercase())) + { + return Some(name.clone()); + } + } + self.first_destinations.get(&target).cloned() + } +} + impl OpenCADStudio { /// `PUBLISH `: publish the sheet list at `path`. pub(in crate::app) fn start_sheet_publish(&mut self, path: &Path) -> Task { @@ -85,6 +119,16 @@ impl OpenCADStudio { .file_stem() .map(|stem| stem.to_string_lossy().into_owned()) .unwrap_or_default(); + let mut destinations = std::collections::HashMap::new(); + let mut first_destinations = std::collections::HashMap::new(); + for (index, sheet) in list.sheets.iter().enumerate() { + let name = sheet_destination(index); + let drawing = canonical(&sheet.drawing); + destinations + .entry((drawing.clone(), sheet.layout.to_lowercase())) + .or_insert_with(|| name.clone()); + first_destinations.entry(drawing).or_insert(name); + } self.sheet_publish = Some(Box::new(SheetPublish { list, title, @@ -92,6 +136,8 @@ impl OpenCADStudio { pdf, opening: None, return_tab: self.tabs[self.active_tab].id, + destinations, + first_destinations, published: 0, failed: 0, started: std::time::Instant::now(), @@ -193,10 +239,26 @@ impl OpenCADStudio { let count = job.list.sheets.len(); let mut pages = Vec::new(); let mut titles = Vec::new(); + let mut names = Vec::new(); + let one_file = matches!(job.list.target, Target::MultiSheetPdf(_)); for k in start..end { let sheet = &job.list.sheets[k]; match self.sheet_page(sheet) { - Ok(page) => { + Ok(mut page) => { + // In one PDF, a link to a sheet of the list opens its page. + let content = &mut page.content; + content.destination = None; + for link in &mut content.links { + link.destination = if one_file { + job.link_destination(link, &sheet.drawing) + } else { + None + }; + } + if one_file { + content.destination = Some(sheet_destination(k)); + } + names.push(content.destination.clone()); self.command_line.push_output( crate::tf!( " [{}/{count}] {}: {:.1}×{:.1} mm", @@ -229,7 +291,7 @@ impl OpenCADStudio { return; }; match crate::io::pdf_export::render_pdf_document(&pages, style.as_ref()) - .and_then(|doc| pdf.append(doc, &titles)) + .and_then(|doc| pdf.append(doc, &titles, &names)) { Ok(appended) => job.published += appended, Err(error) => { @@ -535,4 +597,147 @@ mod tests { assert_eq!(app.tabs.iter().filter(|tab| !tab.is_start).count(), 1); let _ = std::fs::remove_dir_all(&dir); } + + /// The page annotations of a PDF page, as (action type, target). + fn annotations( + doc: &lopdf::Document, + page: lopdf::ObjectId, + ) -> Vec<(String, String, [f32; 4])> { + let page = doc.get_dictionary(page).unwrap(); + let Ok(list) = page.get(b"Annots").and_then(lopdf::Object::as_array) else { + return Vec::new(); + }; + list.iter() + .map(|annotation| { + let annotation = doc + .get_dictionary(annotation.as_reference().unwrap()) + .unwrap(); + let action = annotation.get(b"A").unwrap().as_dict().unwrap(); + let kind = String::from_utf8(action.get(b"S").unwrap().as_name().unwrap().to_vec()) + .unwrap(); + let target = action + .get(b"D") + .or_else(|_| action.get(b"URI")) + .unwrap() + .as_str() + .unwrap(); + let rect: Vec = annotation + .get(b"Rect") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|v| v.as_float().unwrap()) + .collect(); + ( + kind, + String::from_utf8(target.to_vec()).unwrap(), + [rect[0], rect[1], rect[2], rect[3]], + ) + }) + .collect() + } + + /// A table-of-contents row the way openCirt links it: a text of spaces + /// fitted over the row, linked to the other drawing (relative path, its + /// layout). In the published PDF the row opens that sheet's page; a web + /// link stays an address. + #[test] + fn a_link_to_a_sheet_of_the_list_opens_its_page() { + use crate::scene::hyperlink::Link; + use document::types::Vector3; + let dir = temp_dir("publish-links"); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + let (toc, b) = (dir.join("toc.dxf"), dir.join("sub").join("b.dxf")); + drawing(&b); + let mut doc = document::Document::new(); + let frame = document::entities::Line::from_points( + Vector3::new(0.0, 0.0, 0.0), + Vector3::new(200.0, 100.0, 0.0), + ); + let frame = doc.add_entity(document::EntityType::Line(frame)).unwrap(); + let mut row = document::entities::Text::with_value(" ", Vector3::new(20.0, 50.0, 0.0)); + row.height = 10.0; + row.horizontal_alignment = document::entities::TextHorizontalAlignment::Fit; + row.alignment_point = Some(Vector3::new(180.0, 50.0, 0.0)); + let row = doc.add_entity(document::EntityType::Text(row)).unwrap(); + crate::scene::hyperlink::set( + &mut doc, + row, + Some(&Link { + url: "sub/b.dxf".into(), + text: "Blatt B".into(), + location: "Model".into(), + flags: 0, + }), + ); + crate::scene::hyperlink::set( + &mut doc, + frame, + Some(&Link { + url: "https://example.org/".into(), + ..Default::default() + }), + ); + std::fs::write( + &toc, + crate::io::save_to_bytes(&doc, "dxf", doc.version).unwrap(), + ) + .unwrap(); + let out = dir.join("set.pdf"); + let list = dir.join("set.dsd"); + std::fs::write( + &list, + [ + sheet("0001 - Inhalt", &toc, "Model"), + sheet("0002 - Blatt B", &b, "Model"), + format!("[Target]\nType=6\nDWF={}\n", out.display()), + ] + .concat(), + ) + .unwrap(); + let mut app = OpenCADStudio::new_for_test(); + assert_eq!( + app.run_batch(&format!("PUBLISH \"{}\"\n", list.display()), &[]), + 0 + ); + let pdf = lopdf::Document::load(&out).unwrap(); + let pages: Vec = pdf.get_pages().into_values().collect(); + let links = annotations(&pdf, pages[0]); + assert_eq!(links.len(), 2, "{links:?}"); + let row_link = links.iter().find(|link| link.0 == "GoTo").unwrap(); + assert_eq!(row_link.1, "OcsSheet000002"); + // The row's link is far wider than high. + let [x0, y0, x1, y1] = row_link.2; + assert!(x1 - x0 > 5.0 * (y1 - y0) && y1 > y0, "{row_link:?}"); + assert!(links + .iter() + .any(|link| link.0 == "URI" && link.1 == "https://example.org/")); + let names = pdf + .catalog() + .unwrap() + .get(b"Names") + .unwrap() + .as_dict() + .unwrap(); + let tree = names + .get(b"Dests") + .unwrap() + .as_dict() + .unwrap() + .get(b"Names") + .unwrap() + .as_array() + .unwrap(); + let target = tree + .chunks(2) + .find(|pair| pair[0].as_str().unwrap() == b"OcsSheet000002") + .unwrap(); + assert_eq!( + target[1].as_array().unwrap()[0].as_reference().unwrap(), + pages[1] + ); + assert!(annotations(&pdf, pages[1]).is_empty()); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src/app/update/file/mod.rs b/src/app/update/file/mod.rs index 55227de20d..f109bd6c33 100644 --- a/src/app/update/file/mod.rs +++ b/src/app/update/file/mod.rs @@ -324,6 +324,8 @@ impl OpenCADStudio { #[cfg(test)] mod plot_paper_tests; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod plot_link_tests; #[cfg(test)] mod plot_device_persistence_tests; diff --git a/src/app/update/file/plot.rs b/src/app/update/file/plot.rs index 33f554d3b2..a5d850a8c8 100644 --- a/src/app/update/file/plot.rs +++ b/src/app/update/file/plot.rs @@ -456,6 +456,8 @@ pub(crate) fn plot_scene_content( group_splits: splits, entity_layers, entity_plot_styles, + links: plot_links(scene), + destination: None, }; } let (mut model_pattern_wires, model_hatches, model_wipeouts, model_images) = @@ -514,9 +516,217 @@ pub(crate) fn plot_scene_content( group_splits: splits, entity_layers, entity_plot_styles, + links: plot_links(scene), + destination: None, } } +/// The hyperlinks the plot of the current layout carries, as the reference +/// application exports them: those of the layout's own objects, and of the +/// model-space objects a viewport of the layout shows (their area mapped onto +/// the sheet and cut to the viewport), on layers that plot. Block members +/// and attributes take no part. A relative file address is taken from +/// HYPERLINKBASE, else from the drawing's folder. +pub(crate) fn plot_links(scene: &crate::scene::Scene) -> Vec { + let doc = &scene.document; + let owner = scene.current_layout_block_handle(); + let base = match doc.header.hyperlink_base.trim() { + "" => scene.material_base_dir.clone(), + base => Some(std::path::PathBuf::from(base)), + }; + let linked = |entity: &document::EntityType| { + let common = entity.common(); + if common.invisible { + return None; + } + let link = crate::scene::hyperlink::Link::of(entity).filter(|link| !link.is_empty())?; + doc.layers + .get(&common.layer) + .is_none_or(|layer| layer.is_plottable && !layer.flags.frozen && !layer.flags.off) + .then_some(link) + }; + let plot_link = + |link: crate::scene::hyperlink::Link, entity, bounds| crate::io::plot::PlotLink { + entity, + bounds, + url: link.url, + location: link.location, + base: base.clone(), + destination: None, + }; + let mut links = Vec::new(); + for entity in doc.entities() { + if entity.common().owner_handle != owner { + continue; + } + if let Some(link) = linked(entity) { + links.push(plot_link( + link, + Some(entity.common().handle), + link_bounds(entity), + )); + } + } + if scene.current_layout == "Model" { + return links; + } + let model = doc.header.model_space_block_handle; + let (_, _, viewports) = scene.paper_viewport_handles(); + for &handle in viewports.iter() { + let Some(document::EntityType::Viewport(viewport)) = doc.get_entity(handle) else { + continue; + }; + if viewport.common.owner_handle != owner || !viewport.is_on() { + continue; + } + let Some(frame) = scene.viewport_frame(handle) else { + continue; + }; + let (cx, cy) = (viewport.center.x, viewport.center.y); + let (hw, hh) = (viewport.width / 2.0, viewport.height / 2.0); + for entity in doc.entities() { + if entity.common().owner_handle != model { + continue; + } + let Some(link) = linked(entity) else { + continue; + }; + let Some([x0, y0, x1, y1]) = link_bounds(entity) else { + continue; + }; + let mut area = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] { + let p = frame.model_to_paper(glam::DVec3::new(x, y, 0.0)); + area = [ + area[0].min(p.x), + area[1].min(p.y), + area[2].max(p.x), + area[3].max(p.y), + ]; + } + let area = [ + area[0].max(cx - hw), + area[1].max(cy - hh), + area[2].min(cx + hw), + area[3].min(cy + hh), + ]; + if area[2] > area[0] && area[3] > area[1] { + links.push(plot_link(link, None, Some(area))); + } + } + } + links +} + +/// Pages of one drawing's layouts written into one file: a link to one of +/// these layouts (an address naming no file, or this drawing) opens its page. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn link_layouts_within( + pages: &mut [crate::io::pdf_export::PdfPageInput], + names: &[String], + own: Option<&std::path::Path>, +) { + let canonical = + |path: &std::path::Path| std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let own_file = own.map(canonical); + let destination = |layout: &str| format!("OcsLayout {layout}"); + let mut targets = std::collections::HashSet::new(); + for page in pages.iter_mut() { + for link in &mut page.content.links { + let this_drawing = link.url.trim().is_empty() + || link + .drawing(own) + .is_some_and(|target| own_file.as_ref() == Some(&canonical(&target))); + if !this_drawing { + continue; + } + let layout = link.layout_candidates().into_iter().find_map(|candidate| { + names + .iter() + .find(|name| name.eq_ignore_ascii_case(candidate)) + }); + if let Some(layout) = layout { + link.destination = Some(destination(layout)); + targets.insert(layout.clone()); + } + } + } + for (page, name) in pages.iter_mut().zip(names) { + if targets.contains(name) { + page.content.destination = Some(destination(name)); + } + } +} + +/// The area of a linked object that plots no ink, such as a text of spaces +/// stretched over a table row as the link of that row. A text between two +/// points (fit, aligned) spans them, from below its baseline to above its +/// height as the reference application sizes it (0.226 and 0.834 of the +/// height); other objects their extents, a flat text given its height. +fn link_bounds(entity: &document::EntityType) -> Option<[f64; 4]> { + use document::entities::TextHorizontalAlignment as Horizontal; + let (below, above) = (0.226, 0.834); + let corners: Vec<[f64; 2]> = match entity { + document::EntityType::Text(text) + if matches!( + text.horizontal_alignment, + Horizontal::Fit | Horizontal::Aligned + ) => + { + let start = text.insertion_point; + let end = text.alignment_point?; + let (dx, dy) = (end.x - start.x, end.y - start.y); + let length = dx.hypot(dy); + if length <= 0.0 { + return None; + } + // Up is to the left of the baseline. + let (ux, uy) = (-dy / length * text.height, dx / length * text.height); + [(start.x, start.y), (end.x, end.y)] + .into_iter() + .flat_map(|(x, y)| { + [ + [x - ux * below, y - uy * below], + [x + ux * above, y + uy * above], + ] + }) + .collect() + } + _ => { + let (min, max) = crate::scene::convert::tess::entity_bounds(entity); + let (mut y0, mut y1) = (min[1], max[1]); + if let document::EntityType::Text(text) = entity { + if y1 - y0 <= 0.0 { + y0 -= text.height * below; + y1 += text.height * above; + } + } + vec![[min[0], y0], [max[0], y1]] + } + }; + let mut bounds = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for [x, y] in corners { + bounds = [ + bounds[0].min(x), + bounds[1].min(y), + bounds[2].max(x), + bounds[3].max(y), + ]; + } + (bounds.iter().all(|v| v.is_finite()) && bounds[2] > bounds[0] && bounds[3] > bounds[1]) + .then_some(bounds) +} + /// Resolve the object style and ByLayer or ByBlock inheritance for the /// plotted occurrence. Block wires keep the member and the outer INSERT. pub(crate) fn plot_entity_styles( @@ -1363,7 +1573,15 @@ impl OpenCADStudio { if selected.is_empty() { return Err(crate::t!("Select at least one layout.").into_owned()); } - self.plot_layout_pages(&selected) + let mut pages = self.plot_layout_pages(&selected)?; + let names: Vec = selected.into_iter().map(|(name, _)| name).collect(); + #[cfg(not(target_arch = "wasm32"))] + link_layouts_within( + &mut pages, + &names, + self.tabs[self.active_tab].current_path.as_deref(), + ); + Ok(pages) } /// The pages of `sheets` in the active drawing, each layout plotted with diff --git a/src/app/update/file/plot_link_tests.rs b/src/app/update/file/plot_link_tests.rs new file mode 100644 index 0000000000..24f330964a --- /dev/null +++ b/src/app/update/file/plot_link_tests.rs @@ -0,0 +1,94 @@ +//! Links between the layouts of one drawing written into one PDF. + +use super::plot::link_layouts_within; +use crate::io::pdf_export::PdfPageInput; +use crate::io::plot::{PlotContent, PlotLink}; + +fn page(links: Vec) -> PdfPageInput { + PdfPageInput { + content: PlotContent { + links, + ..Default::default() + }, + paper_w: 420.0, + paper_h: 297.0, + offset_x: 0.0, + offset_y: 0.0, + rotation_deg: 0, + content_rotation: 0.0, + scale: 1.0, + clip: None, + options: Default::default(), + plot_style: None, + geopdf: None, + } +} + +fn link(url: &str, location: &str) -> PlotLink { + PlotLink { + url: url.into(), + location: location.into(), + ..Default::default() + } +} + +/// A link to a layout written into the same file opens its page, by the +/// layout's name in any case, also as a `view,layout` location; a link to +/// another drawing or a layout not written stays an address. Only pages +/// links reach get a name. +#[test] +fn a_link_to_another_layout_of_the_drawing_opens_its_page() { + let mut pages = vec![ + page(vec![ + link("", "plan b"), + link("", "Front,PLAN C"), + link("other.dwg", "Plan B"), + link("", "Plan D"), + ]), + page(Vec::new()), + page(Vec::new()), + ]; + let names = ["Plan A", "Plan B", "Plan C"].map(String::from); + link_layouts_within(&mut pages, &names, None); + let destinations: Vec> = pages[0] + .content + .links + .iter() + .map(|link| link.destination.as_deref()) + .collect(); + assert_eq!( + destinations, + vec![ + Some("OcsLayout Plan B"), + Some("OcsLayout Plan C"), + None, + None + ] + ); + let named: Vec> = pages + .iter() + .map(|page| page.content.destination.as_deref()) + .collect(); + assert_eq!( + named, + vec![None, Some("OcsLayout Plan B"), Some("OcsLayout Plan C")] + ); +} + +/// The drawing's own path, however written, is this drawing. +#[test] +fn a_link_to_the_drawing_itself_by_its_path_stays_inside() { + let dir = std::env::temp_dir().join(format!("ocs-own-link-{}", std::process::id())); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + let own = dir.join("a.dwg"); + std::fs::write(&own, b"").unwrap(); + let mut by_path = link("../a.dwg", "Plan B"); + by_path.base = Some(dir.join("sub")); + let mut pages = vec![page(vec![by_path]), page(Vec::new())]; + link_layouts_within(&mut pages, &["Plan A".into(), "Plan B".into()], Some(&own)); + assert_eq!( + pages[0].content.links[0].destination.as_deref(), + Some("OcsLayout Plan B") + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/src/io/pdf_export.rs b/src/io/pdf_export.rs index c6ee0da1a0..8c9539f70a 100644 --- a/src/io/pdf_export.rs +++ b/src/io/pdf_export.rs @@ -568,9 +568,267 @@ pub(crate) fn render_pdf_document( } } } + let annotations = pages + .iter() + .enumerate() + .flat_map(|(index, page)| { + page_link_annotations(page) + .into_iter() + .map(move |(rect, action)| (index, rect, action)) + }) + .collect(); + let destinations = pages + .iter() + .enumerate() + .filter_map(|(index, page)| Some((index, page.content.destination.clone()?))) + .collect(); + install_links(&mut lo, annotations, destinations); Ok(lo) } +/// What a link annotation opens. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum LinkAction { + /// A page of the same file, by its destination name. + Destination(String), + /// An address the viewer opens. + Uri(String), +} + +/// The link annotations of a page: the area each linked object covers on +/// the page, in points (`[x0, y0, x1, y1]`), and what it opens. The area is +/// the object's plotted ink, or its own bounds where it plots none, mapped +/// to the page as the page draws it and cut to the plot window and sheet. +pub(crate) fn page_link_annotations(page: &PdfPageInput) -> Vec<([f32; 4], LinkAction)> { + let content = &page.content; + if content.links.is_empty() { + return Vec::new(); + } + let (ox, oy) = (page.offset_x, page.offset_y); + let s = page.scale as f64; + if !(s.is_finite() && s > 0.0) { + return Vec::new(); + } + let marker_h = page.paper_h / s; + let wanted: std::collections::HashSet = content + .links + .iter() + .filter_map(|link| link.entity) + .collect(); + let mut areas: std::collections::HashMap = + std::collections::HashMap::new(); + let mut add = |handle: document::Handle, [x0, y0, x1, y1]: [f64; 4]| { + let area = areas.entry(handle).or_insert([x0, y0, x1, y1]); + *area = [ + area[0].min(x0), + area[1].min(y0), + area[2].max(x1), + area[3].max(y1), + ]; + }; + for wire in content.wires.iter() { + let Some(handle) = crate::scene::Scene::handle_from_wire_name(&wire.wire.name) else { + continue; + }; + if wanted.contains(&handle) { + if let Some(bounds) = wire_sheet_bounds(&wire.wire, ox, oy, marker_h) { + add(handle, bounds); + } + } + } + for hatch in content.hatches.iter().chain(&content.wipeouts) { + if let Some(handle) = hatch.entity.filter(|handle| wanted.contains(handle)) { + if let Some(bounds) = hatch_sheet_bounds(hatch, ox, oy) { + add(handle, bounds); + } + } + } + // The page's own mapping: content turn, then page rotation and scale. + let (paper_w, paper_h) = (page.paper_w, page.paper_h); + let (cos, sin, tx, ty) = match page.rotation_deg { + 90 => (0.0, 1.0, paper_w, 0.0), + 180 => (-1.0, 0.0, paper_w, paper_h), + 270 => (0.0, -1.0, 0.0, paper_h), + _ => (1.0, 0.0, 0.0, 0.0), + }; + let k = MM_TO_PT as f64; + let clip = page + .clip + .map(|(cx, cy, cw, ch)| [cx as f64, cy as f64, (cx + cw) as f64, (cy + ch) as f64]); + let mut annotations = Vec::new(); + for link in &content.links { + let area = link + .entity + .and_then(|handle| areas.get(&handle).copied()) + .or_else(|| { + link.bounds + .map(|[x0, y0, x1, y1]| [x0 + ox, y0 + oy, x1 + ox, y1 + oy]) + }); + let Some(area) = area else { + continue; + }; + let action = match (&link.destination, link.url.trim()) { + (Some(name), _) => LinkAction::Destination(name.clone()), + (None, "") => continue, + (None, url) => LinkAction::Uri(link_uri(url, link.is_web())), + }; + let mut turned = crate::io::plot::turned_bounds(page.content_rotation, area); + if let Some(window) = clip { + turned = [ + turned[0].max(window[0]), + turned[1].max(window[1]), + turned[2].min(window[2]), + turned[3].min(window[3]), + ]; + if turned[2] <= turned[0] || turned[3] <= turned[1] { + continue; + } + } + let mut rect = [ + f64::INFINITY, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NEG_INFINITY, + ]; + for (x, y) in [ + (turned[0], turned[1]), + (turned[2], turned[1]), + (turned[2], turned[3]), + (turned[0], turned[3]), + ] { + let px = (cos * s * x - sin * s * y + tx) * k; + let py = (sin * s * x + cos * s * y + ty) * k; + rect = [ + rect[0].min(px), + rect[1].min(py), + rect[2].max(px), + rect[3].max(py), + ]; + } + let rect = [ + rect[0].max(0.0), + rect[1].max(0.0), + rect[2].min(paper_w * k), + rect[3].min(paper_h * k), + ]; + // Less than a point across is nothing to click. + if !(rect[2] - rect[0] >= 1.0 && rect[3] - rect[1] >= 1.0) { + continue; + } + annotations.push((rect.map(|v| v as f32), action)); + } + annotations +} + +/// A link address as a URI: a web address as it is, a file as a relative +/// reference or a `file:` URI, with what a URI cannot hold %-escaped. +fn link_uri(url: &str, web: bool) -> String { + let url = if web { + url.to_string() + } else { + let path = url.replace('\\', "/"); + if path.starts_with('/') { + format!("file://{path}") + } else if path.as_bytes().get(1) == Some(&b':') { + // A Windows drive. + format!("file:///{path}") + } else { + path + } + }; + let mut out = String::with_capacity(url.len()); + for byte in url.bytes() { + if byte.is_ascii_alphanumeric() || b"-._~:/?#[]@!$&'()*+,;=%".contains(&byte) { + out.push(byte as char); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +/// Put the link annotations on their pages, and name the pages links reach +/// in the catalog's destination name tree. +pub(crate) fn install_links( + doc: &mut lopdf::Document, + annotations: Vec<(usize, [f32; 4], LinkAction)>, + destinations: Vec<(usize, String)>, +) { + use lopdf::{Dictionary, Object, StringFormat}; + let pages: Vec = doc.get_pages().into_values().collect(); + for (page, rect, action) in annotations { + let Some(&page_id) = pages.get(page) else { + continue; + }; + let annotation = doc.add_object(link_annotation(rect, &action)); + if let Ok(page) = doc.get_dictionary_mut(page_id) { + if !matches!(page.get(b"Annots"), Ok(Object::Array(_))) { + page.set("Annots", Object::Array(Vec::new())); + } + if let Ok(Object::Array(list)) = page.get_mut(b"Annots") { + list.push(Object::Reference(annotation)); + } + } + } + let mut names: Vec<(String, lopdf::ObjectId)> = destinations + .into_iter() + .filter_map(|(page, name)| Some((name, *pages.get(page)?))) + .collect(); + if names.is_empty() { + return; + } + // A name tree lists its keys in order. + names.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); + names.dedup_by(|a, b| a.0 == b.0); + let mut list = Vec::with_capacity(names.len() * 2); + for (name, page) in names { + list.push(Object::String(name.into_bytes(), StringFormat::Literal)); + list.push(Object::Array(vec![ + Object::Reference(page), + Object::Name(b"Fit".to_vec()), + ])); + } + let tree = Dictionary::from_iter([("Names", Object::Array(list))]); + if let Ok(catalog) = doc.catalog_mut() { + catalog.set( + "Names", + Dictionary::from_iter([("Dests", Object::Dictionary(tree))]), + ); + } +} + +/// A link annotation over `rect` (points) without a border, opening `action`. +pub(crate) fn link_annotation(rect: [f32; 4], action: &LinkAction) -> lopdf::Dictionary { + use lopdf::{Dictionary, Object, StringFormat}; + let action = match action { + LinkAction::Destination(name) => Dictionary::from_iter([ + ("S", Object::Name(b"GoTo".to_vec())), + ( + "D", + Object::String(name.clone().into_bytes(), StringFormat::Literal), + ), + ]), + LinkAction::Uri(uri) => Dictionary::from_iter([ + ("S", Object::Name(b"URI".to_vec())), + ( + "URI", + Object::String(uri.clone().into_bytes(), StringFormat::Literal), + ), + ]), + }; + Dictionary::from_iter([ + ("Type", Object::Name(b"Annot".to_vec())), + ("Subtype", Object::Name(b"Link".to_vec())), + ( + "Rect", + Object::Array(rect.iter().map(|&v| Object::Real(v)).collect()), + ), + ("Border", Object::Array(vec![0.into(), 0.into(), 0.into()])), + ("H", Object::Name(b"I".to_vec())), + ("A", Object::Dictionary(action)), + ]) +} + fn append_pdf_page( doc: &mut PdfDocument, image_resources: &mut std::collections::HashMap<(usize, u32, u32), printpdf::XObjectId>, @@ -599,6 +857,7 @@ fn append_pdf_page( group_splits, entity_layers, entity_plot_styles, + .. } = &page.content; let (paper_w, paper_h) = (page.paper_w as f32, page.paper_h as f32); let (ox, oy) = (page.offset_x, page.offset_y); @@ -4076,6 +4335,149 @@ mod tests { ); } + /// A page with a 20 × 10 mm rectangle plotted for object 31, at (30, 40). + fn linked_page() -> PdfPageInput { + let wire = PlotWire { + wire: WireModel::solid( + "31".into(), + vec![ + [30.0, 40.0, 0.0], + [50.0, 40.0, 0.0], + [50.0, 50.0, 0.0], + [30.0, 50.0, 0.0], + [30.0, 40.0, 0.0], + ], + [0.0, 0.0, 0.0, 1.0], + false, + ), + draw_depth: 0.0, + }; + let mut page = test_page(vec![wire]); + page.content.links = vec![ + crate::io::plot::PlotLink { + entity: Some(document::Handle::new(31)), + url: "https://example.org/a b".into(), + ..Default::default() + }, + // Plots nothing: its own area, opening a page of the file. + crate::io::plot::PlotLink { + entity: Some(document::Handle::new(32)), + bounds: Some([100.0, 100.0, 140.0, 110.0]), + url: "sheets/b.dwg".into(), + location: "A1".into(), + destination: Some("Sheet B".into()), + ..Default::default() + }, + // An address naming nothing and no page to open: no link. + crate::io::plot::PlotLink { + bounds: Some([0.0, 0.0, 10.0, 10.0]), + ..Default::default() + }, + ]; + page + } + + fn near(rect: [f32; 4], mm: [f64; 4]) -> bool { + rect.iter() + .zip(mm) + .all(|(got, mm)| (*got as f64 - mm * MM_TO_PT as f64).abs() < 0.01) + } + + /// A link covers its object's plotted ink, or its own area where it + /// plots none, and opens its address or a page of the file. + #[test] + fn links_cover_their_objects_and_open_their_targets() { + let annotations = page_link_annotations(&linked_page()); + assert_eq!(annotations.len(), 2); + assert!( + near(annotations[0].0, [30.0, 40.0, 50.0, 50.0]), + "{annotations:?}" + ); + assert_eq!( + annotations[0].1, + LinkAction::Uri("https://example.org/a%20b".into()) + ); + assert!(near(annotations[1].0, [100.0, 100.0, 140.0, 110.0])); + assert_eq!(annotations[1].1, LinkAction::Destination("Sheet B".into())); + + // A page turned a quarter: x' = width - y, y' = x. + let mut turned = linked_page(); + turned.rotation_deg = 90; + let annotations = page_link_annotations(&turned); + assert!(near( + annotations[0].0, + [210.0 - 50.0, 30.0, 210.0 - 40.0, 50.0] + )); + // A plot window leaves only what lies in it. + let mut windowed = linked_page(); + windowed.clip = Some((0.0, 0.0, 40.0, 297.0)); + let annotations = page_link_annotations(&windowed); + assert_eq!(annotations.len(), 1); + assert!(near(annotations[0].0, [30.0, 40.0, 40.0, 50.0])); + } + + /// The PDF carries the links as annotations, and names the pages links + /// reach. + #[test] + fn links_become_annotations_and_named_pages() { + let mut target = test_page(Vec::new()); + target.content.destination = Some("Sheet B".into()); + let bytes = render_pdf_bytes(&[linked_page(), target], None).unwrap(); + let doc = lopdf::Document::load_mem(&bytes).unwrap(); + let pages: Vec = doc.get_pages().into_values().collect(); + let page = doc.get_dictionary(pages[0]).unwrap(); + let annotations: Vec<&lopdf::Dictionary> = page + .get(b"Annots") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|a| doc.get_dictionary(a.as_reference().unwrap()).unwrap()) + .collect(); + assert_eq!(annotations.len(), 2); + let action = |index: usize| annotations[index].get(b"A").unwrap().as_dict().unwrap(); + assert_eq!(action(0).get(b"S").unwrap().as_name().unwrap(), b"URI"); + assert_eq!( + action(0).get(b"URI").unwrap().as_str().unwrap(), + b"https://example.org/a%20b" + ); + assert_eq!(action(1).get(b"S").unwrap().as_name().unwrap(), b"GoTo"); + assert_eq!(action(1).get(b"D").unwrap().as_str().unwrap(), b"Sheet B"); + let names = doc + .catalog() + .unwrap() + .get(b"Names") + .unwrap() + .as_dict() + .unwrap(); + let list = names + .get(b"Dests") + .unwrap() + .as_dict() + .unwrap() + .get(b"Names") + .unwrap() + .as_array() + .unwrap(); + assert_eq!(list[0].as_str().unwrap(), b"Sheet B"); + assert_eq!( + list[1].as_array().unwrap()[0].as_reference().unwrap(), + pages[1] + ); + // A page without links carries no annotations. + let annots = doc.get_dictionary(pages[1]).unwrap().get(b"Annots"); + assert!(annots.is_err() || annots.unwrap().as_array().unwrap().is_empty()); + } + + #[test] + fn link_addresses_become_uris() { + assert_eq!(link_uri("Blätter/a b.dwg", false), "Bl%C3%A4tter/a%20b.dwg"); + assert_eq!(link_uri("..\\x\\y.dwg", false), "../x/y.dwg"); + assert_eq!(link_uri("C:\\p\\y.dwg", false), "file:///C:/p/y.dwg"); + assert_eq!(link_uri("/p/y.dwg", false), "file:///p/y.dwg"); + assert_eq!(link_uri("mailto:a@b.de", true), "mailto:a@b.de"); + } + // Runs fully outside the export window never reach the content stream. #[test] fn clip_culls_runs_outside_the_export_window() { diff --git a/src/io/pdf_publish.rs b/src/io/pdf_publish.rs index 41b020586f..a2ec014625 100644 --- a/src/io/pdf_publish.rs +++ b/src/io/pdf_publish.rs @@ -29,6 +29,8 @@ pub struct PublishPdf { pages: Vec, /// Bookmark title and page of each sheet. bookmarks: Vec<(String, u32)>, + /// The pages links reach by name, and their names. + destinations: Vec<(String, u32)>, /// Optional-content group of each layer name, in first-seen order. layers: Vec, layer_ids: HashMap, u32>, @@ -50,6 +52,7 @@ impl PublishPdf { pages_id: 0, pages: Vec::new(), bookmarks: Vec::new(), + destinations: Vec::new(), layers: Vec::new(), layer_ids: HashMap::new(), }; @@ -65,8 +68,14 @@ impl PublishPdf { } /// Append every page of `doc` in order, the page at index `i` bookmarked - /// with `titles[i]`. Returns the number of pages appended. - pub fn append(&mut self, mut doc: lopdf::Document, titles: &[String]) -> Result { + /// with `titles[i]` and named `destinations[i]` for links that open it. + /// Returns the number of pages appended. + pub fn append( + &mut self, + mut doc: lopdf::Document, + titles: &[String], + destinations: &[Option], + ) -> Result { doc.compress(); let pages: Vec = doc.get_pages().into_values().collect(); // The drawing's layers: its optional-content groups by name. @@ -158,6 +167,9 @@ impl PublishPdf { if let Some(title) = titles.get(index) { self.bookmarks.push((title.clone(), number)); } + if let Some(Some(name)) = destinations.get(index) { + self.destinations.push((name.clone(), number)); + } } Ok(self.pages.len() - first_page) } @@ -191,6 +203,25 @@ impl PublishPdf { catalog.set("Outlines", Object::Reference((outlines, 0))); catalog.set("PageMode", Object::Name(b"UseOutlines".to_vec())); } + if !self.destinations.is_empty() { + // A name tree lists its keys in order; a name links to its first page. + let mut names = std::mem::take(&mut self.destinations); + names.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes())); + names.dedup_by(|a, b| a.0 == b.0); + let mut list = Vec::with_capacity(names.len() * 2); + for (name, page) in names { + list.push(Object::String(name.into_bytes(), StringFormat::Literal)); + list.push(Object::Array(vec![ + Object::Reference((page, 0)), + Object::Name(b"Fit".to_vec()), + ])); + } + let tree = Dictionary::from_iter([("Names", Object::Array(list))]); + catalog.set( + "Names", + Dictionary::from_iter([("Dests", Object::Dictionary(tree))]), + ); + } if !self.layers.is_empty() { let groups: Vec = self .layers @@ -576,14 +607,19 @@ mod tests { let path = dir.join("set.pdf"); let mut pdf = PublishPdf::create(&path).unwrap(); assert_eq!( - pdf.append(sheet(1191, 842, &["0", "Walls"]), &["0001 - A3".into()]) - .unwrap(), + pdf.append( + sheet(1191, 842, &["0", "Walls"]), + &["0001 - A3".into()], + &[] + ) + .unwrap(), 1 ); assert_eq!( pdf.append( sheet(842, 595, &["Walls", "Doors"]), - &["0002 - Übersicht".into()] + &["0002 - Übersicht".into()], + &[Some("Sheet 2".into())] ) .unwrap(), 1 @@ -635,6 +671,17 @@ mod tests { ] ); + // Links open the second sheet by its name. + let names = catalog.get(b"Names").unwrap().as_dict().unwrap(); + let dests = names.get(b"Dests").unwrap().as_dict().unwrap(); + let list = dests.get(b"Names").unwrap().as_array().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].as_str().unwrap(), b"Sheet 2"); + assert_eq!( + list[1].as_array().unwrap()[0].as_reference().unwrap(), + pages[1] + ); + // "Walls" is one group for both sheets; each page's properties name // groups the catalog lists. let properties = catalog.get(b"OCProperties").unwrap().as_dict().unwrap(); @@ -688,12 +735,13 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("set.pdf"); let mut pdf = PublishPdf::create(&path).unwrap(); - pdf.append(sheet(100, 100, &[]), &[]).unwrap(); + pdf.append(sheet(100, 100, &[]), &[], &[]).unwrap(); drop(pdf); assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); let mut pdf = PublishPdf::create(&path).unwrap(); - pdf.append(sheet(100, 100, &["0"]), &["x".into()]).unwrap(); + pdf.append(sheet(100, 100, &["0"]), &["x".into()], &[]) + .unwrap(); pdf.finish("Set", false).unwrap(); let doc = lopdf::Document::load(&path).unwrap(); assert!(doc.catalog().unwrap().get(b"Outlines").is_err()); diff --git a/src/io/plot.rs b/src/io/plot.rs index ef65f3ab89..c1ce5407b9 100644 --- a/src/io/plot.rs +++ b/src/io/plot.rs @@ -167,6 +167,91 @@ pub struct PlotContent { /// Effective STB style keyed by the plotted object and optional block member. pub entity_plot_styles: std::collections::HashMap<(document::Handle, Option), String>, + /// The hyperlinks of the plotted objects, for formats that carry links. + pub links: Vec, + /// The name links reach this page by, when a page of the same file is + /// their target (a named destination of the PDF). + pub destination: Option, +} + +/// A hyperlink on a plotted object. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PlotLink { + /// The object the link sits on: its plotted geometry is the link's area. + pub entity: Option, + /// The area in drawing coordinates (`[x0, y0, x1, y1]`) where the object + /// plots nothing, such as a text of spaces. + pub bounds: Option<[f64; 4]>, + /// The address as stored: a web address, a file, or empty for the + /// drawing itself. + pub url: String, + /// The named location: a layout or a view. + pub location: String, + /// The folder a relative file address is taken from. + pub base: Option, + /// A page of the same file the link opens (its `destination`), when the + /// target is one of the pages written with it. + pub destination: Option, +} + +impl PlotLink { + /// A web, mail or other address with a scheme, not a file. + pub fn is_web(&self) -> bool { + let url = self.url.trim(); + let scheme = url.split_once(':').map(|(scheme, _)| scheme).unwrap_or(""); + // `C:` is a drive, not a scheme. + scheme.len() > 1 + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + } + + /// The drawing a file link opens: its address taken from `base` when + /// relative, the drawing `own` for an empty address. `None` for a web + /// address. + #[cfg(not(target_arch = "wasm32"))] + pub fn drawing(&self, own: Option<&std::path::Path>) -> Option { + let url = self.url.trim().trim_matches('"'); + if url.is_empty() { + return own.map(std::path::Path::to_path_buf); + } + if self.is_web() && !url.to_ascii_lowercase().starts_with("file:") { + return None; + } + let url = url + .strip_prefix("file:///") + .map(|rest| { + if cfg!(windows) { + rest.to_string() + } else { + format!("/{rest}") + } + }) + .unwrap_or_else(|| url.to_string()); + let mut path = std::path::PathBuf::from(&url); + let base = self.base.clone().unwrap_or_default(); + // A link written on Windows names its folders with backslashes. + #[cfg(not(windows))] + if url.contains('\\') && !base.join(&path).exists() { + path = std::path::PathBuf::from(url.replace('\\', "/")); + } + if path.is_relative() { + path = base.join(path); + } + Some(std::fs::canonicalize(&path).unwrap_or(path)) + } + + /// The layouts the named location can mean: the whole location, and the + /// layout of a `view,layout` pair. + pub fn layout_candidates(&self) -> Vec<&str> { + let location = self.location.trim(); + let mut names = vec![location]; + if let Some((_, layout)) = location.rsplit_once(',') { + names.push(layout.trim()); + } + names.retain(|name| !name.is_empty()); + names + } } /// Owned geometry and settings for one plot page.