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] 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")),