diff --git a/assets/locales/pending/drawing-export-window.json b/assets/locales/pending/drawing-export-window.json new file mode 100644 index 00000000000..9a8a19bf3e4 --- /dev/null +++ b/assets/locales/pending/drawing-export-window.json @@ -0,0 +1,433 @@ +{ + "en": { + "help.drawing.export": "Writes sheets of the open drawing to SVG or PNG files, on white or blue paper. Use it to share or print a drawing.", + "ui.drawing_export.as_last_were_one": "1 view on {sheet} was written as it last was.", + "ui.drawing_export.as_last_were_other": "{count} views on {sheet} were written as they last were.", + "ui.drawing_export.close": "Close Export Drawing", + "ui.drawing_export.colour": "Color", + "ui.drawing_export.colour_black_white": "Black and white", + "ui.drawing_export.colour_blue": "A blue paper is always in color.", + "ui.drawing_export.colour_grey": "Grayscale", + "ui.drawing_export.colour_rgb": "Color", + "ui.drawing_export.colour_transparent": "Transparent", + "ui.drawing_export.dimensions_one": "1 dimension on {sheet} isn't drawn: {why}", + "ui.drawing_export.dimensions_other": "{count} dimensions on {sheet} aren't drawn. The first: {why}", + "ui.drawing_export.dpi_note": "Uses each sheet's own picture setting unless you change it here.", + "ui.drawing_export.dpi_reset": "Use each sheet's own", + "ui.drawing_export.dpi_set": "Every chosen sheet uses this resolution.", + "ui.drawing_export.exporting": "Exporting…", + "ui.drawing_export.failed": "{sheet} wasn't exported: {error}", + "ui.drawing_export.files": "Files: {files}. A file of the same name is replaced.", + "ui.drawing_export.folder": "Folder", + "ui.drawing_export.folder_choose": "Choose when exporting", + "ui.drawing_export.folder_design": "Same as the design", + "ui.drawing_export.folder_unsaved": "Save the design first to export next to it.", + "ui.drawing_export.format": "Format", + "ui.drawing_export.no_sheet": "Choose at least one sheet.", + "ui.drawing_export.out_of_date_one": "1 view is out of date.", + "ui.drawing_export.out_of_date_other": "{count} views are out of date.", + "ui.drawing_export.output": "Output", + "ui.drawing_export.paper": "Paper", + "ui.drawing_export.paper_blueprint": "Blueprint", + "ui.drawing_export.paper_info": "The paper is chosen here. It doesn't follow the sheet color you work with.", + "ui.drawing_export.paper_note": "Blue papers draw light lines and text, in SVG and PNG. A blueprint theme starts here on the matching blue.", + "ui.drawing_export.paper_prussian_blue": "Prussian Blue", + "ui.drawing_export.paper_white": "White", + "ui.drawing_export.planned": "Planned: not available yet", + "ui.drawing_export.refused": "{sheet} wasn't exported: {view} can't be drawn ({reason}).", + "ui.drawing_export.resolution": "Resolution", + "ui.drawing_export.saved": "Saved {sheet} to {path}", + "ui.drawing_export.several": "Each sheet is its own file, named after its sheet.", + "ui.drawing_export.sheets": "Sheets", + "ui.drawing_export.stopped": "the export stopped before it finished", + "ui.drawing_export.stopping": "Stopping…", + "ui.drawing_export.title": "Export Drawing", + "ui.drawing_export.view_back": "Back view", + "ui.drawing_export.view_bottom": "Bottom view", + "ui.drawing_export.view_failed": "{view} can't be drawn, so {sheet} won't export: {reason}", + "ui.drawing_export.view_front": "Front view", + "ui.drawing_export.view_iso": "Isometric view", + "ui.drawing_export.view_left": "Left view", + "ui.drawing_export.view_number": "View {number}", + "ui.drawing_export.view_right": "Right view", + "ui.drawing_export.view_top": "Top view" + }, + "en-GB": { + "ui.drawing_export.colour": "Colour", + "ui.drawing_export.colour_blue": "A blue paper is always in colour.", + "ui.drawing_export.colour_grey": "Greyscale", + "ui.drawing_export.colour_rgb": "Colour", + "ui.drawing_export.paper_info": "The paper is chosen here. It doesn't follow the sheet colour you work with." + }, + "ar": { + "help.drawing.export": "يكتب أوراق الرسم المفتوح في ملفات SVG أو PNG، على ورق أبيض أو أزرق. استخدمه لمشاركة رسم أو طباعته.", + "ui.drawing_export.as_last_were_one": "كُتب منظر واحد في {sheet} كما كان آخر مرة.", + "ui.drawing_export.as_last_were_other": "كُتبت {count} مناظر في {sheet} كما كانت آخر مرة.", + "ui.drawing_export.close": "إغلاق تصدير الرسم", + "ui.drawing_export.colour": "اللون", + "ui.drawing_export.colour_black_white": "أبيض وأسود", + "ui.drawing_export.colour_blue": "الورق الأزرق ملوّن دائمًا.", + "ui.drawing_export.colour_grey": "تدرّج رمادي", + "ui.drawing_export.colour_rgb": "ملوّن", + "ui.drawing_export.colour_transparent": "شفاف", + "ui.drawing_export.dimensions_one": "بُعد واحد في {sheet} غير مرسوم: {why}", + "ui.drawing_export.dimensions_other": "{count} أبعاد في {sheet} غير مرسومة. الأول: {why}", + "ui.drawing_export.dpi_note": "يستخدم إعداد الصورة الخاص بكل ورقة ما لم تغيّره هنا.", + "ui.drawing_export.dpi_reset": "استخدام إعداد كل ورقة", + "ui.drawing_export.dpi_set": "كل ورقة مختارة تستخدم هذه الدقة.", + "ui.drawing_export.exporting": "جارٍ التصدير…", + "ui.drawing_export.failed": "لم تُصدَّر {sheet}: {error}", + "ui.drawing_export.files": "الملفات: {files}. يُستبدل الملف الذي يحمل الاسم نفسه.", + "ui.drawing_export.folder": "المجلد", + "ui.drawing_export.folder_choose": "الاختيار عند التصدير", + "ui.drawing_export.folder_design": "مجلد التصميم نفسه", + "ui.drawing_export.folder_unsaved": "احفظ التصميم أولًا للتصدير بجانبه.", + "ui.drawing_export.format": "التنسيق", + "ui.drawing_export.no_sheet": "اختر ورقة واحدة على الأقل.", + "ui.drawing_export.out_of_date_one": "منظر واحد قديم.", + "ui.drawing_export.out_of_date_other": "{count} مناظر قديمة.", + "ui.drawing_export.output": "الإخراج", + "ui.drawing_export.paper": "الورق", + "ui.drawing_export.paper_blueprint": "مخطط أزرق", + "ui.drawing_export.paper_info": "يُختار الورق هنا. لا يتبع لون الورقة الذي تعمل به.", + "ui.drawing_export.paper_note": "يرسم الورق الأزرق خطوطًا ونصوصًا فاتحة، في SVG وPNG. في سمة المخطط الأزرق يبدأ هذا الخيار باللون الأزرق المطابق.", + "ui.drawing_export.paper_prussian_blue": "الأزرق البروسي", + "ui.drawing_export.paper_white": "أبيض", + "ui.drawing_export.planned": "مخطط له: غير متاح بعد", + "ui.drawing_export.refused": "لم تُصدَّر {sheet}: تعذّر رسم {view} ({reason}).", + "ui.drawing_export.resolution": "الدقة", + "ui.drawing_export.saved": "حُفظت {sheet} في {path}", + "ui.drawing_export.several": "كل ورقة ملف مستقل يحمل اسمها.", + "ui.drawing_export.sheets": "الأوراق", + "ui.drawing_export.stopped": "توقف التصدير قبل أن ينتهي", + "ui.drawing_export.stopping": "جارٍ الإيقاف…", + "ui.drawing_export.title": "تصدير الرسم", + "ui.drawing_export.view_back": "المنظر الخلفي", + "ui.drawing_export.view_bottom": "المنظر السفلي", + "ui.drawing_export.view_failed": "تعذّر رسم {view}، لذلك لن تُصدَّر {sheet}: {reason}", + "ui.drawing_export.view_front": "المنظر الأمامي", + "ui.drawing_export.view_iso": "منظر متساوي القياس", + "ui.drawing_export.view_left": "المنظر الأيسر", + "ui.drawing_export.view_number": "المنظر {number}", + "ui.drawing_export.view_right": "المنظر الأيمن", + "ui.drawing_export.view_top": "المنظر العلوي" + }, + "de": { + "help.drawing.export": "Schreibt Blätter der geöffneten Zeichnung als SVG- oder PNG-Dateien, auf weißem oder blauem Papier. Damit geben Sie eine Zeichnung weiter oder drucken sie.", + "ui.drawing_export.as_last_were_one": "1 Ansicht auf {sheet} wurde im letzten Stand geschrieben.", + "ui.drawing_export.as_last_were_other": "{count} Ansichten auf {sheet} wurden im letzten Stand geschrieben.", + "ui.drawing_export.close": "Zeichnung exportieren schließen", + "ui.drawing_export.colour": "Farbe", + "ui.drawing_export.colour_black_white": "Schwarzweiß", + "ui.drawing_export.colour_blue": "Blaues Papier ist immer farbig.", + "ui.drawing_export.colour_grey": "Graustufen", + "ui.drawing_export.colour_rgb": "Farbe", + "ui.drawing_export.colour_transparent": "Transparent", + "ui.drawing_export.dimensions_one": "1 Bemaßung auf {sheet} wird nicht gezeichnet: {why}", + "ui.drawing_export.dimensions_other": "{count} Bemaßungen auf {sheet} werden nicht gezeichnet. Die erste: {why}", + "ui.drawing_export.dpi_note": "Verwendet die Bildeinstellung jedes Blatts, sofern Sie sie hier nicht ändern.", + "ui.drawing_export.dpi_reset": "Einstellung jedes Blatts verwenden", + "ui.drawing_export.dpi_set": "Jedes gewählte Blatt verwendet diese Auflösung.", + "ui.drawing_export.exporting": "Wird exportiert…", + "ui.drawing_export.failed": "{sheet} wurde nicht exportiert: {error}", + "ui.drawing_export.files": "Dateien: {files}. Eine gleichnamige Datei wird ersetzt.", + "ui.drawing_export.folder": "Ordner", + "ui.drawing_export.folder_choose": "Beim Exportieren wählen", + "ui.drawing_export.folder_design": "Wie die Konstruktion", + "ui.drawing_export.folder_unsaved": "Speichern Sie die Konstruktion zuerst, um daneben zu exportieren.", + "ui.drawing_export.format": "Format", + "ui.drawing_export.no_sheet": "Wählen Sie mindestens ein Blatt.", + "ui.drawing_export.out_of_date_one": "1 Ansicht ist veraltet.", + "ui.drawing_export.out_of_date_other": "{count} Ansichten sind veraltet.", + "ui.drawing_export.output": "Ausgabe", + "ui.drawing_export.paper": "Papier", + "ui.drawing_export.paper_blueprint": "Blaupause", + "ui.drawing_export.paper_info": "Das Papier wird hier gewählt. Es folgt nicht der Blattfarbe, mit der Sie arbeiten.", + "ui.drawing_export.paper_note": "Blaue Papiere zeichnen helle Linien und Texte, in SVG und PNG. Ein Blaupausen-Design beginnt hier mit dem passenden Blau.", + "ui.drawing_export.paper_prussian_blue": "Preußischblau", + "ui.drawing_export.paper_white": "Weiß", + "ui.drawing_export.planned": "Geplant: noch nicht verfügbar", + "ui.drawing_export.refused": "{sheet} wurde nicht exportiert: {view} kann nicht gezeichnet werden ({reason}).", + "ui.drawing_export.resolution": "Auflösung", + "ui.drawing_export.saved": "{sheet} gespeichert unter {path}", + "ui.drawing_export.several": "Jedes Blatt wird eine eigene Datei, benannt nach dem Blatt.", + "ui.drawing_export.sheets": "Blätter", + "ui.drawing_export.stopped": "der Export wurde vor dem Ende abgebrochen", + "ui.drawing_export.stopping": "Wird abgebrochen…", + "ui.drawing_export.title": "Zeichnung exportieren", + "ui.drawing_export.view_back": "Rückansicht", + "ui.drawing_export.view_bottom": "Untenansicht", + "ui.drawing_export.view_failed": "{view} kann nicht gezeichnet werden, daher wird {sheet} nicht exportiert: {reason}", + "ui.drawing_export.view_front": "Vorderansicht", + "ui.drawing_export.view_iso": "Isometrische Ansicht", + "ui.drawing_export.view_left": "Linke Seitenansicht", + "ui.drawing_export.view_number": "Ansicht {number}", + "ui.drawing_export.view_right": "Rechte Seitenansicht", + "ui.drawing_export.view_top": "Draufsicht" + }, + "he": { + "help.drawing.export": "כותב גיליונות של השרטוט הפתוח לקובצי SVG או PNG, על נייר לבן או כחול. השתמשו בכך כדי לשתף או להדפיס שרטוט.", + "ui.drawing_export.as_last_were_one": "מבט אחד ב-{sheet} נכתב כפי שהיה לאחרונה.", + "ui.drawing_export.as_last_were_other": "{count} מבטים ב-{sheet} נכתבו כפי שהיו לאחרונה.", + "ui.drawing_export.close": "סגירת ייצוא שרטוט", + "ui.drawing_export.colour": "צבע", + "ui.drawing_export.colour_black_white": "שחור-לבן", + "ui.drawing_export.colour_blue": "נייר כחול הוא תמיד בצבע.", + "ui.drawing_export.colour_grey": "גווני אפור", + "ui.drawing_export.colour_rgb": "צבע", + "ui.drawing_export.colour_transparent": "שקוף", + "ui.drawing_export.dimensions_one": "מידה אחת ב-{sheet} לא שורטטה: {why}", + "ui.drawing_export.dimensions_other": "{count} מידות ב-{sheet} לא שורטטו. הראשונה: {why}", + "ui.drawing_export.dpi_note": "משתמש בהגדרת התמונה של כל גיליון, אלא אם תשנו אותה כאן.", + "ui.drawing_export.dpi_reset": "שימוש בהגדרה של כל גיליון", + "ui.drawing_export.dpi_set": "כל גיליון שנבחר משתמש ברזולוציה זו.", + "ui.drawing_export.exporting": "מייצא…", + "ui.drawing_export.failed": "{sheet} לא יוצא: {error}", + "ui.drawing_export.files": "קבצים: {files}. קובץ באותו שם יוחלף.", + "ui.drawing_export.folder": "תיקייה", + "ui.drawing_export.folder_choose": "בחירה בעת הייצוא", + "ui.drawing_export.folder_design": "כמו התכן", + "ui.drawing_export.folder_unsaved": "שמרו קודם את התכן כדי לייצא לצידו.", + "ui.drawing_export.format": "תבנית", + "ui.drawing_export.no_sheet": "בחרו לפחות גיליון אחד.", + "ui.drawing_export.out_of_date_one": "מבט אחד אינו מעודכן.", + "ui.drawing_export.out_of_date_other": "{count} מבטים אינם מעודכנים.", + "ui.drawing_export.output": "פלט", + "ui.drawing_export.paper": "נייר", + "ui.drawing_export.paper_blueprint": "שרטוט כחול", + "ui.drawing_export.paper_info": "הנייר נבחר כאן. הוא אינו עוקב אחר צבע הגיליון שבו אתם עובדים.", + "ui.drawing_export.paper_note": "ניירות כחולים משרטטים קווים וטקסט בהירים, ב-SVG וב-PNG. בערכת נושא של שרטוט כחול הבחירה כאן מתחילה בכחול המתאים.", + "ui.drawing_export.paper_prussian_blue": "כחול פרוסי", + "ui.drawing_export.paper_white": "לבן", + "ui.drawing_export.planned": "מתוכנן: עדיין לא זמין", + "ui.drawing_export.refused": "{sheet} לא יוצא: לא ניתן לשרטט את {view} ({reason}).", + "ui.drawing_export.resolution": "רזולוציה", + "ui.drawing_export.saved": "{sheet} נשמר ב-{path}", + "ui.drawing_export.several": "כל גיליון הוא קובץ נפרד, הנקרא על שם הגיליון.", + "ui.drawing_export.sheets": "גיליונות", + "ui.drawing_export.stopped": "הייצוא נעצר לפני שהסתיים", + "ui.drawing_export.stopping": "עוצר…", + "ui.drawing_export.title": "ייצוא שרטוט", + "ui.drawing_export.view_back": "מבט מאחור", + "ui.drawing_export.view_bottom": "מבט מלמטה", + "ui.drawing_export.view_failed": "לא ניתן לשרטט את {view}, ולכן {sheet} לא ייוצא: {reason}", + "ui.drawing_export.view_front": "מבט חזית", + "ui.drawing_export.view_iso": "מבט איזומטרי", + "ui.drawing_export.view_left": "מבט משמאל", + "ui.drawing_export.view_number": "מבט {number}", + "ui.drawing_export.view_right": "מבט מימין", + "ui.drawing_export.view_top": "מבט על" + }, + "ja": { + "help.drawing.export": "開いている図面のシートを白または青の用紙で SVG または PNG ファイルに書き出します。図面を共有したり印刷したりするときに使います。", + "ui.drawing_export.as_last_were_one": "{sheet} のビュー 1 個は前回の状態で書き出されました。", + "ui.drawing_export.as_last_were_other": "{sheet} のビュー {count} 個は前回の状態で書き出されました。", + "ui.drawing_export.close": "図面の書き出しを閉じる", + "ui.drawing_export.colour": "色", + "ui.drawing_export.colour_black_white": "白黒", + "ui.drawing_export.colour_blue": "青い用紙は常にカラーです。", + "ui.drawing_export.colour_grey": "グレースケール", + "ui.drawing_export.colour_rgb": "カラー", + "ui.drawing_export.colour_transparent": "透明", + "ui.drawing_export.dimensions_one": "{sheet} の寸法 1 個が描かれていません: {why}", + "ui.drawing_export.dimensions_other": "{sheet} の寸法 {count} 個が描かれていません。最初の理由: {why}", + "ui.drawing_export.dpi_note": "ここで変更しない限り、各シートの画像設定を使います。", + "ui.drawing_export.dpi_reset": "各シートの設定を使う", + "ui.drawing_export.dpi_set": "選んだすべてのシートがこの解像度を使います。", + "ui.drawing_export.exporting": "書き出し中…", + "ui.drawing_export.failed": "{sheet} は書き出されませんでした: {error}", + "ui.drawing_export.files": "ファイル: {files}。同じ名前のファイルは置き換えられます。", + "ui.drawing_export.folder": "フォルダー", + "ui.drawing_export.folder_choose": "書き出し時に選ぶ", + "ui.drawing_export.folder_design": "デザインと同じ", + "ui.drawing_export.folder_unsaved": "デザインの横に書き出すには、先にデザインを保存してください。", + "ui.drawing_export.format": "形式", + "ui.drawing_export.no_sheet": "シートを 1 つ以上選んでください。", + "ui.drawing_export.out_of_date_one": "1 個のビューが古くなっています。", + "ui.drawing_export.out_of_date_other": "{count} 個のビューが古くなっています。", + "ui.drawing_export.output": "出力", + "ui.drawing_export.paper": "用紙", + "ui.drawing_export.paper_blueprint": "青焼き", + "ui.drawing_export.paper_info": "用紙はここで選びます。作業中のシートの色には従いません。", + "ui.drawing_export.paper_note": "青い用紙では、SVG と PNG のどちらでも線と文字が明るく描かれます。青焼きテーマでは、ここは対応する青から始まります。", + "ui.drawing_export.paper_prussian_blue": "プルシアンブルー", + "ui.drawing_export.paper_white": "白", + "ui.drawing_export.planned": "予定: まだ使えません", + "ui.drawing_export.refused": "{sheet} は書き出されませんでした: {view} を描けません ({reason})。", + "ui.drawing_export.resolution": "解像度", + "ui.drawing_export.saved": "{sheet} を {path} に保存しました", + "ui.drawing_export.several": "シートごとに、そのシート名のファイルになります。", + "ui.drawing_export.sheets": "シート", + "ui.drawing_export.stopped": "書き出しが終わる前に止まりました", + "ui.drawing_export.stopping": "停止しています…", + "ui.drawing_export.title": "図面の書き出し", + "ui.drawing_export.view_back": "背面図", + "ui.drawing_export.view_bottom": "下面図", + "ui.drawing_export.view_failed": "{view} を描けないため、{sheet} は書き出されません: {reason}", + "ui.drawing_export.view_front": "正面図", + "ui.drawing_export.view_iso": "等角図", + "ui.drawing_export.view_left": "左側面図", + "ui.drawing_export.view_number": "ビュー {number}", + "ui.drawing_export.view_right": "右側面図", + "ui.drawing_export.view_top": "平面図" + }, + "ko": { + "help.drawing.export": "열린 도면의 시트를 흰색 또는 파란색 용지에 SVG나 PNG 파일로 씁니다. 도면을 공유하거나 인쇄할 때 사용합니다.", + "ui.drawing_export.as_last_were_one": "{sheet}의 뷰 1개가 마지막 상태로 기록되었습니다.", + "ui.drawing_export.as_last_were_other": "{sheet}의 뷰 {count}개가 마지막 상태로 기록되었습니다.", + "ui.drawing_export.close": "도면 내보내기 닫기", + "ui.drawing_export.colour": "색상", + "ui.drawing_export.colour_black_white": "흑백", + "ui.drawing_export.colour_blue": "파란색 용지는 항상 컬러입니다.", + "ui.drawing_export.colour_grey": "회색조", + "ui.drawing_export.colour_rgb": "컬러", + "ui.drawing_export.colour_transparent": "투명", + "ui.drawing_export.dimensions_one": "{sheet}의 치수 1개가 그려지지 않았습니다: {why}", + "ui.drawing_export.dimensions_other": "{sheet}의 치수 {count}개가 그려지지 않았습니다. 첫 번째: {why}", + "ui.drawing_export.dpi_note": "여기서 바꾸지 않으면 각 시트의 그림 설정을 사용합니다.", + "ui.drawing_export.dpi_reset": "각 시트의 설정 사용", + "ui.drawing_export.dpi_set": "선택한 모든 시트가 이 해상도를 사용합니다.", + "ui.drawing_export.exporting": "내보내는 중…", + "ui.drawing_export.failed": "{sheet}을(를) 내보내지 못했습니다: {error}", + "ui.drawing_export.files": "파일: {files}. 같은 이름의 파일은 대체됩니다.", + "ui.drawing_export.folder": "폴더", + "ui.drawing_export.folder_choose": "내보낼 때 선택", + "ui.drawing_export.folder_design": "디자인과 같은 폴더", + "ui.drawing_export.folder_unsaved": "디자인 옆에 내보내려면 먼저 디자인을 저장하세요.", + "ui.drawing_export.format": "형식", + "ui.drawing_export.no_sheet": "시트를 하나 이상 선택하세요.", + "ui.drawing_export.out_of_date_one": "뷰 1개가 최신이 아닙니다.", + "ui.drawing_export.out_of_date_other": "뷰 {count}개가 최신이 아닙니다.", + "ui.drawing_export.output": "출력", + "ui.drawing_export.paper": "용지", + "ui.drawing_export.paper_blueprint": "청사진", + "ui.drawing_export.paper_info": "용지는 여기서 선택합니다. 작업 중인 시트 색상을 따르지 않습니다.", + "ui.drawing_export.paper_note": "파란색 용지는 SVG와 PNG 모두에서 선과 글자를 밝게 그립니다. 청사진 테마에서는 이곳이 같은 파란색으로 시작합니다.", + "ui.drawing_export.paper_prussian_blue": "프러시안 블루", + "ui.drawing_export.paper_white": "흰색", + "ui.drawing_export.planned": "예정: 아직 사용할 수 없음", + "ui.drawing_export.refused": "{sheet}을(를) 내보내지 못했습니다: {view}을(를) 그릴 수 없습니다 ({reason}).", + "ui.drawing_export.resolution": "해상도", + "ui.drawing_export.saved": "{sheet}을(를) {path}에 저장했습니다", + "ui.drawing_export.several": "각 시트는 시트 이름을 딴 별도의 파일이 됩니다.", + "ui.drawing_export.sheets": "시트", + "ui.drawing_export.stopped": "내보내기가 끝나기 전에 중단되었습니다", + "ui.drawing_export.stopping": "중지하는 중…", + "ui.drawing_export.title": "도면 내보내기", + "ui.drawing_export.view_back": "배면도", + "ui.drawing_export.view_bottom": "저면도", + "ui.drawing_export.view_failed": "{view}을(를) 그릴 수 없어 {sheet}은(는) 내보내지 않습니다: {reason}", + "ui.drawing_export.view_front": "정면도", + "ui.drawing_export.view_iso": "등각 뷰", + "ui.drawing_export.view_left": "좌측면도", + "ui.drawing_export.view_number": "뷰 {number}", + "ui.drawing_export.view_right": "우측면도", + "ui.drawing_export.view_top": "평면도" + }, + "vi": { + "help.drawing.export": "Ghi các tờ của bản vẽ đang mở thành tệp SVG hoặc PNG, trên giấy trắng hoặc xanh. Dùng để chia sẻ hoặc in bản vẽ.", + "ui.drawing_export.as_last_were_one": "1 hình chiếu trên {sheet} được ghi như lần cuối.", + "ui.drawing_export.as_last_were_other": "{count} hình chiếu trên {sheet} được ghi như lần cuối.", + "ui.drawing_export.close": "Đóng Xuất bản vẽ", + "ui.drawing_export.colour": "Màu", + "ui.drawing_export.colour_black_white": "Đen trắng", + "ui.drawing_export.colour_blue": "Giấy xanh luôn có màu.", + "ui.drawing_export.colour_grey": "Thang xám", + "ui.drawing_export.colour_rgb": "Màu", + "ui.drawing_export.colour_transparent": "Trong suốt", + "ui.drawing_export.dimensions_one": "1 kích thước trên {sheet} không được vẽ: {why}", + "ui.drawing_export.dimensions_other": "{count} kích thước trên {sheet} không được vẽ. Cái đầu tiên: {why}", + "ui.drawing_export.dpi_note": "Dùng thiết lập hình ảnh riêng của mỗi tờ, trừ khi bạn đổi ở đây.", + "ui.drawing_export.dpi_reset": "Dùng thiết lập riêng của mỗi tờ", + "ui.drawing_export.dpi_set": "Mọi tờ đã chọn dùng độ phân giải này.", + "ui.drawing_export.exporting": "Đang xuất…", + "ui.drawing_export.failed": "{sheet} chưa được xuất: {error}", + "ui.drawing_export.files": "Tệp: {files}. Tệp cùng tên sẽ bị thay thế.", + "ui.drawing_export.folder": "Thư mục", + "ui.drawing_export.folder_choose": "Chọn khi xuất", + "ui.drawing_export.folder_design": "Giống thiết kế", + "ui.drawing_export.folder_unsaved": "Hãy lưu thiết kế trước để xuất cạnh nó.", + "ui.drawing_export.format": "Định dạng", + "ui.drawing_export.no_sheet": "Chọn ít nhất một tờ.", + "ui.drawing_export.out_of_date_one": "1 hình chiếu đã cũ.", + "ui.drawing_export.out_of_date_other": "{count} hình chiếu đã cũ.", + "ui.drawing_export.output": "Đầu ra", + "ui.drawing_export.paper": "Giấy", + "ui.drawing_export.paper_blueprint": "Bản in xanh", + "ui.drawing_export.paper_info": "Giấy được chọn ở đây. Nó không theo màu tờ bạn đang làm việc.", + "ui.drawing_export.paper_note": "Giấy xanh vẽ đường và chữ sáng màu, trong SVG và PNG. Với chủ đề bản in xanh, lựa chọn ở đây bắt đầu bằng màu xanh tương ứng.", + "ui.drawing_export.paper_prussian_blue": "Xanh Phổ", + "ui.drawing_export.paper_white": "Trắng", + "ui.drawing_export.planned": "Dự kiến: chưa có", + "ui.drawing_export.refused": "{sheet} chưa được xuất: không vẽ được {view} ({reason}).", + "ui.drawing_export.resolution": "Độ phân giải", + "ui.drawing_export.saved": "Đã lưu {sheet} vào {path}", + "ui.drawing_export.several": "Mỗi tờ là một tệp riêng, đặt theo tên tờ.", + "ui.drawing_export.sheets": "Tờ", + "ui.drawing_export.stopped": "việc xuất đã dừng trước khi xong", + "ui.drawing_export.stopping": "Đang dừng…", + "ui.drawing_export.title": "Xuất bản vẽ", + "ui.drawing_export.view_back": "Hình chiếu sau", + "ui.drawing_export.view_bottom": "Hình chiếu dưới", + "ui.drawing_export.view_failed": "Không vẽ được {view}, nên {sheet} sẽ không được xuất: {reason}", + "ui.drawing_export.view_front": "Hình chiếu đứng", + "ui.drawing_export.view_iso": "Hình chiếu trục đo", + "ui.drawing_export.view_left": "Hình chiếu trái", + "ui.drawing_export.view_number": "Hình chiếu {number}", + "ui.drawing_export.view_right": "Hình chiếu phải", + "ui.drawing_export.view_top": "Hình chiếu bằng" + }, + "zh": { + "help.drawing.export": "将打开的图纸中的图纸页以白色或蓝色纸张写成 SVG 或 PNG 文件。用于分享或打印图纸。", + "ui.drawing_export.as_last_were_one": "{sheet} 上的 1 个视图按上次的状态写出。", + "ui.drawing_export.as_last_were_other": "{sheet} 上的 {count} 个视图按上次的状态写出。", + "ui.drawing_export.close": "关闭导出图纸", + "ui.drawing_export.colour": "颜色", + "ui.drawing_export.colour_black_white": "黑白", + "ui.drawing_export.colour_blue": "蓝色纸张始终为彩色。", + "ui.drawing_export.colour_grey": "灰度", + "ui.drawing_export.colour_rgb": "彩色", + "ui.drawing_export.colour_transparent": "透明", + "ui.drawing_export.dimensions_one": "{sheet} 上有 1 个尺寸未绘制:{why}", + "ui.drawing_export.dimensions_other": "{sheet} 上有 {count} 个尺寸未绘制。第一个:{why}", + "ui.drawing_export.dpi_note": "除非在此更改,否则使用每张图纸页自己的图像设置。", + "ui.drawing_export.dpi_reset": "使用每张图纸页自己的设置", + "ui.drawing_export.dpi_set": "所有选中的图纸页都使用此分辨率。", + "ui.drawing_export.exporting": "正在导出…", + "ui.drawing_export.failed": "{sheet} 未导出:{error}", + "ui.drawing_export.files": "文件:{files}。同名文件将被替换。", + "ui.drawing_export.folder": "文件夹", + "ui.drawing_export.folder_choose": "导出时选择", + "ui.drawing_export.folder_design": "与设计相同", + "ui.drawing_export.folder_unsaved": "请先保存设计,才能导出到它旁边。", + "ui.drawing_export.format": "格式", + "ui.drawing_export.no_sheet": "请至少选择一张图纸页。", + "ui.drawing_export.out_of_date_one": "1 个视图已过时。", + "ui.drawing_export.out_of_date_other": "{count} 个视图已过时。", + "ui.drawing_export.output": "输出", + "ui.drawing_export.paper": "纸张", + "ui.drawing_export.paper_blueprint": "蓝图", + "ui.drawing_export.paper_info": "纸张在此选择,不跟随您工作时的图纸页颜色。", + "ui.drawing_export.paper_note": "蓝色纸张在 SVG 和 PNG 中都以浅色绘制线条和文字。蓝图主题下,此处从对应的蓝色开始。", + "ui.drawing_export.paper_prussian_blue": "普鲁士蓝", + "ui.drawing_export.paper_white": "白色", + "ui.drawing_export.planned": "计划中:尚不可用", + "ui.drawing_export.refused": "{sheet} 未导出:无法绘制 {view}({reason})。", + "ui.drawing_export.resolution": "分辨率", + "ui.drawing_export.saved": "已将 {sheet} 保存到 {path}", + "ui.drawing_export.several": "每张图纸页单独成为一个文件,以图纸页名称命名。", + "ui.drawing_export.sheets": "图纸页", + "ui.drawing_export.stopped": "导出在完成前停止了", + "ui.drawing_export.stopping": "正在停止…", + "ui.drawing_export.title": "导出图纸", + "ui.drawing_export.view_back": "后视图", + "ui.drawing_export.view_bottom": "仰视图", + "ui.drawing_export.view_failed": "无法绘制 {view},因此 {sheet} 不会导出:{reason}", + "ui.drawing_export.view_front": "主视图", + "ui.drawing_export.view_iso": "等轴测视图", + "ui.drawing_export.view_left": "左视图", + "ui.drawing_export.view_number": "视图 {number}", + "ui.drawing_export.view_right": "右视图", + "ui.drawing_export.view_top": "俯视图" + } +} diff --git a/crates/engine/src/cmd/drawing_export.rs b/crates/engine/src/cmd/drawing_export.rs index a7d6e665347..f2577d38ed0 100644 --- a/crates/engine/src/cmd/drawing_export.rs +++ b/crates/engine/src/cmd/drawing_export.rs @@ -28,6 +28,7 @@ const CONTRACT: TypedContract = TypedContract::new(); const MAX_PATH_BYTES: usize = 4096; pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Sheet", crate::checked!("drawing.export", export)) + .at("DRAWING REVIEW", "OUTPUT") .icon("export") .in_drawing() .noundo() diff --git a/crates/engine/src/cmd/drawing_ui.rs b/crates/engine/src/cmd/drawing_ui.rs index 68988e0b06e..acb30d2d785 100644 --- a/crates/engine/src/cmd/drawing_ui.rs +++ b/crates/engine/src/cmd/drawing_ui.rs @@ -2,9 +2,9 @@ //! //! These entries reserve discoverable homes while the owning Drawing contracts land. //! JSON execution always refuses; the UI may show reviewed option layouts separately. -//! `drawing.export.planned` keeps the disabled UI action separate from `drawing.export` -//! (the sheet export provider). View previews likewise use `.planned` ids so the -//! real base-view and projected-view providers keep their executable contracts. +//! View previews use `.planned` ids so the real base-view and projected-view providers keep +//! their executable contracts. Export has arrived: `drawing.export` holds its ribbon place, and +//! its button opens the Export window. use super::CommandSpec; @@ -84,7 +84,6 @@ pub static COMMANDS: &[CommandSpec] = &[ planned!("drawing.update.planned", "Update Drawing", "4892").at("DRAWING REVIEW", "CHANGES").icon("drawing_update"), planned!("drawing.check.planned", "Check Drawing", "4894").at("DRAWING REVIEW", "CHANGES").icon("drawing_check"), planned!("drawing.revision", "Add Drawing Revision", "4894").at("DRAWING REVIEW", "REVISION").icon("drawing_revision"), - planned!("drawing.export.planned", "Export Drawing", "4890").at("DRAWING REVIEW", "OUTPUT").icon("export"), planned!("drawing.print", "Print Drawing", "4890").at("DRAWING REVIEW", "OUTPUT").icon("drawing_print"), planned!("drawing.view.break", "Break View", "7578").at("DRAWING LAYOUT", "VIEWS").icon("drawing_view_break"), planned!("drawing.view.auxiliary.planned", "Auxiliary View", "13044").at("DRAWING LAYOUT", "VIEWS").icon("drawing_view_auxiliary"), @@ -120,7 +119,9 @@ mod tests { for id in ["drawing.export", "drawing.view.base", "drawing.view.projected", "drawing.view.section", "drawing.view.auxiliary"] { assert!(crate::find_command(id).unwrap().planned.is_none(), "the executable provider {id} stays registered"); } - assert!(crate::find_command("drawing.export.planned").unwrap().planned.is_some(), "the scaffold export stays disabled"); + assert!(crate::find_command("drawing.export.planned").is_none(), "the real export holds its ribbon place"); + let export = crate::find_command("drawing.export").unwrap(); + assert_eq!((export.tab, export.panel), ("DRAWING REVIEW", "OUTPUT")); for command in super::COMMANDS { assert!(command.planned.is_some(), "{}", command.id); assert!(!command.info(&session).enabled, "{}", command.id); diff --git a/crates/engine/src/drawing_scene.rs b/crates/engine/src/drawing_scene.rs index a8716db577b..79615bcbff5 100644 --- a/crates/engine/src/drawing_scene.rs +++ b/crates/engine/src/drawing_scene.rs @@ -682,6 +682,13 @@ pub(crate) fn update(s: &mut Session) { s.drawing_scenes.updated = s.world_state().ok(); } +/// Moves each time a view or a reading of dimensions is kept, or the cache turns to another +/// drawing: with the session's revision, it says when [`standing`] (`drawing.status`) may read +/// differently, so a window that shows it reads it again only then. Read-only and cheap. +pub fn drawn(s: &Session) -> (Option, u64) { + (s.drawing_scenes.drawing, s.drawing_scenes.serial) +} + /// `d`, the drawing open, is deferred and the model has moved on from its last [`update`]. pub(crate) fn held(s: &Session, d: &Drawing) -> bool { s.world_state().is_ok_and(|state| s.drawing_scenes.holds(d, &state)) diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index aa32b6aacf6..20eed2826f8 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -59,6 +59,7 @@ pub const DOCUMENTED: &[&str] = &[ "contact.list", "document.inspect", "document.units", + "drawing.export", "drawing.table.edit", "edit.checkpoint", "edit.restore_checkpoint", diff --git a/crates/ui-egui/src/drawing_export_panel.rs b/crates/ui-egui/src/drawing_export_panel.rs new file mode 100644 index 00000000000..364ebbdcbb8 --- /dev/null +++ b/crates/ui-egui/src/drawing_export_panel.rs @@ -0,0 +1,744 @@ +//! The Drawing workspace's Export window (decision D24, board `review-export.png` in +//! `docs/design/drawing-ui/`): a right-hand panel that writes the chosen sheets of the open drawing +//! through `drawing.export`, one file a sheet, each as a background job (`file_load`), so a large +//! PNG never blocks the window. It holds only the window's choices; the engine checks every value +//! again. PDF and DXF show as planned until their writers land on `drawings`. +//! +//! The paper is the export's own choice, never the sheet colour on screen; a blueprint theme only +//! starts it on the matching blue. A view that can't be drawn is named here, before the export and +//! after a refusal alike, from the drawing's status (`drawing.status` lists it as `failed` with its +//! reason), never from the refusal's text, so a sheet is never refused silently. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{Receiver, TryRecvError}; + +use serde_json::{Value, json}; +use solidcraft_engine::doc::drawing::Drawing; +use solidcraft_engine::doc::drawing::view::ViewKind; +use solidcraft_engine::doc::ids; +use solidcraft_engine::geom::drawing_sheet::SheetSize; +use solidcraft_engine::geom::drawing_view::NamedView; + +use crate::SolveApp; +use crate::ui_kit::{self, StatusTone}; +use solidcraft_theme::Tokens; + +/// The command the window builds: its ribbon button opens the window, and the window runs it. +pub const ID: &str = "drawing.export"; +/// What a sheet export stopped by Cancel answers (`file_load`). +const CANCELLED: &str = "file operation cancelled"; +/// The longest file name the window makes, in characters, before its extension. +const MAX_NAME: usize = 120; + +/// The formats the window writes. PDF and DXF are shown, faded, as planned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Format { + Svg, + Png, +} + +impl Format { + fn name(self) -> &'static str { + match self { + Format::Svg => "svg", + Format::Png => "png", + } + } +} + +/// The paper a sheet is exported on (`drawing.export {paper}`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Paper { + White, + Blueprint, + PrussianBlue, +} + +impl Paper { + const ALL: [Paper; 3] = [Paper::White, Paper::Blueprint, Paper::PrussianBlue]; + + fn name(self) -> &'static str { + match self { + Paper::White => "white", + Paper::Blueprint => "blueprint", + Paper::PrussianBlue => "prussian_blue", + } + } +} + +/// How a PNG on white paper stores its pixels (`drawing.export {colour}`). A blue paper is always +/// in colour. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Colour { + Grey, + BlackWhite, + Rgb, + Transparent, +} + +impl Colour { + const ALL: [Colour; 4] = [Colour::Grey, Colour::BlackWhite, Colour::Rgb, Colour::Transparent]; + + fn name(self) -> &'static str { + match self { + Colour::Grey => "grey", + Colour::BlackWhite => "black_white", + Colour::Rgb => "rgb", + Colour::Transparent => "transparent", + } + } +} + +/// Where the files go. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Folder { + /// Beside the saved design, named after the design and each sheet. + Design, + /// A save dialog when Export is pressed. + Choose, +} + +/// One sheet being written to `path`: the background job answers on `reply`. +struct Job { + sheet: u64, + path: String, + reply: Receiver, +} + +/// The window's choices while it is open. Screen state only: nothing here is saved. +pub struct Export { + pub format: Format, + pub sheets: BTreeSet, + pub paper: Paper, + /// The PNG resolution the window sets; `None` keeps each sheet's own. + pub dpi: Option, + pub colour: Colour, + pub folder: Folder, + jobs: Vec, + /// OK was pressed: the window closes once every sheet is written. + close_when_done: bool, + /// Cancel stopped the sheets being written: the window stays to say which were written. + stopping: bool, + /// What the last export said, sheet by sheet, translated. + outcome: Vec<(StatusTone, String)>, + /// The last `drawing.status` reply, and the revision and drawing cache it was read at. + status: Option, + status_read: Option, +} + +/// What `drawing.status` was read at: the session's revision and how far the drawing's views and +/// dimensions are drawn ([`solidcraft_engine::drawing_scene::drawn`]). It reads the same until +/// one of them moves. +type StatusKey = (u64, (Option, u64)); + +impl Export { + fn new(first_sheet: Option, paper: Paper, saved: bool) -> Self { + Export { + format: Format::Svg, + sheets: first_sheet.into_iter().collect(), + paper, + dpi: None, + colour: Colour::Grey, + folder: if saved { Folder::Design } else { Folder::Choose }, + jobs: Vec::new(), + close_when_done: false, + stopping: false, + outcome: Vec::new(), + status: None, + status_read: None, + } + } + + /// Sheets are being written. + pub fn busy(&self) -> bool { + !self.jobs.is_empty() + } +} + +/// The paper the window starts on: the matching blue in a blueprint theme, else white. The engine +/// stays explicit (`drawing.export` is white unless told otherwise); this is only the window's +/// first choice. +pub fn starting_paper(theme: &str) -> Paper { + let theme = theme.to_ascii_lowercase(); + if theme.contains("prussian") { + Paper::PrussianBlue + } else if theme.contains("blueprint") { + Paper::Blueprint + } else { + Paper::White + } +} + +/// Open the window for the drawing open (the ribbon's Export, `ui.start drawing.export`). With no +/// drawing open the engine's own rule says why, and nothing opens. A window writing sheets stays as +/// it is: a new one would drop the sheets under way, and what they say. +pub fn open(app: &mut SolveApp) { + if app.drawing_workspace.export.as_ref().is_some_and(Export::busy) { + app.drawing_workspace.settings_open = false; + return; + } + if let Some(command) = solidcraft_engine::find_command(ID) + && let Err(why) = command.allowed(&app.session) + { + app.set_status(crate::friendly_error(ID, &why), true); + return; + } + let first = app.session.drawing(ID).ok().and_then(|d| d.sheets.first().map(|s| s.id)); + let paper = starting_paper(&app.preferences.theme); + app.drawing_workspace.export = Some(Export::new(first, paper, app.session.path.is_some())); + app.drawing_workspace.settings_open = false; +} + +/// Close the window (Cancel, its close button, Esc, another panel). While sheets are being written +/// it stops them instead and stays open, so it can say which were written and which weren't. +pub fn close(app: &mut SolveApp) { + if app.drawing_workspace.export.as_ref().is_some_and(Export::busy) { + stop(app); + } else { + app.drawing_workspace.export = None; + } +} + +/// Another panel asks for the window's place: it goes, unless it is writing sheets, which it goes on +/// with and stays for (dropping it would leave them writing with nothing to say what they did). +pub fn give_way(app: &mut SolveApp) { + if !app.drawing_workspace.export.as_ref().is_some_and(Export::busy) { + app.drawing_workspace.export = None; + } +} + +/// Stop the sheets being written: those waiting are dropped, the one under way is told to stop, and +/// each answers in the window. A file already written is said as saved. Other file operations go on. +fn stop(app: &mut SolveApp) { + let Some(export) = app.drawing_workspace.export.as_mut() else { return }; + export.stopping = true; + export.close_when_done = false; + let paths: Vec = export.jobs.iter().map(|job| job.path.clone()).collect(); + app.file_load.cancel_sheet_exports(&paths); +} + +/// A sheet's paper size as people name it: `A3`, `ANSI B`, `Letter`, or its sides for a custom one. +fn size_name(size: &SheetSize) -> String { + match size { + SheetSize::Custom { sides_mm: [a, b] } => format!("{a:.0} × {b:.0} mm"), + SheetSize::Standard(paper) => { + let code = serde_json::to_value(paper).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(); + match code.split_once('_') { + Some((family, letter)) => format!("{} {}", family.to_uppercase(), letter.to_uppercase()), + None if code.starts_with('a') => code.to_uppercase(), + None => { + let mut chars = code.chars(); + chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default() + } + } + } + } +} + +/// A view as people name it: by the way it looks when that is a named view ("Right view"), else by +/// its place among its sheet's views ("View 3"). Two views of one name on a sheet take their number. +pub fn view_name(d: &Drawing, view: u64) -> String { + let on_sheet: Vec = d.view(view).map_or_else(Vec::new, |v| d.views.iter().filter(|o| o.sheet == v.sheet).map(|o| o.id).collect()); + let number = on_sheet.iter().position(|id| *id == view).map_or(0, |at| at + 1); + let plain = |id: u64| -> Option<&'static str> { + let looks = match d.view(id)?.kind { + ViewKind::Base { view: solidcraft_engine::doc::drawing_view::ViewDirection::Named(named), .. } => Some(named), + _ => d.resolve_view(id).ok().and_then(|r| NamedView::ALL.iter().copied().find(|n| n.basis() == r.basis)), + }?; + Some(match looks { + NamedView::Front => "ui.drawing_export.view_front", + NamedView::Back => "ui.drawing_export.view_back", + NamedView::Top => "ui.drawing_export.view_top", + NamedView::Bottom => "ui.drawing_export.view_bottom", + NamedView::Left => "ui.drawing_export.view_left", + NamedView::Right => "ui.drawing_export.view_right", + NamedView::IsoFrontRight | NamedView::IsoFrontLeft | NamedView::IsoBackRight | NamedView::IsoBackLeft => "ui.drawing_export.view_iso", + }) + }; + let numbered = solidcraft_ui_text::format("ui.drawing_export.view_number", &[("number", &number.to_string())]); + match plain(view) { + Some(key) if on_sheet.iter().filter(|id| plain(**id) == Some(key)).count() > 1 => format!("{} ({number})", solidcraft_ui_text::tr(key)), + Some(key) => solidcraft_ui_text::tr(key).to_owned(), + None => numbered, + } +} + +/// A file name made from the design's and a sheet's names: characters no file system takes become +/// dashes, and it is kept short. +pub fn file_stem(design: &str, sheet: &str) -> String { + let joined = format!("{design} - {sheet}"); + let cleaned: String = + joined.chars().map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '-' } else { c }).collect(); + let short: String = cleaned.trim().chars().take(MAX_NAME).collect(); + let short = short.trim_end_matches(['.', ' ']).to_owned(); + if short.is_empty() { "drawing".into() } else { short } +} + +/// The file each chosen sheet goes to: `base` for one sheet; for several, `base`'s name with each +/// sheet's after it. Names are made distinct, and each ends in the format's extension. +pub fn paths_for(base: &Path, sheets: &[(u64, String)], extension: &str) -> Vec<(u64, PathBuf)> { + let folder = base.parent().map(Path::to_path_buf).unwrap_or_default(); + let stem = base.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "drawing".into()); + let mut taken: BTreeSet = BTreeSet::new(); + let mut out = Vec::new(); + for (sheet, name) in sheets { + let mut own = if sheets.len() == 1 { stem.clone() } else { file_stem(&stem, name) }; + let mut n = 2; + while !taken.insert(own.to_lowercase()) { + own = format!("{} ({n})", if sheets.len() == 1 { stem.clone() } else { file_stem(&stem, name) }); + n += 1; + } + out.push((*sheet, folder.join(format!("{own}.{extension}")))); + } + out +} + +/// What the window sends for one sheet. +fn params(export: &Export, sheet: u64, path: &str) -> Value { + let mut p = json!({"sheet": ids::encode(sheet), "format": export.format.name(), "path": path, "paper": export.paper.name()}); + if export.format == Format::Png { + if let Some(dpi) = export.dpi { + p["dpi"] = json!(dpi); + } + // A blue paper is always in colour: the engine refuses another. + if export.paper == Paper::White { + p["colour"] = json!(export.colour.name()); + } + } + p +} + +/// The chosen sheets in drawing order, with their names. +fn chosen(d: &Drawing, export: &Export) -> Vec<(u64, String)> { + d.sheets.iter().filter(|s| export.sheets.contains(&s.id)).map(|s| (s.id, s.name.clone())).collect() +} + +/// Queue a background job for each sheet and its file. +fn begin(app: &mut SolveApp, files: Vec<(u64, PathBuf)>) { + let Some(export) = app.drawing_workspace.export.as_mut() else { return }; + export.outcome.clear(); + let mut queued = Vec::new(); + for (sheet, path) in files { + let path = path.to_string_lossy().into_owned(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut request = crate::file_load::Request::new(&path, crate::file_load::Kind::ExportSheet); + request.options = params(export, sheet, &path).as_object().cloned().unwrap_or_default(); + request.reply = Some(tx); + queued.push(request); + export.jobs.push(Job { sheet, path, reply: rx }); + } + for request in queued { + // A refusal to queue answers the job's reply, which the window then shows. + let _ = crate::file_load::begin_request(app, request); + } +} + +/// Export the chosen sheets now (Apply, or OK with `close`). +fn export_now(app: &mut SolveApp, close: bool) { + let Ok(d) = app.session.drawing(ID).cloned() else { return }; + let Some(export) = app.drawing_workspace.export.as_mut() else { return }; + let sheets = chosen(&d, export); + if sheets.is_empty() || export.busy() { + return; + } + export.close_when_done = close; + let extension = export.format.name(); + let design = app.session.doc.name.clone(); + let first = sheets.first().map(|(_, name)| name.clone()).unwrap_or_default(); + let suggested = if sheets.len() == 1 { file_stem(&design, &first) } else { file_stem(&design, "").trim_end_matches([' ', '-']).to_owned() }; + match (export.folder, app.session.path.as_deref().map(Path::new).and_then(Path::parent)) { + (Folder::Design, Some(folder)) => { + let files = sheets.iter().map(|(id, name)| (*id, folder.join(format!("{}.{extension}", file_stem(&design, name))))).collect(); + begin(app, distinct(files)); + } + _ => { + app.pick_save(&format!("{suggested}.{extension}"), &[extension], move |app, path| { + let Some(path) = path else { + if let Some(export) = app.drawing_workspace.export.as_mut() { + export.close_when_done = false; + } + return; + }; + let mut base = PathBuf::from(path); + if !base.extension().is_some_and(|e| e.eq_ignore_ascii_case(extension)) { + base.as_mut_os_string().push(format!(".{extension}")); + } + begin(app, paths_for(&base, &sheets, extension)); + }); + } + } +} + +/// Files made distinct where two sheets' names clean to the same file name. +fn distinct(files: Vec<(u64, PathBuf)>) -> Vec<(u64, PathBuf)> { + let mut taken: BTreeSet = BTreeSet::new(); + files + .into_iter() + .map(|(sheet, path)| { + let mut candidate = path.clone(); + let mut n = 2; + while !taken.insert(candidate.to_string_lossy().to_lowercase()) { + let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let extension = path.extension().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + candidate = path.with_file_name(format!("{stem} ({n}).{extension}")); + n += 1; + } + (sheet, candidate) + }) + .collect() +} + +/// What one finished sheet says in the window. +fn outcome_lines(d: Option<&Drawing>, views: &[(u64, u64, String, String)], sheet: u64, reply: &Value) -> Vec<(StatusTone, String)> { + let sheet_name = d.and_then(|d| d.sheets.iter().find(|s| s.id == sheet)).map_or_else(|| ids::encode(sheet), |s| s.name.clone()); + if reply.get("ok").and_then(Value::as_bool) == Some(true) { + let result = reply.get("result").unwrap_or(&Value::Null); + // The file's name: the folder is the one the window shows or the one just chosen. + let path = result.get("path").and_then(Value::as_str).unwrap_or_default(); + let file = Path::new(path).file_name().map_or_else(|| path.to_owned(), |f| f.to_string_lossy().into_owned()); + let mut lines = vec![(StatusTone::Dim, solidcraft_ui_text::format("ui.drawing_export.saved", &[("sheet", &sheet_name), ("path", &file)]))]; + let stale = result.get("out_of_date").and_then(Value::as_array).map_or(0, Vec::len); + if stale > 0 { + let key = if stale == 1 { "ui.drawing_export.as_last_were_one" } else { "ui.drawing_export.as_last_were_other" }; + lines.push((StatusTone::Warning, solidcraft_ui_text::format(key, &[("sheet", &sheet_name), ("count", &stale.to_string())]))); + } + let missing: Vec<&Value> = result + .get("dimensions") + .and_then(Value::as_array) + .map_or_else(Vec::new, |all| all.iter().filter(|d| d.get("drawn") == Some(&json!(false))).collect()); + if let Some(first) = missing.first() { + let why = first.get("why").and_then(Value::as_str).unwrap_or_default(); + let key = if missing.len() == 1 { "ui.drawing_export.dimensions_one" } else { "ui.drawing_export.dimensions_other" }; + lines.push(( + StatusTone::Warning, + solidcraft_ui_text::format(key, &[("sheet", &sheet_name), ("count", &missing.len().to_string()), ("why", why)]), + )); + } + return lines; + } + let error = reply.get("error").and_then(Value::as_str).unwrap_or_default(); + if error == CANCELLED { + let stopped = solidcraft_ui_text::tr("ui.drawing_export.stopped"); + return vec![(StatusTone::Warning, solidcraft_ui_text::format("ui.drawing_export.failed", &[("sheet", &sheet_name), ("error", stopped)]))]; + } + // The status lists each view of the sheet that can't be drawn, with its reason: name it as people know it. + let named: Vec<(StatusTone, String)> = d.map_or_else(Vec::new, |d| { + views + .iter() + .filter(|(_, s, status, _)| *s == sheet && status == "failed") + .map(|(view, _, _, reason)| { + let text = solidcraft_ui_text::format( + "ui.drawing_export.refused", + &[("sheet", &sheet_name), ("view", &view_name(d, *view)), ("reason", reason)], + ); + (StatusTone::Error, text) + }) + .collect() + }); + if named.is_empty() { + let text = solidcraft_ui_text::format("ui.drawing_export.failed", &[("sheet", &sheet_name), ("error", &crate::friendly_error(ID, error))]); + vec![(StatusTone::Error, text)] + } else { + named + } +} + +/// Take the answers of finished sheets, and close the window after OK once every sheet is written. +fn collect(app: &mut SolveApp) { + let d = app.session.drawing(ID).ok().cloned(); + let Some(export) = app.drawing_workspace.export.as_mut() else { return }; + let mut finished = false; + let mut stopped = false; + let mut lines = Vec::new(); + let views = listed(export); + export.jobs.retain(|job| match job.reply.try_recv() { + Ok(reply) => { + stopped |= reply.get("error").and_then(Value::as_str) == Some(CANCELLED); + lines.extend(outcome_lines(d.as_deref(), &views, job.sheet, &reply)); + finished = true; + false + } + Err(TryRecvError::Empty) => true, + Err(TryRecvError::Disconnected) => { + lines.extend(outcome_lines( + d.as_deref(), + &views, + job.sheet, + &json!({"ok": false, "error": solidcraft_ui_text::tr("ui.drawing_export.stopped")}), + )); + finished = true; + false + } + }); + export.outcome.extend(lines); + // Cancel here or on the progress card: the window stays to say which sheets were written. + export.stopping |= stopped; + if finished && export.jobs.is_empty() { + let failed = export.outcome.iter().any(|(tone, _)| matches!(tone, StatusTone::Error)); + let stopped = std::mem::take(&mut export.stopping); + if export.close_when_done && !failed && !stopped { + app.drawing_workspace.export = None; + } else { + export.close_when_done = false; + } + } +} + +/// Read the drawing's status (`drawing.status`, read-only) when the window opens, after a change to +/// the design and after a view or its dimensions are drawn, so a view that can't be drawn is named +/// before Export is pressed. Nothing else changes it, so it isn't read again until then: each read +/// measures every dimension of the drawing. +fn refresh_status(app: &mut SolveApp) { + let key = |app: &SolveApp| (app.session.revision, solidcraft_engine::drawing_scene::drawn(&app.session)); + let seen = key(app); + if app.drawing_workspace.export.as_ref().is_none_or(|e| e.status_read == Some(seen)) { + return; + } + let status = app.session.execute("drawing.status", &json!({})).ok(); + // As read: the read itself may bring the cache to the drawing open. + let read = key(app); + if let Some(export) = app.drawing_workspace.export.as_mut() { + export.status = status; + export.status_read = Some(read); + } +} + +/// The views of the chosen sheets the status lists, as (view, sheet, status, reason). +fn listed(export: &Export) -> Vec<(u64, u64, String, String)> { + let views = export.status.as_ref().and_then(|s| s.get("views")).and_then(Value::as_array); + views + .into_iter() + .flatten() + .filter_map(|v| { + let view = ids::decode(v.get("view")?.as_str()?)?; + let sheet = ids::decode(v.get("sheet")?.as_str()?)?; + let status = v.get("status")?.as_str()?.to_owned(); + let reason = v.get("reason").and_then(Value::as_str).unwrap_or_default().to_owned(); + Some((view, sheet, status, reason)) + }) + .collect() +} + +fn close_button(ui: &mut egui::Ui) -> bool { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(egui::vec2(t.space_24, t.space_24), egui::Sense::hover()); + let r = ui_kit::icon_button_at(ui, rect, "close", solidcraft_ui_text::tr("ui.drawing_export.close")); + crate::scenario::publish_target("drawing:export:close", rect); + r.clicked() +} + +/// The window's contents, in the Drawing workspace's right-hand panel host. +pub fn body(app: &mut SolveApp, ui: &mut egui::Ui) { + collect(app); + if app.session.open_drawing.is_none() { + // Its sheets are gone with it: nothing is left to write them for. + stop(app); + app.drawing_workspace.export = None; + return; + } + let Ok(d) = app.session.drawing(ID).cloned() else { return }; + refresh_status(app); + let saved = app.session.path.is_some(); + let design = app.session.doc.name.clone(); + let Some(export) = app.drawing_workspace.export.as_mut() else { return }; + // Sheets deleted while the window is open leave its choice. + export.sheets.retain(|id| d.sheets.iter().any(|s| s.id == *id)); + let t = Tokens::get(); + let mut close = false; + ui.horizontal(|ui| { + ui.heading(solidcraft_ui_text::tr("ui.drawing_export.title")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| close = close_button(ui)); + }); + ui.add_space(t.space_8); + + ui_kit::section_heading(ui, solidcraft_ui_text::tr("ui.drawing_export.format")); + let planned = solidcraft_ui_text::tr("ui.drawing_export.planned"); + let mut format = match export.format { + Format::Svg => 1, + Format::Png => 2, + }; + let formats = ["PDF", "SVG", "PNG", "DXF"]; + let reasons = [Some(planned), None, None, Some(planned)]; + let targets = ["drawing:export:format:pdf", "drawing:export:format:svg", "drawing:export:format:png", "drawing:export:format:dxf"]; + // Each row of segments under its own id: segments are numbered within their parent. + let picked = ui + .push_id("drawing_export_format", |ui| { + ui_kit::segmented(ui, &mut format, &formats, ui_kit::Segments { disabled_reasons: &reasons, targets: &targets, ..Default::default() }) + }) + .inner; + if picked { + export.format = if format == 2 { Format::Png } else { Format::Svg }; + } + ui.add_space(t.space_8); + + ui_kit::section_heading(ui, solidcraft_ui_text::tr("ui.drawing_export.sheets")); + let views = listed(export); + for sheet in &d.sheets { + let mut on = export.sheets.contains(&sheet.id); + let label = format!("{} · {}", sheet.name, size_name(&sheet.sheet.size)); + let r = ui_kit::checkbox(ui, &label, &mut on); + crate::scenario::publish_target(&format!("drawing:export:sheet:{}", sheet.name), r.rect); + if r.changed() { + if on { + export.sheets.insert(sheet.id); + } else { + export.sheets.remove(&sheet.id); + } + } + for (view, _, _, reason) in views.iter().filter(|(_, s, status, _)| *s == sheet.id && status == "failed") { + let text = solidcraft_ui_text::format( + "ui.drawing_export.view_failed", + &[("view", &view_name(&d, *view)), ("sheet", &sheet.name), ("reason", reason)], + ); + ui_kit::status_line(ui, &text, StatusTone::Warning); + } + } + if export.sheets.is_empty() { + ui_kit::status_line(ui, solidcraft_ui_text::tr("ui.drawing_export.no_sheet"), StatusTone::Warning); + } + ui.add_space(t.space_8); + + ui_kit::section_heading(ui, solidcraft_ui_text::tr("ui.drawing_export.paper")); + let papers = [ + solidcraft_ui_text::tr("ui.drawing_export.paper_white"), + solidcraft_ui_text::tr("ui.drawing_export.paper_blueprint"), + solidcraft_ui_text::tr("ui.drawing_export.paper_prussian_blue"), + ]; + let mut paper = Paper::ALL.iter().position(|p| *p == export.paper).unwrap_or(0); + let paper_targets = ["drawing:export:paper:white", "drawing:export:paper:blueprint", "drawing:export:paper:prussian_blue"]; + let picked = ui + .push_id("drawing_export_paper", |ui| { + ui_kit::segmented(ui, &mut paper, &papers, ui_kit::Segments { targets: &paper_targets, ..Default::default() }) + }) + .inner; + if picked { + export.paper = Paper::ALL.get(paper).copied().unwrap_or(Paper::White); + } + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.paper_note"), ui_kit::Text::Note("drawing_export_paper")); + ui.add_space(t.space_8); + + ui_kit::section_heading(ui, solidcraft_ui_text::tr("ui.drawing_export.output")); + if export.format == Format::Png { + let own = d.sheets.iter().find(|s| export.sheets.contains(&s.id)).map_or(solidcraft_engine::doc::drawing::DEFAULT_DPI, |s| s.dpi); + let resolution = solidcraft_ui_text::tr("ui.drawing_export.resolution"); + let mut dpi = export.dpi.unwrap_or(own); + ui_kit::row(ui, resolution, |ui| { + let r = ui_kit::number_field(ui, &mut dpi, 25.0..=2400.0, 1.0, " dpi"); + crate::scenario::publish_target("drawing:export:dpi", r.rect); + if r.changed() && dpi.is_finite() { + export.dpi = Some(dpi.clamp(25.0, 2400.0)); + } + }); + if export.dpi.is_some() { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.dpi_set"), ui_kit::Text::Note("drawing_export_dpi")); + if ui_kit::button(ui, solidcraft_ui_text::tr("ui.drawing_export.dpi_reset"), ui_kit::Button::Normal).clicked() { + export.dpi = None; + } + } else { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.dpi_note"), ui_kit::Text::Note("drawing_export_dpi")); + } + let colour_label = solidcraft_ui_text::tr("ui.drawing_export.colour"); + let colours = [ + solidcraft_ui_text::tr("ui.drawing_export.colour_grey"), + solidcraft_ui_text::tr("ui.drawing_export.colour_black_white"), + solidcraft_ui_text::tr("ui.drawing_export.colour_rgb"), + solidcraft_ui_text::tr("ui.drawing_export.colour_transparent"), + ]; + let blue = export.paper != Paper::White; + let only_rgb = solidcraft_ui_text::tr("ui.drawing_export.colour_blue"); + let shown_colour = if blue { Colour::Rgb } else { export.colour }; + let current = Colour::ALL.iter().position(|c| *c == shown_colour).and_then(|at| colours.get(at)).copied().unwrap_or_default(); + ui_kit::row(ui, colour_label, |ui| { + // A blue paper is always in colour: the choice is shown, and held, until the paper is white. + ui.add_enabled_ui(!blue, |ui| { + let r = ui_kit::dropdown_menu(ui, "drawing_export_colour", current, |ui| { + for (colour, label) in Colour::ALL.iter().zip(colours) { + let r = ui.selectable_label(export.colour == *colour, label); + crate::scenario::publish_target(&format!("drawing:export:colour:{}", colour.name()), r.rect); + if r.clicked() { + export.colour = *colour; + } + } + }); + crate::scenario::publish_target("drawing:export:colour", r.rect); + if blue { + r.on_disabled_hover_text(only_rgb); + } + }); + }); + if blue { + ui_kit::text(ui, only_rgb, ui_kit::Text::Note("drawing_export_colour")); + } + } + let folder_label = solidcraft_ui_text::tr("ui.drawing_export.folder"); + if !saved { + export.folder = Folder::Choose; + } + let shown = solidcraft_ui_text::tr(match export.folder { + Folder::Design => "ui.drawing_export.folder_design", + Folder::Choose => "ui.drawing_export.folder_choose", + }); + ui_kit::row(ui, folder_label, |ui| { + let r = ui_kit::dropdown_menu(ui, "drawing_export_folder", shown, |ui| { + for (folder, key, enabled) in + [(Folder::Design, "ui.drawing_export.folder_design", saved), (Folder::Choose, "ui.drawing_export.folder_choose", true)] + { + let r = ui.add_enabled_ui(enabled, |ui| ui.selectable_label(export.folder == folder, solidcraft_ui_text::tr(key))).inner; + crate::scenario::publish_target( + &format!("drawing:export:folder:{}", if folder == Folder::Design { "design" } else { "choose" }), + r.rect, + ); + if r.clicked() { + export.folder = folder; + } + } + }); + crate::scenario::publish_target("drawing:export:folder", r.rect); + }); + if !saved { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.folder_unsaved"), ui_kit::Text::Note("drawing_export_unsaved")); + } + let sheets = chosen(&d, export); + if export.folder == Folder::Design && !sheets.is_empty() { + let names: Vec = sheets.iter().map(|(_, name)| format!("{}.{}", file_stem(&design, name), export.format.name())).collect(); + let files = solidcraft_ui_text::format("ui.drawing_export.files", &[("files", &names.join(", "))]); + ui_kit::text(ui, files.as_str(), ui_kit::Text::Note("drawing_export_files")); + } else if sheets.len() > 1 { + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.several"), ui_kit::Text::Note("drawing_export_files")); + } + ui.add_space(t.space_8); + ui_kit::text(ui, solidcraft_ui_text::tr("ui.drawing_export.paper_info"), ui_kit::Text::Hint("drawing_export_paper_info")); + for (tone, line) in &export.outcome { + ui_kit::status_line(ui, line, *tone); + } + ui.add_space(t.space_8); + + // The footer says what a held drawing will write as it last was, as the board's does. + let held = export.status.as_ref().and_then(|s| s.get("held")).and_then(Value::as_bool) == Some(true); + let stale = views.iter().filter(|(_, sheet, status, _)| export.sheets.contains(sheet) && status == "out_of_date").count(); + let footer_status = if export.busy() { + Some(solidcraft_ui_text::tr(if export.stopping { "ui.drawing_export.stopping" } else { "ui.drawing_export.exporting" }).to_owned()) + } else if held && stale > 0 { + let key = if stale == 1 { "ui.drawing_export.out_of_date_one" } else { "ui.drawing_export.out_of_date_other" }; + Some(solidcraft_ui_text::format(key, &[("count", &stale.to_string())])) + } else { + None + }; + let ready = !sheets.is_empty() && !export.busy(); + let action = + ui_kit::footer(ui, "OK", "Cancel", ready, ui_kit::Footer { apply: Some("Apply"), status: footer_status.as_deref(), ..Default::default() }); + match action { + ui_kit::Action::Ok if ready => export_now(app, true), + ui_kit::Action::Apply if ready => export_now(app, false), + ui_kit::Action::Cancel => close = true, + _ => {} + } + if close { + crate::drawing_export_panel::close(app); + } +} + +#[cfg(test)] +#[path = "drawing_export_panel_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/drawing_export_panel_tests.rs b/crates/ui-egui/src/drawing_export_panel_tests.rs new file mode 100644 index 00000000000..f4ac1b3faee --- /dev/null +++ b/crates/ui-egui/src/drawing_export_panel_tests.rs @@ -0,0 +1,380 @@ +use super::*; +use crate::scenario::Harness; + +/// A box with a drawing open: a front view on the first sheet, a top view above it, and a second, +/// empty sheet. The Drawing workspace is shown. +fn drawing(h: &mut Harness) -> (u64, u64, u64) { + h.app.home.open = false; + h.app.run("solid.box", json!({"length": 100, "width": 50, "height": 20})).unwrap(); + h.app.run("drawing.create", json!({})).unwrap(); + let sheet = h.app.session.drawing("test").unwrap().sheets[0].id; + let base = + h.app.run("drawing.view.base", json!({"sheet": ids::encode(sheet), "view": "front", "scale": "1:2", "position_mm": [150, 120]})).unwrap(); + let front = ids::decode(base["view"].as_str().unwrap()).unwrap(); + let projected = h.app.run("drawing.view.projected", json!({"parent": ids::encode(front), "side": "above"})).unwrap(); + let top = ids::decode(projected["view"].as_str().unwrap()).unwrap(); + h.app.run("drawing.sheet.add", json!({})).unwrap(); + h.app.preferences.drawings_preview = true; + crate::drawing_workspace::enter(&mut h.app, true).unwrap(); + (sheet, front, top) +} + +fn wait(h: &mut Harness) { + let began = std::time::Instant::now(); + loop { + h.frames(1); + let busy = h.app.drawing_workspace.export.as_ref().is_some_and(Export::busy); + if h.app.file_load.idle() && !h.app.file_picker_busy() && !busy { + break; + } + assert!(began.elapsed().as_secs() < 30, "export did not finish"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + h.frames(2); +} + +/// A sheet export of the drawing that isn't the window's (an agent's, through the control channel). +fn other_export(h: &mut Harness, sheet: u64, file: &str) -> std::sync::mpsc::Receiver { + let path = h.dir.join(file).to_string_lossy().into_owned(); + let mut request = crate::file_load::Request::new(&path, crate::file_load::Kind::ExportSheet); + request.options = json!({"sheet": ids::encode(sheet), "format": "svg", "path": path}).as_object().cloned().unwrap_or_default(); + let (tx, rx) = std::sync::mpsc::channel(); + request.reply = Some(tx); + crate::file_load::begin_request(&mut h.app, request).unwrap(); + rx +} + +/// Hold the next file worker until `release` is sent; `started` says when it is waiting. +fn hold_next_worker(h: &mut Harness) -> (std::sync::mpsc::Receiver, std::sync::mpsc::Sender<()>) { + let (started_tx, started) = std::sync::mpsc::channel(); + let (release, release_rx) = std::sync::mpsc::channel(); + h.app.file_load.worker_gate = Some((started_tx, release_rx)); + (started, release) +} + +fn until_started(h: &mut Harness, started: &std::sync::mpsc::Receiver) { + let began = std::time::Instant::now(); + while started.try_recv().is_err() { + h.frames(1); + assert!(began.elapsed().as_secs() < 30, "the export did not start"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +fn answer_saves_with(h: &mut Harness, file: &str) { + let path = h.dir.join(file).to_string_lossy().into_owned(); + h.app.services.pick_save = Some(Box::new(move |_, _| Box::pin(std::future::ready(Some(path.clone()))))); +} + +#[test] +fn a_blueprint_theme_starts_on_its_blue_and_every_other_theme_on_white() { + assert_eq!(starting_paper("blueprint"), Paper::Blueprint); + assert_eq!(starting_paper("Prussian Blue"), Paper::PrussianBlue); + for theme in ["dark", "light", "cga", "solidcraft-95", ""] { + assert_eq!(starting_paper(theme), Paper::White, "{theme}"); + } +} + +#[test] +fn file_names_take_the_design_and_sheet_and_lose_what_no_file_system_takes() { + assert_eq!(file_stem("Bracket", "Sheet 1"), "Bracket - Sheet 1"); + assert_eq!(file_stem("a/b", "c:d*?\"<>|"), "a-b - c-d------"); + assert_eq!(file_stem("", ""), "-"); + assert_eq!(file_stem("x".repeat(400).as_str(), "y").chars().count(), MAX_NAME); + // One sheet takes the file chosen; several take its name with each sheet's, made distinct. + let one = paths_for(Path::new("/out/plate.svg"), &[(1, "Sheet 1".into())], "svg"); + assert_eq!(one, [(1, PathBuf::from("/out/plate.svg"))]); + let two = paths_for(Path::new("/out/plate.png"), &[(1, "A/B".into()), (2, "A-B".into())], "png"); + assert_eq!(two, [(1, PathBuf::from("/out/plate - A-B.png")), (2, PathBuf::from("/out/plate - A-B (2).png"))]); +} + +/// A refused sheet names the views the status lists as failed on it, with their reasons, and +/// nothing is read from the refusal's text; a status that names none leaves the friendly error. +#[test] +fn a_refused_sheet_names_its_failed_view_from_the_status() { + let mut h = Harness::new(); + let (sheet, front, top) = drawing(&mut h); + let d = h.app.session.drawing("test").unwrap().clone(); + let refusal = json!({"ok": false, "error": "drawing.export: not written"}); + let views = vec![ + (front, sheet, "ok".to_owned(), String::new()), + (top, sheet, "failed".to_owned(), "not supported yet: shaded".to_owned()), + (top, sheet + 1, "failed".to_owned(), "another sheet".to_owned()), + ]; + let lines = outcome_lines(Some(&d), &views, sheet, &refusal); + let said: Vec<&str> = lines.iter().map(|(_, l)| l.as_str()).collect(); + assert_eq!(lines.len(), 1, "{said:?}"); + assert!(matches!(lines[0].0, StatusTone::Error)); + assert!(lines[0].1.contains(view_name(&d, top).as_str()) && lines[0].1.contains("not supported yet: shaded"), "{said:?}"); + let none = outcome_lines(Some(&d), &views[..1], sheet, &refusal); + assert_eq!(none.len(), 1); + assert!(none[0].1.contains(&crate::friendly_error(ID, "drawing.export: not written")), "{}", none[0].1); +} + +#[test] +fn sheets_are_listed_with_their_paper_size() { + use solidcraft_engine::geom::drawing_sheet::PaperSize; + assert_eq!(size_name(&SheetSize::Standard(PaperSize::A3)), "A3"); + assert_eq!(size_name(&SheetSize::Standard(PaperSize::AnsiB)), "ANSI B"); + assert_eq!(size_name(&SheetSize::Standard(PaperSize::ArchE1)), "ARCH E1"); + assert_eq!(size_name(&SheetSize::Standard(PaperSize::Letter)), "Letter"); + assert_eq!(size_name(&SheetSize::Custom { sides_mm: [300.0, 200.0] }), "300 × 200 mm"); +} + +/// The ribbon's Export opens the window only with a drawing open; `engine.execute` runs the command +/// with no window, and the window changes nothing in the design or its undo. +#[test] +fn export_opens_its_window_from_the_ribbon_and_never_from_a_programmatic_call() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.drawings_preview = true; + crate::drawing_workspace::enter(&mut h.app, true).unwrap(); + h.app.start(ID); + assert!(h.app.drawing_workspace.export.is_none(), "no drawing open: nothing opens"); + crate::drawing_workspace::enter(&mut h.app, false).unwrap(); + let (sheet, ..) = drawing(&mut h); + let reply = h.call("engine.execute", json!({"command": ID, "params": {"sheet": ids::encode(sheet)}})); + assert!(reply["result"]["svg"].as_str().is_some_and(|svg| svg.starts_with(" = std::fs::read_dir(&h.dir).unwrap().flatten().map(|e| e.file_name()).collect(); + let said = h.app.drawing_workspace.export.as_ref().map(|e| e.outcome.iter().map(|(_, l)| l.clone()).collect::>()); + assert!(h.dir.join("plate - Sheet 1.png").exists(), "{files:?} {said:?}"); + for name in ["plate - Sheet 1.png", "plate - Sheet 2.png"] { + let png = std::fs::read(h.dir.join(name)).unwrap_or_else(|e| panic!("{name}: {e}")); + assert!(png.starts_with(b"\x89PNG"), "{name}"); + // The header's colour type: 2 is RGB, as a blue paper always is. + assert_eq!(png.get(25), Some(&2), "{name}"); + } + assert!(h.app.drawing_workspace.export.is_none(), "OK closes the window once both sheets are written"); + + // On white paper the PNG's colour is the window's choice: black and white is one bit a pixel. + h.frames(30); + h.app.start(ID); + h.frames(30); + h.step(&json!({"click": {"handle": "drawing:export:format:png"}})).unwrap(); + h.step(&json!({"click": {"handle": "drawing:export:paper:white"}})).unwrap(); + h.step(&json!({"click": {"handle": "drawing:export:colour"}})).unwrap(); + h.step(&json!({"click": {"handle": "drawing:export:colour:black_white"}})).unwrap(); + assert_eq!(h.app.drawing_workspace.export.as_ref().map(|e| e.colour), Some(Colour::BlackWhite)); + if let Some(export) = h.app.drawing_workspace.export.as_mut() { + export.dpi = Some(50.0); + } + // The resolution set here adds its reset button, which moves OK down. + h.frames(2); + answer_saves_with(&mut h, "plate-bw.png"); + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + wait(&mut h); + let png = std::fs::read(h.dir.join("plate-bw.png")).unwrap(); + assert_eq!((png.get(24), png.get(25)), (Some(&1), Some(&0)), "1-bit greyscale"); +} + +/// A view that can't be drawn is named in the window before the export, and the refused sheet +/// names it after; the window stays open and writes no file. +#[test] +fn a_view_that_cant_be_drawn_is_named_instead_of_refused_silently() { + let mut h = Harness::new(); + let (sheet, _, top) = drawing(&mut h); + h.app.run("drawing.view.edit", json!({"view": ids::encode(top), "set": {"visual_style": "shaded_visible"}})).unwrap(); + // The sheet page has drawn its views, so the status lists the one that can't be drawn as failed. + solidcraft_engine::drawing_scene::extract(&mut h.app.session, sheet).unwrap(); + for _ in 0..10 { + if !solidcraft_engine::drawing_scene::step(&mut h.app.session) { + break; + } + } + let name = view_name(h.app.session.drawing("test").unwrap(), top); + assert_eq!(name, solidcraft_ui_text::tr("ui.drawing_export.view_top")); + h.app.start(ID); + h.frames(3); + answer_saves_with(&mut h, "refused.svg"); + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + wait(&mut h); + assert!(!h.dir.join("refused.svg").exists()); + let export = h.app.drawing_workspace.export.as_ref().expect("a refusal keeps the window open"); + let said: Vec<&str> = export.outcome.iter().map(|(_, line)| line.as_str()).collect(); + assert!(said.iter().any(|line| line.contains(&name) && line.contains("shaded")), "{said:?}"); + assert!(!said.iter().any(|line| line.contains(&ids::encode(top))), "named, not by id: {said:?}"); +} + +/// Two views that look the same way on one sheet take their numbers; a view seen another way is +/// numbered by its place. +#[test] +fn views_are_named_as_people_know_them() { + let mut h = Harness::new(); + let (sheet, front, top) = drawing(&mut h); + let d = h.app.session.drawing("test").unwrap().clone(); + assert_eq!(view_name(&d, front), solidcraft_ui_text::tr("ui.drawing_export.view_front")); + assert_eq!(view_name(&d, top), solidcraft_ui_text::tr("ui.drawing_export.view_top")); + let again = + h.app.run("drawing.view.base", json!({"sheet": ids::encode(sheet), "view": "front", "scale": "1:4", "position_mm": [320, 80]})).unwrap(); + let again = ids::decode(again["view"].as_str().unwrap()).unwrap(); + let d = h.app.session.drawing("test").unwrap().clone(); + let front_name = solidcraft_ui_text::tr("ui.drawing_export.view_front"); + assert!(view_name(&d, front).starts_with(front_name) && view_name(&d, front) != view_name(&d, again)); +} + +/// Cancel while sheets are being written stops them: the one waiting is never written, the one +/// under way stops, and the window stays to say so. Export pressed again meanwhile keeps the window +/// and its sheets instead of leaving them writing with nothing to say what they did. An export that +/// isn't the window's, waiting behind it, goes on. +#[test] +fn cancel_while_sheets_are_written_stops_them_and_says_so() { + let mut h = Harness::new(); + let (sheet, ..) = drawing(&mut h); + h.app.start(ID); + h.frames(3); + h.step(&json!({"click": {"handle": "drawing:export:sheet:Sheet 2"}})).unwrap(); + h.frames(2); + // The first sheet's worker waits to be let go, so both sheets are still to be written. + let (started, release) = hold_next_worker(&mut h); + answer_saves_with(&mut h, "held.svg"); + h.step(&json!({"click": {"handle": "dialog:OK"}})).unwrap(); + until_started(&mut h, &started); + let other = other_export(&mut h, sheet, "other.svg"); + let jobs = |h: &Harness| h.app.drawing_workspace.export.as_ref().map(|e| e.jobs.len()); + assert_eq!(jobs(&h), Some(2)); + + // The window's own guards, called as its buttons do: while a file job runs the app holds clicks + // and keys, but not once the progress card's Cancel has let go of a sheet still finishing. + open(&mut h.app); + h.frames(1); + assert_eq!(jobs(&h), Some(2), "a second Export keeps the sheets under way"); + + close(&mut h.app); + h.frames(1); + let export = h.app.drawing_workspace.export.as_ref().expect("the window stays while the sheets stop"); + assert!(export.stopping && !export.close_when_done); + release.send(()).unwrap(); + wait(&mut h); + for name in ["held - Sheet 1.svg", "held - Sheet 2.svg"] { + assert!(!h.dir.join(name).exists(), "{name} written after Cancel"); + } + let export = h.app.drawing_workspace.export.as_ref().expect("the window says what Cancel stopped"); + let said: Vec<&str> = export.outcome.iter().map(|(_, line)| line.as_str()).collect(); + let stopped = solidcraft_ui_text::tr("ui.drawing_export.stopped"); + assert!(said.len() == 2 && said.iter().all(|line| line.contains(stopped)), "{said:?}"); + assert!(!export.busy() && !export.stopping); + assert!(h.app.file_load.idle()); + assert_eq!(other.try_recv().ok().map(|r| r["ok"].clone()), Some(json!(true)), "the other export went on"); + assert!(h.dir.join("other.svg").exists()); + + // With nothing under way, Cancel closes the window. + h.step(&json!({"click": {"handle": "dialog:Cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.drawing_workspace.export.is_none()); +} + +/// The status is read when the window opens, after a change to the design and after the drawing's +/// views are drawn, and not otherwise: each read measures every dimension of the drawing. +#[test] +fn the_status_is_read_again_only_when_what_it_says_can_change() { + let mut h = Harness::new(); + let (_, front, _) = drawing(&mut h); + h.app.start(ID); + h.frames(3); + let status = |h: &Harness| h.app.drawing_workspace.export.as_ref().and_then(|e| e.status.clone()); + let forget = |h: &mut Harness| { + if let Some(export) = h.app.drawing_workspace.export.as_mut() { + export.status = None; + } + }; + assert!(status(&h).is_some(), "read as the window opens"); + forget(&mut h); + // Two seconds of frames with nothing changed read nothing. + h.frames(120); + assert!(status(&h).is_none(), "read again with nothing changed"); + + // The sheet page draws the views by itself now, so they are drawn by the time the window reads: + // what it read says so. + let drawn = h.app.session.execute("drawing.status", &json!({})).unwrap(); + let front_view = drawn["views"].as_array().and_then(|views| views.iter().find(|v| v["view"] == json!(ids::encode(front)))).cloned(); + assert_eq!(front_view.map(|v| v["status"].clone()), Some(json!("current")), "{drawn}"); + + forget(&mut h); + h.frames(3); + assert!(status(&h).is_none()); + h.app.run("drawing.view.edit", json!({"view": ids::encode(front), "set": {"scale": "1:4"}})).unwrap(); + h.frames(1); + assert!(status(&h).is_some(), "read again after a change to the design"); +} + +/// An import or export under way that isn't the window's is never stopped by its Cancel: only the +/// window's sheets waiting behind it are dropped. +#[test] +fn cancel_stops_only_the_windows_own_sheets() { + let mut h = Harness::new(); + let (sheet, ..) = drawing(&mut h); + h.app.start(ID); + h.frames(3); + let (started, release) = hold_next_worker(&mut h); + let other = other_export(&mut h, sheet, "other.svg"); + until_started(&mut h, &started); + answer_saves_with(&mut h, "mine.svg"); + // OK, as the window's own button would (the other export's progress card covers it now). + export_now(&mut h.app, true); + let began = std::time::Instant::now(); + while !h.app.drawing_workspace.export.as_ref().is_some_and(Export::busy) { + h.frames(1); + assert!(began.elapsed().as_secs() < 30, "the window's sheet was not queued"); + } + close(&mut h.app); + h.frames(1); + release.send(()).unwrap(); + wait(&mut h); + assert_eq!(other.try_recv().ok().map(|r| r["ok"].clone()), Some(json!(true)), "the other export went on"); + assert!(h.dir.join("other.svg").exists() && !h.dir.join("mine.svg").exists()); + let export = h.app.drawing_workspace.export.as_ref().expect("the window says what Cancel stopped"); + let stopped = solidcraft_ui_text::tr("ui.drawing_export.stopped"); + let said: Vec<&str> = export.outcome.iter().map(|(_, line)| line.as_str()).collect(); + assert!(said.len() == 1 && said.iter().all(|line| line.contains(stopped)), "{said:?}"); +} diff --git a/crates/ui-egui/src/drawing_workspace.rs b/crates/ui-egui/src/drawing_workspace.rs index 486f29da466..a522882d494 100644 --- a/crates/ui-egui/src/drawing_workspace.rs +++ b/crates/ui-egui/src/drawing_workspace.rs @@ -26,6 +26,8 @@ pub struct State { pub settings_open: bool, sheet_notice: Option, options: Option, + /// The Export window's choices while it is open (`drawing_export_panel`). + pub(crate) export: Option, placement: Option, note: Option, add_sheet: Option, @@ -104,11 +106,19 @@ pub(crate) fn placing_note(app: &SolveApp) -> bool { } pub fn can_open_options(id: &str) -> bool { - Tool::for_command(id).is_some() || matches!(id, "drawing.sheet.add" | "drawing.sheet.set") + Tool::for_command(id).is_some() || matches!(id, "drawing.sheet.add" | "drawing.sheet.set") || id == crate::drawing_export_panel::ID } /// Dismiss the current Drawing inspector without touching source or drawing data. pub fn close_panel(app: &mut SolveApp) -> bool { + let open = app.drawing_workspace.export.is_some() | reset_panels(app); + crate::drawing_export_panel::close(app); + open +} + +/// Dismiss every Drawing panel but Export, which stays while it is writing sheets +/// ([`crate::drawing_export_panel::give_way`]); whether one was open. +fn reset_panels(app: &mut SolveApp) -> bool { let open = app.drawing_workspace.settings_open || app.drawing_workspace.options.is_some() || app.drawing_workspace.add_sheet.is_some() @@ -125,12 +135,19 @@ pub fn close_panel(app: &mut SolveApp) -> bool { open } -/// Toolbar clicks inspect options. Engine execution still uses command parameters directly. +/// Toolbar clicks inspect options. Engine execution still uses command parameters directly. Export +/// opens its window (`ui.start drawing.export`); `engine.execute` still runs the command alone. pub fn start(app: &mut SolveApp, id: &str) -> bool { if !active(app) || !can_open_options(id) { return false; } - close_panel(app); + if id == crate::drawing_export_panel::ID { + reset_panels(app); + crate::drawing_export_panel::open(app); + return true; + } + reset_panels(app); + crate::drawing_export_panel::give_way(app); match id { "drawing.sheet.add" => open_add_sheet(app), "drawing.sheet.set" => app.drawing_workspace.settings_open = true, @@ -250,7 +267,8 @@ fn sheet_settings_actions(app: &mut SolveApp, ui: &mut egui::Ui) { fn toggle_sheet_settings(app: &mut SolveApp) { let open = !app.drawing_workspace.settings_open; - close_panel(app); + reset_panels(app); + crate::drawing_export_panel::give_way(app); app.drawing_workspace.settings_open = open; } @@ -687,7 +705,7 @@ fn show_delete_sheet(app: &mut SolveApp, ctx: &egui::Context) { pub fn panel(app: &mut SolveApp, ui: &mut egui::Ui) { app.drawing_workspace.settings = None; - if !active(app) || (!app.drawing_workspace.settings_open && app.drawing_workspace.options.is_none()) { + if !active(app) || !panel_open(app) { return; } let left = app.preferences.drawing_panel_side == "left"; @@ -763,13 +781,21 @@ fn floating_panel(app: &mut SolveApp, ui: &mut egui::Ui, left: bool, width: f32) } fn panel_title(app: &SolveApp) -> &'static str { + if app.drawing_workspace.export.is_some() { + return solidcraft_ui_text::tr("ui.drawing_export.title"); + } app.drawing_workspace.options.map_or_else(|| solidcraft_ui_text::tr("cmd.drawing_sheet_set"), Tool::title) } pub(crate) fn inspector_visible(app: &SolveApp) -> bool { active(app) && app.preferences.drawing_sheets_visibility != "legacy" - && (app.drawing_workspace.settings_open || app.drawing_workspace.options.is_some()) + && panel_open(app) +} + +/// A right-hand panel is open: Sheet Settings, a tool's options or Export. +fn panel_open(app: &SolveApp) -> bool { + app.drawing_workspace.settings_open || app.drawing_workspace.options.is_some() || app.drawing_workspace.export.is_some() } pub(crate) fn inspector_title(app: &SolveApp) -> &str { @@ -783,6 +809,10 @@ pub(crate) fn inspector_contents(app: &mut SolveApp, ui: &mut egui::Ui) { } fn panel_body(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.drawing_workspace.export.is_some() { + crate::drawing_export_panel::body(app, ui); + return; + } let options = app.drawing_workspace.options; ui.horizontal(|ui| { ui.heading(panel_title(app)); @@ -814,7 +844,9 @@ pub(crate) fn inset(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) } fn panel_fields(app: &mut SolveApp, ui: &mut egui::Ui) { - if let Some(placement) = &mut app.drawing_workspace.placement { + if app.drawing_workspace.export.is_some() { + crate::drawing_export_panel::body(app, ui); + } else if let Some(placement) = &mut app.drawing_workspace.placement { let finished = inset(ui, |ui| { placement.fields(ui, &app.session.doc.name); panels::finish_placement(ui) diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 9c6510bc4e1..6ea04bb7985 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -419,6 +419,21 @@ impl FileLoad { }); running.into_iter().chain(waiting).chain(self.queued.iter().map(entry)).collect() } + + /// Stop only the sheet exports to `paths` (the Export window's Cancel): those waiting are + /// dropped and answered as cancelled; the one being written is told to stop and answers once + /// its worker says whether it published the file. Every other file operation goes on. + pub(crate) fn cancel_sheet_exports(&mut self, paths: &[String]) { + let ours = |r: &Request| r.kind == Kind::ExportSheet && paths.contains(&r.path); + if let Some(r) = self.running.as_ref().filter(|r| ours(&r.request)) { + r.progress.cancel(); + } + let (stopped, kept): (VecDeque, VecDeque) = std::mem::take(&mut self.queued).into_iter().partition(|r| ours(r)); + self.queued = kept; + for q in stopped { + q.answer(Err("file operation cancelled".into())); + } + } } /// A file operation as the operations panel shows it ([`FileLoad::operations`]). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5a9ce04c796..777ad69f9cd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -211,6 +211,7 @@ mod blend_dialog_tests; #[cfg(test)] mod boundary_dialog_tests; pub(crate) mod display_lod; +pub mod drawing_export_panel; pub mod drawing_jobs; pub mod drawing_sheet_page; pub mod drawing_workspace; diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 6e6e4dc03d3..09ca931757d 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -342,7 +342,7 @@ pub const SECTIONS: &[Section] = &[ promoted: 3, ids: &["drawing.revision", "drawing.revise.planned", "drawing.revision.tag.add.planned"], }, - Section { tab: "DRAWING REVIEW", panel: "OUTPUT", promoted: 2, ids: &["drawing.export.planned", "drawing.print"] }, + Section { tab: "DRAWING REVIEW", panel: "OUTPUT", promoted: 2, ids: &["drawing.export", "drawing.print"] }, Section { tab: "MODEL", panel: "SKETCH", @@ -666,7 +666,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[ ("drawing.check.planned", "Check Drawing"), ("drawing.dimension", "Dimension"), ("drawing.dimension.from_model.planned", "Model Dims."), - ("drawing.export.planned", "Export"), + ("drawing.export", "Export"), ("drawing.hole_callout", "Hole Callout"), ("drawing.image", "Image"), ("drawing.leader", "Leader Note"),