From 93c57e66ba0d5dcf7d951220d51e241f908f4de6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 00:27:16 +0300 Subject: [PATCH 01/23] Restore b10 state --- README.md | 11 +- WHATS_NEW.md | 253 ++++ apps/cadcraft/build.rs | 8 + apps/cadcraft/src/main.rs | 3 +- apps/cadcraft/src/workspace.rs | 15 + crates/doc/src/entity.rs | 13 + crates/doc/src/extents.rs | 1 + crates/doc/src/tables.rs | 9 + crates/doc/src/tables/tablebreak.rs | 29 + crates/engine/src/cmd/annotate.rs | 1 + crates/engine/src/cmd/annotate_tests.rs | 14 + crates/engine/src/cmd/file.rs | 3 +- crates/engine/src/cmd/gripcmds.rs | 32 +- crates/engine/src/cmd/griphot.rs | 15 +- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/modify2.rs | 82 +- crates/engine/src/cmd/modify2_tests.rs | 81 +- crates/engine/src/cmd/props.rs | 88 +- crates/engine/src/cmd/table/cells.rs | 127 +- crates/engine/src/cmd/trimextend.rs | 54 +- crates/engine/src/grips.rs | 235 ++- crates/engine/src/grips_tests.rs | 78 +- crates/engine/src/guard.rs | 9 + crates/engine/src/lib.rs | 12 +- crates/engine/src/prompt.rs | 33 + crates/engine/tests/annotative.rs | 1 + crates/engine/tests/mtext_columns.rs | 1 + crates/engine/tests/trim_extend_options.rs | 47 + crates/fonts/src/lib.rs | 95 +- crates/fonts/src/shx.rs | 705 +++++++++ crates/fonts/src/ttf.rs | 219 ++- crates/io/src/dxf_mleader.rs | 18 +- crates/io/src/dxf_read.rs | 7 + crates/io/src/dxf_write.rs | 25 +- crates/io/src/tests.rs | 1 + crates/io/tests/followups_626.rs | 1 + crates/io/tests/mleader_content.rs | 1 + crates/io/tests/mleader_roundtrip.rs | 21 + crates/io/tests/tables_objects_roundtrip.rs | 22 + crates/render/src/dim.rs | 114 +- crates/render/src/lib.rs | 163 +- crates/render/src/linetype_text.rs | 2 +- crates/render/src/paper.rs | 8 +- crates/render/src/table.rs | 2 +- crates/ui-egui/src/canvas.rs | 240 ++- crates/ui-egui/src/chrome.rs | 143 +- crates/ui-egui/src/closing.rs | 2 +- crates/ui-egui/src/custom_patterns.rs | 209 +++ crates/ui-egui/src/dialogs.rs | 3 +- crates/ui-egui/src/dimstyles.rs | 1247 ++++++++++++++++ crates/ui-egui/src/docking.rs | 178 ++- crates/ui-egui/src/exchange.rs | 1 + crates/ui-egui/src/hatchdlg.rs | 63 +- crates/ui-egui/src/i18n/mod.rs | 108 ++ crates/ui-egui/src/i18n/ru.tsv | 341 +++++ crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/i18n/uk.tsv | 324 ++++ crates/ui-egui/src/icons.rs | 83 +- crates/ui-egui/src/lib.rs | 60 +- crates/ui-egui/src/managers.rs | 14 +- crates/ui-egui/src/menus.rs | 30 +- crates/ui-egui/src/mtext_editor.rs | 394 ++++- crates/ui-egui/src/opening.rs | 4 +- crates/ui-egui/src/options/dialog.rs | 182 ++- crates/ui-egui/src/options/mod.rs | 53 +- crates/ui-egui/src/palettes.rs | 336 ++++- crates/ui-egui/src/theme.rs | 150 +- crates/ui-egui/src/toolbar.rs | 1305 +++++++++++++++++ .../tests/clipboard_between_drawings.rs | 83 ++ crates/ui-egui/tests/dialog_dispatch.rs | 1 + crates/ui-egui/tests/dimstyles.rs | 117 ++ crates/ui-egui/tests/docking_workflows.rs | 2 + crates/ui-egui/tests/rtl_names.rs | 17 + crates/ui-egui/tests/shared_controls.rs | 2 + crates/ui-egui/tests/text_double_click.rs | 21 +- crates/ui-egui/tests/text_editing.rs | 156 ++ crates/ui-egui/tests/toolbar_dock.rs | 117 ++ crates/ui-egui/tests/toolsets_ribbon.rs | 54 + crates/ui-egui/tests/workspace_focus.rs | 7 +- 79 files changed, 8360 insertions(+), 348 deletions(-) create mode 100644 WHATS_NEW.md create mode 100644 crates/fonts/src/shx.rs create mode 100644 crates/ui-egui/src/custom_patterns.rs create mode 100644 crates/ui-egui/src/dimstyles.rs create mode 100644 crates/ui-egui/src/toolbar.rs create mode 100644 crates/ui-egui/tests/clipboard_between_drawings.rs create mode 100644 crates/ui-egui/tests/dimstyles.rs create mode 100644 crates/ui-egui/tests/rtl_names.rs create mode 100644 crates/ui-egui/tests/text_editing.rs create mode 100644 crates/ui-egui/tests/toolbar_dock.rs create mode 100644 crates/ui-egui/tests/toolsets_ribbon.rs diff --git a/README.md b/README.md index a259af4f34..328d2d65ed 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,11 @@

CADCraft

- Computer-aided design and drafting; an open-source, clean-room reimplementation of Autodesk AutoCAD, rebuilt in pure Rust. + Computer-aided design and drafting; an open-source, modern 2D and 3D CAD application, built in pure Rust.

- A fast, open-source take on the AutoCAD workflow: the command line, object snaps, layers, + A fast, open-source CAD workflow: the command line, object snaps, layers, dimensions, hatches, blocks and DXF drawings you already know. It runs natively on macOS, Windows, Linux and FreeBSD, and in the browser via WebAssembly.
By the ArtCraft team. @@ -247,6 +247,11 @@ accessible labels and keyboard focus. CADCraft keeps its multicolor icon painter disabled tint and tool commands. The native host saves workspace visibility and toolset choices atomically; `CADCRAFT_CONFIG_DIR` selects an isolated profile. Compact toolbar groups move into a More menu, and status readouts truncate with a full-value tooltip before they reach layout tabs. +The Tool Bar docks at the top (a row of buttons) or on the left edge (a column): drag its handle, +right-click it, or use **Window ▸ Tool Bar Position**. Drag a button along the bar to reorder it, +right-click it to remove it, right-click any Tool Sets button to add it, or pick commands in +**Window ▸ Customize Tool Bar...**. Every button's tooltip names the tool, its command, alias and +shortcut; the bar's position and buttons are saved with the workspace. Painted toolbar and tab controls have accessible labels and visible keyboard focus. Property controls remain application-specific. @@ -394,8 +399,6 @@ ArtCraft Team and are not covered by this license. They may be used only unmodif part of this repository and CADCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and modified versions must remove them. -Autodesk, AutoCAD and DWG are trademarks or registered trademarks of Autodesk, Inc. in the United States and/or other countries. CADCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Autodesk, Inc.; these names are used only to describe the workflows and file formats it is compatible with. -

ArtCraft
Made by the ArtCraft team and community. diff --git a/WHATS_NEW.md b/WHATS_NEW.md new file mode 100644 index 0000000000..81402b1264 --- /dev/null +++ b/WHATS_NEW.md @@ -0,0 +1,253 @@ +# CADCraft — что нового / What's new + +Изменения после версии 0.9.0. Новые записи добавляются сверху, с датой. +Пожалуйста, попробуйте описанное и напишите, что работает не так, чего не хватает и какие у вас есть идеи. + +Changes since version 0.9.0. New entries go on top, with a date. +Please try what is described here and tell us what doesn't work as expected, what is missing, and what ideas you have. + +--- + +## 20.10.2026 (0.9.0-b10) + +### Русский + +**Шрифты SHX** +- Текст в стилях со шрифтами SHX (romans.shx, simplex.shx, txt.shx, ивритские шрифты вроде GIL.SHX и другие) теперь рисуется этими шрифтами, если файл .shx лежит в одной из папок шрифтов («Инструменты ▸ Параметры ▸ Шрифты»). Читаются обычные шрифты SHX, Unicode-шрифты и big fonts (BIGFONT). +- Если в шрифте нет нужного символа, он берётся из встроенного шрифта CADCraft. +- Строка с ивритом выкладывается справа налево, как в AutoCAD. +- Найденные шрифты SHX больше не попадают в сообщение «Не найдены шрифты». + +**Штриховка: вкладка «Свои образцы»** +- В окне Hatch and Gradient («Штриховка и градиент») появилась третья вкладка «Свои образцы» (Custom Patterns). Укажите папку с файлами .pat (вручную или кнопкой «Обзор…»), и программа покажет все образцы из этих файлов списком. +- Рядом со списком видно, как выглядит выбранный образец. +- На вкладке есть угол, масштаб и исходная точка, как на вкладке «Шаблон». Справа те же разделы Boundaries и «Параметры». +- Папка запоминается. Кнопка «Обновить» перечитывает её после того, как вы добавили или изменили файлы. + +**Листы (layouts)** +- Найдена причина, по которой листы из «אריה צוק» выглядели меньше, чем в AutoCAD. Чертёж в дюймовой системе (MEASUREMENT = 0), а листы настроены в миллиметрах. CADCraft брал единицы листа из настроек чертежа, и лист A3 получался 16,5 × 11,7 единицы вместо 420 × 297. Теперь единицы бумаги берутся из настроек самого листа, как в AutoCAD, и рамка помещается на лист так же. +- При сохранении эти единицы записываются в файл. + +**Темы оформления** +- Добавлены темы «Чёрная» и «Светло-голубая» (#85abf6). Их можно выбрать в «Инструменты ▸ Параметры» или в меню «Вид ▸ Тема интерфейса». + +**Ввод у курсора** +- Текст, который вы набираете в командной строке, теперь дублируется в окошке рядом с курсором: число сторон многоугольника, имя, параметр или имя команды. Окошко показывается и при выключенном динамическом вводе (F12). + +### English + +**SHX fonts** +- Text in styles that use SHX fonts (romans.shx, simplex.shx, txt.shx, Hebrew fonts such as GIL.SHX and others) is now drawn with those fonts when the .shx file is in one of the font folders (Tools ▸ Options ▸ Fonts). Regular SHX shape fonts, Unicode fonts and big fonts are read. +- Characters a font lacks are taken from CADCraft's built-in font. +- A line with Hebrew is laid out right to left, as in AutoCAD. +- SHX fonts that are found no longer appear in the "Fonts not found" list. + +**Hatch: Custom Patterns tab** +- The Hatch and Gradient window has a third tab, Custom Patterns. Point it at a folder of .pat files (type the path or use Browse…) and it lists every pattern in those files. +- A preview of the selected pattern is shown beside the list. +- The tab has angle, scale and hatch origin, as the Pattern tab does. Boundaries and Options are on the right as before. +- The folder is remembered. Reload reads it again after you add or change files. + +**Layouts** +- Found why the layouts of "אריה צוק" looked smaller than in AutoCAD. The drawing is in inches (MEASUREMENT = 0) but its layouts are set up in millimetres. CADCraft took the paper units from the drawing, so an A3 sheet came out 16.5 × 11.7 units instead of 420 × 297. Paper units now come from the layout's own settings, as in AutoCAD, and the title block fits the sheet the same way. +- These units are written back when the drawing is saved. + +**Interface themes** +- Two new themes: Black and Light Blue (#85abf6). Choose them in Tools ▸ Options or View ▸ Interface Theme. + +**Typed input by the cursor** +- What you type at the command line is now repeated in a small box next to the cursor: a polygon's number of sides, a name, an option or a command name. The box shows even with Dynamic Input (F12) off. + +--- + +## 20.10.2026 (0.9.0-b9) + +### Русский + +**Палитра «Наборы инструментов» (Tool Sets)** +- Палитру можно превратить в ленту (ribbon), как в Microsoft Office. Лента встаёт прямо под строкой меню «Файл, Правка, Вид…». +- У ленты вкладки по задачам: «Рисование», «Модификация», «Аннотации», «Блок», «Параметризация», «3D-моделирование». На вкладке инструменты сгруппированы, название группы подписано снизу. Крупные кнопки подписаны, мелкие стоят столбиками по три. +- Если перетащить палитру к верхнему краю чертежа, она тоже становится лентой. +- Правый щелчок в любом месте палитры или ленты открывает меню: «Плавающая панель», «Закрепить слева», «Превратить в ленту», «Переместить в группу» (к слоям и свойствам или к другой группе панелей), «Закрыть панель». Пункта, который уже действует, в меню нет. +- Правый щелчок по кнопке инструмента показывает это же меню, а под ним прежние пункты раздела «Показывать на панели». + +**Обрезать и Удлинить (TRIM / EXTEND)** +- Если перед запуском команды объекты уже выделены, они становятся режущими (граничными) кромками. Пока команда работает, они остаются подсвеченными. Подсветка снимается, когда команда завершается или отменяется. +- Щелчок в пустом месте начинает линию-«забор». Второй щелчок задаёт её конец, и всё, что эта линия пересекает, обрезается (удлиняется). Раньше в этом случае открывалась прямоугольная рамка. Рамка по-прежнему доступна через параметр Crossing в командной строке. + +**Значки** +- «Переместить»: крупные стрелки. +- «Повернуть»: стрелка на конце дуги. +- «Обрезать»: ножницы, разрезающие линию надвое. +- «Удлинить»: крупная стрелка. +- «Параллельный» размер (Aligned): значок повёрнут на 13°. + +### English + +**The Tool Sets palette** +- The palette can turn into a ribbon, as in Microsoft Office. The ribbon sits right under the File, Edit, View… menu bar. +- The ribbon has a tab per task: Draw, Modify, Annotate, Block, Parametric, 3D Modeling. On each tab the tools are grouped, with the group's name underneath. Large buttons have labels, small ones are stacked in columns of three. +- Dragging the palette to the top edge of the drawing also turns it into the ribbon. +- Right-clicking anywhere in the palette or the ribbon opens a menu: Float Panel, Pin to Left, Transform to Ribbon, Move to Group (beside Layers/Properties or another panel group), Close Panel. The option already in effect is left out. +- Right-clicking a tool button shows the same menu, with the existing "Show on Tool Bar" items under it. + +**TRIM / EXTEND** +- Objects selected before you start the command become its cutting (boundary) edges. They stay highlighted while the command runs, and the highlight goes away when the command ends or is cancelled. +- A click in empty space starts a fence line. A second click sets its end point, and everything the line crosses is trimmed (extended). Before this, a click in empty space opened a rectangular window. The window is still available through the Crossing option. + +**Icons** +- Move: larger arrows. +- Rotate: an arrowhead at the end of the arc. +- Trim: scissors cutting a line in two. +- Extend: a larger arrow. +- Aligned dimension: the icon is turned 13°. + +--- + +## 19.10.2026 (0.9.0-b8) + +### Русский + +**Размеры: ручка текста** +- «Растянуть» двигает размерную линию вместе с текстом поперёк. Текст при этом остаётся на своём месте относительно стрелок. +- «Переместить с размерной линией» ставит текст туда, где курсор, в том числе за стрелки. Размерная линия продлевается до текста. +- Пока вы тянете ручку, видно то же самое, что получится после щелчка. + +**Мультивыноски в палитре «Свойства»** +- Можно менять стиль мультивыноски, тип выноски (прямая или сплайн), стрелку, размер стрелки, длину полки и высоту текста. +- Стрелку можно выбрать из того же списка, что у размеров, включая пользовательские блоки-стрелки чертежа. +- Стрелки мультивыносок из файлов DWG и DXF теперь читаются и сохраняются. Раньше все мультивыноски рисовались с замкнутой залитой стрелкой. + +**Копирование между чертежами** +- Ctrl+C в одном открытом чертеже и Ctrl+V в другом теперь работают. Раньше после щелчка по вкладке другого чертежа программа не реагировала на Ctrl+V и на ввод команд. + +**Блоки на листах** +- Двойной щелчок по блоку на листе (layout) открывает редактор блоков, как в пространстве модели. + +**Имена файлов на иврите** +- На вкладках, в списке недавних файлов и в окне «Сохранить изменения?» имя читается так же, как в проводнике: буквы справа налево, «.dwg» справа. + +### English + +**Dimensions: the text grip** +- Stretch moves the dimension line across together with the text. The text keeps its place relative to the arrowheads. +- Move with Dim Line puts the text where the cursor is, even past the arrowheads. The dimension line is extended to reach the text. +- While you drag the grip, you see exactly what you will get when you click. + +**Multileaders in the Properties palette** +- You can change the multileader style, the leader type (straight or spline), the arrowhead, the arrowhead size, the landing distance and the text height. +- The arrowhead list is the same one dimensions use, including the drawing's own arrowhead blocks. +- Multileader arrowheads are now read from and saved to DWG and DXF files. Before this, every multileader was drawn with a closed filled arrowhead. + +**Copying between drawings** +- Ctrl+C in one open drawing and Ctrl+V in another now works. Before this, after clicking another drawing's tab, the program ignored Ctrl+V and typed commands. + +**Blocks on layouts** +- Double-clicking a block on a layout opens the Block Editor, as it does in model space. + +**Hebrew file names** +- On the drawing tabs, in the recent files list and in the "Save changes?" window, the name reads as it does in File Explorer: letters right to left, ".dwg" on the right. + +--- + +## 19.10.2026 (0.9.0-b7) + +### Русский + +**Размеры** +- Пользовательские стрелки (блоки чертежа, например hatz или DIM1) рисуются правильно, с нужным размером и поворотом. Раньше они заменялись на «Замкнутую залитую». +- В «Свойствах» и в редакторе размерного стиля такая стрелка показывается как «Пользовательская: имя блока», и её можно выбрать из списка. +- «Переместить с выноской»: под текстом рисуется полочка, а от размерной линии к ней идёт выноска. +- Ручка текста стоит там, где текст виден на экране. +- Текст, который в AutoCAD сдвинут вдоль размерной линии, после открытия файла остаётся на месте и не прыгает в середину при первой правке. + +**Блоки** +- Двойной щелчок по блоку открывает редактор блоков. Если у блока есть атрибуты, открывается их редактирование. Внешние ссылки двойной щелчок не трогает. + +### English + +**Dimensions** +- User arrowheads (blocks of the drawing, such as hatz or DIM1) are drawn correctly, at the right size and angle. Before this, they were replaced with "Closed filled". +- In Properties and in the dimension style editor such an arrowhead shows as "User Arrow: block name" and can be picked from the list. +- Move with Leader: a landing line is drawn under the text, with a leader from the dimension line to it. +- The text grip sits where the text appears on screen. +- Text that was moved along the dimension line in AutoCAD stays in place after the file is opened, and no longer jumps to the middle on the first edit. + +**Blocks** +- Double-clicking a block opens the Block Editor. If the block has attributes, their editor opens instead. External references are left alone. + +--- + +## 19.10.2026 + +### Русский + +**Размерные стили** +- Новый диспетчер размерных стилей: создание, изменение, сравнение стилей и выбор текущего. +- Редактор стиля с вкладками: «Линии», «Символы и стрелки», «Текст», «Размещение», «Основные единицы», «Альтернативные единицы», «Допуски». +- В «Свойствах» у выбранного размера видны настройки его стиля (стрелки, линии, текст и другие). Изменение настройки применяется только к этому размеру, как переопределение в AutoCAD. +- У ручки текста размера появилось меню: «Переместить с размерной линией», «Переместить только текст», «Переместить с выноской», «Над размерной линией», «По центру по вертикали» и «Восстановить положение текста». + +**Интерфейс** +- Кнопка приложения (меню «Файл») стоит первой на панели инструментов. В меню есть пакетная печать. +- Окно «Параметры» больше не меняет размер при переходе между вкладками. + +### English + +**Dimension styles** +- New Dimension Style Manager: create, modify and compare styles, and set the current one. +- Style editor with tabs: Lines, Symbols and Arrows, Text, Fit, Primary Units, Alternate Units, Tolerances. +- In Properties, a selected dimension shows its style settings (arrowheads, lines, text and more). Changing a setting changes only that dimension, like an override in AutoCAD. +- The dimension text grip has a menu: Move with Dim Line, Move Text Only, Move with Leader, Above Dim Line, Center Vertically and Reset Text Position. + +**Interface** +- The application button (the File menu) is the first button on the Tool Bar. Its menu includes Batch Print. +- The Options window keeps the same size on every tab. + +--- + +## 18.10.2026 + +### Русский + +**Панели инструментов** +- Панель инструментов можно закрепить сверху или слева, перетащив её за маркер. +- Кнопки можно переставлять перетаскиванием, добавлять и убирать в окне «Настроить панель инструментов». Там же можно вернуть всё по умолчанию. +- Подсказки у кнопок показывают название команды, её псевдоним и сочетание клавиш. +- Отдельные панели «Наборы инструментов» и «Слои» тоже закрепляются сверху или слева и настраиваются. На панели «Слои» есть выпадающий список текущего слоя. + +**Шрифты** +- В «Инструменты ▸ Параметры ▸ Шрифты» можно добавить свои папки со шрифтами (.ttf, .otf, .ttc). Они просматриваются раньше системных шрифтов. +- После открытия чертежа программа сообщает, каких шрифтов не хватает и каким шрифтом рисуется такой текст. + +**Редактирование текста на месте** +- Двойной щелчок по тексту, многострочному тексту, размеру, мультивыноске или ячейке таблицы открывает редактор прямо на чертеже. +- В ячейках таблицы Tab переходит к следующей ячейке, Shift+Tab к предыдущей, Alt+↑/↓ к ячейке выше или ниже. +- В тексте размера можно вставить измеренное значение (<>) или вернуть только измеренное значение. + +**Редактор текста** +- Панель редактора нарисована заново, кнопки стоят в два ряда. Есть кнопка закрытия. +- Добавлено меню «Дополнительные символы»: ≈, ≠, ≤, ≥, ×, ÷, √, ∞, Δ, Ω, µ, π, α, β, γ, φ, ², ³, ½, ¼, ¾, ‰ и другие. +- Если в шрифте текста нет нужного символа, он берётся из запасного шрифта, а не пропадает. + +### English + +**Tool bars** +- The Tool Bar can be docked at the top or on the left by dragging its handle. +- Buttons can be reordered by dragging, and added or removed in the Customize Tool Bar window. You can also reset everything to the defaults there. +- Button tooltips show the command name, its alias and its keyboard shortcut. +- The separate Tool Sets and Layers tool bars can also be docked at the top or on the left, and customized. The Layers bar has a current layer drop-down. + +**Fonts** +- In Tools ▸ Options ▸ Fonts you can add your own font folders (.ttf, .otf, .ttc). They are searched before the system fonts. +- After a drawing opens, the program reports which fonts are missing and which font that text is drawn with instead. + +**Editing text in place** +- Double-clicking text, multiline text, a dimension, a multileader or a table cell opens the editor right on the drawing. +- In table cells, Tab moves to the next cell, Shift+Tab to the previous one, Alt+↑/↓ to the cell above or below. +- In dimension text you can insert the measured value (<>) or go back to the measured value only. + +**Text editor** +- The editor's toolbar has been redrawn, with buttons in two rows. There is a close button. +- New Additional symbols menu: ≈, ≠, ≤, ≥, ×, ÷, √, ∞, Δ, Ω, µ, π, α, β, γ, φ, ², ³, ½, ¼, ¾, ‰ and more. +- When the text's font has no glyph for a symbol, it is taken from a fallback font instead of disappearing. diff --git a/apps/cadcraft/build.rs b/apps/cadcraft/build.rs index 1349ebe367..82140b9d5b 100644 --- a/apps/cadcraft/build.rs +++ b/apps/cadcraft/build.rs @@ -5,6 +5,7 @@ fn main() { println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft.ico"); println!("cargo:rerun-if-env-changed=CADCRAFT_REQUIRE_WINRES"); println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_SHA"); + println!("cargo:rerun-if-env-changed=CADCRAFT_VERSION_LABEL"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } @@ -18,6 +19,13 @@ fn main() { .set("LegalCopyright", "Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", "cadcraft.exe") .set("InternalName", "cadcraft"); + // A build's own label (`0.9.0-b3`) in the file's Properties ▸ Details. + if let Ok(label) = std::env::var("CADCRAFT_VERSION_LABEL") { + let label: String = label.chars().filter(|c| c.is_ascii_graphic()).take(40).collect(); + if !label.is_empty() { + res.set("ProductVersion", &label).set("FileVersion", &label); + } + } if let Err(e) = res.compile() { if std::env::var_os("CADCRAFT_REQUIRE_WINRES").is_some() { eprintln!("embedding Windows resources failed: {e}"); diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 157294ac58..64e7b67a90 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -143,6 +143,7 @@ fn services() -> Services { .save_file() .map(|p| p.to_string_lossy().to_string()) })), + pick_folder: Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))), } } @@ -198,7 +199,7 @@ fn app_icon() -> Option { fn version_string() -> String { let sha = option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"); - format!("cadcraft {} ({sha})", env!("CARGO_PKG_VERSION")) + format!("cadcraft {} ({sha})", cadcraft_ui_egui::VERSION) } /// The control port from `--control ` or `CADCRAFT_CONTROL_PORT` (`source`); a value that is diff --git a/apps/cadcraft/src/workspace.rs b/apps/cadcraft/src/workspace.rs index e2a429d94c..aae343471f 100644 --- a/apps/cadcraft/src/workspace.rs +++ b/apps/cadcraft/src/workspace.rs @@ -39,6 +39,10 @@ fn snapshot(ui: &UiState) -> Result { if ui.collapsed_groups.len() > 64 || ui.collapsed_groups.iter().any(|name| name.len() > 256) { return Err("collapsedGroups exceeds the workspace size limit".into()); } + let bars = [&ui.toolbar_items, &ui.toolsets_bar.items, &ui.layers_bar.items]; + if bars.iter().any(|items| items.len() > 256 || items.iter().any(|item| item.len() > 64)) { + return Err("toolbarItems exceeds the workspace size limit".into()); + } if ui.history_lines > 12 { return Err("historyLines must be between 0 and 12".into()); } @@ -47,6 +51,10 @@ fn snapshot(ui: &UiState) -> Result { "showToolsets": ui.show_toolsets, "showPalettes": ui.show_palettes, "showToolbar": ui.show_toolbar, + "toolbarDock": ui.toolbar_dock, + "toolbarItems": ui.toolbar_items, + "toolsetsBar": ui.toolsets_bar, + "layersBar": ui.layers_bar, "showFileTabs": ui.show_file_tabs, "showStatusBar": ui.show_status_bar, "showCommandLine": ui.show_command_line, @@ -211,6 +219,13 @@ mod tests { show_command_line: false, toolset_tab: "Modeling".into(), collapsed_groups: vec!["Solid".into()], + toolbar_dock: cadcraft_ui_egui::toolbar::Dock::Left, + toolbar_items: vec!["line".into(), "|".into(), "circle".into()], + layers_bar: cadcraft_ui_egui::toolbar::BarState { + show: false, + dock: cadcraft_ui_egui::toolbar::Dock::Left, + items: vec!["layoff".into(), cadcraft_ui_egui::toolbar::LAYER_COMBO.into()], + }, history_lines: 5, dialog: Some("layers".into()), start_tab: true, diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 4d22c1753a..d872e2c512 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -710,6 +710,10 @@ pub struct MLeader { pub style: String, #[serde(default = "one")] pub arrow_size: f64, + /// Arrowhead of the leader lines: a DIMBLK-style name (`_DotSmall`, `_Open30`, `_None`…) or a + /// user arrowhead block of the drawing; empty for the style's (closed filled by default). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub arrow: String, /// Leader lines are smooth curves through their points (leader type Spline). An empty /// `leaders` is a multileader without a leader line (leader type None). #[serde(default)] @@ -720,6 +724,15 @@ pub struct MLeader { } impl MLeader { + /// The arrowhead it draws: its own, else its style's (in `d`). + pub fn arrow_in<'a>(&'a self, d: &'a crate::Drawing) -> &'a str { + if self.arrow.trim().is_empty() { + d.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(&self.style)).map_or("", |s| s.arrow_block.as_str()) + } else { + &self.arrow + } + } + /// Each leader line as drawn: through its points to the landing, smoothed for spline leaders. pub fn leader_paths(&self) -> Vec> { self.leaders diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index 0fbd73c814..be24d8b743 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -352,6 +352,7 @@ mod tests { text: Some(mtext.clone()), style: "Standard".into(), arrow_size: 1.0, + arrow: String::new(), spline: false, block: None, }; diff --git a/crates/doc/src/tables.rs b/crates/doc/src/tables.rs index f9824ec6d9..a5bcc7561d 100644 --- a/crates/doc/src/tables.rs +++ b/crates/doc/src/tables.rs @@ -594,6 +594,9 @@ impl DimStyle { pub struct MLeaderStyle { pub name: String, pub arrow_size: f64, + /// Arrowhead (a DIMBLK-style name or a user block); empty for closed filled. + #[serde(skip_serializing_if = "String::is_empty")] + pub arrow_block: String, pub text_height: f64, pub landing_gap: f64, pub dogleg: f64, @@ -607,6 +610,7 @@ impl Default for MLeaderStyle { MLeaderStyle { name: "Standard".into(), arrow_size: 0.18, + arrow_block: String::new(), text_height: 0.18, landing_gap: 0.09, dogleg: 0.36, @@ -735,6 +739,10 @@ pub struct PageSetup { pub width_mm: f64, pub height_mm: f64, pub margins_mm: [f64; 4], + /// The layout's paper units (DXF group 72): `Some(true)` millimetres, `Some(false)` inches; + /// `None` follows the drawing's MEASUREMENT. Paper space is drawn in these units. + #[serde(skip_serializing_if = "Option::is_none")] + pub mm_units: Option, pub landscape: bool, /// "layout" | "extents" | "display" | "window" | "limits". pub plot_area: String, @@ -760,6 +768,7 @@ impl Default for PageSetup { width_mm: 215.9, height_mm: 279.4, margins_mm: [6.35, 6.35, 6.35, 6.35], + mm_units: None, landscape: true, plot_area: "layout".into(), scale_to_fit: false, diff --git a/crates/doc/src/tables/tablebreak.rs b/crates/doc/src/tables/tablebreak.rs index 48137f1168..8366887f6f 100644 --- a/crates/doc/src/tables/tablebreak.rs +++ b/crates/doc/src/tables/tablebreak.rs @@ -162,6 +162,25 @@ impl Table { b } + /// The top-left corner, width and height of cell (`row`, `col`) — over its merged span — in + /// the part that holds the row. + pub fn cell_rect(&self, row: usize, col: usize) -> Option<(Vec2, f64, f64)> { + if col >= self.col_widths.len() || row >= self.row_heights.len() { + return None; + } + let (rs, cs) = + self.cells.get(row).and_then(|r| r.get(col)).and_then(|c| c.merged).map_or((1, 1), |(a, b)| (a.max(1) as usize, b.max(1) as usize)); + let x: f64 = self.col_widths.iter().take(col).map(|w| size(*w)).sum(); + let w: f64 = self.col_widths.iter().skip(col).take(cs).map(|w| size(*w)).sum(); + for part in self.parts() { + let Some(at) = part.rows.iter().position(|r| *r == row) else { continue }; + let y: f64 = part.rows.iter().take(at).map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum(); + let h: f64 = part.rows.iter().skip(at).take(rs).map(|r| size(self.row_heights.get(*r).copied().unwrap_or(0.0))).sum(); + return Some((part.origin + Vec2::new(x, -y), w, h)); + } + None + } + /// The cell (row, col) under `p`, in any part. pub fn cell_at_point(&self, p: Vec2) -> Option<(usize, usize)> { for part in self.parts() { @@ -216,6 +235,16 @@ mod tests { } } + #[test] + fn cell_rect_covers_the_merged_span_and_hostile_indices_are_none() { + let mut t = table(3); + assert_eq!(t.cell_rect(1, 1), Some((Vec2::new(2.0, -1.0), 3.0, 1.0))); + t.cells[0][0].merged = Some((1, 2)); + assert_eq!(t.cell_rect(0, 0), Some((Vec2::ZERO, 5.0, 1.0))); + assert_eq!(t.cell_rect(9, 0), None); + assert_eq!(t.cell_rect(0, usize::MAX), None); + } + #[test] fn unbroken_is_one_part() { let t = table(5); diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 48254955a3..839e56e719 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -454,6 +454,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< }), style: st.name.clone(), arrow_size: st.arrow_size * k, + arrow: String::new(), spline: false, block: None, })) diff --git a/crates/engine/src/cmd/annotate_tests.rs b/crates/engine/src/cmd/annotate_tests.rs index 4a68075721..d77644c87f 100644 --- a/crates/engine/src/cmd/annotate_tests.rs +++ b/crates/engine/src/cmd/annotate_tests.rs @@ -573,3 +573,17 @@ fn linetype_rename_updates_references() { assert!(s.execute("rename", &json!({ "table": "linetype", "from": "ByLayer", "to": "X" })).is_err()); assert_eq!(s.doc().unwrap().entity(by_layer).unwrap().common.linetype, "ByLayer"); } + +#[test] +fn missing_fonts_name_the_style_and_the_substitute() { + let mut s = Session::new(); + s.execute("style", &json!({ "name": "Gost", "font": "gost_cadcraft_missing.shx" })).unwrap(); + s.execute("style", &json!({ "name": "Gost2", "font": "GOST_CADCRAFT_MISSING.SHX" })).unwrap(); + let missing = s.execute("fonts.missing", &json!({})).unwrap(); + let list = missing.as_array().unwrap(); + assert_eq!(list.len(), 1, "one entry per font: {missing}"); + assert_eq!(list[0]["style"], "Gost"); + assert!(list[0]["substitute"].as_str().is_some_and(|s| !s.is_empty())); + let fonts = s.execute("fonts.list", &json!({})).unwrap(); + assert!(fonts["folders"].is_array() && fonts["fonts"].is_array()); +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index b08b9d7e87..c6c977ca24 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -295,7 +295,8 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result) -> usize { +fn add_read(s: &mut Session, mut drawing: Drawing, binary_dxf: bool, name: &str, path: Option) -> usize { + crate::grips::adopt_file_dim_text(&mut drawing); let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); if let Some(st) = s.docs.get_mut(i) { diff --git a/crates/engine/src/cmd/gripcmds.rs b/crates/engine/src/cmd/gripcmds.rs index cf637d9c80..b6ca5f862b 100644 --- a/crates/engine/src/cmd/gripcmds.rs +++ b/crates/engine/src/cmd/gripcmds.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use super::curves; use super::*; -use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip}; +use crate::grips::{GripAction, GripMode, mode_matrix, stretch_grip}; use crate::{EngineError, Result, Session}; pub fn specs() -> Vec { @@ -22,7 +22,7 @@ pub fn specs() -> Vec { CommandSpec::new("grip.mirror", "Grip Mirror", run_grip_mirror) .params("{handles?, base | baseHandle+index, to (second mirror point), copy?}"), CommandSpec::new("grip.option", "Grip Option", run_grip_option).params( - "{handle, index, option: addVertex|removeVertex|toArc|toLine|lengthen|radius, to? (point), value? (lengthen: length change; radius)}", + "{handle, index, option: addVertex|removeVertex|toArc|toLine|lengthen|radius|moveWithDimLine|moveTextOnly|moveWithLeader|aboveDimLine|centerVertically|resetTextPosition, to? (point), value? (lengthen: length change; radius)}", ), CommandSpec::new("grip", "Grip Edit", run_grip) .params("interactive: select grips, then the grip modes with [Base point/Copy/Undo/Reference/eXit]; JSON: use grip.stretch/move/rotate/scale/mirror") @@ -45,11 +45,14 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result { return Err(EngineError::Other("The object is on a locked layer.".into())); } let e = curves::entity(s, h)?; - let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?; + // `to` is where the grip as shown goes; a dimension's text grip shows where the text is drawn, + // which its stored position may not be. + let from = crate::grips::grip_points(s.doc()?, &e.kind).get(i).copied().unwrap_or(to); + let raw = e.kind.grips().get(i).copied().unwrap_or(from); + let k = stretch_grip(&e.kind, i, raw + (to - from)).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?; let mut edits = vec![(h, k)]; // The other `handles` with a grip on the same point stretch with it (connected objects stay // connected); locked ones and edits that would be degenerate are left alone. - let from = e.kind.grips().get(i).copied().unwrap_or(to); let tol = 1e-9 * (1.0 + from.len()); for o in targets(s, p)? { if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) { @@ -64,14 +67,6 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result { } let d = s.doc_mut()?; for (o, k) in &mut edits { - // A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows. - if let cadcraft_doc::EntityKind::Dimension(dm) = k - && let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind) - && dm.text_mid != old.text_mid - { - let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); - st.follow_text(dm, d.header.f64("DIMSCALE", 1.0)); - } d.modify_entity(*o, |e| e.kind = k.clone())?; } Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::>() })) @@ -86,7 +81,7 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result .or_else(|| hs.first().copied()) .ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?; let i = index_param(cmd, p)?; - let g = curves::entity(s, h)?.kind.grips(); + let g = crate::grips::grip_points(s.doc()?, &curves::entity(s, h)?.kind); g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip")) } @@ -115,7 +110,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result { None => { let base = match point_param(p, "base") { Some(b) => b, - None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?, + None => crate::grips::grip_points(s.doc()?, &curves::entity(s, h0)?.kind).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?, }; point_req(cmd, p, "to")? - base } @@ -137,13 +132,18 @@ fn run_grip_option(s: &mut Session, p: &Value) -> Result { let action: GripAction = p .get("option") .and_then(|v| serde_json::from_value(v.clone()).ok()) - .ok_or_else(|| bad(cmd, "`option` must be addVertex, removeVertex, toArc, toLine, lengthen or radius"))?; + .ok_or_else(|| { + bad( + cmd, + "`option` must be addVertex, removeVertex, toArc, toLine, lengthen, radius, moveWithDimLine, moveTextOnly, moveWithLeader, aboveDimLine, centerVertically or resetTextPosition", + ) + })?; if curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } let e = curves::entity(s, h)?; let value = p.get("value").and_then(Value::as_f64); - let k = grip_action(&e.kind, i, action, point_param(p, "to"), value) + let k = crate::grips::grip_action_in(s.doc()?, &e.kind, i, action, point_param(p, "to"), value) .ok_or_else(|| bad(cmd, "that option doesn't apply to this grip, or the result would be degenerate"))?; s.doc_mut()?.modify_entity(h, |e| e.kind = k)?; Ok(json!({ "handle": h.hex() })) diff --git a/crates/engine/src/cmd/griphot.rs b/crates/engine/src/cmd/griphot.rs index 802f65e695..7fd74c7c29 100644 --- a/crates/engine/src/cmd/griphot.rs +++ b/crates/engine/src/cmd/griphot.rs @@ -15,7 +15,7 @@ use super::gripcmds::stretch_grips; use super::helpers::line; use super::machines::number; use super::modify::transform_entities; -use crate::grips::{GripAction, GripMode, grip_action, grip_actions, mode_matrix}; +use crate::grips::{GripAction, GripMode, grip_actions, mode_matrix}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Running, Session, Step}; /// At most this many grips are hot at once (input-derived: a cap on the work per edit). @@ -114,7 +114,7 @@ impl GripEdit { continue; } let Some(e) = d.entity(h) else { continue }; - let gs = e.kind.grips(); + let gs = crate::grips::grip_points(d, &e.kind); // The nearest grip of this object within the tolerance. let best = gs .iter() @@ -174,7 +174,7 @@ impl GripEdit { fn acted(&self, s: &Session, action: GripAction, to: Option, value: Option) -> Option<(Handle, EntityKind)> { let &(h, i) = self.hot.first()?; let e = s.doc().ok()?.entity(h)?; - grip_action(&e.kind, i, action, to, value).map(|k| (h, k)) + crate::grips::grip_action_in(s.doc().ok()?, &e.kind, i, action, to, value).map(|k| (h, k)) } /// Apply a multifunctional option; the grip edit ends. @@ -357,7 +357,14 @@ impl Interactive for GripEdit { GripAction::ToArc => ("Specify a point on the arc", Accept::POINT), GripAction::Lengthen => ("Specify end point or length change", Accept::POINT_OR_NUMBER), GripAction::Radius => ("Specify radius", Accept::POINT_OR_NUMBER), - GripAction::RemoveVertex | GripAction::ToLine => ("", Accept::POINT), + GripAction::MoveWithDimLine | GripAction::MoveTextOnly | GripAction::MoveWithLeader => { + ("Specify new location for dimension text", Accept::POINT) + } + GripAction::RemoveVertex + | GripAction::ToLine + | GripAction::AboveDimLine + | GripAction::CenterVertically + | GripAction::ResetTextPosition => ("", Accept::POINT), }; Prompt::new(format!("{} {msg}", a.title()), accept).kw(&["eXit"]).base(base) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index f7307f26bf..29bbb838b0 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -32,6 +32,7 @@ mod pline_opts; pub mod plotters; mod props; pub use props::MatchProps; +pub use props::{missing_fonts, substitute_font}; mod qselect; mod selecttools; mod settings; diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 5562f969c6..10d7ab38a8 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -76,8 +76,13 @@ pub fn specs() -> Vec { CommandSpec::new("textedit", "Edit Text...", run_textedit) .menu(&["Modify", "Object", "Edit Text..."]) .alias(&["ed", "ddedit"]) - .params("{handle, text} (text, mtext, attribute definitions, dimension text override)") + .params("{handle, text} (text, mtext, attribute definitions, dimension text override, multileader text)") .interactive(|_| Ok(Box::new(TextEditM::default()))), + // Double-clicking text, a dimension or a multileader: TEXTEDIT for that one object, in the + // in-place editor. + CommandSpec::new("textedit.object", "Edit Text", run_textedit) + .params("same as textedit") + .interactive(|_| Ok(Box::new(TextEditM { single: true, ..TextEditM::default() }))), ] } @@ -2162,6 +2167,69 @@ fn text_of(k: &EntityKind) -> Option { EntityKind::AttDef(a) => Some(a.text.value.clone()), EntityKind::MText(t) => Some(t.contents.replace("\\P", "\n")), EntityKind::Dimension(d) => Some(if d.text.is_empty() { "<>".into() } else { d.text.clone() }), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.contents.replace("\\P", "\n")), + _ => None, + } +} + +/// A box for the in-place editor showing one line of text where `t` sits. +fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { + use cadcraft_doc::{HAlign, VAlign}; + let col = match t.halign { + HAlign::Left => 0u8, + HAlign::Right => 2, + _ => 1, + }; + let row = match t.valign { + VAlign::Top => 0u8, + VAlign::Middle => 1, + _ if t.halign == HAlign::Middle => 1, + _ => 2, + }; + let left_baseline = t.halign == HAlign::Left && t.valign == VAlign::Baseline; + let at = if left_baseline { t.insert } else { t.align_pt.unwrap_or(t.insert) }; + cadcraft_doc::MText { + insert: at, + height: t.height, + width: 0.0, + attach: row * 3 + col + 1, + rotation: t.rotation, + style: t.style.clone(), + contents: t.value.clone(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + } +} + +/// What the in-place editor edits for object `h`: an MTEXT or multileader text as multiline +/// text, a TEXT or attribute definition as one line, a dimension's text with `<>` for its value. +pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { + use crate::{EditorKind, TextEditor}; + let d = s.doc().ok()?; + let key = h.hex(); + match &d.entity(h)?.kind { + EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key }), + EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key }), + EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key }), + EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key }), + EntityKind::Dimension(dm) => { + let g = cadcraft_render::dimension_in(d, dm); + let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value; + let mtext = cadcraft_doc::MText { + insert: g.text_pos.to3(0.0), + height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 }, + width: 0.0, + attach: 5, + rotation: g.text_angle, + style: d.dim_style(&dm.style).map(|st| st.text_style.clone()).unwrap_or_else(|| dm.style.clone()), + contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() }, + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + Some(TextEditor { mtext, kind: EditorKind::Dimension { measured }, key }) + } _ => None, } } @@ -2179,6 +2247,10 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { d.text = if text == "<>" { String::new() } else { text.to_string() }; d.block = None; } + EntityKind::MLeader(m) => match &mut m.text { + Some(t) => t.contents = text.replace('\n', "\\P"), + None => return Err(other("This multileader has no text.")), + }, _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), } set_kind(s, h, k) @@ -2197,6 +2269,8 @@ fn run_textedit(s: &mut Session, p: &Value) -> Result { #[derive(Default)] struct TextEditM { h: Option<(Handle, String)>, + /// What the in-place editor shows for the picked object. + editor: Option, /// Edits made in this run, newest last: each object as it was before (the Undo option). edits: Vec<(Handle, EntityKind)>, /// Single mode: end after one edit (the Mode option; Multiple by default). @@ -2234,6 +2308,7 @@ impl Interactive for TextEditM { (None, Input::Point(p)) => { let h = curves::pick_at(s, p).ok_or_else(|| other("*Invalid selection*"))?; let old = text_of(&curves::entity(s, h)?.kind).ok_or_else(|| other("Select a text, mtext, attribute definition or dimension."))?; + self.editor = editor_for(s, h); self.h = Some((h, old)); Ok(Step::Continue) } @@ -2243,10 +2318,12 @@ impl Interactive for TextEditM { set_text(s, h, &t)?; self.edits.push((h, before)); self.h = None; + self.editor = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (Some(_), Input::Enter) => { self.h = None; + self.editor = None; Ok(if self.single { Step::Done } else { Step::Continue }) } (None, Input::Enter) => Ok(Step::Done), @@ -2264,6 +2341,9 @@ impl Interactive for TextEditM { _ => Ok(Step::Continue), } } + fn text_editor(&self) -> Option { + if self.mode || self.h.is_none() { None } else { self.editor.clone() } + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/modify2_tests.rs b/crates/engine/src/cmd/modify2_tests.rs index 9b76c84fc4..f6fba8a393 100644 --- a/crates/engine/src/cmd/modify2_tests.rs +++ b/crates/engine/src/cmd/modify2_tests.rs @@ -2,7 +2,7 @@ use cadcraft_doc::{EntityKind, Handle, Space}; use cadcraft_geom::{Arc, Polyline, Vec2}; use serde_json::{Value, json}; -use crate::Session; +use crate::{Input, Session}; fn last(s: &Session) -> EntityKind { s.doc().unwrap().model.last().unwrap().kind.clone() @@ -721,3 +721,82 @@ fn offset_polyline_arc_bulge_follows_joined_endpoints() { assert!(near(arc.center, 10.0, 5.0), "arc centre drifted to {:?}", arc.center); assert!((arc.radius - 4.0).abs() < 1e-6, "radius {}", arc.radius); } + +/// Start `cmd` and pick the object at `at`: what the in-place editor gets. +fn pick_for_editor(s: &mut Session, cmd: &str, at: Vec2) -> crate::TextEditor { + s.start(cmd).unwrap(); + s.input(Input::Point(at)).unwrap(); + s.text_editor().unwrap_or_else(|| panic!("no editor: {}", s.prompt_text())) +} + +#[test] +fn double_click_editing_describes_each_kind_and_applies_the_text() { + use crate::EditorKind; + let mut s = Session::new(); + // Multiline text: the editor starts from its contents, with formatting codes. + let m = h(&s.execute("mtext", &json!({"at": [0, 0], "text": "{\\fArial|b1;Bold}\\Pline"})).unwrap()); + let e = pick_for_editor(&mut s, "textedit.object", Vec2::new(0.05, -0.05)); + assert_eq!(e.kind, EditorKind::MText); + assert_eq!(e.key, m); + assert!(e.mtext.contents.contains("Bold"), "{}", e.mtext.contents); + s.input(Input::Text("new\\Ptext".into())).unwrap(); + assert!(s.running.is_none(), "one object only"); + assert!(matches!(kind(&s, &m), EntityKind::MText(x) if x.contents == "new\\Ptext")); + + // One line of text: plain, no formatting. + let t = h(&s.execute("text", &json!({"at": [20, 0], "text": "single"})).unwrap()); + let e = pick_for_editor(&mut s, "textedit.object", Vec2::new(20.05, 0.05)); + assert_eq!((e.kind, e.mtext.contents.as_str()), (EditorKind::Line, "single")); + s.input(Input::Text("changed".into())).unwrap(); + assert!(matches!(kind(&s, &t), EntityKind::Text(x) if x.value == "changed")); + + // A dimension: `<>` is the measured value, which the editor is told. + let d = h(&s.execute("dimlinear", &json!({"p1": [0, 10], "p2": [8, 10], "at": [4, 12]})).unwrap()); + let EntityKind::Dimension(dm) = kind(&s, &d) else { panic!() }; + let at = cadcraft_render::dimension_in(s.doc().unwrap(), &dm).text_pos; + let e = pick_for_editor(&mut s, "textedit.object", at); + let EditorKind::Dimension { measured } = &e.kind else { panic!("{:?}", e.kind) }; + assert!(measured.contains('8'), "{measured}"); + assert_eq!(e.mtext.contents, "<>"); + s.input(Input::Text("L=<> mm".into())).unwrap(); + assert!(matches!(kind(&s, &d), EntityKind::Dimension(x) if x.text == "L=<> mm")); + + // A multileader's text. + let ml = h(&s.execute("mleader", &json!({"points": [[40, 0], [44, 4]], "text": "note"})).unwrap()); + let EntityKind::MLeader(mm) = kind(&s, &ml) else { panic!() }; + let at = mm.text.as_ref().unwrap().insert.xy(); + s.start("textedit.object").unwrap(); + s.input(Input::Point(at + Vec2::new(0.05, -0.05))).unwrap(); + let e = s.text_editor().expect("the multileader's text"); + assert_eq!(e.kind, EditorKind::MText); + s.input(Input::Text("new note".into())).unwrap(); + assert!(matches!(kind(&s, &ml), EntityKind::MLeader(x) if x.text.as_ref().is_some_and(|t| t.contents == "new note"))); +} + +#[test] +fn table_cells_are_edited_in_place_and_tab_moves_on() { + use crate::EditorKind; + let mut s = Session::new(); + let t = h(&s.execute("table", &json!({"at": [0, 0], "rows": 2, "cols": 2, "colWidth": 3, "rowHeight": 1})).unwrap()); + let EntityKind::Table(tb) = kind(&s, &t) else { panic!() }; + let (corner, w, hgt) = tb.cell_rect(tb.row_heights.len() - 1, 0).unwrap(); + let e = pick_for_editor(&mut s, "tabledit.cell", corner + Vec2::new(w / 2.0, -hgt / 2.0)); + assert!(matches!(&e.kind, EditorKind::TableCell { name } if name.starts_with('A')), "{:?}", e.kind); + assert!(e.mtext.width > 0.0 && e.mtext.width < w); + let first = e.key.clone(); + s.input(Input::Text("left".into())).unwrap(); + s.input(Input::Keyword("Next".into())).unwrap(); + let e2 = s.text_editor().unwrap(); + assert_ne!(e2.key, first); + s.input(Input::Text("right".into())).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + let EntityKind::Table(tb) = kind(&s, &t) else { panic!() }; + let last = tb.cells.last().unwrap(); + assert_eq!((last[0].text.as_str(), last[1].text.as_str()), ("left", "right")); + // Up from the first row ends, as Tab past the last cell does. + s.start("tabledit.cell").unwrap(); + s.input(Input::Point(tb.cell_rect(0, 0).map(|(c, w, h)| c + Vec2::new(w / 2.0, -h / 2.0)).unwrap())).unwrap(); + s.input(Input::Keyword("Up".into())).unwrap(); + assert!(s.running.is_none()); +} diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 6e68a9d8d2..3cbeb23127 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, }"), + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline, dogleg (landing distance; 0 = no landing), textHeight}"), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -38,6 +38,15 @@ pub fn specs() -> Vec { .alias(&["st"]) .params("{name, font?, bigFont?, height?, widthFactor?, oblique? (degrees), backwards?, upsideDown?, vertical?, annotative?, current?} → styles"), CommandSpec::new("style.list", "List Text Styles", run_style_list).params("{} → text styles").noundo(), + CommandSpec::new("fonts.missing", "Missing Fonts", run_fonts_missing) + .params("{} → [{style, font, substitute}]: text style fonts CADCraft can't find, and what it draws them with") + .noundo(), + CommandSpec::new("fonts.rescan", "Look for Fonts Again", run_fonts_rescan) + .params("{} → fonts.list: look again for fonts added to or removed from the font folders") + .noundo(), + CommandSpec::new("fonts.list", "List Fonts", run_fonts_list) + .params("{} → {folders, fonts: [{name, family?, user}]}: the fonts text styles can use, the user's font folders' first") + .noundo(), CommandSpec::new("style.rename", "Rename Text Style", run_style_rename).params("{from, to}"), CommandSpec::new("style.delete", "Delete Text Style", run_style_delete).params("{name} (not Standard, the current style or one in use)"), CommandSpec::new("style.current", "Set Current Text Style", run_style_current).params("{name}"), @@ -203,6 +212,16 @@ fn run_set(s: &mut Session, p: &Value) -> Result { let dim_style = str_param(p, "dimStyle") .map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found")))) .transpose()?; + let mleader_style = str_param(p, "mleaderStyle") + .map(|n| { + d.mleader_styles + .iter() + .find(|st| st.name.eq_ignore_ascii_case(n)) + .map(|st| st.name.clone()) + .or_else(|| n.eq_ignore_ascii_case("Standard").then(|| "Standard".to_string())) + .ok_or_else(|| bad("properties.set", format!("multileader style `{n}` not found"))) + }) + .transpose()?; let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { @@ -375,6 +394,38 @@ fn run_set(s: &mut Session, p: &Value) -> Result { dm.block = None; } } + EntityKind::MLeader(m) => { + if let Some(st) = &mleader_style { + m.style.clone_from(st); + } + if let Some(v) = str_param(p, "arrow") { + m.arrow = v.trim().to_string(); + } + if let Some(x) = num("arrowSize").filter(|x| *x >= 0.0) { + m.arrow_size = x; + } + match str_param(p, "leaderType").map(str::to_ascii_lowercase).as_deref() { + Some("spline") => m.spline = true, + Some("straight") => m.spline = false, + _ => {} + } + if let Some(x) = num("dogleg").filter(|x| *x >= 0.0) { + // The content stays at the end of the landing. + let land = m.landing.x; + let side = |x: f64| if x >= land { 1.0 } else { -1.0 }; + let shift = x - m.dogleg; + if let Some(t) = &mut m.text { + t.insert.x += shift * side(t.insert.x); + } + if let Some(b) = &mut m.block { + b.insert.x += shift * side(b.insert.x); + } + m.dogleg = x; + } + if let (Some(x), Some(t)) = (num("textHeight").filter(|x| *x > 0.0), &mut m.text) { + t.height = x; + } + } EntityKind::Hatch(h) => { if let Some(v) = str_param(p, "pattern") { if !h.pattern.eq_ignore_ascii_case(v) { @@ -566,6 +617,41 @@ fn run_style_list(s: &mut Session, _p: &Value) -> Result { Ok(styles_json(s.doc()?)) } +/// The font a style font that can't be found is drawn with: FONTALT when it is found, else the +/// built-in stroke font. +pub fn substitute_font() -> String { + let alt = cadcraft_fonts::ttf::font_alt(); + if !alt.is_empty() && cadcraft_fonts::ttf::find(&alt).is_some() { alt } else { cadcraft_fonts::BUILTIN_FONT.to_string() } +} + +/// Text style fonts (and big fonts) of `d` that CADCraft can't find, once each. +pub fn missing_fonts(d: &cadcraft_doc::Drawing) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + for st in &d.text_styles { + let font = st.font.trim(); + if !cadcraft_fonts::ttf::available(font) && !out.iter().any(|(_, f)| f.eq_ignore_ascii_case(font)) { + out.push((st.name.clone(), font.to_string())); + } + } + out +} + +fn run_fonts_missing(s: &mut Session, _p: &Value) -> Result { + let sub = substitute_font(); + Ok(json!(missing_fonts(s.doc()?).into_iter().map(|(style, font)| json!({ "style": style, "font": font, "substitute": sub })).collect::>())) +} + +fn run_fonts_rescan(s: &mut Session, p: &Value) -> Result { + cadcraft_fonts::ttf::rescan(); + run_fonts_list(s, p) +} + +fn run_fonts_list(_s: &mut Session, _p: &Value) -> Result { + let fonts: Vec = + cadcraft_fonts::ttf::installed().into_iter().map(|f| json!({ "name": f.name, "family": f.family, "user": f.user })).collect(); + Ok(json!({ "folders": cadcraft_fonts::ttf::font_dirs(), "fonts": fonts })) +} + fn run_style_current(s: &mut Session, p: &Value) -> Result { let name = str_param(p, "name").ok_or_else(|| bad("style.current", "`name` is required"))?; let d = s.doc_mut()?; diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index a2efca4d64..cdeb8e62d0 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -29,6 +29,10 @@ pub fn specs() -> Vec { CommandSpec::new("tabledit", "Edit Table Cell", run_tabledit) .params("{handle?, at: [x,y] | row+col, text (=… for a formula)}") .interactive(|_| Ok(Box::new(TableEditM::default()))), + // Double-clicking a table cell: the in-place editor, which moves between cells. + CommandSpec::new("tabledit.cell", "Edit Table Cells", run_tabledit) + .params("same as tabledit") + .interactive(|_| Ok(Box::new(TableEditM { stay: true, ..TableEditM::default() }))), CommandSpec::new("tableexport", "Export Table", run_export) .params("{handle, path? (.csv), separator?: \",\" | \"\\t\"} → {csv, rows, cols, path?}") .interactive(|_| Ok(Box::new(ExportM::default()))), @@ -426,10 +430,101 @@ fn run_tabledit(s: &mut Session, p: &Value) -> Result { super::run_set(s, &q) } -/// TABLEDIT at the command line: pick a cell, type its text (or `=formula`). +/// TABLEDIT at the command line: pick a cell, type its text (or `=formula`). In the in-place +/// editor (`stay`), the text keeps the cell open: `Next`, `Previous`, `Up` and `Down` move to +/// another cell and Enter ends. #[derive(Default)] struct TableEditM { cell: Option<(Handle, usize, usize)>, + stay: bool, + /// The in-place editor's box for the current cell (`stay` only). + editor: Option, +} + +impl TableEditM { + fn open(&mut self, s: &Session, cell: (Handle, usize, usize)) { + self.cell = Some(cell); + self.editor = if self.stay { cell_editor(s, cell.0, cell.1, cell.2) } else { None }; + } +} + +/// The cell's text to edit: its formula, or its text. +fn cell_source(t: &Table, r: usize, c: usize) -> String { + t.cells.get(r).and_then(|row| row.get(c)).map(|c| c.formula.clone().unwrap_or_else(|| c.text.clone())).unwrap_or_default() +} + +/// The cell `dir` of (r, c) that is not covered by a merge: Next and Previous run along the rows +/// and wrap; Up and Down stay in the column. `None` at the table's edge. +fn neighbour(t: &Table, r: usize, c: usize, dir: &str) -> Option<(usize, usize)> { + let rows = t.row_heights.len().min(t.cells.len()).min(MAX_ROWS); + let cols = t.col_widths.len().min(MAX_COLS); + if rows == 0 || cols == 0 { + return None; + } + let covered = cadcraft_render::table_covered(t); + let free = |r: usize, c: usize| !covered.get(r).and_then(|v| v.get(c)).copied().unwrap_or(false); + let (mut r, mut c) = (r.min(rows - 1), c.min(cols - 1)); + for _ in 0..rows.saturating_mul(cols) { + match dir { + "Next" => { + c += 1; + if c >= cols { + c = 0; + r += 1; + } + if r >= rows { + return None; + } + } + "Previous" => { + if c == 0 { + if r == 0 { + return None; + } + r -= 1; + c = cols - 1; + } else { + c -= 1; + } + } + "Up" => r = r.checked_sub(1)?, + "Down" => { + r += 1; + if r >= rows { + return None; + } + } + _ => return None, + } + if free(r, c) { + return Some((r, c)); + } + } + None +} + +/// The in-place editor's box for cell (r, c) of table `h`. +fn cell_editor(s: &Session, h: Handle, r: usize, c: usize) -> Option { + let d = s.doc().ok()?; + let EntityKind::Table(t) = &d.entity(h)?.kind else { return None }; + let (corner, w, _) = t.cell_rect(r, c)?; + let height = t.cells.get(r).and_then(|row| row.get(c)).and_then(|c| c.text_height).unwrap_or(t.text_height); + let height = if height.is_finite() && height > 0.0 { height } else { 0.18 }; + let margin = d.table_styles.iter().find(|st| st.name.eq_ignore_ascii_case(&t.style)).map_or(0.06, |st| st.margin); + let margin = if margin.is_finite() && margin >= 0.0 { margin.min(w * 0.25) } else { 0.0 }; + let mtext = cadcraft_doc::MText { + insert: (corner + Vec2::new(margin, -margin)).to3(t.insert.z), + height, + width: (w - 2.0 * margin).max(height), + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: cell_source(t, r, c), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + Some(crate::TextEditor { mtext, kind: crate::EditorKind::TableCell { name: cell_name(r, c) }, key: format!("{}:{r}:{c}", h.hex()) }) } impl Interactive for TableEditM { @@ -457,13 +552,38 @@ impl Interactive for TableEditM { (_, Input::Cancel) => Ok(Step::Cancel), (None, Input::Point(p)) => { match cell_under(s, p) { - Some(c) => self.cell = Some(c), + Some(c) => self.open(s, c), None => s.echo("No table cell there."), } Ok(Step::Continue) } (None, Input::Enter) => Ok(Step::Cancel), (Some(_), Input::Enter) => Ok(Step::Done), + (Some((h, r, c)), Input::Keyword(k)) if self.stay && matches!(k.as_str(), "Next" | "Previous" | "Up" | "Down") => { + let (h, r, c) = (*h, *r, *c); + let next = s + .doc() + .ok() + .and_then(|d| d.entity(h)) + .and_then(|e| if let EntityKind::Table(t) = &e.kind { neighbour(t, r, c, &k) } else { None }); + match next { + Some((r, c)) => { + self.open(s, (h, r, c)); + Ok(Step::Continue) + } + // Past the table's edge: done, as the last cell's Tab is in AutoCAD. + None => Ok(Step::Done), + } + } + (Some((h, r, c)), Input::Text(t)) if self.stay => { + let q = json!({ "handle": h.hex(), "row": r, "col": c, "text": t }); + let cell = (*h, *r, *c); + if let Err(e) = super::run_set(s, &q) { + s.echo(e.to_string()); + } + self.open(s, cell); + Ok(Step::Continue) + } (Some((h, r, c)), Input::Text(t) | Input::Keyword(t)) => { let q = json!({ "handle": h.hex(), "row": r, "col": c, "text": t }); match super::run_set(s, &q) { @@ -477,6 +597,9 @@ impl Interactive for TableEditM { _ => Ok(Step::Continue), } } + fn text_editor(&self) -> Option { + self.cell.and(self.editor.clone()) + } } // ---------------------------------------------------------------- TABLEEXPORT diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 4640c58acb..29aca81ef5 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -222,6 +222,8 @@ enum Stage { Fence(Vec), /// A crossing window: its first corner once picked. Crossing(Option), + /// A pick in empty space: a line from this point; everything it crosses is trimmed (extended). + Line(Vec2), Mode, Project, Edge, @@ -250,6 +252,15 @@ impl TrimM { s.set_selection(Vec::new()); self.stage = Stage::Edges(Vec::new()); } + /// The cutting (boundary) edges stay selected, so they show highlighted until the command + /// ends; with no edges (every object cuts) nothing is. + fn show_edges(&self, s: &mut Session) { + let shown: Vec = match (&self.edges, s.doc()) { + (Some(edges), Ok(d)) => edges.iter().copied().filter(|h| d.entity(*h).is_some()).collect(), + _ => Vec::new(), + }; + s.set_selection(shown); + } /// Run `f` as one undoable step of the command; a step that changed nothing records none. fn step(&mut self, s: &mut Session, f: impl FnOnce(&mut Self, &mut Session) -> Result<()>) -> Result<()> { let before = s.state()?.doc.clone(); @@ -315,7 +326,8 @@ impl Interactive for TrimM { if self.extend { "EXTEND" } else { "TRIM" } } fn begin(&mut self, s: &mut Session) -> Result { - s.set_selection(Vec::new()); + // Objects selected before the command are its cutting (boundary) edges. + let pre = s.selection().to_vec(); let quick = quick_mode(s); let proj = match proj_mode(s) { 0 => "None", @@ -327,7 +339,13 @@ impl Interactive for TrimM { if edge_mode(s) { "Extend" } else { "None" }, if quick { "Quick" } else { "Standard" } )); - if !quick { + if !pre.is_empty() { + let n = pre.len(); + self.edges = Some(pre); + self.show_edges(s); + let what = if self.extend { "boundary" } else { "cutting" }; + s.echo(format!("{n} {what} edge{} selected.", if n == 1 { "" } else { "s" })); + } else if !quick { self.select_edges(s); } Ok(Step::Continue) @@ -357,6 +375,7 @@ impl Interactive for TrimM { Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l), }, Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT), + Stage::Line(a) => Prompt::new("Specify end point of the fence line", Accept::POINT).base(*a), Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT), Stage::Mode => { let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" }; @@ -395,8 +414,8 @@ impl Interactive for TrimM { self.stage = Stage::Edges(picked); } Input::Enter => { - s.set_selection(Vec::new()); self.edges = if picked.is_empty() { None } else { Some(picked) }; + self.show_edges(s); self.stage = Stage::Pick; } _ => {} @@ -415,7 +434,7 @@ impl Interactive for TrimM { self.stage = Stage::Erase(picked); } Input::Enter => { - s.set_selection(Vec::new()); + self.show_edges(s); self.step(s, |_, s| { let d = s.doc_mut()?; for h in &picked { @@ -455,6 +474,21 @@ impl Interactive for TrimM { } Ok(Step::Continue) } + Stage::Line(a) => { + match i { + Input::Point(b) => { + self.stage = Stage::Pick; + let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ())); + if let Err(e) = r { + s.echo(e.to_string()); + } + self.show_edges(s); + } + Input::Enter | Input::Keyword(_) => self.stage = Stage::Pick, + _ => {} + } + Ok(Step::Continue) + } Stage::Crossing(first) => { match (first, i) { (None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)), @@ -475,17 +509,22 @@ impl Interactive for TrimM { let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; let space = s.space(); let Some(h) = crate::select::pick(s.doc()?, &space, p, ap) else { - // A pick in empty space opens a crossing window there. - self.stage = Stage::Crossing(Some(p)); + // A pick in empty space starts a fence line there: what it crosses is + // trimmed (extended) once its end point is picked. + self.stage = Stage::Line(p); return Ok(Step::Continue); }; let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ())); if let Err(e) = r { s.echo(e.to_string()); } + self.show_edges(s); Ok(Step::Continue) } - Input::Enter => Ok(Step::Done), + Input::Enter => { + s.set_selection(Vec::new()); + Ok(Step::Done) + } Input::Keyword(k) => { match k.as_str() { "cuTting edges" | "Boundary edges" => self.select_edges(s), @@ -526,6 +565,7 @@ impl Interactive for TrimM { .filter_map(|w| Some(line(*w.first()?, *w.get(1)?))) .collect(), Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)], + Stage::Line(a) => vec![line(*a, c)], _ => Vec::new(), } } diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index 964bc1f61f..e1ee10e8d2 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -243,10 +243,33 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option { - set_xy(&mut d.text_mid, to); - d.user_text_pos = true; - } + _ => match d.kind { + // Stretch: the dimension line follows the text across, and the text keeps its + // place along the line (relative to the arrowheads). Move with Dim Line also + // slides it along. + DimKind::Linear { .. } | DimKind::Aligned => { + let u = match d.kind { + DimKind::Linear { rotation } => Vec2::from_angle(rotation), + _ => (d.p14.xy() - d.p13.xy()).normalized(), + }; + let n = u.perp(); + let from = *grips.get(3)?; + let shift = n * (to - from).dot(n); + if !shift.is_finite() { + return None; + } + let q = d.defpt.xy() + shift; + set_xy(&mut d.defpt, q); + if d.user_text_pos { + let t = d.text_mid.xy() + shift; + set_xy(&mut d.text_mid, t); + } + } + _ => { + set_xy(&mut d.text_mid, to); + d.user_text_pos = true; + } + }, } d.block = None; } @@ -308,6 +331,122 @@ fn shift_params(e: &mut cadcraft_doc::Ellipse, by: f64) { } } +/// The grip points of an object as the drawing shows it: a dimension's text grip sits on its +/// text where the dimension places it (its stored text position is only kept once the user +/// moves the text). +pub fn grip_points(d: &cadcraft_doc::Drawing, kind: &EntityKind) -> Vec { + let mut g = kind.grips(); + if let EntityKind::Dimension(dm) = kind { + // The text as drawn: a file's dimension shows its own block, whose text may sit away + // from where CADCraft would put it. + let file_text = dm.block.as_ref().and_then(|b| d.blocks.get(b)).and_then(|b| { + b.entities.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.insert.xy()), + EntityKind::Text(t) => Some(t.justify_point()), + _ => None, + }) + }); + if let Some(t) = g.get_mut(3) { + let p = match file_text { + Some(p) => p, + None if dm.user_text_pos => *t, + None => cadcraft_render::dimension_in(d, dm).text_pos, + }; + if p.is_finite() { + *t = p; + } + } + // A linear or aligned dimension's line grip sits where the line meets the second + // extension line (any point of the line places it), clear of the text grip. + let u = match dm.kind { + DimKind::Linear { rotation } => Some(Vec2::from_angle(rotation)), + DimKind::Aligned => Some((dm.p14.xy() - dm.p13.xy()).normalized()).filter(|u| *u != Vec2::ZERO), + _ => None, + }; + if let (Some(u), Some(l)) = (u, g.get_mut(2)) { + let p = dm.defpt.xy() + u * (dm.p14.xy() - dm.defpt.xy()).dot(u); + if p.is_finite() { + *l = p; + } + } + } + g +} + +/// A file's dimensions whose text the file shows away from where CADCraft would put it (moved +/// along the line in AutoCAD without the user-position flag): their text keeps that place, so +/// editing them later doesn't make it jump. +pub(crate) fn adopt_file_dim_text(d: &mut cadcraft_doc::Drawing) { + let spaces = std::iter::once(cadcraft_doc::Space::Model).chain(d.layouts.iter().map(|l| cadcraft_doc::Space::Paper(l.name.clone()))); + let mut moved: Vec<(Handle, Vec2)> = Vec::new(); + for space in spaces.collect::>() { + let Some(st) = d.space(&space) else { continue }; + for e in st.iter() { + let EntityKind::Dimension(dm) = &e.kind else { continue }; + if dm.user_text_pos || !matches!(dm.kind, DimKind::Linear { .. } | DimKind::Aligned) { + continue; + } + let Some(block) = dm.block.as_ref().and_then(|b| d.blocks.get(b)) else { continue }; + let Some(shown) = block.entities.iter().find_map(|x| match &x.kind { + EntityKind::MText(t) if t.attach == 5 => Some(t.insert.xy()), + _ => None, + }) else { + continue; + }; + let ours = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { block: None, ..dm.clone() }); + if shown.is_finite() && ours.text_height > 0.0 && shown.dist(ours.text_pos) > ours.text_height { + moved.push((e.handle, shown)); + } + } + } + for (h, p) in moved { + let _ = d.modify_entity(h, |e| { + if let EntityKind::Dimension(dm) = &mut e.kind { + set_xy(&mut dm.text_mid, p); + dm.user_text_pos = true; + } + }); + } +} + +/// [`grip_action`] with the drawing at hand: Move with Dim Line also slides the text along the +/// line to the point (the preview shows the same). +pub fn grip_action_in( + d: &cadcraft_doc::Drawing, + kind: &EntityKind, + index: usize, + action: GripAction, + to: Option, + value: Option, +) -> Option { + let mut k = grip_action(kind, index, action, to, value)?; + if let (GripAction::MoveWithDimLine, Some(to)) = (action, to) { + text_along_line(d, &mut k, to); + } + Some(k) +} + +/// Move with Dim Line, once the dimension line runs through the picked point: the text sits on +/// it (above it, as the style places text) where the point is along it. +pub fn text_along_line(d: &cadcraft_doc::Drawing, kind: &mut EntityKind, to: Vec2) { + let EntityKind::Dimension(dm) = kind else { return }; + let u = match dm.kind { + DimKind::Linear { rotation } => Vec2::from_angle(rotation), + DimKind::Aligned => (dm.p14.xy() - dm.p13.xy()).normalized(), + _ => return, + }; + if u == Vec2::ZERO || !u.is_finite() { + return; + } + dm.user_text_pos = false; + let home = cadcraft_render::dimension_in(d, dm).text_pos; + let at = home + u * (to - home).dot(u); + if at.is_finite() { + set_xy(&mut dm.text_mid, at); + dm.user_text_pos = true; + } +} + /// A multifunctional grip option besides Stretch (the menu a polyline, line or arc grip shows). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -324,6 +463,18 @@ pub enum GripAction { Lengthen, /// Arc midpoint: change the radius, keeping the center and angles. Radius, + /// Dimension text: move the dimension line with the text. + MoveWithDimLine, + /// Dimension text: move the text alone (DIMTMOVE 2 for this dimension). + MoveTextOnly, + /// Dimension text: move the text with a leader to the dimension line (DIMTMOVE 1). + MoveWithLeader, + /// Dimension text: above the dimension line (DIMTAD 1), in its default place. + AboveDimLine, + /// Dimension text: centred on the dimension line (DIMTAD 0), in its default place. + CenterVertically, + /// Dimension text: back to its default place. + ResetTextPosition, } impl GripAction { @@ -336,6 +487,12 @@ impl GripAction { GripAction::ToLine => "conVert to line", GripAction::Lengthen => "Lengthen", GripAction::Radius => "Radius", + GripAction::MoveWithDimLine => "move with Dim line", + GripAction::MoveTextOnly => "move Text only", + GripAction::MoveWithLeader => "move with Leader", + GripAction::AboveDimLine => "Above dim line", + GripAction::CenterVertically => "center Vertically", + GripAction::ResetTextPosition => "Reset text position", } } /// The grip menu label. @@ -347,6 +504,12 @@ impl GripAction { GripAction::ToLine => "Convert to Line", GripAction::Lengthen => "Lengthen", GripAction::Radius => "Radius", + GripAction::MoveWithDimLine => "Move with Dim Line", + GripAction::MoveTextOnly => "Move Text Only", + GripAction::MoveWithLeader => "Move with Leader", + GripAction::AboveDimLine => "Above Dim Line", + GripAction::CenterVertically => "Center Vertically", + GripAction::ResetTextPosition => "Reset Text Position", } } /// The mode name on the command line ("** ADD VERTEX **"). @@ -358,11 +521,20 @@ impl GripAction { GripAction::ToLine => "** CONVERT TO LINE **", GripAction::Lengthen => "** LENGTHEN **", GripAction::Radius => "** RADIUS **", + GripAction::MoveWithDimLine => "** MOVE WITH DIM LINE **", + GripAction::MoveTextOnly => "** MOVE TEXT ONLY **", + GripAction::MoveWithLeader => "** MOVE WITH LEADER **", + GripAction::AboveDimLine => "** ABOVE DIM LINE **", + GripAction::CenterVertically => "** CENTER VERTICALLY **", + GripAction::ResetTextPosition => "** RESET TEXT POSITION **", } } /// Whether the option needs a point (or value); the others act at once. pub fn needs_point(self) -> bool { - !matches!(self, GripAction::RemoveVertex | GripAction::ToLine) + !matches!( + self, + GripAction::RemoveVertex | GripAction::ToLine | GripAction::AboveDimLine | GripAction::CenterVertically | GripAction::ResetTextPosition + ) } } @@ -383,6 +555,21 @@ pub fn grip_actions(kind: &EntityKind, index: usize) -> Vec { EntityKind::Line(_) if index == 0 || index == 2 => vec![GripAction::Lengthen], EntityKind::Arc(_) if index == 0 || index == 2 => vec![GripAction::Lengthen], EntityKind::Arc(_) if index == 1 => vec![GripAction::Radius], + // The text grip of a dimension. + EntityKind::Dimension(d) if index == 3 => { + let mut v = Vec::new(); + if matches!(d.kind, DimKind::Linear { .. } | DimKind::Aligned) { + v.push(GripAction::MoveWithDimLine); + } + v.extend([ + GripAction::MoveTextOnly, + GripAction::MoveWithLeader, + GripAction::AboveDimLine, + GripAction::CenterVertically, + GripAction::ResetTextPosition, + ]); + v + } _ => Vec::new(), } } @@ -455,6 +642,41 @@ pub fn grip_action(kind: &EntityKind, index: usize, action: GripAction, to: Opti let q = fixed + dir * new_len; set_xy(if index == 0 { &mut l.a } else { &mut l.b }, q); } + (EntityKind::Dimension(d), GripAction::MoveWithDimLine) => { + // The dimension line moves through the point; the text goes back to its place on it + // ([`text_along_line`] then slides it along to the point). + let to = to?; + let u = match d.kind { + DimKind::Linear { rotation } => Vec2::from_angle(rotation), + _ => (d.p14.xy() - d.p13.xy()).normalized(), + }; + if u == Vec2::ZERO { + return None; + } + let n = u.perp(); + let q = d.defpt.xy() + n * (to - d.defpt.xy()).dot(n); + set_xy(&mut d.defpt, q); + d.user_text_pos = false; + // The text stays on the line wherever along it it goes (DIMTMOVE 0 for this one). + d.overrides.insert("textMove".into(), serde_json::json!(0)); + d.block = None; + } + (EntityKind::Dimension(d), GripAction::MoveTextOnly | GripAction::MoveWithLeader) => { + let to = to?; + set_xy(&mut d.text_mid, to); + d.user_text_pos = true; + d.overrides.insert("textMove".into(), serde_json::json!(if action == GripAction::MoveTextOnly { 2 } else { 1 })); + d.block = None; + } + (EntityKind::Dimension(d), GripAction::AboveDimLine | GripAction::CenterVertically) => { + d.overrides.insert("textAbove".into(), serde_json::json!(if action == GripAction::AboveDimLine { 1 } else { 0 })); + d.user_text_pos = false; + d.block = None; + } + (EntityKind::Dimension(d), GripAction::ResetTextPosition) => { + d.user_text_pos = false; + d.block = None; + } (EntityKind::Arc(a), GripAction::Lengthen) => { let c = a.center.xy(); let ang = match (value, to) { @@ -528,7 +750,8 @@ impl Session { /// Grip points of an object (the indices `grip_edit` takes). pub fn grips_of(&self, handle: Handle) -> Result> { - self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into())) + let d = self.doc()?; + d.entity(handle).map(|e| grip_points(d, &e.kind)).ok_or_else(|| EngineError::Other("no such object".into())) } } diff --git a/crates/engine/src/grips_tests.rs b/crates/engine/src/grips_tests.rs index 1cf720f673..01dfb18b53 100644 --- a/crates/engine/src/grips_tests.rs +++ b/crates/engine/src/grips_tests.rs @@ -135,7 +135,9 @@ fn spline_text_insert_and_dimension_grips() { let g = s.grips_of(d).unwrap(); assert_eq!(g.len(), 4); s.grip_edit(d, 3, v(5.0, 6.0), GripMode::Stretch).unwrap(); - assert!(matches!(kind(&s, d), EntityKind::Dimension(x) if x.user_text_pos && near(x.text_mid.xy(), 5.0, 6.0))); + assert!(matches!(kind(&s, d), EntityKind::Dimension(x) if !x.user_text_pos)); + let shown = s.grips_of(d).unwrap()[3]; + assert!(near(shown, 5.0, 6.0), "{shown:?}"); s.grip_edit(d, 1, v(12.0, 0.0), GripMode::Stretch).unwrap(); assert!(matches!(kind(&s, d), EntityKind::Dimension(x) if near(x.p14.xy(), 12.0, 0.0))); } @@ -222,3 +224,77 @@ fn grips_on_locked_layers_and_hostile_values() { } } } + +#[test] +fn a_dimensions_text_grip_sits_on_its_text_and_has_the_text_options() { + use cadcraft_doc::EntityKind; + let mut s = Session::new(); + let h = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string(); + let handle = cadcraft_doc::Handle::parse_hex(&h).unwrap(); + let g = s.grips_of(handle).unwrap(); + assert!((g[3] - Vec2::new(5.0, 3.0)).len() < 1.0, "on the drawn text: {:?}", g[3]); + let kind = |s: &Session| s.doc().unwrap().entity(handle).unwrap().kind.clone(); + let labels: Vec<&str> = grip_actions(&kind(&s), 3).iter().map(|a| a.label()).collect(); + assert_eq!(labels, ["Move with Dim Line", "Move Text Only", "Move with Leader", "Above Dim Line", "Center Vertically", "Reset Text Position"]); + // Move Text Only: the text alone, DIMTMOVE 2 for this dimension. + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "moveTextOnly", "to": [5, 8] })).unwrap(); + let EntityKind::Dimension(d) = kind(&s) else { panic!() }; + assert!(d.user_text_pos && d.text_mid.xy() == Vec2::new(5.0, 8.0) && d.defpt.y == 3.0); + assert_eq!(d.overrides.get("textMove"), Some(&json!(2))); + assert!((s.grips_of(handle).unwrap()[3] - Vec2::new(5.0, 8.0)).len() < 1e-9); + // Reset Text Position, then Above Dim Line. + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "resetTextPosition" })).unwrap(); + let EntityKind::Dimension(d) = kind(&s) else { panic!() }; + assert!(!d.user_text_pos); + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "aboveDimLine" })).unwrap(); + let EntityKind::Dimension(d) = kind(&s) else { panic!() }; + assert_eq!(d.overrides.get("textAbove"), Some(&json!(1))); + // Move with Dim Line: the dimension line goes through the point, the text along it there. + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "moveWithDimLine", "to": [7, 6] })).unwrap(); + let EntityKind::Dimension(d) = kind(&s) else { panic!() }; + assert!((d.defpt.y - 6.0).abs() < 1e-9, "{:?}", d.defpt); + assert!(d.user_text_pos && (d.text_mid.x - 7.0).abs() < 1e-9, "{:?}", d.text_mid); + // At the hot-grip prompt the options are keywords too. + s.set_selection(vec![handle]); + s.start_grip_edit(&[(handle, 3)]).unwrap(); + s.input(crate::Input::Keyword("center Vertically".into())).unwrap(); + let EntityKind::Dimension(d) = kind(&s) else { panic!() }; + assert_eq!(d.overrides.get("textAbove"), Some(&json!(0))); +} + +#[test] +fn stretching_the_text_grip_moves_the_dimension_line_and_keeps_the_text_by_the_arrows() { + use cadcraft_doc::EntityKind; + let mut s = Session::new(); + s.execute("dimstyle", &json!({ "name": "Free", "textMove": 2, "current": true })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let handle = h(&r); + let shown = s.grips_of(handle).unwrap()[3]; + s.execute("grip.stretch", &json!({ "handle": handle.hex(), "index": 3, "to": [shown.x - 2.0, shown.y + 5.0] })).unwrap(); + let EntityKind::Dimension(d) = kind(&s, handle) else { panic!() }; + assert!((d.defpt.y - 8.0).abs() < 1e-9, "the line follows the text across: {:?}", d.defpt); + assert!(!d.user_text_pos, "the text keeps its place between the arrows"); + let now = s.grips_of(handle).unwrap()[3]; + assert!((now.x - shown.x).abs() < 1e-9 && (now.y - shown.y - 5.0).abs() < 1e-9, "{shown:?} -> {now:?}"); + // Text placed along the line keeps that place too. + s.execute("grip.option", &json!({ "handle": handle.hex(), "index": 3, "option": "moveWithDimLine", "to": [2, 8] })).unwrap(); + let before = s.grips_of(handle).unwrap()[3]; + s.execute("grip.stretch", &json!({ "handle": handle.hex(), "index": 3, "to": [before.x + 4.0, before.y + 2.0] })).unwrap(); + let EntityKind::Dimension(d) = kind(&s, handle) else { panic!() }; + assert!((d.defpt.y - 10.0).abs() < 1e-9 && (d.text_mid.x - before.x).abs() < 1e-9, "{d:?}"); +} + +#[test] +fn move_with_dim_line_takes_the_text_past_the_arrows_and_the_line_out_to_it() { + use cadcraft_doc::EntityKind; + let mut s = Session::new(); + s.execute("dimstyle", &json!({ "name": "Free", "textMove": 2, "current": true })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap(); + let handle = h(&r); + s.execute("grip.option", &json!({ "handle": handle.hex(), "index": 3, "option": "moveWithDimLine", "to": [16, 6] })).unwrap(); + let EntityKind::Dimension(d) = kind(&s, handle) else { panic!() }; + assert!((d.defpt.y - 6.0).abs() < 1e-9 && (d.text_mid.x - 16.0).abs() < 1e-9, "{d:?}"); + let g = cadcraft_render::dimension_in(s.doc().unwrap(), &d); + let reach = g.lines.iter().flatten().filter(|p| (p.y - 6.0).abs() < 1e-9).map(|p| p.x).fold(f64::MIN, f64::max); + assert!(reach > 16.0, "the dimension line runs out under the text: {reach}"); +} diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 34401e3148..ec980cb0a9 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -93,6 +93,15 @@ impl Interactive for Guarded { None }) } + fn text_editor(&self) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.text_editor())).unwrap_or_else(|_| { + self.broken.set(Some("panic in prompt")); + None + }) + } } #[cfg(test)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 778b969605..b37444c646 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -43,7 +43,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step}; +pub use prompt::{Accept, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor}; #[derive(Debug, thiserror::Error)] pub enum EngineError { @@ -1269,6 +1269,11 @@ impl Session { } self.pending_window = None; self.select_mode = None; + // TRIM and EXTEND keep their edges selected (highlighted) while they run; they stay + // selected no longer than the command, however it ends. + if matches!(run.id.as_str(), "trim" | "extend") { + self.set_selection(Vec::new()); + } let label = find_command(&run.id).map(|c| c.label).unwrap_or("Command"); let _ = cancelled; if let Some(m) = cmd::blocks::refedit::after_command(self, &run.before, &run.id) { @@ -1347,6 +1352,11 @@ impl Session { self.running.as_ref().and_then(|r| r.machine.editing_mtext()) } + /// The text the running command edits in place ([`Interactive::text_editor`]). + pub fn text_editor(&self) -> Option { + self.running.as_ref().and_then(|r| r.machine.text_editor()) + } + pub fn current_prompt(&self) -> Option { if let Some(p) = self.lisp_prompt() { return Some(p); diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index b5de83286c..9995bcd5e7 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -220,6 +220,39 @@ pub trait Interactive: Send { fn editing_mtext(&self) -> Option { None } + /// The text the in-place editor edits: where, how, its current contents and what kind of + /// object holds it. By default the new multiline text of [`Interactive::editing_mtext`]. + fn text_editor(&self) -> Option { + self.editing_mtext().map(|mtext| TextEditor { mtext, kind: EditorKind::NewMText, key: String::new() }) + } +} + +/// What the in-place text editor edits ([`Interactive::text_editor`]). The editor answers the +/// command's text prompt with the new contents (`Input::Text`), then `Input::Enter`; a table cell +/// may answer a move keyword instead of Enter (`Next`, `Previous`, `Up`, `Down`). +#[derive(Clone, Debug, PartialEq)] +pub struct TextEditor { + /// Where the box sits (insertion point, attachment, rotation), its width (0: grows with the + /// text), text height and style; `contents` is the text to start from, in MTEXT codes. + pub mtext: cadcraft_doc::MText, + pub kind: EditorKind, + /// Which object (and cell) is being edited: a new key means a new text to load. + pub key: String, +} + +/// The kind of text the in-place editor edits. +#[derive(Clone, Debug, PartialEq)] +pub enum EditorKind { + /// Multiline text being created (MTEXT). + NewMText, + /// Existing multiline text: an MTEXT, a multileader's text. + MText, + /// One line of plain text (TEXT, attribute definition): no formatting, Enter finishes. + Line, + /// A dimension's text: `<>` stands for the measured value, shown as `measured`. + Dimension { measured: String }, + /// A table cell (`name` such as `B3`); Tab, Shift+Tab and the arrows move between cells. + TableCell { name: String }, } /// See [`Interactive::drag`]. diff --git a/crates/engine/tests/annotative.rs b/crates/engine/tests/annotative.rs index 6a49ae93be..b397f10fdf 100644 --- a/crates/engine/tests/annotative.rs +++ b/crates/engine/tests/annotative.rs @@ -321,6 +321,7 @@ fn annotative_mtext_columns_follow_the_scale() { text: Some(mtext), style: "Standard".into(), arrow_size: 1.0, + arrow: String::new(), spline: false, block: None, }), diff --git a/crates/engine/tests/mtext_columns.rs b/crates/engine/tests/mtext_columns.rs index 61420352a7..1ed5d2efa6 100644 --- a/crates/engine/tests/mtext_columns.rs +++ b/crates/engine/tests/mtext_columns.rs @@ -112,6 +112,7 @@ fn scale_scales_multileader_text_width_and_columns() { text: Some(text), style: "Standard".into(), arrow_size: 1.0, + arrow: String::new(), spline: false, block: None, }; diff --git a/crates/engine/tests/trim_extend_options.rs b/crates/engine/tests/trim_extend_options.rs index 5302a68c95..43aa722d9d 100644 --- a/crates/engine/tests/trim_extend_options.rs +++ b/crates/engine/tests/trim_extend_options.rs @@ -201,3 +201,50 @@ fn json_forms_take_fence_crossing_edge_mode_and_mode() { assert_eq!(r["extended"], 1); assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((10.0, -5.0), (10.0, 5.0))]); } + +/// The handle of the line with these ends. +fn handle_of(s: &Session, seg: Seg) -> cadcraft_engine::doc::Handle { + s.doc() + .unwrap() + .model + .iter() + .find(|e| matches!(&e.kind, EntityKind::Line(l) if ((r(l.a.x), r(l.a.y)), (r(l.b.x), r(l.b.y))) == seg)) + .unwrap() + .handle +} + +#[test] +fn objects_selected_before_trim_are_its_cutting_edges_and_stay_highlighted() { + let mut s = ladder(); + let edge = handle_of(&s, ((0.0, -5.0), (0.0, 5.0))); + s.set_selection(vec![edge]); + s.cmdline("TRIM").unwrap(); + assert_eq!(s.selection(), [edge], "the edge stays selected (highlighted) while TRIM runs"); + // Only the x = 0 line cuts: the y = 0 line loses its left part, the x = 10 line doesn't cut. + s.script("-2,0\n").unwrap(); + assert_eq!(s.selection(), [edge]); + assert!(lines(&s).contains(&((0.0, 0.0), (15.0, 0.0))), "{:?}", lines(&s)); + s.script("\n").unwrap(); + assert!(s.running.is_none()); + assert!(s.selection().is_empty(), "the highlight ends with the command"); + // Cancelling ends it too. + s.set_selection(vec![edge]); + s.cmdline("EXTEND").unwrap(); + assert_eq!(s.selection(), [edge]); + s.cancel(); + assert!(s.selection().is_empty()); +} + +#[test] +fn a_pick_in_empty_space_draws_a_fence_line_and_trims_what_it_crosses() { + let mut s = ladder(); + // Quick mode. From empty space at 5,-3 to 5,3: both horizontal lines are cut between the edges. + s.script("TRIM 5,-3\n").unwrap(); + assert_eq!(s.current_prompt().map(|p| p.message), Some("Specify end point of the fence line".into())); + s.script("5,3\n\n").unwrap(); + assert!(s.running.is_none(), "{}", s.prompt_text()); + assert_eq!( + lines(&s), + with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (0.0, 2.0)), ((10.0, 0.0), (15.0, 0.0)), ((10.0, 2.0), (15.0, 2.0))]) + ); +} diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 9ccc69cacb..17b14ce222 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -16,6 +16,7 @@ pub mod bidi; mod complex; mod mtext; +pub mod shx; mod stroke; pub mod subset; pub mod ttf; @@ -212,6 +213,62 @@ pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Sh out } +/// Shape one line in an SHX font: each character's shape program scaled so the font's capital +/// height is the text height; characters the font (and its big font) lack come from the stroke +/// font. A line with right-to-left letters (Hebrew) is laid out in display order: its +/// right-to-left runs reversed, brackets mirrored, the base direction from its first letter. +fn shape_shx(font: &TextFont, s: &str, height: f64, width_factor: f64, oblique: f64) -> Shaped { + let TextFont::Shx { font, big } = font else { return shape_stroke(s, height, width_factor, oblique) }; + let h = if height.is_finite() && height > 0.0 { height } else { 1.0 }; + let wf = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 }; + let shear = oblique.tan().clamp(-10.0, 10.0); + let mut out = Shaped::default(); + let mut x = 0.0; + let mut spans: Vec<(f64, f64, bool, bool)> = Vec::new(); + let decoded = decode_controls(s); + let ordered: Vec<(char, bool, bool)> = if decoded.iter().any(|(c, _, _)| bidi::has_rtl(&c.to_string())) { + let chars: Vec = decoded.iter().map(|(c, _, _)| *c).collect(); + let mut v = Vec::with_capacity(decoded.len()); + for (r, rtl) in bidi::visual_runs(&chars, None) { + let run = decoded.get(r).unwrap_or_default(); + if rtl { + v.extend(run.iter().rev().map(|(c, u, o)| (bidi::mirror(*c), *u, *o))); + } else { + v.extend(run.iter().copied()); + } + } + v + } else { + decoded + }; + for (c, under, over) in ordered { + if bidi::is_format_control(c) { + continue; + } + let x0 = x; + let from = |f: &shx::ShxFont| f.code_for(c).and_then(|code| f.glyph(code)).map(|g| (g, h / f.above)); + match from(font).or_else(|| big.as_deref().and_then(from)) { + Some((g, sc)) => { + for st in &g.strokes { + out.strokes.push(st.iter().map(|p| Vec2::new(x + p.x * sc * wf + p.y * sc * shear, p.y * sc)).collect()); + } + x += g.advance * sc * wf; + } + None => { + let mut piece = shape_stroke(&c.to_string(), h, wf, oblique); + piece.map(|p| p + Vec2::new(x, 0.0)); + let adv = stroke_advance(c, h, wf); + out.extend(piece); + x += adv; + } + } + spans.push((x0, x, under, over)); + } + out.strokes.extend(decorations(&spans, h)); + out.width = x.max(0.0); + out +} + /// Draw stroke-font glyph `spec` with its left edge at `x` (`sc` = text height / cap height). fn draw_stroke_glyph(out: &mut Shaped, spec: &str, x: f64, sc: f64, wf: f64, shear: f64) { for st in stroke::strokes(spec) { @@ -263,6 +320,9 @@ pub fn line_width(s: &str, height: f64, width_factor: f64) -> f64 { /// Width of the gap MTEXT leaves between two words. Words are measured without their trailing /// letter gap, so the stroke font's gap is added on both sides of the space, as TEXT lays it out. pub fn space_width(font: &TextFont, height: f64, width_factor: f64) -> f64 { + if let TextFont::Shx { .. } = font { + return shape_shx(font, " ", height, width_factor, 0.0).width; + } if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, " ", height, width_factor) { @@ -278,13 +338,36 @@ pub enum TextFont { #[default] Stroke, Outline(ttf::Face), + /// An SHX shape font from the user's font folders, with the style's big font when it has one. + Shx { + font: std::sync::Arc, + big: Option>, + }, +} + +/// Whether a style font name means an SHX file: `.shx`, or no extension at all (`romans`). +fn names_shx(name: &str) -> bool { + let n = name.trim(); + let file = n.rsplit(['\\', '/']).next().unwrap_or(n); + file.to_ascii_lowercase().ends_with(".shx") || !file.contains('.') } impl TextFont { - /// Resolve a text style font name: an installed TTF/OTF/TTC when found; else, for a font we - /// can't find (an SHX file, a missing TTF), the FONTALT font ([`ttf::font_alt`]) when set; - /// else the stroke font. + /// Resolve a text style font name: an SHX font in the user's font folders for an SHX name; + /// an installed TTF/OTF/TTC when found; else, for a font we can't find (an SHX file, a + /// missing TTF), the FONTALT font ([`ttf::font_alt`]) when set; else the stroke font. pub fn resolve(name: &str) -> TextFont { + Self::resolve_style(name, "") + } + + /// [`TextFont::resolve`] with the style's big font (for an SHX font). + pub fn resolve_style(name: &str, big_font: &str) -> TextFont { + if names_shx(name) + && let Some(font) = shx::find(name) + { + let big = Some(big_font).filter(|b| !b.trim().is_empty()).and_then(shx::find); + return TextFont::Shx { font, big }; + } if let Some(f) = ttf::find(name) { return TextFont::Outline(f); } @@ -410,6 +493,9 @@ pub(crate) fn decorations(spans: &[(f64, f64, bool, bool)], h: f64) -> Vec Shaped { + if let TextFont::Shx { .. } = font { + return shape_shx(font, s, height, width_factor, oblique); + } if let TextFont::Outline(face) = font && let Some(sh) = ttf::shape(face, s, height, width_factor, oblique) { @@ -420,6 +506,9 @@ pub fn shape_line(font: &TextFont, s: &str, height: f64, width_factor: f64, obli /// Width of one line in `font`. pub fn text_width(font: &TextFont, s: &str, height: f64, width_factor: f64) -> f64 { + if let TextFont::Shx { .. } = font { + return shape_shx(font, s, height, width_factor, 0.0).width; + } if let TextFont::Outline(face) = font && let Some(w) = ttf::width(face, s, height, width_factor) { diff --git a/crates/fonts/src/shx.rs b/crates/fonts/src/shx.rs new file mode 100644 index 0000000000..f229dbd1da --- /dev/null +++ b/crates/fonts/src/shx.rs @@ -0,0 +1,705 @@ +//! SHX shape fonts (AutoCAD's compiled `.shx` files): the drawing's own stroke fonts, read from +//! the user's font folders at run time. Nothing of any SHX font ships with CADCraft. +//! +//! Three file kinds are read (format as published in the AutoCAD Customization Guide, "Shape +//! Descriptions"): +//! - `shapes 1.0` / `1.1`: a table of (shape number, length) after three counts, then each shape +//! as a NUL-terminated name and its bytes. Shape 0 holds the font's above / below heights. +//! - `unifont 1.0`: a shape count and the font information record, then each shape as number, +//! length and bytes (shape numbers are Unicode code points). +//! - `bigfont 1.0`: escape-byte ranges, then a table of (number, length, offset). +//! +//! A shape is a little program for a pen: vector bytes (length in the high nibble, one of 16 +//! directions in the low one) and the special codes 0–14 (pen up / down, scale, push / pop, +//! sub-shapes, displacements, octant, fractional and bulge arcs, vertical-only commands). +//! [`ShxFont::glyph`] runs it into polylines in font units; the end position is the advance. +//! +//! Everything read from the file is hostile: offsets and lengths are checked, programs are +//! bounded in steps, sub-shape nesting and points, and arcs in segments. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; + +use cadcraft_geom::Vec2; + +/// Largest SHX file read. +const MAX_FILE_BYTES: u64 = 16 << 20; +/// Most shapes taken from one file. +const MAX_SHAPES: usize = 70_000; +/// Most bytes one glyph program may run (sub-shapes included). +const MAX_STEPS: usize = 20_000; +/// Deepest sub-shape nesting. +const MAX_DEPTH: usize = 8; +/// Most points one glyph may produce. +const MAX_POINTS: usize = 50_000; +/// Deepest position stack (the format allows 4; some fonts push more). +const MAX_STACK: usize = 16; + +/// What a shape file is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Shapes, + Unifont, + Bigfont, +} + +/// A parsed SHX font: its shapes' programs by shape number, and its metrics. +#[derive(Debug)] +pub struct ShxFont { + pub name: String, + pub kind: Kind, + /// Height of capitals above the baseline, in font units (text height covers this). + pub above: f64, + /// Depth of descenders below the baseline, in font units. + pub below: f64, + shapes: HashMap>, +} + +/// A glyph run into strokes: polylines in font units, baseline at y = 0, and the pen's final +/// x (the advance to the next character). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Glyph { + pub strokes: Vec>, + pub advance: f64, +} + +fn u16le(b: &[u8], i: usize) -> Option { + Some(u16::from_le_bytes([*b.get(i)?, *b.get(i + 1)?])) +} +fn u32le(b: &[u8], i: usize) -> Option { + Some(u32::from_le_bytes([*b.get(i)?, *b.get(i + 1)?, *b.get(i + 2)?, *b.get(i + 3)?])) +} + +/// The bytes after a shape's NUL-terminated name. +fn after_name(def: &[u8]) -> &[u8] { + match def.iter().position(|b| *b == 0) { + Some(n) => def.get(n + 1..).unwrap_or_default(), + None => &[], + } +} + +impl ShxFont { + /// Parse SHX bytes; `None` when they are not a shape font this reader knows. + pub fn parse(name: &str, b: &[u8]) -> Option { + let head = b.get(..b.len().min(40))?; + let text: String = head.iter().take_while(|c| **c != 0x1a).map(|c| *c as char).collect(); + let start = text.len() + 1; + let lower = text.to_ascii_lowercase(); + if !lower.starts_with("autocad-86") { + return None; + } + let mut shapes: HashMap> = HashMap::new(); + let (kind, mut above, mut below); + if lower.contains("unifont") { + kind = Kind::Unifont; + let count = usize::try_from(u32le(b, start)?).ok()?.min(MAX_SHAPES); + let info_len = usize::from(u16le(b, start + 4)?); + let info = b.get(start + 6..start + 6 + info_len)?; + let rest = after_name(info); + above = f64::from(*rest.first().unwrap_or(&0)); + below = f64::from(*rest.get(1).unwrap_or(&0)); + let mut i = start + 6 + info_len; + for _ in 0..count { + let (Some(num), Some(len)) = (u16le(b, i), u16le(b, i + 2)) else { break }; + let len = usize::from(len); + let Some(def) = b.get(i + 4..i + 4 + len) else { break }; + shapes.insert(u32::from(num), after_name(def).to_vec()); + i += 4 + len; + } + } else if lower.contains("bigfont") { + kind = Kind::Bigfont; + let count = usize::from(u16le(b, start)?).min(MAX_SHAPES); + let ranges = usize::from(u16le(b, start + 2)?); + let mut i = start + 4 + ranges * 4; + above = 0.0; + below = 0.0; + for _ in 0..count { + let (Some(num), Some(len), Some(off)) = (u16le(b, i), u16le(b, i + 2), u32le(b, i + 4)) else { break }; + i += 8; + let (len, off) = (usize::from(len), usize::try_from(off).ok()?); + let Some(def) = b.get(off..off.saturating_add(len)) else { continue }; + let body = after_name(def); + if num == 0 { + above = f64::from(*body.first().unwrap_or(&0)); + } else { + shapes.insert(u32::from(num), body.to_vec()); + } + } + } else if lower.contains("shapes") { + kind = Kind::Shapes; + let count = usize::from(u16le(b, start + 4)?).min(MAX_SHAPES); + let mut index = Vec::with_capacity(count); + let mut i = start + 6; + for _ in 0..count { + let (Some(num), Some(len)) = (u16le(b, i), u16le(b, i + 2)) else { break }; + index.push((num, usize::from(len))); + i += 4; + } + above = 0.0; + below = 0.0; + for (num, len) in index { + let Some(def) = b.get(i..i + len) else { break }; + i += len; + let body = after_name(def); + if num == 0 { + above = f64::from(*body.first().unwrap_or(&0)); + below = f64::from(*body.get(1).unwrap_or(&0)); + } else { + shapes.insert(u32::from(num), body.to_vec()); + } + } + } else { + return None; + } + if above <= 0.0 { + // A font without its information shape: take the capital letter's height. + above = 10.0; + } + Some(ShxFont { name: name.to_string(), kind, above, below, shapes }) + } + + /// Whether the font draws shape `code`. + pub fn has(&self, code: u32) -> bool { + self.shapes.contains_key(&code) + } + + /// The shape that draws `c`: its code point, or for a one-byte font a Hebrew letter at + /// its Windows-1255 or DOS (862) position, and the old AutoCAD positions of °, ± and ⌀. + pub fn code_for(&self, c: char) -> Option { + let u = u32::from(c); + let mut tries: Vec = vec![u]; + if (0x05D0..=0x05EA).contains(&u) { + tries.extend([u - 0x05D0 + 0xE0, u - 0x05D0 + 0x80]); + } + match c { + '°' => tries.extend([0xB0, 0x7F]), + '±' => tries.extend([0xB1, 0x80]), + '⌀' | '∅' | 'Ø' => tries.extend([0x2205, 0x2300, 0xD8, 0x81]), + _ => {} + } + tries.into_iter().find(|t| self.has(*t)) + } + + /// Run shape `code` into strokes (font units). + pub fn glyph(&self, code: u32) -> Option { + let prog = self.shapes.get(&code)?; + let mut pen = Pen { pos: Vec2::ZERO, down: true, scale: 1.0, stack: Vec::new(), strokes: Vec::new(), cur: Vec::new(), steps: 0, points: 0 }; + self.run(prog, &mut pen, 0); + pen.lift(); + Some(Glyph { strokes: pen.strokes, advance: pen.pos.x }) + } + + fn run(&self, p: &[u8], pen: &mut Pen, depth: usize) { + let mut i = 0usize; + let byte = |i: usize| p.get(i).copied(); + let sbyte = |i: usize| p.get(i).map(|b| f64::from(*b as i8)); + // Code 14: the next command is for vertical text only; it is read and not drawn. + let mut skip = false; + while i < p.len() { + pen.steps += 1; + if pen.steps > MAX_STEPS || pen.points > MAX_POINTS { + return; + } + let Some(code) = byte(i) else { return }; + i += 1; + let draw = !skip; + skip = false; + if code >= 0x10 { + let len = f64::from(code >> 4); + let d = DIRS.get(usize::from(code & 0x0f)).copied().unwrap_or((1.0, 0.0)); + if draw { + pen.move_by(Vec2::new(d.0, d.1) * (len * pen.scale)); + } + continue; + } + match code { + 0 => { + if draw { + return; + } + } + 1 => { + if draw { + pen.down = true; + } + } + 2 => { + if draw { + pen.lift(); + pen.down = false; + } + } + 3 | 4 => { + let f = f64::from(byte(i).unwrap_or(1).max(1)); + i += 1; + if draw { + pen.scale = if code == 3 { pen.scale / f } else { pen.scale * f }; + } + } + 5 => { + if draw && pen.stack.len() < MAX_STACK { + pen.stack.push(pen.pos); + } + } + 6 => { + if draw && let Some(q) = pen.stack.pop() { + pen.lift(); + pen.pos = q; + } + } + 7 => { + let (num, extra) = match self.kind { + Kind::Shapes => (u32::from(byte(i).unwrap_or(0)), 1), + Kind::Unifont => (u32::from(u16::from_be_bytes([byte(i).unwrap_or(0), byte(i + 1).unwrap_or(0)])), 2), + Kind::Bigfont => match byte(i) { + Some(0) => (u32::from(u16::from_be_bytes([byte(i + 1).unwrap_or(0), byte(i + 2).unwrap_or(0)])), 7), + _ => (u32::from(byte(i).unwrap_or(0)), 1), + }, + }; + i += extra; + if draw + && depth < MAX_DEPTH + && let Some(sub) = self.shapes.get(&num) + { + let saved = pen.scale; + self.run(sub, pen, depth + 1); + pen.scale = saved; + } + } + 8 => { + let (dx, dy) = (sbyte(i).unwrap_or(0.0), sbyte(i + 1).unwrap_or(0.0)); + i += 2; + if draw { + pen.move_by(Vec2::new(dx, dy) * pen.scale); + } + } + 9 => loop { + let (dx, dy) = (sbyte(i).unwrap_or(0.0), sbyte(i + 1).unwrap_or(0.0)); + i += 2; + if (dx == 0.0 && dy == 0.0) || i > p.len() { + break; + } + if draw { + pen.move_by(Vec2::new(dx, dy) * pen.scale); + } + }, + 10 => { + let r = f64::from(byte(i).unwrap_or(0)) * pen.scale; + let oct = byte(i + 1).unwrap_or(0); + i += 2; + if draw { + let (cw, start, n) = octants(oct); + let a0 = start * 45.0; + let sweep = n * 45.0; + pen.arc(r, a0, if cw { a0 - sweep } else { a0 + sweep }); + } + } + 11 => { + let (so, eo) = (f64::from(byte(i).unwrap_or(0)), f64::from(byte(i + 1).unwrap_or(0))); + let r = f64::from(u16::from_be_bytes([byte(i + 2).unwrap_or(0), byte(i + 3).unwrap_or(0)])) * pen.scale; + let oct = byte(i + 4).unwrap_or(0); + i += 5; + if draw { + let (cw, start, n) = octants(oct); + let (so, eo) = (so * 45.0 / 256.0, eo * 45.0 / 256.0); + let (a0, a1) = if cw { + let a0 = start * 45.0 - so; + let last = start - (n - 1.0); + (a0, if eo > 0.0 { last * 45.0 - eo } else { (last - 1.0) * 45.0 }) + } else { + let a0 = start * 45.0 + so; + let last = start + (n - 1.0); + (a0, if eo > 0.0 { last * 45.0 + eo } else { (last + 1.0) * 45.0 }) + }; + pen.arc(r, a0, a1); + } + } + 12 => { + let (dx, dy, bu) = (sbyte(i).unwrap_or(0.0), sbyte(i + 1).unwrap_or(0.0), sbyte(i + 2).unwrap_or(0.0)); + i += 3; + if draw { + pen.bulge(Vec2::new(dx, dy) * pen.scale, bu / 127.0); + } + } + 13 => loop { + let (dx, dy) = (sbyte(i).unwrap_or(0.0), sbyte(i + 1).unwrap_or(0.0)); + i += 2; + if (dx == 0.0 && dy == 0.0) || i > p.len() { + break; + } + let bu = sbyte(i).unwrap_or(0.0); + i += 1; + if draw { + pen.bulge(Vec2::new(dx, dy) * pen.scale, bu / 127.0); + } + }, + 14 => skip = true, + _ => {} + } + } + } +} + +/// The 16 vector directions, counter-clockwise from east, as unit-square steps. +const DIRS: [(f64, f64); 16] = [ + (1.0, 0.0), + (1.0, 0.5), + (1.0, 1.0), + (0.5, 1.0), + (0.0, 1.0), + (-0.5, 1.0), + (-1.0, 1.0), + (-1.0, 0.5), + (-1.0, 0.0), + (-1.0, -0.5), + (-1.0, -1.0), + (-0.5, -1.0), + (0.0, -1.0), + (0.5, -1.0), + (1.0, -1.0), + (1.0, -0.5), +]; + +/// An octant byte: clockwise (sign bit), the starting octant (bits 4–6) and the number of +/// octants (bits 0–3, 0 meaning all 8). +fn octants(b: u8) -> (bool, f64, f64) { + let cw = b & 0x80 != 0; + let start = f64::from((b >> 4) & 0x07); + let n = match b & 0x0f { + 0 => 8.0, + n => f64::from(n.min(8)), + }; + (cw, start, n) +} + +struct Pen { + pos: Vec2, + down: bool, + scale: f64, + stack: Vec, + strokes: Vec>, + cur: Vec, + steps: usize, + points: usize, +} + +impl Pen { + fn lift(&mut self) { + let cur = std::mem::take(&mut self.cur); + if cur.len() >= 2 { + self.strokes.push(cur); + } else if let Some(p) = cur.first() + && self.down + { + // A dot: drawn as a tiny stroke. + self.strokes.push(vec![*p, *p + Vec2::new(0.25, 0.0)]); + } + } + fn line_to(&mut self, q: Vec2) { + if !q.is_finite() { + return; + } + if self.down { + if self.cur.is_empty() { + self.cur.push(self.pos); + } + self.cur.push(q); + self.points += 1; + } + self.pos = q; + } + fn move_by(&mut self, d: Vec2) { + let q = self.pos + d; + if self.down { + self.line_to(q); + } else { + self.pos = q; + } + } + /// An arc of radius `r` from angle `a0` to `a1` (degrees; the pen is on the circle at `a0`). + fn arc(&mut self, r: f64, a0: f64, a1: f64) { + if !(r.is_finite() && r > 0.0) { + return; + } + let (s, e) = (a0.to_radians(), a1.to_radians()); + let center = self.pos - Vec2::from_angle(s) * r; + let n = (((e - s).abs() / (std::f64::consts::PI / 16.0)).ceil() as usize).clamp(1, 64); + for k in 1..=n { + let a = s + (e - s) * k as f64 / n as f64; + let q = center + Vec2::from_angle(a) * r; + if self.down { + self.line_to(q); + } else { + self.pos = q; + } + } + } + /// An arc over chord `d` whose height is `bulge` × half the chord (a bulge of ±1 is a half + /// circle, positive counter-clockwise); 0 is a straight line. + fn bulge(&mut self, d: Vec2, bulge: f64) { + let start = self.pos; + let end = start + d; + if bulge.abs() < 1e-9 || d.len() < 1e-12 { + self.move_by(d); + return; + } + let theta = 4.0 * bulge.atan(); + let chord = d.len(); + let r = chord / (2.0 * (theta / 2.0).sin()).abs(); + let mid = start.mid(end); + let h = r * (theta / 2.0).cos(); + let n = d.perp() / chord; + let center = mid + n * (h * theta.signum()); + let (a0, a1) = ((start - center).angle(), (start - center).angle() + theta); + let segs = ((theta.abs() / (std::f64::consts::PI / 16.0)).ceil() as usize).clamp(1, 64); + for k in 1..=segs { + let q = if k == segs { end } else { center + Vec2::from_angle(a0 + (a1 - a0) * k as f64 / segs as f64) * r.abs() }; + if self.down { + self.line_to(q); + } else { + self.pos = q; + } + } + } +} + +// --- Finding fonts ------------------------------------------------------------------------- + +#[derive(Default)] +struct Registry { + generation: Option, + /// `.shx` files in the user's font folders, by lower-case stem. + files: HashMap, + /// Fonts registered by name (tests, web builds). + bytes: HashMap>>, + loaded: HashMap>>, +} + +fn registry() -> MutexGuard<'static, Registry> { + static R: OnceLock> = OnceLock::new(); + R.get_or_init(|| Mutex::new(Registry::default())).lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The lower-case file stem of a style font name: `C:\13\FONTS\HEBTXT.SHX` → `hebtxt`. +pub fn stem(name: &str) -> String { + let n = name.trim(); + let file = n.rsplit(['\\', '/']).next().unwrap_or(n); + let lower = file.to_ascii_lowercase(); + lower.strip_suffix(".shx").unwrap_or(&lower).trim().to_string() +} + +#[cfg(not(target_arch = "wasm32"))] +fn scan(dirs: &[String]) -> HashMap { + let mut out = HashMap::new(); + // A folder listed earlier wins. + let mut stack: Vec = dirs.iter().rev().map(PathBuf::from).collect(); + let mut seen = 0usize; + while let Some(d) = stack.pop() { + let Ok(rd) = std::fs::read_dir(&d) else { continue }; + let mut sub = Vec::new(); + for e in rd.flatten() { + seen += 1; + if seen > 50_000 { + return out; + } + let p = e.path(); + if p.is_dir() { + sub.push(p); + continue; + } + let is_shx = p.extension().is_some_and(|x| x.eq_ignore_ascii_case("shx")); + if is_shx && let Some(s) = p.file_stem().map(|s| s.to_string_lossy().to_ascii_lowercase()) { + out.entry(s).or_insert(p); + } + } + stack.extend(sub.into_iter().rev()); + } + out +} + +#[cfg(target_arch = "wasm32")] +fn scan(_dirs: &[String]) -> HashMap { + HashMap::new() +} + +/// Register SHX bytes under a font name (tests, web builds). +pub fn register(name: &str, bytes: Vec) { + let mut r = registry(); + let k = stem(name); + r.loaded.remove(&k); + r.bytes.insert(k, Arc::new(bytes)); +} + +/// The SHX font a style names (`romans_s.shx`, `miryl`, a full path), from the user's font +/// folders ([`crate::ttf::set_font_dirs`]); `None` when there is none. +pub fn find(name: &str) -> Option> { + let k = stem(name); + if k.is_empty() { + return None; + } + let mut r = registry(); + let generation = crate::ttf::generation(); + if r.generation != Some(generation) { + r.files = scan(&crate::ttf::font_dirs()); + r.loaded.clear(); + r.generation = Some(generation); + } + if let Some(f) = r.loaded.get(&k) { + return f.clone(); + } + let bytes: Option>> = match r.bytes.get(&k) { + Some(b) => Some(b.clone()), + None => r.files.get(&k).and_then(|p| { + #[cfg(not(target_arch = "wasm32"))] + { + (std::fs::metadata(p).ok()?.len() <= MAX_FILE_BYTES).then(|| std::fs::read(p).ok()).flatten().map(Arc::new) + } + #[cfg(target_arch = "wasm32")] + { + let _ = p; + None + } + }), + }; + let font = bytes.and_then(|b| ShxFont::parse(&k, &b)).map(Arc::new); + if r.loaded.len() > 256 { + r.loaded.clear(); + } + r.loaded.insert(k, font.clone()); + font +} + +/// SHX fonts in the user's font folders, by file stem (for font lists). +pub fn installed() -> Vec { + let mut r = registry(); + let generation = crate::ttf::generation(); + if r.generation != Some(generation) { + r.files = scan(&crate::ttf::font_dirs()); + r.loaded.clear(); + r.generation = Some(generation); + } + let mut v: Vec = r.files.keys().chain(r.bytes.keys()).cloned().collect(); + v.sort(); + v.dedup(); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A tiny `shapes 1.0` font of our own: shape 0 (above 4, below 1), `A` an up-and-over + /// path, `B` with an octant arc, `C` using a sub-shape. + pub(crate) fn sample() -> Vec { + let mut b = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); + let shapes: Vec<(u16, Vec)> = vec![ + (0, [b"T\0".to_vec(), vec![4, 1, 0, 0]].concat()), + // A: up 4 (0x44), right 2 (0x20), down 4 (0x4C), pen up, right 1 (0x10), end. + (u16::from(b'A'), [b"A\0".to_vec(), vec![0x44, 0x20, 0x4C, 2, 0x10, 0]].concat()), + // B: pen up, right 4, pen down, half circle of radius 2 from 0° CCW (4 octants) back to the + // origin, pen up, then 5 to the right. + (u16::from(b'B'), [b"B\0".to_vec(), vec![2, 0x40, 1, 10, 2, 0x04, 2, 8, 5, 0, 0]].concat()), + // C: sub-shape A, then 8,(1,0). + (u16::from(b'C'), [b"C\0".to_vec(), vec![7, b'A', 0]].concat()), + ]; + let first = 0u16; + let last = u16::from(b'C'); + b.extend(first.to_le_bytes()); + b.extend(last.to_le_bytes()); + b.extend(u16::try_from(shapes.len()).unwrap_or(0).to_le_bytes()); + for (n, d) in &shapes { + b.extend(n.to_le_bytes()); + b.extend(u16::try_from(d.len()).unwrap_or(0).to_le_bytes()); + } + for (_, d) in &shapes { + b.extend(d); + } + b + } + + #[test] + fn reads_a_shapes_font_and_runs_its_programs() { + let f = ShxFont::parse("t", &sample()).expect("parses"); + assert_eq!(f.kind, Kind::Shapes); + assert_eq!((f.above, f.below), (4.0, 1.0)); + let a = f.glyph(u32::from(b'A')).expect("A"); + assert_eq!(a.strokes, vec![vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 4.0), Vec2::new(2.0, 4.0), Vec2::new(2.0, 0.0)]]); + assert_eq!(a.advance, 3.0); + let b = f.glyph(u32::from(b'B')).expect("B"); + let arc = b.strokes.first().expect("an arc"); + let top = arc.iter().map(|p| p.y).fold(f64::MIN, f64::max); + assert!((top - 2.0).abs() < 1e-9, "a half circle of radius 2 reaches y = 2: {top}"); + assert!(arc.last().is_some_and(|p| (p.x - 0.0).abs() < 1e-9 && p.y.abs() < 1e-9), "{arc:?}"); + assert_eq!(f.glyph(u32::from(b'C')).map(|g| g.advance), Some(3.0)); + } + + #[test] + fn text_in_an_shx_style_is_drawn_with_the_font() { + register("tiny_test.shx", sample()); + let font = crate::TextFont::resolve("C:\\FONTS\\TINY_TEST.SHX"); + assert!(matches!(font, crate::TextFont::Shx { .. }), "{font:?}"); + // Text height 8 is twice the font's capital height (4): A is 3 units wide, B 5. + let sh = crate::shape_line(&font, "AB", 8.0, 1.0, 0.0); + assert!((sh.width - 16.0).abs() < 1e-9, "{}", sh.width); + let top = sh.strokes.iter().flatten().map(|p| p.y).fold(f64::MIN, f64::max); + assert!((top - 8.0).abs() < 1e-9, "{top}"); + // A character the font lacks comes from the stroke font. + let with_x = crate::shape_line(&font, "AX", 8.0, 1.0, 0.0); + assert!(with_x.width > 6.0 && with_x.strokes.len() > 1); + assert!(crate::ttf::available("tiny_test.shx")); + } + + #[test] + fn hebrew_letters_find_their_one_byte_positions() { + let mut b = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); + let shapes: Vec<(u16, Vec)> = vec![(0, b"H\0\x04\x01\x00\x00".to_vec()), (0xE0, b"\0\x14\x00".to_vec())]; + b.extend(0u16.to_le_bytes()); + b.extend(0xE0u16.to_le_bytes()); + b.extend(2u16.to_le_bytes()); + for (n, d) in &shapes { + b.extend(n.to_le_bytes()); + b.extend(u16::try_from(d.len()).unwrap_or(0).to_le_bytes()); + } + for (_, d) in &shapes { + b.extend(d); + } + let f = ShxFont::parse("h", &b).expect("parses"); + assert_eq!(f.code_for('א'), Some(0xE0)); + assert_eq!(f.code_for('ב'), None); + } + + #[test] + fn hostile_bytes_never_panic() { + let good = sample(); + for cut in 0..good.len() { + let _ = ShxFont::parse("x", good.get(..cut).unwrap_or_default()); + } + let mut bad = good.clone(); + for i in 24..bad.len() { + if let Some(b) = bad.get_mut(i) { + *b = b.wrapping_mul(37).wrapping_add(11); + } + if let Some(f) = ShxFont::parse("x", &bad) { + for c in 0..300 { + let _ = f.glyph(c); + } + } + } + // A shape that calls itself stops. + let mut b = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); + let shapes: Vec<(u16, Vec)> = vec![(0, b"T\0\x04\x01\x00\x00".to_vec()), (65, b"\0\x07\x41\x10\x00".to_vec())]; + b.extend(0u16.to_le_bytes()); + b.extend(65u16.to_le_bytes()); + b.extend(2u16.to_le_bytes()); + for (n, d) in &shapes { + b.extend(n.to_le_bytes()); + b.extend(u16::try_from(d.len()).unwrap_or(0).to_le_bytes()); + } + for (_, d) in &shapes { + b.extend(d); + } + let f = ShxFont::parse("loop", &b).expect("parses"); + assert!(f.glyph(65).is_some()); + } +} diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 62759c1b0a..45cc442bbb 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -13,6 +13,10 @@ //! //! On native builds both start from the `CADCRAFT_FONTALT` / `CADCRAFT_FONTFALLBACK` //! environment variables. +//! +//! Besides the system font folders, the user's own font folders ([`set_font_dirs`], Options ▸ +//! Fonts) are searched first: a font placed there wins over an installed one with the same file +//! name. use std::collections::HashMap; use std::path::PathBuf; @@ -75,6 +79,16 @@ impl Face { pub fn has_glyph(&self, c: char) -> bool { self.font().is_some_and(|f| f.charmap().map(c).is_some()) } + /// The family name, as the font gives it. + pub fn family_name(&self) -> Option { + let f = self.font()?; + [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME] + .into_iter() + .find_map(|id| f.localized_strings(id).next().map(|s| s.to_string())) + .map(|s| s.chars().filter(|c| !c.is_control()).take(80).collect::()) + .filter(|s| !s.trim().is_empty()) + } + fn names(&self) -> Vec { let Some(f) = self.font() else { return Vec::new() }; [skrifa::string::StringId::FAMILY_NAME, skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FULL_NAME] @@ -179,6 +193,8 @@ struct Db { fallback: Fallback, /// Bytes of font files loaded from disk so far (bounded by `MAX_LOADED_BYTES`). loaded_bytes: usize, + /// Stems of the fonts found in the user's font folders. + user: std::collections::HashSet, } /// State of the missing-glyph search. @@ -209,7 +225,11 @@ fn lock() -> MutexGuard<'static, Db> { let mut g = DB.get_or_init(|| Mutex::new(Db::default())).lock().unwrap_or_else(PoisonError::into_inner); if !g.scanned { g.scanned = true; - g.paths = scan().into_iter().map(|(stem, p)| (stem, Source::File(p))).collect(); + let user = scan_dirs(&user_dirs(), true); + g.user = user.keys().cloned().collect(); + let mut all = scan(); + all.extend(user); + g.paths = all.into_iter().map(|(stem, p)| (stem, Source::File(p))).collect(); // Embedded craft-fonts fonts take the place of an installed file with the same stem. for f in crate::CRAFT_FONTS { g.paths.insert(f.stem(), Source::Static(f.bytes)); @@ -220,7 +240,6 @@ fn lock() -> MutexGuard<'static, Db> { #[cfg(not(target_arch = "wasm32"))] fn scan() -> HashMap { - let mut out = HashMap::new(); let mut dirs: Vec = Vec::new(); if cfg!(target_os = "macos") { dirs.extend(["/System/Library/Fonts", "/System/Library/Fonts/Supplemental", "/Library/Fonts"].map(Into::into)); @@ -239,7 +258,15 @@ fn scan() -> HashMap { dirs.push(PathBuf::from(h).join(".local/share/fonts")); } } - let mut stack = dirs; + scan_dirs(&dirs, false) +} + +/// Font files under `dirs` by lower-case stem; the first file found with a stem wins +/// (`in_order`: a folder listed earlier wins over a later one). +#[cfg(not(target_arch = "wasm32"))] +fn scan_dirs(dirs: &[PathBuf], in_order: bool) -> HashMap { + let mut out = HashMap::new(); + let mut stack: Vec = if in_order { dirs.iter().rev().cloned().collect() } else { dirs.to_vec() }; let mut seen = 0usize; while let Some(d) = stack.pop() { let Ok(rd) = std::fs::read_dir(&d) else { continue }; @@ -270,6 +297,137 @@ fn scan() -> HashMap { HashMap::new() } +#[cfg(target_arch = "wasm32")] +fn scan_dirs(_dirs: &[PathBuf], _in_order: bool) -> HashMap { + HashMap::new() +} + +/// Most user font folders. +pub const MAX_FONT_DIRS: usize = 16; +/// The longest font folder path kept. +const MAX_DIR_CHARS: usize = 1024; + +fn dirs_lock() -> MutexGuard<'static, Vec> { + static DIRS: OnceLock>> = OnceLock::new(); + DIRS.get_or_init(|| Mutex::new(Vec::new())).lock().unwrap_or_else(PoisonError::into_inner) +} + +fn user_dirs() -> Vec { + dirs_lock().clone() +} + +/// Counts changes to the set of fonts ([`set_font_dirs`], [`rescan`]): text drawn before a change +/// may have been drawn with another font. +static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// The font set's change count (see [`GENERATION`]). +pub fn generation() -> u64 { + GENERATION.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The user's font folders, searched before the system's. +pub fn font_dirs() -> Vec { + user_dirs().iter().map(|p| p.to_string_lossy().to_string()).collect() +} + +/// Clean a font folder list: trimmed, without empty, repeated or over-long entries, at most +/// [`MAX_FONT_DIRS`]. +pub fn clean_dirs>(dirs: &[S]) -> Vec { + let mut out: Vec = Vec::new(); + for d in dirs.iter().take(MAX_FONT_DIRS * 4) { + let d = d.as_ref().trim(); + if d.is_empty() || d.chars().count() > MAX_DIR_CHARS || d.chars().any(char::is_control) || out.iter().any(|o| o == d) { + continue; + } + out.push(d.to_string()); + if out.len() >= MAX_FONT_DIRS { + break; + } + } + out +} + +/// Set the user's font folders (Options ▸ Fonts) and look for fonts again. +pub fn set_font_dirs>(dirs: &[S]) { + let dirs: Vec = clean_dirs(dirs).into_iter().map(PathBuf::from).collect(); + { + let mut current = dirs_lock(); + if *current == dirs { + return; + } + *current = dirs; + } + rescan(); +} + +/// Forget what was found and look for fonts again (files added to a font folder). +pub fn rescan() { + let mut g = lock(); + // Fonts registered by name (no file behind them) stay. + let paths = std::mem::take(&mut g.paths); + g.files.retain(|k, _| !paths.contains_key(k)); + g.scanned = false; + g.resolved.clear(); + g.fallback = Fallback::default(); + g.loaded_bytes = 0; + g.user.clear(); + drop(g); + GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// A font file CADCraft can use, for font lists. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FontFile { + /// The name a text style stores: the file name (`arial.ttf`), or the name of a font built + /// into CADCraft. + pub name: String, + /// The family name inside the file, read for fonts in the user's folders. + pub family: Option, + /// Found in one of the user's font folders. + pub user: bool, +} + +/// The fonts CADCraft can use: those in the user's folders first (with their family names), +/// then the installed and built-in ones, by name. +pub fn installed() -> Vec { + /// Fonts whose family name is read for the list. + const MAX_NAMED: usize = 200; + let mut g = lock(); + let mut list: Vec<(String, String, bool)> = g + .paths + .iter() + .map(|(stem, src)| { + let name = match src { + Source::File(p) => p.file_name().map_or_else(|| stem.clone(), |n| n.to_string_lossy().to_string()), + Source::Static(_) => stem.clone(), + }; + (stem.clone(), name, g.user.contains(stem)) + }) + .collect(); + list.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase()))); + let mut named = 0usize; + list.into_iter() + .map(|(stem, name, user)| { + let family = if user && named < MAX_NAMED { + named += 1; + g.file(&stem).and_then(|b| faces(&b).into_iter().next()).and_then(|f| f.family_name()) + } else { + None + }; + FontFile { name, family, user } + }) + .collect() +} + +/// Whether a text style font is drawn as named: a font CADCraft found, or its own stroke font. +/// Other names (an SHX file, a missing TTF) are drawn with a substitute ([`crate::TextFont::resolve`]). +pub fn available(name: &str) -> bool { + let k = key(name); + // The built-in stroke font is CADCraft's own stand-in for the basic stroke fonts. + let stand_in = matches!(k.trim_end_matches(".shx"), "txt" | "simplex" | "romans"); + k.is_empty() || stand_in || k == crate::BUILTIN_FONT.to_ascii_lowercase() || crate::shx::find(name).is_some() || find(name).is_some() +} + #[cfg(not(target_arch = "wasm32"))] fn read_file(path: &std::path::Path) -> Option> { /// Font files larger than this are never read. @@ -310,7 +468,25 @@ impl Db { return Some(face); } } - self.by_family(k) + self.by_family(k).or_else(|| self.user_family(k)) + } + + /// A face in the user's font folders whose family or full name is `k`, whatever its file is + /// called (the folders are small; at most 200 files are looked at). + fn user_family(&mut self, k: &str) -> Option { + let want = norm(k); + if want.is_empty() { + return None; + } + let mut stems: Vec = self.user.iter().cloned().collect(); + stems.sort(); + for stem in stems.into_iter().take(200) { + let Some(bytes) = self.file(&stem) else { continue }; + if let Some(face) = faces(&bytes).into_iter().find(|f| f.names().iter().any(|n| *n == want || format!("{n}regular") == want)) { + return Some(face); + } + } + None } /// A face whose family or full name is `k`, among files with a similar stem, then among the @@ -867,6 +1043,41 @@ pub fn layout_line(face: &Face, s: &str, height: f64, width_factor: f64, oblique mod family_tests { use super::*; + #[test] + fn font_folders_are_cleaned_and_unknown_shx_names_are_not_available() { + let long = "x".repeat(MAX_DIR_CHARS + 1); + let many: Vec = (0..40).map(|i| format!("/fonts/{i}")).collect(); + assert_eq!(clean_dirs(&[" /a ", "", "/a", "/b", long.as_str(), "bad\u{0}dir"]), vec!["/a".to_string(), "/b".to_string()]); + assert_eq!(clean_dirs(&many).len(), MAX_FONT_DIRS); + assert!(!available("gost_cadcraft.shx")); + assert!(available("txt.shx") && available("SIMPLEX.SHX"), "the built-in stroke font stands in for these"); + assert!(available("")); + assert!(available(crate::BUILTIN_FONT)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_font_in_a_user_folder_is_found_listed_and_dropped_with_the_folder() { + let Some(src) = scan().into_values().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("ttf"))) else { return }; + let dir = std::env::temp_dir().join(format!("cadcraft-fontdir-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let Ok(_) = std::fs::copy(&src, dir.join("CadcraftTestFace.ttf")) else { return }; + let before = generation(); + set_font_dirs(&[dir.to_string_lossy().to_string()]); + assert!(generation() > before); + assert!(find("CadcraftTestFace.ttf").is_some()); + let listed = installed(); + let entry = listed.iter().find(|f| f.name == "CadcraftTestFace.ttf"); + assert!(entry.is_some_and(|f| f.user && f.family.is_some()), "{entry:?}"); + assert!(listed.first().is_some_and(|f| f.user), "the user's fonts come first"); + if let Some(family) = entry.and_then(|f| f.family.clone()) { + assert!(find(&family).is_some(), "found by its family name: {family}"); + } + set_font_dirs::<&str>(&[]); + assert!(find("CadcraftTestFace.ttf").is_none()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_family_is_looked_for_in_files_starting_with_its_first_word() { let stems: Vec = ["gost", "gost2304a", "gost common", "arial", "isocpeur"].map(String::from).to_vec(); diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index 04ce90a014..f29b84d722 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -78,6 +78,9 @@ struct Parsed { dogleg_on: Option, dogleg: Option, arrow: Option, + /// Arrowhead BLOCK_RECORD (342 on the entity, else 341 of a leader line). + arrow_block: Option, + line_arrow_block: Option, content: Option, text_style: Option, block: Option, @@ -148,6 +151,7 @@ fn parse(tags: &[Tag]) -> Parsed { 291 => p.dogleg_on = Some(t.i64() != 0), 41 => p.dogleg = finite(f), 42 => p.arrow = finite(f), + 342 => p.arrow_block = handle(t), 172 => p.content = Some(t.i64()), 343 => p.text_style = handle(t), 344 => p.block = handle(t), @@ -253,6 +257,7 @@ fn parse(tags: &[Tag]) -> Parsed { } } } + 341 => p.line_arrow_block = p.line_arrow_block.take().or_else(|| handle(t)), _ => {} }, } @@ -334,6 +339,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { text, style: def.name, arrow_size: pos(p.arrow_ctx).or(pos(p.arrow)).unwrap_or(def.arrow_size), + arrow: String::new(), spline: p.leader_type == Some(2), block, } @@ -361,6 +367,10 @@ pub(crate) fn resolve(tags: &[Tag], m: &mut MLeader, styles: &HashMap { @@ -459,6 +469,8 @@ pub(crate) struct Refs { pub text_style: Option, /// BLOCK_RECORD handle of the content block. pub block: Option, + /// BLOCK_RECORD handle of its own arrowhead. + pub arrow: Option, } /// The groups of a MULTILEADER record after its `AcDbMLeader` marker. @@ -572,7 +584,8 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { s(&mut t, 340, &r.style); // Overridden properties: leader type, landing and dogleg, arrowhead size, content type, // text style and height, block content (the entity holds its own values). - i(&mut t, 90, 0x1 | 0x10 | 0x40 | 0x80 | 0x200 | 0x400 | 0x800 | 0x1_0000 | 0x8_0000); + let arrow_flag = if r.arrow.is_some() { 0x100 } else { 0 }; + i(&mut t, 90, 0x1 | 0x10 | 0x40 | 0x80 | arrow_flag | 0x200 | 0x400 | 0x800 | 0x1_0000 | 0x8_0000); i( &mut t, 170, @@ -589,6 +602,9 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { i(&mut t, 290, 1); i(&mut t, 291, i64::from(m.dogleg > 0.0)); f(&mut t, 41, m.dogleg); + if let Some(a) = &r.arrow { + s(&mut t, 342, a); + } f(&mut t, 42, m.arrow_size); i( &mut t, diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index 7615bc569c..e4b4a4086f 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -2063,6 +2063,7 @@ impl Objects { let st = MLeaderStyle { name: name.clone(), arrow_size: num(44, def.arrow_size, 0.0), + arrow_block: t.s(341).and_then(|h| rx.brs.get(&h.trim().to_ascii_uppercase()).cloned()).unwrap_or_default(), text_height: t.f(45).filter(|v| v.is_finite() && *v > 0.0).unwrap_or(def.text_height), landing_gap: num(42, def.landing_gap, 0.0), dogleg: num(43, def.dogleg, 0.0), @@ -2193,6 +2194,12 @@ fn page_setup(t: &T) -> PageSetup { p.height_mm = w.max(h); } p.margins_mm = [mm(40, p.margins_mm[0]), mm(41, p.margins_mm[1]), mm(42, p.margins_mm[2]), mm(43, p.margins_mm[3])]; + // Plot paper units: 0 inches, 1 millimetres (2 pixels: raster devices, drawn as millimetres). + p.mm_units = match t.i(72) { + Some(0) => Some(false), + Some(1 | 2) => Some(true), + _ => None, + }; // Plot rotation 1 or 3 turns the media a quarter turn; media defined wider than tall is // already landscape. let rotated = matches!(t.i(73), Some(1 | 3)); diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index cd4d2c17cf..bbccc4438f 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -942,6 +942,7 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx style: cx.mleader_style(&m.style), text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)), block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()), + arrow: Some(m.arrow.trim()).filter(|a| !a.is_empty()).and_then(|a| cx.arrow(a)), }; w.t.extend(crate::dxf_mleader::entity_tags(d, m, &refs)); } @@ -1665,7 +1666,11 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { for s in &d.dim_styles { arrow_names.extend([s.arrow_block.clone(), s.arrow_block1.clone(), s.arrow_block2.clone(), s.leader_arrow_block.clone()]); } + arrow_names.extend(d.mleader_styles.iter().map(|s| s.arrow_block.clone())); for e in &every { + if let EntityKind::MLeader(m) = &e.kind { + arrow_names.push(m.arrow.clone()); + } if let EntityKind::Dimension(dm) = &e.kind { for (k, v) in &dm.overrides { let Some(f) = DimStyle::field_name(k).filter(|f| f.starts_with("arrowBlock") || *f == "leaderArrowBlock") else { continue }; @@ -2257,7 +2262,8 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { } let byblock_ltype = ltype_handles.get("BYBLOCK").cloned(); for (s, h) in mleader_styles.iter().zip(&mleader_handles) { - mleader_style_obj(&mut w, s, h, &mleader_dict, byblock_ltype.as_deref(), cx.style(&s.text_style)); + let arrow = Some(s.arrow_block.trim()).filter(|a| !a.is_empty()).and_then(|a| cx.arrow(a)); + mleader_style_obj(&mut w, s, h, &mleader_dict, byblock_ltype.as_deref(), cx.style(&s.text_style), arrow); } // Multiline styles. w.t.extend(crate::dxf_mline::objects(&cx.mlines, &root_dict)); @@ -2359,6 +2365,8 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.s(3, &l.name); w.s(350, layout_handles.get(i).cloned().unwrap_or_default()); } + // Plot paper units of a layout that names none: the drawing's measurement system. + let metric_paper = d.header.i64("MEASUREMENT", 0) == 1; let layout_obj = |w: &mut W, h: &str, name: &str, tab: i64, brh: &str, flags: i64, page: &PageSetup, view: Option<(Vec2, f64)>| { // Plot scale: a standard scale when fitting or 1:1, otherwise custom (142 paper units // per 143 drawing units). @@ -2405,7 +2413,7 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.f(c, v); } w.i(70, plot_flags); - w.i(72, 0); + w.i(72, i64::from(page.mm_units.unwrap_or(metric_paper))); w.i(73, i64::from(page.landscape)); w.i(74, plot_type); w.s(7, &page.plot_style_table); @@ -2571,7 +2579,15 @@ fn group_obj(w: &mut W, g: &Group, h: &str, dict: &str, written: &std::collectio /// A MLEADERSTYLE object (DXF Reference, OBJECTS: MLEADERSTYLE): MText content and straight /// ByBlock leaders with the style's landing gap, dogleg length, arrow size, text style and /// text height. -fn mleader_style_obj(w: &mut W, s: &MLeaderStyle, h: &str, dict: &str, byblock_ltype: Option<&str>, text_style: Option) { +fn mleader_style_obj( + w: &mut W, + s: &MLeaderStyle, + h: &str, + dict: &str, + byblock_ltype: Option<&str>, + text_style: Option, + arrow: Option, +) { // ByBlock as a 32-bit colour value (0xC1000000). const BYBLOCK: i64 = -1_056_964_608; w.s(0, "MLEADERSTYLE"); @@ -2597,6 +2613,9 @@ fn mleader_style_obj(w: &mut W, s: &MLeaderStyle, h: &str, dict: &str, byblock_l w.i(291, 1); w.f(43, s.dogleg); w.s(3, ""); + if let Some(a) = arrow { + w.s(341, &a); + } w.f(44, s.arrow_size); w.s(300, ""); if let Some(ts) = text_style { diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 0fb8407a51..a1ae98f5b8 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1552,6 +1552,7 @@ fn mleader_is_written_as_multileader() { text: Some(text), style: "Standard".into(), arrow_size: 2.5, + arrow: String::new(), spline: false, block: None, }; diff --git a/crates/io/tests/followups_626.rs b/crates/io/tests/followups_626.rs index a44a27eb43..797d4b5356 100644 --- a/crates/io/tests/followups_626.rs +++ b/crates/io/tests/followups_626.rs @@ -48,6 +48,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { }), style: "Standard".into(), arrow_size: 1.0, + arrow: String::new(), spline: false, block: None, }; diff --git a/crates/io/tests/mleader_content.rs b/crates/io/tests/mleader_content.rs index 07f4b16bc7..0c2ac30747 100644 --- a/crates/io/tests/mleader_content.rs +++ b/crates/io/tests/mleader_content.rs @@ -17,6 +17,7 @@ fn spline_leader_and_block_content_are_written() { text: None, style: "Standard".into(), arrow_size: 1.0, + arrow: String::new(), spline: true, block: Some(Insert { block: "TAG".into(), diff --git a/crates/io/tests/mleader_roundtrip.rs b/crates/io/tests/mleader_roundtrip.rs index 4cb1bff34c..502ea8d8b8 100644 --- a/crates/io/tests/mleader_roundtrip.rs +++ b/crates/io/tests/mleader_roundtrip.rs @@ -35,6 +35,7 @@ fn text_mleader() -> MLeader { }), style: "Callout".into(), arrow_size: 0.3, + arrow: String::new(), spline: false, block: None, } @@ -129,6 +130,7 @@ fn spline_leader_with_block_content_and_attributes() { text: None, style: "Standard".into(), arrow_size: 0.18, + arrow: String::new(), spline: true, block: Some(ins), }; @@ -265,3 +267,22 @@ fn multileader_through_dwg() { assert_eq!(got.len(), 1, "{:?}", back.model.iter().map(|e| e.kind.dxf_name()).collect::>()); assert_eq!(*got[0], m); } + +#[test] +fn a_multileaders_own_arrowhead_survives() { + let mut d = Drawing::new_metric(); + d.text_styles.push(TextStyle { name: "Notes".into(), ..TextStyle::default() }); + d.mleader_styles.push(MLeaderStyle { name: "Callout".into(), arrow_size: 0.3, ..MLeaderStyle::default() }); + // A user arrowhead block, and a built-in arrowhead by its block name. + let mut blk = Block::new("HATZ"); + blk.entities.push(Entity::new(Handle(0x200), EntityKind::Line(Line { a: Vec3::new(-1.0, -1.0, 0.0), b: Vec3::new(1.0, 1.0, 0.0) }))); + d.blocks.insert("HATZ".into(), std::sync::Arc::new(blk)); + for arrow in ["HATZ", "_Open30"] { + let m = MLeader { arrow: arrow.into(), ..text_mleader() }; + d.add(&Space::Model, Common { layer: "0".into(), ..Common::default() }, EntityKind::MLeader(m)).unwrap(); + } + d.add(&Space::Model, Common { layer: "0".into(), ..Common::default() }, EntityKind::MLeader(text_mleader())).unwrap(); + let (_, back) = roundtrip(&d); + let got: Vec = mleaders(&back).iter().map(|m| m.arrow.to_ascii_uppercase()).collect(); + assert_eq!(got, ["HATZ", "_OPEN30", ""], "own arrowheads kept, the style's left to the style"); +} diff --git a/crates/io/tests/tables_objects_roundtrip.rs b/crates/io/tests/tables_objects_roundtrip.rs index 0f75e4cd3d..5eb4b4798f 100644 --- a/crates/io/tests/tables_objects_roundtrip.rs +++ b/crates/io/tests/tables_objects_roundtrip.rs @@ -65,6 +65,7 @@ fn multileader_styles_and_current_style_round_trip() { let callout = MLeaderStyle { name: "Callout".into(), arrow_size: 2.0, + arrow_block: "_DotSmall".into(), text_height: 3.0, landing_gap: 1.0, dogleg: 5.0, @@ -97,6 +98,10 @@ fn layout_page_setup_and_paper_view_round_trip() { second.page.lineweights = false; second.page.plot_area = "window".into(); second.page.device = "DWG To PDF.pc3".into(); + // An inch drawing's layouts are written with inch paper units, and read back saying so. + for l in &mut d.layouts { + l.page.mm_units = Some(false); + } let r = round_trip(&d); for (a, b) in d.layouts.iter().zip(&r.layouts) { assert_eq!(a.name, b.name); @@ -106,6 +111,23 @@ fn layout_page_setup_and_paper_view_round_trip() { assert_eq!(r.layouts.len(), d.layouts.len()); } +#[test] +fn a_layout_in_millimetres_in_an_inch_drawing_is_drawn_in_millimetres() { + // As AutoCAD writes it: MEASUREMENT 0 (inches) but the layout's plot paper units are mm, so + // paper space is in millimetres and an A3 sheet is 420 × 297 units, not 16.5 × 11.7. + let mut d = Drawing::new_imperial(); + let l = d.layouts.get_mut(0).expect("Layout1"); + l.page.width_mm = 297.0; + l.page.height_mm = 420.0; + l.page.margins_mm = [0.0; 4]; + l.page.mm_units = Some(true); + let r = round_trip(&d); + let page = &r.layouts.first().expect("Layout1").page; + assert_eq!(page.mm_units, Some(true)); + let sheet = cadcraft_render::paper::Sheet::from_page(page, cadcraft_render::paper::paper_unit_mm(&r)); + assert!((sheet.size.x - 420.0).abs() < 1e-9 && (sheet.size.y - 297.0).abs() < 1e-9, "{:?}", sheet.size); +} + #[test] fn named_views_ucss_and_groups_round_trip() { let mut d = Drawing::new_imperial(); diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index a57142bad4..0d83346892 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -460,6 +460,53 @@ pub struct DimText { pub fixed_height: f64, pub width_factor: f64, pub oblique: f64, + /// User arrowheads: blocks of the drawing named by DIMBLK / DIMBLK1 / DIMBLK2, by name, as + /// unit-size geometry with the tip at the origin pointing along +x. + pub user_arrows: Vec<(String, ArrowGeom)>, +} + +/// An end marker: one of the arrowheads drawn in code, or a user arrowhead block. +#[derive(Clone, Copy)] +enum Head<'a> { + Std(Arrowhead), + User(&'a ArrowGeom), +} + +impl Head<'_> { + fn is_tick(self) -> bool { + match self { + Head::Std(a) => a.is_tick(), + Head::User(_) => false, + } + } + fn geom(self, tip: Vec2, dir: Vec2, size: f64) -> ArrowGeom { + match self { + Head::Std(a) => arrowhead(a, tip, dir, size), + Head::User(g) => { + let dir = if dir == Vec2::ZERO || !dir.is_finite() { Vec2::X } else { dir }; + let size = if size.is_finite() { size.abs() } else { 0.0 }; + let n = dir.perp(); + let at = |p: &Vec2| tip + dir * (p.x * size) + n * (p.y * size); + ArrowGeom { lines: g.lines.iter().map(|l| l.iter().map(at).collect()).collect(), tris: g.tris.iter().map(at).collect() } + } + } + } + fn inset(self, size: f64) -> f64 { + match self { + Head::Std(a) => a.inset(size), + Head::User(_) => 0.0, + } + } +} + +/// The end marker a DIMBLK name gives: a user arrowhead block when the drawing has one by that +/// name, else the built-in arrowhead. +fn head<'a>(name: &str, font: &'a DimText) -> Head<'a> { + let n = name.trim(); + match font.user_arrows.iter().find(|(k, _)| !n.is_empty() && k.eq_ignore_ascii_case(n)) { + Some((_, g)) => Head::User(g), + None => Head::Std(Arrowhead::parse(n)), + } } /// Generate the geometry of a dimension with the stroke font. @@ -476,8 +523,8 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let gap = st.text_gap.abs() * k; let tsz = st.tick_size * k; let ticks = tsz > 0.0; - let blk1 = Arrowhead::parse(if st.arrow_block1.is_empty() { &st.arrow_block } else { &st.arrow_block1 }); - let blk2 = Arrowhead::parse(if st.arrow_block2.is_empty() { &st.arrow_block } else { &st.arrow_block2 }); + let blk1 = head(if st.arrow_block1.is_empty() { &st.arrow_block } else { &st.arrow_block1 }, font); + let blk2 = head(if st.arrow_block2.is_empty() { &st.arrow_block } else { &st.arrow_block2 }, font); let mut g = DimGeometry { text_height: th, ..Default::default() }; // Measure the text: lay it out once at the origin, centred. let wf = if font.width_factor > 0.0 && font.width_factor.is_finite() { font.width_factor } else { 1.0 }; @@ -499,12 +546,12 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let mut text_angle = 0.0; let mut text_mid = d.text_mid.xy(); // Place an end marker: tick or arrowhead. Returns how far the dimension line stops short. - let end = |g: &mut DimGeometry, kind: Arrowhead, tip: Vec2, dir: Vec2| -> f64 { + let end = |g: &mut DimGeometry, kind: Head<'_>, tip: Vec2, dir: Vec2| -> f64 { if ticks { g.dim(tick(tip, dir, tsz)); 0.0 } else { - g.add_arrow(arrowhead(kind, tip, dir, asz)); + g.add_arrow(kind.geom(tip, dir, asz)); kind.inset(asz) } }; @@ -680,13 +727,32 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font } to_text(&mut g, if outside_arrows { f2 + u * stub } else { f2 }); } - // DIMTMOVE 1: a leader from the dimension line to text moved off it. + // DIMTMOVE 0: text the user moved along the line past an extension line takes the + // dimension line with it, out to its far end. + if d.user_text_pos && st.text_move == 0 && has_text && text_in { + let len = (f2 - f1).dot(u); + let t = (text_mid - f1).dot(u); + if t.is_finite() && len.is_finite() { + if t + half > len + 1e-9 { + seg(&mut g, f2, f1 + u * (t + half)); + } + if t - half < -1e-9 { + seg(&mut g, f1 + u * (t - half), f1); + } + } + } + // DIMTMOVE 1: text moved off the dimension line sits on a landing (a line under the + // text, as long as the text), joined to the middle of the dimension line by a leader + // to its nearer end. if d.user_text_pos && st.text_move == 1 && has_text { let base = f1.mid(f2); let off = (text_mid - base).dot(n).abs(); - if off > tht / 2.0 + gap + 1e-9 { - let side = if (base - text_mid).dot(tr) >= 0.0 { tr } else { -tr }; - g.dim(vec![base, text_mid + side * (tw / 2.0 + gap)]); + if off > tht + gap { + let under = text_mid - tr.perp() * (tht / 2.0 + gap / 2.0); + let (a, b) = (under - tr * (tw / 2.0 + gap / 2.0), under + tr * (tw / 2.0 + gap / 2.0)); + let near = if a.dist(base) <= b.dist(base) { a } else { b }; + g.dim(vec![base, near]); + g.dim(vec![a, b]); } } // DIMJOGLINE: a zigzag in the dimension line, 1.5 text heights tall. @@ -1312,4 +1378,36 @@ mod tests { let g = dimension_geometry(&d, &DimStyle::default(), 1.0); assert!(g.lines.is_empty() && g.fills.is_empty(), "{:?}", g.lines); } + + #[test] + fn a_user_arrowhead_block_is_drawn_at_each_end_and_a_moved_text_sits_on_a_landing() { + let cross = ArrowGeom { + lines: vec![vec![Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0)], vec![Vec2::new(0.0, -1.0), Vec2::new(0.0, 1.0)]], + tris: Vec::new(), + }; + let font = DimText { width_factor: 1.0, user_arrows: vec![("Hatz".into(), cross)], ..Default::default() }; + let st = st_with(|s| { + s.arrow_block = "HATZ".into(); + s.arrow_size = 0.5; + }); + let d = lin((0.0, 0.0), (10.0, 0.0), (5.0, 3.0), 0.0); + let g = dimension_geometry_with(&d, &st, 1.0, &font); + // The cross's vertical stroke at both ends of the dimension line, half a unit each way. + for x in [0.0, 10.0] { + assert!( + g.lines.iter().any(|l| l.len() == 2 && (l[0] - Vec2::new(x, 2.5)).len() < 1e-9 && (l[1] - Vec2::new(x, 3.5)).len() < 1e-9) + || g.lines.iter().any(|l| l.len() == 2 && (l[1] - Vec2::new(x, 2.5)).len() < 1e-9 && (l[0] - Vec2::new(x, 3.5)).len() < 1e-9), + "{x}: {:?}", + g.lines + ); + } + assert!(g.fills.is_empty(), "no closed filled arrows"); + // DIMTMOVE 1, text moved well off the line: a leader and a landing under the text. + let st = st_with(|s| s.text_move = 1); + let moved = Dimension { user_text_pos: true, text_mid: cadcraft_geom::Vec3::new(14.0, 8.0, 0.0), ..d }; + let g = dimension_geometry_with(&moved, &st, 1.0, &font); + let landing = + g.lines.iter().find(|l| l.len() == 2 && (l[0].y - l[1].y).abs() < 1e-9 && l[0].y < 8.0 && l[0].y > 7.0 && (l[0].x - l[1].x).abs() > 0.2); + assert!(landing.is_some(), "a landing under the text: {:?}", g.lines); + } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8dadabe88b..5d90e2a1a5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1206,9 +1206,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { let st = ctx.d.dim_style(&l.style); // DIMASZ × DIMSCALE of the leader's style (the drawing's DIMSCALE when it is 0). let size = st.map(|s| s.arrow_size).unwrap_or(0.18) * leader_scale(ctx.d, st); - // DIMLDRBLK ("" = closed filled). - let kind = dim::Arrowhead::parse(st.map(|s| s.leader_arrow_block.as_str()).unwrap_or("")); - let g = dim::arrowhead(kind, *a, (*a - *n).normalized(), size); + // DIMLDRBLK ("" = closed filled), or a user arrowhead block. + let g = named_arrow(ctx.d, st.map(|s| s.leader_arrow_block.as_str()).unwrap_or(""), *a, (*a - *n).normalized(), size); for l in &g.lines { b.polyline(ctx, rgb, lw, l); } @@ -1220,7 +1219,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { for pts in m.leader_paths() { b.polyline(ctx, rgb, lw, &pts); if let (Some(a), Some(n)) = (pts.first(), pts.get(1)) { - b.tris(ctx, rgb, &dim::arrow(*a, (*a - *n).normalized(), m.arrow_size)); + let g = named_arrow(ctx.d, m.arrow_in(ctx.d), *a, (*a - *n).normalized(), m.arrow_size); + for l in &g.lines { + b.polyline(ctx, rgb, lw, l); + } + b.tris(ctx, rgb, &g.tris); } } if let Some(t) = &m.text { @@ -1289,7 +1292,7 @@ fn text_style(d: &Drawing, name: &str) -> cadcraft_doc::TextStyle { /// Shape a TEXT / ATTRIB / ATTDEF with its style's font and generation flags. pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (cadcraft_fonts::Shaped, Bounds2) { let ts = text_style(d, &t.style); - let font = cadcraft_fonts::TextFont::resolve(&ts.font); + let font = cadcraft_fonts::TextFont::resolve_style(&ts.font, &ts.big_font); let (h, v) = align(t.halign, t.valign); let p = cadcraft_fonts::TextParams { insert: t.insert.xy(), @@ -1317,7 +1320,7 @@ pub fn layout_mtext_entity(d: &Drawing, t: &cadcraft_doc::MText) -> cadcraft_fon rotation: t.rotation, line_spacing: t.line_spacing, line_spacing_exact: t.line_spacing_exact, - font: cadcraft_fonts::TextFont::resolve(&ts.font), + font: cadcraft_fonts::TextFont::resolve_style(&ts.font, &ts.big_font), width_factor: ts.width_factor, oblique: ts.oblique, columns: t.columns.as_ref().map(|c| cadcraft_fonts::MTextColumnSpec { @@ -1354,7 +1357,153 @@ fn mtext(b: &mut Builder, ctx: &Ctx, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) /// The font settings of a dimension style's text style. pub fn dim_text(d: &Drawing, st: &cadcraft_doc::DimStyle) -> DimText { let ts = text_style(d, &st.text_style); - DimText { font: cadcraft_fonts::TextFont::resolve(&ts.font), fixed_height: ts.height, width_factor: ts.width_factor, oblique: ts.oblique } + let mut user_arrows: Vec<(String, ArrowGeom)> = Vec::new(); + for name in [&st.arrow_block, &st.arrow_block1, &st.arrow_block2] { + let n = name.trim(); + if n.is_empty() || user_arrows.iter().any(|(k, _)| k.eq_ignore_ascii_case(n)) { + continue; + } + if let Some(g) = user_arrow(d, n) { + user_arrows.push((n.to_string(), g)); + } + } + DimText { + font: cadcraft_fonts::TextFont::resolve_style(&ts.font, &ts.big_font), + fixed_height: ts.height, + width_factor: ts.width_factor, + oblique: ts.oblique, + user_arrows, + } +} + +/// The block a DIMBLK name refers to, if the drawing has one (names compare without case). +pub fn arrow_block<'a>(d: &'a Drawing, name: &str) -> Option<&'a cadcraft_doc::Block> { + let n = name.trim(); + if n.is_empty() { + return None; + } + d.blocks.get(n).or_else(|| d.blocks.iter().find(|(k, _)| k.eq_ignore_ascii_case(n)).map(|(_, b)| b)).map(|b| b.as_ref()) +} + +/// The arrowhead `name` names (a DIMBLK-style name, or a user arrowhead block of `d`) at `tip`, +/// pointing along `dir`, `size` long. +pub fn named_arrow(d: &Drawing, name: &str, tip: Vec2, dir: Vec2, size: f64) -> ArrowGeom { + let dir = if dir == Vec2::ZERO || !dir.is_finite() { Vec2::X } else { dir }; + match user_arrow(d, name.trim()) { + Some(g) => { + let size = if size.is_finite() { size.abs() } else { 0.0 }; + let n = dir.perp(); + let at = |p: &Vec2| tip + dir * (p.x * size) + n * (p.y * size); + ArrowGeom { lines: g.lines.iter().map(|l| l.iter().map(at).collect()).collect(), tris: g.tris.iter().map(at).collect() } + } + None => dim::arrowhead(dim::Arrowhead::parse(name), tip, dir, size), + } +} + +/// A user arrowhead: the block's lines, arcs, circles and polylines as strokes, its solids, +/// solid hatches and wide polylines as fills, relative to the block base (the arrow's tip, +/// the arrow pointing along +x at unit size). Built-in arrowhead blocks (`_Oblique`…) are +/// drawn in code instead, so they are left out. +fn user_arrow(d: &Drawing, name: &str) -> Option { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock, PoisonError}; + if name.starts_with('_') { + return None; + } + let b = arrow_block(d, name)?; + static CACHE: OnceLock>>> = OnceLock::new(); + let key = (b as *const cadcraft_doc::Block as usize, b.entities.len(), name.to_string()); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + if let Some(g) = cache.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return g.clone(); + } + let g = arrow_geometry(b); + let mut c = cache.lock().unwrap_or_else(PoisonError::into_inner); + if c.len() > 512 { + c.clear(); + } + c.insert(key, g.clone()); + g +} + +fn arrow_geometry(b: &cadcraft_doc::Block) -> Option { + use cadcraft_doc::EntityKind as K; + const SEGS: usize = 32; + let base = b.base.xy(); + let mut g = ArrowGeom::default(); + let arc_pts = |c: Vec2, r: f64, a0: f64, sweep: f64| -> Vec { + (0..=SEGS).map(|i| c - base + Vec2::from_angle(a0 + sweep * i as f64 / SEGS as f64) * r).collect() + }; + // A polyline's points, its arcs sampled. + let poly_pts = |vs: &[cadcraft_geom::PolyVertex], closed: bool| -> Vec { + let mut out = Vec::new(); + let n = vs.len(); + let segs = if closed { n } else { n.saturating_sub(1) }; + for i in 0..segs { + let (Some(a), Some(c)) = (vs.get(i), vs.get((i + 1) % n.max(1))) else { break }; + out.push(a.p - base); + if a.bulge.abs() > 1e-9 { + let theta = 4.0 * a.bulge.atan(); + let chord = c.p - a.p; + if chord.len() > 1e-12 { + // The centre sits off the chord's midpoint by (1 - b²) / 4b chords, to its left. + let center = a.p.mid(c.p) + chord.perp() * ((1.0 - a.bulge * a.bulge) / (4.0 * a.bulge)); + let r = (a.p - center).len(); + let a0 = (a.p - center).angle(); + for k in 1..SEGS { + out.push(center - base + Vec2::from_angle(a0 + theta * k as f64 / SEGS as f64) * r); + } + } + } + } + if let Some(last) = if closed { vs.first() } else { vs.last() } { + out.push(last.p - base); + } + out + }; + for e in b.entities.iter().take(512) { + match &e.kind { + K::Line(l) => g.lines.push(vec![l.a.xy() - base, l.b.xy() - base]), + K::Circle(c) => g.lines.push(arc_pts(c.center.xy(), c.radius, 0.0, std::f64::consts::TAU)), + K::Arc(a) => { + let sweep = cadcraft_geom::ccw_sweep(a.start, a.end); + g.lines.push(arc_pts(a.center.xy(), a.radius, a.start, sweep)); + } + K::LwPolyline(p) => { + let pts = poly_pts(&p.vertices, p.closed); + let w = p.const_width.max(p.vertices.iter().map(|v| v.start_width.max(v.end_width)).fold(0.0, f64::max)); + if w > 1e-12 { + // A wide polyline: each piece a filled band. + for s in pts.windows(2) { + let (a, c) = (s[0], s[1]); + let n = (c - a).perp().normalized() * (w / 2.0); + g.tris.extend([a - n, c - n, c + n, a - n, c + n, a + n]); + } + } else { + g.lines.push(pts); + } + } + K::Solid(s) | K::Trace(s) => { + let c: Vec = s.corners.iter().map(|p| p.xy() - base).collect(); + if let [a, b2, c2, d2] = c[..] { + g.tris.extend([a, b2, c2, b2, d2, c2]); + } + } + K::Hatch(h) if h.solid => { + for l in &h.loops { + let pts = poly_pts(&l.vertices, true); + if let Some((&first, rest)) = pts.split_first() { + for s in rest.windows(2) { + g.tris.extend([first, s[0], s[1]]); + } + } + } + } + _ => {} + } + } + let ok = g.lines.iter().flatten().chain(&g.tris).all(|p| p.is_finite()); + (ok && !(g.lines.is_empty() && g.tris.is_empty())).then_some(g) } /// Geometry of a dimension in a drawing: its style, overrides and text font. diff --git a/crates/render/src/linetype_text.rs b/crates/render/src/linetype_text.rs index a012f0df0d..13c90ba228 100644 --- a/crates/render/src/linetype_text.rs +++ b/crates/render/src/linetype_text.rs @@ -83,7 +83,7 @@ fn elements(d: &Drawing, lt: &Linetype, scale: f64) -> Vec { if !(height.is_finite() && height > 0.0) { continue; } - let font = TextFont::resolve(&ts.font); + let font = TextFont::resolve_style(&ts.font, &ts.big_font); let params = TextParams { width_factor: if ts.width_factor.is_finite() && ts.width_factor > 0.0 { ts.width_factor } else { 1.0 }, oblique: if ts.oblique.is_finite() { ts.oblique } else { 0.0 }, diff --git a/crates/render/src/paper.rs b/crates/render/src/paper.rs index aff4395c9a..cc083e2e8f 100644 --- a/crates/render/src/paper.rs +++ b/crates/render/src/paper.rs @@ -96,8 +96,14 @@ impl Sheet { pub fn bounds(&self) -> Bounds2 { Bounds2::new(Vec2::ZERO, self.size) } - /// The sheet for a page setup in a drawing whose paper units are `unit_mm` millimetres. + /// The sheet for a page setup in a drawing whose paper units are `unit_mm` millimetres (the + /// layout's own paper units, when it names them, win). pub fn from_page(page: &PageSetup, unit_mm: f64) -> Sheet { + let unit_mm = match page.mm_units { + Some(true) => 1.0, + Some(false) => 25.4, + None => unit_mm, + }; let sane = |v: f64, d: f64| if v.is_finite() && v > 0.0 { v.min(100_000.0) } else { d }; let w = sane(page.width_mm, 215.9); let h = sane(page.height_mm, 279.4); diff --git a/crates/render/src/table.rs b/crates/render/src/table.rs index b6a161aaf1..9c6fb7e3c5 100644 --- a/crates/render/src/table.rs +++ b/crates/render/src/table.rs @@ -353,7 +353,7 @@ pub(crate) fn draw(b: &mut Builder, ctx: &Ctx, t: &Table, rgb: Ink, lw: f32) { } for tx in &g.texts { let ts = crate::text_style(ctx.d, &tx.style); - let font = cadcraft_fonts::TextFont::resolve(&ts.font); + let font = cadcraft_fonts::TextFont::resolve_style(&ts.font, &ts.big_font); // Cell content is MTEXT (`\P`, `{\Q15;…}`, `\F…;`): laid out as such, at the cell's // alignment point (its numbering is MTEXT's attachment). let mp = cadcraft_fonts::MTextParams { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e5725e353a..2f72530016 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -47,6 +47,9 @@ fn same_content(a: &ListKey, b: &ListKey) -> bool { #[derive(Default)] pub struct CanvasState { pub list: Option, + /// The font set the list was drawn with ([`cadcraft_fonts::ttf::generation`]): a new font + /// folder redraws the text. + font_generation: u64, key: ListKey, /// The area `list` was built for (hatch patterns exist only inside it); a view leaving it /// rebuilds the list. @@ -106,6 +109,10 @@ pub struct CanvasState { grip_editing: bool, /// The grip whose menu (Stretch, Add Vertex, Lengthen…) a right-click opened. grip_menu: Option<(Handle, usize)>, + /// The grip with options under the resting cursor, and since when; its menu opens on hover. + grip_hover: Option<((Handle, usize), f64)>, + /// The grip whose menu opened on hover, and where the menu is. + grip_popup: Option<((Handle, usize), Pos2)>, /// Dynamic block grips of the selection (cached), the one being dragged, and the list grip /// whose choices are open (and whether it opened this frame). pub(crate) dyn_grips: crate::dyngrips::Cache, @@ -244,6 +251,12 @@ fn prim_color32(prim: &cadcraft_render::DPrim, bg: Rgb) -> Color32 { /// yet, is built at once. fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], ctx: &egui::Context) { let px = 1.0 / xf.scale; + let fonts = cadcraft_fonts::ttf::generation(); + if app.canvas.font_generation != fonts { + app.canvas.font_generation = fonts; + app.canvas.list = None; + app.canvas.job = None; + } let Ok(st) = app.session.state() else { return }; // Rebuild when the drawing changes, the zoom moves by more than 2x (tessellation band) or a // view leaves the area the list was built for. @@ -1366,6 +1379,12 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let pp = xf_paper.to_world(hp); let in_rect = |v: &cadcraft_doc::Viewport| (pp.x - v.center.x).abs() <= v.width / 2.0 && (pp.y - v.center.y).abs() <= v.height / 2.0; let in_active = active_vp.as_ref().is_some_and(|v| active_clip.as_ref().map_or(in_rect(v), |c| c.contains(pp))); + // On the sheet itself (no viewport active), a block, text or dimension drawn on the sheet + // is edited as in model space; elsewhere the click goes into a viewport. + let on_sheet = app.session.state().is_ok_and(|st| st.mspace.is_none()); + if on_sheet && app.session.running.is_none() && edit_text_at(app, pp) { + return; + } if !in_active { app.canvas.hot_grips.clear(); app.session.pending_window = None; @@ -1379,7 +1398,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { return; } } - // Double-click text to edit it, as in AutoCAD: TEXTEDIT with that object already picked. + // Double-click text, a dimension, a multileader or a table cell to edit it in place, as in + // AutoCAD: TEXTEDIT (TABLEDIT) with that object already picked. if inside && dbl_primary && app.session.running.is_none() @@ -1572,6 +1592,13 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } else if idle || app.canvas.snap_menu { crate::context_menu::show(app, &resp); } + // Resting the cursor on a grip with options opens its menu too, as in AutoCAD. + if idle && !app.canvas.snap_menu && app.canvas.grip_menu.is_none() { + hover_grip_menu(app, ui, &xf, hover_pos, inside); + } else { + app.canvas.grip_hover = None; + app.canvas.grip_popup = None; + } // Hover highlight (throttled to cursor movement). // The cursor picks objects (pick box, rollover highlight): "Select objects" and single-object @@ -1753,7 +1780,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let gs = app.session.settings.gripsize as f32; for h in sel.iter().take(200) { if let Some(e) = st.doc.entity(*h) { - for (gi, g) in e.kind.grips().into_iter().enumerate() { + for (gi, g) in cadcraft_engine::grips::grip_points(&st.doc, &e.kind).into_iter().enumerate() { let sp = xf.to_screen(g); if rect.contains(sp) { let r = Rect::from_center_size(sp, vec2(gs * 2.0, gs * 2.0)); @@ -1847,6 +1874,13 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if let Some(hp) = hover_pos { draw_crosshair(app, &painter, rect, hp, selecting); } + if !app.session.settings.dynmode + && !app.cmd.buffer.is_empty() + && let Some(hp) = hover_pos + { + // Dynamic Input off: what is typed still shows by the cursor. + echo_box(&painter, hp, None, &app.cmd.buffer, false); + } if app.session.settings.dynmode && let Some(hp) = hover_pos { @@ -1866,13 +1900,41 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { /// offers Edit Text for); false when there is none. fn edit_text_at(app: &mut CadApp, p: Vec2) -> bool { use cadcraft_engine::doc::EntityKind; - let is_text = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { - app.session.doc().ok()?.entity(h).map(|e| matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_))) + // A block reference: its attributes (Enhanced Attribute Editor), or the Block Editor for a + // block without them, as in AutoCAD. External references are left alone. + let block = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + let d = app.session.doc().ok()?; + let EntityKind::Insert(i) = &d.entity(h)?.kind else { return None }; + let xref = d.blocks.get(&i.block).is_some_and(|b| b.xref_path.is_some()); + (!xref).then(|| (h, i.attribs.iter().any(|a| !a.constant))) }); - if is_text != Some(true) { - return false; + if let Some((h, attributes)) = block { + if attributes { + app.start("attedit"); + if let Err(e) = app.session.input(Input::Pick(vec![h])) { + app.session.echo(e.to_string()); + } + } else if let Err(e) = app.run("bedit", serde_json::json!({ "handle": h.hex() })) { + app.session.echo(e); + } + return true; } - app.start("textedit"); + let picked = cadcraft_engine::cmd::curves::pick_at(&app.session, p).and_then(|h| { + app.session.doc().ok()?.entity(h).map(|e| match &e.kind { + EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_) => Some("textedit.object"), + EntityKind::MLeader(m) if m.text.is_some() => Some("textedit.object"), + EntityKind::Table(t) if t.cell_at_point(p).is_some() => Some("tabledit.cell"), + _ => None, + }) + }); + // Inside a table cell, away from its lines: the cell. + let command = picked.flatten().or_else(|| { + let d = app.session.doc().ok()?; + let space = d.space(&app.session.space())?; + space.iter().any(|e| matches!(&e.kind, EntityKind::Table(t) if t.cell_at_point(p).is_some())).then_some("tabledit.cell") + }); + let Some(command) = command else { return false }; + app.start(command); if let Err(e) = app.session.input(Input::Point(p)) { app.session.echo(e.to_string()); } @@ -2029,7 +2091,13 @@ fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2) { hover } }; - let Some(prompt) = app.session.current_prompt() else { return }; + let Some(prompt) = app.session.current_prompt() else { + // At "Command:": the command name being typed. + if !app.cmd.buffer.is_empty() { + echo_box(p, at, None, &app.cmd.buffer, false); + } + return; + }; // DYNPROMPT = 0: no prompt beside the cursor (the value boxes stay). let show_prompt = app.session.settings.dynprompt; let options = show_prompt && !prompt.keywords.is_empty(); @@ -2042,13 +2110,18 @@ fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2) { options_menu(app, p, r, hover); return; } + // Text typed at a prompt (a number of sides, a name, an option) shows in a box by the cursor, + // so the eyes needn't go to the command line and back. + if !app.cmd.buffer.is_empty() { + let r = echo_box(p, at, show_prompt.then(|| crate::i18n::t(&prompt.message)), &app.cmd.buffer, options); + options_menu(app, p, r, hover); + return; + } if !show_prompt { return; } let mut text = crate::i18n::t(&prompt.message).to_string(); - if !app.cmd.buffer.is_empty() { - text = format!("{}: {}", crate::i18n::t(&prompt.message), app.cmd.buffer); - } else if let (Some(base), Some(c)) = (prompt.base, app.canvas.cursor) { + if let (Some(base), Some(c)) = (prompt.base, app.canvas.cursor) { text = format!( "{} {} < {}°", crate::i18n::t(&prompt.message), @@ -2069,6 +2142,33 @@ fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2) { options_menu(app, p, r, hover); } +/// The text being typed at the command line, in an input box beside the cursor, after the prompt +/// (`message`) when there is one; returns the tooltip's rectangle. +fn echo_box(p: &egui::Painter, at: Pos2, message: Option<&str>, typed: &str, options: bool) -> Rect { + let t = Tokens::get(); + let label = message.map(|m| p.layout_no_wrap(format!("{m}:"), crate::theme::small(), t.text_dim)); + let value = p.layout_no_wrap(typed.to_string(), crate::theme::body(), t.text); + let box_size = vec2((value.size().x + 14.0).max(48.0), value.size().y + 6.0); + let label_w = label.as_ref().map_or(0.0, |g| g.size().x + 8.0); + let hint = if options { OPTIONS_HINT_W } else { 0.0 }; + let r = tooltip_frame(p, at, vec2(label_w + box_size.x + 10.0 + hint, box_size.y + 8.0)); + if let Some(g) = label { + let y = r.center().y - g.size().y / 2.0; + p.galley(pos2(r.left() + 6.0, y), g, t.text_dim); + } + let b = Rect::from_min_size(pos2(r.left() + 5.0 + label_w, r.top() + 4.0), box_size); + p.rect_filled(b, 2.0, t.field); + p.rect_stroke(b, 2.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + let text_at = pos2(b.left() + 5.0, b.center().y - value.size().y / 2.0); + let caret_x = text_at.x + value.size().x + 1.0; + p.galley(text_at, value, t.text); + p.line_segment([pos2(caret_x, b.top() + 3.0), pos2(caret_x, b.bottom() - 3.0)], Stroke::new(1.0, t.text)); + if options { + options_hint(p, r); + } + r +} + /// The drawing's length units: (LUNITS, LUPREC). pub(crate) fn length_units(session: &cadcraft_engine::Session) -> (i64, i64) { session.doc().map(|d| (d.header.i64("LUNITS", 2), d.header.i64("LUPREC", 4))).unwrap_or((2, 4)) @@ -2328,6 +2428,77 @@ fn grip_menu(app: &mut CadApp, resp: &egui::Response) { app.canvas.grip_menu = None; } let Some(choice) = chosen else { return }; + apply_grip_choice(app, g, choice); +} + +/// Seconds the cursor rests on a grip before its menu opens. +const GRIP_HOVER_DELAY: f64 = 0.4; + +/// The grip menu that opens when the cursor rests on a grip with options (a dimension's text +/// grip, a polyline vertex…); it closes when the cursor leaves the grip and the menu. +fn hover_grip_menu(app: &mut CadApp, ui: &egui::Ui, xf: &Xf, hover: Option, inside: bool) { + let ctx = ui.ctx().clone(); + let now = ctx.input(|i| i.time); + let busy = ctx.input(|i| i.pointer.any_down()) || ctx.dragged_id().is_some(); + let over = if inside && !busy { grip_at(app, xf, hover).filter(|g| !grip_options(app, *g).is_empty()) } else { None }; + if let Some((g, at)) = app.canvas.grip_popup { + let options = grip_options(app, g); + if options.is_empty() { + app.canvas.grip_popup = None; + return; + } + let mut chosen: Option> = None; + let area = egui::Area::new(egui::Id::new("cc_grip_hover_menu")).order(egui::Order::Foreground).fixed_pos(at).show(&ctx, |ui| { + egui::Frame::menu(ui.style()).show(ui, |ui| { + ui.set_min_width(170.0); + // Menu items: the whole row lights up, no button frames. + ui.with_layout(egui::Layout::top_down_justified(egui::Align::LEFT), |ui| { + ui.spacing_mut().button_padding = vec2(8.0, 4.0); + let item = |ui: &mut egui::Ui, label: &str| ui.add(egui::Button::new(crate::i18n::t(label)).frame_when_inactive(false)).clicked(); + let vertex = options.contains(&cadcraft_engine::grips::GripAction::RemoveVertex); + if item(ui, if vertex { "Stretch Vertex" } else { "Stretch" }) { + chosen = Some(None); + } + for a in &options { + if item(ui, a.label()) { + chosen = Some(Some(*a)); + } + } + }); + }); + }); + let on_menu = ctx.pointer_latest_pos().is_some_and(|p| area.response.rect.expand(8.0).contains(p)); + if let Some(choice) = chosen { + app.canvas.grip_popup = None; + app.canvas.grip_hover = None; + apply_grip_choice(app, g, choice); + } else if !on_menu && over != Some(g) { + app.canvas.grip_popup = None; + app.canvas.grip_hover = over.map(|g| (g, now)); + } + return; + } + match (over, app.canvas.grip_hover) { + (Some(g), Some((h, since))) if h == g => { + if now - since >= GRIP_HOVER_DELAY { + let point = app.session.grips_of(g.0).ok().and_then(|p| p.get(g.1).copied()); + if let Some(p) = point { + app.canvas.grip_popup = Some((g, xf.to_screen(p) + vec2(10.0, 10.0))); + } + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(GRIP_HOVER_DELAY - (now - since) + 0.01)); + } + } + (Some(g), _) => { + app.canvas.grip_hover = Some((g, now)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(GRIP_HOVER_DELAY + 0.01)); + } + (None, _) => app.canvas.grip_hover = None, + } +} + +/// Run a grip menu choice: Stretch (`None`) or an option, on grip `g` made hot. +fn apply_grip_choice(app: &mut CadApp, g: (Handle, usize), choice: Option) { app.canvas.hot_grips = vec![g]; let r = app.session.start_grip_edit(&[g]).and_then(|()| match choice { Some(a) => app.session.input(Input::Keyword(a.keyword().to_string())), @@ -2353,7 +2524,7 @@ fn grip_at(app: &CadApp, xf: &Xf, hover: Option) -> Option<(Handle, usize) if st.doc.layer(&e.common.layer).is_some_and(|l| l.locked) { continue; } - for (i, g) in e.kind.grips().into_iter().enumerate() { + for (i, g) in cadcraft_engine::grips::grip_points(&st.doc, &e.kind).into_iter().enumerate() { let sp = xf.to_screen(g); if (sp.x - hp.x).abs() <= gs && (sp.y - hp.y).abs() <= gs { return Some((*h, i)); @@ -2627,6 +2798,51 @@ mod hatch_pick_tests { assert_eq!(super::hatch_at(&app, Vec2::new(60.0, 60.0), 10.0), None); } + #[test] + fn double_clicking_text_dimensions_and_table_cells_opens_the_in_place_editor() { + let mut app = CadApp::new(Session::new(), Services::default()); + // The text sits away from the drawing area's top-left corner (the viewport label). + app.session.execute("line", &json!({ "points": [[-10, 20], [-9, 20]] })).unwrap(); + app.session.execute("mtext", &json!({ "at": [0, 10], "text": "hello world", "height": 1.0 })).unwrap(); + app.session.execute("table", &json!({ "at": [20, 10], "rows": 2, "cols": 2, "colWidth": 6, "rowHeight": 2 })).unwrap(); + let _ = app.session.zoom_extents(); + let ctx = egui::Context::default(); + let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))); + let mut time = 0.0; + let mut frame = |app: &mut CadApp, events: Vec| { + time += 0.1; + app.logic(&ctx); + let input = egui::RawInput { screen_rect: screen, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.ui(ui)); + out.textures_delta.clear(); + }; + let mut double_click = |app: &mut CadApp, world: Vec2| { + // Far enough from any earlier click not to count as its second or third. + for _ in 0..10 { + frame(app, Vec::new()); + } + let at = app.canvas.xf.unwrap().to_screen(world); + let button = |pressed| egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::default(), + }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true), button(false)]); + frame(app, vec![button(true), button(false)]); + frame(app, Vec::new()); + }; + double_click(&mut app, Vec2::new(1.0, 9.6)); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("textedit.object")); + assert!(matches!(app.session.text_editor().map(|e| e.kind), Some(cadcraft_engine::EditorKind::MText))); + app.session.cancel(); + app.session.set_selection(Vec::new()); + double_click(&mut app, Vec2::new(23.0, 7.0)); + assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("tabledit.cell")); + assert!(matches!(app.session.text_editor().map(|e| e.kind), Some(cadcraft_engine::EditorKind::TableCell { .. }))); + } + #[test] fn double_clicking_a_hatch_opens_the_hatch_edit_dialog() { let mut app = CadApp::new(Session::new(), Services::default()); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 3e0860e31f..6936626fdb 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -9,37 +9,6 @@ use crate::theme::Tokens; pub mod annoscale; -const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[ - &[ - (Icon::New, "new", "New Drawing", Some("Cmd+N")), - (Icon::Open, "open", "Open", Some("Cmd+O")), - (Icon::Save, "qsave", "Save", Some("Cmd+S")), - (Icon::SaveAs, "saveas", "Save As", None), - ], - &[(Icon::Undo, "u", "Undo", Some("Cmd+Z")), (Icon::Redo, "redo", "Redo", Some("Cmd+Shift+Z"))], - &[ - (Icon::Plot, "plot", "Print", None), - (Icon::Publish, "publish", "Batch Publish", None), - (Icon::PageSetup, "pagesetup", "Page Setup Manager", None), - (Icon::Preview, "preview", "Plot Preview", None), - ], - &[ - (Icon::Import, "import", "Import", None), - (Icon::Export, "export", "Export", None), - (Icon::Attach, "attach", "Attach", None), - (Icon::Share, "share", "Share", None), - ], - &[(Icon::ZoomWindow, "zoom.window", "Zoom Window", None), (Icon::Pan, "pan", "Pan", None), (Icon::Orbit, "3dorbit", "Orbit", None)], - &[ - (Icon::ZoomExtents, "zoom.extents", "Zoom Extents", None), - (Icon::Properties, "ui.toggle.palettes", "Properties", None), - (Icon::Layers, "ui.dialog.layers", "Layer Properties Manager", None), - (Icon::Blocks, "ui.dialog.blocks", "Blocks", None), - ], - &[(Icon::Measure, "dist", "Measure Distance", None), (Icon::List, "list", "List", None), (Icon::Area, "area", "Area", None)], - &[(Icon::Help, "ui.dialog.about", "Help", None)], -]; - /// Height of the macOS integrated title row (#161). AppKit draws the traffic lights itself, /// centred in the standard 28 pt title-bar band at the top of the window; moving them would take /// AppKit calls (`unsafe`, which the workspace forbids). So the title row is that band, and what @@ -65,17 +34,20 @@ fn title_left(left: f32, width: f32, text_w: f32) -> f32 { pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); let title_h = if app.integrated_titlebar { MAC_TITLE_BAR } else { 0.0 }; - let tb_h = if app.ui.show_toolbar { 34.0 } else { 0.0 }; + let tb_h = if app.ui.show_toolbar && app.ui.toolbar_dock == crate::toolbar::Dock::Top { crate::toolbar::THICKNESS } else { 0.0 }; egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| { let r = ui.max_rect(); if title_h > 0.0 { let title = match app.session.state() { - Ok(st) if !app.ui.start_tab => format!("CADCraft {}{}", st.title, if st.title.contains('.') { "" } else { ".dwg" }), + Ok(st) if !app.ui.start_tab => { + let name = format!("{}{}", st.title, if st.title.contains('.') { "" } else { ".dwg" }); + format!("CADCraft {name}") + } _ => format!("CADCraft {}", crate::tl!("Start")), }; // Centred on the traffic lights' centre line (the row's middle): with the system font // the capitals' middle is the text box's middle, so no optical nudge. - let galley = ui.painter().layout_no_wrap(title, egui::FontId::proportional(13.0), t.text_dim); + let galley = ui.painter().layout_job(crate::i18n::job(&title, egui::FontId::proportional(13.0), t.text_dim)); let x = title_left(r.left(), r.width(), galley.size().x); ui.painter().galley(pos2(x, r.top() + (title_h - galley.size().y) / 2.0), galley, t.text_dim); // Allow dragging the window by the title row. @@ -91,85 +63,8 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) { } if tb_h > 0.0 { let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h)); - let mut x = r.left() + if app.integrated_titlebar { 120.0 } else { 12.0 }; - let size = 26.0; - let mut clicked = None; - let mac = ui.ctx().os().is_mac(); - let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect(); - let available = (row.right() - 12.0 - x).max(0.0); - let Some(fit) = craft_ui::layout::fit_toolbar(&widths, available, 24.0, 30.0) else { - // Very small windows still expose the complete command row by scrolling. - ui.scope_builder(egui::UiBuilder::new().max_rect(row.shrink2(vec2(4.0, 0.0))), |ui| { - egui::ScrollArea::horizontal().id_salt("toolbar_small").show(ui, |ui| { - ui.horizontal(|ui| { - for group in TOOLBAR { - for (icon, cmd, tip, _) in *group { - if icons::button(ui, *icon, size, tip, false).clicked() { - clicked = Some(*cmd); - } - } - ui.add_space(18.0); - } - }); - }); - }); - if let Some(command) = clicked { - app.start(command); - } - return; - }; - for (index, _) in &fit.shown { - let Some(group) = TOOLBAR.get(*index) else { continue }; - for (icon, cmd, label, shortcut) in group.iter() { - let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(size, size)); - let resp = ui.interact(br, ui.id().with(("tb", *cmd)), Sense::click()); - if resp.hovered() { - ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6)); - } - icons::paint(ui.painter(), br.shrink(4.0), *icon, false); - let tip = match shortcut { - Some(sc) => format!("{} ({})", crate::i18n::t(label), crate::menus::shortcut_label(sc, mac)), - None => crate::i18n::t(label).to_string(), - }; - icons::describe_control(ui, &resp, &tip, None, false); - if resp.on_hover_text(tip).clicked() { - clicked = Some(*cmd); - } - x += size + 6.0; - } - x += 18.0; - } - if !fit.overflow.is_empty() { - let br = Rect::from_min_size(pos2(x, row.center().y - size / 2.0), vec2(fit.overflow_width, size)); - let response = ui.interact(br, ui.id().with("toolbar_more"), Sense::click()); - if response.hovered() { - ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6)); - } - for offset in [-5.0, 0.0, 5.0] { - ui.painter().circle_filled(br.center() + vec2(offset, 0.0), 1.5, t.text); - } - icons::describe_control(ui, &response, "More toolbar commands", None, false); - egui::Popup::menu(&response).show(|ui| { - for (position, index) in fit.overflow.iter().enumerate() { - let Some(group) = TOOLBAR.get(*index) else { continue }; - if position > 0 { - ui.separator(); - } - for (_, command, label, _) in *group { - let response = ui.button(crate::i18n::t(label)); - crate::control::record_widget(ui, &response, label, "button", None); - if response.clicked() { - clicked = Some(*command); - ui.close(); - } - } - } - }); - response.on_hover_text(crate::tl!("More toolbar commands")); - } - if let Some(c) = clicked { - app.start(c); - } + let left = r.left() + if app.integrated_titlebar { 120.0 } else { 12.0 }; + crate::toolbar::top(app, ui, Rect::from_min_max(pos2(left, row.top()), row.max)); } }); } @@ -266,7 +161,7 @@ pub fn file_tabs(app: &mut CadApp, ui: &mut egui::Ui) { /// `text` laid out on one line no wider than `max_width`, ending in "…" when it had to be cut; /// and whether it was. fn elided(p: &egui::Painter, text: &str, font: egui::FontId, color: egui::Color32, max_width: f32) -> (std::sync::Arc, bool) { - let mut job = egui::text::LayoutJob::simple_singleline(text.to_string(), font, color); + let mut job = crate::i18n::job(text, font, color); job.wrap = egui::text::TextWrapping { max_width: max_width.max(0.0), max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; let galley = p.layout_job(job); let cut = galley.elided; @@ -527,7 +422,7 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { p.text( pos2(left.left() + 34.0, left.top() + 98.0), egui::Align2::LEFT_CENTER, - crate::tf!("Version {version}", version = env!("CARGO_PKG_VERSION")), + crate::tf!("Version {version}", version = crate::VERSION), crate::theme::small(), t.text_faint, ); @@ -555,9 +450,21 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { } let dir = std::path::Path::new(path).parent().map(|d| d.display().to_string()).unwrap_or_default(); let clip = p.with_clip_rect(row.shrink(2.0)); - clip.text(pos2(row.left() + 10.0, row.top() + 13.0), egui::Align2::LEFT_CENTER, crate::menus::file_name(path), crate::theme::body(), t.text); - clip.text(pos2(row.left() + 10.0, row.top() + 30.0), egui::Align2::LEFT_CENTER, dir, crate::theme::small(), t.text_faint); - if resp.on_hover_text(path).clicked() { + crate::i18n::paint( + &clip, + pos2(row.left() + 10.0, row.top() + 13.0), + egui::Align2::LEFT_CENTER, + &crate::menus::file_name(path), + crate::theme::body(), + t.text, + ); + crate::i18n::paint(&clip, pos2(row.left() + 10.0, row.top() + 30.0), egui::Align2::LEFT_CENTER, &dir, crate::theme::small(), t.text_faint); + if resp + .on_hover_ui(|ui| { + ui.label(crate::i18n::widget(ui, path, egui::TextStyle::Body)); + }) + .clicked() + { recent = Some(path.clone()); } y += 46.0; diff --git a/crates/ui-egui/src/closing.rs b/crates/ui-egui/src/closing.rs index d03fafa4b1..877d285cf7 100644 --- a/crates/ui-egui/src/closing.rs +++ b/crates/ui-egui/src/closing.rs @@ -208,7 +208,7 @@ pub fn prompt(app: &mut CadApp, ctx: &egui::Context) { ui.set_width(360.0); ui.label(RichText::new("CADCraft").strong()); ui.add_space(4.0); - ui.label(format!("Save changes to {title}?")); + ui.label(crate::i18n::widget(ui, &format!("Save changes to {title}?"), egui::TextStyle::Body)); ui.label(RichText::new("Your changes will be lost if you don't save them.").color(t.text_dim)); ui.add_space(10.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/src/custom_patterns.rs b/crates/ui-egui/src/custom_patterns.rs new file mode 100644 index 0000000000..cb55ecb4dc --- /dev/null +++ b/crates/ui-egui/src/custom_patterns.rs @@ -0,0 +1,209 @@ +//! The Hatch and Gradient dialog's Custom Patterns tab: the hatch patterns of the `.pat` files in +//! a folder the user names, listed with a preview of the one selected. +//! +//! The folder is read when it changes or on Reload, not every frame. A pattern used for a hatch is +//! loaded into the session's pattern list from its file when OK is pressed (HATCH.PATTERNS), so +//! the hatch keeps its line families like any pattern loaded from a file. + +use std::cell::RefCell; + +use cadcraft_doc::library::PatternLine; +use cadcraft_doc::library::files::parse_pat; +use egui::{Rect, Sense, Stroke, pos2, vec2}; + +use crate::theme::Tokens; + +/// Most `.pat` files read from the folder, and most patterns listed. +const MAX_FILES: usize = 500; +const MAX_PATTERNS: usize = 5000; +/// Largest `.pat` file read. +const MAX_FILE_BYTES: u64 = 4 << 20; + +/// A pattern found in the folder. +#[derive(Clone, Debug, PartialEq)] +pub struct Found { + /// The `.pat` file it is in. + pub file: String, + pub name: String, + pub description: String, + pub lines: Vec, +} + +/// What the folder held when last read. +#[derive(Clone, Debug, Default)] +struct Listing { + folder: String, + generation: u64, + patterns: Vec, + problem: Option, +} + +thread_local! { + static LISTING: RefCell

= RefCell::new(Listing { generation: u64::MAX, ..Listing::default() }); + static GENERATION: RefCell = const { RefCell::new(0) }; +} + +/// Read the folder again on the next frame (files were added or changed). +pub fn reload() { + GENERATION.with(|g| *g.borrow_mut() += 1); +} + +/// The patterns of every `.pat` file in `folder` (not its subfolders), by file then name. +pub fn scan(folder: &str) -> (Vec, Option) { + let dir = folder.trim(); + if dir.is_empty() { + return (Vec::new(), None); + } + let Ok(rd) = std::fs::read_dir(dir) else { + return (Vec::new(), Some(crate::tl!("This folder does not exist").to_string())); + }; + let mut files: Vec = rd + .flatten() + .map(|e| e.path()) + .filter(|p| p.is_file() && p.extension().is_some_and(|x| x.eq_ignore_ascii_case("pat"))) + .take(MAX_FILES) + .collect(); + files.sort(); + let mut out = Vec::new(); + for path in files { + if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(u64::MAX) > MAX_FILE_BYTES { + continue; + } + let Ok(bytes) = std::fs::read(&path) else { continue }; + // Pattern files are ASCII, often written in a Windows code page: decode leniently. + let text = String::from_utf8_lossy(&bytes); + for p in parse_pat(&text).items { + if out.len() >= MAX_PATTERNS { + break; + } + out.push(Found { file: path.to_string_lossy().to_string(), name: p.name, description: p.description, lines: p.lines }); + } + } + let problem = out.is_empty().then(|| crate::tl!("No hatch patterns (.pat files) in this folder").to_string()); + (out, problem) +} + +/// The folder's patterns, read again when the folder or the reload count changed. +fn listing(folder: &str) -> (Vec, Option) { + let generation = GENERATION.with(|g| *g.borrow()); + LISTING.with(|cell| { + let mut l = cell.borrow_mut(); + if l.folder != folder || l.generation != generation { + let (patterns, problem) = scan(folder); + *l = Listing { folder: folder.to_string(), generation, patterns, problem }; + } + (l.patterns.clone(), l.problem.clone()) + }) +} + +/// Draw a pattern's preview in `r`: its lines over a few repeats, or "SOLID" filled. +pub fn preview(p: &egui::Painter, r: Rect, lines: &[PatternLine]) { + let t = Tokens::get(); + p.rect_filled(r, 3.0, t.field); + let inner = r.shrink(4.0); + let runs = cadcraft_engine::render::pattern_swatch(lines, 1.0); + let at = |v: &cadcraft_engine::geom::Vec2| pos2(inner.min.x + v.x as f32 * inner.width(), inner.max.y - v.y as f32 * inner.height()); + let clip = p.with_clip_rect(inner); + for run in &runs { + match run.as_slice() { + [] => {} + [dot] => { + clip.circle_filled(at(dot), 0.9, t.text); + } + pts => { + clip.add(egui::Shape::line(pts.iter().map(at).collect(), Stroke::new(1.0, t.text))); + } + } + } + p.rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); +} + +/// What the tab asks the dialog to do. +pub enum TabAction { + None, + /// Pick the folder with the system's folder dialog. + Browse, +} + +/// The tab: the folder, the list of its patterns and the preview of the chosen one. A click sets +/// `pattern` and `file`. +pub fn tab_ui(ui: &mut egui::Ui, folder: &mut String, pattern: &mut String, file: &mut Option, can_browse: bool) -> TabAction { + let mut action = TabAction::None; + ui.label(crate::tl!("Folder with hatch pattern files (.pat):")); + ui.horizontal(|ui| { + let w = ui.available_width() - if can_browse { 150.0 } else { 70.0 }; + ui.add(egui::TextEdit::singleline(folder).desired_width(w.max(120.0)).hint_text(crate::tl!("Folder path"))); + if can_browse && ui.button(crate::tl!("Browse...")).clicked() { + action = TabAction::Browse; + } + if ui.button(crate::tl!("Reload")).on_hover_text(crate::tl!("Read the folder again")).clicked() { + reload(); + } + }); + let (found, problem) = listing(folder); + if let Some(p) = &problem { + ui.colored_label(Tokens::get().text_dim, p); + } + ui.add_space(4.0); + let selected = found.iter().find(|f| f.name.eq_ignore_ascii_case(pattern) && file.as_deref() == Some(f.file.as_str())); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(190.0); + egui::Frame::NONE.stroke(Stroke::new(1.0, Tokens::get().border)).inner_margin(2.0).show(ui, |ui| { + egui::ScrollArea::vertical() + .id_salt("custom_patterns_list") + .auto_shrink([false, false]) + .max_height(200.0) + .min_scrolled_height(200.0) + .show(ui, |ui| { + ui.set_width(182.0); + for f in &found { + let on = selected.is_some_and(|s| s.name == f.name && s.file == f.file); + let tip = if f.description.is_empty() { f.file.clone() } else { format!("{}\n{}", f.description, f.file) }; + if ui.selectable_label(on, &f.name).on_hover_text(tip).clicked() { + *pattern = f.name.clone(); + *file = Some(f.file.clone()); + } + } + }); + }); + }); + ui.vertical(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(170.0, 170.0), Sense::hover()); + match selected { + Some(f) => { + preview(ui.painter(), r, &f.lines); + ui.label(egui::RichText::new(&f.name).strong()); + if !f.description.is_empty() { + ui.add(egui::Label::new(egui::RichText::new(&f.description).small()).wrap()); + } + } + None => { + let t = Tokens::get(); + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("Preview"), crate::theme::small(), t.text_faint); + } + } + }); + }); + action +} + +#[cfg(test)] +mod tests { + #[test] + fn a_folder_of_pat_files_lists_their_patterns() { + let dir = std::env::temp_dir().join(format!("cadcraft-custom-pat-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("mine.pat"), "*MYLINES, my lines\n0, 0,0, 0,1\n*MYGRID, grid\n0, 0,0, 0,1\n90, 0,0, 0,1\n").unwrap(); + std::fs::write(dir.join("notes.txt"), "not a pattern").unwrap(); + let (found, problem) = super::scan(&dir.to_string_lossy()); + assert!(problem.is_none()); + let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["MYLINES", "MYGRID"]); + assert_eq!(found.get(1).map(|f| f.lines.len()), Some(2)); + let (none, problem) = super::scan(&dir.join("missing").to_string_lossy()); + assert!(none.is_empty() && problem.is_some()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 914de61729..15faadaf16 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -23,6 +23,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "units" => units(app, ctx, &mut open), "hatch" => crate::hatchdlg::dialog(app, ctx, &mut open), "about" => about(ctx, &mut open), + o if o == "toolbar" || o.starts_with("toolbar:") => crate::toolbar::dialog(app, ctx, o, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), "blocks" => blocks(app, ctx, &mut open), @@ -321,7 +322,7 @@ fn about(ctx: &egui::Context, open: &mut bool) { 2 => crate::credits::models_ui(ui), _ => { ui.heading(crate::tl!("CADCraft")); - ui.label(crate::tf!("Version {version}", version = env!("CARGO_PKG_VERSION"))); + ui.label(crate::tf!("Version {version}", version = crate::VERSION)); ui.label(crate::tl!("Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust.")); ui.add_space(6.0); ui.label(RichText::new(crate::tl!("One of the Crafting Apps by the ArtCraft team and community.")).color(t.text_dim)); diff --git a/crates/ui-egui/src/dimstyles.rs b/crates/ui-egui/src/dimstyles.rs new file mode 100644 index 0000000000..0a19d510ad --- /dev/null +++ b/crates/ui-egui/src/dimstyles.rs @@ -0,0 +1,1247 @@ +//! The Dimension Style Manager (DIMSTYLE, Format ▸ Dimension Style...) and its style editor. +//! +//! The manager lists the drawing's dimension styles with a preview of the selected one and +//! Set Current, New..., Modify..., Override... and Compare.... The editor (New, Modify, Override) +//! shows the style's settings on seven tabs — Lines, Symbols and Arrows, Text, Fit, Primary Units, +//! Alternate Units, Tolerances — with a live preview, and changes nothing until OK: +//! Modify and New run DIMSTYLE with every setting, Override sets the changed DIM* variables +//! (SETVAR), the overrides new dimensions take on. +//! +//! The settings are edited as the style's JSON form (the [`DimStyle`] field names), so the same +//! rows serve the editor and the Properties palette ([`field_row`]). + +use std::cell::RefCell; +use std::collections::HashMap; + +use cadcraft_doc::DimStyle; +use cadcraft_render::DisplayList; +use egui::{Color32, RichText, Sense, Stroke, vec2}; +use serde_json::{Map, Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The arrowheads, as DIMBLK names and their labels. +pub const ARROWS: &[(&str, &str)] = &[ + ("", "Closed filled"), + ("_CLOSEDBLANK", "Closed blank"), + ("_CLOSED", "Closed"), + ("_DOT", "Dot"), + ("_ARCHTICK", "Architectural tick"), + ("_OBLIQUE", "Oblique"), + ("_OPEN", "Open"), + ("_ORIGIN", "Origin indicator"), + ("_ORIGIN2", "Origin indicator 2"), + ("_OPEN90", "Right angle"), + ("_OPEN30", "Open 30"), + ("_DOTSMALL", "Dot small"), + ("_DOTBLANK", "Dot blank"), + ("_SMALL", "Dot small blank"), + ("_BOXBLANK", "Box"), + ("_BOXFILLED", "Box filled"), + ("_DATUMBLANK", "Datum triangle"), + ("_DATUMFILLED", "Datum triangle filled"), + ("_INTEGRAL", "Integral"), + ("_NONE", "None"), +]; + +const LINEAR_UNITS: &[(i64, &str)] = + &[(1, "Scientific"), (2, "Decimal"), (3, "Engineering"), (4, "Architectural"), (5, "Fractional"), (6, "Windows Desktop")]; +const ALT_UNITS: &[(i64, &str)] = &[ + (1, "Scientific"), + (2, "Decimal"), + (3, "Engineering"), + (4, "Architectural Stacked"), + (5, "Fractional Stacked"), + (6, "Architectural"), + (7, "Fractional"), + (8, "Windows Desktop"), +]; +const ANGULAR_UNITS: &[(i64, &str)] = &[(0, "Decimal Degrees"), (1, "Degrees Minutes Seconds"), (2, "Gradians"), (3, "Radians")]; +const FRACTIONS: &[(i64, &str)] = &[(0, "Horizontal"), (1, "Diagonal"), (2, "Not Stacked")]; +const TEXT_VERTICAL: &[(i64, &str)] = &[(0, "Centered"), (1, "Above"), (2, "Outside"), (3, "JIS"), (4, "Below")]; +const TEXT_HORIZONTAL: &[(i64, &str)] = + &[(0, "Centered"), (1, "At Ext Line 1"), (2, "At Ext Line 2"), (3, "Over Ext Line 1"), (4, "Over Ext Line 2")]; +const FIT: &[(i64, &str)] = &[(3, "Either text or arrows (best fit)"), (1, "Arrows"), (2, "Text"), (0, "Both text and arrows")]; +const TEXT_MOVE: &[(i64, &str)] = + &[(0, "Beside the dimension line"), (1, "Over dimension line, with leader"), (2, "Over dimension line, without leader")]; +const TOL_JUST: &[(i64, &str)] = &[(0, "Bottom"), (1, "Middle"), (2, "Top")]; +const ARC_SYMBOL: &[(i64, &str)] = &[(0, "Preceding dimension text"), (1, "Above dimension text"), (2, "None")]; +const SEPARATORS: &[(&str, &str)] = &[(".", "'.' (Period)"), (",", "',' (Comma)"), (" ", "' ' (Space)")]; + +/// How one setting is edited. +#[derive(Clone, Copy)] +pub enum Kind { + /// A length or factor. + Num(&'static str), + /// A choice among numbered options. + Choice(&'static str, &'static [(i64, &'static str)]), + /// Decimal places, 0–8. + Precision(&'static str), + Bool(&'static str), + /// One bit of a bit code (zero suppression). + Bit(&'static str, u64), + Color(&'static str), + /// An arrowhead; the first one also sets DIMBLK. + Arrow(&'static str), + Lineweight(&'static str), + Linetype(&'static str), + TextStyle(&'static str), + /// The text before or after the placeholder (`<>`, or `[]` for alternate units) of a + /// prefix/suffix template. + Prefix(&'static str, &'static str), + Suffix(&'static str, &'static str), + Separator(&'static str), + /// Tolerance display: None, Symmetrical, Deviation, Limits, Basic. + TolMethod, + /// Text alignment: Horizontal, Aligned with dimension line, ISO standard. + TextAlign, + /// The frame around the text (DIMGAP negative). + Frame, + /// The offset from the dimension line (DIMGAP's size, keeping the frame). + Gap, + /// Center marks: None, Mark, Line, and the size. + CenterType, + CenterSize, +} + +/// A labelled setting. +pub type Row = (&'static str, Kind); + +/// The editor's tabs and their groups of settings. +pub const TABS: &[(&str, &[(&str, &[Row])])] = &[ + ( + "Lines", + &[ + ( + "Dimension lines", + &[ + ("Color", Kind::Color("dimLineColor")), + ("Linetype", Kind::Linetype("dimLinetype")), + ("Lineweight", Kind::Lineweight("dimLineweight")), + ("Extend beyond ticks", Kind::Num("dimLineExtend")), + ("Baseline spacing", Kind::Num("baselineSpacing")), + ("Suppress dim line 1", Kind::Bool("suppressDim1")), + ("Suppress dim line 2", Kind::Bool("suppressDim2")), + ], + ), + ( + "Extension lines", + &[ + ("Color", Kind::Color("extLineColor")), + ("Linetype ext line 1", Kind::Linetype("extLinetype1")), + ("Linetype ext line 2", Kind::Linetype("extLinetype2")), + ("Lineweight", Kind::Lineweight("extLineweight")), + ("Suppress ext line 1", Kind::Bool("suppressExt1")), + ("Suppress ext line 2", Kind::Bool("suppressExt2")), + ("Extend beyond dim lines", Kind::Num("extExtend")), + ("Offset from origin", Kind::Num("extOffset")), + ("Fixed length extension lines", Kind::Bool("fixedExt")), + ("Length", Kind::Num("fixedExtLength")), + ], + ), + ], + ), + ( + "Symbols and Arrows", + &[ + ( + "Arrowheads", + &[ + ("First", Kind::Arrow("arrowBlock1")), + ("Second", Kind::Arrow("arrowBlock2")), + ("Leader", Kind::Arrow("leaderArrowBlock")), + ("Arrow size", Kind::Num("arrowSize")), + ("Tick size", Kind::Num("tickSize")), + ], + ), + ("Center marks", &[("Type", Kind::CenterType), ("Size", Kind::CenterSize)]), + ("Arc length symbol", &[("Arc length symbol", Kind::Choice("arcSymbol", ARC_SYMBOL))]), + ("Radius jog dimension", &[("Jog angle", Kind::Num("jogAngle"))]), + ], + ), + ( + "Text", + &[ + ( + "Text appearance", + &[ + ("Text style", Kind::TextStyle("textStyle")), + ("Text color", Kind::Color("textColor")), + ("Text height", Kind::Num("textHeight")), + ("Fraction height scale", Kind::Num("tolScale")), + ("Draw frame around text", Kind::Frame), + ], + ), + ( + "Text placement", + &[ + ("Vertical", Kind::Choice("textAbove", TEXT_VERTICAL)), + ("Horizontal", Kind::Choice("textJust", TEXT_HORIZONTAL)), + ("Offset from dim line", Kind::Gap), + ], + ), + ("Text alignment", &[("Alignment", Kind::TextAlign)]), + ], + ), + ( + "Fit", + &[ + ( + "Fit options", + &[ + ("Move outside the extension lines", Kind::Choice("fit", FIT)), + ("Always keep text between ext lines", Kind::Bool("textInside")), + ("Suppress arrows if they don't fit inside", Kind::Bool("suppressOutsideArrows")), + ], + ), + ("Text placement", &[("When text is not in the default position", Kind::Choice("textMove", TEXT_MOVE))]), + ("Scale for dimension features", &[("Annotative", Kind::Bool("annotative")), ("Use overall scale of", Kind::Num("scale"))]), + ("Fine tuning", &[("Draw dim line between ext lines", Kind::Bool("forceLineInside"))]), + ], + ), + ( + "Primary Units", + &[ + ( + "Linear dimensions", + &[ + ("Unit format", Kind::Choice("linearUnit", LINEAR_UNITS)), + ("Precision", Kind::Precision("decimals")), + ("Fraction format", Kind::Choice("fractionFormat", FRACTIONS)), + ("Decimal separator", Kind::Separator("decimalSeparator")), + ("Round off", Kind::Num("round")), + ("Prefix", Kind::Prefix("post", "<>")), + ("Suffix", Kind::Suffix("post", "<>")), + ("Measurement scale factor", Kind::Num("linearFactor")), + ("Suppress leading zeros", Kind::Bit("zeroSuppression", 4)), + ("Suppress trailing zeros", Kind::Bit("zeroSuppression", 8)), + ], + ), + ( + "Angular dimensions", + &[ + ("Units format", Kind::Choice("angularUnit", ANGULAR_UNITS)), + ("Precision", Kind::Precision("angularDecimals")), + ("Suppress leading zeros", Kind::Bit("angularZeroSuppression", 1)), + ("Suppress trailing zeros", Kind::Bit("angularZeroSuppression", 2)), + ], + ), + ], + ), + ( + "Alternate Units", + &[( + "Alternate units", + &[ + ("Display alternate units", Kind::Bool("alt")), + ("Unit format", Kind::Choice("altUnit", ALT_UNITS)), + ("Precision", Kind::Precision("altDecimals")), + ("Multiplier for alt units", Kind::Num("altFactor")), + ("Round distances to", Kind::Num("altRound")), + ("Prefix", Kind::Prefix("altPost", "[]")), + ("Suffix", Kind::Suffix("altPost", "[]")), + ("Suppress leading zeros", Kind::Bit("altZeroSuppression", 4)), + ("Suppress trailing zeros", Kind::Bit("altZeroSuppression", 8)), + ], + )], + ), + ( + "Tolerances", + &[( + "Tolerance format", + &[ + ("Method", Kind::TolMethod), + ("Precision", Kind::Precision("tolDecimals")), + ("Upper value", Kind::Num("tolPlus")), + ("Lower value", Kind::Num("tolMinus")), + ("Scaling for height", Kind::Num("tolScale")), + ("Vertical position", Kind::Choice("tolJust", TOL_JUST)), + ("Suppress leading zeros", Kind::Bit("tolZeroSuppression", 4)), + ("Suppress trailing zeros", Kind::Bit("tolZeroSuppression", 8)), + ], + )], + ), +]; + +/// A dimension's settings in the Properties palette, by group (per-dimension overrides). +pub const PROPERTIES: &[(&str, &[Row])] = &[ + ( + "Lines & Arrows", + &[ + ("Arrow 1", Kind::Arrow("arrowBlock1")), + ("Arrow 2", Kind::Arrow("arrowBlock2")), + ("Arrow size", Kind::Num("arrowSize")), + ("Dim line color", Kind::Color("dimLineColor")), + ("Dim line lineweight", Kind::Lineweight("dimLineweight")), + ("Dim line 1", Kind::Bool("suppressDim1")), + ("Dim line 2", Kind::Bool("suppressDim2")), + ("Ext line color", Kind::Color("extLineColor")), + ("Ext line lineweight", Kind::Lineweight("extLineweight")), + ("Ext line 1", Kind::Bool("suppressExt1")), + ("Ext line 2", Kind::Bool("suppressExt2")), + ("Ext line ext", Kind::Num("extExtend")), + ("Ext line offset", Kind::Num("extOffset")), + ("Ext line fixed", Kind::Bool("fixedExt")), + ("Ext line fixed length", Kind::Num("fixedExtLength")), + ], + ), + ( + "Text", + &[ + ("Text style", Kind::TextStyle("textStyle")), + ("Text color", Kind::Color("textColor")), + ("Text height", Kind::Num("textHeight")), + ("Text offset", Kind::Gap), + ("Text frame", Kind::Frame), + ("Text pos vert", Kind::Choice("textAbove", TEXT_VERTICAL)), + ("Text pos hor", Kind::Choice("textJust", TEXT_HORIZONTAL)), + ("Text alignment", Kind::TextAlign), + ], + ), + ( + "Fit", + &[ + ("Dim line inside", Kind::Bool("forceLineInside")), + ("Dim scale overall", Kind::Num("scale")), + ("Fit", Kind::Choice("fit", FIT)), + ("Text inside", Kind::Bool("textInside")), + ("Text movement", Kind::Choice("textMove", TEXT_MOVE)), + ], + ), + ( + "Primary Units", + &[ + ("Dim units", Kind::Choice("linearUnit", LINEAR_UNITS)), + ("Precision", Kind::Precision("decimals")), + ("Decimal separator", Kind::Separator("decimalSeparator")), + ("Dim prefix", Kind::Prefix("post", "<>")), + ("Dim suffix", Kind::Suffix("post", "<>")), + ("Dim roundoff", Kind::Num("round")), + ("Dim scale linear", Kind::Num("linearFactor")), + ("Suppress leading zeros", Kind::Bit("zeroSuppression", 4)), + ("Suppress trailing zeros", Kind::Bit("zeroSuppression", 8)), + ("Angle format", Kind::Choice("angularUnit", ANGULAR_UNITS)), + ("Angle precision", Kind::Precision("angularDecimals")), + ], + ), + ( + "Alternate Units", + &[ + ("Alt enabled", Kind::Bool("alt")), + ("Alt format", Kind::Choice("altUnit", ALT_UNITS)), + ("Alt precision", Kind::Precision("altDecimals")), + ("Alt multiplier", Kind::Num("altFactor")), + ("Alt round", Kind::Num("altRound")), + ("Alt prefix", Kind::Prefix("altPost", "[]")), + ("Alt suffix", Kind::Suffix("altPost", "[]")), + ], + ), + ( + "Tolerances", + &[ + ("Tolerance display", Kind::TolMethod), + ("Tolerance limit upper", Kind::Num("tolPlus")), + ("Tolerance limit lower", Kind::Num("tolMinus")), + ("Tolerance precision", Kind::Precision("tolDecimals")), + ("Tolerance text height", Kind::Num("tolScale")), + ("Tolerance pos vert", Kind::Choice("tolJust", TOL_JUST)), + ], + ), +]; + +/// The fields of `after` that differ from `before`. +pub fn changed_fields(before: &Map, after: &Map) -> Map { + after.iter().filter(|(k, v)| before.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect() +} + +/// The drawing's names a row may offer: linetypes and text styles. +#[derive(Clone, Default)] +pub struct Names { + pub linetypes: Vec, + pub text_styles: Vec, + /// User arrowhead blocks the drawing's dimension styles use. + pub arrow_blocks: Vec, +} + +impl Names { + pub fn of(d: &cadcraft_doc::Drawing) -> Names { + let mut arrow_blocks: Vec = Vec::new(); + let dims = d.dim_styles.iter().flat_map(|st| [&st.arrow_block, &st.arrow_block1, &st.arrow_block2, &st.leader_arrow_block]); + let mleaders = d.mleader_styles.iter().map(|st| &st.arrow_block); + for n in dims.chain(mleaders) { + if !builtin_arrow(n) && cadcraft_render::arrow_block(d, n).is_some() && !arrow_blocks.iter().any(|b| b.eq_ignore_ascii_case(n)) { + arrow_blocks.push(n.trim().to_string()); + } + } + Names { + linetypes: d.linetypes.iter().map(|l| l.name.clone()).collect(), + text_styles: d.text_styles.iter().map(|s| s.name.clone()).collect(), + arrow_blocks, + } + } +} + +fn num(m: &Map, f: &str) -> f64 { + m.get(f).and_then(Value::as_f64).unwrap_or(0.0) +} +fn int(m: &Map, f: &str) -> i64 { + m.get(f).and_then(|v| v.as_i64().or_else(|| v.as_bool().map(i64::from))).unwrap_or(0) +} +fn flag(m: &Map, f: &str) -> bool { + m.get(f).and_then(Value::as_bool).unwrap_or(false) +} +fn text(m: &Map, f: &str) -> String { + m.get(f).and_then(Value::as_str).unwrap_or("").to_string() +} + +fn color_label(v: &Value) -> String { + let c: cadcraft_color::Color = serde_json::from_value(v.clone()).unwrap_or_default(); + crate::i18n::t(&c.name()).to_string() +} + +fn combo(ui: &mut egui::Ui, id: impl std::hash::Hash + std::fmt::Debug, current: &T, items: &[(T, String)]) -> Option { + let shown = items.iter().find(|(v, _)| v == current).map_or_else(String::new, |(_, l)| l.clone()); + let mut picked = None; + egui::ComboBox::from_id_salt(id) + .width((ui.available_width() - 14.0).clamp(80.0, 190.0)) + .selected_text(crate::i18n::widget(ui, &shown, egui::TextStyle::Button)) + .height(320.0) + .show_ui(ui, |ui| { + for (v, l) in items { + if ui.selectable_label(v == current, crate::i18n::widget(ui, l, egui::TextStyle::Button)).clicked() && v != current { + picked = Some(v.clone()); + } + } + }); + picked +} + +/// The arrowhead list: the built-in ones, then the drawing's user arrowheads (and `cur` when it +/// is a block none of the styles use). +fn arrow_items(names: &Names, cur: &str) -> Vec<(String, String)> { + let mut items: Vec<(String, String)> = ARROWS.iter().map(|(n, l)| (n.to_string(), crate::i18n::t(l).to_string())).collect(); + let cur = cur.trim().to_string(); + for b in names.arrow_blocks.iter().chain((!builtin_arrow(&cur)).then_some(&cur)) { + if !items.iter().any(|(n, _)| n.eq_ignore_ascii_case(b)) { + items.push((b.clone(), format!("{} {}", crate::tl!("User Arrow:"), b))); + } + } + items +} + +/// The entry of [`arrow_items`] that `cur` (any spelling of an arrowhead) is. +fn shown_arrow(names: &Names, cur: &str) -> String { + if builtin_arrow(cur) { + ARROWS.iter().find(|(n, _)| same_arrow(n, cur)).map_or(String::new(), |(n, _)| n.to_string()) + } else { + arrow_items(names, cur).into_iter().find(|(n, _)| n.eq_ignore_ascii_case(cur.trim())).map_or(cur.to_string(), |(n, _)| n) + } +} + +/// An arrowhead drop-down (built-in arrowheads and the drawing's user arrowhead blocks) showing +/// `cur`; the name picked. +pub fn arrow_combo(ui: &mut egui::Ui, id: egui::Id, names: &Names, cur: &str) -> Option { + combo(ui, id, &shown_arrow(names, cur), &arrow_items(names, cur)) +} + +/// The decimal places as AutoCAD shows them: `0`, `0.0`, `0.00`… +fn precision_items() -> Vec<(i64, String)> { + (0..=8).map(|n| (n, if n == 0 { "0".to_string() } else { format!("0.{}", "0".repeat(n as usize)) })).collect() +} + +/// The arrowhead a DIMBLK value names, for comparing names written differently. +fn same_arrow(a: &str, b: &str) -> bool { + cadcraft_render::Arrowhead::parse(a) == cadcraft_render::Arrowhead::parse(b) +} + +/// Whether a DIMBLK name is one of the arrowheads drawn in code (any of its spellings); other +/// names are user arrowheads (blocks). +pub fn builtin_arrow(name: &str) -> bool { + let norm = |s: &str| s.trim().trim_start_matches('_').chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); + let n = norm(name); + n.is_empty() + || ARROWS.iter().any(|(k, l)| norm(k) == n || norm(l) == n) + || ["filled", "blank", "architecturaltick", "tick", "rightangle", "originindicator", "originindicator2", "box", "datumtriangle"] + .contains(&n.as_str()) +} + +/// The tolerance display of a style (0 None, 1 Symmetrical, 2 Deviation, 3 Limits, 4 Basic). +fn tol_method(m: &Map) -> i64 { + if flag(m, "limits") { + 3 + } else if flag(m, "tolerance") { + if (num(m, "tolPlus") - num(m, "tolMinus")).abs() < 1e-12 { 1 } else { 2 } + } else if num(m, "textGap") < 0.0 { + 4 + } else { + 0 + } +} + +/// Split a prefix/suffix template at its placeholder. +fn split_post(post: &str, placeholder: &str) -> (String, String) { + match post.find(placeholder) { + Some(i) => (post[..i].to_string(), post[i + placeholder.len()..].to_string()), + None => (String::new(), post.to_string()), + } +} + +/// One setting's control; true when it changed `m`. +pub fn field_row(ui: &mut egui::Ui, id: egui::Id, names: &Names, m: &mut Map, kind: Kind) -> bool { + let before = m.clone(); + match kind { + Kind::Num(f) => { + let mut v = num(m, f); + let speed = (v.abs() * 0.01).max(0.001); + if ui.add(egui::DragValue::new(&mut v).speed(speed).max_decimals(4).min_decimals(2)).changed() && v.is_finite() { + m.insert(f.into(), json!(v)); + } + } + Kind::Choice(f, items) => { + let items: Vec<(i64, String)> = items.iter().map(|(v, l)| (*v, crate::i18n::t(l).to_string())).collect(); + if let Some(v) = combo(ui, id.with(f), &int(m, f), &items) { + m.insert(f.into(), json!(v)); + } + } + Kind::Precision(f) => { + if let Some(v) = combo(ui, id.with(f), &int(m, f), &precision_items()) { + m.insert(f.into(), json!(v)); + } + } + Kind::Bool(f) => { + let mut b = flag(m, f); + if ui.checkbox(&mut b, "").changed() { + m.insert(f.into(), json!(b)); + } + } + Kind::Bit(f, bit) => { + let v = int(m, f) as u64; + let mut b = v & bit != 0; + if ui.checkbox(&mut b, "").changed() { + m.insert(f.into(), json!(if b { v | bit } else { v & !bit })); + } + } + Kind::Color(f) => { + let cur = m.get(f).cloned().unwrap_or(Value::Null); + let mut items: Vec<(Value, String)> = vec![ + (json!({ "kind": "byBlock" }), crate::tl!("ByBlock").to_string()), + (json!({ "kind": "byLayer" }), crate::tl!("ByLayer").to_string()), + ]; + for (aci, name) in [(1, "Red"), (2, "Yellow"), (3, "Green"), (4, "Cyan"), (5, "Blue"), (6, "Magenta"), (7, "White")] { + items.push((serde_json::to_value(cadcraft_color::Color::Index(aci)).unwrap_or(Value::Null), crate::i18n::t(name).to_string())); + } + if !items.iter().any(|(v, _)| *v == cur) { + items.push((cur.clone(), color_label(&cur))); + } + if let Some(v) = combo(ui, id.with(f), &cur, &items) { + m.insert(f.into(), v); + } + } + Kind::Arrow(f) => { + let mut cur = text(m, f); + // An empty per-end arrowhead uses DIMBLK. + if cur.is_empty() && f != "leaderArrowBlock" { + cur = text(m, "arrowBlock"); + } + let shown = shown_arrow(names, &cur); + let shown = shown.as_str(); + if let Some(v) = arrow_combo(ui, id.with(f), names, &cur) { + // The first arrowhead sets the second too while they match, as AutoCAD's does. + if f == "arrowBlock1" { + let second = text(m, "arrowBlock2"); + let second = if second.is_empty() { text(m, "arrowBlock") } else { second }; + if second.eq_ignore_ascii_case(shown) || (builtin_arrow(&second) && builtin_arrow(shown) && same_arrow(&second, shown)) { + m.insert("arrowBlock2".into(), json!(v)); + } + m.insert("arrowBlock".into(), json!(v)); + } + m.insert(f.into(), json!(v)); + } + } + Kind::Lineweight(f) => { + let mut items: Vec<(i64, String)> = + vec![(-2, crate::tl!("ByBlock").into()), (-1, crate::tl!("ByLayer").into()), (-3, crate::tl!("Default").into())]; + items.extend(cadcraft_doc::Lineweight::STANDARD.iter().map(|v| (i64::from(*v), format!("{:.2} mm", f64::from(*v) / 100.0)))); + if let Some(v) = combo(ui, id.with(f), &int(m, f), &items) { + m.insert(f.into(), json!(v)); + } + } + Kind::Linetype(f) => { + let mut items: Vec<(String, String)> = + vec![(String::new(), crate::tl!("ByBlock").into()), ("ByLayer".into(), crate::tl!("ByLayer").into())]; + for n in &names.linetypes { + if !["ByLayer", "ByBlock"].iter().any(|x| x.eq_ignore_ascii_case(n)) { + items.push((n.clone(), n.clone())); + } + } + let cur = text(m, f); + let cur = items.iter().find(|(v, _)| v.eq_ignore_ascii_case(&cur)).map_or(cur, |(v, _)| v.clone()); + if let Some(v) = combo(ui, id.with(f), &cur, &items) { + m.insert(f.into(), json!(v)); + } + } + Kind::TextStyle(f) => { + let items: Vec<(String, String)> = names.text_styles.iter().map(|n| (n.clone(), n.clone())).collect(); + let cur = text(m, f); + let cur = items.iter().find(|(v, _)| v.eq_ignore_ascii_case(&cur)).map_or(cur, |(v, _)| v.clone()); + if let Some(v) = combo(ui, id.with(f), &cur, &items) { + m.insert(f.into(), json!(v)); + } + } + Kind::Prefix(f, ph) | Kind::Suffix(f, ph) => { + let (mut pre, mut suf) = split_post(&text(m, f), ph); + let prefix = matches!(kind, Kind::Prefix(..)); + let r = + ui.add(egui::TextEdit::singleline(if prefix { &mut pre } else { &mut suf }).desired_width(ui.available_width().clamp(80.0, 186.0))); + if r.changed() { + let post = if pre.is_empty() && suf.is_empty() { String::new() } else { format!("{pre}{ph}{suf}") }; + m.insert(f.into(), json!(post)); + } + } + Kind::Separator(f) => { + let items: Vec<(String, String)> = SEPARATORS.iter().map(|(v, l)| (v.to_string(), l.to_string())).collect(); + if let Some(v) = combo(ui, id.with(f), &text(m, f), &items) { + m.insert(f.into(), json!(v)); + } + } + Kind::TolMethod => { + let items: Vec<(i64, String)> = ["None", "Symmetrical", "Deviation", "Limits", "Basic"] + .iter() + .enumerate() + .map(|(i, l)| (i as i64, crate::i18n::t(l).to_string())) + .collect(); + if let Some(v) = combo(ui, id.with("tolmethod"), &tol_method(m), &items) { + let gap = num(m, "textGap").abs(); + m.insert("tolerance".into(), json!(v == 1 || v == 2)); + m.insert("limits".into(), json!(v == 3)); + m.insert("textGap".into(), json!(if v == 4 { -gap } else { gap })); + if v == 1 { + m.insert("tolMinus".into(), json!(num(m, "tolPlus"))); + } + } + } + Kind::TextAlign => { + let (ih, oh) = (flag(m, "textInsideHorizontal"), flag(m, "textOutsideHorizontal")); + let cur = match (ih, oh) { + (true, _) => 0, + (false, false) => 1, + (false, true) => 2, + }; + let items: Vec<(i64, String)> = ["Horizontal", "Aligned with dimension line", "ISO standard"] + .iter() + .enumerate() + .map(|(i, l)| (i as i64, crate::i18n::t(l).to_string())) + .collect(); + if let Some(v) = combo(ui, id.with("textalign"), &cur, &items) { + m.insert("textInsideHorizontal".into(), json!(v == 0)); + m.insert("textOutsideHorizontal".into(), json!(v != 1)); + } + } + Kind::Frame => { + let gap = num(m, "textGap"); + let mut b = gap < 0.0; + if ui.checkbox(&mut b, "").changed() { + m.insert("textGap".into(), json!(if b { -gap.abs() } else { gap.abs() })); + } + } + Kind::Gap => { + let gap = num(m, "textGap"); + let mut v = gap.abs(); + if ui.add(egui::DragValue::new(&mut v).speed(0.005).range(0.0..=1e6).max_decimals(4).min_decimals(2)).changed() { + m.insert("textGap".into(), json!(if gap < 0.0 { -v } else { v })); + } + } + Kind::CenterType => { + let c = num(m, "centerMark"); + let cur = if c == 0.0 { + 0 + } else if c > 0.0 { + 1 + } else { + 2 + }; + let items: Vec<(i64, String)> = + ["None", "Mark", "Line"].iter().enumerate().map(|(i, l)| (i as i64, crate::i18n::t(l).to_string())).collect(); + if let Some(v) = combo(ui, id.with("centertype"), &cur, &items) { + let size = if c == 0.0 { 0.09 } else { c.abs() }; + m.insert( + "centerMark".into(), + json!(match v { + 0 => 0.0, + 1 => size, + _ => -size, + }), + ); + } + } + Kind::CenterSize => { + let c = num(m, "centerMark"); + let mut v = c.abs(); + let r = ui.add_enabled(c != 0.0, egui::DragValue::new(&mut v).speed(0.005).range(0.0..=1e6).max_decimals(4).min_decimals(2)); + if r.changed() && v > 0.0 { + m.insert("centerMark".into(), json!(if c < 0.0 { -v } else { v })); + } + } + } + *m != before +} + +/// A style's JSON form. +pub fn style_map(st: &DimStyle) -> Map { + match serde_json::to_value(st) { + Ok(Value::Object(m)) => m, + _ => Map::new(), + } +} + +/// The style a JSON form describes (unknown or bad values keep the defaults). +pub fn map_style(m: &Map) -> DimStyle { + let mut st = DimStyle::default(); + let mut fields = m.clone(); + fields.remove("name"); + st.apply_fields(&fields); + st.name = text(m, "name"); + st +} + +// ---------------------------------------------------------------- preview + +thread_local! { + static PREVIEWS: RefCell>> = RefCell::new(HashMap::new()); +} + +/// The preview drawing of `st`: a part with linear, aligned, radius and angular dimensions in +/// that style, sized to its text height. +fn build_preview(st: &DimStyle) -> Option { + let mut s = cadcraft_engine::Session::new(); + let mut fields = style_map(st); + fields.insert("name".into(), json!("Preview")); + fields.insert("current".into(), json!(true)); + fields.insert("annotative".into(), json!(false)); + s.execute("dimstyle", &Value::Object(fields)).ok()?; + let th = st.text_height * if st.scale > 0.0 { st.scale } else { 1.0 }; + let f = if th.is_finite() && th > 0.0 { th / 0.18 } else { 1.0 }; + let p = |x: f64, y: f64| json!([x * f, y * f]); + let _ = s.execute("layer.new", &json!({ "name": "Part", "color": 40, "current": true })); + let outline = [(0.0, 0.0), (3.0, 0.0), (2.0, 1.7), (1.0, 1.7), (1.0, 2.2), (0.0, 2.2), (0.0, 0.0)]; + s.execute("line", &json!({ "points": outline.iter().map(|(x, y)| p(*x, *y)).collect::>() })).ok()?; + let circle = s.execute("circle", &json!({ "center": p(0.55, 0.85), "radius": 0.4 * f })).ok()?; + let _ = s.execute("layer.new", &json!({ "name": "Dims", "color": 7, "current": true })); + let _ = s.execute("dimlinear", &json!({ "p1": p(0.0, 2.2), "p2": p(1.0, 2.2), "at": p(0.5, 2.75) })); + let _ = s.execute("dimlinear", &json!({ "p1": p(0.0, 0.0), "p2": p(0.0, 2.2), "at": p(-0.55, 1.1) })); + let _ = s.execute("dimaligned", &json!({ "p1": p(3.0, 0.0), "p2": p(2.0, 1.7), "at": p(3.05, 1.2) })); + if let Some(h) = circle["handle"].as_str() { + let _ = s.execute("dimradius", &json!({ "handle": h, "at": p(0.05, 0.35) })); + } + let _ = s.execute("dimangular", &json!({ "vertex": p(3.0, 0.0), "p1": p(0.0, 0.0), "p2": p(2.0, 1.7), "at": p(2.2, 0.45) })); + let d = s.doc().ok()?; + Some(cadcraft_render::build(d, &cadcraft_doc::Space::Model, &cadcraft_render::Options::default())) +} + +/// Draw the preview of `st` in a `size` box. +pub fn preview(ui: &mut egui::Ui, st: &DimStyle, size: egui::Vec2) { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); + let p = ui.painter_at(rect); + p.rect_filled(rect, 2.0, t.canvas); + let key = serde_json::to_string(st).unwrap_or_default(); + let list = PREVIEWS.with(|c| { + let mut c = c.borrow_mut(); + if c.len() > 64 { + c.clear(); + } + c.entry(key).or_insert_with(|| build_preview(st)).clone() + }); + let Some(list) = list else { return }; + let b = list.bounds; + if b.is_empty() || !(b.width() > 0.0 && b.height() > 0.0) { + return; + } + let inner = rect.shrink(12.0); + let scale = (f64::from(inner.width()) / b.width()).min(f64::from(inner.height()) / b.height()); + let xf = crate::canvas::Xf { rect, center: b.center(), scale }; + let bg = cadcraft_color::Rgb(t.canvas.r(), t.canvas.g(), t.canvas.b()); + crate::canvas::draw_list(&p, &xf, &list, bg, false); +} + +// ---------------------------------------------------------------- the manager + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + Modify, + New, + Override, +} + +#[derive(Clone)] +struct Editor { + mode: Mode, + name: String, + base: Map, + style: Map, + tab: usize, +} + +#[derive(Clone)] +struct NewStyle { + name: String, + from: String, + annotative: bool, +} + +#[derive(Clone, Default)] +struct State { + sel: Option, + in_use_only: bool, + new: Option, + editor: Option, + compare: Option<(String, String)>, + rename: Option<(String, String)>, +} + +fn state_id() -> egui::Id { + egui::Id::new("cc_dimstyle_manager") +} + +/// Dimension style names used by dimensions, leaders and tolerances anywhere in the drawing. +fn styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { + use cadcraft_doc::EntityKind; + let mut out: Vec = Vec::new(); + let spaces = std::iter::once(cadcraft_doc::Space::Model).chain(d.layouts.iter().map(|l| cadcraft_doc::Space::Paper(l.name.clone()))); + for space in spaces { + let Some(st) = d.space(&space) else { continue }; + for e in st.iter() { + let name = match &e.kind { + EntityKind::Dimension(dm) => &dm.style, + EntityKind::Leader(l) => &l.style, + EntityKind::Tolerance(t) => &t.style, + _ => continue, + }; + if !out.iter().any(|n| n.eq_ignore_ascii_case(name)) { + out.push(name.clone()); + } + } + } + out +} + +/// A small blue mark for annotative styles, as the style lists show it. +fn annotative_mark(ui: &mut egui::Ui, on: bool) { + let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); + if on { + let c = Color32::from_rgb(70, 140, 230); + let m = r.center(); + for a in [-90.0f32, 30.0, 150.0] { + let d = vec2(a.to_radians().cos(), a.to_radians().sin()) * 6.0; + ui.painter().line_segment([m, m + d], Stroke::new(2.0, c)); + } + } +} + +/// Format ▸ Dimension Style...: the manager, and the editor or New / Compare windows it opens. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let t = Tokens::get(); + let Ok(d) = app.session.doc() else { + *open = false; + return; + }; + let mut st: State = ctx.data(|m| m.get_temp(state_id())).unwrap_or_default(); + let current = d.header.str("DIMSTYLE", "Standard"); + let used = styles_in_use(d); + let styles: Vec = d.dim_styles.clone(); + let names = Names::of(d); + let overrides = d.dim_overrides(); + let sel = st.sel.clone().filter(|s| styles.iter().any(|x| x.name.eq_ignore_ascii_case(s))).unwrap_or_else(|| current.clone()); + let sel_style = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&sel)).cloned().unwrap_or_default(); + let mut run: Vec<(&'static str, Value)> = Vec::new(); + let modal = st.editor.is_some() || st.new.is_some() || st.compare.is_some(); + + egui::Window::new(crate::tl!("Dimension Style Manager")) + .id(egui::Id::new("cc_dimstyle_window")) + .open(open) + .resizable(false) + .collapsible(false) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.add_enabled_ui(!modal, |ui| { + ui.label(format!("{} {current}", crate::tl!("Current dimension style:"))); + ui.add_space(4.0); + ui.horizontal_top(|ui| { + // Styles and the List filter. + ui.vertical(|ui| { + ui.set_width(220.0); + ui.label(crate::tl!("Styles:")); + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(4.0).show(ui, |ui| { + egui::ScrollArea::vertical() + .id_salt("cc_dimstyle_list") + .max_height(230.0) + .min_scrolled_height(230.0) + .auto_shrink([false, false]) + .show(ui, |ui| { + for s in styles.iter().filter(|s| { + !st.in_use_only + || used.iter().any(|u| u.eq_ignore_ascii_case(&s.name)) + || s.name.eq_ignore_ascii_case(¤t) + }) { + ui.horizontal(|ui| { + annotative_mark(ui, s.annotative); + let mut label = RichText::new(&s.name); + if s.name.eq_ignore_ascii_case(¤t) { + label = label.strong(); + } + let r = ui.selectable_label(s.name.eq_ignore_ascii_case(&sel), label); + if r.clicked() { + st.sel = Some(s.name.clone()); + } + if r.double_clicked() { + run.push(("dimstyle.current", json!({ "name": s.name }))); + } + r.context_menu(|ui| { + if ui.button(crate::tl!("Set Current")).clicked() { + run.push(("dimstyle.current", json!({ "name": s.name }))); + ui.close(); + } + if ui.button(crate::tl!("Rename")).clicked() { + st.rename = Some((s.name.clone(), s.name.clone())); + ui.close(); + } + let deletable = !s.name.eq_ignore_ascii_case("Standard") + && !s.name.eq_ignore_ascii_case(¤t) + && !used.iter().any(|u| u.eq_ignore_ascii_case(&s.name)); + if ui.add_enabled(deletable, egui::Button::new(crate::tl!("Delete"))).clicked() { + run.push(("dimstyle.delete", json!({ "name": s.name }))); + ui.close(); + } + }); + }); + } + }); + }); + if let Some((from, mut to)) = st.rename.clone() { + ui.horizontal(|ui| { + let r = ui.add(egui::TextEdit::singleline(&mut to).desired_width(150.0)); + r.request_focus(); + if ui.input(|i| i.key_pressed(egui::Key::Enter)) { + if !to.trim().is_empty() && to.trim() != from { + run.push(("dimstyle.rename", json!({ "from": from, "to": to.trim() }))); + st.sel = Some(to.trim().to_string()); + } + st.rename = None; + } else if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + st.rename = None; + } else { + st.rename = Some((from.clone(), to.clone())); + } + }); + } + ui.add_space(4.0); + ui.label(crate::tl!("List:")); + let items = vec![(false, crate::tl!("All styles").to_string()), (true, crate::tl!("Styles in use").to_string())]; + if let Some(v) = combo(ui, "cc_dimstyle_listfilter", &st.in_use_only, &items) { + st.in_use_only = v; + } + }); + // Preview and description. + ui.vertical(|ui| { + ui.label(format!("{} {sel}", crate::tl!("Preview of:"))); + preview(ui, &sel_style, vec2(320.0, 230.0)); + ui.add_space(4.0); + ui.label(crate::tl!("Description")); + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(6.0).show(ui, |ui| { + ui.set_width(308.0); + ui.set_min_height(48.0); + let mut desc = sel.clone(); + if sel_style.annotative { + desc.push_str(&format!(" ({})", crate::tl!("Annotative"))); + } + ui.label(desc); + if sel.eq_ignore_ascii_case(¤t) && !overrides.is_empty() { + ui.label(RichText::new(format!("+ {} {}", overrides.len(), crate::tl!("overrides"))).color(t.text_dim)); + } + }); + }); + // Buttons. + ui.vertical(|ui| { + let w = vec2(120.0, 26.0); + if ui.add_enabled(!sel.eq_ignore_ascii_case(¤t), egui::Button::new(crate::tl!("Set Current")).min_size(w)).clicked() { + run.push(("dimstyle.current", json!({ "name": sel }))); + } + if ui.add(egui::Button::new(crate::tl!("New...")).min_size(w)).clicked() { + st.new = Some(NewStyle { + name: format!("{} {sel}", crate::tl!("Copy of")), + from: sel.clone(), + annotative: sel_style.annotative, + }); + } + if ui.add(egui::Button::new(crate::tl!("Modify...")).min_size(w)).clicked() { + let m = style_map(&sel_style); + st.editor = Some(Editor { mode: Mode::Modify, name: sel.clone(), base: m.clone(), style: m, tab: 0 }); + } + let cur_style = styles.iter().find(|x| x.name.eq_ignore_ascii_case(¤t)).cloned().unwrap_or_default(); + if ui + .add_enabled(sel.eq_ignore_ascii_case(¤t), egui::Button::new(crate::tl!("Override...")).min_size(w)) + .on_disabled_hover_text(crate::tl!("Overrides apply to the current style")) + .clicked() + { + let base = style_map(&cur_style); + let mut with = base.clone(); + with.extend(overrides.clone()); + st.editor = Some(Editor { mode: Mode::Override, name: current.clone(), base, style: with, tab: 0 }); + } + if ui.add(egui::Button::new(crate::tl!("Compare...")).min_size(w)).clicked() { + st.compare = Some((sel.clone(), current.clone())); + } + }); + }); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(crate::tl!("Close")).min_size(vec2(90.0, 24.0))).clicked() { + st.compare = None; + st.editor = None; + st.new = None; + ctx.data_mut(|m| m.insert_temp(egui::Id::new("cc_dimstyle_close"), true)); + } + }); + }); + }); + if ctx.data_mut(|m| m.remove_temp::(egui::Id::new("cc_dimstyle_close"))).is_some() { + *open = false; + } + + // New Dimension Style: the name, the style to start with, annotative. + if let Some(mut n) = st.new.clone() { + let mut keep = true; + let mut go = false; + egui::Window::new(crate::tl!("Create New Dimension Style")) + .id(egui::Id::new("cc_dimstyle_new")) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + egui::Grid::new("cc_dimstyle_new_grid").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| { + ui.label(crate::tl!("New Style Name:")); + ui.add(egui::TextEdit::singleline(&mut n.name).desired_width(220.0)); + ui.end_row(); + ui.label(crate::tl!("Start With:")); + let items: Vec<(String, String)> = styles.iter().map(|s| (s.name.clone(), s.name.clone())).collect(); + if let Some(v) = combo(ui, "cc_dimstyle_new_from", &n.from, &items) { + n.from = v; + } + ui.end_row(); + ui.label(crate::tl!("Annotative")); + ui.checkbox(&mut n.annotative, ""); + ui.end_row(); + }); + let taken = styles.iter().any(|s| s.name.eq_ignore_ascii_case(n.name.trim())); + if taken { + ui.label(RichText::new(crate::tl!("A style with this name already exists.")).color(t.warn)); + } + ui.horizontal(|ui| { + if ui.add_enabled(!n.name.trim().is_empty() && !taken, egui::Button::new(crate::tl!("Continue"))).clicked() { + go = true; + } + if ui.button(crate::tl!("Cancel")).clicked() { + keep = false; + } + }); + }); + if go { + let from = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n.from)).cloned().unwrap_or_default(); + let mut m = style_map(&from); + m.insert("name".into(), json!(n.name.trim())); + m.insert("annotative".into(), json!(n.annotative)); + st.editor = Some(Editor { mode: Mode::New, name: n.name.trim().to_string(), base: m.clone(), style: m, tab: 0 }); + st.new = None; + } else { + st.new = keep.then_some(n); + } + } + + // The style editor. + if let Some(mut ed) = st.editor.clone() { + let mut close = false; + let mut ok = false; + let title = match ed.mode { + Mode::Modify => format!("{} {}", crate::tl!("Modify Dimension Style:"), ed.name), + Mode::New => format!("{} {}", crate::tl!("New Dimension Style:"), ed.name), + Mode::Override => format!("{} {}", crate::tl!("Override Current Style:"), ed.name), + }; + egui::Window::new(title) + .id(egui::Id::new("cc_dimstyle_editor")) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + ui.horizontal_wrapped(|ui| { + for (i, (name, _)) in TABS.iter().enumerate() { + if ui.selectable_label(ed.tab == i, crate::i18n::t(name)).clicked() { + ed.tab = i; + } + } + }); + ui.separator(); + ui.horizontal_top(|ui| { + ui.allocate_ui_with_layout(vec2(480.0, 430.0), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(480.0, 430.0)); + egui::ScrollArea::vertical().id_salt(("cc_dimstyle_tab", ed.tab)).max_height(430.0).auto_shrink([false, false]).show( + ui, + |ui| { + let (_, groups) = TABS.get(ed.tab).copied().unwrap_or(TABS[0]); + for (group, rows) in groups { + ui.label(RichText::new(crate::i18n::t(group)).strong()); + egui::Grid::new(("cc_dimstyle_grid", ed.tab, *group)) + .num_columns(2) + .spacing(vec2(12.0, 6.0)) + .min_col_width(200.0) + .show(ui, |ui| { + for (label, kind) in rows.iter() { + ui.label(crate::i18n::t(label)); + field_row( + ui, + egui::Id::new(("cc_dimstyle_field", ed.tab, *group, *label)), + &names, + &mut ed.style, + *kind, + ); + ui.end_row(); + } + }); + ui.add_space(8.0); + } + }, + ); + }); + ui.vertical(|ui| { + preview(ui, &map_style(&ed.style), vec2(300.0, 240.0)); + if ed.mode == Mode::Override { + ui.label(RichText::new(crate::tl!("Overrides apply to new dimensions in the current style.")).small().color(t.text_dim)); + } + }); + }); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(crate::tl!("Cancel")).min_size(vec2(80.0, 24.0))).clicked() { + close = true; + } + if ui.add(egui::Button::new(crate::tl!("OK")).min_size(vec2(80.0, 24.0))).clicked() { + ok = true; + } + }); + }); + if ok { + match ed.mode { + Mode::Modify | Mode::New => { + let mut p = ed.style.clone(); + p.insert("name".into(), json!(ed.name)); + p.insert("current".into(), json!(ed.mode == Mode::Modify && ed.name.eq_ignore_ascii_case(¤t))); + run.push(("dimstyle", Value::Object(p))); + st.sel = Some(ed.name.clone()); + } + Mode::Override => { + for (var, field) in cadcraft_doc::DIMVARS { + let (Some(new), old) = (ed.style.get(*field), ed.base.get(*field)) else { continue }; + let was = overrides.get(*field).or(old); + if Some(new) == was { + continue; + } + let value = match new { + Value::Bool(b) => json!(i64::from(*b)), + Value::Object(_) => { + let c: cadcraft_color::Color = serde_json::from_value(new.clone()).unwrap_or_default(); + json!(c.to_aci()) + } + v => v.clone(), + }; + run.push(("setvar", json!({ "name": var, "value": value }))); + } + } + } + st.editor = None; + } else if close { + st.editor = None; + } else { + st.editor = Some(ed); + } + } + + // Compare two styles: the variables that differ. + if let Some((mut a, mut b)) = st.compare.clone() { + let mut keep = true; + egui::Window::new(crate::tl!("Compare Dimension Styles")) + .id(egui::Id::new("cc_dimstyle_compare")) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .pivot(egui::Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + let items: Vec<(String, String)> = styles.iter().map(|s| (s.name.clone(), s.name.clone())).collect(); + egui::Grid::new("cc_dimstyle_cmp_pick").num_columns(2).show(ui, |ui| { + ui.label(crate::tl!("Compare:")); + if let Some(v) = combo(ui, "cc_dimstyle_cmp_a", &a, &items) { + a = v; + } + ui.end_row(); + ui.label(crate::tl!("With:")); + if let Some(v) = combo(ui, "cc_dimstyle_cmp_b", &b, &items) { + b = v; + } + ui.end_row(); + }); + ui.separator(); + let ma = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&a)).map(style_map).unwrap_or_default(); + let mb = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&b)).map(style_map).unwrap_or_default(); + let diffs: Vec<(&str, String, String)> = cadcraft_doc::DIMVARS + .iter() + .filter(|(_, f)| ma.get(*f) != mb.get(*f)) + .map(|(v, f)| (*v, show_value(ma.get(*f)), show_value(mb.get(*f)))) + .collect(); + if diffs.is_empty() { + ui.label(crate::tl!("The two styles are the same.")); + } else { + ui.label(format!("{} {}", crate::tl!("Differences found:"), diffs.len())); + egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { + egui::Grid::new("cc_dimstyle_cmp").striped(true).num_columns(3).spacing(vec2(16.0, 4.0)).show(ui, |ui| { + ui.label(RichText::new(crate::tl!("Variable")).strong()); + ui.label(RichText::new(&a).strong()); + ui.label(RichText::new(&b).strong()); + ui.end_row(); + for (v, x, y) in &diffs { + ui.monospace(*v); + ui.label(x); + ui.label(y); + ui.end_row(); + } + }); + }); + } + ui.separator(); + if ui.button(crate::tl!("Close")).clicked() { + keep = false; + } + }); + st.compare = keep.then_some((a, b)); + } + + ctx.data_mut(|m| m.insert_temp(state_id(), st)); + for (cmd, p) in run { + // Errors are echoed on the command line by `run`. + let _ = app.run(cmd, p); + } +} + +fn show_value(v: Option<&Value>) -> String { + match v { + None => String::new(), + Some(Value::String(s)) if s.is_empty() => "\"\"".into(), + Some(Value::String(s)) => s.clone(), + Some(Value::Object(_)) => v.map(color_label).unwrap_or_default(), + Some(v) => v.to_string(), + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index c44f8d1cfa..32147bdff0 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -30,7 +30,7 @@ impl Panel { Self::ExternalRefs => "externalReferences", } } - fn label(self) -> &'static str { + pub fn label(self) -> &'static str { match self { Self::Canvas => "Drawing", Self::ToolSets => "Tool Sets", @@ -285,7 +285,8 @@ impl Workspace { } fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> { - workspace.set_visible(Panel::ToolSets, app.ui.show_toolsets)?; + // As a ribbon, Tool Sets sits under the menu bar, not among the palettes. + workspace.set_visible(Panel::ToolSets, app.ui.show_toolsets && !app.ui.toolsets_ribbon)?; if !app.ui.show_palettes { workspace.set_visible(Panel::Layers, false)?; workspace.set_visible(Panel::Properties, false)?; @@ -298,7 +299,9 @@ fn sync(workspace: &mut Workspace, app: &crate::CadApp) -> Result<(), String> { } fn publish_visibility(app: &mut crate::CadApp, workspace: &Workspace) { - app.ui.show_toolsets = workspace.layout.contains(&Panel::ToolSets); + if !app.ui.toolsets_ribbon { + app.ui.show_toolsets = workspace.layout.contains(&Panel::ToolSets); + } app.ui.show_palettes = workspace.layout.contains(&Panel::Layers) || workspace.layout.contains(&Panel::Properties); } @@ -380,6 +383,13 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) { return; } for action in output.actions { + // Tool Sets dragged to the top edge becomes the ribbon under the menu bar. + if let Action::Move { panel: Panel::ToolSets, anchor: Panel::Canvas, placement: Placement::Split(Zone::Top) } = &action { + if let Err(error) = apply_toolsets(app, ToolSetsAction::Ribbon, ui.ctx()) { + app.set_status(format!("Panel move was not applied: {error}")); + } + continue; + } if let Err(error) = serde_json::to_value(action).map_err(|error| error.to_string()).and_then(|action| command(app, false, &json!({"action": action}))) { @@ -397,3 +407,165 @@ fn panel_limits(panel: &Panel) -> PanelLimits { }; PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) } } + +/// Where the Tool Sets palette is: shown as a ribbon under the menu bar, floating, pinned in a +/// column of its own (left of the drawing by default), in a group with other palettes, or closed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToolSetsPlace { + Ribbon, + Floating, + Pinned, + Grouped, + Closed, +} + +/// What the Tool Sets right-click menu asks for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToolSetsAction { + Float, + PinLeft, + Ribbon, + /// Into the group (tabs or stack) that holds this panel. + Group(Panel), + Close, +} + +/// Every panel of a node, in order. +fn node_panels(node: &Node, out: &mut Vec) { + match node { + Node::Split { first, second, .. } => { + node_panels(first, out); + node_panels(second, out); + } + Node::Tabs { panels, .. } => out.extend(panels.iter().copied()), + Node::Stack { entries } => out.extend(entries.iter().map(|e| e.panel)), + } +} + +/// The groups (tab groups, stacks and floating groups) of a layout, each as its panels. +fn groups(layout: &Layout) -> Vec> { + fn walk(node: &Node, out: &mut Vec>) { + match node { + Node::Split { first, second, .. } => { + walk(first, out); + walk(second, out); + } + Node::Tabs { panels, .. } => out.push(panels.clone()), + Node::Stack { entries } => out.push(entries.iter().map(|e| e.panel).collect()), + } + } + let mut out = Vec::new(); + if let Some(root) = &layout.root { + walk(root, &mut out); + } + out.extend(layout.floating.iter().map(|g| g.panels.clone())); + out +} + +pub fn toolsets_place(app: &crate::CadApp) -> ToolSetsPlace { + if !app.ui.show_toolsets { + return ToolSetsPlace::Closed; + } + if app.ui.toolsets_ribbon { + return ToolSetsPlace::Ribbon; + } + let layout = &app.ui.docking.layout; + if layout.floating.iter().any(|g| g.panels.contains(&Panel::ToolSets)) { + return ToolSetsPlace::Floating; + } + match groups(layout).into_iter().find(|g| g.contains(&Panel::ToolSets)) { + Some(g) if g.len() > 1 => ToolSetsPlace::Grouped, + _ => ToolSetsPlace::Pinned, + } +} + +/// The groups Tool Sets can join: (a member to join beside, the group's name). +pub fn toolsets_groups(app: &crate::CadApp) -> Vec<(Panel, String)> { + groups(&app.ui.docking.layout) + .into_iter() + .filter(|g| !g.contains(&Panel::ToolSets) && !g.contains(&Panel::Canvas)) + .filter_map(|g| { + let first = *g.first()?; + let name = g.iter().map(|p| crate::i18n::t(p.label()).to_string()).collect::>().join(" / "); + Some((first, name)) + }) + .collect() +} + +/// The Tool Sets right-click menu: every place but the one it is in now. +pub fn toolsets_menu(ui: &mut egui::Ui, place: ToolSetsPlace, groups: &[(Panel, String)], out: &mut Option) { + let item = |ui: &mut egui::Ui, label: &str, action: ToolSetsAction, out: &mut Option| { + if ui.button(crate::i18n::t(label)).clicked() { + *out = Some(action); + ui.close(); + } + }; + if place != ToolSetsPlace::Floating { + item(ui, "Float Panel", ToolSetsAction::Float, out); + } + if place != ToolSetsPlace::Pinned { + item(ui, "Pin to Left", ToolSetsAction::PinLeft, out); + } + if place != ToolSetsPlace::Ribbon { + item(ui, "Transform to Ribbon", ToolSetsAction::Ribbon, out); + } + if !groups.is_empty() { + ui.menu_button(crate::i18n::t("Move to Group"), |ui| { + for (panel, name) in groups { + if ui.button(crate::i18n::widget(ui, name, egui::TextStyle::Button)).clicked() { + *out = Some(ToolSetsAction::Group(*panel)); + ui.close(); + } + } + }); + } + item(ui, "Close Panel", ToolSetsAction::Close, out); +} + +/// Width of Tool Sets pinned on the left. +const PINNED_WIDTH: f32 = 220.0; + +/// Carry out a Tool Sets menu choice. +pub fn apply_toolsets(app: &mut crate::CadApp, action: ToolSetsAction, ctx: &egui::Context) -> Result<(), String> { + if action == ToolSetsAction::Close { + app.ui.show_toolsets = false; + return Ok(()); + } + app.ui.show_toolsets = true; + app.ui.toolsets_ribbon = action == ToolSetsAction::Ribbon; + let mut workspace = app.ui.docking.clone(); + sync(&mut workspace, app)?; + match action { + ToolSetsAction::Ribbon | ToolSetsAction::Close => {} + ToolSetsAction::Float => { + let screen = ctx.content_rect(); + let rect = [screen.left() + 60.0, screen.top() + 140.0, 240.0, (screen.height() - 220.0).clamp(240.0, 640.0)]; + workspace.apply(Action::Float { panel: Panel::ToolSets, rect })?; + } + ToolSetsAction::Group(anchor) => { + workspace.apply(Action::Move { panel: Panel::ToolSets, anchor, placement: Placement::Split(Zone::Center) })?; + } + ToolSetsAction::PinLeft => { + // Out of where it is, then back in as a column left of everything docked. + workspace.apply(Action::Close { panel: Panel::ToolSets })?; + let mut sibling = Vec::new(); + if let Some(root) = &workspace.layout.root { + node_panels(root, &mut sibling); + } + let location = Location { + floating: None, + anchor: Some(Panel::Canvas), + placement: Placement::Split(Zone::Left), + size: Some(SplitSize::FixedFirst(PINNED_WIDTH)), + stack: None, + sibling, + }; + workspace.hidden.retain(|(p, _)| *p != Panel::ToolSets); + workspace.hidden.push((Panel::ToolSets, location)); + workspace.set_visible(Panel::ToolSets, true)?; + } + } + publish_visibility(app, &workspace); + app.ui.docking = workspace; + Ok(()) +} diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index d78464b58f..acc7c2f79e 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -176,6 +176,7 @@ mod tests { b.borrow_mut().push(name.to_string()); None })), + pick_folder: None, }; (CadApp::new(Session::new(), services), asked) } diff --git a/crates/ui-egui/src/hatchdlg.rs b/crates/ui-egui/src/hatchdlg.rs index 7388e5a604..769b79e9d0 100644 --- a/crates/ui-egui/src/hatchdlg.rs +++ b/crates/ui-egui/src/hatchdlg.rs @@ -22,6 +22,10 @@ pub(crate) const ORIGIN_MODES: [&str; 5] = ["bottomLeft", "bottomRight", "topRig #[derive(Clone, Debug, PartialEq)] pub struct Fill { pub gradient: bool, + /// The Custom Patterns tab is open (a pattern from a `.pat` file in the user's folder). + pub custom: bool, + /// The `.pat` file of a custom pattern: loaded when OK is pressed. + pub pattern_file: Option, pub pattern: String, pub scale: f64, /// Pattern or gradient angle, degrees. @@ -76,6 +80,8 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState { let origin_mode = mode.checked_sub(1).and_then(|i| usize::try_from(i).ok()).and_then(|i| ORIGIN_MODES.get(i)).copied().unwrap_or("bottomLeft"); let fill = Fill { gradient, + custom: false, + pattern_file: None, pattern: h.str("HPNAME", "ANSI31"), scale, angle, @@ -347,6 +353,16 @@ pub fn resume(app: &mut CadApp) { /// OK: run the dialog's command. True when the dialog closes; a failed command keeps it open /// with the error (the drawing is unchanged). pub fn ok(app: &mut CadApp) -> bool { + // A custom pattern joins the pattern list from its file first. + let file = app.hatch_dlg.as_ref().filter(|st| st.fill.custom && !st.fill.gradient).and_then(|st| st.fill.pattern_file.clone()); + if let Some(file) = file + && let Err(e) = app.run("hatch.patterns", json!({ "file": file })) + { + if let Some(st) = app.hatch_dlg.as_mut() { + st.error = Some(e); + } + return false; + } let Some(call) = app.hatch_dlg.as_ref().map(ok_call) else { return true }; let Some((cmd, p)) = call else { app.hatch_dlg = None; @@ -371,6 +387,8 @@ enum Action { Ok, Cancel, Pick(PickMode), + /// Choose the Custom Patterns folder. + BrowseFolder, } fn shape_label(name: &str) -> &'static str { @@ -412,11 +430,13 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }; let title = if st.edit.is_empty() { crate::tl!("Hatch and Gradient") } else { crate::tl!("Hatch Edit") }; let mut action = Action::None; + let mut folder = app.ui.pattern_folder.clone(); + let can_browse = app.services.pick_folder.is_some(); egui::Window::new(title).id(egui::Id::new("hatch_dialog")).open(open).collapsible(false).resizable(false).show(ctx, |ui| { ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(340.0); - fill_ui(ui, &mut st.fill, &mut action); + ui.set_width(if st.fill.custom { 400.0 } else { 340.0 }); + fill_ui(ui, &mut st.fill, &mut action, &mut folder, can_browse); }); // Space, not a vertical separator: a separator takes the height available, and the // window grew by it every frame until the buttons left the screen. @@ -441,6 +461,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }); }); app.hatch_dlg = Some(st); + app.ui.pattern_folder = folder; match action { Action::Ok => { if ok(app) { @@ -452,6 +473,12 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { *open = false; } Action::Pick(mode) => start_pick(app, mode), + Action::BrowseFolder => { + if let Some(dir) = app.services.pick_folder.as_ref().and_then(|pick| pick()) { + app.ui.pattern_folder = dir; + crate::custom_patterns::reload(); + } + } Action::None => { if !*open { app.hatch_dlg = None; @@ -460,13 +487,37 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action) { +fn fill_ui(ui: &mut egui::Ui, f: &mut Fill, action: &mut Action, folder: &mut String, can_browse: bool) { ui.horizontal(|ui| { - ui.selectable_value(&mut f.gradient, false, crate::tl!("Pattern")); - ui.selectable_value(&mut f.gradient, true, crate::tl!("Gradient")); + if ui.selectable_label(!f.gradient && !f.custom, crate::tl!("Pattern")).clicked() { + f.gradient = false; + f.custom = false; + } + if ui.selectable_label(f.gradient, crate::tl!("Gradient")).clicked() { + f.gradient = true; + f.custom = false; + } + if ui.selectable_label(!f.gradient && f.custom, crate::tl!("Custom Patterns")).clicked() { + f.gradient = false; + f.custom = true; + } }); ui.separator(); - if f.gradient { + if f.custom && !f.gradient { + if let crate::custom_patterns::TabAction::Browse = crate::custom_patterns::tab_ui(ui, folder, &mut f.pattern, &mut f.pattern_file, can_browse) + { + *action = Action::BrowseFolder; + } + ui.add_space(4.0); + egui::Grid::new("hatch_custom_pattern").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { + ui.label(crate::tl!("Angle")); + ui.add(egui::DragValue::new(&mut f.angle).speed(1.0).range(-360.0..=360.0).clamp_existing_to_range(false).suffix("°")); + ui.end_row(); + ui.label(crate::tl!("Scale")); + ui.add(egui::DragValue::new(&mut f.scale).speed(0.05).range(0.0001..=1.0e6).clamp_existing_to_range(false)); + ui.end_row(); + }); + } else if f.gradient { egui::Grid::new("hatch_gradient").num_columns(2).spacing(vec2(12.0, 6.0)).show(ui, |ui| { ui.label(crate::tl!("Color 1")); if let Some(c) = crate::layers::color_button(ui, egui::Id::new("hatch_color1"), f.color1, false, 160.0) { diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 9c10511a7e..44635be832 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -353,3 +353,111 @@ macro_rules! tf { #[cfg(test)] mod tests; + +/// Whether `c` is written right to left (Hebrew, Arabic). +fn is_rtl(c: char) -> bool { + matches!(u32::from(c), 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF) +} + +/// Whether `s` holds right-to-left letters, so it needs [`job`] to be drawn in reading order. +pub fn has_rtl(s: &str) -> bool { + s.chars().any(is_rtl) +} + +/// Whether `c` attaches to the letter before it (combining marks, Hebrew points, joiners). +fn is_mark(c: char) -> bool { + matches!(u32::from(c), 0x0300..=0x036F | 0x0591..=0x05BD | 0x05BF | 0x05C1..=0x05C2 | 0x05C4..=0x05C5 | 0x05C7 | 0x0610..=0x061A | 0x064B..=0x065F | 0x0670 | 0x200C..=0x200D | 0xFE00..=0xFE0F | 0xFE20..=0xFE2F) +} + +/// The pieces of `s` in display order for a left-to-right line, each to be shaped on its own: +/// left-to-right runs whole, right-to-left runs letter by letter (with their marks) reversed and +/// brackets mirrored. The text shaper turns any piece holding a right-to-left letter around, and +/// with a font that covers Latin and Hebrew alike (Segoe UI) it would turn the whole name +/// (extension included) around; one letter per piece leaves nothing to turn. +fn display_pieces(s: &str) -> Vec { + let chars: Vec = s.chars().collect(); + let mut out = Vec::new(); + for (r, rtl) in cadcraft_fonts::bidi::visual_runs(&chars, Some(false)) { + let run = chars.get(r).unwrap_or_default(); + if !rtl { + out.push(run.iter().collect()); + continue; + } + let mut clusters: Vec = Vec::new(); + for c in run { + match clusters.last_mut() { + Some(last) if is_mark(*c) => last.push(*c), + _ => clusters.push(cadcraft_fonts::bidi::mirror(*c).to_string()), + } + } + out.extend(clusters.into_iter().rev()); + } + out +} + +/// `s` (a file, drawing, block or layer name…) laid out on one line in reading order: right-to-left +/// runs read as they do in the file manager, `שלום.dwg` with the extension on the right. +pub fn job(s: &str, font: egui::FontId, color: egui::Color32) -> egui::text::LayoutJob { + if !has_rtl(s) { + return egui::text::LayoutJob::simple_singleline(s.to_string(), font, color); + } + // Sections pushed one by one: `append` would merge them back into one (same format), and the + // shaper works section by section. + let mut job = egui::text::LayoutJob::default(); + for piece in display_pieces(s) { + let start = job.text.len(); + job.text.push_str(&piece); + job.sections.push(egui::text::LayoutSection { + leading_space: 0.0, + byte_range: egui::text::ByteIndex(start)..egui::text::ByteIndex(job.text.len()), + format: egui::TextFormat::simple(font.clone(), color), + }); + } + job +} + +/// `s` as widget text (button, label, menu item) in reading order; the widget's own colour. +pub fn widget(ui: &egui::Ui, s: &str, style: egui::TextStyle) -> egui::WidgetText { + if !has_rtl(s) { + return s.to_string().into(); + } + egui::WidgetText::from(job(s, style.resolve(ui.style()), egui::Color32::PLACEHOLDER)) +} + +/// Paints `s` in reading order, anchored like [`egui::Painter::text`]; returns its rectangle. +pub fn paint(p: &egui::Painter, pos: egui::Pos2, anchor: egui::Align2, s: &str, font: egui::FontId, color: egui::Color32) -> egui::Rect { + let galley = p.layout_job(job(s, font, color)); + let rect = anchor.anchor_size(pos, galley.size()); + p.galley(rect.min, galley, color); + rect +} + +/// `s` in display order as one plain string, for tests and logs (what [`job`] shows). +pub fn ltr(s: &str) -> std::borrow::Cow<'_, str> { + if !has_rtl(s) { + return std::borrow::Cow::Borrowed(s); + } + std::borrow::Cow::Owned(display_pieces(s).concat()) +} + +#[cfg(test)] +mod ltr_tests { + #[test] + fn hebrew_file_names_keep_the_extension_on_the_right() { + assert_eq!(super::ltr("שלום.dwg"), "םולש.dwg"); + assert_eq!(super::ltr("plan 2.dwg"), "plan 2.dwg"); + assert_eq!(super::ltr("תוכנית קומה 1.dwg"), "1 המוק תינכות.dwg"); + } + + #[test] + fn every_right_to_left_letter_is_shaped_alone() { + // Pieces: each Hebrew letter by itself, the extension whole, so the shaper (which turns + // any piece holding Hebrew around) cannot reverse the name or its extension. + assert_eq!(super::display_pieces("שלום.dwg"), ["ם", "ו", "ל", "ש", ".dwg"]); + assert_eq!(super::display_pieces("plan.dwg"), ["plan.dwg"]); + // Points stay on their letter. + assert_eq!(super::display_pieces("שָׁלוֹם"), ["ם", "וֹ", "ל", "שָׁ"]); + let job = super::job("שלום.dwg", egui::FontId::proportional(12.0), egui::Color32::WHITE); + assert_eq!(job.sections.len(), 5); + } +} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f6b1ae7315..a145f72912 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1008,3 +1008,344 @@ Sheet Books to PDF... Книги листов в PDF... Not a number or distance: {text} Не число и не расстояние: {text} Query Texts Запрос текстов + Add Separator Добавить разделитель + Add to Tool Bar Добавить на панель инструментов + Alias: Псевдоним: + Command: Команда: + Commands Команды + Customize Tool Bar Настройка панели инструментов + Customize Tool Bar... Настроить панель инструментов... + Dock Tool Bar Закрепить панель инструментов + Dock at Left Закрепить слева + Dock at Top Закрепить сверху + Drag buttons along the Tool Bar to reorder them, or its handle to dock it. Перетаскивайте кнопки вдоль панели, чтобы изменить их порядок, а маркер панели — чтобы закрепить её. + Drag to dock the Tool Bar at the top or on the left Перетащите, чтобы закрепить панель инструментов сверху или слева + Hide Tool Bar Скрыть панель инструментов + Left (column) Слева (столбец) + More toolbar commands Другие команды панели инструментов + Move Down Вниз + Move Tool Bar Button Переместить кнопку панели инструментов + Move Up Вверх + Position: Положение: + Remove from Tool Bar Убрать с панели инструментов + Reset Tool Bar Сбросить панель инструментов + Reset to Default По умолчанию + Search: Поиск: + Separator Разделитель + Shortcut: Клавиши: + Show Tool Bar Показывать панель инструментов + Tool Bar Position Положение панели инструментов + Tool Bar buttons Кнопки панели инструментов + Top Сверху + Top (row) Сверху (строка) + Standard Tool Bar Стандартная панель + Tool Sets Tool Bar Панель «Наборы инструментов» + Layers Tool Bar Панель «Слои» + More Tool Sets bar commands Другие команды панели «Наборы инструментов» + More Layers bar commands Другие команды панели «Слои» + Current layer: Текущий слой: + Tool Bar: Панель: + Tool Bars Панели инструментов + Show on Tool Bar Показывать на панели + Current Layer Текущий слой + Options Параметры + Options... Параметры... + Display Экран + Open and Save Открытие и сохранение + Selection Выбор + User Preferences Пользовательские настройки + Profiles Профили + Changes apply at once and are kept for next time. Изменения применяются сразу и сохраняются до следующего запуска. + Fonts Шрифты + Font folders Папки шрифтов + Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Положите шрифты TrueType или OpenType (.ttf, .otf, .ttc) в папку и добавьте её сюда. Эти папки просматриваются раньше системных шрифтов; папка выше в списке имеет приоритет. + No font folders yet Папок шрифтов пока нет + This folder does not exist Такой папки нет + Add Folder... Добавить папку... + Folder path Путь к папке + Look for Fonts Again Найти шрифты заново + After adding or removing font files in a folder После добавления или удаления файлов шрифтов в папке + Fonts found in these folders: Шрифтов найдено в этих папках: + Every font this drawing uses was found. Все шрифты этого чертежа найдены. + Fonts this drawing uses that were not found: Шрифты чертежа, которые не найдены: + style стиль + Fonts not found: Не найдены шрифты: + Text in them is drawn with Текст в них рисуется шрифтом + Add a font folder in Tools ▸ Options ▸ Fonts. Добавьте папку шрифтов: Инструменты ▸ Параметры ▸ Шрифты. + Cell Ячейка + Tab: next cell · Shift+Tab: previous · Alt+↑↓: cell above, below Tab — следующая ячейка · Shift+Tab — предыдущая · Alt+↑↓ — ячейка выше, ниже + Tab: next cell Tab — следующая ячейка + Previous cell (Shift+Tab) Предыдущая ячейка (Shift+Tab) + Next cell (Tab) Следующая ячейка (Tab) + Enter to finish Enter — завершить + the measured value измеренное значение + Insert <> Вставить <> + Insert the measured value at the cursor Вставить измеренное значение в позицию курсора + Measured Value Only Только измеренное + Replace the text with the measured value Заменить текст измеренным значением + Missing Fonts Отсутствующие шрифты + List Fonts Список шрифтов + Edit Text Редактировать текст + Edit Table Cells Редактировать ячейки таблицы + Dimension Text Текст размера + Align left По левому краю + Align right По правому краю + Justify По ширине + Additional symbols Дополнительные символы + Close (same as Cancel) Закрыть (то же, что «Отмена») + Center line Осевая линия + Almost equal Приблизительно равно + Not equal Не равно + Less than or equal Меньше или равно + Greater than or equal Больше или равно + Multiplication Умножение + Division Деление + Square root Квадратный корень + Infinity Бесконечность + Delta Дельта + Ohm Ом + Micro Микро + Pi Пи + Alpha Альфа + Beta Бета + Gamma Гамма + Phi Фи + Squared В квадрате + Cubed В кубе + One half Одна вторая + One quarter Одна четвёртая + Three quarters Три четверти + Per mille Промилле + Bullet Маркер + Number sign Знак номера + Insert tab Вставить табуляцию + Text color Цвет текста + Application menu Меню приложения + Batch Print... Пакетная печать... + A style with this name already exists. Стиль с таким именем уже есть. + Above Над линией + Above Dim Line Над размерной линией + Above dimension text Над текстом размера + Aligned with dimension line Вдоль размерной линии + Alignment Ориентация + All styles Все стили + Alt enabled Альт. единицы + Alt format Альт. формат + Alt multiplier Альт. множитель + Alt precision Альт. точность + Alt prefix Альт. префикс + Alt round Альт. округление + Alt suffix Альт. суффикс + Alternate Units Альтернативные единицы + Alternate units Альтернативные единицы + Always keep text between ext lines Всегда помещать текст между выносными + Angle format Формат углов + Angle precision Точность углов + Angular dimensions Угловые размеры + Annotative Аннотативный + Arc length symbol Символ длины дуги + Architectural Архитектурные + Architectural Stacked Архитектурные (дробь) + Architectural tick Архитектурная засечка + Arrow 1 Стрелка 1 + Arrow 2 Стрелка 2 + Arrow size Размер стрелки + Arrowheads Стрелки + Arrows Стрелки + At Ext Line 1 У 1-й выносной + At Ext Line 2 У 2-й выносной + Baseline spacing Шаг в базовых размерах + Basic Номинальный + Below Под линией + Beside the dimension line Рядом с размерной линией + Both text and arrows Текст и стрелки + Bottom Снизу + Box filled Квадрат залитый + Center Vertically По центру по вертикали + Center marks Маркеры центра + Centered По центру + Closed blank Замкнутая пустая + Closed filled Замкнутая залитая + Compare Dimension Styles Сравнение размерных стилей + Compare... Сравнить... + Compare: Сравнить: + Copy of Копия + Create New Dimension Style Новый размерный стиль + Current dimension style: Текущий размерный стиль: + Datum triangle Треугольник базы + Datum triangle filled Треугольник базы залитый + Decimal Десятичные + Decimal Degrees Десятичные градусы + Decimal separator Десятичный разделитель + Degrees Minutes Seconds Градусы/минуты/секунды + Deviation Отклонения + Diagonal Диагональная + Differences found: Найдено отличий: + Dim line 1 Разм. линия 1 скрыта + Dim line 2 Разм. линия 2 скрыта + Dim line color Цвет разм. линии + Dim line inside Разм. линия внутри + Dim line lineweight Вес разм. линии + Dim prefix Префикс + Dim roundoff Округление + Dim scale linear Масштаб измерений + Dim scale overall Глобальный масштаб + Dim suffix Суффикс + Dim units Единицы + Dimension Style Manager Диспетчер размерных стилей + Dimension lines Размерные линии + Display alternate units Показывать альтернативные единицы + Dot Точка + Dot blank Точка пустая + Dot small Точка малая + Dot small blank Точка малая пустая + Draw dim line between ext lines Размерная линия между выносными + Draw frame around text Рамка вокруг текста + Either text or arrows (best fit) Текст или стрелки (оптимально) + Engineering Инженерные + Ext line 1 Выносная 1 скрыта + Ext line 2 Выносная 2 скрыта + Ext line color Цвет выносных + Ext line ext Удлинение выносных + Ext line fixed Фикс. длина выносных + Ext line fixed length Длина выносных + Ext line lineweight Вес выносных + Ext line offset Отступ выносных + Extend beyond dim lines Удлинение за размерные + Extend beyond ticks Удлинение за засечки + Extension lines Выносные линии + Fine tuning Подгонка элементов + Fit Размещение + Fit options Опции размещения + Fixed length extension lines Выносные линии фикс. длины + Fraction format Формат дробей + Fraction height scale Масштаб высоты дробей + Fractional Дробные + Fractional Stacked Дробные (дробь) + Gradians Грады + ISO standard Согласно ISO + Integral Интеграл + JIS JIS + Jog angle Угол излома + Limits Предельные размеры + Linear dimensions Линейные размеры + Lines Линии + Lines & Arrows Линии и стрелки + Linetype ext line 1 Тип выносной 1 + Linetype ext line 2 Тип выносной 2 + List: Показать: + Lower value Нижнее значение + Mark Маркер + Measurement scale factor Масштаб измерений + Method Способ + Middle Посередине + Modify Dimension Style: Изменение размерного стиля: + Modify... Изменить... + Move Text Only Переместить только текст + Move outside the extension lines Выносить за выносные линии + Move with Dim Line Переместить с размерной линией + Move with Leader Переместить с выноской + Multiplier for alt units Множитель альт. единиц + New Dimension Style: Новый размерный стиль: + New Style Name: Имя нового стиля: + New... Новый... + Not Stacked Не в столбик + Oblique Наклонная + Offset from dim line Отступ от размерной линии + Offset from origin Отступ от объекта + Open Разомкнутая + Open 30 Разомкнутая 30 + Origin indicator Начало отсчёта + Origin indicator 2 Начало отсчёта 2 + Outside Снаружи + Over Ext Line 1 Над 1-й выносной + Over Ext Line 2 Над 2-й выносной + Over dimension line, with leader Над размерной линией, с выноской + Over dimension line, without leader Над размерной линией, без выноски + Override Current Style: Переопределение текущего стиля: + Override... Переопределить... + Overrides apply to new dimensions in the current style. Переопределения применяются к новым размерам текущего стиля. + Overrides apply to the current style Переопределения задаются для текущего стиля + Preceding dimension text Перед текстом размера + Precision Точность + Prefix Префикс + Preview of: Образец: + Primary Units Основные единицы + Radians Радианы + Radius jog dimension Радиус с изломом + Rename Переименовать + Reset Text Position Восстановить положение текста + Right angle Прямой угол + Round distances to Округлять до + Round off Округление + Scale for dimension features Масштаб размерных элементов + Scaling for height Масштаб высоты + Scientific Научные + Second Вторая + Size Размер + Start With: На основе: + Styles in use Используемые стили + Styles: Стили: + Suffix Суффикс + Suppress arrows if they don't fit inside Подавлять стрелки, если не помещаются + Suppress dim line 1 Скрыть размерную линию 1 + Suppress dim line 2 Скрыть размерную линию 2 + Suppress ext line 1 Скрыть выносную 1 + Suppress ext line 2 Скрыть выносную 2 + Suppress leading zeros Подавлять ведущие нули + Suppress trailing zeros Подавлять хвостовые нули + Symbols and Arrows Символы и стрелки + Symmetrical Симметрично + Text alignment Ориентация текста + Text appearance Свойства текста + Text frame Рамка текста + Text inside Текст внутри + Text movement Перемещение текста + Text offset Отступ текста + Text placement Выравнивание текста + Text pos hor Текст по горизонтали + Text pos vert Текст по вертикали + The two styles are the same. Стили совпадают. + Tick size Размер засечки + Tolerance display Отображение допуска + Tolerance format Формат допусков + Tolerance limit lower Нижний допуск + Tolerance limit upper Верхний допуск + Tolerance pos vert Положение допуска + Tolerance precision Точность допуска + Tolerance text height Высота текста допуска + Tolerances Допуски + Unit format Формат единиц + Units format Формат единиц + Upper value Верхнее значение + Use overall scale of Глобальный масштаб + Variable Переменная + Vertical position Положение по вертикали + When text is not in the default position Если текст не в стандартном положении + Windows Desktop Как в Windows + With: С: + overrides переопределений + Measurement Значение + User Arrow: Пользовательская: + Leaders Выноски + Leader type Тип выноски + Arrowhead Стрелка + Arrowhead size Размер стрелки + Landing distance Длина полки + Straight Прямая + Annotate Аннотации + 3D Modeling 3D-моделирование + Float Panel Плавающая панель + Pin to Left Закрепить слева + Transform to Ribbon Превратить в ленту + Move to Group Переместить в группу + Close Panel Закрыть панель + Custom Patterns Свои образцы + Folder with hatch pattern files (.pat): Папка с файлами образцов штриховки (.pat): + Browse... Обзор... + Reload Обновить + Read the folder again Прочитать папку заново + No hatch patterns (.pat files) in this folder В этой папке нет образцов штриховки (файлов .pat) + Preview Предпросмотр + Black Чёрная + Light Blue Светло-голубая diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 15de435a8b..74eaacf223 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -91,6 +91,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { include_str!("../xrefs.rs"), include_str!("../canvas.rs"), include_str!("../chrome.rs"), + include_str!("../toolbar.rs"), include_str!("../cmdline.rs"), include_str!("../credits.rs"), include_str!("../palettes/quickcalc.rs"), diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index adce43ae73..6cfdb18d9d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1330,3 +1330,327 @@ Justify За шириною Text color Колір тексту Click the ruler to add a tab stop, right-click to remove one Натисніть на лінійку, щоб додати табуляцію; права кнопка видаляє її + Add Separator Додати роздільник + Add to Tool Bar Додати на панель інструментів + Alias: Псевдонім: + Command: Команда: + Commands Команди + Customize Tool Bar Налаштування панелі інструментів + Customize Tool Bar... Налаштувати панель інструментів... + Dock Tool Bar Закріпити панель інструментів + Dock at Left Закріпити ліворуч + Dock at Top Закріпити зверху + Drag buttons along the Tool Bar to reorder them, or its handle to dock it. Перетягуйте кнопки вздовж панелі, щоб змінити їх порядок, а маркер панелі — щоб закріпити її. + Drag to dock the Tool Bar at the top or on the left Перетягніть, щоб закріпити панель інструментів зверху або ліворуч + Hide Tool Bar Сховати панель інструментів + Left (column) Ліворуч (стовпчик) + Move Down Вниз + Move Tool Bar Button Перемістити кнопку панелі інструментів + Move Up Вгору + Position: Розташування: + Remove from Tool Bar Прибрати з панелі інструментів + Reset Tool Bar Скинути панель інструментів + Reset to Default Скинути до типових + Search: Пошук: + Separator Роздільник + Shortcut: Клавіші: + Show Tool Bar Показувати панель інструментів + Tool Bar Position Розташування панелі інструментів + Tool Bar buttons Кнопки панелі інструментів + Top Зверху + Top (row) Зверху (рядок) + Standard Tool Bar Стандартна панель інструментів + Tool Sets Tool Bar Панель «Набори інструментів» + Layers Tool Bar Панель «Шари» + More Tool Sets bar commands Інші команди панелі «Набори інструментів» + More Layers bar commands Інші команди панелі «Шари» + Current layer: Поточний шар: + Tool Bar: Панель: + Tool Bars Панелі інструментів + Show on Tool Bar Показувати на панелі + Current Layer Поточний шар + Fonts Шрифти + Font folders Теки шрифтів + Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Покладіть шрифти TrueType або OpenType (.ttf, .otf, .ttc) у теку й додайте її сюди. Ці теки переглядаються раніше за системні шрифти; тека вище у списку має пріоритет. + No font folders yet Тек шрифтів ще немає + This folder does not exist Такої теки немає + Add Folder... Додати теку... + Folder path Шлях до теки + Look for Fonts Again Знайти шрифти знову + After adding or removing font files in a folder Після додавання чи вилучення файлів шрифтів у теці + Fonts found in these folders: Шрифтів знайдено в цих теках: + Every font this drawing uses was found. Усі шрифти цього креслення знайдено. + Fonts this drawing uses that were not found: Шрифти креслення, яких не знайдено: + style стиль + Fonts not found: Не знайдено шрифтів: + Text in them is drawn with Текст у них малюється шрифтом + Add a font folder in Tools ▸ Options ▸ Fonts. Додайте теку шрифтів: Інструменти ▸ Параметри ▸ Шрифти. + Cell Комірка + Tab: next cell · Shift+Tab: previous · Alt+↑↓: cell above, below Tab — наступна комірка · Shift+Tab — попередня · Alt+↑↓ — комірка вище, нижче + Tab: next cell Tab — наступна комірка + Previous cell (Shift+Tab) Попередня комірка (Shift+Tab) + Next cell (Tab) Наступна комірка (Tab) + Enter to finish Enter — завершити + the measured value виміряне значення + Insert <> Вставити <> + Insert the measured value at the cursor Вставити виміряне значення в позицію курсора + Measured Value Only Лише виміряне + Replace the text with the measured value Замінити текст виміряним значенням + Missing Fonts Відсутні шрифти + List Fonts Список шрифтів + Edit Text Редагувати текст + Edit Table Cells Редагувати комірки таблиці + Dimension Text Текст розміру + Align left За лівим краєм + Align right За правим краєм + Additional symbols Додаткові символи + Close (same as Cancel) Закрити (те саме, що «Скасувати») + Center line Осьова лінія + Almost equal Приблизно дорівнює + Not equal Не дорівнює + Less than or equal Менше або дорівнює + Greater than or equal Більше або дорівнює + Multiplication Множення + Division Ділення + Square root Квадратний корінь + Infinity Нескінченність + Delta Дельта + Ohm Ом + Micro Мікро + Pi Пі + Alpha Альфа + Beta Бета + Gamma Гамма + Phi Фі + Squared У квадраті + Cubed У кубі + One half Одна друга + One quarter Одна четверта + Three quarters Три чверті + Per mille Проміле + Bullet Маркер + Number sign Знак номера + Application menu Меню програми + Batch Print... Пакетний друк... + A style with this name already exists. Стиль із такою назвою вже є. + Above Над лінією + Above Dim Line Над розмірною лінією + Above dimension text Над текстом розміру + Aligned with dimension line Уздовж розмірної лінії + Alignment Орієнтація + All styles Усі стилі + Alt enabled Альт. одиниці + Alt format Альт. формат + Alt multiplier Альт. множник + Alt precision Альт. точність + Alt prefix Альт. префікс + Alt round Альт. округлення + Alt suffix Альт. суфікс + Alternate Units Альтернативні одиниці + Alternate units Альтернативні одиниці + Always keep text between ext lines Завжди розміщувати текст між виносними + Angle format Формат кутів + Angle precision Точність кутів + Angular dimensions Кутові розміри + Annotative Анотативний + Arc length symbol Символ довжини дуги + Architectural Архітектурні + Architectural Stacked Архітектурні (дріб) + Architectural tick Архітектурна засічка + Arrow 1 Стрілка 1 + Arrow 2 Стрілка 2 + Arrow size Розмір стрілки + Arrowheads Стрілки + Arrows Стрілки + At Ext Line 1 Біля 1-ї виносної + At Ext Line 2 Біля 2-ї виносної + Baseline spacing Крок базових розмірів + Basic Номінальний + Below Під лінією + Beside the dimension line Поруч із розмірною лінією + Both text and arrows Текст і стрілки + Bottom Знизу + Box filled Квадрат залитий + Center Vertically По центру по вертикалі + Center marks Маркери центру + Closed blank Замкнена порожня + Closed filled Замкнена залита + Compare Dimension Styles Порівняння розмірних стилів + Compare... Порівняти... + Compare: Порівняти: + Copy of Копія + Create New Dimension Style Новий розмірний стиль + Current dimension style: Поточний розмірний стиль: + Datum triangle Трикутник бази + Datum triangle filled Трикутник бази залитий + Decimal Десяткові + Decimal Degrees Десяткові градуси + Decimal separator Десятковий роздільник + Degrees Minutes Seconds Градуси/хвилини/секунди + Deviation Відхилення + Diagonal Діагональна + Differences found: Знайдено відмінностей: + Dim line 1 Розм. лінія 1 прихована + Dim line 2 Розм. лінія 2 прихована + Dim line color Колір розм. лінії + Dim line inside Розм. лінія всередині + Dim line lineweight Вага розм. лінії + Dim prefix Префікс + Dim roundoff Округлення + Dim scale linear Масштаб вимірів + Dim scale overall Глобальний масштаб + Dim suffix Суфікс + Dim units Одиниці + Dimension Style Manager Диспетчер розмірних стилів + Dimension lines Розмірні лінії + Display alternate units Показувати альтернативні одиниці + Dot Точка + Dot blank Точка порожня + Dot small Точка мала + Dot small blank Точка мала порожня + Draw dim line between ext lines Розмірна лінія між виносними + Draw frame around text Рамка навколо тексту + Either text or arrows (best fit) Текст або стрілки (оптимально) + Engineering Інженерні + Ext line 1 Виносна 1 прихована + Ext line 2 Виносна 2 прихована + Ext line color Колір виносних + Ext line ext Подовження виносних + Ext line fixed Фікс. довжина виносних + Ext line fixed length Довжина виносних + Ext line lineweight Вага виносних + Ext line offset Відступ виносних + Extend beyond dim lines Подовження за розмірні + Extend beyond ticks Подовження за засічки + Extension lines Виносні лінії + Fine tuning Припасування + Fit Розміщення + Fit options Параметри розміщення + Fixed length extension lines Виносні лінії фікс. довжини + Fraction format Формат дробів + Fraction height scale Масштаб висоти дробів + Fractional Дробові + Fractional Stacked Дробові (дріб) + Gradians Гради + ISO standard Згідно з ISO + Integral Інтеграл + JIS JIS + Jog angle Кут зламу + Limits Граничні розміри + Linear dimensions Лінійні розміри + Lines Лінії + Lines & Arrows Лінії та стрілки + Linetype ext line 1 Тип виносної 1 + Linetype ext line 2 Тип виносної 2 + List: Показати: + Lower value Нижнє значення + Mark Маркер + Measurement scale factor Масштаб вимірів + Method Спосіб + Middle Посередині + Modify Dimension Style: Зміна розмірного стилю: + Modify... Змінити... + Move Text Only Перемістити лише текст + Move outside the extension lines Виносити за виносні лінії + Move with Dim Line Перемістити з розмірною лінією + Move with Leader Перемістити з виноскою + Multiplier for alt units Множник альт. одиниць + New Dimension Style: Новий розмірний стиль: + New Style Name: Назва нового стилю: + New... Новий... + Not Stacked Не в стовпчик + Offset from dim line Відступ від розмірної лінії + Offset from origin Відступ від об'єкта + Open 30 Розімкнена 30 + Origin indicator Початок відліку + Origin indicator 2 Початок відліку 2 + Outside Ззовні + Over Ext Line 1 Над 1-ю виносною + Over Ext Line 2 Над 2-ю виносною + Over dimension line, with leader Над розмірною лінією, з виноскою + Over dimension line, without leader Над розмірною лінією, без виноски + Override Current Style: Перевизначення поточного стилю: + Override... Перевизначити... + Overrides apply to new dimensions in the current style. Перевизначення застосовуються до нових розмірів поточного стилю. + Overrides apply to the current style Перевизначення задаються для поточного стилю + Preceding dimension text Перед текстом розміру + Precision Точність + Prefix Префікс + Preview of: Зразок: + Primary Units Основні одиниці + Radians Радіани + Radius jog dimension Радіус зі зламом + Rename Перейменувати + Reset Text Position Відновити положення тексту + Right angle Прямий кут + Round distances to Округлювати до + Round off Округлення + Scale for dimension features Масштаб розмірних елементів + Scaling for height Масштаб висоти + Scientific Наукові + Second Друга + Size Розмір + Start With: На основі: + Styles in use Використовувані стилі + Styles: Стилі: + Suffix Суфікс + Suppress arrows if they don't fit inside Приховувати стрілки, якщо не вміщуються + Suppress dim line 1 Приховати розмірну лінію 1 + Suppress dim line 2 Приховати розмірну лінію 2 + Suppress ext line 1 Приховати виносну 1 + Suppress ext line 2 Приховати виносну 2 + Suppress leading zeros Приховувати початкові нулі + Suppress trailing zeros Приховувати кінцеві нулі + Symbols and Arrows Символи та стрілки + Symmetrical Симетрично + Text alignment Орієнтація тексту + Text appearance Властивості тексту + Text frame Рамка тексту + Text inside Текст усередині + Text movement Переміщення тексту + Text offset Відступ тексту + Text placement Вирівнювання тексту + Text pos hor Текст по горизонталі + Text pos vert Текст по вертикалі + The two styles are the same. Стилі однакові. + Tick size Розмір засічки + Tolerance display Відображення допуску + Tolerance format Формат допусків + Tolerance limit lower Нижній допуск + Tolerance limit upper Верхній допуск + Tolerance pos vert Положення допуску + Tolerance precision Точність допуску + Tolerance text height Висота тексту допуску + Tolerances Допуски + Unit format Формат одиниць + Units format Формат одиниць + Upper value Верхнє значення + Use overall scale of Глобальний масштаб + Variable Змінна + Vertical position Положення по вертикалі + When text is not in the default position Якщо текст не в стандартному положенні + Windows Desktop Як у Windows + With: З: + overrides перевизначень + Measurement Значення + User Arrow: Користувацька: + Leaders Виноски + Leader type Тип виноски + Arrowhead Стрілка + Arrowhead size Розмір стрілки + Landing distance Довжина полички + Straight Пряма + Annotate Анотації + 3D Modeling 3D-моделювання + Float Panel Плаваюча панель + Pin to Left Закріпити ліворуч + Transform to Ribbon Перетворити на стрічку + Move to Group Перемістити в групу + Close Panel Закрити панель + Custom Patterns Власні зразки + Folder with hatch pattern files (.pat): Тека з файлами зразків штрихування (.pat): + Browse... Огляд... + Read the folder again Прочитати теку знову + No hatch patterns (.pat files) in this folder У цій теці немає зразків штрихування (файлів .pat) + Black Чорна + Light Blue Світло-блакитна diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e0e238900c..f6388af996 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -214,6 +214,13 @@ impl Pen<'_> { let (nx, ny) = (-uy, ux); self.tri([(x, y), (x - ux * 3.0 + nx * 1.4, y - uy * 3.0 + ny * 1.4), (x - ux * 3.0 - nx * 1.4, y - uy * 3.0 - ny * 1.4)], c); } + /// A larger arrowhead than [`Pen::arrow_tip`]: `len` long, `half` wide either side. + fn big_arrow(&self, x: f32, y: f32, dx: f32, dy: f32, len: f32, half: f32, c: Color32) { + let l = (dx * dx + dy * dy).sqrt().max(1e-3); + let (ux, uy) = (dx / l, dy / l); + let (nx, ny) = (-uy, ux); + self.tri([(x, y), (x - ux * len + nx * half, y - uy * len + ny * half), (x - ux * len - nx * half, y - uy * len - ny * half)], c); + } fn text(&self, x: f32, y: f32, s: &str, size: f32, c: Color32) { self.p.text(self.at(x, y), egui::Align2::CENTER_CENTER, s, egui::FontId::proportional(size * self.sc()), c); } @@ -481,20 +488,24 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.la(14.0, 21.0, 19.0, 21.0); } Move => { - pen.la(12.0, 3.0, 12.0, 21.0); - pen.la(3.0, 12.0, 21.0, 12.0); - pen.arrow_tip(12.0, 2.0, 0.0, -1.0, a); - pen.arrow_tip(12.0, 22.0, 0.0, 1.0, a); - pen.arrow_tip(2.0, 12.0, -1.0, 0.0, a); - pen.arrow_tip(22.0, 12.0, 1.0, 0.0, a); + pen.la(12.0, 6.0, 12.0, 18.0); + pen.la(6.0, 12.0, 18.0, 12.0); + pen.big_arrow(12.0, 1.5, 0.0, -1.0, 5.5, 3.3, a); + pen.big_arrow(12.0, 22.5, 0.0, 1.0, 5.5, 3.3, a); + pen.big_arrow(1.5, 12.0, -1.0, 0.0, 5.5, 3.3, a); + pen.big_arrow(22.5, 12.0, 1.0, 0.0, 5.5, 3.3, a); } Copy => { pen.rect(3.0, 3.0, 11.0, 13.0, b); pen.rect(10.0, 8.0, 11.0, 13.0, a); } Rotate => { - pen.arc(12.0, 12.0, 8.0, 100.0, 380.0, a); - pen.arrow_tip(10.6, 4.1, -1.0, 0.1, a); + // Most of a circle, counter-clockwise, ending in an arrowhead along it. + pen.arc(12.0, 12.0, 8.0, 50.0, 300.0, a); + let end = 300f32.to_radians(); + let (px, py) = (12.0 + 8.0 * end.cos(), 12.0 - 8.0 * end.sin()); + let (ux, uy) = (-end.sin(), -end.cos()); + pen.big_arrow(px + ux * 4.5, py + uy * 4.5, ux, uy, 5.5, 3.3, a); pen.dot(12.0, 12.0); } Scale => { @@ -519,20 +530,22 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.la(4.0, 18.0, 4.0, 22.0); } Trim => { - pen.l(8.0, 2.0, 8.0, 22.0); - pen.l(16.0, 2.0, 16.0, 22.0); - pen.l(2.0, 12.0, 8.0, 12.0); - pen.l(16.0, 12.0, 22.0, 12.0); - for x in [9.5, 12.0, 14.5] { - pen.la(x, 12.0, x + 1.0, 12.0); - } - pen.poly(&[(10.0, 17.0), (12.0, 15.0), (14.0, 17.0)], false, a); + // Scissors cutting a line in two: the line's halves apart under the blades. + pen.l(1.5, 20.0, 9.0, 20.0); + pen.l(15.0, 20.0, 22.5, 20.0); + pen.c(7.5, 4.5, 3.0, a); + pen.c(16.5, 4.5, 3.0, a); + pen.poly(&[(9.3, 6.9), (14.6, 18.5)], false, a); + pen.poly(&[(14.7, 6.9), (9.4, 18.5)], false, a); + pen.tri([(14.6, 18.5), (13.0, 13.5), (11.8, 14.6)], a); + pen.tri([(9.4, 18.5), (11.0, 13.5), (12.2, 14.6)], a); + pen.fill_c(12.0, 12.6, 1.3, pen.pt); } Extend => { - pen.l(20.0, 2.0, 20.0, 22.0); - pen.l(3.0, 12.0, 11.0, 12.0); - pen.la(11.0, 12.0, 19.0, 12.0); - pen.arrow_tip(19.5, 12.0, 1.0, 0.0, a); + pen.l(21.0, 2.0, 21.0, 22.0); + pen.l(2.0, 12.0, 9.0, 12.0); + pen.la(9.0, 12.0, 14.0, 12.0); + pen.big_arrow(20.5, 12.0, 1.0, 0.0, 7.0, 4.0, a); } Fillet => { pen.l(4.0, 20.0, 4.0, 12.0); @@ -599,7 +612,21 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.poly(&[(20.0, 6.0), (20.0, 11.0), (11.0, 11.0), (11.0, 14.0)], false, b); pen.fill_rect(9.5, 14.0, 3.0, 8.0, a); } - DimLinear | DimAligned | DimBaseline | DimContinue | QDim => { + DimAligned => { + // The linear dimension's figure turned 13° counter-clockwise, as an aligned + // dimension follows a slanted object. + let (sin, cos) = 13f32.to_radians().sin_cos(); + let r = |x: f32, y: f32| (12.0 + (x - 12.0) * cos + (y - 12.0) * sin, 12.0 - (x - 12.0) * sin + (y - 12.0) * cos); + let line = |x1: f32, y1: f32, x2: f32, y2: f32, c: Color32| pen.poly(&[r(x1, y1), r(x2, y2)], false, c); + let (y0, y1) = (9.0, 19.0); + line(4.0, y1, 4.0, 6.0, b); + line(20.0, y1, 20.0, 6.0, b); + line(4.0, y0, 20.0, y0, a); + let ((ax, ay), (bx, by)) = (r(4.0, y0), r(20.0, y0)); + pen.arrow_tip(ax, ay, -cos, sin, a); + pen.arrow_tip(bx, by, cos, -sin, a); + } + DimLinear | DimBaseline | DimContinue | QDim => { let (y0, y1) = (8.0, 18.0); pen.l(4.0, y1, 4.0, 5.0); pen.l(20.0, y1, 20.0, 5.0); @@ -612,7 +639,6 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.l(12.0, y1, 12.0, 5.0); } QDim => pen.text(12.0, 15.0, "Q", 7.0, b), - DimAligned => {} _ => pen.text(12.0, 14.5, "1.5", 6.0, b), } } @@ -910,6 +936,12 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { /// A shared button interaction with CADCraft's original multicolor icon painting. pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response { + button_bare(ui, icon, size, tooltip, selected).on_hover_text(crate::i18n::t(tooltip)) +} + +/// [`button`] without its hover text, for callers that show a richer tooltip +/// ([`crate::toolbar::tool_button`]). +pub fn button_bare(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: bool) -> egui::Response { let t = Tokens::get(); let visuals = |fill| ButtonVisuals { fill, stroke: Stroke::NONE, icon: t.icon }; let style = IconButtonStyle { @@ -926,7 +958,7 @@ pub fn button(ui: &mut egui::Ui, icon: Icon, size: f32, tooltip: &str, selected: paint(ui.painter(), rect.shrink(size * 0.08), icon, !ui.is_enabled()); }); crate::control::record_widget(ui, &resp, tooltip, "button", Some(selected)); - resp.on_hover_text(crate::i18n::t(tooltip)) + resp } /// Labels and focus outlines for controls whose existing geometry is painted by the app. @@ -945,9 +977,8 @@ pub fn describe_control(ui: &egui::Ui, response: &egui::Response, label: &str, s node.set_selected(selected); } }); - if response.clicked() { - response.request_focus(); - } + // A click leaves the keyboard with the drawing (shortcuts such as Ctrl+V and typed + // commands keep working after switching drawings); Tab still reaches the tab. } if response.has_focus() && response.rect.width() > 4.0 && response.rect.height() > 4.0 { ui.painter().rect_stroke(response.rect.shrink(2.0), 2.0, Stroke::new(1.0, Tokens::get().accent), egui::StrokeKind::Inside); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 91c48e5f8a..4cb638bbfd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,7 +19,9 @@ pub mod cmdline; pub mod context_menu; pub mod control; pub mod credits; +pub mod custom_patterns; pub mod dialogs; +pub mod dimstyles; pub mod docking; pub mod hatchdlg; mod mtext_editor; @@ -44,6 +46,7 @@ pub mod plotstyles; pub mod quick; pub mod shortcut_menus; pub mod theme; +pub mod toolbar; pub mod viewcube; pub mod vpscale; @@ -73,6 +76,14 @@ pub struct UiState { pub show_toolsets: bool, pub show_palettes: bool, pub show_toolbar: bool, + /// Where the Tool Bar is docked: along the top (a row of buttons) or the left edge (a column). + pub toolbar_dock: toolbar::Dock, + /// The Tool Bar's buttons in order, as command ids; `"|"` separates groups ([`toolbar`]). + pub toolbar_items: Vec, + /// The Tool Sets bar (drawing and editing tools): shown, dock, buttons ([`toolbar`]). + pub toolsets_bar: toolbar::BarState, + /// The Layers bar (layer tools and the current layer): shown, dock, buttons. + pub layers_bar: toolbar::BarState, pub show_file_tabs: bool, pub show_status_bar: bool, pub show_command_line: bool, @@ -86,7 +97,13 @@ pub struct UiState { pub system_cursor: bool, /// "Drafting" or "Modeling". pub toolset_tab: String, + /// Tool Sets shown as a ribbon (tabs of tool groups) under the menu bar instead of a palette. + pub toolsets_ribbon: bool, + /// The ribbon's open tab ([`palettes::RIBBON`]). + pub ribbon_tab: String, pub collapsed_groups: Vec, + /// The folder the Hatch and Gradient dialog's Custom Patterns tab lists `.pat` files from. + pub pattern_folder: String, /// Tools the user took out of the Tool Sets palette (command ids); each category's gear /// menu puts them back. pub hidden_tools: Vec, @@ -159,6 +176,10 @@ impl Default for UiState { show_toolsets: true, show_palettes: true, show_toolbar: true, + toolbar_dock: toolbar::Dock::default(), + toolbar_items: toolbar::default_items(), + toolsets_bar: toolbar::Bar::ToolSets.default_state(), + layers_bar: toolbar::Bar::Layers.default_state(), show_file_tabs: true, show_status_bar: true, show_command_line: true, @@ -167,7 +188,10 @@ impl Default for UiState { show_layer_list: false, system_cursor: std::env::var("CADCRAFT_SYSTEM_CURSOR").is_ok_and(|v| !matches!(v.trim(), "" | "0" | "false" | "off")), toolset_tab: "Drafting".into(), + toolsets_ribbon: false, + ribbon_tab: "Draw".into(), collapsed_groups: Vec::new(), + pattern_folder: String::new(), hidden_tools: Vec::new(), properties_all: true, in_window_menu: !cfg!(target_os = "macos"), @@ -183,11 +207,20 @@ impl Default for UiState { } } +/// The version shown in Help ▸ About and the window: the package version, or the build's own +/// label when one is given at build time (`CADCRAFT_VERSION_LABEL`, such as `0.9.0-b3`). +pub const VERSION: &str = match option_env!("CADCRAFT_VERSION_LABEL") { + Some(label) => label, + None => env!("CARGO_PKG_VERSION"), +}; + /// Host services (file pickers, clipboard) injected by the app so this crate stays portable. #[derive(Default)] pub struct Services { pub pick_open: Option Option>>, pub pick_save: Option Option>>, + /// Pick a folder (Options ▸ Fonts); `None` where the host has no folder dialog. + pub pick_folder: Option Option>>, } pub struct CadApp { @@ -509,6 +542,22 @@ impl CadApp { if let Some(w) = v.get("warnings").and_then(Value::as_array).and_then(|w| w.first()).and_then(Value::as_str) { self.set_status(w.to_string()); } + // Fonts the drawing's text styles name that can't be found: say what stands in. + let missing = self.session.doc().map(cadcraft_engine::cmd::missing_fonts).unwrap_or_default(); + if !missing.is_empty() { + let names: Vec<&str> = missing.iter().map(|(_, f)| f.as_str()).take(6).collect(); + let more = if missing.len() > names.len() { format!(" (+{})", missing.len() - names.len()) } else { String::new() }; + let msg = format!( + "{} {}{more}. {} {}. {}", + crate::tl!("Fonts not found:"), + names.join(", "), + crate::tl!("Text in them is drawn with"), + cadcraft_engine::cmd::substitute_font(), + crate::tl!("Add a font folder in Tools ▸ Options ▸ Fonts.") + ); + self.session.echo(msg.clone()); + self.set_status(msg); + } // A dynamic block's own drawing: ask whether to open it in the Block Editor. if self.session.state().is_ok_and(|st| cadcraft_engine::blockedit::has_authoring_elements(&st.doc)) { self.ui.dialog = Some("authoring".into()); @@ -545,9 +594,12 @@ impl CadApp { // browser report changes as input); the saved choice itself never changes here. let shown = self.ui.theme.resolve(ctx.system_theme()); theme::set_active(shown); + let palette = self.ui.theme.palette(); + let palette_changed = theme::palette() != palette; + theme::set_palette(palette); theme::set_canvas(self.options.canvas()); let follows_system = self.ui.theme == theme::ThemePref::System; - if self.shown_theme != Some(shown) || self.shown_follows_system != follows_system { + if self.shown_theme != Some(shown) || self.shown_follows_system != follows_system || palette_changed { theme::apply(ctx, shown, follows_system); self.shown_theme = Some(shown); self.shown_follows_system = follows_system; @@ -622,9 +674,15 @@ impl CadApp { if self.ui.in_window_menu { menus::menu_bar(self, ui); } + // Tool Sets as a ribbon: right under the menu bar. + if self.ui.show_toolsets && self.ui.toolsets_ribbon { + palettes::ribbon(self, ui); + } if self.ui.show_status_bar { chrome::status_bar(self, ui); } + toolbar::top_panels(self, ui); + toolbar::left_panels(self, ui); if self.ui.show_file_tabs { chrome::file_tabs(self, ui); } diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 4e008ddda7..2d133b9cdb 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -28,6 +28,7 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option "linetype", "ddptype" | "ptype" => "ptype", "style" | "st" => "textstyle", + "dimstyle" | "dimstyle.dimension" | "d" | "dst" | "ddim" => "dimstyle", "tablestyle" | "ts" => "tablestyle", "mleaderstyle" | "mls" => "mleaderstyle", "pagesetup" => "pagesetup", @@ -49,6 +50,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool "linetype" => linetype(app, ctx, open), "ptype" => point_style(app, ctx, open), "textstyle" => text_style(app, ctx, open), + "dimstyle" => { + crate::dimstyles::dialog(app, ctx, open); + None + } "tablestyle" => table_style(app, ctx, open), "mleaderstyle" => mleader_style(app, ctx, open), "pagesetup" => page_setup(app, ctx, open), @@ -316,6 +321,13 @@ fn text_style(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action .map(|s| Style { name: s.name.clone(), fields: vec![ + Field::Choice("font", "Font", s.font.clone(), { + let mut names = crate::options::font_choices().0; + if !s.font.trim().is_empty() && !names.iter().any(|n| n.eq_ignore_ascii_case(s.font.trim())) { + names.insert(0, s.font.clone()); + } + names + }), Field::Num("height", "Height (0 = ask)", s.height), Field::Num("widthFactor", "Width factor", s.width_factor), Field::Bool("backwards", "Backwards", s.backwards), @@ -441,7 +453,7 @@ fn style_manager(ctx: &egui::Context, open: &mut bool, title: &str, cmd: &'stati Field::Choice(key, label, v, choices) => { ui.label(*label); let mut picked = None; - egui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt((cmd, *key)).selected_text(v.as_str()).height(320.0).show_ui(ui, |ui| { for c in choices { if ui.selectable_label(c == v, c).clicked() && c != v { picked = Some(c.clone()); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9672270f7b..d5ec4a8d10 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -34,6 +34,16 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.animations.off", "Off", &["View", "Accessibility", "Animation Effects", "Off"], None), ("ui.animations", "Animation Effects", &[], None), ("ui.toggle.toolbar", "Tool Bar", &["Window", "Tool Bar"], None), + ("ui.toolbar.top", "Top", &["Window", "Tool Bar Position", "Top"], None), + ("ui.toolbar.left", "Left", &["Window", "Tool Bar Position", "Left"], None), + ("ui.toggle.toolbar.toolsets", "Tool Sets Tool Bar", &["Window", "Tool Sets Tool Bar"], None), + ("ui.toggle.toolbar.layers", "Layers Tool Bar", &["Window", "Layers Tool Bar"], None), + ("ui.dialog.toolbar", "Customize Tool Bar...", &["Window", "Customize Tool Bar..."], None), + ("ui.toolbar.dock", "Dock Tool Bar", &[], None), + ("ui.toolbar.add", "Add to Tool Bar", &[], None), + ("ui.toolbar.remove", "Remove from Tool Bar", &[], None), + ("ui.toolbar.move", "Move Tool Bar Button", &[], None), + ("ui.toolbar.reset", "Reset Tool Bar", &[], None), ("ui.toggle.filetabs", "File Tab", &["Window", "File Tab"], None), ("ui.toggle.statusbar", "Status Bar", &["Window", "Status Bar"], None), ("ui.toggle.cmdline", "Command Line", &["Window", "Command Line"], Some("Cmd+9")), @@ -42,6 +52,8 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.theme.system", "Use System Setting", &["View", "Interface Theme", "Use System Setting"], None), ("ui.theme.light", "Light", &["View", "Interface Theme", "Light"], None), ("ui.theme.dark", "Dark", &["View", "Interface Theme", "Dark"], None), + ("ui.theme.black", "Black", &["View", "Interface Theme", "Black"], None), + ("ui.theme.lightblue", "Light Blue", &["View", "Interface Theme", "Light Blue"], None), ("ui.theme", "Interface Theme", &[], None), ("ui.saveformat.dxf", "DXF", &["File", "Default Save Format", "DXF"], None), ("ui.saveformat.dwg", "DWG", &["File", "Default Save Format", "DWG"], None), @@ -86,6 +98,9 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option Option { + "ui.theme.system" | "ui.theme.light" | "ui.theme.dark" | "ui.theme.black" | "ui.theme.lightblue" => { let pref = crate::theme::ThemePref::parse(id.trim_start_matches("ui.theme.")).unwrap_or_default(); set_theme(app, pref) } @@ -254,7 +269,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option match params.get("theme").and_then(Value::as_str) { Some(name) => match crate::theme::ThemePref::parse(name) { Some(pref) => set_theme(app, pref), - None => Err(format!("unknown theme \"{name}\" (system, light or dark)")), + None => Err(format!("unknown theme \"{name}\" (system, light, dark, black or lightblue)")), }, None => Ok(theme_json(app)), }, @@ -339,6 +354,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { @@ -436,7 +452,12 @@ fn theme_json(app: &CadApp) -> Value { crate::theme::ThemePref::System => app.shown_theme(), p => p.resolve(None), }; - json!({ "theme": app.ui.theme.as_str(), "shown": if shown == egui::Theme::Light { "light" } else { "dark" } }) + let shown = match app.ui.theme { + crate::theme::ThemePref::Black | crate::theme::ThemePref::LightBlue => app.ui.theme.as_str(), + _ if shown == egui::Theme::Light => "light", + _ => "dark", + }; + json!({ "theme": app.ui.theme.as_str(), "shown": shown }) } fn set_animations(app: &mut CadApp, pref: crate::animation::AnimationPref) -> Value { @@ -542,7 +563,7 @@ pub(crate) fn shortcut_label(s: &str, mac: bool) -> String { pub(crate) fn entry_ui(ui: &mut egui::Ui, e: &Entry, clicked: &mut Option) { match e { Entry::Item { label, id, shortcut, enabled } => { - let mut b = egui::Button::new(crate::i18n::t(label)); + let mut b = egui::Button::new(crate::i18n::widget(ui, crate::i18n::t(label), egui::TextStyle::Button)); if let Some(s) = shortcut { b = b.shortcut_text(shortcut_label(s, ui.ctx().os().is_mac())); } @@ -692,6 +713,7 @@ mod tests { log.borrow_mut().push(name.to_string()); answer.clone() })), + pick_folder: None, }; (CadApp::new(Session::new(), services), asked) } diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 9e7db5803b..3ef99d4839 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -1,11 +1,18 @@ -//! The in-place MTEXT editor: while MTEXT asks for its text, a text box opens on the canvas at +//! The in-place text editor: while MTEXT asks for its text, a text box opens on the canvas at //! the text's location and width with a formatting toolbar (font, height, bold, italic, //! underline, overline, colour, alignment, lists, tabs) and a ruler for the paragraph's indents //! and tab stops. The text and its formats live in the engine's //! [`cadcraft_engine::mtext_edit::Formatted`]; this file only draws and forwards edits. +//! +//! The same editor edits existing text when a command describes it +//! ([`cadcraft_engine::Session::text_editor`]): double-click multiline text or a multileader +//! (toolbar and ruler), one line of text (a plain line, Enter finishes), a dimension (`<>` is +//! the measured value) or a table cell (Tab and Shift+Tab move to the next and previous cell, +//! Alt+↑ and Alt+↓ to the cell above and below). use std::sync::Arc; +use cadcraft_engine::EditorKind; use cadcraft_engine::mtext_edit::{CharFmt, Flag, Formatted, ListStyle, MTextColor, ParaAlign, TabKind}; use egui::text::{CCursor, CCursorRange, LayoutJob}; use egui::{Align2, Color32, FontId, Rect, RichText, Sense, Shape, Stroke, TextFormat, pos2, vec2}; @@ -36,6 +43,10 @@ struct State { sel: (usize, usize), /// A caret position to set on the text box in the next frame (after a toolbar insertion). caret: Option, + /// The object being edited ([`cadcraft_engine::TextEditor::key`]): another one reloads. + key: String, + /// Give the text box the keyboard in the next frame. + focus: bool, } fn state_id() -> egui::Id { @@ -57,27 +68,65 @@ fn color32(c: MTextColor) -> Color32 { /// Show the editor while MTEXT collects its text; clears its state when it isn't running. pub fn show(app: &mut CadApp, ctx: &egui::Context) { - let mtext = app.session.editing_mtext(); + let editor = app.session.text_editor(); let asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); - let (Some(mt), true) = (mtext, asking) else { + let (Some(editor), true) = (editor, asking) else { ctx.data_mut(|d| d.remove::(state_id())); return; }; + let mt = &editor.mtext; + let kind = editor.kind.clone(); let t = Tokens::get(); let (rect, scale) = app.canvas.xf.map_or((ctx.content_rect(), 20.0), |x| (x.rect, x.scale.max(1e-6))); - let mut st = ctx.data_mut(|d| d.get_temp::(state_id())).unwrap_or_else(|| { - let mut fmt = Formatted::default(); + let mut st = ctx.data_mut(|d| d.get_temp::(state_id())).filter(|st| st.key == editor.key).unwrap_or_else(|| { + let mut fmt = match &kind { + EditorKind::NewMText => Formatted::default(), + // One line of plain text: backslashes and braces are text, not codes. + EditorKind::Line => { + let mut f = Formatted::default(); + f.set_text(&mt.contents, &CharFmt::default()); + f + } + _ => Formatted::from_contents(&mt.contents), + }; if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).map(|s| s.font.clone())) { // A family name, not a font file (`txt.shx`, `arial.ttf`). if !f.is_empty() && !f.contains('.') { fmt.base_font = f; } } - State { fmt, typing: CharFmt::default(), typing_at: 0, top: 70.0, sel: (0, 0), caret: None } + let end = fmt.len(); + State { fmt, typing: CharFmt::default(), typing_at: end, top: 70.0, sel: (end, end), caret: Some(end), key: editor.key.clone(), focus: true } }); + let line = kind == EditorKind::Line; + let cell = matches!(kind, EditorKind::TableCell { .. }); + let formatting = !line; + let ruler_shown = matches!(kind, EditorKind::NewMText | EditorKind::MText); + // Keys the editor takes before the text box: Tab between table cells, Enter ends one line. + let mut done = Done::No; + if cell { + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::SHIFT, egui::Key::Tab) { + done = Done::Move("Previous"); + } else if i.consume_key(egui::Modifiers::NONE, egui::Key::Tab) { + done = Done::Move("Next"); + } else if i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowUp) { + done = Done::Move("Up"); + } else if i.consume_key(egui::Modifiers::ALT, egui::Key::ArrowDown) { + done = Done::Move("Down"); + } + }); + } + if line && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + done = Done::Ok; + } + // Ctrl+Enter (⌘↩) finishes, taken before the text box can make it a new line. + if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::Enter)) { + done = Done::Ok; + } let base_h = if mt.height > 0.0 { mt.height } else { 0.2 }; let px = ((base_h * scale) as f32).clamp(MIN_PX, MAX_PX); - let width = if mt.width > 0.0 { ((mt.width * scale) as f32).clamp(280.0, rect.width().max(280.0) * 0.9) } else { 380.0 }; + let width = if mt.width > 0.0 { ((mt.width * scale) as f32).clamp(380.0, rect.width().max(380.0) * 0.9) } else { 380.0 }; // The box's top-left corner on screen (rotation is ignored while editing). let code = usize::from(mt.attach.clamp(1, 9) - 1); let (col, row) = ((code % 3) as f64, (code / 3) as f64); @@ -87,16 +136,31 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { let max_x = (rect.right() - width - 8.0).max(rect.left()); let pos = pos2(at.x.clamp(rect.left(), max_x), at.y.clamp(rect.top() + st.top, (rect.bottom() - 120.0).max(rect.top() + st.top))); - let mut done = Done::No; let top_start = pos.y - st.top; egui::Area::new(egui::Id::new("mtext_editor_area")).order(egui::Order::Foreground).fixed_pos(pos2(pos.x, top_start)).show(ctx, |ui| { egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.accent)).inner_margin(egui::Margin::same(0)).show(ui, |ui| { ui.set_width(width); let y0 = ui.cursor().top(); - toolbar(ui, &mut st, base_h); - ruler(ui, &mut st, px, width, base_h); + let title = match &kind { + EditorKind::NewMText | EditorKind::MText => crate::tl!("Multiline Text").to_string(), + EditorKind::Line => crate::tl!("Text").to_string(), + EditorKind::Dimension { .. } => crate::tl!("Dimension Text").to_string(), + EditorKind::TableCell { name } => format!("{} {name}", crate::tl!("Cell")), + }; + if header(ui, &title, cell) { + done = Done::Cancel; + } + if formatting { + toolbar(ui, &mut st, base_h); + } + if ruler_shown { + ruler(ui, &mut st, px, width, base_h); + } + if let EditorKind::Dimension { measured } = &kind { + dimension_row(ui, &mut st, measured); + } st.top = ui.cursor().top() - y0; - text_box(ui, &mut st, base_h, px, width, &t); + text_box(ui, &mut st, base_h, px, width, &t, line); ui.horizontal(|ui| { ui.add_space(4.0); if ui.button(crate::tl!("OK")).clicked() { @@ -105,30 +169,58 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { if ui.button(crate::tl!("Cancel")).clicked() { done = Done::Cancel; } - let finish = if ui.ctx().os().is_mac() { crate::tl!("⌘↩ to finish") } else { crate::tl!("Ctrl+Enter to finish") }; + if cell { + if icon_button(ui, false, crate::tl!("Previous cell (Shift+Tab)"), |p, r, c| paint_triangle(p, r, c, -1.0)).clicked() { + done = Done::Move("Previous"); + } + if icon_button(ui, false, crate::tl!("Next cell (Tab)"), |p, r, c| paint_triangle(p, r, c, 1.0)).clicked() { + done = Done::Move("Next"); + } + } + let finish = match (line, ui.ctx().os().is_mac()) { + (true, _) => crate::tl!("Enter to finish"), + (false, true) => crate::tl!("⌘↩ to finish"), + (false, false) => crate::tl!("Ctrl+Enter to finish"), + }; ui.label(RichText::new(finish).small().color(t.text_dim)); }); }); }); if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { done = Done::Cancel; - } else if ctx.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) { - done = Done::Ok; } + let contents = if line { st.fmt.text().to_string() } else { st.fmt.to_contents() }; match done { Done::No => { ctx.data_mut(|d| d.insert_temp(state_id(), st)); } - Done::Ok => { + Done::Ok if kind == EditorKind::NewMText => { ctx.data_mut(|d| d.remove::(state_id())); // The editor holds the whole contents: one input, then Enter ends MTEXT's text entry. if !st.fmt.is_empty() { - let _ = app.session.input(cadcraft_engine::Input::Text(st.fmt.to_contents())); + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); } if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") { let _ = app.session.input(cadcraft_engine::Input::Enter); } } + Done::Ok => { + ctx.data_mut(|d| d.remove::(state_id())); + // Existing text: the new contents (even empty), then a table cell ends its editing. + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); + if cell { + let _ = app.session.input(cadcraft_engine::Input::Enter); + } + } + Done::Move(dir) => { + ctx.data_mut(|d| d.remove::(state_id())); + let r = app.session.input(cadcraft_engine::Input::Text(contents)); + report(app, r); + let r = app.session.input(cadcraft_engine::Input::Keyword(dir.into())); + report(app, r); + } Done::Cancel => { ctx.data_mut(|d| d.remove::(state_id())); app.session.cancel(); @@ -136,11 +228,39 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } } +/// Show a refused edit on the command line. +fn report(app: &mut CadApp, r: Result) { + if let Err(e) = r { + app.session.echo(e.to_string()); + } +} + #[derive(PartialEq)] enum Done { No, Ok, Cancel, + /// Keep this cell's text and move to another (a TABLEDIT move keyword). + Move(&'static str), +} + +/// A dimension's text: what `<>` stands for, and buttons to insert it or go back to it alone. +fn dimension_row(ui: &mut egui::Ui, st: &mut State, measured: &str) { + let t = Tokens::get(); + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.label(RichText::new(format!("<> = {measured}")).monospace().color(t.text)); + ui.label(RichText::new(crate::tl!("the measured value")).small().color(t.text_dim)); + if ui.small_button(crate::tl!("Insert <>")).on_hover_text(crate::tl!("Insert the measured value at the cursor")).clicked() { + insert(st, "<>"); + } + if ui.small_button(crate::tl!("Measured Value Only")).on_hover_text(crate::tl!("Replace the text with the measured value")).clicked() { + st.fmt = Formatted::from_contents("<>"); + st.sel = (2, 2); + st.caret = Some(2); + st.typing_at = 2; + } + }); } /// Change the selected characters' format, or the next typed ones' when nothing is selected. @@ -190,12 +310,20 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { let cur = current(st); let range = st.sel.0.min(st.sel.1)..st.sel.0.max(st.sel.1); let mut refocus = false; - ui.horizontal_wrapped(|ui| { + // Row 1: character format. + ui.horizontal(|ui| { ui.add_space(4.0); // Font let shown = cur.font.clone().unwrap_or_else(|| st.fmt.base_font.clone()); egui::ComboBox::from_id_salt("mtext_font").width(120.0).selected_text(shown.clone()).show_ui(ui, |ui| { - for fam in FAMILIES.iter().map(|s| s.to_string()).chain(cur.font.clone().filter(|f| !FAMILIES.contains(&f.as_str()))) { + // The fonts in the user's font folders, then the usual ones, then the text's own. + let mut families = crate::options::font_choices().1; + for f in FAMILIES.iter().map(|s| s.to_string()).chain(cur.font.clone()) { + if !families.iter().any(|x| x.eq_ignore_ascii_case(&f)) { + families.push(f); + } + } + for fam in families { if ui.selectable_label(shown == fam, &fam).clicked() { change(st, |c| c.font = Some(fam.clone())); refocus = true; @@ -224,9 +352,16 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { refocus = true; } } - // Colour + ui.separator(); + // Colour: an A over a bar in the colour, as word processors show it. let swatch = cur.color.map_or(ui.visuals().text_color(), color32); - ui.menu_button(RichText::new("A▾").color(swatch).strong(), |ui| { + let resp = icon_button_wide(ui, false, crate::tl!("Text color"), |p, r, c| { + let a = Rect::from_min_size(r.min, vec2(r.height(), r.height())); + p.text(pos2(a.center().x, a.top() + a.height() * 0.42), Align2::CENTER_CENTER, "A", FontId::proportional(a.height() * 0.8), c); + p.rect_filled(Rect::from_min_max(pos2(a.left() + 1.0, a.bottom() - 3.0), pos2(a.right() - 1.0, a.bottom())), 0.0, swatch); + paint_chevron(p, Rect::from_min_max(pos2(a.right() + 1.0, r.top()), r.max), c); + }); + egui::Popup::menu(&resp).show(|ui| { if ui.button(crate::tl!("ByLayer")).clicked() { change(st, |c| c.color = None); refocus = true; @@ -251,26 +386,25 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { let v = (u32::from(rgb[0]) << 16) | (u32::from(rgb[1]) << 8) | u32::from(rgb[2]); change(st, |c| c.color = Some(MTextColor::Rgb(v))); } - }) - .response - .on_hover_text(crate::tl!("Text color")); - ui.separator(); - // Paragraph alignment + }); + }); + // Row 2: paragraph, lists, tab and symbols. + ui.horizontal(|ui| { + ui.add_space(4.0); let para = st.fmt.para(st.fmt.paragraph_of(range.start)); - for (al, glyph, tip) in [ - (ParaAlign::Left, "⇤", crate::tl!("Left")), - (ParaAlign::Center, "↔", crate::tl!("Center")), - (ParaAlign::Right, "⇥", crate::tl!("Right")), - (ParaAlign::Justify, "≡", crate::tl!("Justify")), + for (al, tip) in [ + (ParaAlign::Left, crate::tl!("Align left")), + (ParaAlign::Center, crate::tl!("Center")), + (ParaAlign::Right, crate::tl!("Align right")), + (ParaAlign::Justify, crate::tl!("Justify")), ] { let on = para.align == al; - if ui.selectable_label(on, glyph).on_hover_text(tip).clicked() { + if icon_button(ui, on, tip, |p, r, c| paint_align(p, r, c, al)).clicked() { st.fmt.edit_paras(range.clone(), |p| p.align = if on { ParaAlign::Default } else { al }); refocus = true; } } ui.separator(); - // Lists and special characters if ui.button("•≡").on_hover_text(crate::tl!("Bulleted list")).clicked() { st.fmt.make_list(range.clone(), ListStyle::Bullet, 3.0 * base_h); refocus = true; @@ -279,23 +413,189 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { st.fmt.make_list(range.clone(), ListStyle::Number, 3.0 * base_h); refocus = true; } - for (glyph, tip, code) in [ - ("⇥|", crate::tl!("Insert tab"), "\t"), - ("°", crate::tl!("Degree"), "°"), - ("±", crate::tl!("Plus/minus"), "±"), - ("⌀", crate::tl!("Diameter"), "⌀"), - ] { - if ui.button(glyph).on_hover_text(tip).clicked() { - insert(st, code); - refocus = true; - } + ui.separator(); + if icon_button(ui, false, crate::tl!("Insert tab"), paint_tab).clicked() { + insert(st, "\t"); + refocus = true; } + let resp = icon_button_wide(ui, false, crate::tl!("Additional symbols"), |p, r, c| { + let a = Rect::from_min_size(r.min, vec2(r.height(), r.height())); + p.text(a.center(), Align2::CENTER_CENTER, "Ω", FontId::proportional(a.height() * 0.85), c); + paint_chevron(p, Rect::from_min_max(pos2(a.right() + 1.0, r.top()), r.max), c); + }); + egui::Popup::menu(&resp).show(|ui| { + ui.label(RichText::new(crate::tl!("Additional symbols")).strong()); + egui::Grid::new("mtext_symbols").spacing(vec2(2.0, 2.0)).show(ui, |ui| { + for (i, (sym, name)) in SYMBOLS.iter().enumerate() { + let b = egui::Button::new(RichText::new(*sym).size(17.0)).min_size(vec2(30.0, 28.0)); + if ui + .add(b) + .on_hover_text(format!("{} ({sym}, U+{:04X})", crate::i18n::t(name), sym.chars().next().map_or(0, u32::from))) + .clicked() + { + insert(st, sym); + refocus = true; + ui.close(); + } + if i % 8 == 7 { + ui.end_row(); + } + } + }); + }); }); if refocus { ui.ctx().memory_mut(|m| m.request_focus(edit_id())); } } +/// The symbols of the Additional symbols menu: drafting marks, comparisons, Greek letters, +/// powers and fractions. +const SYMBOLS: [(&str, &str); 32] = [ + ("°", "Degree"), + ("±", "Plus/minus"), + ("⌀", "Diameter"), + ("∠", "Angle"), + ("⊥", "Perpendicular"), + ("∥", "Parallel"), + ("℄", "Center line"), + ("⌒", "Arc"), + ("≈", "Almost equal"), + ("≠", "Not equal"), + ("≤", "Less than or equal"), + ("≥", "Greater than or equal"), + ("×", "Multiplication"), + ("÷", "Division"), + ("√", "Square root"), + ("∞", "Infinity"), + ("Δ", "Delta"), + ("Ω", "Ohm"), + ("µ", "Micro"), + ("π", "Pi"), + ("α", "Alpha"), + ("β", "Beta"), + ("γ", "Gamma"), + ("φ", "Phi"), + ("²", "Squared"), + ("³", "Cubed"), + ("½", "One half"), + ("¼", "One quarter"), + ("¾", "Three quarters"), + ("‰", "Per mille"), + ("•", "Bullet"), + ("№", "Number sign"), +]; + +/// A square toolbar button drawn by `paint` (icon rectangle, colour): lit when `on`. +fn icon_button(ui: &mut egui::Ui, on: bool, tip: &str, paint: impl FnOnce(&egui::Painter, Rect, Color32)) -> egui::Response { + icon_button_sized(ui, on, tip, vec2(24.0, 22.0), vec2(16.0, 16.0), paint) +} + +/// A toolbar button with room for a drop-down arrow after its icon. +fn icon_button_wide(ui: &mut egui::Ui, on: bool, tip: &str, paint: impl FnOnce(&egui::Painter, Rect, Color32)) -> egui::Response { + icon_button_sized(ui, on, tip, vec2(32.0, 22.0), vec2(24.0, 16.0), paint) +} + +fn icon_button_sized( + ui: &mut egui::Ui, + on: bool, + tip: &str, + size: egui::Vec2, + icon: egui::Vec2, + paint: impl FnOnce(&egui::Painter, Rect, Color32), +) -> egui::Response { + let t = Tokens::get(); + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + let fill = if on { + Some(t.accent.gamma_multiply(0.45)) + } else if resp.hovered() { + Some(t.control_hover) + } else { + None + }; + if let Some(fill) = fill { + ui.painter().rect_filled(rect, 3.0, fill); + } + let color = if resp.hovered() || on { t.text } else { ui.visuals().text_color() }; + paint(ui.painter(), Rect::from_center_size(rect.center(), icon), color); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tip)); + resp.on_hover_text(crate::i18n::t(tip)) +} + +/// Paragraph alignment as word processors draw it: five lines of text, long and short, lined up +/// on the left, the centre or the right, or all full width. +fn paint_align(p: &egui::Painter, r: Rect, c: Color32, al: ParaAlign) { + let stroke = Stroke::new(1.6, c); + for i in 0..5 { + let y = r.top() + 1.5 + i as f32 * 3.25; + let w = match al { + ParaAlign::Justify => r.width(), + _ if i % 2 == 0 => r.width(), + ParaAlign::Center => r.width() * 0.6, + _ => r.width() * 0.62, + }; + let x0 = match al { + ParaAlign::Center => r.center().x - w / 2.0, + ParaAlign::Right => r.right() - w, + _ => r.left(), + }; + p.line_segment([pos2(x0, y), pos2(x0 + w, y)], stroke); + } +} + +/// Insert tab: an arrow running into a stop. +fn paint_tab(p: &egui::Painter, r: Rect, c: Color32) { + let stroke = Stroke::new(1.6, c); + let y = r.center().y; + let stop = r.right() - 1.5; + p.line_segment([pos2(r.left() + 1.0, y), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop - 6.5, y - 4.5), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop - 6.5, y + 4.5), pos2(stop - 2.0, y)], stroke); + p.line_segment([pos2(stop, r.top() + 2.0), pos2(stop, r.bottom() - 2.0)], stroke); +} + +/// A small drop-down arrow in `r`. +fn paint_chevron(p: &egui::Painter, r: Rect, c: Color32) { + let m = r.center(); + p.add(Shape::convex_polygon(vec![pos2(m.x - 3.0, m.y - 1.5), pos2(m.x + 3.0, m.y - 1.5), pos2(m.x, m.y + 2.0)], c, Stroke::NONE)); +} + +/// A triangle pointing left (`dir` -1) or right (1). +fn paint_triangle(p: &egui::Painter, r: Rect, c: Color32, dir: f32) { + let m = r.center(); + let pts = vec![pos2(m.x + 4.0 * dir, m.y), pos2(m.x - 3.0 * dir, m.y - 5.0), pos2(m.x - 3.0 * dir, m.y + 5.0)]; + p.add(Shape::convex_polygon(pts, c, Stroke::NONE)); +} + +/// The editor's title and its close button (the same as Cancel); a table cell's hint. True when +/// the close button was clicked. +fn header(ui: &mut egui::Ui, title: &str, cell: bool) -> bool { + let t = Tokens::get(); + let mut close = false; + ui.horizontal(|ui| { + ui.add_space(6.0); + let label = ui.label(RichText::new(title).strong()); + if cell { + label.on_hover_text(crate::tl!("Tab: next cell · Shift+Tab: previous · Alt+↑↓: cell above, below")); + ui.label(RichText::new(crate::tl!("Tab: next cell")).small().color(t.text_dim)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(2.0); + let (rect, resp) = ui.allocate_exact_size(vec2(22.0, 20.0), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 3.0, Color32::from_rgb(196, 43, 28)); + } + let c = if resp.hovered() { Color32::WHITE } else { ui.visuals().text_color() }; + let k = Rect::from_center_size(rect.center(), vec2(9.0, 9.0)); + ui.painter().line_segment([k.left_top(), k.right_bottom()], Stroke::new(1.5, c)); + ui.painter().line_segment([k.right_top(), k.left_bottom()], Stroke::new(1.5, c)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, crate::tl!("Close"))); + close = resp.on_hover_text(crate::tl!("Close (same as Cancel)")).clicked(); + }); + }); + close +} + /// Insert `s` at the caret (over the selection). fn insert(st: &mut State, s: &str) { let (a, b) = (st.sel.0.min(st.sel.1), st.sel.0.max(st.sel.1)); @@ -374,7 +674,7 @@ fn ruler(ui: &mut egui::Ui, st: &mut State, px: f32, width: f32, base_h: f64) { bg.on_hover_text(crate::tl!("Click the ruler to add a tab stop, right-click to remove one")); } -fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens) { +fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens, line: bool) { let id = edit_id(); if let Some(at) = st.caret.take() && let Some(mut s) = egui::TextEdit::load_state(ui.ctx(), id) @@ -427,18 +727,18 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, ui.fonts_mut(|f| f.layout_job(job)) }; let mut buf = st.fmt.text().to_string(); - let out = egui::TextEdit::multiline(&mut buf) + let edit = if line { egui::TextEdit::singleline(&mut buf) } else { egui::TextEdit::multiline(&mut buf).desired_rows(5).lock_focus(true) }; + let out = edit .id(id) .desired_width(width) - .desired_rows(5) .margin(egui::Margin::symmetric(4, 4)) - .lock_focus(true) .char_limit(cadcraft_engine::mtext_edit::MAX_CHARS) .layouter(&mut layouter) .show(ui); - if !out.response.has_focus() && buf.is_empty() && st.fmt.is_empty() { + if !out.response.has_focus() && (st.focus || (buf.is_empty() && st.fmt.is_empty())) { out.response.request_focus(); } + st.focus = false; if out.response.changed() { let typing = st.typing.clone(); st.fmt.set_text(&buf, &typing); diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 4db230c5c0..7d3cec34ca 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -67,7 +67,7 @@ impl Opening { /// The text of the card: the file and how long it has taken, or how many files are queued. fn label(&self) -> Option { let first = self.jobs.first()?; - let name = std::path::Path::new(&first.path).file_name().map_or_else(|| first.path.clone(), |n| n.to_string_lossy().to_string()); + let name = crate::menus::file_name(&first.path); let secs = first.started.elapsed().as_secs_f32(); let more = self.jobs.len() - 1; Some(if more == 0 { format!("Opening {name}... {secs:.0} s") } else { format!("Opening {name} and {more} more... {secs:.0} s") }) @@ -110,7 +110,7 @@ mod tests { /// cannot be read is reported like a failed OPEN without adding a drawing. #[test] fn open_path_reads_in_the_background_and_reports_failure() { - let mut app = CadApp::new(Session::new(), Services { pick_open: None, pick_save: None }); + let mut app = CadApp::new(Session::new(), Services { pick_open: None, pick_save: None, pick_folder: None }); let before = app.session.docs.len(); let missing = std::env::temp_dir().join(format!("cadcraft-missing-{}.dxf", std::process::id())); let p = missing.to_string_lossy().to_string(); diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index f72ee4fc63..2049c94d99 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -12,17 +12,19 @@ use crate::animation::AnimationPref; use crate::theme::{ThemePref, Tokens}; /// The tabs: (id in the dialog name, label). -pub(super) const TABS: [(&str, &str); 6] = [ +pub(super) const TABS: [(&str, &str); 7] = [ ("display", "Display"), ("files", "Open and Save"), + ("fonts", "Fonts"), ("drafting", "Drafting"), ("selection", "Selection"), ("preferences", "User Preferences"), ("profiles", "Profiles"), ]; -const WIDTH: f32 = 580.0; -const MIN_TAB_HEIGHT: f32 = 200.0; +const WIDTH: f32 = 610.0; +/// Height of every tab's page. +const TAB_HEIGHT: f32 = 340.0; /// Show the Options dialog (`name` is `"options"` or `"options:"`). pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool) { @@ -50,17 +52,21 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool }); ui.separator(); ui.add_space(4.0); - let top = ui.cursor().top(); - match tab { - "files" => files(app, ui, &mut changes), - "drafting" => drafting(app, ui, &mut changes, &mut start), - "selection" => selection(app, ui, &mut changes), - "preferences" => preferences(app, ui, &mut changes), - "profiles" => profiles(app, ui, &mut changes), - _ => display(app, ui, &mut changes), - } - // The same height on every tab, so switching tabs doesn't move the buttons. - ui.add_space((MIN_TAB_HEIGHT - (ui.cursor().top() - top)).max(8.0)); + // Every tab is the same height (a taller one scrolls), so switching tabs neither + // resizes the dialog nor moves it. + egui::ScrollArea::vertical().id_salt(("options_tab", tab)).max_height(TAB_HEIGHT).auto_shrink([false, false]).show(ui, |ui| { + ui.set_min_height(TAB_HEIGHT); + match tab { + "files" => files(app, ui, &mut changes), + "fonts" => fonts(app, ui, &mut changes), + "drafting" => drafting(app, ui, &mut changes, &mut start), + "selection" => selection(app, ui, &mut changes), + "preferences" => preferences(app, ui, &mut changes), + "profiles" => profiles(app, ui, &mut changes), + _ => display(app, ui, &mut changes), + } + }); + ui.add_space(4.0); ui.separator(); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -98,6 +104,8 @@ fn theme_label(t: ThemePref) -> &'static str { ThemePref::System => crate::tl!("Use System Setting"), ThemePref::Light => crate::tl!("Light"), ThemePref::Dark => crate::tl!("Dark"), + ThemePref::Black => crate::tl!("Black"), + ThemePref::LightBlue => crate::tl!("Light Blue"), } } @@ -249,6 +257,152 @@ fn files(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { hint(ui, crate::tl!("Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off.")); } +/// The fonts found in the user's font folders, kept while the font set is unchanged. +#[derive(Clone, Default)] +struct FontsSeen { + generation: Option, + fonts: Vec<(String, Option)>, +} + +/// Options ▸ Fonts: the folders searched for fonts before the system's, the fonts found there and +/// the current drawing's fonts that can't be found. +fn fonts(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { + let t = Tokens::get(); + let folders = cadcraft_fonts::ttf::font_dirs(); + let sel_id = egui::Id::new("cc_options_font_sel"); + let typed_id = egui::Id::new("cc_options_font_typed"); + let mut sel: Option = ui.data(|d| d.get_temp(sel_id)).filter(|i: &usize| *i < folders.len()); + let mut typed: String = ui.data(|d| d.get_temp(typed_id)).unwrap_or_default(); + let mut next = folders.clone(); + let mut changed = false; + + ui.label(RichText::new(crate::tl!("Font folders")).strong()); + hint( + ui, + crate::tl!( + "Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins." + ), + ); + ui.add_space(4.0); + ui.horizontal(|ui| { + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(4.0).show(ui, |ui| { + ui.set_width(400.0); + ui.set_min_height(92.0); + egui::ScrollArea::vertical().id_salt("cc_options_font_dirs").max_height(92.0).auto_shrink([false, true]).show(ui, |ui| { + if folders.is_empty() { + ui.label(RichText::new(crate::tl!("No font folders yet")).color(t.text_faint).italics()); + } + for (i, f) in folders.iter().enumerate() { + let exists = cfg!(target_arch = "wasm32") || std::path::Path::new(f).is_dir(); + let mut text = RichText::new(f.as_str()); + if !exists { + text = text.color(t.text_faint).strikethrough(); + } + let r = ui.selectable_label(sel == Some(i), text); + let r = if exists { r } else { r.on_hover_text(crate::tl!("This folder does not exist")) }; + if r.clicked() { + sel = Some(i); + } + } + }); + }); + ui.vertical(|ui| { + let full = folders.len() >= cadcraft_fonts::ttf::MAX_FONT_DIRS; + if let Some(pick) = app.services.pick_folder.as_ref() + && ui.add_enabled(!full, egui::Button::new(crate::tl!("Add Folder..."))).clicked() + && let Some(dir) = pick() + { + next.push(dir); + sel = Some(next.len() - 1); + changed = true; + } + if ui.add_enabled(sel.is_some(), egui::Button::new(crate::tl!("Remove"))).clicked() + && let Some(i) = sel + { + next.remove(i); + sel = None; + changed = true; + } + if ui.add_enabled(sel.is_some_and(|i| i > 0), egui::Button::new(crate::tl!("Move Up"))).clicked() + && let Some(i) = sel + { + next.swap(i, i - 1); + sel = Some(i - 1); + changed = true; + } + if ui.add_enabled(sel.is_some_and(|i| i + 1 < folders.len()), egui::Button::new(crate::tl!("Move Down"))).clicked() + && let Some(i) = sel + { + next.swap(i, i + 1); + sel = Some(i + 1); + changed = true; + } + }); + }); + ui.horizontal(|ui| { + let r = ui.add(egui::TextEdit::singleline(&mut typed).hint_text(crate::tl!("Folder path")).desired_width(330.0)); + let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + let ok = !typed.trim().is_empty() && folders.len() < cadcraft_fonts::ttf::MAX_FONT_DIRS; + if (ui.add_enabled(ok, egui::Button::new(crate::tl!("Add"))).clicked() || (enter && ok)) && !next.iter().any(|f| f == typed.trim()) { + next.push(typed.trim().to_string()); + sel = Some(next.len() - 1); + typed.clear(); + changed = true; + } + if ui.button(crate::tl!("Look for Fonts Again")).on_hover_text(crate::tl!("After adding or removing font files in a folder")).clicked() { + cadcraft_fonts::ttf::rescan(); + } + }); + ui.data_mut(|d| { + d.insert_temp(typed_id, typed); + if let Some(i) = sel { + d.insert_temp(sel_id, i); + } else { + d.remove::(sel_id); + } + }); + if changed { + changes.insert("fontFolders".into(), json!(next)); + } + + // The fonts found there. + ui.add_space(8.0); + let seen_id = egui::Id::new("cc_options_fonts_seen"); + let generation = cadcraft_fonts::ttf::generation(); + let mut seen: FontsSeen = ui.data(|d| d.get_temp(seen_id)).unwrap_or_default(); + if seen.generation != Some(generation) { + let fonts = cadcraft_fonts::ttf::installed().into_iter().filter(|f| f.user).map(|f| (f.name, f.family)).collect(); + seen = FontsSeen { generation: Some(generation), fonts }; + ui.data_mut(|d| d.insert_temp(seen_id, seen.clone())); + } + ui.label(RichText::new(format!("{} {}", crate::tl!("Fonts found in these folders:"), seen.fonts.len())).strong()); + egui::ScrollArea::vertical().id_salt("cc_options_fonts_found").max_height(90.0).auto_shrink([false, true]).show(ui, |ui| { + for (name, family) in &seen.fonts { + ui.horizontal(|ui| { + ui.label(name.as_str()); + if let Some(family) = family { + ui.label(RichText::new(format!("— {family}")).color(t.text_dim)); + } + }); + } + }); + + // The current drawing's fonts that can't be found. + if let Ok(d) = app.session.doc() { + let missing = cadcraft_engine::cmd::missing_fonts(d); + ui.add_space(8.0); + if missing.is_empty() { + hint(ui, crate::tl!("Every font this drawing uses was found.")); + } else { + ui.label(RichText::new(crate::tl!("Fonts this drawing uses that were not found:")).strong()); + let sub = cadcraft_engine::cmd::substitute_font(); + for (style, font) in missing.iter().take(12) { + ui.label(format!("{font} ({} {style}) → {sub}", crate::tl!("style"))); + } + } + } +} + fn drafting(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map, start: &mut Option<&'static str>) { let t = Tokens::get(); grid(ui, "options_drafting", |ui| { diff --git a/crates/ui-egui/src/options/mod.rs b/crates/ui-egui/src/options/mod.rs index 852b065ba7..f5803ce6dc 100644 --- a/crates/ui-egui/src/options/mod.rs +++ b/crates/ui-egui/src/options/mod.rs @@ -21,6 +21,7 @@ //! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default | //! | `selectionColor` | the colour selected objects are highlighted in: `"#rrggbb"`, or `null` for the theme's | //! | `snapMarkerSize` | object snap marker size in points, 5–31 | +//! | `fontFolders` | folders searched for TrueType/OpenType fonts before the system's, in order (up to 16) | //! //! SAVETIME and SAVEFILEPATH are the engine's autosave settings, kept with the autosave state //! rather than in the profile. @@ -141,6 +142,7 @@ struct UiChanges { savetime: Option, savefilepath: Option, time_sensitive_right_click: Option, + font_folders: Option>, } fn color_param(key: &str, v: &Value) -> Result, String> { @@ -154,7 +156,7 @@ fn color_param(key: &str, v: &Value) -> Result, String> { fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result { let text = || v.as_str().ok_or_else(|| format!("{key} must be text")); match key { - "theme" => c.theme = Some(ThemePref::parse(text()?).ok_or("theme must be system, light or dark")?), + "theme" => c.theme = Some(ThemePref::parse(text()?).ok_or("theme must be system, light, dark, black or lightblue")?), "animations" => c.animations = Some(AnimationPref::parse(text()?).ok_or("animations must be system, on or off")?), "interfaceLanguage" => { c.language = Some( @@ -179,6 +181,12 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result { c.save_version = Some(crate::SaveVersion::parse(name.trim()).ok_or("saveVersion must be 2000, 2004, 2007, 2010, 2013 or 2018")?); } "timeSensitiveRightClick" => c.time_sensitive_right_click = Some(v.as_bool().ok_or("timeSensitiveRightClick must be true or false")?), + "fontFolders" => { + let list = + v.as_array().filter(|a| a.len() <= cadcraft_fonts::ttf::MAX_FONT_DIRS).ok_or("fontFolders must be a list of up to 16 folders")?; + let names: Option> = list.iter().map(Value::as_str).collect(); + c.font_folders = Some(cadcraft_fonts::ttf::clean_dirs(&names.ok_or("fontFolders must be a list of folder paths")?)); + } k if k.eq_ignore_ascii_case("SAVETIME") => { let max = cadcraft_engine::autosave::MAX_SAVETIME; let n = v @@ -214,6 +222,7 @@ fn ui_json(app: &CadApp) -> Map { m.insert("SAVETIME".into(), json!(cadcraft_engine::autosave::savetime())); m.insert("SAVEFILEPATH".into(), json!(cadcraft_engine::autosave::savefilepath())); m.insert("timeSensitiveRightClick".into(), json!(o.time_sensitive_right_click)); + m.insert("fontFolders".into(), json!(cadcraft_fonts::ttf::font_dirs())); m } @@ -284,6 +293,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { if let Some(b) = ui.time_sensitive_right_click { app.options.time_sensitive_right_click = b; } + if let Some(dirs) = &ui.font_folders { + cadcraft_fonts::ttf::set_font_dirs(dirs); + } Ok(report(app)) } @@ -297,6 +309,37 @@ fn reset_ui(app: &mut CadApp) { app.ui.system_cursor = d.system_cursor; app.ui.history_lines = d.history_lines; app.options = UiOptions::default(); + cadcraft_fonts::ttf::set_font_dirs::<&str>(&[]); +} + +/// Fonts for font lists, refreshed when the font set changes: (text style font names — the +/// user's folders' fonts first —, family names of the user's fonts). +pub fn font_choices() -> (Vec, Vec) { + thread_local! { + static CACHE: std::cell::RefCell, Vec)>> = const { std::cell::RefCell::new(None) }; + } + let generation = cadcraft_fonts::ttf::generation(); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + if let Some((g, names, families)) = c.as_ref() + && *g == generation + { + return (names.clone(), families.clone()); + } + let fonts = cadcraft_fonts::ttf::installed(); + let mut names = vec![cadcraft_fonts::BUILTIN_FONT.to_string()]; + names.extend(fonts.iter().map(|f| f.name.clone())); + let mut families: Vec = Vec::new(); + for f in fonts.iter().filter(|f| f.user) { + if let Some(fam) = &f.family + && !families.contains(fam) + { + families.push(fam.clone()); + } + } + *c = Some((generation, names.clone(), families.clone())); + (names, families) + }) } impl CadApp { @@ -314,6 +357,7 @@ impl CadApp { "selectionColor": color_json(self.options.selection_color), "snapMarkerSize": self.options.snap_marker_size, "timeSensitiveRightClick": self.options.time_sensitive_right_click, + "fontFolders": cadcraft_fonts::ttf::font_dirs(), }) .to_string() } @@ -329,7 +373,9 @@ impl CadApp { cadcraft_engine::cmd::options::restore(&mut self.session, vars); } let mut c = UiChanges::default(); - for key in ["systemCursor", "modelBackground", "paperBackground", "selectionColor", "snapMarkerSize", "timeSensitiveRightClick"] { + for key in + ["systemCursor", "modelBackground", "paperBackground", "selectionColor", "snapMarkerSize", "timeSensitiveRightClick", "fontFolders"] + { if let Some(value) = v.get(key) { let _ = parse_ui(key, value, &mut c); } @@ -353,6 +399,9 @@ impl CadApp { if let Some(b) = c.time_sensitive_right_click { self.options.time_sensitive_right_click = b; } + if let Some(dirs) = &c.font_folders { + cadcraft_fonts::ttf::set_font_dirs(dirs); + } } } diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index c5283e084f..c99c06e4b3 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -126,9 +126,15 @@ fn command_known(id: &str) -> bool { pub fn toolsets(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); + // Right-click anywhere in Tool Sets: where to put it (float, pin, ribbon, group, close). + let place = crate::docking::toolsets_place(app); + let panel_groups = crate::docking::toolsets_groups(app); + let mut panel_action: Option = None; egui::Frame::NONE.fill(t.panel).show(ui, |ui| { let r = ui.max_rect(); let p = ui.painter().clone(); + ui.interact(r, ui.id().with("ts_background"), Sense::click()) + .context_menu(|ui| crate::docking::toolsets_menu(ui, place, &panel_groups, &mut panel_action)); // Tabs. let tab_h = 28.0; let mut x = r.left(); @@ -164,6 +170,10 @@ pub fn toolsets(app: &mut CadApp, ui: &mut egui::Ui) { let mut toggle_group = None; let mut tool_visible: Option<(String, bool)> = None; let mut restore: Vec = Vec::new(); + // Right-click a tool: put it on a tool bar or take it off. + let toolbar_items: Vec<(crate::toolbar::Bar, Vec)> = + crate::toolbar::Bar::ALL.into_iter().map(|bar| (bar, crate::toolbar::state(&app.ui, bar).items)).collect(); + let mut to_toolbar: Option<(&'static str, crate::toolbar::Bar, bool)> = None; ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing = vec2(0.0, 0.0); @@ -220,7 +230,9 @@ pub fn toolsets(app: &mut CadApp, ui: &mut egui::Ui) { continue; } ui.add_enabled_ui(command_known(cmd), |ui| { - if icons::button(ui, *icon, 40.0, tip, false).clicked() { + let resp = crate::toolbar::tool_button(ui, *icon, 40.0, cmd, tip); + toolbar_menu(&resp, cmd, &toolbar_items, &mut to_toolbar, (place, &panel_groups, &mut panel_action)); + if resp.clicked() { clicked = Some(cmd); } }); @@ -236,7 +248,9 @@ pub fn toolsets(app: &mut CadApp, ui: &mut egui::Ui) { ui.spacing_mut().item_spacing = vec2(2.0, 0.0); for (icon, cmd, tip) in row.iter() { ui.add_enabled_ui(command_known(cmd), |ui| { - if icons::button(ui, *icon, 23.0, tip, false).clicked() { + let resp = crate::toolbar::tool_button(ui, *icon, 23.0, cmd, tip); + toolbar_menu(&resp, cmd, &toolbar_items, &mut to_toolbar, (place, &panel_groups, &mut panel_action)); + if resp.clicked() { clicked = Some(cmd); } }); @@ -267,11 +281,51 @@ pub fn toolsets(app: &mut CadApp, ui: &mut egui::Ui) { app.ui.collapsed_groups.push(g); } } + if let Some((cmd, bar, add)) = to_toolbar { + let id = if add { "ui.toolbar.add" } else { "ui.toolbar.remove" }; + if let Err(e) = app.run(id, json!({ "command": cmd, "bar": bar.id() })) { + app.set_status(&e); + } + } if let Some(c) = clicked { app.cmd.buffer.clear(); app.start(c); } }); + if let Some(a) = panel_action + && let Err(e) = crate::docking::apply_toolsets(app, a, ui.ctx()) + { + app.set_status(&e); + } +} + +/// What the Tool Sets panel menu needs: where Tool Sets is, the groups it can join, and where the +/// choice goes. +type PanelMenu<'a> = (crate::docking::ToolSetsPlace, &'a [(crate::docking::Panel, String)], &'a mut Option); + +/// The right-click menu of a Tool Sets button: a tick per tool bar puts the tool on that bar or +/// takes it off. +fn toolbar_menu( + resp: &egui::Response, + cmd: &'static str, + bars: &[(crate::toolbar::Bar, Vec)], + to_toolbar: &mut Option<(&'static str, crate::toolbar::Bar, bool)>, + panel: PanelMenu<'_>, +) { + resp.context_menu(|ui| { + let (place, groups, out) = panel; + crate::docking::toolsets_menu(ui, place, groups, out); + ui.separator(); + ui.label(egui::RichText::new(crate::tl!("Show on Tool Bar")).weak()); + for (bar, items) in bars { + let on = items.iter().any(|i| i == cmd); + let mut checked = on; + if ui.checkbox(&mut checked, crate::i18n::t(bar.title())).changed() { + *to_toolbar = Some((cmd, *bar, checked)); + ui.close(); + } + } + }); } pub const MODELING: &[(&str, &[Tool], &[Tool])] = &[ @@ -302,7 +356,7 @@ fn section_header(ui: &mut egui::Ui, title: &str) -> Rect { hr } -fn swatch(p: &egui::Painter, r: Rect, c: Color) { +pub(crate) fn swatch(p: &egui::Painter, r: Rect, c: Color) { let rgb = c.resolve(Color::Index(7), Color::Index(7)); p.rect_filled(r, 1.0, Color32::from_rgb(rgb.0, rgb.1, rgb.2)); p.rect_stroke(r, 1.0, Stroke::new(1.0, Color32::from_gray(30)), egui::StrokeKind::Inside); @@ -341,6 +395,38 @@ pub fn right_palettes(app: &mut CadApp, ui: &mut egui::Ui) { }); } +/// A layer for the current-layer drop-downs: name, on, frozen, locked, colour. +pub(crate) type LayerRow = (String, bool, bool, bool, Color); + +/// The current-layer drop-down's list: on/off, freeze/thaw and lock/unlock per layer; picking a +/// name makes it current. The choice comes back in `set_current` or `toggle` (name, key, value). +pub(crate) fn layer_list( + ui: &mut egui::Ui, + layers: &[LayerRow], + cur: &str, + set_current: &mut Option, + toggle: &mut Option<(String, &'static str, bool)>, +) { + for (name, on, frozen, locked, color) in layers { + ui.horizontal(|ui| { + if icons::button(ui, if *on { Icon::Bulb } else { Icon::BulbOff }, 18.0, "On/Off", false).clicked() { + *toggle = Some((name.clone(), "on", !*on)); + } + if icons::button(ui, if *frozen { Icon::Snowflake } else { Icon::Sun }, 18.0, "Freeze/Thaw", false).clicked() { + *toggle = Some((name.clone(), "frozen", !*frozen)); + } + if icons::button(ui, if *locked { Icon::Lock } else { Icon::Unlock }, 18.0, "Lock/Unlock", false).clicked() { + *toggle = Some((name.clone(), "locked", !*locked)); + } + let (sr, _) = ui.allocate_exact_size(vec2(12.0, 12.0), Sense::hover()); + swatch(ui.painter(), sr, *color); + if ui.selectable_label(name.eq_ignore_ascii_case(cur), name).clicked() { + *set_current = Some(name.clone()); + } + }); + } +} + pub(crate) fn layers_section(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); section_header(ui, "Layers"); @@ -376,7 +462,7 @@ pub(crate) fn layers_section(app: &mut CadApp, ui: &mut egui::Ui) { // Current layer combo. let Ok(d) = app.session.doc() else { return }; let cur = d.header.str("CLAYER", "0"); - let layers: Vec<(String, bool, bool, bool, Color)> = d.layers.iter().map(|l| (l.name.clone(), l.on, l.frozen, l.locked, l.color)).collect(); + let layers: Vec = d.layers.iter().map(|l| (l.name.clone(), l.on, l.frozen, l.locked, l.color)).collect(); let cur_info = layers.iter().find(|l| l.0.eq_ignore_ascii_case(&cur)).cloned(); let mut set_current = None; let mut toggle: Option<(String, &str, bool)> = None; @@ -401,24 +487,7 @@ pub(crate) fn layers_section(app: &mut CadApp, ui: &mut egui::Ui) { } icons::paint(p, Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::ChevronDown, false); egui::Popup::from_toggle_button_response(&resp).width(w).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - for (name, on, frozen, locked, color) in &layers { - ui.horizontal(|ui| { - if icons::button(ui, if *on { Icon::Bulb } else { Icon::BulbOff }, 18.0, "On/Off", false).clicked() { - toggle = Some((name.clone(), "on", !*on)); - } - if icons::button(ui, if *frozen { Icon::Snowflake } else { Icon::Sun }, 18.0, "Freeze/Thaw", false).clicked() { - toggle = Some((name.clone(), "frozen", !*frozen)); - } - if icons::button(ui, if *locked { Icon::Lock } else { Icon::Unlock }, 18.0, "Lock/Unlock", false).clicked() { - toggle = Some((name.clone(), "locked", !*locked)); - } - let (sr, _) = ui.allocate_exact_size(vec2(12.0, 12.0), Sense::hover()); - swatch(ui.painter(), sr, *color); - if ui.selectable_label(name.eq_ignore_ascii_case(&cur), name).clicked() { - set_current = Some(name.clone()); - } - }); - } + layer_list(ui, &layers, &cur, &mut set_current, &mut toggle); }); }); ui.add_space(4.0); @@ -837,6 +906,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let ids: Vec = sel.iter().map(|h| h.hex()).collect(); let mut set: Option = None; let mut custom_set: Option = None; + let mut dim_override: Option = None; let group = |ui: &mut egui::Ui, title: &str| { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::hover()); ui.painter().rect_filled(r.shrink2(vec2(6.0, 1.0)), 2.0, t.chrome_dark); @@ -1046,16 +1116,70 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Angle", "angle", real(hh.angle.to_degrees()), &mut set, &mut bad, &ids); } EntityKind::Dimension(dm) => { + prop_row(ui, "Dim style", |ui| { + if let Some(n) = pick_menu(ui, &dm.style, d.dim_styles.iter().map(|st| st.name.clone())) { + set = Some(json!({ "handles": ids, "dimStyle": n })); + } + }); + prop_row(ui, "Measurement", |ui| read_only(ui, &cadcraft_render::dimension_in(d, dm).value)); prop_row(ui, "Text override", |ui| { if let Some(s) = edit_field(ui, ui.id().with(("dimtxt", &ids)), dm.text.clone()) { set = Some(json!({ "handles": ids, "textOverride": s })); } }); - prop_row(ui, "Dim style", |ui| { - if let Some(n) = pick_menu(ui, &dm.style, d.dim_styles.iter().map(|st| st.name.clone())) { - set = Some(json!({ "handles": ids, "dimStyle": n })); + // The dimension's style settings with its own overrides; a change overrides that + // setting for the selected dimensions (DIMOVERRIDE). + let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides); + let before = crate::dimstyles::style_map(&style); + let mut after = before.clone(); + let names = crate::dimstyles::Names::of(d); + for (title, rows) in crate::dimstyles::PROPERTIES { + group(ui, title); + for (label, kind) in rows.iter() { + prop_row(ui, label, |ui| { + crate::dimstyles::field_row(ui, egui::Id::new(("cc_dimprop", *title, *label)), &names, &mut after, *kind); + }); + } + } + let changed = crate::dimstyles::changed_fields(&before, &after); + if !changed.is_empty() { + let mut p = changed; + p.insert("handles".into(), json!(ids)); + dim_override = Some(Value::Object(p)); + } + } + EntityKind::MLeader(ml) => { + let styles: Vec = if d.mleader_styles.is_empty() { + vec!["Standard".to_string()] + } else { + d.mleader_styles.iter().map(|s| s.name.clone()).collect() + }; + prop_row(ui, "Multileader style", |ui| { + if let Some(n) = pick_menu(ui, &ml.style, styles) { + set = Some(json!({ "handles": ids, "mleaderStyle": n })); } }); + group(ui, "Leaders"); + let (straight, spline) = (crate::tl!("Straight").to_string(), crate::tl!("Spline").to_string()); + prop_row(ui, "Leader type", |ui| { + let cur = if ml.spline { &spline } else { &straight }; + if let Some(n) = pick_menu(ui, cur, [straight.clone(), spline.clone()]) { + set = Some(json!({ "handles": ids, "leaderType": if n == spline { "spline" } else { "straight" } })); + } + }); + // The arrowhead: built-in ones and the drawing's arrowhead blocks, as for dimensions. + let names = crate::dimstyles::Names::of(d); + prop_row(ui, "Arrowhead", |ui| { + if let Some(v) = crate::dimstyles::arrow_combo(ui, egui::Id::new(("cc_mlarrow", &ids)), &names, ml.arrow_in(d)) { + set = Some(json!({ "handles": ids, "arrow": v })); + } + }); + num(ui, "Arrowhead size", "arrowSize", real(ml.arrow_size), &mut set, &mut bad, &ids); + num(ui, "Landing distance", "dogleg", real(ml.dogleg), &mut set, &mut bad, &ids); + if let Some(t) = &ml.text { + group(ui, "Text"); + num(ui, "Text height", "textHeight", real(t.height), &mut set, &mut bad, &ids); + } } EntityKind::Insert(i) => { // A dynamic block reference shows its dynamic block's name, not its anonymous @@ -1097,4 +1221,166 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { if let Some(p) = custom_set { let _ = app.run("blocks.reference.set", p); } + if let Some(p) = dim_override { + let _ = app.run("dimstyle.override", p); + } +} + +/// The Tool Sets ribbon: tabs by task, each a row of the Tool Sets groups (by name). +pub const RIBBON: &[(&str, &[&str])] = &[ + ("Draw", &["Draw", "Hatch"]), + ("Modify", &["Modify"]), + ("Annotate", &["Text", "Dimension", "Leader"]), + ("Block", &["Block"]), + ("Parametric", &["Parametric"]), + ("3D Modeling", &["Primitives", "Solid", "Boolean", "View"]), +]; + +/// A Tool Sets group by name (Drafting, then Modeling). +fn tool_group(name: &str) -> Option<&'static (&'static str, &'static [Tool], &'static [Tool])> { + DRAFTING.iter().chain(MODELING.iter()).find(|(n, _, _)| *n == name) +} + +/// Ribbon heights: the tab strip, the tools, the group names under them. +const RIBBON_TABS: f32 = 26.0; +const RIBBON_TOOLS: f32 = 80.0; +const RIBBON_NAMES: f32 = 18.0; +/// Small ribbon buttons are stacked three to a column. +const RIBBON_ROWS: usize = 3; + +/// Tool Sets as a ribbon, right under the menu bar: a tab per task, its tool groups side by side +/// (large tools with their names, then small ones in columns of three), the group's name under it. +pub fn ribbon(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let place = crate::docking::toolsets_place(app); + let groups = crate::docking::toolsets_groups(app); + let mut panel_action: Option = None; + let toolbar_items: Vec<(crate::toolbar::Bar, Vec)> = + crate::toolbar::Bar::ALL.into_iter().map(|bar| (bar, crate::toolbar::state(&app.ui, bar).items)).collect(); + let mut to_toolbar: Option<(&'static str, crate::toolbar::Bar, bool)> = None; + let mut clicked: Option<&'static str> = None; + let mut tab_clicked: Option<&'static str> = None; + if !RIBBON.iter().any(|(n, _)| *n == app.ui.ribbon_tab) { + app.ui.ribbon_tab = "Draw".into(); + } + let current = app.ui.ribbon_tab.clone(); + let hidden: Vec = app.ui.hidden_tools.clone(); + let height = RIBBON_TABS + RIBBON_TOOLS + RIBBON_NAMES + 4.0; + egui::Panel::top("cc_ribbon").exact_size(height).frame(egui::Frame::NONE.fill(t.panel)).show(ui, |ui| { + let r = ui.max_rect(); + let p = ui.painter().clone(); + ui.interact(r, ui.id().with("ribbon_background"), Sense::click()) + .context_menu(|ui| crate::docking::toolsets_menu(ui, place, &groups, &mut panel_action)); + // Tabs. + let strip = Rect::from_min_size(r.min, vec2(r.width(), RIBBON_TABS)); + p.rect_filled(strip, 0.0, t.chrome); + let mut x = r.left() + 6.0; + for (name, _) in RIBBON { + let label = crate::i18n::t(name); + let w = p.layout_no_wrap(label.to_string(), egui::FontId::proportional(13.0), t.text).size().x + 24.0; + let tr = Rect::from_min_size(pos2(x, r.top() + 2.0), vec2(w, RIBBON_TABS - 2.0)); + let active = current == *name; + let resp = ui.interact(tr, ui.id().with(("ribbon_tab", name)), Sense::click()); + if active { + p.rect_filled(tr, egui::CornerRadius { nw: 3, ne: 3, sw: 0, se: 0 }, t.panel); + } else if resp.hovered() { + p.rect_filled(tr, 3.0, t.control_hover); + } + p.text(tr.center(), egui::Align2::CENTER_CENTER, label, egui::FontId::proportional(13.0), if active { t.text } else { t.text_dim }); + icons::describe_control(ui, &resp, label, Some(active), true); + resp.context_menu(|ui| crate::docking::toolsets_menu(ui, place, &groups, &mut panel_action)); + if resp.clicked() { + tab_clicked = Some(name); + } + x += w + 2.0; + } + // The open tab's groups. + let body = Rect::from_min_max(pos2(r.left(), strip.bottom() + 2.0), r.max); + let groups_here = RIBBON.iter().find(|(n, _)| *n == current).map_or(&[][..], |(_, g)| *g); + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + egui::ScrollArea::horizontal().id_salt("ribbon_scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing = vec2(2.0, 2.0); + ui.add_space(6.0); + for gname in groups_here { + let Some((name, large, small)) = tool_group(gname) else { continue }; + let shown = + |tools: &[Tool]| -> Vec { tools.iter().copied().filter(|(_, c, _)| !hidden.iter().any(|h| h == c)).collect() }; + let (large, small) = (shown(large), shown(small)); + let group = ui.vertical(|ui| { + ui.horizontal_top(|ui| { + ui.set_height(RIBBON_TOOLS); + ui.spacing_mut().item_spacing = vec2(2.0, 1.0); + for (icon, cmd, tip) in &large { + ui.allocate_ui_with_layout(vec2(66.0, RIBBON_TOOLS), egui::Layout::top_down(egui::Align::Center), |ui| { + ui.add_enabled_ui(command_known(cmd), |ui| { + let resp = crate::toolbar::tool_button(ui, *icon, 36.0, cmd, tip); + toolbar_menu(&resp, cmd, &toolbar_items, &mut to_toolbar, (place, &groups, &mut panel_action)); + if resp.clicked() { + clicked = Some(cmd); + } + }); + ui.add( + egui::Label::new(egui::RichText::new(crate::i18n::t(tip)).size(11.0).color(t.text_dim)) + .wrap_mode(egui::TextWrapMode::Wrap) + .halign(egui::Align::Center) + .selectable(false), + ); + }); + } + for column in small.chunks(RIBBON_ROWS) { + ui.vertical(|ui| { + ui.add_space(2.0); + for (icon, cmd, tip) in column { + ui.add_enabled_ui(command_known(cmd), |ui| { + let resp = crate::toolbar::tool_button(ui, *icon, 24.0, cmd, tip); + toolbar_menu(&resp, cmd, &toolbar_items, &mut to_toolbar, (place, &groups, &mut panel_action)); + if resp.clicked() { + clicked = Some(cmd); + } + }); + } + }); + } + }); + }); + // The group's name under its tools, and a line between groups. + let gr = group.response.rect; + let name_rect = + Rect::from_min_size(pos2(gr.left(), body.top() + RIBBON_TOOLS + 1.0), vec2(gr.width().max(40.0), RIBBON_NAMES)); + ui.painter().text( + name_rect.center(), + egui::Align2::CENTER_CENTER, + crate::i18n::t(name), + egui::FontId::proportional(11.5), + t.text_dim, + ); + ui.add_space(6.0); + let (sep, _) = ui.allocate_exact_size(vec2(1.0, RIBBON_TOOLS + RIBBON_NAMES - 6.0), Sense::hover()); + ui.painter().vline(sep.center().x, sep.y_range(), Stroke::new(1.0, t.border)); + ui.add_space(6.0); + } + }); + }); + }); + p.hline(r.x_range(), r.bottom() - 0.5, Stroke::new(1.0, t.border)); + }); + if let Some(name) = tab_clicked { + app.ui.ribbon_tab = name.into(); + } + if let Some((cmd, bar, add)) = to_toolbar { + let id = if add { "ui.toolbar.add" } else { "ui.toolbar.remove" }; + if let Err(e) = app.run(id, json!({ "command": cmd, "bar": bar.id() })) { + app.set_status(&e); + } + } + if let Some(c) = clicked { + app.cmd.buffer.clear(); + app.start(c); + } + if let Some(a) = panel_action + && let Err(e) = crate::docking::apply_toolsets(app, a, ui.ctx()) + { + app.set_status(&e); + } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9064b92e42..5b0f481e07 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -22,32 +22,59 @@ pub enum ThemePref { /// The default: CADCraft's original look. #[default] Dark, + /// Near-black chrome over a black drawing area. + Black, + /// Light blue chrome (#85abf6) with dark text. + #[serde(rename = "lightblue", alias = "light-blue")] + LightBlue, +} + +/// The palette a theme draws with: the light and dark themes' own, or one of the extra palettes +/// built on them (egui's light / dark look underneath). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Palette { + #[default] + Standard, + Black, + LightBlue, } /// The theme `System` uses when the OS (or browser) reports no appearance. pub const SYSTEM_FALLBACK: Theme = Theme::Dark; impl ThemePref { - pub const ALL: [ThemePref; 3] = [ThemePref::System, ThemePref::Light, ThemePref::Dark]; + pub const ALL: [ThemePref; 5] = [ThemePref::System, ThemePref::Light, ThemePref::Dark, ThemePref::Black, ThemePref::LightBlue]; pub fn as_str(self) -> &'static str { match self { ThemePref::System => "system", ThemePref::Light => "light", ThemePref::Dark => "dark", + ThemePref::Black => "black", + ThemePref::LightBlue => "lightblue", } } pub fn parse(s: &str) -> Option { - ThemePref::ALL.into_iter().find(|t| t.as_str().eq_ignore_ascii_case(s.trim())) + let s = s.trim().replace(['-', '_', ' '], ""); + ThemePref::ALL.into_iter().find(|t| t.as_str().eq_ignore_ascii_case(&s)) + } + + /// The palette this choice draws with. + pub fn palette(self) -> Palette { + match self { + ThemePref::Black => Palette::Black, + ThemePref::LightBlue => Palette::LightBlue, + _ => Palette::Standard, + } } /// The theme to show, given what the OS reports (`ctx.system_theme()`). pub fn resolve(self, system: Option) -> Theme { match self { ThemePref::System => system.unwrap_or(SYSTEM_FALLBACK), - ThemePref::Light => Theme::Light, - ThemePref::Dark => Theme::Dark, + ThemePref::Light | ThemePref::LightBlue => Theme::Light, + ThemePref::Dark | ThemePref::Black => Theme::Dark, } } } @@ -66,6 +93,20 @@ pub fn set_active(theme: Theme) { ACTIVE.with(|a| a.set(theme)); } +thread_local! { + /// The palette in use on the UI thread (set by [`set_palette`] each frame). + static PALETTE: Cell = const { Cell::new(Palette::Standard) }; +} + +/// The palette [`Tokens::get`] returns colours from. +pub fn palette() -> Palette { + PALETTE.with(Cell::get) +} + +pub fn set_palette(p: Palette) { + PALETTE.with(|a| a.set(p)); +} + #[derive(Clone, Copy, Debug, PartialEq)] pub struct Tokens { pub chrome: Color32, @@ -205,6 +246,61 @@ impl Tokens { ..Tokens::DARK }; + /// Near-black chrome and a black drawing area, in [`Tokens::DARK`]'s accents. + pub const BLACK: Tokens = Tokens { + chrome: Color32::from_rgb(0x1a, 0x1a, 0x1a), + chrome_dark: Color32::from_rgb(0x10, 0x10, 0x10), + panel: Color32::from_rgb(0x1c, 0x1c, 0x1c), + tab_active: Color32::from_rgb(0x33, 0x33, 0x33), + control: Color32::from_rgb(0x2a, 0x2a, 0x2a), + control_hover: Color32::from_rgb(0x3a, 0x3a, 0x3a), + border: Color32::from_rgb(0x30, 0x30, 0x30), + canvas: Color32::from_rgb(0x00, 0x00, 0x00), + grid_minor: Color32::from_rgb(0x12, 0x12, 0x12), + grid_major: Color32::from_rgb(0x20, 0x20, 0x20), + text: Color32::from_rgb(0xe6, 0xe6, 0xe6), + text_dim: Color32::from_rgb(0xa8, 0xa8, 0xa8), + text_faint: Color32::from_rgb(0x80, 0x80, 0x80), + icon: Color32::from_rgb(0xd8, 0xd8, 0xd8), + cmd_bg: Color32::from_rgba_unmultiplied_const(0x14, 0x14, 0x14, 0xf0), + field: Color32::from_rgb(0x0c, 0x0c, 0x0c), + cmd_history: Color32::from_rgba_unmultiplied_const(0x0a, 0x0a, 0x0a, 170), + cmd_border: Color32::from_rgb(0x3a, 0x3a, 0x3a), + list_bg: Color32::from_rgb(0x14, 0x14, 0x14), + list_row: Color32::from_rgb(0x2a, 0x2a, 0x2a), + ..Tokens::DARK + }; + + /// Light blue chrome (#85abf6) with dark blue text; the drawing area as in [`Tokens::LIGHT`]. + pub const LIGHT_BLUE: Tokens = Tokens { + chrome: Color32::from_rgb(0x85, 0xab, 0xf6), + chrome_dark: Color32::from_rgb(0x72, 0x99, 0xe6), + panel: Color32::from_rgb(0x9d, 0xbc, 0xf8), + tab_active: Color32::from_rgb(0xc4, 0xd7, 0xfb), + control: Color32::from_rgb(0xae, 0xc8, 0xf9), + control_hover: Color32::from_rgb(0xc2, 0xd6, 0xfb), + border: Color32::from_rgb(0x5f, 0x86, 0xd3), + text: Color32::from_rgb(0x0f, 0x1c, 0x33), + text_dim: Color32::from_rgb(0x26, 0x3a, 0x5c), + text_faint: Color32::from_rgb(0x41, 0x55, 0x78), + icon: Color32::from_rgb(0x15, 0x24, 0x40), + icon_accent: Color32::from_rgb(0x0d, 0x45, 0xb5), + icon_point: Color32::from_rgb(0xc2, 0x44, 0x0c), + accent: Color32::from_rgb(0x16, 0x56, 0xcf), + cmd_bg: Color32::from_rgba_unmultiplied_const(0xe3, 0xec, 0xfd, 0xf0), + toggle_on: Color32::from_rgb(0x16, 0x56, 0xcf), + field: Color32::from_rgb(0xf0, 0xf5, 0xff), + select_bg: Color32::from_rgb(0xc6, 0xda, 0xfd), + cmd_history: Color32::from_rgba_unmultiplied_const(0xd6, 0xe4, 0xfc, 0xdc), + cmd_border: Color32::from_rgb(0x5f, 0x86, 0xd3), + cmd_keyword: Color32::from_rgb(0x0b, 0x46, 0xb0), + cmd_keyword_hover: Color32::from_rgb(0xc4, 0xd7, 0xfb), + list_bg: Color32::from_rgb(0xf2, 0xf7, 0xff), + list_row: Color32::from_rgb(0xd4, 0xe3, 0xfd), + warn: Color32::from_rgb(0x7a, 0x43, 0x00), + ..Tokens::LIGHT + }; + /// The palette of `theme`. pub fn of(theme: Theme) -> Tokens { match theme { @@ -213,9 +309,18 @@ impl Tokens { } } + /// The colours of `palette` over `theme` (an extra palette replaces the theme's own). + pub fn of_palette(theme: Theme, palette: Palette) -> Tokens { + match palette { + Palette::Standard => Tokens::of(theme), + Palette::Black => Tokens::BLACK, + Palette::LightBlue => Tokens::LIGHT_BLUE, + } + } + /// The palette of the theme in use, with the user's drawing-area colours ([`set_canvas`]). pub fn get() -> Tokens { - CANVAS.with(Cell::get).over(Tokens::of(active())) + CANVAS.with(Cell::get).over(Tokens::of_palette(active(), palette())) } /// These tokens with `bg` as the model-space background: the grid, axes, crosshair and the @@ -352,6 +457,18 @@ pub fn install_fonts(ctx: &egui::Context, language: &str) { .enumerate() .map(|(i, bytes)| (format!("system-cjk-{i}"), std::sync::Arc::new(egui::FontData::from_owned(bytes)))), ); + // Drafting symbols (⌀ ∠ ⊥ ℄ …) that the interface face lacks: an installed symbol font + // after the others, so the text editor and its symbol menu never show empty boxes. + let symbols: &[&str] = if cfg!(target_os = "macos") { + &["/System/Library/Fonts/Apple Symbols.ttf", "/System/Library/Fonts/Supplemental/Arial Unicode.ttf"] + } else if cfg!(windows) { + &["C:\\Windows\\Fonts\\seguisym.ttf", "C:\\Windows\\Fonts\\cambria.ttc"] + } else { + &["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/TTF/DejaVuSans.ttf"] + }; + if let Some(bytes) = symbols.iter().find_map(|p| read_capped(std::path::Path::new(p), MAX_UI_FONT_BYTES)) { + added.push(("system-symbols".into(), std::sync::Arc::new(egui::FontData::from_owned(bytes)))); + } // العربية: an installed Arabic face after the Latin ones (egui's bundled faces carry no // Arabic glyphs), for the Arabic interface. if language == "ar" @@ -629,7 +746,14 @@ pub fn can_show(language: &str) -> bool { /// egui's visuals for `theme`, from its tokens. fn visuals(theme: Theme) -> Visuals { - let t = Tokens::of(theme); + // The extra palettes stand on their own look (light blue on egui's light one, black on dark). + let p = palette(); + let base = match p { + Palette::Black => Theme::Dark, + Palette::LightBlue => Theme::Light, + Palette::Standard => theme, + }; + let t = if base == theme { Tokens::of_palette(theme, p) } else { Tokens::of(theme) }; let mut v = match theme { Theme::Dark => Visuals::dark(), Theme::Light => Visuals::light(), @@ -681,6 +805,20 @@ pub fn apply(ctx: &egui::Context, theme: Theme, follow_system: bool) { #[cfg(test)] mod tests { + #[test] + fn black_and_light_blue_themes_have_their_own_palettes() { + use super::{Palette, ThemePref, Tokens}; + assert_eq!(ThemePref::parse("light-blue"), Some(ThemePref::LightBlue)); + assert_eq!(ThemePref::parse("Black"), Some(ThemePref::Black)); + assert_eq!(ThemePref::LightBlue.resolve(None), egui::Theme::Light); + assert_eq!(ThemePref::Black.resolve(None), egui::Theme::Dark); + assert_eq!(Tokens::of_palette(egui::Theme::Light, Palette::LightBlue).chrome, egui::Color32::from_rgb(0x85, 0xab, 0xf6)); + assert_eq!(Tokens::of_palette(egui::Theme::Dark, Palette::Black).canvas, egui::Color32::BLACK); + assert_eq!(ThemePref::LightBlue.palette(), Palette::LightBlue); + let json = serde_json::to_string(&ThemePref::LightBlue).unwrap_or_default(); + assert_eq!(json, "\"lightblue\""); + } + #[test] fn korean_font_rejects_invalid_or_glyphless_files() { for bytes in [vec![], vec![0xff; 32], vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs new file mode 100644 index 0000000000..87a854085a --- /dev/null +++ b/crates/ui-egui/src/toolbar.rs @@ -0,0 +1,1305 @@ +//! The tool bars: strips of command buttons docked along the top of the window (a row) or the +//! left edge (a column). There are three: the standard Tool Bar (file, output, view), the Tool +//! Sets bar (drawing and editing tools) and the Layers bar (layer tools and the current layer). +//! +//! The buttons and their order are the user's: drag a button along the bar to move it, right-click +//! it to remove it, add any Tool Sets command from its right-click menu or from the Customize Tool +//! Bar dialog (Window ▸ Customize Tool Bar...). Drag the handle at the start of the bar to dock it +//! at the top or on the left. Every button has a tooltip with its name, command, alias and +//! keyboard shortcut. +//! +//! The order is saved as command ids in [`crate::UiState::toolbar_items`] (`"|"` is a group +//! separator); ids the bar does not know are skipped, so a hand-edited or older workspace never +//! breaks it. + +use egui::{Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::icons::{self, Icon}; +use crate::theme::Tokens; + +/// A group separator in [`crate::UiState::toolbar_items`]. +pub const SEPARATOR: &str = "|"; +/// Most buttons and separators the bar holds (the saved workspace caps the list too). +pub const MAX_ITEMS: usize = 200; +/// Height of the bar docked at the top, width of the bar docked on the left. +pub const THICKNESS: f32 = 34.0; +/// Button size, the gap after a button and the room a separator takes. +const BUTTON: f32 = 26.0; +const GAP: f32 = 6.0; +const SEP: f32 = 13.0; +/// The drag handle at the start of the bar. +const GRIP: f32 = 12.0; + +/// Where the Tool Bar is docked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Dock { + /// Along the top of the window, buttons in a row. + #[default] + Top, + /// Along the left edge of the window, buttons in a column. + Left, +} + +impl Dock { + pub fn as_str(self) -> &'static str { + match self { + Dock::Top => "top", + Dock::Left => "left", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "top" | "row" | "horizontal" => Some(Dock::Top), + "left" | "column" | "vertical" => Some(Dock::Left), + _ => None, + } + } +} + +/// One of the tool bars. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Bar { + /// The standard Tool Bar: file, undo, output, view and inquiry commands. + Standard, + /// Drawing and editing tools (the classic Draw and Modify bars). + ToolSets, + /// Layer tools and the current layer. + Layers, +} + +impl Bar { + pub const ALL: [Bar; 3] = [Bar::Standard, Bar::ToolSets, Bar::Layers]; + + pub fn id(self) -> &'static str { + match self { + Bar::Standard => "standard", + Bar::ToolSets => "toolSets", + Bar::Layers => "layers", + } + } + + pub fn parse(s: &str) -> Option { + let s = s.trim(); + Bar::ALL.into_iter().find(|b| b.id().eq_ignore_ascii_case(s)).or(match s.to_ascii_lowercase().as_str() { + "" | "toolbar" | "tool bar" => Some(Bar::Standard), + "toolsets" | "tool sets" | "draw" => Some(Bar::ToolSets), + _ => None, + }) + } + + /// English name (translated when shown). + pub fn title(self) -> &'static str { + match self { + Bar::Standard => "Standard Tool Bar", + Bar::ToolSets => "Tool Sets Tool Bar", + Bar::Layers => "Layers Tool Bar", + } + } + + /// Accessible label of the bar's More button. + fn more_label(self) -> &'static str { + match self { + Bar::Standard => "More toolbar commands", + Bar::ToolSets => "More Tool Sets bar commands", + Bar::Layers => "More Layers bar commands", + } + } + + pub fn default_items(self) -> Vec { + let ids: &[&str] = match self { + Bar::Standard => return default_items(), + Bar::ToolSets => &[ + "line", + "pline", + "circle", + "arc", + "rectang", + "polygon", + "ellipse", + "spline", + "hatch", + "|", + "insert", + "block", + "|", + "text", + "mtext", + "|", + "move", + "copy", + "rotate", + "mirror", + "scale", + "offset", + "arrayrect", + "trim", + "extend", + "fillet", + "erase", + ], + Bar::Layers => { + &["ui.dialog.layers", LAYER_COMBO, "|", "laymcur", "laymch", "layerp", "|", "layiso", "layoff", "layfrz", "laylck", "layulk"] + } + }; + ids.iter().map(|s| s.to_string()).collect() + } + + pub fn default_state(self) -> BarState { + BarState { show: true, dock: if self == Bar::ToolSets { Dock::Left } else { Dock::Top }, items: self.default_items() } + } +} + +/// Whether a tool bar shows, where it is docked and its buttons in order (command ids; `"|"` +/// separates groups). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct BarState { + pub show: bool, + pub dock: Dock, + pub items: Vec, +} + +/// The state fields of `bar`: shown, dock, items. +fn fields(ui: &mut crate::UiState, bar: Bar) -> (&mut bool, &mut Dock, &mut Vec) { + match bar { + Bar::Standard => (&mut ui.show_toolbar, &mut ui.toolbar_dock, &mut ui.toolbar_items), + Bar::ToolSets => (&mut ui.toolsets_bar.show, &mut ui.toolsets_bar.dock, &mut ui.toolsets_bar.items), + Bar::Layers => (&mut ui.layers_bar.show, &mut ui.layers_bar.dock, &mut ui.layers_bar.items), + } +} + +/// A copy of `bar`'s state. +pub fn state(ui: &crate::UiState, bar: Bar) -> BarState { + match bar { + Bar::Standard => BarState { show: ui.show_toolbar, dock: ui.toolbar_dock, items: ui.toolbar_items.clone() }, + Bar::ToolSets => ui.toolsets_bar.clone(), + Bar::Layers => ui.layers_bar.clone(), + } +} + +/// The current-layer drop-down, an item only the bars hold (not a command). +pub const LAYER_COMBO: &str = "layer.combo"; +/// Width of the current-layer drop-down in a row. +const COMBO_W: f32 = 220.0; +/// The category of the layer tools. +const LAYERS_CATEGORY: &str = "Layers"; +/// The layer tools (the Layers palette's row) and the current layer. +const LAYER_TOOLS: &[(Icon, &str, &str)] = &[ + (Icon::LayerProps, "ui.dialog.layers", "Layer Properties"), + (Icon::Layers, LAYER_COMBO, "Current Layer"), + (Icon::MakeCurrent, "laymcur", "Make Object's Layer Current"), + (Icon::LayerMatch, "laymch", "Match Layer"), + (Icon::LayerPrev, "layerp", "Previous Layer"), + (Icon::LayerIso, "layiso", "Isolate"), + (Icon::LayerOff, "layoff", "Turn Off Layer"), + (Icon::LayerFreeze, "layfrz", "Freeze Layer"), + (Icon::LayerLock, "laylck", "Lock Layer"), + (Icon::Unlock, "layulk", "Unlock Layer"), +]; + +/// The default bar: file, undo, output, exchange, navigation, palettes, inquiry and help groups. +const STANDARD: &[&[(Icon, &str, &str, Option<&str>)]] = &[ + &[ + (Icon::New, "new", "New Drawing", Some("Cmd+N")), + (Icon::Open, "open", "Open", Some("Cmd+O")), + (Icon::Save, "qsave", "Save", Some("Cmd+S")), + (Icon::SaveAs, "saveas", "Save As", None), + ], + &[(Icon::Undo, "u", "Undo", Some("Cmd+Z")), (Icon::Redo, "redo", "Redo", Some("Cmd+Shift+Z"))], + &[ + (Icon::Plot, "plot", "Print", None), + (Icon::Publish, "publish", "Batch Publish", None), + (Icon::PageSetup, "pagesetup", "Page Setup Manager", None), + (Icon::Preview, "preview", "Plot Preview", None), + ], + &[ + (Icon::Import, "import", "Import", None), + (Icon::Export, "export", "Export", None), + (Icon::Attach, "attach", "Attach", None), + (Icon::Share, "share", "Share", None), + ], + &[(Icon::ZoomWindow, "zoom.window", "Zoom Window", None), (Icon::Pan, "pan", "Pan", None), (Icon::Orbit, "3dorbit", "Orbit", None)], + &[ + (Icon::ZoomExtents, "zoom.extents", "Zoom Extents", None), + (Icon::Properties, "ui.toggle.palettes", "Properties", None), + (Icon::Layers, "ui.dialog.layers", "Layer Properties Manager", None), + (Icon::Blocks, "ui.dialog.blocks", "Blocks", None), + ], + &[(Icon::Measure, "dist", "Measure Distance", None), (Icon::List, "list", "List", None), (Icon::Area, "area", "Area", None)], + &[(Icon::Help, "ui.dialog.about", "Help", None)], +]; + +/// The category of the [`STANDARD`] tools in the Customize dialog. +const STANDARD_CATEGORY: &str = "Standard"; + +/// A command the Tool Bar can hold. +#[derive(Clone, Copy, Debug)] +pub struct Tool { + pub icon: Icon, + /// Command id, as `app.start` takes it. + pub command: &'static str, + /// English label (translated when shown). + pub label: &'static str, + /// Tool Sets category, or "Standard". + pub category: &'static str, + shortcut: Option<&'static str>, +} + +impl Tool { + /// A tool outside the catalog (a Tool Sets button), for its tooltip. + pub fn new(icon: Icon, command: &'static str, label: &'static str) -> Tool { + Tool { icon, command, label, category: "", shortcut: None } + } + + /// Keyboard shortcut, in the menus' notation (`Cmd+S`). + pub fn shortcut(&self) -> Option<&'static str> { + self.shortcut + .or_else(|| cadcraft_engine::find_command(self.command).and_then(|c| c.shortcut)) + .or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == self.command).and_then(|c| c.3)) + } + + /// Whether the command exists yet. The standard tools always run (some are routed by the UI). + pub fn enabled(&self) -> bool { + self.category == STANDARD_CATEGORY + || self.category == LAYERS_CATEGORY + || cadcraft_engine::find_command(self.command).is_some() + || crate::menus::is_ui_command(self.command) + } + + /// Name with its shortcut: the button's accessible label. + fn accessible_label(&self, mac: bool) -> String { + match self.shortcut() { + Some(sc) => format!("{} ({})", crate::i18n::t(self.label), crate::menus::shortcut_label(sc, mac)), + None => crate::i18n::t(self.label).to_string(), + } + } +} + +fn push(tools: &mut Vec, tool: Tool) { + if !tools.iter().any(|t| t.command == tool.command) { + tools.push(tool); + } +} + +/// Every command the bar can hold: the standard tools, then the Tool Sets (Drafting, Modeling). +pub fn catalog() -> &'static [Tool] { + static CATALOG: std::sync::OnceLock> = std::sync::OnceLock::new(); + CATALOG.get_or_init(|| { + let mut tools = Vec::new(); + for group in STANDARD { + for (icon, command, label, shortcut) in group.iter() { + push(&mut tools, Tool { icon: *icon, command, label, category: STANDARD_CATEGORY, shortcut: *shortcut }); + } + } + for (icon, command, label) in LAYER_TOOLS { + push(&mut tools, Tool { icon: *icon, command, label, category: LAYERS_CATEGORY, shortcut: None }); + } + for groups in [crate::palettes::DRAFTING, crate::palettes::MODELING] { + for (name, large, small) in groups.iter() { + for (icon, command, label) in large.iter().chain(small.iter()) { + push(&mut tools, Tool { icon: *icon, command, label, category: name, shortcut: None }); + } + } + } + tools + }) +} + +/// The catalog entry for a command id. +pub fn find(command: &str) -> Option { + catalog().iter().find(|t| t.command == command).copied() +} + +/// The standard bar CADCraft starts with. +pub fn default_items() -> Vec { + let mut items = Vec::new(); + for (i, group) in STANDARD.iter().enumerate() { + if i > 0 { + items.push(SEPARATOR.to_string()); + } + items.extend(group.iter().map(|(_, command, _, _)| command.to_string())); + } + items +} + +/// `items` without unknown or repeated commands, doubled, leading or trailing separators, at +/// most [`MAX_ITEMS`] long. +pub fn sanitize(items: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for item in items.iter().take(MAX_ITEMS * 4) { + if out.len() >= MAX_ITEMS { + break; + } + if item == SEPARATOR { + if out.last().is_some_and(|last| last != SEPARATOR) { + out.push(SEPARATOR.to_string()); + } + } else if find(item).is_some() && !out.contains(item) { + out.push(item.clone()); + } + } + while out.last().is_some_and(|last| last == SEPARATOR) { + out.pop(); + } + out +} + +/// Move the item at `from` so it lands before the item now at `slot` (`items.len()` = the end). +pub fn move_item(items: &mut Vec, from: usize, slot: usize) { + if from >= items.len() || slot > items.len() { + return; + } + let item = items.remove(from); + let to = if slot > from { slot - 1 } else { slot }; + items.insert(to.min(items.len()), item); +} + +/// Add `command` before `index` (or at the end). Unknown and present commands are left out. +pub fn add_item(items: &mut Vec, command: &str, index: Option) -> bool { + if find(command).is_none() || items.iter().any(|i| i == command) || items.len() >= MAX_ITEMS { + return false; + } + let at = index.unwrap_or(items.len()).min(items.len()); + items.insert(at, command.to_string()); + true +} + +/// The tooltip of a tool button: name, command and alias, shortcut. +pub fn tooltip(ui: &mut egui::Ui, tool: &Tool, mac: bool) { + ui.set_max_width(280.0); + ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); + if !tool.command.starts_with("ui.") && tool.command != LAYER_COMBO { + let name = tool.command.split('.').next().unwrap_or(tool.command).to_ascii_uppercase(); + let mut line = format!("{} {name}", crate::tl!("Command:")); + if let Some(alias) = cadcraft_engine::find_command(tool.command).and_then(|c| c.aliases.first()) { + line.push_str(&format!(" {} {}", crate::tl!("Alias:"), alias.to_ascii_uppercase())); + } + ui.label(RichText::new(line).weak()); + } + if let Some(sc) = tool.shortcut() { + ui.label(RichText::new(format!("{} {}", crate::tl!("Shortcut:"), crate::menus::shortcut_label(sc, mac))).weak()); + } + if !tool.enabled() { + ui.label(RichText::new(crate::tl!("Not available yet")).weak().italics()); + } +} + +/// An icon button with the tool tooltip (Tool Sets palette). +pub fn tool_button(ui: &mut egui::Ui, icon: Icon, size: f32, command: &'static str, label: &'static str) -> egui::Response { + let tool = Tool::new(icon, command, label); + let mac = ui.ctx().os().is_mac(); + icons::button_bare(ui, icon, size, label, false).on_hover_ui(|ui| tooltip(ui, &tool, mac)).on_disabled_hover_ui(|ui| tooltip(ui, &tool, mac)) +} + +/// What the bar was asked to do this frame (applied after drawing it). +enum Action { + Run(&'static str), + Move { + from: usize, + slot: usize, + }, + Remove(usize), + Dock(Dock), + Customize, + Show(Bar, bool), + /// A command of the application menu (as the menus run it). + AppMenu, + AppCommand(&'static str), + SetLayer(String), + LayerToggle(String, &'static str, bool), +} + +/// The bar's right-click menu; `item` is the button it was opened on. +fn options_menu(ui: &mut egui::Ui, bar: Bar, shown: [bool; 3], item: Option, dock: Dock, action: &mut Option) { + if let Some(index) = item { + if ui.button(crate::tl!("Remove from Tool Bar")).clicked() { + *action = Some(Action::Remove(index)); + ui.close(); + } + ui.separator(); + } + if ui.radio(dock == Dock::Top, crate::tl!("Dock at Top")).clicked() { + *action = Some(Action::Dock(Dock::Top)); + ui.close(); + } + if ui.radio(dock == Dock::Left, crate::tl!("Dock at Left")).clicked() { + *action = Some(Action::Dock(Dock::Left)); + ui.close(); + } + ui.separator(); + if ui.button(crate::tl!("Customize Tool Bar...")).clicked() { + *action = Some(Action::Customize); + ui.close(); + } + if ui.button(crate::tl!("Hide Tool Bar")).clicked() { + *action = Some(Action::Show(bar, false)); + ui.close(); + } + ui.separator(); + ui.label(RichText::new(crate::tl!("Tool Bars")).weak()); + for (other, on) in Bar::ALL.into_iter().zip(shown) { + let mut checked = on; + if ui.checkbox(&mut checked, crate::i18n::t(other.title())).changed() { + *action = Some(Action::Show(other, checked)); + ui.close(); + } + } +} + +/// Where dropping the bar's handle at `pointer` docks it: near the top or the left edge. +fn drop_target(screen: Rect, pointer: Pos2) -> Option { + let from_left = pointer.x - screen.left(); + let from_top = pointer.y - screen.top(); + if from_left.min(from_top) > 160.0 { + return None; + } + Some(if from_left < from_top { Dock::Left } else { Dock::Top }) +} + +/// The standard bar docked at the top, in `row` of the title panel. +pub fn top(app: &mut CadApp, ui: &mut egui::Ui, row: Rect) { + strip(app, ui, row, false, Bar::Standard); +} + +/// The other bars docked at the top: one row each, below the menu bar. +pub fn top_panels(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + for bar in [Bar::ToolSets, Bar::Layers] { + let st = state(&app.ui, bar); + if !st.show || st.dock != Dock::Top { + continue; + } + egui::Panel::top(egui::Id::new(("cc_toolbar_top", bar.id()))) + .exact_size(THICKNESS) + .resizable(false) + .frame(egui::Frame::NONE.fill(t.chrome)) + .show(ui, |ui| { + let r = ui.max_rect(); + ui.painter().hline(r.x_range(), r.bottom() - 0.5, Stroke::new(1.0, t.border)); + strip(app, ui, Rect::from_min_max(pos2(r.left() + 12.0, r.top()), r.max), false, bar); + }); + } +} + +/// The bars docked on the left: a column each along the left edge of the window. +pub fn left_panels(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + for bar in Bar::ALL { + let st = state(&app.ui, bar); + if !st.show || st.dock != Dock::Left { + continue; + } + let id = if bar == Bar::Standard { egui::Id::new("cc_toolbar_left") } else { egui::Id::new(("cc_toolbar_left", bar.id())) }; + egui::Panel::left(id).exact_size(THICKNESS).resizable(false).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| { + let r = ui.max_rect(); + ui.painter().vline(r.right() - 0.5, r.y_range(), Stroke::new(1.0, t.border)); + strip(app, ui, r, true, bar); + }); + } +} + +/// The current layer and every layer, for the drop-down. +fn layer_rows(app: &CadApp) -> Option<(String, Vec)> { + let d = app.session.doc().ok()?; + let cur = d.header.str("CLAYER", "0").to_string(); + Some((cur, d.layers.iter().map(|l| (l.name.clone(), l.on, l.frozen, l.locked, l.color)).collect())) +} + +/// Lay out and run `bar` in `area`: a row, or a column when `vertical`. +fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: Bar) { + let t = Tokens::get(); + let mac = ui.ctx().os().is_mac(); + let st = state(&app.ui, bar); + let dock = st.dock; + let shown_bars = Bar::ALL.map(|b| state(&app.ui, b).show); + let mut items = sanitize(&st.items); + let mut action: Option = None; + let id = if bar == Bar::Standard { ui.id().with("cc_toolbar") } else { egui::Id::new(("cc_toolbar", bar.id())) }; + let layers = if items.iter().any(|i| i == LAYER_COMBO) { layer_rows(app) } else { None }; + + // Main-axis start and end, cross-axis centre; `slot` is a rect at a main-axis position. + let (start, end) = if vertical { (area.top() + 4.0, area.bottom() - 4.0) } else { (area.left(), area.right() - 12.0) }; + let cross = if vertical { area.center().x } else { area.center().y }; + let slot = |pos: f32, len: f32, thick: f32| { + if vertical { + Rect::from_min_size(pos2(cross - thick / 2.0, pos), vec2(thick, len)) + } else { + Rect::from_min_size(pos2(pos, cross - thick / 2.0), vec2(len, thick)) + } + }; + let main = |p: Pos2| if vertical { p.y } else { p.x }; + + // The bar's empty space: right-click for its options (not a keyboard stop). + let background = ui.interact(area, id.with("background"), Sense::CLICK); + background.context_menu(|ui| options_menu(ui, bar, shown_bars, None, dock, &mut action)); + + // The handle: drag it to the top or the left edge to dock the bar there. + let grip = slot(start, GRIP, BUTTON); + let grip_resp = ui.interact(grip, id.with("grip"), Sense::DRAG).on_hover_cursor(egui::CursorIcon::Grab); + for i in 0..4 { + for j in [-2.0, 2.0] { + let along = grip.min + + if vertical { + vec2(grip.width() / 2.0 - 7.5 + i as f32 * 5.0, grip.height() / 2.0 + j) + } else { + vec2(grip.width() / 2.0 + j, grip.height() / 2.0 - 7.5 + i as f32 * 5.0) + }; + ui.painter().circle_filled(along, 1.0, t.text_dim); + } + } + let grip_resp = if grip_resp.dragged() { + grip_resp + } else { + grip_resp.on_hover_ui(|ui| { + ui.label(RichText::new(crate::i18n::t(bar.title())).strong()); + ui.label(crate::tl!("Drag to dock the Tool Bar at the top or on the left")); + }) + }; + let screen = ui.ctx().content_rect(); + if grip_resp.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if let Some(target) = ui.ctx().pointer_latest_pos().and_then(|p| drop_target(screen, p)) { + let preview = match target { + Dock::Top => Rect::from_min_size(screen.min, vec2(screen.width(), THICKNESS)), + Dock::Left => Rect::from_min_size(screen.min, vec2(THICKNESS, screen.height())), + }; + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, id.with("dock_preview"))); + painter.rect_filled(preview, 2.0, t.accent.gamma_multiply(0.25)); + painter.rect_stroke(preview, 2.0, Stroke::new(2.0, t.accent), egui::StrokeKind::Inside); + } + } + if grip_resp.drag_stopped() + && let Some(target) = ui.ctx().pointer_latest_pos().and_then(|p| drop_target(screen, p)) + { + action = Some(Action::Dock(target)); + } + + // How many items fit; the rest go to the More menu at the end. + let mut first = start + GRIP + 4.0; + // The standard bar starts with the application button: always there, never customized. + if bar == Bar::Standard { + let br = slot(first, BUTTON, BUTTON); + if app_button(ui, br, id.with("app_menu"), vertical) { + action = Some(Action::AppMenu); + } + let at = first + BUTTON + GAP + (SEP - GAP) / 2.0; + let half = BUTTON / 2.0 - 3.0; + if vertical { + ui.painter().hline((cross - half)..=(cross + half), at, Stroke::new(1.0, t.border)); + } else { + ui.painter().vline(at, (cross - half)..=(cross + half), Stroke::new(1.0, t.border)); + } + first += BUTTON + GAP + SEP; + } + let extent = |item: &String| { + if item == SEPARATOR { + SEP + } else if item == LAYER_COMBO && !vertical { + COMBO_W + GAP + } else { + BUTTON + GAP + } + }; + let room = end - first; + let total: f32 = items.iter().map(extent).sum(); + let mut shown = items.len(); + if total > room { + let budget = room - (BUTTON + GAP); + let mut used = 0.0; + shown = 0; + for item in &items { + let w = extent(item); + if used + w > budget { + break; + } + used += w; + shown += 1; + } + } + + let dragging = ui.ctx().dragged_id().is_some(); + let mut placed: Vec<(usize, Rect)> = Vec::new(); + let mut drag_from: Option = None; + let mut drop_from: Option = None; + let mut pos = first; + for (index, item) in items.iter().enumerate().take(shown) { + if item == SEPARATOR { + let at = pos + (SEP - GAP) / 2.0; + let half = BUTTON / 2.0 - 3.0; + if vertical { + ui.painter().hline((cross - half)..=(cross + half), at, Stroke::new(1.0, t.border)); + } else { + ui.painter().vline(at, (cross - half)..=(cross + half), Stroke::new(1.0, t.border)); + } + pos += SEP; + continue; + } + let Some(tool) = find(item) else { continue }; + let combo = tool.command == LAYER_COMBO; + let len = if combo && !vertical { COMBO_W } else { BUTTON }; + let br = slot(pos, len, if combo && !vertical { 24.0 } else { BUTTON }); + let resp = ui.interact(br, id.with(("tb", tool.command)), Sense::click() | Sense::DRAG); + if combo { + paint_combo(ui, br, resp.hovered() || resp.dragged(), vertical, layers.as_ref()); + } else { + if resp.hovered() || resp.dragged() { + ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6)); + } + icons::paint(ui.painter(), br.shrink(4.0), tool.icon, !tool.enabled()); + } + icons::describe_control(ui, &resp, &tool.accessible_label(mac), None, false); + let resp = if dragging { + resp + } else if combo { + let current = layers.as_ref().map(|(cur, _)| cur.clone()).unwrap_or_default(); + resp.on_hover_ui(|ui| { + ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); + ui.label(RichText::new(format!("{} {current}", crate::tl!("Current layer:"))).weak()); + }) + } else { + resp.on_hover_ui(|ui| tooltip(ui, &tool, mac)) + }; + resp.context_menu(|ui| options_menu(ui, bar, shown_bars, Some(index), dock, &mut action)); + if combo { + if let Some((cur, rows)) = &layers { + let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; + egui::Popup::from_toggle_button_response(&resp) + .align(align) + .width(COMBO_W.max(240.0)) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + let mut set_current = None; + let mut toggle = None; + crate::palettes::layer_list(ui, rows, cur, &mut set_current, &mut toggle); + if let Some(name) = set_current { + action = Some(Action::SetLayer(name)); + ui.close(); + } else if let Some((name, key, on)) = toggle { + action = Some(Action::LayerToggle(name, key, on)); + } + }); + } + } else if resp.clicked() && tool.enabled() { + action = Some(Action::Run(tool.command)); + } + if resp.dragged() { + drag_from = Some(index); + } + if resp.drag_stopped() { + drop_from = Some(index); + } + placed.push((index, br)); + pos += len + GAP; + } + + // Dragging a button: show where it lands; dropping it on the bar moves it there. + let insertion = |p: Pos2| -> Option<(usize, f32)> { + if !area.expand(24.0).contains(p) { + return None; + } + let along = main(p); + match placed.iter().find(|(_, r)| main(r.center()) > along) { + Some((index, r)) => Some((*index, main(r.min) - GAP / 2.0)), + None => placed.last().map(|(index, r)| (index + 1, main(r.max) + GAP / 2.0)), + } + }; + if let Some(from) = drag_from { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + let pointer = ui.ctx().pointer_latest_pos(); + if let Some((_, at)) = pointer.and_then(insertion) { + let half = BUTTON / 2.0 + 2.0; + let stroke = Stroke::new(2.0, t.accent); + if vertical { + ui.painter().hline((cross - half)..=(cross + half), at, stroke); + } else { + ui.painter().vline(at, (cross - half)..=(cross + half), stroke); + } + } + if let (Some(p), Some(tool)) = (pointer, items.get(from).and_then(|c| find(c))) { + let ghost = Rect::from_center_size(p + vec2(10.0, 10.0), vec2(BUTTON, BUTTON)); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, id.with("ghost"))); + painter.rect_filled(ghost, 3.0, t.control_hover); + painter.rect_stroke(ghost, 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + icons::paint(&painter, ghost.shrink(4.0), tool.icon, false); + } + } + if let Some(from) = drop_from + && let Some((slot_index, _)) = ui.ctx().pointer_latest_pos().and_then(insertion) + && slot_index != from + && slot_index != from + 1 + { + action = Some(Action::Move { from, slot: slot_index }); + } + + // The items that did not fit. + if shown < items.len() { + let br = slot(pos, BUTTON, BUTTON); + let response = ui.interact(br, id.with("toolbar_more"), Sense::click()); + if response.hovered() { + ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6)); + } + for offset in [-5.0, 0.0, 5.0] { + let d = if vertical { vec2(0.0, offset) } else { vec2(offset, 0.0) }; + ui.painter().circle_filled(br.center() + d, 1.5, t.text); + } + icons::describe_control(ui, &response, bar.more_label(), None, false); + let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; + egui::Popup::menu(&response).align(align).show(|ui| { + for item in items.iter().skip(shown) { + if item == SEPARATOR { + ui.separator(); + continue; + } + let Some(tool) = find(item) else { continue }; + if tool.command == LAYER_COMBO { + // The drop-down does not fit a menu row: its layers are listed in place. + if let Some((cur, rows)) = &layers { + let mut set_current = None; + let mut toggle = None; + crate::palettes::layer_list(ui, rows, cur, &mut set_current, &mut toggle); + if let Some(name) = set_current { + action = Some(Action::SetLayer(name)); + ui.close(); + } else if let Some((name, key, on)) = toggle { + action = Some(Action::LayerToggle(name, key, on)); + } + } + continue; + } + let response = ui.add_enabled(tool.enabled(), egui::Button::new(crate::i18n::t(tool.label))); + crate::control::record_widget(ui, &response, tool.label, "button", None); + let response = response.on_hover_ui(|ui| tooltip(ui, &tool, mac)); + if response.clicked() { + action = Some(Action::Run(tool.command)); + ui.close(); + } + } + ui.separator(); + if ui.button(crate::tl!("Customize Tool Bar...")).clicked() { + action = Some(Action::Customize); + ui.close(); + } + }); + response.on_hover_text(crate::i18n::t(bar.more_label())); + } + + if matches!(action, Some(Action::AppMenu)) { + let picked = ui.ctx().data_mut(|d| d.remove_temp::<&'static str>(id.with("app_menu").with("picked"))); + action = picked.map(Action::AppCommand); + } + match action { + Some(Action::Run(command)) => run_tool(app, command), + Some(Action::Move { from, slot }) => { + move_item(&mut items, from, slot); + *fields(&mut app.ui, bar).2 = sanitize(&items); + } + Some(Action::Remove(index)) => { + if index < items.len() { + items.remove(index); + } + *fields(&mut app.ui, bar).2 = sanitize(&items); + } + Some(Action::Dock(target)) => *fields(&mut app.ui, bar).1 = target, + Some(Action::Customize) => app.ui.dialog = Some(format!("toolbar:{}", bar.id())), + Some(Action::Show(other, on)) => *fields(&mut app.ui, other).0 = on, + Some(Action::AppMenu) => {} + Some(Action::AppCommand(command)) => crate::menus::activate(app, command), + Some(Action::SetLayer(name)) => { + let _ = app.run("layer.current", json!({ "name": name })); + } + Some(Action::LayerToggle(name, key, on)) => { + let _ = app.run("layer.set", json!({ "name": name, key: on })); + } + None => {} + } +} + +/// The application menu: the file commands and Options, under the CADCraft button. +pub const APP_MENU: &[(&str, &str)] = &[ + ("new", "New"), + ("open", "Open..."), + ("qsave", "Save"), + ("saveas", "Save As..."), + ("|", ""), + ("import", "Import..."), + ("export", "Export..."), + ("|", ""), + ("plot", "Print..."), + ("publish", "Batch Print..."), + ("|", ""), + ("close", "Close"), + ("options", "Options..."), +]; + +/// The CADCraft application icon, decoded once. +fn app_icon(ctx: &egui::Context) -> Option { + const PNG: &[u8] = include_bytes!("../../../assets/app-icon/cadcraft-64.png"); + let id = egui::Id::new("cc_app_icon"); + if let Some(t) = ctx.data(|d| d.get_temp::>(id)) { + return t; + } + let tex = image::load_from_memory(PNG).ok().map(|img| { + let img = img.to_rgba8(); + let size = [img.width() as usize, img.height() as usize]; + ctx.load_texture("cc_app_icon", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR) + }); + ctx.data_mut(|d| d.insert_temp(id, tex.clone())); + tex +} + +/// The application button with its menu. True when a menu command was chosen this frame (the +/// command is remembered until the bar's action runs). +fn app_button(ui: &mut egui::Ui, rect: Rect, id: egui::Id, vertical: bool) -> bool { + let t = Tokens::get(); + let resp = ui.interact(rect, id, Sense::click()); + let open = egui::Popup::is_id_open(ui.ctx(), egui::Popup::default_response_id(&resp)); + if resp.hovered() || open { + ui.painter().rect_filled(rect, 3.0, t.control_hover.gamma_multiply(0.8)); + } + match app_icon(ui.ctx()) { + Some(tex) => { + ui.painter().image(tex.id(), rect.shrink(2.0), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => icons::paint(ui.painter(), rect.shrink(4.0), Icon::New, false), + } + icons::describe_control(ui, &resp, "CADCraft", None, false); + let resp = resp.on_hover_text(crate::tl!("Application menu")); + let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; + let mut picked = None; + egui::Popup::menu(&resp).align(align).show(|ui| { + ui.set_min_width(200.0); + for (command, label) in APP_MENU { + if *command == SEPARATOR { + ui.separator(); + continue; + } + let mut button = egui::Button::new(crate::i18n::t(label)); + if let Some(sc) = cadcraft_engine::find_command(command).and_then(|c| c.shortcut) { + button = button.shortcut_text(crate::menus::shortcut_label(sc, ui.ctx().os().is_mac())); + } + let r = ui.add(button); + crate::control::record_widget(ui, &r, label, "button", None); + if r.clicked() { + picked = Some(*command); + ui.close(); + } + } + }); + if let Some(c) = picked { + ui.ctx().data_mut(|d| d.insert_temp(id.with("picked"), c)); + return true; + } + false +} + +/// Run a bar's tool: layer tools act at once (as in the Layers palette), the others start like a +/// typed command. +fn run_tool(app: &mut CadApp, command: &'static str) { + let layer_tool = find(command).is_some_and(|t| t.category == LAYERS_CATEGORY) && !command.starts_with("ui."); + if layer_tool { + let _ = app.run(command, json!({})); + } else { + app.start(command); + } +} + +/// The current-layer drop-down: its state icons, colour and name in a row, a layers icon in a column. +fn paint_combo(ui: &egui::Ui, rect: Rect, hovered: bool, vertical: bool, layers: Option<&(String, Vec)>) { + let t = Tokens::get(); + let p = ui.painter(); + if vertical { + if hovered { + p.rect_filled(rect, 3.0, t.control_hover.gamma_multiply(0.6)); + } + icons::paint(p, rect.shrink(4.0), Icon::Layers, false); + return; + } + p.rect_filled(rect, 3.0, if hovered { t.control_hover } else { t.control }); + let current = layers.and_then(|(cur, rows)| rows.iter().find(|r| r.0.eq_ignore_ascii_case(cur))); + if let Some((name, on, frozen, locked, color)) = current { + let mut x = rect.left() + 6.0; + for icon in [ + if *on { Icon::Bulb } else { Icon::BulbOff }, + if *locked { Icon::Lock } else { Icon::Unlock }, + if *frozen { Icon::Snowflake } else { Icon::Sun }, + ] { + icons::paint(p, Rect::from_min_size(pos2(x, rect.center().y - 8.0), vec2(16.0, 16.0)), icon, false); + x += 18.0; + } + crate::palettes::swatch(p, Rect::from_min_size(pos2(x + 2.0, rect.center().y - 5.0), vec2(10.0, 10.0)), *color); + let text_rect = Rect::from_min_max(pos2(x + 18.0, rect.top()), pos2(rect.right() - 22.0, rect.bottom())); + p.with_clip_rect(text_rect).text(pos2(text_rect.left(), rect.center().y), egui::Align2::LEFT_CENTER, name, crate::theme::body(), t.text); + } + icons::paint(p, Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::ChevronDown, false); +} + +/// Selection and search of the Customize Tool Bar dialog. +#[derive(Clone, Default)] +struct DialogState { + filter: String, + available: Option<&'static str>, + current: Option, +} + +/// A list row: the tool's icon and its name. +fn row(ui: &mut egui::Ui, icon: Icon, name: &str, selected: bool, dim: bool) -> egui::Response { + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + icons::paint(ui.painter(), r, icon, dim); + ui.selectable_label(selected, name) + }) + .inner +} + +/// Window ▸ Customize Tool Bar...: where a bar is docked and which buttons it holds, in order. +/// `which` is the dialog id, `toolbar:` (`toolbar` alone: the standard bar). +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, which: &str, open: &mut bool) { + let bar = which.strip_prefix("toolbar:").and_then(Bar::parse).unwrap_or(Bar::Standard); + let id = egui::Id::new("Customize Tool Bar"); + let state_id = id.with(("state", bar.id())); + let mut st: DialogState = ctx.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let bar_state = state(&app.ui, bar); + let mut items = sanitize(&bar_state.items); + let mut dock = bar_state.dock; + let mut show = bar_state.show; + let mut changed = false; + let mut switch_to = None; + egui::Window::new(crate::tl!("Customize Tool Bar")).id(id).open(open).resizable(false).collapsible(false).show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Tool Bar:")); + for other in Bar::ALL { + if ui.selectable_label(other == bar, crate::i18n::t(other.title())).clicked() && other != bar { + switch_to = Some(other); + } + } + }); + ui.separator(); + ui.horizontal(|ui| { + ui.checkbox(&mut show, crate::tl!("Show Tool Bar")); + ui.add_space(16.0); + ui.label(crate::tl!("Position:")); + ui.radio_value(&mut dock, Dock::Top, crate::tl!("Top (row)")); + ui.radio_value(&mut dock, Dock::Left, crate::tl!("Left (column)")); + }); + ui.separator(); + let mut add: Option<&'static str> = None; + let mut add_separator = false; + let mut shift: Option = None; + let mut remove = false; + let mut reset = false; + ui.horizontal_top(|ui| { + // Every command the bar can hold, by category. + ui.vertical(|ui| { + ui.set_width(250.0); + ui.label(RichText::new(crate::tl!("Commands")).strong()); + ui.horizontal(|ui| { + ui.label(crate::tl!("Search:")); + ui.add(egui::TextEdit::singleline(&mut st.filter).desired_width(170.0)); + }); + let mac = ui.ctx().os().is_mac(); + egui::ScrollArea::vertical().id_salt("tb_available").max_height(340.0).auto_shrink([false, false]).show(ui, |ui| { + let needle = st.filter.trim().to_lowercase(); + let mut category = ""; + for tool in catalog() { + let name = crate::i18n::t(tool.label); + if !needle.is_empty() && !name.to_lowercase().contains(&needle) && !tool.command.contains(needle.as_str()) { + continue; + } + if tool.category != category { + category = tool.category; + ui.add_space(4.0); + ui.label(RichText::new(crate::i18n::t(category)).weak()); + } + let on_bar = items.iter().any(|i| i == tool.command); + let resp = row(ui, tool.icon, name, st.available == Some(tool.command), on_bar); + let resp = resp.on_hover_ui(|ui| tooltip(ui, tool, mac)); + if resp.clicked() { + st.available = Some(tool.command); + } + if resp.double_clicked() && !on_bar { + add = Some(tool.command); + } + } + }); + }); + // Add a command or a separator to the bar. + ui.vertical(|ui| { + ui.add_space(80.0); + let can_add = st.available.is_some_and(|c| !items.iter().any(|i| i == c)); + if ui.add_enabled(can_add, egui::Button::new(format!("{} →", crate::tl!("Add")))).clicked() { + add = st.available; + } + ui.add_space(6.0); + if ui.button(crate::tl!("Add Separator")).clicked() { + add_separator = true; + } + }); + // The bar's buttons in order. + ui.vertical(|ui| { + ui.set_width(250.0); + ui.label(RichText::new(crate::tl!("Tool Bar buttons")).strong()); + egui::ScrollArea::vertical().id_salt("tb_current").max_height(340.0).auto_shrink([false, false]).show(ui, |ui| { + for (index, item) in items.iter().enumerate() { + let selected = st.current == Some(index); + let resp = if item == SEPARATOR { + ui.selectable_label(selected, RichText::new(format!("──── {} ────", crate::tl!("Separator"))).weak()) + } else if let Some(tool) = find(item) { + row(ui, tool.icon, crate::i18n::t(tool.label), selected, false) + } else { + continue; + }; + if resp.clicked() { + st.current = Some(index); + } + } + }); + let picked = st.current.filter(|i| *i < items.len()); + ui.horizontal(|ui| { + if ui.add_enabled(picked.is_some_and(|i| i > 0), egui::Button::new(crate::tl!("Move Up"))).clicked() { + shift = Some(true); + } + if ui.add_enabled(picked.is_some_and(|i| i + 1 < items.len()), egui::Button::new(crate::tl!("Move Down"))).clicked() { + shift = Some(false); + } + if ui.add_enabled(picked.is_some(), egui::Button::new(crate::tl!("Remove"))).clicked() { + remove = true; + } + }); + if ui.button(crate::tl!("Reset to Default")).clicked() { + reset = true; + } + }); + }); + ui.separator(); + ui.label(RichText::new(crate::tl!("Drag buttons along the Tool Bar to reorder them, or its handle to dock it.")).weak()); + + let picked = st.current.filter(|i| *i < items.len()); + if let Some(command) = add { + let at = picked.map(|i| i + 1); + if add_item(&mut items, command, at) { + st.current = Some(at.unwrap_or(items.len().saturating_sub(1))); + changed = true; + } + } + if add_separator && items.len() < MAX_ITEMS { + let at = picked.map(|i| i + 1).unwrap_or(items.len()).min(items.len()); + items.insert(at, SEPARATOR.to_string()); + st.current = Some(at); + changed = true; + } + if let (Some(up), Some(i)) = (shift, picked) { + if up && i > 0 { + items.swap(i, i - 1); + st.current = Some(i - 1); + changed = true; + } else if !up && i + 1 < items.len() { + items.swap(i, i + 1); + st.current = Some(i + 1); + changed = true; + } + } + if remove && let Some(i) = picked { + items.remove(i); + st.current = if items.is_empty() { None } else { Some(i.min(items.len() - 1)) }; + changed = true; + } + if reset { + items = bar.default_items(); + st.current = None; + changed = true; + } + }); + ctx.data_mut(|d| d.insert_temp(state_id, st)); + let (shown, docked, saved) = fields(&mut app.ui, bar); + if changed { + // Separators may sit side by side while editing in the list; the bar shows them once. + *saved = items.into_iter().take(MAX_ITEMS).collect(); + } + *docked = dock; + *shown = show; + if let Some(other) = switch_to { + app.ui.dialog = Some(format!("toolbar:{}", other.id())); + } +} + +/// `ui.toolbar.*` commands (menus, command line, control channel). `None` if `id` isn't one. +/// Every command takes `"bar"`: `"standard"` (the default), `"toolSets"` or `"layers"`. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + let bar = match params.get("bar").and_then(Value::as_str) { + None => Bar::Standard, + Some(name) => match Bar::parse(name) { + Some(bar) => bar, + None if id.starts_with("ui.toolbar.") => { + return Some(Err(format!("unknown tool bar \"{}\" (standard, toolSets or layers)", name.chars().take(40).collect::()))); + } + None => Bar::Standard, + }, + }; + let report = |app: &CadApp, bar: Bar| { + let st = state(&app.ui, bar); + json!({ "bar": bar.id(), "show": st.show, "position": st.dock.as_str(), "items": sanitize(&st.items) }) + }; + Some(match id { + "ui.toolbar.top" | "ui.toolbar.left" => { + let (shown, dock, _) = fields(&mut app.ui, bar); + *dock = if id == "ui.toolbar.top" { Dock::Top } else { Dock::Left }; + *shown = true; + Ok(report(&*app, bar)) + } + "ui.toggle.toolbar.toolsets" | "ui.toggle.toolbar.layers" => { + let bar = if id.ends_with("toolsets") { Bar::ToolSets } else { Bar::Layers }; + let shown = fields(&mut app.ui, bar).0; + *shown = params.get("on").and_then(Value::as_bool).unwrap_or(!*shown); + Ok(report(&*app, bar)) + } + // `{"position": "top"|"left"}` docks the bar; without it, reports the bar. + "ui.toolbar.dock" => match params.get("position").and_then(Value::as_str) { + Some(name) => match Dock::parse(name) { + Some(dock) => { + *fields(&mut app.ui, bar).1 = dock; + Ok(report(&*app, bar)) + } + None => Err(format!("unknown Tool Bar position \"{}\" (top or left)", name.chars().take(40).collect::())), + }, + None => Ok(report(&*app, bar)), + }, + // `{"command": "line", "index": 3}` adds a Tool Sets, layer or standard command. + "ui.toolbar.add" => { + let Some(command) = params.get("command").and_then(Value::as_str) else { return Some(Err("ui.toolbar.add needs \"command\"".into())) }; + let index = params.get("index").and_then(Value::as_u64).map(|i| usize::try_from(i).unwrap_or(usize::MAX)); + let mut items = sanitize(&state(&app.ui, bar).items); + if command == SEPARATOR { + let at = index.unwrap_or(items.len()).min(items.len()); + items.insert(at, SEPARATOR.to_string()); + } else if !add_item(&mut items, command, index) { + return Some(Err(format!("\"{}\" cannot be added to the Tool Bar", command.chars().take(40).collect::()))); + } + *fields(&mut app.ui, bar).2 = sanitize(&items); + Ok(report(&*app, bar)) + } + // `{"command": "line"}` or `{"index": 3}` removes a button. + "ui.toolbar.remove" => { + let mut items = sanitize(&state(&app.ui, bar).items); + let at = match (params.get("command").and_then(Value::as_str), params.get("index").and_then(Value::as_u64)) { + (Some(command), _) => items.iter().position(|i| i == command), + (None, Some(i)) => usize::try_from(i).ok().filter(|i| *i < items.len()), + (None, None) => None, + }; + let Some(at) = at else { return Some(Err("No such Tool Bar button".into())) }; + items.remove(at); + *fields(&mut app.ui, bar).2 = sanitize(&items); + Ok(report(&*app, bar)) + } + // `{"from": 0, "to": 5}`: move a button before the one now at `to`. + "ui.toolbar.move" => { + let mut items = sanitize(&state(&app.ui, bar).items); + let get = |key: &str| params.get(key).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let (Some(from), Some(to)) = (get("from"), get("to")) else { return Some(Err("ui.toolbar.move needs \"from\" and \"to\"".into())) }; + if from >= items.len() || to > items.len() { + return Some(Err("Tool Bar position out of range".into())); + } + move_item(&mut items, from, to); + *fields(&mut app.ui, bar).2 = sanitize(&items); + Ok(report(&*app, bar)) + } + "ui.toolbar.reset" => { + *fields(&mut app.ui, bar).2 = bar.default_items(); + Ok(report(&*app, bar)) + } + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn strings(items: &[&str]) -> Vec { + items.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn default_bar_is_the_standard_groups() { + let items = default_items(); + assert_eq!(items.first().map(String::as_str), Some("new")); + assert_eq!(items.last().map(String::as_str), Some("ui.dialog.about")); + assert_eq!(items.iter().filter(|i| *i == SEPARATOR).count(), STANDARD.len() - 1); + assert_eq!(sanitize(&items), items, "the default bar is already clean"); + } + + #[test] + fn sanitize_drops_unknown_repeated_and_stray_separators() { + let items = strings(&["|", "line", "nonsense", "line", "|", "|", "circle", "|"]); + assert_eq!(sanitize(&items), strings(&["line", "|", "circle"])); + let many: Vec = std::iter::repeat_n("line".to_string(), 10_000).collect(); + assert_eq!(sanitize(&many), strings(&["line"])); + } + + #[test] + fn move_item_lands_before_the_slot() { + let mut items = strings(&["a", "b", "c", "d"]); + move_item(&mut items, 0, 3); + assert_eq!(items, strings(&["b", "c", "a", "d"])); + move_item(&mut items, 3, 0); + assert_eq!(items, strings(&["d", "b", "c", "a"])); + move_item(&mut items, 1, 4); + assert_eq!(items, strings(&["d", "c", "a", "b"])); + move_item(&mut items, 9, 0); + move_item(&mut items, 0, 9); + assert_eq!(items, strings(&["d", "c", "a", "b"]), "out of range does nothing"); + } + + #[test] + fn add_item_takes_catalog_commands_once() { + let mut items = strings(&["new"]); + assert!(add_item(&mut items, "line", Some(0))); + assert!(!add_item(&mut items, "line", None), "already on the bar"); + assert!(!add_item(&mut items, "rm -rf", None), "not a tool"); + assert_eq!(items, strings(&["line", "new"])); + } + + #[test] + fn every_drafting_tool_is_in_the_catalog() { + for groups in [crate::palettes::DRAFTING, crate::palettes::MODELING] { + for (_, large, small) in groups.iter() { + for (_, command, _) in large.iter().chain(small.iter()) { + assert!(find(command).is_some(), "{command}"); + } + } + } + } + + #[test] + fn every_bar_default_is_clean() { + for bar in Bar::ALL { + let items = bar.default_items(); + assert_eq!(sanitize(&items), items, "{bar:?}"); + assert_eq!(Bar::parse(bar.id()), Some(bar)); + } + assert!(Bar::Layers.default_items().iter().any(|i| i == LAYER_COMBO)); + assert!(!Bar::ToolSets.default_items().iter().any(|i| i == "revcloud"), "keeps palette-only names unique for tests"); + } + + #[test] + fn dock_names() { + assert_eq!(Dock::parse("Left"), Some(Dock::Left)); + assert_eq!(Dock::parse("column"), Some(Dock::Left)); + assert_eq!(Dock::parse("top"), Some(Dock::Top)); + assert_eq!(Dock::parse("bottom"), None); + assert_eq!(serde_json::to_value(Dock::Left).ok(), Some(json!("left"))); + } + + #[test] + fn dropping_the_handle_docks_at_the_nearer_edge() { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)); + assert_eq!(drop_target(screen, pos2(20.0, 400.0)), Some(Dock::Left)); + assert_eq!(drop_target(screen, pos2(600.0, 20.0)), Some(Dock::Top)); + assert_eq!(drop_target(screen, pos2(600.0, 400.0)), None); + } +} diff --git a/crates/ui-egui/tests/clipboard_between_drawings.rs b/crates/ui-egui/tests/clipboard_between_drawings.rs new file mode 100644 index 0000000000..1975eb96b3 --- /dev/null +++ b/crates/ui-egui/tests/clipboard_between_drawings.rs @@ -0,0 +1,83 @@ +//! Ctrl+C in one open drawing, Ctrl+V in another: the objects are pasted there. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +/// The text the app put on the system clipboard in the last frames, if any. +fn copied(h: &Harness<'_, CadApp>) -> Option { + h.output().platform_output.commands.iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) +} + +#[test] +fn copy_in_one_drawing_and_paste_in_another() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.run("line", json!({ "points": [[0, 0], [10, 0]] })).unwrap(); + app.run("circle", json!({ "center": [5, 5], "radius": 2 })).unwrap(); + app.run("block", json!({ "name": "DOT", "base": [5, 5], "handles": [app.session.doc().unwrap().model.iter().nth(1).unwrap().handle.hex()], "keep": "convert" })) + .unwrap(); + let first = app.session.active; + let all: Vec<_> = app.session.doc().unwrap().model.iter().map(|e| e.handle).collect(); + app.session.set_selection(all); + let mut h = harness(app); + h.event(Event::Copy); + let mut text = None; + for _ in 0..4 { + h.run_steps(1); + text = text.or_else(|| copied(&h)); + } + assert_eq!( + h.state().session.clipboard.len(), + 2, + "{:?}", + h.state().session.doc().unwrap().model.iter().map(|e| e.kind.type_name()).collect::>() + ); + // Another drawing, made active by clicking its tab (which must not keep the keyboard). + h.state_mut().run("new", json!({})).unwrap(); + h.run_steps(3); + let second = h.state().session.active; + let title = h.state().session.docs[second].title.clone(); + h.state_mut().run("document.switch", json!({ "index": first })).unwrap(); + h.run_steps(3); + h.get_by_label(&title).click(); + h.run_steps(3); + assert_eq!(h.state().session.active, second); + assert_ne!(second, first); + assert!(h.state().session.doc().unwrap().model.is_empty()); + assert!(!h.ctx.egui_wants_keyboard_input(), "the clicked tab doesn't hold the keyboard"); + // Ctrl+V: egui reports it as a Paste event with the system clipboard's text. + h.event(Event::Paste(text.unwrap_or_else(|| "something else".into()))); + h.run_steps(3); + assert_eq!( + h.state().session.running.as_ref().map(|r| r.id.as_str()), + Some("pasteclip"), + "{:?}", + h.state().session.log.iter().rev().take(5).collect::>() + ); + h.state_mut().session.input(Input::Point(Vec2::new(100.0, 100.0))).unwrap(); + h.run_steps(2); + let d = h.state().session.doc().unwrap(); + assert_eq!(d.model.len(), 2); + assert!(d.model.iter().any(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block == "DOT"))); + assert!(d.block("DOT").is_some()); +} diff --git a/crates/ui-egui/tests/dialog_dispatch.rs b/crates/ui-egui/tests/dialog_dispatch.rs index 05f725b4a0..51d48b987c 100644 --- a/crates/ui-egui/tests/dialog_dispatch.rs +++ b/crates/ui-egui/tests/dialog_dispatch.rs @@ -20,6 +20,7 @@ fn app() -> (CadApp, Rc>) { b.set(b.get() + 1); None })), + pick_folder: None, }; (CadApp::new(Session::new(), services), picks) } diff --git a/crates/ui-egui/tests/dimstyles.rs b/crates/ui-egui/tests/dimstyles.rs new file mode 100644 index 0000000000..04f9ca9f1d --- /dev/null +++ b/crates/ui-egui/tests/dimstyles.rs @@ -0,0 +1,117 @@ +//! The Dimension Style Manager and editor, the dimension rows of the Properties palette and the +//! dimension text grip's menu. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn harness(setup: impl FnOnce(&mut CadApp)) -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("new", json!({})).unwrap(); + app.ui.start_tab = false; + app.ui.in_window_menu = false; + setup(&mut app); + let mut h = Harness::builder().with_size(vec2(1280.0, 900.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +fn click(h: &mut Harness<'_, CadApp>, label: &str) { + h.query_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click(); + h.run_steps(4); +} + +#[test] +fn format_dimension_style_opens_the_manager_and_new_makes_a_style() { + let mut h = harness(|app| app.start("dimstyle")); + assert_eq!(h.state().ui.dialog.as_deref(), Some("dimstyle")); + assert!(h.query_by_label_contains("Current dimension style:").is_some()); + click(&mut h, "New..."); + click(&mut h, "Continue"); + assert!(h.query_by_label_contains("New Dimension Style:").is_some(), "the editor opens"); + for tab in ["Lines", "Symbols and Arrows", "Text", "Fit", "Primary Units", "Alternate Units", "Tolerances"] { + click(&mut h, tab); + } + click(&mut h, "OK"); + let doc = h.state().session.doc().unwrap(); + assert!(doc.dim_style("Copy of Standard").is_some(), "{:?}", doc.dim_styles.iter().map(|s| &s.name).collect::>()); + assert_eq!(doc.header.str("DIMSTYLE", "Standard"), "Standard", "a new style is not made current"); +} + +#[test] +fn modify_and_set_current_and_compare() { + let mut h = harness(|app| { + app.run("dimstyle", json!({ "name": "ISO-25", "textHeight": 2.5, "current": false })).unwrap(); + app.ui.dialog = Some("dimstyle".into()); + }); + click(&mut h, "ISO-25"); + click(&mut h, "Set Current"); + assert_eq!(h.state().session.doc().unwrap().header.str("DIMSTYLE", ""), "ISO-25"); + click(&mut h, "Modify..."); + click(&mut h, "OK"); + assert_eq!(h.state().session.doc().unwrap().dim_style("ISO-25").unwrap().text_height, 2.5, "OK without changes keeps the style"); + click(&mut h, "Compare..."); + assert!(h.query_by_label_contains("The two styles are the same.").is_some()); +} + +#[test] +fn a_selected_dimension_shows_its_style_settings_in_properties() { + let mut hx = String::new(); + let mut h = harness(|app| { + hx = app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string(); + let handle = cadcraft_engine::doc::Handle::parse_hex(&hx).unwrap(); + app.session.set_selection(vec![handle]); + // Room for the Properties palette's rows. + app.run("ui.dock", json!({ "operation": "close", "panel": "layers" })).unwrap(); + }); + h.run_steps(3); + // The rows' values: arrowheads, text placement, fit, units (row labels are painted). + for value in ["Closed filled", "Centered", "Either text or arrows (best fit)", "Decimal"] { + assert!(h.query_all_by_label_contains(value).next().is_some() || h.query_all_by_value(value).next().is_some(), "{value}"); + } + // The same overrides the palette sets. + h.state_mut().run("dimstyle.override", json!({ "handles": [hx], "arrowSize": 0.5 })).unwrap(); + let doc = h.state().session.doc().unwrap(); + let Some(EntityKind::Dimension(d)) = doc.model.iter().find(|e| e.handle.hex() == hx).map(|e| e.kind.clone()) else { panic!() }; + assert_eq!(d.overrides.get("arrowSize"), Some(&json!(0.5))); +} + +#[test] +fn resting_on_the_text_grip_opens_its_menu() { + let mut hx = String::new(); + let mut h = harness(|app| { + hx = app.run("dimlinear", json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 3] })).unwrap()["handle"].as_str().unwrap().to_string(); + app.run("view.set", json!({ "center": [5, 3], "height": 20 })).unwrap(); + let handle = cadcraft_engine::doc::Handle::parse_hex(&hx).unwrap(); + app.session.set_selection(vec![handle]); + }); + h.run_steps(3); + let handle = cadcraft_engine::doc::Handle::parse_hex(&hx).unwrap(); + let grip = h.state().session.grips_of(handle).unwrap()[3]; + let at: Pos2 = h.state().canvas.xf.unwrap().to_screen(grip); + h.event(Event::PointerMoved(at)); + for _ in 0..40 { + h.step(); + std::thread::sleep(std::time::Duration::from_millis(15)); + } + h.run_steps(2); + assert!(h.query_by_label("Move Text Only").is_some(), "the menu opened on hover"); + let item = h.get_by_label("Move Text Only").rect().center(); + h.event(Event::PointerMoved(item)); + h.run_steps(1); + h.event(Event::PointerButton { pos: item, button: PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.event(Event::PointerButton { pos: item, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + assert!(h.state().session.running.is_some(), "the grip is hot, asking for the text location"); + assert!(h.state().session.prompt_text().contains("MOVE TEXT ONLY"), "{}", h.state().session.prompt_text()); +} diff --git a/crates/ui-egui/tests/docking_workflows.rs b/crates/ui-egui/tests/docking_workflows.rs index bf356f829a..54615b0c99 100644 --- a/crates/ui-egui/tests/docking_workflows.rs +++ b/crates/ui-egui/tests/docking_workflows.rs @@ -17,6 +17,8 @@ fn harness(state: Option, width: f32, scale: f32) -> Harness<'static, C app.ui = state; } app.ui.in_window_menu = false; + // These tests drive the Tool Sets palette; its tools also sit on the Tool Sets bar. + app.ui.toolsets_bar.show = false; app.integrated_titlebar = true; let mut harness = Harness::builder().with_size(vec2(width, 760.0)).with_pixels_per_point(scale).build_ui_state( |ui, app: &mut CadApp| { diff --git a/crates/ui-egui/tests/rtl_names.rs b/crates/ui-egui/tests/rtl_names.rs new file mode 100644 index 0000000000..a1f10305c6 --- /dev/null +++ b/crates/ui-egui/tests/rtl_names.rs @@ -0,0 +1,17 @@ +//! A Hebrew file name reads as it does in the file manager: the letters right to left, the +//! extension on the right (`שלום.dwg`), whatever the text shaper does with right-to-left runs. + +#[test] +fn hebrew_file_name_is_laid_out_in_reading_order() { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |_| {}); + out.textures_delta.clear(); + let job = cadcraft_ui_egui::i18n::job("שלום.dwg", egui::FontId::proportional(14.0), egui::Color32::WHITE); + let galley = ctx.fonts_mut(|f| f.layout_job(job)); + let mut glyphs: Vec<(f32, char)> = galley.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| (g.pos.x, g.chr))).collect(); + glyphs.sort_by(|a, b| a.0.total_cmp(&b.0)); + let shown: String = glyphs.iter().map(|(_, c)| c).collect(); + // Left to right on screen: the last letter first, the extension last and not reversed. + assert_eq!(shown, "םולש.dwg"); + ctx.tex_manager().write().take_delta().clear(); +} diff --git a/crates/ui-egui/tests/shared_controls.rs b/crates/ui-egui/tests/shared_controls.rs index 2c6bc2ab84..1d46cbeadd 100644 --- a/crates/ui-egui/tests/shared_controls.rs +++ b/crates/ui-egui/tests/shared_controls.rs @@ -8,6 +8,8 @@ use egui_kittest::kittest::Queryable; fn app() -> CadApp { let mut app = CadApp::new(Session::default(), Services::default()); + // These tests drive the Tool Sets palette; its tools also sit on the Tool Sets bar. + app.ui.toolsets_bar.show = false; app.run("ui.sample", serde_json::json!({})).unwrap(); app } diff --git a/crates/ui-egui/tests/text_double_click.rs b/crates/ui-egui/tests/text_double_click.rs index 782234d108..b152c9c32e 100644 --- a/crates/ui-egui/tests/text_double_click.rs +++ b/crates/ui-egui/tests/text_double_click.rs @@ -56,15 +56,16 @@ fn double_click_on_text_starts_textedit_for_that_object() { let mut h = harness(); double_click(&mut h, at); let s = &h.state().session; - assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit"), "object {i}"); + assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("textedit.object"), "object {i}"); + assert!(s.text_editor().is_some(), "object {i}: the in-place editor opens"); let p = s.current_prompt().unwrap(); assert_eq!(p.message, "Enter new text", "object {i}: the clicked text is already picked"); assert_eq!(p.default.as_deref(), Some(old), "object {i}"); h.state_mut().session.input(Input::Text(new.into())).unwrap(); h.run_steps(2); assert_eq!(text_at(&h, i), new); - // TEXTEDIT goes on asking for objects (its Multiple mode), as AutoCAD's does. - assert_eq!(h.state().session.current_prompt().unwrap().message, "Select an annotation object"); + // A double-click edits that one object: the command ends with it. + assert!(h.state().session.running.is_none(), "object {i}"); } } @@ -76,3 +77,17 @@ fn double_click_elsewhere_starts_no_command() { assert_eq!(h.state().session.running.as_ref().map(|r| r.id.as_str()), None, "{at:?}"); } } + +#[test] +fn double_click_on_a_block_reference_opens_the_block_editor() { + let mut h = harness(); + { + let app = h.state_mut(); + let c = app.run("circle", json!({ "center": [30, 20], "radius": 2 })).unwrap()["handle"].as_str().unwrap().to_string(); + app.run("block", json!({ "name": "Wheel", "base": [30, 20], "handles": [c] })).unwrap(); + app.run("insert", json!({ "name": "Wheel", "at": [30, 20] })).unwrap(); + } + h.run_steps(3); + double_click(&mut h, Vec2::new(32.0, 20.0)); + assert!(h.state().session.state().unwrap().block_edit.is_some(), "the Block Editor is open"); +} diff --git a/crates/ui-egui/tests/text_editing.rs b/crates/ui-egui/tests/text_editing.rs new file mode 100644 index 0000000000..ad132c88ee --- /dev/null +++ b/crates/ui-egui/tests/text_editing.rs @@ -0,0 +1,156 @@ +//! The in-place text editor on existing objects: one line of text finishes with Enter, a table +//! cell moves on with Tab, a dimension keeps `<>` for its measured value, and Options ▸ Fonts +//! lists font folders. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::{EditorKind, Input, Session}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::{Event, Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +fn harness(setup: impl FnOnce(&mut CadApp)) -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("new", json!({})).unwrap(); + app.ui.start_tab = false; + app.ui.in_window_menu = false; + setup(&mut app); + let mut h = Harness::builder().with_size(vec2(1280.0, 860.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +fn handle(v: &Value) -> String { + v["handle"].as_str().unwrap().to_string() +} + +fn entity(h: &Harness<'_, CadApp>, hex: &str) -> EntityKind { + let doc = h.state().session.doc().unwrap(); + doc.model.iter().find(|e| e.handle.hex() == hex).unwrap().kind.clone() +} + +fn key(h: &mut Harness<'_, CadApp>, key: Key, modifiers: Modifiers) { + h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + h.event(Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }); + h.run_steps(3); +} + +fn type_text(h: &mut Harness<'_, CadApp>, text: &str) { + h.event(Event::Text(text.into())); + h.run_steps(3); +} + +#[test] +fn one_line_of_text_is_edited_in_place_and_enter_finishes() { + let mut t = String::new(); + let mut h = harness(|app| { + t = handle(&app.run("text", json!({ "at": [0, 0], "text": "Plan", "height": 2.0 })).unwrap()); + app.start("textedit.object"); + app.session.input(Input::Point(cadcraft_geom::Vec2::new(0.5, 0.5))).unwrap(); + }); + assert_eq!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::Line)); + type_text(&mut h, " B"); + key(&mut h, Key::Enter, Modifiers::NONE); + assert!(h.state().session.running.is_none(), "{}", h.state().session.prompt_text()); + assert!(matches!(entity(&h, &t), EntityKind::Text(x) if x.value == "Plan B")); +} + +#[test] +fn tab_keeps_a_cell_and_moves_to_the_next() { + let mut t = String::new(); + let mut h = harness(|app| { + t = handle(&app.run("table", json!({ "at": [0, 10], "rows": 2, "cols": 2, "colWidth": 6, "rowHeight": 2 })).unwrap()); + app.start("tabledit.cell"); + app.session.input(Input::Point(cadcraft_geom::Vec2::new(3.0, 9.0))).unwrap(); + }); + type_text(&mut h, "A"); + key(&mut h, Key::Tab, Modifiers::NONE); + assert!(matches!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::TableCell { name }) if name == "B1")); + type_text(&mut h, "B"); + key(&mut h, Key::Enter, Modifiers::COMMAND); + assert!(h.state().session.running.is_none(), "{}", h.state().session.prompt_text()); + let EntityKind::Table(tb) = entity(&h, &t) else { panic!() }; + assert_eq!((tb.cells[0][0].text.as_str(), tb.cells[0][1].text.as_str()), ("A", "B")); +} + +#[test] +fn a_dimension_shows_its_measured_value_and_keeps_the_placeholder() { + let mut d = String::new(); + let mut h = harness(|app| { + d = handle(&app.run("dimlinear", json!({ "p1": [0, 0], "p2": [25, 0], "at": [12, 4] })).unwrap()); + let doc = app.session.doc().unwrap(); + let Some(EntityKind::Dimension(dm)) = doc.model.iter().find(|e| e.handle.hex() == d).map(|e| e.kind.clone()) else { panic!() }; + let at = cadcraft_render::dimension_in(doc, &dm).text_pos; + app.start("textedit.object"); + app.session.input(Input::Point(at)).unwrap(); + }); + assert!(h.query_by_label_contains("<> = 25").is_some(), "the measured value is shown"); + key(&mut h, Key::Home, Modifiers::NONE); + type_text(&mut h, "L="); + key(&mut h, Key::Enter, Modifiers::COMMAND); + assert!(matches!(entity(&h, &d), EntityKind::Dimension(x) if x.text == "L=<>"), "{:?}", entity(&h, &d)); +} + +#[test] +fn options_lists_font_folders_and_the_drawings_missing_fonts() { + let mut h = harness(|app| { + app.run("style", json!({ "name": "Gost", "font": "gost_cadcraft_test.shx" })).unwrap(); + app.ui.dialog = Some("options:fonts".into()); + }); + h.run_steps(3); + assert!(h.query_by_label("Font folders").is_some()); + assert!(h.query_by_label_contains("gost_cadcraft_test.shx").is_some(), "the missing font is listed"); + let dir = std::env::temp_dir().join(format!("cadcraft-ui-fonts-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.to_string_lossy().to_string(); + let r = h.state_mut().run("options", json!({ "fontFolders": [path.clone(), path.clone(), ""] })).unwrap(); + assert_eq!(r["fontFolders"], json!([path])); + assert!(h.state_mut().run("options", json!({ "fontFolders": "nope" })).is_err()); + let saved = h.state().profile_json(); + h.state_mut().run("options", json!({ "fontFolders": [] })).unwrap(); + h.state_mut().load_profile(&saved); + assert_eq!(cadcraft_fonts::ttf::font_dirs(), vec![path]); + h.state_mut().run("options", json!({ "fontFolders": [] })).unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_options_dialog_keeps_its_place_and_size_on_every_tab() { + let mut h = harness(|app| app.ui.dialog = Some("options".into())); + let mut rects = Vec::new(); + for tab in ["display", "files", "fonts", "drafting", "selection", "preferences", "profiles"] { + h.state_mut().ui.dialog = Some(format!("options:{tab}")); + h.run_steps(4); + rects.push((tab, h.get_by_label("Close").rect())); + } + let first = rects[0].1; + for (tab, r) in &rects { + assert!((r.min - first.min).length() < 0.5, "{tab}: {r:?} vs {first:?}"); + } +} + +#[test] +fn the_application_button_opens_the_file_menu_and_cannot_be_removed() { + let mut h = harness(|_| {}); + h.get_by_label("CADCraft").click(); + h.run_steps(3); + for label in ["New", "Open...", "Save", "Save As...", "Import...", "Export...", "Print...", "Batch Print...", "Close", "Options..."] { + assert!(h.query_all_by_label_contains(label).next().is_some(), "{label}"); + } + h.query_all_by_label_contains("Options...").next().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_deref(), Some("options")); + // Not one of the bar's items: the customizable list never holds it. + assert!(!cadcraft_ui_egui::toolbar::default_items().iter().any(|i| i.contains("app"))); + h.state_mut().run("ui.toolbar.reset", json!({})).unwrap(); + h.state_mut().ui.toolbar_items.clear(); + h.run_steps(3); + assert!(h.query_by_label("CADCraft").is_some(), "an empty bar still has the application button"); +} diff --git a/crates/ui-egui/tests/toolbar_dock.rs b/crates/ui-egui/tests/toolbar_dock.rs new file mode 100644 index 0000000000..6d433203f3 --- /dev/null +++ b/crates/ui-egui/tests/toolbar_dock.rs @@ -0,0 +1,117 @@ +//! The Tool Bar is a row when docked at the top and a column when docked on the left, and its +//! buttons are the user's to add, remove and reorder. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::toolbar::{self, Dock}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn harness(dock: Dock) -> Harness<'static, CadApp> { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("new", json!({})).unwrap(); + app.ui.start_tab = false; + app.ui.in_window_menu = false; + app.ui.toolbar_dock = dock; + let mut h = Harness::builder().with_size(vec2(1280.0, 860.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(5); + h +} + +#[test] +fn docked_at_the_top_the_buttons_form_a_row() { + let h = harness(Dock::Top); + let preview = h.get_by_label("Plot Preview").rect(); + let zoom = h.get_by_label("Zoom Window").rect(); + assert!((preview.center().y - zoom.center().y).abs() < 1.0, "{preview:?} {zoom:?}"); + assert!(zoom.left() > preview.right()); + assert!(preview.top() < 60.0, "the row sits along the top: {preview:?}"); +} + +#[test] +fn docked_on_the_left_the_buttons_form_a_column() { + let h = harness(Dock::Left); + let preview = h.get_by_label("Plot Preview").rect(); + let zoom = h.get_by_label("Zoom Window").rect(); + assert!((preview.center().x - zoom.center().x).abs() < 1.0, "{preview:?} {zoom:?}"); + assert!(zoom.top() > preview.bottom()); + let canvas_left = h.get_by_label("Drawing1").rect().left(); + assert!(preview.right() < canvas_left, "the column sits left of the drawing tabs: {preview:?}"); + assert!(preview.left() < toolbar::THICKNESS, "the column sits along the left edge: {preview:?}"); +} + +#[test] +fn the_dock_command_moves_the_bar() { + let mut h = harness(Dock::Top); + h.state_mut().run("ui.toolbar.dock", json!({ "position": "left" })).unwrap(); + h.run_steps(5); + assert_eq!(h.state().ui.toolbar_dock, Dock::Left); + assert!(h.get_by_label("Plot Preview").rect().left() < toolbar::THICKNESS); + assert!(h.state_mut().run("ui.toolbar.dock", json!({ "position": "bottom" })).is_err()); +} + +#[test] +fn buttons_are_added_moved_and_removed() { + let mut h = harness(Dock::Top); + let app = h.state_mut(); + app.run("ui.toolbar.add", json!({ "command": "circle", "index": 0 })).unwrap(); + assert_eq!(app.ui.toolbar_items.first().map(String::as_str), Some("circle")); + assert!(app.run("ui.toolbar.add", json!({ "command": "circle" })).is_err(), "a button appears once"); + assert!(app.run("ui.toolbar.add", json!({ "command": "not-a-command" })).is_err()); + app.run("ui.toolbar.move", json!({ "from": 0, "to": 3 })).unwrap(); + assert_eq!(app.ui.toolbar_items.get(2).map(String::as_str), Some("circle")); + app.run("ui.toolbar.remove", json!({ "command": "plot" })).unwrap(); + assert!(!app.ui.toolbar_items.iter().any(|i| i == "plot")); + h.run_steps(5); + assert!(h.query_by_label("Print").is_none(), "the removed button is gone"); + h.state_mut().run("ui.toolbar.reset", json!({})).unwrap(); + assert_eq!(h.state().ui.toolbar_items, toolbar::default_items()); +} + +#[test] +fn customize_opens_from_the_window_menu_command() { + let mut h = harness(Dock::Top); + h.state_mut().start("ui.dialog.toolbar"); + h.run_steps(5); + assert_eq!(h.state().ui.dialog.as_deref(), Some("toolbar")); + assert!(h.query_by_label("Add Separator").is_some()); +} + +#[test] +fn the_layers_bar_is_a_row_at_the_top_with_the_current_layer() { + let mut h = harness(Dock::Top); + let combo = h.get_by_label("Current Layer").rect(); + assert!(combo.width() > 150.0, "a row shows the drop-down: {combo:?}"); + assert!(combo.top() < 120.0, "under the menu bar: {combo:?}"); + h.state_mut().run("ui.toolbar.dock", json!({ "bar": "layers", "position": "left" })).unwrap(); + h.run_steps(5); + let combo = h.get_by_label("Current Layer").rect(); + assert!(combo.width() < 30.0, "a column shows a button: {combo:?}"); + h.state_mut().run("ui.toggle.toolbar.layers", json!({ "on": false })).unwrap(); + h.run_steps(5); + assert!(h.query_by_label("Current Layer").is_none()); +} + +#[test] +fn the_tool_sets_bar_is_a_column_on_the_left_and_can_move_to_the_top() { + let mut h = harness(Dock::Top); + let st = toolbar::state(&h.state().ui, toolbar::Bar::ToolSets); + assert!(st.show && st.dock == Dock::Left && st.items.first().map(String::as_str) == Some("line")); + let more = h.get_by_label("More Tool Sets bar commands").rect(); + assert!(more.left() < 2.0 * toolbar::THICKNESS, "the column runs along the left: {more:?}"); + let app = h.state_mut(); + app.run("ui.toolbar.dock", json!({ "bar": "toolSets", "position": "top" })).unwrap(); + app.run("ui.toolbar.add", json!({ "bar": "toolSets", "command": "revcloud", "index": 0 })).unwrap(); + assert_eq!(toolbar::state(&app.ui, toolbar::Bar::ToolSets).items.first().map(String::as_str), Some("revcloud")); + assert!(app.run("ui.toolbar.add", json!({ "bar": "nope", "command": "line" })).is_err()); + h.run_steps(5); + assert!(h.query_by_label("More Tool Sets bar commands").is_none(), "a row at 1280 px holds every tool"); +} diff --git a/crates/ui-egui/tests/toolsets_ribbon.rs b/crates/ui-egui/tests/toolsets_ribbon.rs new file mode 100644 index 0000000000..0712da2fe4 --- /dev/null +++ b/crates/ui-egui/tests/toolsets_ribbon.rs @@ -0,0 +1,54 @@ +//! Tool Sets can float, pin to the left, join a group, close, or turn into a ribbon under the +//! menu bar; its right-click menu offers every place but the current one. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::docking::{Panel, ToolSetsAction, ToolSetsPlace, apply_toolsets, toolsets_place}; +use cadcraft_ui_egui::{CadApp, Services}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +fn harness() -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + CadApp::new(Session::new(), Services::default()), + ); + h.run_steps(3); + h +} + +fn act(h: &mut Harness<'_, CadApp>, a: ToolSetsAction) { + let ctx = h.ctx.clone(); + apply_toolsets(h.state_mut(), a, &ctx).unwrap(); + h.run_steps(3); +} + +#[test] +fn tool_sets_moves_between_ribbon_floating_pinned_and_grouped() { + let mut h = harness(); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Pinned); + + act(&mut h, ToolSetsAction::Ribbon); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Ribbon); + assert!(!h.state().ui.docking.layout.contains(&Panel::ToolSets), "not a palette while it is the ribbon"); + // The ribbon's tabs and its Draw tools show. + assert!(h.query_by_label("Annotate").is_some()); + assert!(h.query_all_by_label("Rectangle").count() >= 1); + + act(&mut h, ToolSetsAction::Float); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Floating); + assert!(!h.state().ui.toolsets_ribbon); + + act(&mut h, ToolSetsAction::Group(Panel::Layers)); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Grouped); + + act(&mut h, ToolSetsAction::PinLeft); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Pinned); + + act(&mut h, ToolSetsAction::Close); + assert_eq!(toolsets_place(h.state()), ToolSetsPlace::Closed); + assert!(!h.state().ui.docking.layout.contains(&Panel::ToolSets)); +} diff --git a/crates/ui-egui/tests/workspace_focus.rs b/crates/ui-egui/tests/workspace_focus.rs index e83ee0d024..cefc1c62b0 100644 --- a/crates/ui-egui/tests/workspace_focus.rs +++ b/crates/ui-egui/tests/workspace_focus.rs @@ -10,6 +10,8 @@ fn harness() -> Harness<'static, CadApp> { let mut app = CadApp::new(Session::default(), Services::default()); app.integrated_titlebar = true; app.ui.in_window_menu = false; + // These tests drive the Tool Sets palette; its tools also sit on the Tool Sets bar. + app.ui.toolsets_bar.show = false; let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state( |ui, app: &mut CadApp| { ui.ctx().set_os(egui::os::OperatingSystem::Mac); @@ -38,7 +40,10 @@ fn toolbar_tab_and_shift_tab_skip_title_drag_and_activate_once() { let mut h = harness(); h.key_press(Key::Tab); h.run_steps(2); - assert!(h.get_by_label("New Drawing (⌘N)").is_focused(), "the title drag region is not a keyboard control"); + assert!(h.get_by_label("CADCraft").is_focused(), "the title drag region is not a keyboard control; the application button comes first"); + h.key_press(Key::Tab); + h.run_steps(2); + assert!(h.get_by_label("New Drawing (⌘N)").is_focused()); h.key_press(Key::Tab); h.run_steps(2); assert!(h.get_by_label("Open (⌘O)").is_focused()); From fe632884de9475bbe6243c1f90e591d3423b6735 Mon Sep 17 00:00:00 2001 From: cadcraft Date: Wed, 21 Oct 2026 01:50:11 +0300 Subject: [PATCH 02/23] Application menu with large icons; Save As/Import/Export icons; TEXT and MLEADER open the in-place editor with frame and segment previews; multileader leader type None; Block Manager; Plot Preview zoom and pan; Batch Plot manager across open drawings; style and linetype drop-downs on the Layers bar Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 74 ++++ apps/cadcraft-cli/src/main.rs | 1 + apps/cadcraft/src/main.rs | 1 + crates/doc/src/entity.rs | 12 + crates/doc/src/extents.rs | 1 + crates/engine/src/cmd/annotate.rs | 50 ++- crates/engine/src/cmd/draw.rs | 66 +++- crates/engine/src/cmd/exchange.rs | 148 ++++++- crates/engine/src/cmd/file.rs | 13 + crates/engine/src/cmd/modify2.rs | 2 +- crates/engine/src/cmd/props.rs | 7 +- crates/engine/tests/annotative.rs | 1 + crates/engine/tests/mtext_columns.rs | 1 + crates/engine/tests/text_editor_on_create.rs | 82 ++++ crates/io/src/dxf_mleader.rs | 4 +- crates/io/src/pdf.rs | 21 + crates/io/src/plotter.rs | 5 + crates/io/src/tests.rs | 1 + crates/io/tests/followups_626.rs | 1 + crates/io/tests/mleader_content.rs | 1 + crates/io/tests/mleader_roundtrip.rs | 2 + crates/render/src/lib.rs | 10 +- crates/ui-egui/src/batchplot.rs | 395 +++++++++++++++++++ crates/ui-egui/src/blockmgr.rs | 378 ++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 24 +- crates/ui-egui/src/exchange.rs | 167 ++++++-- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 41 ++ crates/ui-egui/src/i18n/tests.rs | 4 +- crates/ui-egui/src/i18n/uk.tsv | 41 ++ crates/ui-egui/src/icons.rs | 47 ++- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/mtext_editor.rs | 9 +- crates/ui-egui/src/palettes.rs | 23 +- crates/ui-egui/src/toolbar.rs | 249 ++++++++++-- 35 files changed, 1769 insertions(+), 116 deletions(-) create mode 100644 crates/engine/tests/text_editor_on_create.rs create mode 100644 crates/ui-egui/src/batchplot.rs create mode 100644 crates/ui-egui/src/blockmgr.rs diff --git a/WHATS_NEW.md b/WHATS_NEW.md index 81402b1264..db3a39dad8 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,80 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 21.10.2026 (0.9.0-b11) + +### Русский + +**Меню приложения (кнопка CADCraft)** +- Строки стали выше, текст крупнее. Слева от каждого пункта крупный значок. + +**Значки** +- «Сохранить как»: крупный карандаш рядом с дискетой. +- «Импорт» и «Экспорт»: крупные стрелки. + +**Текст (TEXT) и мультивыноска (MLEADER)** +- Пока вы указываете точку вставки, высоту и угол текста, рядом с курсором видна рамка, которую займёт строка. +- После этого открывается окно редактирования текста прямо на чертеже, как у многострочного текста. Enter завершает строку, и окно открывается для следующей строки под ней. Enter в пустой строке завершает команду. +- У мультивыноски, пока вы указываете точки, виден отрезок до курсора. После последней точки открывается окно редактирования текста. +- В палитре «Свойства» у мультивыноски появился тип выноски «Нет». Линия выноски и полка скрываются, но не удаляются: если снова выбрать «Прямая» или «Сплайн», выноска вернётся. В файл DXF записывается тип выноски «невидимая». + +**Диспетчер блоков** +- Кнопка «Блоки» открывает диспетчер блоков: слева список блоков чертежа с поиском, справа предпросмотр выбранного блока, число объектов и вхождений, базовая точка, описание. +- Кнопки: «Вставить» (или двойной щелчок по блоку), «Редактировать блок», «Переименовать», «Удалить» (только неиспользуемый блок), «Сохранить в файл» (WBLOCK), «Создать». + +**Предварительный просмотр печати** +- Сверху кнопки «Увеличить» и «Уменьшить» (лупа с плюсом и с минусом) и «Показать целиком». Колёсико мыши увеличивает и уменьшает изображение вокруг курсора. +- Лист можно перетаскивать мышью. Когда изображение больше окна, снизу и справа появляются полосы прокрутки. +- Окно можно растягивать. Изображение рисуется в более высоком разрешении. + +**Пакетная печать — менеджер печати** +- Пакетная печать открывается в отдельном окне. В нём список листов текущего чертежа в порядке вкладок. +- Порядок меняется перетаскиванием строки или кнопками «Переместить в самый верх», «Переместить выше», «Переместить ниже», «Переместить в самый низ». +- Правый щелчок по листу: «Дублировать» (лист напечатается ещё раз) и «Удалить». +- В разделе «Добавить листы из» можно выбрать любой открытый чертёж и добавить его листы по одному или все сразу. По умолчанию листы других чертежей в список не попадают. +- Внизу выбор: «Один файл PDF со всеми листами» или «Отдельный файл PDF для каждого листа». + +**Панель «Слои»** +- Если слоёв много, у списка текущего слоя появляется полоса прокрутки. +- В панель можно добавить выпадающие списки «Текущий текстовый стиль», «Текущий размерный стиль» и «Текущий тип линий» (в «Настроить панель инструментов», раздел «Слои»). В новой настройке они уже стоят в конце панели. У длинных списков тоже есть прокрутка. + +### English + +**Application menu (the CADCraft button)** +- Taller rows, larger text, and a large icon to the left of each item. + +**Icons** +- Save As: a large pencil beside the floppy disk. +- Import and Export: large arrows. + +**TEXT and MLEADER** +- While you pick the text's start point, height and angle, a frame by the cursor shows where the line will go. +- Then the text editor opens right on the drawing, as for multiline text. Enter finishes the line and the editor opens for the next line below it. Enter on an empty line ends the command. +- While you pick a multileader's points, the segment to the cursor is shown. After the last point the text editor opens. +- The Properties palette offers leader type None for multileaders. The leader line and landing are hidden, not deleted: choosing Straight or Spline again brings them back. DXF files store it as an invisible leader. + +**Block Manager** +- The Blocks button opens a Block Manager: the drawing's blocks in a list with search on the left, and on the right a preview of the selected block, its object and reference counts, base point and description. +- Buttons: Insert (or double-click a block), Edit Block, Rename, Delete (only a block nothing uses), Save to File (WBLOCK), Create. + +**Plot Preview** +- Zoom In and Zoom Out buttons (a magnifier with plus and minus) and Zoom to Fit at the top. The mouse wheel zooms about the cursor. +- Drag the sheet to move it. Scroll bars appear at the bottom and on the right when the image is larger than the window. +- The window can be resized, and the image is rendered at a higher resolution. + +**Batch Plot is now a print manager** +- Batch Plot opens its own window, listing the current drawing's sheets in tab order. +- Change the order by dragging a row or with Move to Top, Move Higher, Move Lower and Move to Bottom. +- Right-click a sheet for Duplicate (it prints again) and Delete. +- Under "Add sheets from" choose any open drawing and add its sheets one by one or all at once. Other drawings' sheets are not in the list unless you add them. +- At the bottom choose "One PDF file with all sheets" or "A separate PDF file for each sheet". + +**Layers bar** +- The current-layer list scrolls when there are many layers. +- Current Text Style, Current Dimension Style and Current Linetype drop-downs can be added to the bar (Customize Tool Bar, Layers section). A fresh setup has them at the end of the bar. Long lists scroll too. + +--- + ## 20.10.2026 (0.9.0-b10) ### Русский diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 8e303ec9d8..7fff9b5d0f 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -169,6 +169,7 @@ fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_plot_book(|items, opts| cadcraft_io::plotter::plot_book(items, opts).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 64e7b67a90..3d54e72b07 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -116,6 +116,7 @@ pub fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_plot_book(|items, opts| cadcraft_io::plotter::plot_book(items, opts).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index d872e2c512..060de2e857 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -718,12 +718,21 @@ pub struct MLeader { /// `leaders` is a multileader without a leader line (leader type None). #[serde(default)] pub spline: bool, + /// Leader type None set on a multileader that has leader lines: they are kept (to come back + /// with Straight or Spline) but not drawn, nor the landing. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub no_leader: bool, /// Block content in place of the text: a block reference placed at the landing. #[serde(default)] pub block: Option, } impl MLeader { + /// It draws no leader line (leader type None). + pub fn leaderless(&self) -> bool { + self.no_leader || self.leaders.is_empty() + } + /// The arrowhead it draws: its own, else its style's (in `d`). pub fn arrow_in<'a>(&'a self, d: &'a crate::Drawing) -> &'a str { if self.arrow.trim().is_empty() { @@ -735,6 +744,9 @@ impl MLeader { /// Each leader line as drawn: through its points to the landing, smoothed for spline leaders. pub fn leader_paths(&self) -> Vec> { + if self.no_leader { + return Vec::new(); + } self.leaders .iter() .map(|l| { diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index be24d8b743..aed018a961 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -354,6 +354,7 @@ mod tests { arrow_size: 1.0, arrow: String::new(), spline: false, + no_leader: false, block: None, }; let b = bounds(EntityKind::MLeader(ml.clone())); diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 839e56e719..002a84c200 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -456,6 +456,7 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< arrow_size: st.arrow_size * k, arrow: String::new(), spline: false, + no_leader: false, block: None, })) } @@ -1556,6 +1557,8 @@ struct MLeaderM { block: bool, block_name: String, block_center: bool, + /// The in-place editor's box while the text is asked for. + editor: Option, } impl MLeaderM { @@ -1578,8 +1581,21 @@ impl MLeaderM { block: o.block && s.doc().is_ok_and(|d| d.block(&s.last_used.mleader_block).is_some()), block_name: s.last_used.mleader_block.clone(), block_center: o.block_center, + editor: None, } } + /// Where the text goes while it is asked for: next to the landing, as the multileader will + /// place it. + fn refresh_editor(&mut self, s: &Session) { + self.editor = if self.wants_text() && self.opt.is_none() { + mleader_kind(s, &self.leader(None), "X", self.landing).and_then(|k| match k { + EntityKind::MLeader(m) => m.text.map(|t| MText { contents: String::new(), ..t }), + _ => None, + }) + } else { + None + }; + } /// Keep the order and Options for the next MLEADER. fn remember(&self, s: &mut Session) { s.last_used.mleader = MLeaderOptions { @@ -1779,6 +1795,30 @@ impl Interactive for MLeaderM { } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + let step = self.answer(s, i); + self.refresh_editor(s); + step + } + fn editing_mtext(&self) -> Option { + self.editor.clone() + } + fn preview(&self, s: &Session, c: Vec2) -> Vec { + if self.opt.is_some() || self.wants_text() || self.leader_done || self.pts.is_empty() { + return Vec::new(); + } + let text = self.text.as_deref().unwrap_or(""); + let next = self.constrained(c); + let shape = mleader_kind(s, &self.leader(Some(next)), text, self.landing) + .and_then(|k| super::mleader_content::apply(s, k, &self.content_spec()).ok()); + // The segment being placed, drawn as well in case the multileader preview hides it. + let mut out = vec![EntityKind::Line(cadcraft_doc::Line { a: v3(*self.pts.last().unwrap_or(&next)), b: v3(next) })]; + out.extend(shape); + out + } +} + +impl MLeaderM { + fn answer(&mut self, s: &mut Session, i: Input) -> Result { if let Some(o) = self.opt { self.opt = self.option(s, o, i); self.remember(s); @@ -1813,16 +1853,6 @@ impl Interactive for MLeaderM { } if self.leader_done && !self.wants_text() { self.finish(s) } else { Ok(Step::Continue) } } - fn preview(&self, s: &Session, c: Vec2) -> Vec { - if self.opt.is_some() || self.wants_text() || self.leader_done || self.pts.is_empty() { - return Vec::new(); - } - let text = self.text.as_deref().unwrap_or(""); - mleader_kind(s, &self.leader(Some(self.constrained(c))), text, self.landing) - .and_then(|k| super::mleader_content::apply(s, k, &self.content_spec()).ok()) - .into_iter() - .collect() - } } #[path = "annotate_tedit.rs"] diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index a9530bd5d1..54efa8b51b 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -1441,6 +1441,11 @@ struct TextM { /// Run by a LISP routine (`command`): one line of text ends the command, as AutoLISP's /// `command` runs TEXT; typed and in scripts each line asks for the next. single_line: bool, + /// The in-place editor's box for the line being typed (once point, height and angle are known). + editor: Option, + /// TEXTSIZE when the command started: the default height and the size of the frame shown + /// before the height is given. + size: f64, } impl TextM { @@ -1453,8 +1458,42 @@ impl TextM { asking_justify: false, line: 0, single_line: s.lisp_running(), + editor: None, + size: s.doc().map(|d| d.header.f64("TEXTSIZE", 0.2)).unwrap_or(0.2), } } + /// Where line `line` starts: one line spacing (5/3 of the height) below the one before. + fn line_at(a: Vec2, h: f64, r: f64, line: usize) -> Vec2 { + a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * line as f64) + } + /// The editor's box once the start point, height and angle are known. + fn refresh_editor(&mut self, s: &Session) { + self.editor = match (self.at, self.height, self.rotation, self.asking_justify) { + (Some(a), Some(h), Some(r), false) => match make_text(s, Self::line_at(a, h, r, self.line), "", h, r, self.justify) { + EntityKind::Text(t) => Some(super::modify2::line_box(&t)), + _ => None, + }, + _ => None, + }; + } + /// The outline of a line of text `h` high at `a`, turned by `r`, placed by the justification: + /// what the text will cover before it is typed (four characters wide). + fn frame(&self, a: Vec2, h: f64, r: f64) -> EntityKind { + let w = h * 3.2; + let x0 = match self.justify.0 { + HAlign::Left | HAlign::Aligned | HAlign::Fit => 0.0, + HAlign::Center | HAlign::Middle => -w / 2.0, + HAlign::Right => -w, + }; + let y0 = match (self.justify.0, self.justify.1) { + (HAlign::Middle, _) | (_, VAlign::Middle) => -h / 2.0, + (_, VAlign::Top) => -h, + (_, VAlign::Bottom) => -h / 3.0, + _ => 0.0, + }; + let corners = [Vec2::new(x0, y0), Vec2::new(x0 + w, y0), Vec2::new(x0 + w, y0 + h), Vec2::new(x0, y0 + h)]; + lwpoly(corners.iter().map(|q| PolyVertex::new(a + q.rotate(r))).collect(), true) + } } impl Interactive for TextM { @@ -1484,6 +1523,29 @@ impl Interactive for TextM { Ok(Step::Continue) } fn input(&mut self, s: &mut Session, i: Input) -> Result { + let step = self.answer(s, i); + self.refresh_editor(s); + step + } + fn text_editor(&self) -> Option { + let mtext = self.editor.clone()?; + Some(crate::TextEditor { mtext, kind: crate::EditorKind::Line, key: format!("new-text:{}", self.line) }) + } + fn preview(&self, _s: &Session, c: Vec2) -> Vec { + if self.asking_justify { + return Vec::new(); + } + match (self.at, self.height, self.rotation) { + (None, _, _) => vec![self.frame(c, self.size, 0.0)], + (Some(a), None, _) => vec![self.frame(a, a.dist(c).max(1e-9), 0.0)], + (Some(a), Some(h), None) if a.dist(c) > 1e-12 => vec![self.frame(a, h, a.angle_to(c))], + _ => Vec::new(), + } + } +} + +impl TextM { + fn answer(&mut self, s: &mut Session, i: Input) -> Result { if self.asking_justify { let code = match &i { Input::Keyword(k) | Input::Text(k) => k.clone(), @@ -1509,8 +1571,10 @@ impl Interactive for TextM { (Some(_), Some(_), None, Input::Text(t)) => { self.rotation = Some(s.angle_settings().direction(&t).ok_or_else(|| crate::EngineError::Other("Requires an angle.".into()))?) } + // An empty line (the editor finished with nothing typed) ends the command. + (Some(_), Some(_), Some(_), Input::Text(t)) if t.is_empty() => return Ok(Step::Done), (Some(a), Some(h), Some(r), Input::Text(t)) => { - let at = a + Vec2::from_angle(r - std::f64::consts::FRAC_PI_2) * (h * 5.0 / 3.0 * self.line as f64); + let at = Self::line_at(a, h, r, self.line); let k = make_text(s, at, &t, h, r, self.justify); s.add_entity(k)?; self.line += 1; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 6429af1f68..a7b9a12ec6 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { .noundo(), CommandSpec::new("publish", "Batch Publish...", run_publish) .menu(&["File", "Batch Publish..."]) - .params("{path?: \"NAME.pdf\" (writes NAME-.pdf per sheet; else returns base64 `data` per sheet), layouts?: [name | \"Model\"] (default: Model if it has objects, then every layout in tab order)} → {sheets: [{layout, bytes, path? | data}]}") + .params("{path?: \"NAME.pdf\" (writes NAME-.pdf per sheet; else returns base64 `data` per sheet), layouts?: [name | \"Model\"] (default: Model if it has objects, then every layout in tab order), sheets?: [{drawing?: index of an open drawing (default the current one), layout: name | \"Model\"}] (in place of layouts; a sheet may repeat), combine?: bool (one PDF of all the sheets, at `path` itself)} → {sheets: [{layout, bytes, path? | data}]}") .noundo(), CommandSpec::new("pdfbook", "Sheet Books to PDF...", run_pdfbook) .menu(&["File", "Sheet Books to PDF..."]) @@ -370,7 +370,153 @@ fn file_part(name: &str) -> String { name.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.') { c } else { '_' }).collect() } +/// One sheet of a PUBLISH list: an open drawing (index in [`Session::docs`]) and a layout of it. +struct PubSheet { + doc: usize, + space: Space, +} + +/// The `sheets` list of PUBLISH: each names an open drawing and one of its layouts. +fn publish_sheets(s: &Session, v: &Value) -> Result> { + let a = v.as_array().ok_or_else(|| bad("publish", "`sheets` must be a list of {drawing?, layout}"))?; + if a.len() > MAX_SHEETS { + return Err(bad("publish", format!("at most {MAX_SHEETS} sheets can be published at once"))); + } + a.iter() + .map(|it| { + let doc = match it.get("drawing") { + None | Some(Value::Null) => s.active, + Some(n) => n + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad("publish", "`drawing` must be the index of an open drawing"))?, + }; + let d = s.docs.get(doc).ok_or_else(|| bad("publish", format!("no open drawing {doc}")))?; + let name = it.get("layout").and_then(Value::as_str).ok_or_else(|| bad("publish", "each sheet needs a `layout`"))?; + let space = if name.eq_ignore_ascii_case("model") { + Space::Model + } else { + Space::Paper(d.doc.layout(name).map(|l| l.name.clone()).ok_or_else(|| bad("publish", format!("{}: no layout `{name}`", d.title)))?) + }; + Ok(PubSheet { doc, space }) + }) + .collect() +} + +/// Write `bytes` to `path` through a temporary file, as PLOT does. +fn write_pdf(path: &str, bytes: &[u8]) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + let tmp = format!("{path}.cadcraft-tmp"); + std::fs::write(&tmp, bytes).map_err(|e| bad("publish", format!("{path}: {e}")))?; + std::fs::rename(&tmp, path).map_err(|e| bad("publish", format!("{path}: {e}"))) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, bytes); + Err(bad("publish", "paths are not available on the web; omit `path` to get the PDF as base64 `data`")) + } +} + +/// PUBLISH of a `sheets` list: sheets of any open drawing, in order, into one PDF (`combine`) or +/// one PDF each. +fn publish_list(s: &mut Session, p: &Value, list: Vec) -> Result { + if list.is_empty() { + return Err(bad("publish", "there are no sheets to publish")); + } + let path = str_param(p, "path").map(str::to_string); + let several = list.iter().any(|x| x.doc != list[0].doc); + if p.get("combine").and_then(Value::as_bool) == Some(true) { + let hook = super::file::plot_book().ok_or_else(|| bad("publish", "combining sheets is not available in this build"))?; + let items: Vec<(&Drawing, Space)> = list.iter().map(|x| (&*s.docs[x.doc].doc, x.space.clone())).collect(); + let bytes = hook(&items, &json!({})).map_err(|e| bad("publish", e))?; + let r = match &path { + Some(path) => { + write_pdf(path, &bytes)?; + json!({ "path": path, "bytes": bytes.len(), "pages": list.len() }) + } + None => json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "pages": list.len() }), + }; + let message = match &path { + Some(path) => format!("Published {} sheet(s) to {path}", list.len()), + None => format!("Published {} sheet(s)", list.len()), + }; + return Ok(json!({ "sheets": [r], "message": message })); + } + let base = path.as_deref().map(|path| { + let pb = std::path::Path::new(path); + let stem = pb.file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| "Drawing".into()); + (pb.parent().map(std::path::Path::to_path_buf).unwrap_or_default(), stem) + }); + let back = s.active; + let mut used = std::collections::HashSet::new(); + let mut out = Vec::new(); + let mut failed = None; + for x in &list { + let name = x.space.tab_name().to_string(); + let mut q = json!({ "layout": name }); + if let Some((dir, stem)) = &base { + // Sheets of other drawings carry the drawing's name; a repeated sheet is numbered. + let mut file = if several { + let title = std::path::Path::new(&s.docs[x.doc].title).file_stem().map(|t| t.to_string_lossy().to_string()).unwrap_or_default(); + format!("{stem}-{}-{}", file_part(&title), file_part(&name)) + } else { + format!("{stem}-{}", file_part(&name)) + }; + let first = file.clone(); + let mut n = 1; + while !used.insert(file.clone()) { + n += 1; + file = format!("{first}-{n}"); + } + q["path"] = json!(dir.join(format!("{file}.pdf")).to_string_lossy()); + } + s.active = x.doc; + let r = s.execute("plot", &q); + s.active = back; + match r { + Ok(mut r) => { + if let Some(o) = r.as_object_mut() { + o.insert("layout".into(), json!(name)); + o.insert("drawing".into(), json!(s.docs[x.doc].title)); + } + out.push(r); + } + Err(e) => { + failed = Some(bad("publish", format!("{}: {name}: {e}", s.docs[x.doc].title))); + break; + } + } + } + if let Some(e) = failed { + return Err(e); + } + let message = match &base { + Some(_) => format!("Published {} sheet(s): {}", out.len(), out.iter().filter_map(|r| r["path"].as_str()).collect::>().join(", ")), + None => format!("Published {} sheet(s)", out.len()), + }; + Ok(json!({ "sheets": out, "message": message })) +} + fn run_publish(s: &mut Session, p: &Value) -> Result { + if let Some(v) = p.get("sheets") { + let list = publish_sheets(s, v)?; + return publish_list(s, p, list); + } + if p.get("combine").and_then(Value::as_bool) == Some(true) { + let names: Vec = match p.get("layouts") { + Some(Value::Array(a)) => a.iter().map(|n| json!({ "layout": n })).collect(), + _ => { + let d = s.doc()?; + let mut layouts: Vec<_> = d.layouts.iter().collect(); + layouts.sort_by_key(|l| l.tab_order); + let model = (!d.model.is_empty()).then(|| json!({ "layout": "Model" })); + model.into_iter().chain(layouts.iter().map(|l| json!({ "layout": l.name }))).collect() + } + }; + let list = publish_sheets(s, &Value::Array(names))?; + return publish_list(s, p, list); + } let d = s.doc()?; let sheets: Vec = match p.get("layouts") { Some(v) => { diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index c6c977ca24..a66ca97a2e 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -30,6 +30,19 @@ pub struct IoHooks { static IO: OnceLock = OnceLock::new(); +/// Plot sheets of several drawings into one PDF, one page each in order, with JSON options for +/// the whole file (installed by the app; PUBLISH with `combine` across open drawings). +pub type PlotBookHook = fn(&[(&Drawing, cadcraft_doc::Space)], &Value) -> std::result::Result, String>; + +static PLOT_BOOK: OnceLock = OnceLock::new(); + +pub fn set_plot_book(h: PlotBookHook) { + let _ = PLOT_BOOK.set(h); +} +pub fn plot_book() -> Option { + PLOT_BOOK.get().copied() +} + pub fn set_io(h: IoHooks) { let _ = IO.set(h); } diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 10d7ab38a8..76a4ab8690 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -2173,7 +2173,7 @@ fn text_of(k: &EntityKind) -> Option { } /// A box for the in-place editor showing one line of text where `t` sits. -fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { +pub(crate) fn line_box(t: &cadcraft_doc::Text) -> cadcraft_doc::MText { use cadcraft_doc::{HAlign, VAlign}; let col = match t.halign { HAlign::Left => 0u8, diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 3cbeb23127..5a5e70fa45 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline, dogleg (landing distance; 0 = no landing), textHeight}"), + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -405,8 +405,9 @@ fn run_set(s: &mut Session, p: &Value) -> Result { m.arrow_size = x; } match str_param(p, "leaderType").map(str::to_ascii_lowercase).as_deref() { - Some("spline") => m.spline = true, - Some("straight") => m.spline = false, + Some("spline") => (m.spline, m.no_leader) = (true, false), + Some("straight") => (m.spline, m.no_leader) = (false, false), + Some("none") => m.no_leader = true, _ => {} } if let Some(x) = num("dogleg").filter(|x| *x >= 0.0) { diff --git a/crates/engine/tests/annotative.rs b/crates/engine/tests/annotative.rs index b397f10fdf..9052d57fa3 100644 --- a/crates/engine/tests/annotative.rs +++ b/crates/engine/tests/annotative.rs @@ -323,6 +323,7 @@ fn annotative_mtext_columns_follow_the_scale() { arrow_size: 1.0, arrow: String::new(), spline: false, + no_leader: false, block: None, }), ..e.clone() diff --git a/crates/engine/tests/mtext_columns.rs b/crates/engine/tests/mtext_columns.rs index 1ed5d2efa6..25c9f9b3be 100644 --- a/crates/engine/tests/mtext_columns.rs +++ b/crates/engine/tests/mtext_columns.rs @@ -114,6 +114,7 @@ fn scale_scales_multileader_text_width_and_columns() { arrow_size: 1.0, arrow: String::new(), spline: false, + no_leader: false, block: None, }; let h = s.add_entity(EntityKind::MLeader(ml)).unwrap(); diff --git a/crates/engine/tests/text_editor_on_create.rs b/crates/engine/tests/text_editor_on_create.rs new file mode 100644 index 0000000000..89c146140f --- /dev/null +++ b/crates/engine/tests/text_editor_on_create.rs @@ -0,0 +1,82 @@ +//! TEXT and MLEADER hand their text to the in-place editor once it is asked for, and show the +//! text's frame / the leader segment while points are picked. + +use cadcraft_engine::doc::EntityKind; +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{EditorKind, Input, Session}; + +fn texts(s: &Session) -> Vec { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Text(t) => Some(t.value.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn text_opens_a_line_editor_for_each_line_and_an_empty_line_ends_it() { + let mut s = Session::new(); + s.start("text").unwrap(); + // Before the start point: the frame of a line of text follows the cursor. + assert!(!s.preview(Vec2::new(1.0, 1.0)).is_empty()); + assert!(s.text_editor().is_none()); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + assert!(!s.preview(Vec2::new(0.0, 2.0)).is_empty(), "the frame grows with the height"); + s.input(Input::Enter).unwrap(); + s.input(Input::Enter).unwrap(); + let ed = s.text_editor().expect("the editor opens at the text prompt"); + assert_eq!(ed.kind, EditorKind::Line); + let first_key = ed.key.clone(); + s.input(Input::Text("first".into())).unwrap(); + let ed = s.text_editor().expect("the next line gets an editor"); + assert_ne!(ed.key, first_key); + assert!(ed.mtext.insert.y < 0.0, "the next line is below the first"); + s.input(Input::Text("second".into())).unwrap(); + s.input(Input::Text(String::new())).unwrap(); + assert!(s.running.is_none()); + assert_eq!(texts(&s), ["first", "second"]); +} + +#[test] +fn mleader_opens_the_editor_after_its_leader_and_previews_the_segment() { + let mut s = Session::new(); + s.start("mleader").unwrap(); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + assert!(!s.preview(Vec2::new(5.0, 5.0)).is_empty(), "the segment to the cursor shows"); + assert!(s.editing_mtext().is_none()); + s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + let m = s.editing_mtext().expect("the editor opens at the landing"); + assert!(m.insert.x > 5.0 && m.contents.is_empty()); + s.input(Input::Text("NOTE".into())).unwrap(); + assert!(s.running.is_none()); + let found = + s.doc().unwrap().model.iter().any(|e| matches!(&e.kind, EntityKind::MLeader(m) if m.text.as_ref().is_some_and(|t| t.contents == "NOTE"))); + assert!(found); +} + +#[test] +fn leader_type_none_hides_the_leader_and_straight_brings_it_back() { + let mut s = Session::new(); + let r = s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap(); + let h = r["handle"].as_str().unwrap().to_string(); + let get = |s: &Session| { + s.doc() + .unwrap() + .model + .iter() + .find_map(|e| match &e.kind { + EntityKind::MLeader(m) => Some(m.clone()), + _ => None, + }) + .unwrap() + }; + s.execute("properties.set", &serde_json::json!({ "handles": [h], "leaderType": "none" })).unwrap(); + let m = get(&s); + assert!(m.leaderless() && !m.leaders.is_empty() && m.leader_paths().is_empty()); + s.execute("properties.set", &serde_json::json!({ "handles": [h], "leaderType": "straight" })).unwrap(); + assert!(!get(&s).leaderless()); +} diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index f29b84d722..ab57d5a864 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -332,6 +332,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { row_spacing: 0.0, } }); + let no_leader = p.leader_type == Some(0) && !leaders.is_empty(); MLeader { leaders, landing, @@ -341,6 +342,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { arrow_size: pos(p.arrow_ctx).or(pos(p.arrow)).unwrap_or(def.arrow_size), arrow: String::new(), spline: p.leader_type == Some(2), + no_leader, block, } } @@ -589,7 +591,7 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec { i( &mut t, 170, - if m.leaders.is_empty() { + if m.leaderless() { 0 } else if m.spline { 2 diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 1423e7a1d9..09c1eb16e3 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -375,6 +375,27 @@ pub fn pdf_items(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Ok(assemble(d, &pages, &fonts, o, &title)) } +/// Write a vector PDF of sheets from several drawings, one page per `(drawing, space)` in order +/// (at most [`MAX_PAGES`]). Each drawing has its own layers, so none become PDF layers. +pub fn pdf_book(items: &[(&Drawing, Space)], o: &PdfOptions) -> Result> { + let Some((first, _)) = items.first() else { return Err(IoError::Format("there are no sheets to plot".into())) }; + if items.len() > MAX_PAGES { + return Err(IoError::Format(format!("at most {MAX_PAGES} sheets fit in one PDF"))); + } + let mut po = o.clone(); + po.layers = false; + let pages = items + .iter() + .map(|(d, s)| { + let links = all_links(d, &po); + sheet(d, s, &po, &links) + }) + .collect::>>()?; + let title = if po.title.is_empty() { pages.first().map(|p| p.label.clone()).unwrap_or_default() } else { po.title.clone() }; + let fonts = if po.text_as_geometry { fonts::Fonts::default() } else { fonts::Fonts::collect(pages.iter().map(|p| &p.list)) }; + Ok(assemble(first, &pages, &fonts, &po, &title)) +} + /// One plotted sheet, ready to be written as a page. struct SheetPage { /// Page size in points. diff --git a/crates/io/src/plotter.rs b/crates/io/src/plotter.rs index d916d76ff5..47e6ed428e 100644 --- a/crates/io/src/plotter.rs +++ b/crates/io/src/plotter.rs @@ -50,6 +50,11 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result> { } } +/// One PDF of sheets from several drawings ([`pdf::pdf_book`]), with the file-wide options of `opts`. +pub fn plot_book(items: &[(&Drawing, Space)], opts: &Value) -> Result> { + pdf::pdf_book(items, &PdfOptions::from_json(opts)) +} + /// The sheet a plot draws on (a model-space plot's printable area inside the device margins). fn sheet(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<(Sheet, cadcraft_doc::PageSetup)> { let page = pdf::page_for(d, space, o)?; diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index a1ae98f5b8..fbbbbb7d44 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1554,6 +1554,7 @@ fn mleader_is_written_as_multileader() { arrow_size: 2.5, arrow: String::new(), spline: false, + no_leader: false, block: None, }; d.add(&Space::Model, Default::default(), EntityKind::MLeader(m.clone())).unwrap(); diff --git a/crates/io/tests/followups_626.rs b/crates/io/tests/followups_626.rs index 797d4b5356..eba7c64646 100644 --- a/crates/io/tests/followups_626.rs +++ b/crates/io/tests/followups_626.rs @@ -50,6 +50,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { arrow_size: 1.0, arrow: String::new(), spline: false, + no_leader: false, block: None, }; d.add(&Space::Model, Common { layer: "0".into(), ..Common::default() }, EntityKind::MLeader(m.clone())).unwrap(); diff --git a/crates/io/tests/mleader_content.rs b/crates/io/tests/mleader_content.rs index 0c2ac30747..3c1984d27f 100644 --- a/crates/io/tests/mleader_content.rs +++ b/crates/io/tests/mleader_content.rs @@ -19,6 +19,7 @@ fn spline_leader_and_block_content_are_written() { arrow_size: 1.0, arrow: String::new(), spline: true, + no_leader: false, block: Some(Insert { block: "TAG".into(), insert: Vec3::new(11.0, 0.0, 0.0), diff --git a/crates/io/tests/mleader_roundtrip.rs b/crates/io/tests/mleader_roundtrip.rs index 502ea8d8b8..8bb8085aad 100644 --- a/crates/io/tests/mleader_roundtrip.rs +++ b/crates/io/tests/mleader_roundtrip.rs @@ -37,6 +37,7 @@ fn text_mleader() -> MLeader { arrow_size: 0.3, arrow: String::new(), spline: false, + no_leader: false, block: None, } } @@ -132,6 +133,7 @@ fn spline_leader_with_block_content_and_attributes() { arrow_size: 0.18, arrow: String::new(), spline: true, + no_leader: false, block: Some(ins), }; d.add(&Space::Model, Common::default(), EntityKind::MLeader(m.clone())).unwrap(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5d90e2a1a5..16b05db5f7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1227,13 +1227,15 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { } } if let Some(t) = &m.text { - let land = m.landing.xy(); - let dir = if t.insert.x >= land.x { 1.0 } else { -1.0 }; - b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); + if !m.no_leader { + let land = m.landing.xy(); + let dir = if t.insert.x >= land.x { 1.0 } else { -1.0 }; + b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); + } mtext(b, ctx, t, rgb, lw); } if let Some(ins) = &m.block { - if m.dogleg > 0.0 && !m.leaders.is_empty() { + if m.dogleg > 0.0 && !m.leaderless() { let land = m.landing.xy(); let dir = if ins.insert.x >= land.x { 1.0 } else { -1.0 }; b.polyline(ctx, rgb, lw, &[land, land + Vec2::new(m.dogleg * dir, 0.0)]); diff --git a/crates/ui-egui/src/batchplot.rs b/crates/ui-egui/src/batchplot.rs new file mode 100644 index 0000000000..da81a1994e --- /dev/null +++ b/crates/ui-egui/src/batchplot.rs @@ -0,0 +1,395 @@ +//! Batch Plot: a print manager. The sheets to plot in a list that can be reordered (drag, or the +//! Move buttons), with sheets repeated or removed; sheets of any open drawing can be added; the +//! result is one PDF with every sheet or one PDF per sheet (PUBLISH with `sheets`). + +use egui::{Rect, RichText, Sense, Stroke, pos2, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::icons::{self, Icon}; +use crate::theme::Tokens; + +/// One sheet in the list: the drawing it belongs to (its title) and the layout (or `Model`). +#[derive(Clone, Debug, PartialEq)] +pub struct Sheet { + pub drawing: String, + pub layout: String, +} + +/// The window's state between frames. +#[derive(Clone, Default)] +struct State { + sheets: Vec, + /// The drawing the list was filled from when the window opened. + filled_for: Option, + selected: Option, + dragging: Option, + /// The drawing whose sheets the Add section shows. + add_from: Option, + separate: bool, + note: Option, +} + +fn state_id() -> egui::Id { + egui::Id::new("cc_batch_plot") +} + +/// The sheets of drawing `d` in tab order: Model when it has objects, then the layouts. +pub fn sheets_of(d: &cadcraft_doc::Drawing, title: &str) -> Vec { + let mut layouts: Vec<_> = d.layouts.iter().collect(); + layouts.sort_by_key(|l| l.tab_order); + let model = (!d.model.is_empty()).then(|| "Model".to_string()); + model.into_iter().chain(layouts.iter().map(|l| l.name.clone())).map(|layout| Sheet { drawing: title.to_string(), layout }).collect() +} + +/// Move the sheet at `from` to stand before `slot` (0..=len). +pub fn move_sheet(v: &mut Vec, from: usize, slot: usize) -> Option { + if from >= v.len() { + return None; + } + let s = v.remove(from); + let to = if slot > from { slot - 1 } else { slot }.min(v.len()); + v.insert(to, s); + Some(to) +} + +/// The PUBLISH parameters for `sheets` (drawing titles resolved to open drawings). +pub fn publish_params(app: &CadApp, sheets: &[Sheet], combine: bool, path: Option<&str>) -> Result { + let list: Vec = sheets + .iter() + .map(|s| { + let i = app + .session + .docs + .iter() + .position(|d| d.title == s.drawing) + .ok_or_else(|| format!("{}: {}", crate::tl!("The drawing is closed"), s.drawing))?; + Ok(json!({ "drawing": i, "layout": s.layout })) + }) + .collect::>()?; + let mut p = json!({ "sheets": list, "combine": combine }); + if let Some(path) = path { + p["path"] = json!(path); + } + Ok(p) +} + +/// What a click asked for, applied once the list is drawn. +enum Act { + Select(usize), + Move(usize, usize), + Duplicate(usize), + Remove(usize), + Add(Sheet), + AddAll(String), + Clear, + Plot, +} + +/// File ▸ Batch Plot: the print manager window. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); + let current = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); + // Opened for a drawing: its sheets, in tab order (others are added by hand). + if st.filled_for.as_deref() != Some(current.as_str()) { + st.sheets = app.session.doc().map(|d| sheets_of(d, ¤t)).unwrap_or_default(); + st.filled_for = Some(current.clone()); + st.selected = None; + st.add_from = Some(current.clone()); + st.note = None; + } + let titles: Vec = app.session.docs.iter().map(|d| d.title.clone()).collect(); + let several = st.sheets.iter().any(|s| s.drawing != current) || titles.len() > 1; + let paper = |s: &Sheet| -> String { + let Some(d) = app.session.docs.iter().find(|d| d.title == s.drawing) else { return crate::tl!("closed").to_string() }; + if s.layout == "Model" { + return String::new(); + } + d.doc.layout(&s.layout).map(|l| l.page.paper.clone()).unwrap_or_default() + }; + let rows: Vec<(String, String, String)> = st.sheets.iter().map(|s| (s.layout.clone(), s.drawing.clone(), paper(s))).collect(); + let can_plot = app.services.pick_save.is_some(); + let mut act: Option = None; + let mut close = false; + egui::Window::new(crate::tl!("Batch Plot")) + .id(egui::Id::new("cc_batch_plot_window")) + .open(open) + .default_size(vec2(680.0, 500.0)) + .min_size(vec2(520.0, 380.0)) + .resizable(true) + .show(ctx, |ui| { + let t = Tokens::get(); + ui.label(RichText::new(crate::tl!("Sheets to plot, in order")).strong()); + ui.horizontal_top(|ui| { + let list_w = (ui.available_width() - 190.0).max(260.0); + let list_h = (ui.available_height() - 190.0).max(140.0); + ui.allocate_ui_with_layout(vec2(list_w, list_h), egui::Layout::top_down(egui::Align::LEFT), |ui| { + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(2.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("cc_batch_list").auto_shrink([false, false]).max_height(list_h - 6.0).show(ui, |ui| { + let w = list_w - 10.0; + ui.set_width(w); + let mut rects: Vec = Vec::new(); + for (i, (layout, drawing, paper)) in rows.iter().enumerate() { + let (r, resp) = ui.allocate_exact_size(vec2(w, 24.0), Sense::click_and_drag()); + rects.push(r); + let on = st.selected == Some(i); + if on { + ui.painter().rect_filled(r, 2.0, t.accent.gamma_multiply(0.35)); + } else if resp.hovered() { + ui.painter().rect_filled(r, 2.0, t.control_hover.gamma_multiply(0.6)); + } + let p = ui.painter().with_clip_rect(r); + let y = r.center().y; + // A grip that shows rows can be dragged. + for dy in [-4.0, 0.0, 4.0] { + p.hline((r.left() + 5.0)..=(r.left() + 13.0), y + dy, Stroke::new(1.0, t.text_faint)); + } + p.text(pos2(r.left() + 20.0, y), egui::Align2::LEFT_CENTER, format!("{}.", i + 1), crate::theme::body(), t.text_dim); + p.text(pos2(r.left() + 48.0, y), egui::Align2::LEFT_CENTER, crate::i18n::t(layout), crate::theme::body(), t.text); + if several { + // Hebrew names read right to left, as in the file manager. + let job = crate::i18n::job(drawing, crate::theme::small(), t.text_dim); + let g = ui.ctx().fonts_mut(|f| f.layout_job(job)); + p.galley(pos2(r.left() + w * 0.45, y - g.size().y / 2.0), g, t.text_dim); + } + p.text(pos2(r.right() - 6.0, y), egui::Align2::RIGHT_CENTER, paper, crate::theme::small(), t.text_dim); + if resp.clicked() || resp.drag_started() { + act = Some(Act::Select(i)); + } + if resp.drag_started() { + st.dragging = Some(i); + } + resp.context_menu(|ui| { + if ui.button(crate::tl!("Duplicate")).clicked() { + act = Some(Act::Duplicate(i)); + ui.close(); + } + if ui.button(crate::tl!("Delete")).clicked() { + act = Some(Act::Remove(i)); + ui.close(); + } + }); + } + if rows.is_empty() { + ui.label(RichText::new(crate::tl!("No sheets. Add sheets below.")).color(t.text_dim)); + } + // Dragging a row: a line where it will land. + if let Some(from) = st.dragging { + let pointer = ui.ctx().pointer_latest_pos(); + let slot = pointer.map(|p| rects.iter().position(|r| p.y < r.center().y).unwrap_or(rects.len())); + if let Some(slot) = slot { + let y = rects.get(slot).map_or_else(|| rects.last().map_or(0.0, |r| r.bottom()), |r| r.top()); + if let Some(first) = rects.first() { + ui.painter().hline(first.left()..=first.right(), y, Stroke::new(2.0, t.accent)); + } + } + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + if ui.input(|i| i.pointer.any_released()) { + if let Some(slot) = slot + && slot != from + && slot != from + 1 + { + act = Some(Act::Move(from, slot)); + } + st.dragging = None; + } + } + }); + }); + }); + // The order and list buttons. + ui.vertical(|ui| { + ui.set_width(180.0); + let sel = st.selected.filter(|i| *i < st.sheets.len()); + let n = st.sheets.len(); + let row = |ui: &mut egui::Ui, icon: Icon, label: &str, enabled: bool| -> bool { + ui.add_enabled_ui(enabled, |ui| { + ui.horizontal(|ui| { + let r = ui.add_sized(vec2(176.0, 26.0), egui::Button::new("")); + let ir = Rect::from_center_size(pos2(r.rect.left() + 15.0, r.rect.center().y), vec2(18.0, 18.0)); + icons::paint(ui.painter(), ir, icon, !enabled); + let col = if enabled { Tokens::get().text } else { Tokens::get().text_faint }; + ui.painter().text( + pos2(r.rect.left() + 30.0, r.rect.center().y), + egui::Align2::LEFT_CENTER, + label, + crate::theme::body(), + col, + ); + r.clicked() + }) + .inner + }) + .inner + }; + if row(ui, Icon::MoveTop, crate::tl!("Move to Top"), sel.is_some_and(|i| i > 0)) + && let Some(i) = sel + { + act = Some(Act::Move(i, 0)); + } + if row(ui, Icon::MoveUp, crate::tl!("Move Higher"), sel.is_some_and(|i| i > 0)) + && let Some(i) = sel + { + act = Some(Act::Move(i, i.saturating_sub(1))); + } + if row(ui, Icon::MoveDown, crate::tl!("Move Lower"), sel.is_some_and(|i| i + 1 < n)) + && let Some(i) = sel + { + act = Some(Act::Move(i, i + 2)); + } + if row(ui, Icon::MoveBottom, crate::tl!("Move to Bottom"), sel.is_some_and(|i| i + 1 < n)) + && let Some(i) = sel + { + act = Some(Act::Move(i, n)); + } + ui.add_space(6.0); + if row(ui, Icon::Copy, crate::tl!("Duplicate"), sel.is_some()) + && let Some(i) = sel + { + act = Some(Act::Duplicate(i)); + } + if row(ui, Icon::Erase, crate::tl!("Delete"), sel.is_some()) + && let Some(i) = sel + { + act = Some(Act::Remove(i)); + } + if row(ui, Icon::Close, crate::tl!("Clear List"), n > 0) { + act = Some(Act::Clear); + } + }); + }); + ui.add_space(6.0); + ui.separator(); + // Adding sheets: from any open drawing. + ui.horizontal(|ui| { + ui.label(crate::tl!("Add sheets from")); + let from = st.add_from.clone().filter(|f| titles.contains(f)).unwrap_or_else(|| current.clone()); + let shown = crate::i18n::widget(ui, &from, egui::TextStyle::Body); + egui::ComboBox::from_id_salt("cc_batch_from").selected_text(shown).width(220.0).show_ui(ui, |ui| { + for title in &titles { + let name = crate::i18n::widget(ui, title, egui::TextStyle::Body); + if ui.selectable_label(*title == from, name).clicked() { + st.add_from = Some(title.clone()); + } + } + }); + if ui.button(crate::tl!("Add All")).clicked() { + act = Some(Act::AddAll(from.clone())); + } + }); + let from = st.add_from.clone().filter(|f| titles.contains(f)).unwrap_or_else(|| current.clone()); + let available = app.session.docs.iter().find(|d| d.title == from).map(|d| sheets_of(&d.doc, &from)).unwrap_or_default(); + egui::ScrollArea::horizontal().id_salt("cc_batch_add").max_height(34.0).show(ui, |ui| { + ui.horizontal(|ui| { + for s in available { + if ui + .button(format!("+ {}", crate::i18n::t(&s.layout))) + .on_hover_text(crate::tl!("Add this sheet to the end of the list")) + .clicked() + { + act = Some(Act::Add(s)); + } + } + }); + }); + ui.separator(); + ui.horizontal(|ui| { + ui.radio_value(&mut st.separate, false, crate::tl!("One PDF file with all sheets")); + ui.radio_value(&mut st.separate, true, crate::tl!("A separate PDF file for each sheet")); + }); + if let Some(n) = &st.note { + ui.label(RichText::new(n).color(t.text_dim)); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + let enabled = can_plot && !st.sheets.is_empty(); + let r = ui.add_enabled(enabled, egui::Button::new(crate::tl!("Plot..."))); + let r = if can_plot { r } else { r.on_disabled_hover_text(crate::tl!("There is no file dialog here")) }; + if r.clicked() { + act = Some(Act::Plot); + } + if ui.button(crate::tl!("Close")).clicked() { + close = true; + } + ui.label(RichText::new(format!("{} {}", st.sheets.len(), crate::tl!("sheets"))).color(t.text_dim)); + }); + }); + match act { + Some(Act::Select(i)) => st.selected = Some(i), + Some(Act::Move(from, slot)) => st.selected = move_sheet(&mut st.sheets, from, slot), + Some(Act::Duplicate(i)) => { + if let Some(s) = st.sheets.get(i).cloned() { + st.sheets.insert(i + 1, s); + st.selected = Some(i + 1); + } + } + Some(Act::Remove(i)) => { + if i < st.sheets.len() { + st.sheets.remove(i); + st.selected = if st.sheets.is_empty() { None } else { Some(i.min(st.sheets.len() - 1)) }; + } + } + Some(Act::Add(s)) => { + st.sheets.push(s); + st.selected = Some(st.sheets.len() - 1); + } + Some(Act::AddAll(title)) => { + if let Some(d) = app.session.docs.iter().find(|d| d.title == title) { + st.sheets.extend(sheets_of(&d.doc, &title)); + } + } + Some(Act::Clear) => { + st.sheets.clear(); + st.selected = None; + } + Some(Act::Plot) => { + let stem = std::path::Path::new(¤t) + .file_stem() + .map(|s| s.to_string_lossy().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "Drawing".into()); + let picked = app.services.pick_save.as_ref().and_then(|pick| pick(&format!("{stem}.pdf"))); + if let Some(path) = picked { + match publish_params(app, &st.sheets, !st.separate, Some(&path)).and_then(|p| app.run("publish", p)) { + Ok(r) => { + let msg = r["message"].as_str().unwrap_or("").to_string(); + app.session.echo(msg); + close = true; + } + Err(e) => st.note = Some(e), + } + } + } + None => {} + } + if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) && st.dragging.is_none() { + *open = false; + } + if *open { + ctx.data_mut(|d| d.insert_temp(state_id(), st)); + } else { + // Opened again later: filled anew from the drawing then current. + ctx.data_mut(|d| d.remove::(state_id())); + } +} + +#[cfg(test)] +mod tests { + use super::{Sheet, move_sheet}; + + fn s(n: &str) -> Sheet { + Sheet { drawing: "A.dwg".into(), layout: n.into() } + } + + #[test] + fn sheets_move_to_a_slot() { + let mut v = vec![s("1"), s("2"), s("3"), s("4")]; + assert_eq!(move_sheet(&mut v, 3, 0), Some(0)); + assert_eq!(v.iter().map(|x| x.layout.as_str()).collect::>(), ["4", "1", "2", "3"]); + assert_eq!(move_sheet(&mut v, 0, 4), Some(3)); + assert_eq!(v.iter().map(|x| x.layout.as_str()).collect::>(), ["1", "2", "3", "4"]); + assert_eq!(move_sheet(&mut v, 1, 3), Some(2)); + assert_eq!(v.iter().map(|x| x.layout.as_str()).collect::>(), ["1", "3", "2", "4"]); + assert_eq!(move_sheet(&mut v, 9, 0), None); + } +} diff --git a/crates/ui-egui/src/blockmgr.rs b/crates/ui-egui/src/blockmgr.rs new file mode 100644 index 0000000000..612dbabcd9 --- /dev/null +++ b/crates/ui-egui/src/blockmgr.rs @@ -0,0 +1,378 @@ +//! The Block Manager: the drawing's blocks in a list beside a preview of the selected one, its +//! details and what can be done with it (insert, edit, create, rename, delete, write to a file). + +use std::sync::Arc; + +use cadcraft_doc::{Drawing, EntityKind}; +use cadcraft_geom::{Bounds2, Vec2}; +use egui::{Rect, Sense, Stroke, pos2, vec2}; +use serde_json::json; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The dialog's own state between frames. +#[derive(Clone, Default)] +struct State { + selected: Option, + filter: String, + /// The new name while renaming the selected block. + rename: Option, + /// The last message (a refused delete or rename). + note: Option, +} + +/// A block's preview, built once per block and drawing revision. +#[derive(Clone)] +struct Preview { + key: (String, u64), + list: Arc, + bounds: Bounds2, +} + +fn state_id() -> egui::Id { + egui::Id::new("cc_block_manager") +} + +/// The named blocks a user works with: not the generated (`*D12`) ones nor layout blocks. +pub fn names(d: &Drawing) -> Vec { + let mut v: Vec = d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect(); + v.sort_by_key(|n| n.to_lowercase()); + v +} + +/// How many block references to `name` the drawing holds (model, layouts and other blocks). +pub fn reference_count(d: &Drawing, name: &str) -> usize { + std::iter::once(&d.model) + .chain(d.layouts.iter().map(|l| &l.entities)) + .chain(d.blocks.values().map(|b| &b.entities)) + .flat_map(|s| s.iter()) + .filter(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(name))) + .count() +} + +/// Build the preview of block `name`: its objects as they draw, and their extents. +fn build(d: &Drawing, name: &str) -> Option<(cadcraft_render::DisplayList, Bounds2)> { + let b = d.block(name)?; + let mut bounds = Bounds2::EMPTY; + for e in b.entities.iter().take(200_000) { + let eb = cadcraft_doc::entity_bounds(d, e, 0); + if !eb.is_empty() && eb.width().is_finite() && eb.height().is_finite() { + bounds = bounds.union(&eb); + } + } + if bounds.is_empty() { + return Some((cadcraft_render::DisplayList::default(), bounds)); + } + let size = bounds.width().max(bounds.height()).max(1e-9); + let opts = cadcraft_render::Options { tolerance: size / 500.0, min_dash: size / 300.0, view_height: size, ..Default::default() }; + let list = cadcraft_render::build_entities(d, b.entities.iter().map(|e| &**e), &opts); + Some((list, bounds)) +} + +/// Draw a display list fitted into `r` on `bg` (a framed square of the canvas colour). +pub fn paint_list(p: &egui::Painter, r: Rect, list: &cadcraft_render::DisplayList, bounds: &Bounds2) { + let t = Tokens::get(); + p.rect_filled(r, 3.0, t.canvas); + let inner = r.shrink(10.0); + if !bounds.is_empty() { + let (w, h) = (bounds.width().max(1e-12), bounds.height().max(1e-12)); + let k = (f64::from(inner.width()) / w).min(f64::from(inner.height()) / h); + let c = bounds.center(); + let mid = inner.center(); + let at = |v: &Vec2| pos2(mid.x + ((v.x - c.x) * k) as f32, mid.y - ((v.y - c.y) * k) as f32); + let bg = cadcraft_color::Rgb(t.canvas.r(), t.canvas.g(), t.canvas.b()); + let clip = p.with_clip_rect(r.shrink(1.0)); + for prim in &list.prims { + let rgb = prim.display_rgb(bg); + let col = egui::Color32::from_rgb(rgb.0, rgb.1, rgb.2); + let pts = list.points(prim); + match prim.kind { + cadcraft_render::Kind::Polyline if pts.len() >= 2 => { + clip.add(egui::Shape::line(pts.iter().map(at).collect(), Stroke::new(1.0, col))); + } + cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => { + let fill = if prim.kind == cadcraft_render::Kind::Mask { t.canvas } else { col }; + let mut mesh = egui::Mesh::default(); + for tri in pts.chunks_exact(3) { + let base = u32::try_from(mesh.vertices.len()).unwrap_or(u32::MAX); + for v in tri { + mesh.colored_vertex(at(v), fill); + } + mesh.add_triangle(base, base + 1, base + 2); + } + clip.add(egui::Shape::mesh(mesh)); + } + cadcraft_render::Kind::Point => { + if let Some(v) = pts.first() { + clip.circle_filled(at(v), 1.2, col); + } + } + _ => {} + } + } + } + p.rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); +} + +/// The preview of `name`, from the cache when the drawing hasn't changed. +fn preview(app: &CadApp, ctx: &egui::Context, name: &str) -> Option { + let revision = app.session.state().map(|s| s.revision).unwrap_or(0); + let key = (name.to_string(), revision); + let id = egui::Id::new("cc_block_manager_preview"); + if let Some(p) = ctx.data(|d| d.get_temp::(id)).filter(|p| p.key == key) { + return Some(p); + } + let d = app.session.doc().ok()?; + let (list, bounds) = build(d, name)?; + let p = Preview { key, list: Arc::new(list), bounds }; + ctx.data_mut(|d| d.insert_temp(id, p.clone())); + Some(p) +} + +/// What a button asked for, done once the window is drawn. +enum Act { + Insert(String), + Edit(String), + Create, + Rename(String, String), + Delete(String), + Write(String), +} + +/// Format ▸ Blocks / the Blocks button: the Block Manager window. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); + let Ok(d) = app.session.doc() else { return }; + let all = names(d); + if st.selected.as_ref().is_some_and(|s| !all.iter().any(|n| n == s)) { + st.selected = None; + st.rename = None; + } + if st.selected.is_none() { + st.selected = all.first().cloned(); + } + let selected = st.selected.clone(); + let info = selected.as_deref().and_then(|n| { + let b = d.block(n)?; + Some((b.entities.len(), reference_count(d, n), b.base, b.annotative, b.description.clone(), b.xref_path.clone())) + }); + let pv = selected.as_deref().and_then(|n| preview(app, ctx, n)); + let can_write = app.services.pick_save.is_some(); + let mut act = None; + egui::Window::new(crate::tl!("Block Manager")) + .id(egui::Id::new("Blocks")) + .open(open) + .default_size(vec2(640.0, 440.0)) + .min_size(vec2(480.0, 320.0)) + .resizable(true) + .show(ctx, |ui| { + let t = Tokens::get(); + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Search blocks")).desired_width(200.0)); + ui.label(egui::RichText::new(format!("{} {}", all.len(), crate::tl!("blocks"))).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { + act = Some(Act::Create); + } + }); + }); + ui.add_space(4.0); + let avail = ui.available_size(); + let list_w = 230.0_f32.min(avail.x * 0.45); + let height = (avail.y - 4.0).max(200.0); + ui.horizontal_top(|ui| { + // The list of blocks. + ui.allocate_ui_with_layout(vec2(list_w, height), egui::Layout::top_down(egui::Align::LEFT), |ui| { + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(2.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("cc_block_list").auto_shrink([false, false]).max_height(height - 6.0).show(ui, |ui| { + ui.set_width(list_w - 8.0); + let filter = st.filter.trim().to_lowercase(); + let mut shown = 0; + for n in all.iter().filter(|n| filter.is_empty() || n.to_lowercase().contains(&filter)) { + shown += 1; + let on = selected.as_deref() == Some(n.as_str()); + let r = ui.selectable_label(on, n); + if r.clicked() { + st.selected = Some(n.clone()); + st.rename = None; + st.note = None; + } + if r.double_clicked() { + act = Some(Act::Insert(n.clone())); + } + r.on_hover_text(crate::tl!("Double-click to insert")); + } + if shown == 0 { + let msg = if all.is_empty() { + crate::tl!("No blocks defined in this drawing.") + } else { + crate::tl!("No blocks match the search.") + }; + ui.label(egui::RichText::new(msg).color(t.text_dim)); + } + }); + }); + }); + // Preview, details and actions of the selected block. + ui.vertical(|ui| { + let side = ui.available_width().min(height - 150.0).clamp(140.0, 320.0); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width().max(side), side), Sense::hover()); + match &pv { + Some(p) => paint_list(ui.painter(), r, &p.list, &p.bounds), + None => { + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("Preview"), crate::theme::small(), t.text_faint); + } + } + if pv.as_ref().is_some_and(|p| p.bounds.is_empty()) { + ui.painter().text( + r.center(), + egui::Align2::CENTER_CENTER, + crate::tl!("The block is empty"), + crate::theme::small(), + t.text_faint, + ); + } + ui.add_space(4.0); + let Some(name) = selected.clone() else { return }; + if let Some(mut new) = st.rename.take() { + let mut keep = true; + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut new).desired_width(160.0)); + if ui.button(crate::tl!("OK")).clicked() && !new.trim().is_empty() { + act = Some(Act::Rename(name.clone(), new.trim().to_string())); + } + if ui.button(crate::tl!("Cancel")).clicked() { + keep = false; + } + }); + if keep { + st.rename = Some(new); + } + } else { + ui.label(egui::RichText::new(&name).strong()); + } + if let Some((objects, refs, base, annotative, description, xref)) = &info { + egui::Grid::new("cc_block_info").num_columns(2).spacing(vec2(12.0, 2.0)).show(ui, |ui| { + ui.label(egui::RichText::new(crate::tl!("Objects")).color(t.text_dim)); + ui.label(objects.to_string()); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("References")).color(t.text_dim)); + ui.label(refs.to_string()); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("Base point")).color(t.text_dim)); + ui.label(format!("{:.4}, {:.4}", base.x, base.y)); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("Annotative")).color(t.text_dim)); + ui.label(if *annotative { crate::tl!("Yes") } else { crate::tl!("No") }); + ui.end_row(); + if let Some(path) = xref { + ui.label(egui::RichText::new(crate::tl!("External reference")).color(t.text_dim)); + ui.label(path); + ui.end_row(); + } + if !description.is_empty() { + ui.label(egui::RichText::new(crate::tl!("Description")).color(t.text_dim)); + ui.label(description); + ui.end_row(); + } + }); + } + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + if ui.button(crate::tl!("Insert")).clicked() { + act = Some(Act::Insert(name.clone())); + } + if ui.button(crate::tl!("Edit Block")).on_hover_text(crate::tl!("Open in the Block Editor")).clicked() { + act = Some(Act::Edit(name.clone())); + } + if ui.button(crate::tl!("Rename...")).clicked() { + st.rename = Some(name.clone()); + } + if ui.button(crate::tl!("Delete")).on_hover_text(crate::tl!("Delete a block that no object uses")).clicked() { + act = Some(Act::Delete(name.clone())); + } + if can_write + && ui.button(crate::tl!("Save to File...")).on_hover_text(crate::tl!("Write the block as a drawing (WBLOCK)")).clicked() + { + act = Some(Act::Write(name.clone())); + } + }); + if let Some(n) = &st.note { + ui.label(egui::RichText::new(n).color(t.text_dim)); + } + }); + }); + }); + match act { + Some(Act::Insert(n)) => { + *open = false; + crate::dialogs::insert_block(app, &n); + } + Some(Act::Edit(n)) => { + *open = false; + if let Err(e) = app.run("bedit", json!({ "name": n })) { + app.session.echo(e); + } + } + Some(Act::Create) => { + *open = false; + app.start("block"); + } + Some(Act::Rename(from, to)) => match app.run("rename", json!({ "table": "block", "from": from, "to": to })) { + Ok(_) => { + st.selected = Some(to); + st.rename = None; + st.note = None; + } + Err(e) => st.note = Some(e), + }, + Some(Act::Delete(n)) => { + let refs = app.session.doc().map(|d| reference_count(d, &n)).unwrap_or(0); + if refs > 0 { + st.note = Some(format!("{} ({refs})", crate::tl!("The block is in use and can't be deleted"))); + } else { + match app.run("purge", json!({ "type": "blocks", "names": n })) { + Ok(_) => { + st.selected = None; + st.note = None; + } + Err(e) => st.note = Some(e), + } + } + } + Some(Act::Write(n)) => { + if let Some(pick) = app.services.pick_save.as_ref() + && let Some(path) = pick(&format!("{n}.dwg")) + && let Err(e) = app.run("wblock", json!({ "path": path, "name": n })) + { + st.note = Some(e); + } + } + None => {} + } + ctx.data_mut(|d| d.insert_temp(state_id(), st)); +} + +#[cfg(test)] +mod tests { + use cadcraft_engine::Session; + use serde_json::json; + + #[test] + fn blocks_list_their_references_and_build_a_preview() { + let mut s = Session::new(); + let c = s.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); + let h = c["handle"].as_str().unwrap().to_string(); + s.execute("block", &json!({"name": "Bolt", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); + s.execute("insert", &json!({"name": "Bolt", "at": [5, 5]})).unwrap(); + s.execute("insert", &json!({"name": "Bolt", "at": [9, 5]})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(super::names(d), ["Bolt"]); + assert_eq!(super::reference_count(d, "bolt"), 2); + let (list, bounds) = super::build(d, "Bolt").unwrap(); + assert!(!list.prims.is_empty()); + assert!((bounds.width() - 4.0).abs() < 1e-6); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 15faadaf16..acbea01f89 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,8 +25,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "about" => about(ctx, &mut open), o if o == "toolbar" || o.starts_with("toolbar:") => crate::toolbar::dialog(app, ctx, o, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), + "publish" => crate::batchplot::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), - "blocks" => blocks(app, ctx, &mut open), + "blocks" => crate::blockmgr::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), @@ -375,28 +376,9 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -fn blocks(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { - let mut pick = None; - egui::Window::new(crate::tl!("Blocks")).id(egui::Id::new("Blocks")).open(open).default_size(vec2(320.0, 360.0)).show(ctx, |ui| { - let Ok(d) = app.session.doc() else { return }; - let names: Vec<&String> = d.blocks.keys().filter(|k| !k.starts_with('*')).collect(); - if names.is_empty() { - ui.label(crate::tl!("No blocks defined in this drawing.")); - } - for n in names { - if ui.button(n).on_hover_text(crate::tl!("Insert this block")).clicked() { - pick = Some(n.clone()); - } - } - }); - if let Some(n) = pick { - insert_block(app, &n); - } -} - /// Start INSERT with `name` already given at its block name prompt, so the next prompt asks for /// the insertion point. -fn insert_block(app: &mut CadApp, name: &str) { +pub(crate) fn insert_block(app: &mut CadApp, name: &str) { app.start("insert"); if app.session.running.as_ref().is_none_or(|r| r.id != "insert") { return; diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index acc7c2f79e..4fee0a2b67 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -31,11 +31,9 @@ pub fn route(app: &mut CadApp, id: &str) -> Result { } } "publish" => { - let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "PUBLISH", "publish {}") }; - match pick(&format!("{stem}.pdf")) { - Some(path) => app.run("publish", json!({ "path": path })), - None => Ok(Value::Null), - } + // The Batch Plot window: which sheets, in what order, into one file or several. + app.ui.dialog = Some("publish".into()); + Ok(Value::Null) } _ => { let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "EXPORT", r#"export {"format": "svg"}"#) }; @@ -53,6 +51,15 @@ fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result, + last_offset: egui::Vec2, +} + #[derive(Clone)] struct Preview { generation: u32, @@ -76,20 +83,33 @@ pub(crate) fn preview_plot(app: &mut CadApp, ctx: &egui::Context, params: Value, app.ui.dialog = Some("preview".into()); } +/// `img` made small enough for the graphics card's largest texture (egui refuses a larger one). +fn fit_texture(ctx: &egui::Context, img: image::RgbaImage) -> image::RgbaImage { + let max = u32::try_from(ctx.input(|i| i.max_texture_side)).unwrap_or(2048).max(256); + let (w, h) = (img.width(), img.height()); + if w <= max && h <= max { + return img; + } + let k = f64::from(max) / f64::from(w.max(h)); + let nw = ((f64::from(w) * k).floor() as u32).clamp(1, max); + let nh = ((f64::from(h) * k).floor() as u32).clamp(1, max); + image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle) +} + /// Render the plot preview of the current layout (or model), or of the Plot dialog's settings, /// as a texture. fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, String), String> { if let Some(f) = ctx.data(|d| d.get_temp::(egui::Id::new(FROM_PLOT))) { let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); + let img = fit_texture(ctx, image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8()); let size = [img.width() as usize, img.height() as usize]; let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); return Ok((tex, f.info)); } - let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?; + let r = app.session.execute("preview", &json!({ "width": 2400 })).map_err(|e| e.to_string())?; let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?; - let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8(); + let img = fit_texture(ctx, image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8()); let size = [img.width() as usize, img.height() as usize]; let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR); let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or("")); @@ -113,24 +133,116 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } }; let (mut close, mut print) = (false, false); - egui::Window::new("Plot Preview").open(open).collapsible(false).resizable(false).show(ctx, |ui| { - match &preview.shown { - Ok((tex, info)) => { - ui.label(info); - let size = tex.size_vec2(); - let k = (760.0 / size.x).min(540.0 / size.y).min(1.0); - ui.image((tex.id(), size * k)); - } - Err(e) => { - ui.label(e); + let view_id = id.with("view"); + let mut view = ctx.data(|d| d.get_temp::(view_id)).filter(|v| v.generation == generation).unwrap_or(View { + generation, + zoom: 1.0, + offset: None, + last_offset: egui::Vec2::ZERO, + }); + egui::Window::new(crate::tl!("Plot Preview")) + .id(egui::Id::new("Plot Preview")) + .open(open) + .collapsible(false) + .resizable(true) + .default_size(egui::vec2(820.0, 640.0)) + .min_size(egui::vec2(360.0, 300.0)) + .show(ctx, |ui| { + // Print, zoom in and out, fit, the zoom level and Close. + let mut zoom_by: Option = None; + ui.horizontal(|ui| { + print = ui.button(crate::tl!("Print...")).clicked(); + ui.separator(); + if crate::icons::button(ui, crate::icons::Icon::ZoomIn, 22.0, crate::tl!("Zoom In"), false).clicked() { + zoom_by = Some(1.25); + } + if crate::icons::button(ui, crate::icons::Icon::ZoomOut, 22.0, crate::tl!("Zoom Out"), false).clicked() { + zoom_by = Some(0.8); + } + if crate::icons::button(ui, crate::icons::Icon::ZoomExtents, 22.0, crate::tl!("Zoom to Fit"), false).clicked() { + view.zoom = 1.0; + view.offset = Some(egui::Vec2::ZERO); + } + ui.label(format!("{:.0}%", view.zoom * 100.0)); + ui.separator(); + close = ui.button(crate::tl!("Close")).clicked(); + if let Ok((_, info)) = &preview.shown { + ui.label(egui::RichText::new(info).weak()); + } + }); + ui.separator(); + match &preview.shown { + Ok((tex, _)) => { + let size = tex.size_vec2(); + let avail = ui.available_size(); + let fit = (avail.x / size.x).min(avail.y / size.y).max(1e-3); + let viewport = ui.available_rect_before_wrap(); + let wheel = ui.ctx().input(|i| { + if viewport.contains(i.pointer.hover_pos().unwrap_or_default()) { + i.smooth_scroll_delta.y + i.zoom_delta().ln() * 200.0 + } else { + 0.0 + } + }); + let pointer = ui.ctx().pointer_hover_pos().filter(|p| viewport.contains(*p)); + // The mouse wheel zooms about the cursor; the buttons about the middle. + let (factor, about) = match zoom_by { + Some(k) => (k, viewport.center()), + None if wheel.abs() > 0.0 && pointer.is_some() => ((wheel / 200.0).exp(), pointer.unwrap_or(viewport.center())), + None => (1.0, viewport.center()), + }; + let old_zoom = view.zoom; + view.zoom = (view.zoom * factor).clamp(1.0 / 4.0, 16.0); + let mut area = egui::ScrollArea::both() + .id_salt("cc_plot_preview_scroll") + .auto_shrink([false, false]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded) + .scroll_source(egui::scroll_area::ScrollSource { + scroll_bar: true, + drag: egui::scroll_area::DragScroll::Never, + mouse_wheel: false, + }); + if (view.zoom - old_zoom).abs() > f32::EPSILON { + // Keep the point under `about` where it is. + let ratio = view.zoom / old_zoom; + let rel = about - viewport.min; + let old = view.offset.unwrap_or(view.last_offset); + view.offset = Some(((old + rel) * ratio - rel).max(egui::Vec2::ZERO)); + } + if let Some(o) = view.offset.take() { + area = area.scroll_offset(o); + } + let shown = size * fit * view.zoom; + // Scroll bars that stay visible (not the thin floating ones) once the sheet is larger. + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + let mut pan = egui::Vec2::ZERO; + let out = area.show(ui, |ui| { + // Centred while smaller than the window. + let pad = ((ui.available_size() - shown) / 2.0).max(egui::Vec2::ZERO); + let (r, resp) = ui.allocate_exact_size(shown + pad * 2.0, egui::Sense::drag()); + let img = egui::Rect::from_min_size(r.min + pad, shown); + ui.painter().rect_filled(img.translate(egui::vec2(3.0, 3.0)), 0.0, egui::Color32::from_black_alpha(90)); + ui.painter().image(tex.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + if resp.hovered() || resp.dragged() { + ui.ctx().set_cursor_icon(if resp.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab }); + } + // Dragging the sheet moves it with the pointer. + if resp.dragged() { + pan = resp.drag_delta(); + } + }); + view.last_offset = out.state.offset; + if pan != egui::Vec2::ZERO { + view.offset = Some((out.state.offset - pan).max(egui::Vec2::ZERO)); + ui.ctx().request_repaint(); + } + } + Err(e) => { + ui.label(e); + } } - } - ui.add_space(4.0); - ui.horizontal(|ui| { - print = ui.button("Print...").clicked(); - close = ui.button("Close").clicked(); }); - }); + ctx.data_mut(|d| d.insert_temp(view_id, view)); if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { close = true; } @@ -187,8 +299,9 @@ mod tests { app.start("export"); app.cmdline("PUBLISH"); app.start("imp"); - assert_eq!(*asked.borrow(), ["Drawing1.svg", "Drawing1.pdf", "open"]); - assert!(app.ui.dialog.is_none()); + assert_eq!(*asked.borrow(), ["Drawing1.svg", "open"]); + assert_eq!(app.ui.dialog.as_deref(), Some("publish"), "PUBLISH opens the Batch Plot window"); + app.ui.dialog = None; app.cmdline("pre"); assert_eq!(app.ui.dialog.as_deref(), Some("preview")); app.ui.dialog = None; @@ -201,7 +314,7 @@ mod tests { let _ = app.run("publish", json!({ "layouts": [] })); let r = app.run("preview", json!({ "width": 64 })).unwrap(); assert!(r["data"].is_string()); - assert_eq!(asked.borrow().len(), 3, "JSON calls never open a file dialog"); + assert_eq!(asked.borrow().len(), 2, "JSON calls never open a file dialog"); assert!(app.ui.dialog.is_none(), "nor the preview window"); let e = app.run("share", json!({})).unwrap_err(); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1c94d73f6a..5189f27668 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1217,3 +1217,4 @@ menu Modify Modifikace Search for pattern Hledat vzor Not a number or distance: {text} Není číslo ani vzdálenost: {text} Query Texts Dotaz na texty + Block Manager Správce bloků diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a145f72912..3c095276ec 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1349,3 +1349,44 @@ Preview Предпросмотр Black Чёрная Light Blue Светло-голубая + Current Text Style Текущий текстовый стиль + Current Dimension Style Текущий размерный стиль + Current Linetype Текущий тип линий + Block Manager Диспетчер блоков + Search blocks Поиск блоков + blocks блоков + Create... Создать... + Make a block from objects (BLOCK) Создать блок из объектов (БЛОК) + Double-click to insert Двойной щелчок — вставить + No blocks match the search. Нет блоков, подходящих под поиск. + The block is empty Блок пуст + Objects Объекты + References Вхождения + Base point Базовая точка + External reference Внешняя ссылка + Edit Block Редактировать блок + Open in the Block Editor Открыть в редакторе блоков + Delete a block that no object uses Удалить блок, который не используется + Save to File... Сохранить в файл... + Write the block as a drawing (WBLOCK) Записать блок как отдельный чертёж (ПБЛОК) + The block is in use and can't be deleted Блок используется, удалить его нельзя + The drawing is closed Чертёж закрыт + closed закрыт + Batch Plot Пакетная печать + Sheets to plot, in order Листы для печати, по порядку + Duplicate Дублировать + No sheets. Add sheets below. Листов нет. Добавьте листы ниже. + Move to Top Переместить в самый верх + Move to Bottom Переместить в самый низ + Clear List Очистить список + Add sheets from Добавить листы из + Add All Добавить все + Add this sheet to the end of the list Добавить этот лист в конец списка + One PDF file with all sheets Один файл PDF со всеми листами + A separate PDF file for each sheet Отдельный файл PDF для каждого листа + Plot... Печать... + There is no file dialog here Здесь нет окна выбора файла + sheets листов + Zoom to Fit Показать целиком + Move Higher Переместить выше + Move Lower Переместить ниже diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 74eaacf223..b1a5b34e49 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -348,7 +348,7 @@ fn dialogs_render_in_ukrainian_and_keep_their_source_ids() { ("dsettings", "Налаштування креслення"), ("about", "Про CADCraft"), ("commands", "Довідник команд"), - ("blocks", "Блоки"), + ("blocks", "Диспетчер блоків"), ("layers", "Диспетчер властивостей шарів"), ("qselect", "Швидкий вибір"), ("parameters", "Диспетчер параметрів"), @@ -498,7 +498,7 @@ fn czech_dialogs_render_with_stable_ids() { ("dsettings", "Nastavení kreslení"), ("about", "O aplikaci CADCraft"), ("commands", "Přehled příkazů"), - ("blocks", "Bloky"), + ("blocks", "Správce bloků"), ("layers", "Správce vlastností hladin"), ("qselect", "Rychlý výběr"), ("parameters", "Správce parametrů"), diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6cfdb18d9d..074ed93a62 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1654,3 +1654,44 @@ No hatch patterns (.pat files) in this folder У цій теці немає зразків штрихування (файлів .pat) Black Чорна Light Blue Світло-блакитна + Current Text Style Поточний текстовий стиль + Current Dimension Style Поточний розмірний стиль + Current Linetype Поточний тип ліній + Block Manager Диспетчер блоків + Search blocks Пошук блоків + blocks блоків + Create... Створити... + Make a block from objects (BLOCK) Створити блок з об'єктів (БЛОК) + Double-click to insert Подвійне клацання — вставити + No blocks match the search. Немає блоків, що відповідають пошуку. + The block is empty Блок порожній + Objects Об'єкти + References Входження + Base point Базова точка + External reference Зовнішнє посилання + Edit Block Редагувати блок + Open in the Block Editor Відкрити в редакторі блоків + Delete a block that no object uses Видалити блок, який не використовується + Save to File... Зберегти у файл... + Write the block as a drawing (WBLOCK) Записати блок як окреме креслення (ПБЛОК) + The block is in use and can't be deleted Блок використовується, видалити його не можна + The drawing is closed Креслення закрите + closed закрите + Batch Plot Пакетний друк + Sheets to plot, in order Аркуші для друку, по порядку + Duplicate Дублювати + No sheets. Add sheets below. Аркушів немає. Додайте аркуші нижче. + Move to Top Перемістити на самий верх + Move to Bottom Перемістити в самий низ + Clear List Очистити список + Add sheets from Додати аркуші з + Add All Додати всі + Add this sheet to the end of the list Додати цей аркуш у кінець списку + One PDF file with all sheets Один файл PDF з усіма аркушами + A separate PDF file for each sheet Окремий файл PDF для кожного аркуша + Plot... Друк... + There is no file dialog here Тут немає вікна вибору файлу + sheets аркушів + Zoom to Fit Показати повністю + Move Higher Перемістити вище + Move Lower Перемістити нижче diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index f6388af996..101127c68d 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -144,6 +144,12 @@ pub enum Icon { PickAdd, SelectObjects, QuickSelect, + ZoomIn, + ZoomOut, + MoveTop, + MoveUp, + MoveDown, + MoveBottom, } struct Pen<'a> { @@ -247,8 +253,15 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.rect(8.0, 4.0, 8.0, 5.0, b); pen.rect(7.0, 13.0, 10.0, 7.0, b); if icon == SaveAs { - pen.la(15.0, 22.0, 22.0, 15.0); - pen.fill_c(15.0, 22.0, 1.2, a); + // A large pencil across the lower-right corner: body, ferrule line and a filled tip. + pen.p.add(egui::Shape::convex_polygon( + [(12.6, 19.4), (20.6, 11.4), (23.6, 14.4), (15.6, 22.4)].iter().map(|(x, y)| pen.at(*x, *y)).collect(), + t.panel, + Stroke::NONE, + )); + pen.poly(&[(12.6, 19.4), (20.6, 11.4), (23.6, 14.4), (15.6, 22.4)], true, a); + pen.la(19.0, 13.0, 22.0, 16.0); + pen.tri([(12.6, 19.4), (15.6, 22.4), (10.8, 24.0)], a); } } Undo => { @@ -280,12 +293,14 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { } Import | Export => { pen.poly(&[(5.0, 3.0), (14.0, 3.0), (18.0, 7.0), (18.0, 21.0), (5.0, 21.0)], true, b); + // A large, thick arrow: into the page for Import, out of it for Export. + let thick = Stroke::new(pen.w * 2.0, a); if icon == Import { - pen.la(1.0, 13.0, 11.0, 13.0); - pen.arrow_tip(12.0, 13.0, 1.0, 0.0, a); + pen.p.line_segment([pen.at(0.5, 13.0), pen.at(8.0, 13.0)], thick); + pen.big_arrow(14.5, 13.0, 1.0, 0.0, 7.0, 5.0, a); } else { - pen.la(11.0, 13.0, 21.0, 13.0); - pen.arrow_tip(23.0, 13.0, 1.0, 0.0, a); + pen.p.line_segment([pen.at(9.0, 13.0), pen.at(17.0, 13.0)], thick); + pen.big_arrow(24.0, 13.0, 1.0, 0.0, 7.0, 5.0, a); } } Attach => { @@ -833,6 +848,26 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.fill_rect(x, y, 8.0, 8.0, if x == 3.0 && y == 3.0 { a } else { b }); } } + ZoomIn | ZoomOut => { + pen.c(10.0, 10.0, 7.0, b); + p.line_segment([pen.at(15.0, 15.0), pen.at(21.5, 21.5)], Stroke::new(pen.w * 2.2, b)); + pen.la(6.5, 10.0, 13.5, 10.0); + if icon == ZoomIn { + pen.la(10.0, 6.5, 10.0, 13.5); + } + } + MoveTop | MoveBottom => { + // A bar at the end the arrow points to. + let (bar, tip, tail, dir) = if icon == MoveTop { (4.0, 7.0, 21.0, -1.0) } else { (20.0, 17.0, 3.0, 1.0) }; + p.line_segment([pen.at(5.0, bar), pen.at(19.0, bar)], Stroke::new(pen.w * 1.6, a)); + pen.l(12.0, tail, 12.0, tip - 5.0 * dir); + pen.big_arrow(12.0, tip, 0.0, dir, 6.0, 4.5, b); + } + MoveUp | MoveDown => { + let dir = if icon == MoveUp { -1.0 } else { 1.0 }; + pen.l(12.0, 12.0 - 8.0 * dir, 12.0, 12.0 + 2.0 * dir); + pen.big_arrow(12.0, 12.0 + 8.0 * dir, 0.0, dir, 7.0, 5.0, b); + } Close => { pen.l(6.0, 6.0, 18.0, 18.0); pen.l(18.0, 6.0, 6.0, 18.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4cb638bbfd..376e884fe2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,7 +10,9 @@ pub mod animation; pub mod autosave; +pub mod batchplot; pub mod bedit; +pub mod blockmgr; pub mod canvas; pub mod chrome; pub mod clipboard; diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 3ef99d4839..88daa03b49 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -131,7 +131,10 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { let code = usize::from(mt.attach.clamp(1, 9) - 1); let (col, row) = ((code % 3) as f64, (code / 3) as f64); let ww = f64::from(width) / scale; - let corner = cadcraft_geom::Vec2::new(mt.insert.x - col * ww / 2.0, mt.insert.y + row * base_h * 2.0); + // One line of text: the editor's line sits on the text's own line (its top a little above the + // cap height), so what is typed shows where the text goes. + let rise = if line { 0.75 } else { 2.0 }; + let corner = cadcraft_geom::Vec2::new(mt.insert.x - col * ww / 2.0, mt.insert.y + row * base_h * rise); let at = app.canvas.xf.map_or(rect.center(), |x| x.to_screen(corner)); let max_x = (rect.right() - width - 8.0).max(rect.left()); let pos = pos2(at.x.clamp(rect.left(), max_x), at.y.clamp(rect.top() + st.top, (rect.bottom() - 120.0).max(rect.top() + st.top))); @@ -201,7 +204,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { let r = app.session.input(cadcraft_engine::Input::Text(contents)); report(app, r); } - if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") { + // MTEXT ends its text with Enter; MLEADER takes Enter for "no text" when nothing was typed. + let still_asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); + if app.session.running.as_ref().is_some_and(|r| r.id == "mtext") || (st.fmt.is_empty() && still_asking) { let _ = app.session.input(cadcraft_engine::Input::Enter); } } diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index c99c06e4b3..981c92ea45 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1160,11 +1160,26 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); group(ui, "Leaders"); - let (straight, spline) = (crate::tl!("Straight").to_string(), crate::tl!("Spline").to_string()); + let (straight, spline, none) = (crate::tl!("Straight").to_string(), crate::tl!("Spline").to_string(), crate::tl!("None").to_string()); prop_row(ui, "Leader type", |ui| { - let cur = if ml.spline { &spline } else { &straight }; - if let Some(n) = pick_menu(ui, cur, [straight.clone(), spline.clone()]) { - set = Some(json!({ "handles": ids, "leaderType": if n == spline { "spline" } else { "straight" } })); + let cur = if ml.leaderless() { + &none + } else if ml.spline { + &spline + } else { + &straight + }; + // None only hides the leader lines, so a multileader without any can't get them back. + let choices = if ml.leaders.is_empty() { vec![none.clone()] } else { vec![straight.clone(), spline.clone(), none.clone()] }; + if let Some(n) = pick_menu(ui, cur, choices) { + let v = if n == spline { + "spline" + } else if n == none { + "none" + } else { + "straight" + }; + set = Some(json!({ "handles": ids, "leaderType": v })); } }); // The arrowhead: built-in ones and the drawing's arrowhead blocks, as for dimensions. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 87a854085a..57397df9e9 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -143,9 +143,24 @@ impl Bar { "fillet", "erase", ], - Bar::Layers => { - &["ui.dialog.layers", LAYER_COMBO, "|", "laymcur", "laymch", "layerp", "|", "layiso", "layoff", "layfrz", "laylck", "layulk"] - } + Bar::Layers => &[ + "ui.dialog.layers", + LAYER_COMBO, + "|", + "laymcur", + "laymch", + "layerp", + "|", + "layiso", + "layoff", + "layfrz", + "laylck", + "layulk", + "|", + TEXTSTYLE_COMBO, + DIMSTYLE_COMBO, + LINETYPE_COMBO, + ], }; ids.iter().map(|s| s.to_string()).collect() } @@ -185,8 +200,26 @@ pub fn state(ui: &crate::UiState, bar: Bar) -> BarState { /// The current-layer drop-down, an item only the bars hold (not a command). pub const LAYER_COMBO: &str = "layer.combo"; +/// The current text style, dimension style and linetype drop-downs. +pub const TEXTSTYLE_COMBO: &str = "textstyle.combo"; +pub const DIMSTYLE_COMBO: &str = "dimstyle.combo"; +pub const LINETYPE_COMBO: &str = "linetype.combo"; /// Width of the current-layer drop-down in a row. const COMBO_W: f32 = 220.0; +/// Width of the style and linetype drop-downs in a row. +const STYLE_COMBO_W: f32 = 160.0; +/// Most height a drop-down's list takes before it scrolls. +const COMBO_LIST_H: f32 = 320.0; + +/// Whether `command` is one of the bars' drop-downs (not a command). +pub fn is_combo(command: &str) -> bool { + [LAYER_COMBO, TEXTSTYLE_COMBO, DIMSTYLE_COMBO, LINETYPE_COMBO].contains(&command) +} + +/// A drop-down's width in a row. +fn combo_width(command: &str) -> f32 { + if command == LAYER_COMBO { COMBO_W } else { STYLE_COMBO_W } +} /// The category of the layer tools. const LAYERS_CATEGORY: &str = "Layers"; /// The layer tools (the Layers palette's row) and the current layer. @@ -201,6 +234,9 @@ const LAYER_TOOLS: &[(Icon, &str, &str)] = &[ (Icon::LayerFreeze, "layfrz", "Freeze Layer"), (Icon::LayerLock, "laylck", "Lock Layer"), (Icon::Unlock, "layulk", "Unlock Layer"), + (Icon::Text, TEXTSTYLE_COMBO, "Current Text Style"), + (Icon::DimLinear, DIMSTYLE_COMBO, "Current Dimension Style"), + (Icon::Line, LINETYPE_COMBO, "Current Linetype"), ]; /// The default bar: file, undo, output, exchange, navigation, palettes, inquiry and help groups. @@ -374,7 +410,7 @@ pub fn add_item(items: &mut Vec, command: &str, index: Option) -> pub fn tooltip(ui: &mut egui::Ui, tool: &Tool, mac: bool) { ui.set_max_width(280.0); ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); - if !tool.command.starts_with("ui.") && tool.command != LAYER_COMBO { + if !tool.command.starts_with("ui.") && !is_combo(tool.command) { let name = tool.command.split('.').next().unwrap_or(tool.command).to_ascii_uppercase(); let mut line = format!("{} {name}", crate::tl!("Command:")); if let Some(alias) = cadcraft_engine::find_command(tool.command).and_then(|c| c.aliases.first()) { @@ -413,6 +449,8 @@ enum Action { AppCommand(&'static str), SetLayer(String), LayerToggle(String, &'static str, bool), + /// A style or linetype drop-down's choice: the drop-down and the name. + SetCurrent(&'static str, String), } /// The bar's right-click menu; `item` is the button it was opened on. @@ -511,6 +549,62 @@ fn layer_rows(app: &CadApp) -> Option<(String, Vec)> Some((cur, d.layers.iter().map(|l| (l.name.clone(), l.on, l.frozen, l.locked, l.color)).collect())) } +/// The current name and every name of a style or linetype drop-down. +fn combo_names(app: &CadApp, combo: &str) -> Option<(String, Vec)> { + let d = app.session.doc().ok()?; + Some(match combo { + TEXTSTYLE_COMBO => (d.header.str("TEXTSTYLE", "Standard").to_string(), d.text_styles.iter().map(|s| s.name.clone()).collect()), + DIMSTYLE_COMBO => (d.header.str("DIMSTYLE", "Standard").to_string(), d.dim_styles.iter().map(|s| s.name.clone()).collect()), + LINETYPE_COMBO => { + let mut names = vec!["ByLayer".to_string(), "ByBlock".to_string()]; + for l in &d.linetypes { + if !names.iter().any(|n| n.eq_ignore_ascii_case(&l.name)) { + names.push(l.name.clone()); + } + } + if !names.iter().any(|n| n.eq_ignore_ascii_case("Continuous")) { + names.insert(2, "Continuous".into()); + } + (d.header.str("CELTYPE", "ByLayer").to_string(), names) + } + _ => return None, + }) +} + +/// A drop-down's list of names: picking one makes it current. It scrolls when long. +fn name_list(ui: &mut egui::Ui, salt: &str, current: &str, names: &[String]) -> Option { + let mut picked = None; + // A scroll bar that is always there once the list is longer than the drop-down. + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt(("cc_combo_list", salt)).max_height(COMBO_LIST_H).auto_shrink([false, true]).show(ui, |ui| { + for n in names { + let shown = if ["ByLayer", "ByBlock"].contains(&n.as_str()) { crate::i18n::t(n).to_string() } else { n.clone() }; + if ui.selectable_label(n.eq_ignore_ascii_case(current), shown).clicked() { + picked = Some(n.clone()); + } + } + }); + picked +} + +/// The current layer list in a drop-down, scrolling when there are many layers. +fn layer_popup(ui: &mut egui::Ui, salt: &str, cur: &str, rows: &[crate::palettes::LayerRow], action: &mut Option) -> bool { + let mut set_current = None; + let mut toggle = None; + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt(("cc_layer_list", salt)).max_height(COMBO_LIST_H).auto_shrink([false, true]).show(ui, |ui| { + crate::palettes::layer_list(ui, rows, cur, &mut set_current, &mut toggle); + }); + if let Some(name) = set_current { + *action = Some(Action::SetLayer(name)); + return true; + } + if let Some((name, key, on)) = toggle { + *action = Some(Action::LayerToggle(name, key, on)); + } + false +} + /// Lay out and run `bar` in `area`: a row, or a column when `vertical`. fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: Bar) { let t = Tokens::get(); @@ -600,8 +694,8 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B let extent = |item: &String| { if item == SEPARATOR { SEP - } else if item == LAYER_COMBO && !vertical { - COMBO_W + GAP + } else if is_combo(item) && !vertical { + combo_width(item) + GAP } else { BUTTON + GAP } @@ -641,12 +735,15 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B continue; } let Some(tool) = find(item) else { continue }; - let combo = tool.command == LAYER_COMBO; - let len = if combo && !vertical { COMBO_W } else { BUTTON }; + let combo = is_combo(tool.command); + let names = if combo && tool.command != LAYER_COMBO { combo_names(app, tool.command) } else { None }; + let len = if combo && !vertical { combo_width(tool.command) } else { BUTTON }; let br = slot(pos, len, if combo && !vertical { 24.0 } else { BUTTON }); let resp = ui.interact(br, id.with(("tb", tool.command)), Sense::click() | Sense::DRAG); - if combo { + if tool.command == LAYER_COMBO { paint_combo(ui, br, resp.hovered() || resp.dragged(), vertical, layers.as_ref()); + } else if combo { + paint_name_combo(ui, br, resp.hovered() || resp.dragged(), vertical, tool.icon, names.as_ref().map(|(c, _)| c.as_str())); } else { if resp.hovered() || resp.dragged() { ui.painter().rect_filled(br, 3.0, t.control_hover.gamma_multiply(0.6)); @@ -656,32 +753,46 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B icons::describe_control(ui, &resp, &tool.accessible_label(mac), None, false); let resp = if dragging { resp - } else if combo { + } else if tool.command == LAYER_COMBO { let current = layers.as_ref().map(|(cur, _)| cur.clone()).unwrap_or_default(); resp.on_hover_ui(|ui| { ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); ui.label(RichText::new(format!("{} {current}", crate::tl!("Current layer:"))).weak()); }) + } else if combo { + let current = names.as_ref().map(|(c, _)| c.clone()).unwrap_or_default(); + resp.on_hover_ui(|ui| { + ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); + ui.label(RichText::new(current).weak()); + }) } else { resp.on_hover_ui(|ui| tooltip(ui, &tool, mac)) }; resp.context_menu(|ui| options_menu(ui, bar, shown_bars, Some(index), dock, &mut action)); - if combo { + let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; + if tool.command == LAYER_COMBO { if let Some((cur, rows)) = &layers { - let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; egui::Popup::from_toggle_button_response(&resp) .align(align) .width(COMBO_W.max(240.0)) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { - let mut set_current = None; - let mut toggle = None; - crate::palettes::layer_list(ui, rows, cur, &mut set_current, &mut toggle); - if let Some(name) = set_current { - action = Some(Action::SetLayer(name)); + if layer_popup(ui, "bar", cur, rows, &mut action) { + ui.close(); + } + }); + } + } else if combo { + if let Some((cur, list)) = &names { + let command = tool.command; + egui::Popup::from_toggle_button_response(&resp) + .align(align) + .width(STYLE_COMBO_W.max(200.0)) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + if let Some(n) = name_list(ui, command, cur, list) { + action = Some(Action::SetCurrent(command, n)); ui.close(); - } else if let Some((name, key, on)) = toggle { - action = Some(Action::LayerToggle(name, key, on)); } }); } @@ -759,16 +870,21 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B let Some(tool) = find(item) else { continue }; if tool.command == LAYER_COMBO { // The drop-down does not fit a menu row: its layers are listed in place. - if let Some((cur, rows)) = &layers { - let mut set_current = None; - let mut toggle = None; - crate::palettes::layer_list(ui, rows, cur, &mut set_current, &mut toggle); - if let Some(name) = set_current { - action = Some(Action::SetLayer(name)); + if let Some((cur, rows)) = &layers + && layer_popup(ui, "more", cur, rows, &mut action) + { + ui.close(); + } + continue; + } + if is_combo(tool.command) { + if let Some((cur, list)) = combo_names(app, tool.command) { + ui.label(RichText::new(crate::i18n::t(tool.label)).weak()); + if let Some(n) = name_list(ui, tool.command, &cur, &list) { + action = Some(Action::SetCurrent(tool.command, n)); ui.close(); - } else if let Some((name, key, on)) = toggle { - action = Some(Action::LayerToggle(name, key, on)); } + ui.separator(); } continue; } @@ -816,6 +932,16 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B Some(Action::LayerToggle(name, key, on)) => { let _ = app.run("layer.set", json!({ "name": name, key: on })); } + Some(Action::SetCurrent(combo, name)) => { + let r = match combo { + TEXTSTYLE_COMBO => app.run("style.current", json!({ "name": name })), + DIMSTYLE_COMBO => app.run("dimstyle.current", json!({ "name": name })), + _ => app.run("linetype", json!({ "current": name })), + }; + if let Err(e) = r { + app.session.echo(e); + } + } None => {} } } @@ -873,17 +999,14 @@ fn app_button(ui: &mut egui::Ui, rect: Rect, id: egui::Id, vertical: bool) -> bo let align = if vertical { egui::RectAlign::RIGHT_START } else { egui::RectAlign::BOTTOM_START }; let mut picked = None; egui::Popup::menu(&resp).align(align).show(|ui| { - ui.set_min_width(200.0); + ui.set_min_width(260.0); + ui.spacing_mut().item_spacing.y = 2.0; for (command, label) in APP_MENU { if *command == SEPARATOR { ui.separator(); continue; } - let mut button = egui::Button::new(crate::i18n::t(label)); - if let Some(sc) = cadcraft_engine::find_command(command).and_then(|c| c.shortcut) { - button = button.shortcut_text(crate::menus::shortcut_label(sc, ui.ctx().os().is_mac())); - } - let r = ui.add(button); + let r = app_menu_row(ui, command, label); crate::control::record_widget(ui, &r, label, "button", None); if r.clicked() { picked = Some(*command); @@ -898,6 +1021,45 @@ fn app_button(ui: &mut egui::Ui, rect: Rect, id: egui::Id, vertical: bool) -> bo false } +/// The icon beside an application-menu command. +pub fn app_menu_icon(command: &str) -> Icon { + match command { + "new" => Icon::New, + "open" => Icon::Open, + "qsave" => Icon::Save, + "saveas" => Icon::SaveAs, + "import" => Icon::Import, + "export" => Icon::Export, + "plot" => Icon::Plot, + "publish" => Icon::Publish, + "close" => Icon::Close, + _ => Icon::Gear, + } +} + +/// One row of the application menu: a large icon, the label in a larger font and the shortcut on +/// the right, 36 points tall. +fn app_menu_row(ui: &mut egui::Ui, command: &str, label: &str) -> egui::Response { + let t = Tokens::get(); + let width = ui.available_width().max(260.0); + let (rect, resp) = ui.allocate_exact_size(vec2(width, 36.0), Sense::click()); + let text = crate::i18n::t(label); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, text.to_string())); + if resp.hovered() { + ui.painter().rect_filled(rect, 3.0, t.control_hover); + } + let icon = Rect::from_center_size(pos2(rect.left() + 22.0, rect.center().y), vec2(28.0, 28.0)); + icons::paint(ui.painter(), icon, app_menu_icon(command), false); + let font = egui::FontId::proportional(crate::theme::body().size + 3.0); + let text_color = if resp.hovered() { ui.visuals().widgets.hovered.fg_stroke.color } else { t.text }; + ui.painter().text(pos2(rect.left() + 46.0, rect.center().y), egui::Align2::LEFT_CENTER, text, font, text_color); + if let Some(sc) = cadcraft_engine::find_command(command).and_then(|c| c.shortcut) { + let sc = crate::menus::shortcut_label(sc, ui.ctx().os().is_mac()); + ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, sc, crate::theme::body(), t.text_dim); + } + resp +} + /// Run a bar's tool: layer tools act at once (as in the Layers palette), the others start like a /// typed command. fn run_tool(app: &mut CadApp, command: &'static str) { @@ -939,6 +1101,27 @@ fn paint_combo(ui: &egui::Ui, rect: Rect, hovered: bool, vertical: bool, layers: icons::paint(p, Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::ChevronDown, false); } +/// A style or linetype drop-down: its icon and the current name in a row, the icon in a column. +fn paint_name_combo(ui: &egui::Ui, rect: Rect, hovered: bool, vertical: bool, icon: Icon, current: Option<&str>) { + let t = Tokens::get(); + let p = ui.painter(); + if vertical { + if hovered { + p.rect_filled(rect, 3.0, t.control_hover.gamma_multiply(0.6)); + } + icons::paint(p, rect.shrink(4.0), icon, false); + return; + } + p.rect_filled(rect, 3.0, if hovered { t.control_hover } else { t.control }); + icons::paint(p, Rect::from_min_size(pos2(rect.left() + 4.0, rect.center().y - 8.0), vec2(16.0, 16.0)), icon, false); + if let Some(name) = current { + let shown = if ["ByLayer", "ByBlock"].contains(&name) { crate::i18n::t(name).to_string() } else { name.to_string() }; + let text_rect = Rect::from_min_max(pos2(rect.left() + 24.0, rect.top()), pos2(rect.right() - 22.0, rect.bottom())); + p.with_clip_rect(text_rect).text(pos2(text_rect.left(), rect.center().y), egui::Align2::LEFT_CENTER, shown, crate::theme::body(), t.text); + } + icons::paint(p, Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::ChevronDown, false); +} + /// Selection and search of the Customize Tool Bar dialog. #[derive(Clone, Default)] struct DialogState { From b935527b8665e4696647e435066b4ed460d5c185 Mon Sep 17 00:00:00 2001 From: cadcraft Date: Thu, 22 Oct 2026 00:08:15 +0300 Subject: [PATCH 03/23] Text style in Properties (multi-select); arrowhead pictures in arrow lists; multileader text grip with Move with Leader / Move Text Only / Reset; PDF page size from the layout's paper units (lineweights no longer shrink); AutoCAD .ctb/.stb plot style tables read and found automatically; new Zoom to Fit, gear, Undo/Redo icons; Text/Dimension Style and Options tool bar buttons; Block Manager as a right panel or window, opened by INSERT Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 56 +++ apps/cadcraft-cli/src/main.rs | 1 + apps/cadcraft/src/main.rs | 1 + crates/doc/src/entity.rs | 65 +++- crates/engine/src/cmd/file.rs | 110 ++++++ crates/engine/src/cmd/layout/plotstyle.rs | 16 +- crates/engine/src/cmd/props.rs | 19 +- crates/engine/src/grips.rs | 20 +- crates/engine/tests/text_editor_on_create.rs | 24 ++ crates/io/src/lib.rs | 1 + crates/io/src/pdf.rs | 5 +- crates/io/src/pia.rs | 234 +++++++++++ crates/io/tests/tables_objects_roundtrip.rs | 23 ++ crates/render/src/lib.rs | 10 +- crates/render/src/paper.rs | 17 + crates/ui-egui/src/blockmgr.rs | 388 ++++++++++++------- crates/ui-egui/src/dialogs.rs | 5 +- crates/ui-egui/src/dimstyles.rs | 69 +++- crates/ui-egui/src/docking.rs | 9 +- crates/ui-egui/src/exchange.rs | 2 +- crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/icons.rs | 83 +++- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus.rs | 5 + crates/ui-egui/src/palettes.rs | 28 ++ crates/ui-egui/src/toolbar.rs | 7 + 27 files changed, 1035 insertions(+), 176 deletions(-) create mode 100644 crates/io/src/pia.rs diff --git a/WHATS_NEW.md b/WHATS_NEW.md index db3a39dad8..ce448440fd 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,62 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 22.10.2026 (0.9.0-b12) + +### Русский + +**Свойства текста и выносок** +- В палитре «Свойства» у текста, многострочного текста и мультивыносок появилась строка «Стиль» (текстовый стиль). Она работает и для нескольких выбранных объектов сразу. Если стили разные, показывается «*РАЗНЫЕ*». +- В списках стрелок (у мультивыносок в «Свойствах» и в редакторе размерного стиля) рядом с каждой стрелкой нарисован её вид, в том числе у пользовательских стрелок-блоков. + +**Ручка текста мультивыноски** +- У текста мультивыноски появилась своя ручка. Её меню: «Переместить с выноской», «Переместить только текст», «Восстановить положение текста». +- «Переместить с выноской» ставит текст в указанную точку, полочка встаёт рядом с текстом, а выноска тянется к ней от своей последней точки. +- «Переместить только текст» двигает один текст. «Восстановить положение текста» возвращает его к полочке. + +**Печать: толщина линий** +- Найдена причина слишком тонких линий. У листов, настроенных в миллиметрах внутри дюймового чертежа (как в «אריה צוק»), PDF получался в 25,4 раза больше листа: A3 был 10,7 × 7,5 м. При печати такой страницы на A3 всё уменьшалось в 25,4 раза, вместе с толщиной линий. Теперь страница PDF имеет размер листа, и толщины линий печатаются как задано. +- Программа читает таблицы стилей печати AutoCAD (.ctb и .stb): цвета, толщины линий, оттенки серого, интенсивность. Если лист ссылается на таблицу, которой нет в программе (у «אריה צוק» это SIVAN.ctb), CADCraft ищет файл рядом с чертежом и в папках стилей печати AutoCAD этого пользователя. Если файл не найден, в командной строке появляется сообщение, и лист печатается с цветами и толщинами самих объектов. Файл .ctb также можно загрузить вручную в «Диспетчере стилей печати». + +**Значки** +- «Показать целиком» в предварительном просмотре: четыре прямых угла вокруг прямоугольника. +- «Параметры»: шестерня с зубцами. +- «Отменить» и «Повторить»: толще дуга и крупнее стрелка. +- На панель инструментов можно добавить кнопки «Текстовый стиль», «Размерный стиль» и «Параметры» («Настроить панель инструментов», раздел «Стандартный»). + +**Диспетчер блоков** +- Кнопка «Вставить блок» (и команда ВСТАВИТЬ / INSERT) открывает диспетчер блоков панелью, закреплённой справа, рядом со «Слоями» и «Свойствами». +- Значок в правом верхнем углу превращает панель в отдельное окно, а в окне — обратно в панель. Программа запоминает, как диспетчер открывался в последний раз. +- Команда -ВСТАВИТЬ (-INSERT) по-прежнему спрашивает имя блока в командной строке. + +### English + +**Text and leader properties** +- The Properties palette has a Style row (text style) for text, multiline text and multileaders. It works for several selected objects at once and shows *VARIES* when their styles differ. +- The arrowhead lists (multileaders in Properties, the dimension style editor) show a picture of each arrowhead, user arrowhead blocks included. + +**The multileader text grip** +- Multileader text has its own grip, with Move with Leader, Move Text Only and Reset Text Position. +- Move with Leader puts the text at the picked point; the landing goes beside the text and the leader runs to it from its last point. +- Move Text Only moves the text alone; Reset Text Position puts it back beside the landing. + +**Printing: lineweights** +- Found why lines printed too thin: a layout set up in millimetres in an inch drawing (as in "אריה צוק") produced a PDF page 25.4 times the sheet (A3 came out 10.7 × 7.5 m), so printing it on A3 shrank everything, lineweights included, 25.4 times. The PDF page is now the size of the sheet and lineweights print as set. +- AutoCAD plot style tables (.ctb and .stb) are read: colours, lineweights, grayscale and screening. When a layout names a table CADCraft doesn't have (SIVAN.ctb for "אריה צוק"), it looks next to the drawing and in this user's AutoCAD plot style folders. If it isn't found, the command line says so and the layout plots with the objects' own colours and lineweights. A .ctb file can also be loaded in the Plot Style Manager. + +**Icons** +- Zoom to Fit in Plot Preview: four right-angle corners around a rectangle. +- Options: a gear with teeth. +- Undo and Redo: a thicker arc and a larger arrowhead. +- Text Style, Dimension Style and Options buttons can be added to the Tool Bar (Customize Tool Bar, Standard section). + +**Block Manager** +- The Insert Block button (and INSERT typed) opens the Block Manager as a panel pinned on the right, beside Layers and Properties. +- The icon at its top right turns the panel into a window, and the window back into a panel. The last choice is remembered. +- -INSERT still asks for the block name on the command line. + +--- + ## 21.10.2026 (0.9.0-b11) ### Русский diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 7fff9b5d0f..550d550e79 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -169,6 +169,7 @@ fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_plot_style_reader(cadcraft_io::pia::read); cadcraft_engine::cmd::file::set_plot_book(|items, opts| cadcraft_io::plotter::plot_book(items, opts).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 3d54e72b07..c7976732fb 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -116,6 +116,7 @@ pub fn install_io() { write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()), plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); + cadcraft_engine::cmd::file::set_plot_style_reader(cadcraft_io::pia::read); cadcraft_engine::cmd::file::set_plot_book(|items, opts| cadcraft_io::plotter::plot_book(items, opts).map_err(|e| e.to_string())); cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 060de2e857..df9ad57ee0 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -728,6 +728,62 @@ pub struct MLeader { } impl MLeader { + /// The grip index of the text (after the leader points and the landing), when it has text. + pub fn text_grip(&self) -> Option { + self.text.as_ref().map(|_| self.leaders.iter().map(Vec::len).sum::() + 1) + } + + /// The gap between the end of the landing and the text, as placed now (never negative). + fn text_gap(&self) -> f64 { + self.text.as_ref().map_or(0.0, |t| ((t.insert.x - self.landing.x).abs() - self.dogleg).max(0.0)) + } + + /// The side of the landing the text is on: 1 to the right, -1 to the left. + fn text_side(&self) -> f64 { + match &self.text { + Some(t) if t.insert.x < self.landing.x => -1.0, + _ => 1.0, + } + } + + /// Move with Leader: the text goes to `to` and the landing follows it (next to the text, + /// at its height), so the leader runs from its last point to the new landing. + pub fn move_with_leader(&mut self, to: Vec2) { + let gap = self.text_gap(); + let last = self.leaders.iter().filter_map(|l| l.last()).map(|v| v.xy()).next().unwrap_or(self.landing.xy()); + let side = if to.x >= last.x { 1.0 } else { -1.0 }; + let old = self.landing.xy(); + self.landing.x = to.x - side * (self.dogleg + gap); + self.landing.y = to.y; + if let Some(t) = &mut self.text { + t.insert.x = to.x; + t.insert.y = to.y; + // Attached at its left edge on the right of the landing, its right edge on the left. + let row = (t.attach.clamp(1, 9) - 1) / 3; + t.attach = row * 3 + if side > 0.0 { 1 } else { 3 }; + } + if let Some(b) = &mut self.block { + let d = self.landing.xy() - old; + b.insert.x += d.x; + b.insert.y += d.y; + } + } + + /// Reset Text Position: the text back beside the landing, on the side it is on. + pub fn reset_text(&mut self) { + let side = self.text_side(); + let (lx, ly) = (self.landing.x, self.landing.y); + let dogleg = self.dogleg; + if let Some(t) = &mut self.text { + // The usual landing gap: half the text height. + let gap = t.height.abs() * 0.5; + t.insert.x = lx + side * (dogleg + gap); + t.insert.y = ly; + let row = (t.attach.clamp(1, 9) - 1) / 3; + t.attach = row * 3 + if side > 0.0 { 1 } else { 3 }; + } + } + /// It draws no leader line (leader type None). pub fn leaderless(&self) -> bool { self.no_leader || self.leaders.is_empty() @@ -1458,7 +1514,14 @@ impl EntityKind { EntityKind::Dimension(d) => vec![d.p13.xy(), d.p14.xy(), d.defpt.xy(), d.text_mid.xy()], EntityKind::MLine(m) => m.points(), EntityKind::Leader(l) => l.vertices.iter().map(|v| v.xy()).collect(), - EntityKind::MLeader(m) => m.leaders.iter().flat_map(|l| l.iter().map(|v| v.xy())).chain(std::iter::once(m.landing.xy())).collect(), + // Leader points, the landing, then the text. + EntityKind::MLeader(m) => m + .leaders + .iter() + .flat_map(|l| l.iter().map(|v| v.xy())) + .chain(std::iter::once(m.landing.xy())) + .chain(m.text.as_ref().map(|t| t.insert.xy())) + .collect(), EntityKind::Hatch(h) => { let b = Bounds2::from_points(h.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); vec![b.center()] diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index a66ca97a2e..20167175d8 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -36,6 +36,68 @@ pub type PlotBookHook = fn(&[(&Drawing, cadcraft_doc::Space)], &Value) -> std::r static PLOT_BOOK: OnceLock = OnceLock::new(); +/// Read an AutoCAD plot style table file (`.ctb`/`.stb` bytes, the file name) into a table +/// (installed by the app; the io layer reads the format). +pub type PlotStyleReader = fn(&[u8], &str) -> std::result::Result; + +static PLOT_STYLE_READER: OnceLock = OnceLock::new(); + +pub fn set_plot_style_reader(h: PlotStyleReader) { + let _ = PLOT_STYLE_READER.set(h); +} +pub fn plot_style_reader() -> Option { + PLOT_STYLE_READER.get().copied() +} + +/// Whether `bytes` are an AutoCAD plot style table file. +pub fn is_pia(bytes: &[u8]) -> bool { + bytes.starts_with(b"PIAFILEVERSION") +} + +/// The folders a missing plot style table is looked for in: `extra` (the drawing's folder), then +/// AutoCAD's plot style folders of this user (Windows: under `%APPDATA%\Autodesk`). +#[cfg(not(target_arch = "wasm32"))] +fn plot_style_dirs(extra: Vec) -> Vec { + let mut dirs = extra; + if let Some(appdata) = std::env::var_os("APPDATA") { + // Autodesk\\\\Plotters\Plot Styles + let list = |p: &std::path::Path| -> Vec { + std::fs::read_dir(p).map(|r| r.flatten().map(|e| e.path()).filter(|p| p.is_dir()).take(64).collect()).unwrap_or_default() + }; + for product in list(&std::path::Path::new(&appdata).join("Autodesk")) { + for release in list(&product) { + for lang in list(&release) { + let ps = lang.join("Plotters").join("Plot Styles"); + if ps.is_dir() { + dirs.push(ps); + } + } + } + } + } + dirs +} + +/// Find the table file `name` (case-insensitive) in `dirs` and read it. +#[cfg(not(target_arch = "wasm32"))] +fn find_plot_style(name: &str, dirs: &[std::path::PathBuf]) -> Option { + let reader = plot_style_reader()?; + for dir in dirs { + let Ok(rd) = std::fs::read_dir(dir) else { continue }; + for e in rd.flatten().take(5000) { + let p = e.path(); + if p.file_name().is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case(name.trim())) + && std::fs::metadata(&p).is_ok_and(|m| m.len() <= cadcraft_doc::MAX_TABLE_FILE as u64) + && let Ok(bytes) = std::fs::read(&p) + && let Ok(t) = reader(&bytes, name.trim()) + { + return Some(t); + } + } + } + None +} + pub fn set_plot_book(h: PlotBookHook) { let _ = PLOT_BOOK.set(h); } @@ -296,6 +358,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { let ReadFile { drawing, binary_dxf, name, path } = f; let i = add_read(s, drawing, binary_dxf, &name, path); super::blocks::xref::after_open(s, i); + find_plot_styles(s, i); Ok(opened(s, i, true)) } @@ -347,6 +410,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result { let bytes = std::fs::read(path).map_err(|e| bad("open", format!("{path}: {e}")))?; let i = open_bytes(s, &bytes, path, Some(path.to_string()))?; super::blocks::xref::after_open(s, i); + find_plot_styles(s, i); return Ok(opened(s, i, true)); } #[cfg(target_arch = "wasm32")] @@ -360,6 +424,52 @@ fn run_open(s: &mut Session, p: &Value) -> Result { Ok(opened(s, i, false)) } +/// The plot style tables the drawing's layouts name that it doesn't hold and CADCraft doesn't +/// have built in (`SIVAN.ctb`): read from the drawing's folder or AutoCAD's plot style folders, +/// so the layouts plot with their colours and lineweights. +pub(crate) fn find_plot_styles(s: &mut Session, i: usize) { + #[cfg(not(target_arch = "wasm32"))] + { + let Some(st) = s.docs.get_mut(i) else { return }; + let mut wanted: Vec = Vec::new(); + for l in &st.doc.layouts { + let n = l.page.plot_style_table.trim(); + if !cadcraft_doc::no_plot_style_table(n) + && cadcraft_doc::plot_style_table(&st.doc, n).is_none() + && !wanted.iter().any(|w| w.eq_ignore_ascii_case(n)) + { + wanted.push(n.to_string()); + } + } + if wanted.is_empty() { + return; + } + let mut extra = Vec::new(); + if let Some(dir) = st.path.as_deref().and_then(|p| std::path::Path::new(p).parent()) { + extra.push(dir.to_path_buf()); + } + let dirs = plot_style_dirs(extra); + let found: Vec = wanted.iter().filter_map(|n| find_plot_style(n, &dirs)).collect(); + let missing: Vec<&String> = wanted.iter().filter(|n| !found.iter().any(|t| t.name.eq_ignore_ascii_case(n))).collect(); + let names: Vec = found.iter().map(|t| t.name.clone()).collect(); + if !found.is_empty() { + let d = std::sync::Arc::make_mut(&mut st.doc); + d.plot_style_tables.extend(found); + st.saved = st.doc.clone(); + } + for n in names { + s.echo(format!("Plot style table {n} found and used for plotting.")); + } + for n in missing { + s.echo(format!( + "Plot style table {n} not found: layouts plot with the objects' own colours and lineweights. Put the file next to the drawing or load it in the Plot Style Manager." + )); + } + } + #[cfg(target_arch = "wasm32")] + let _ = (s, i); +} + fn run_close(s: &mut Session, p: &Value) -> Result { let i = p.get("index").and_then(Value::as_u64).map(|i| i as usize).unwrap_or(s.active); if i >= s.docs.len() { diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index b92b15826d..91b299c3de 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -306,7 +306,21 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { if meta.len() > cadcraft_doc::MAX_TABLE_FILE as u64 { return Err(bad(cmd, format!("{_path}: the plot style table file is too large"))); } - std::fs::read_to_string(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))? + let bytes = std::fs::read(_path).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; + // AutoCAD's own .ctb/.stb files, read as they are. + if super::super::file::is_pia(&bytes) { + let reader = super::super::file::plot_style_reader() + .ok_or_else(|| bad(cmd, "AutoCAD plot style table files can't be read in this build"))?; + let file = std::path::Path::new(_path).file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(); + let mut t = reader(&bytes, &file).map_err(|e| bad(cmd, format!("{_path}: {e}")))?; + if let Some(n) = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) { + t.name = n.chars().take(255).collect(); + } + let out = table_summary(s.doc()?, &t); + store(s.doc_mut()?, t); + return Ok(out); + } + String::from_utf8(bytes).map_err(|_| bad(cmd, format!("{_path}: not a plot style table file")))? } #[cfg(target_arch = "wasm32")] return Err(bad(cmd, "files can't be read here: pass `text`")); diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 5a5e70fa45..70b5a39ecf 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; textStyle (text, multiline text, multileaders); multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -222,9 +222,26 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad("properties.set", format!("multileader style `{n}` not found"))) }) .transpose()?; + let text_style = str_param(p, "textStyle") + .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) + .transpose()?; let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { + // The text style of text, multiline text and a multileader's text. + if let Some(st) = &text_style { + match &mut e.kind { + EntityKind::Text(t) => t.style.clone_from(st), + EntityKind::MText(t) => t.style.clone_from(st), + EntityKind::MLeader(m) => { + if let Some(t) = &mut m.text { + t.style.clone_from(st); + } + } + EntityKind::AttDef(a) => a.text.style.clone_from(st), + _ => {} + } + } // Annotative: Yes supports the current annotation scale; No drops every scale. if let Some(a) = p.get("annotative").and_then(Value::as_bool) { cadcraft_doc::set_annotative(e, a, &anno_scale); diff --git a/crates/engine/src/grips.rs b/crates/engine/src/grips.rs index e1ee10e8d2..4a2d1412b8 100644 --- a/crates/engine/src/grips.rs +++ b/crates/engine/src/grips.rs @@ -288,7 +288,12 @@ pub fn stretch_grip(kind: &EntityKind, index: usize, to: Vec2) -> Option Vec { ]); v } + // The text grip of a multileader. + EntityKind::MLeader(m) if m.text_grip() == Some(index) => { + vec![GripAction::MoveWithLeader, GripAction::MoveTextOnly, GripAction::ResetTextPosition] + } _ => Vec::new(), } } @@ -677,6 +687,14 @@ pub fn grip_action(kind: &EntityKind, index: usize, action: GripAction, to: Opti d.user_text_pos = false; d.block = None; } + (EntityKind::MLeader(m), GripAction::MoveWithLeader) => m.move_with_leader(to?), + (EntityKind::MLeader(m), GripAction::MoveTextOnly) => { + let to = to?; + if let Some(t) = &mut m.text { + set_xy(&mut t.insert, to); + } + } + (EntityKind::MLeader(m), GripAction::ResetTextPosition) => m.reset_text(), (EntityKind::Arc(a), GripAction::Lengthen) => { let c = a.center.xy(); let ang = match (value, to) { diff --git a/crates/engine/tests/text_editor_on_create.rs b/crates/engine/tests/text_editor_on_create.rs index 89c146140f..1e0f8d5484 100644 --- a/crates/engine/tests/text_editor_on_create.rs +++ b/crates/engine/tests/text_editor_on_create.rs @@ -80,3 +80,27 @@ fn leader_type_none_hides_the_leader_and_straight_brings_it_back() { s.execute("properties.set", &serde_json::json!({ "handles": [h], "leaderType": "straight" })).unwrap(); assert!(!get(&s).leaderless()); } + +#[test] +fn multileader_text_grip_moves_with_its_leader_and_resets() { + use cadcraft_engine::grips::{GripAction, grip_action, grip_actions}; + let mut s = Session::new(); + s.execute("mleader", &serde_json::json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap(); + let k = s.doc().unwrap().model.iter().next().unwrap().kind.clone(); + let EntityKind::MLeader(m) = &k else { panic!("not a multileader") }; + let i = m.text_grip().expect("a text grip"); + assert_eq!(k.grips().len(), i + 1); + assert!(grip_actions(&k, i).contains(&GripAction::MoveWithLeader)); + let moved = grip_action(&k, i, GripAction::MoveWithLeader, Some(Vec2::new(20.0, 12.0)), None).unwrap(); + let EntityKind::MLeader(m2) = &moved else { panic!() }; + let t = m2.text.as_ref().unwrap(); + assert!((t.insert.x - 20.0).abs() < 1e-9 && (t.insert.y - 12.0).abs() < 1e-9); + assert!((m2.landing.y - 12.0).abs() < 1e-9 && m2.landing.x < 20.0, "the landing follows the text"); + assert_eq!(m2.leaders, m.leaders, "the leader points stay"); + // Text moved alone, then put back beside the landing. + let alone = grip_action(&k, i, GripAction::MoveTextOnly, Some(Vec2::new(30.0, -4.0)), None).unwrap(); + let back = grip_action(&alone, i, GripAction::ResetTextPosition, None, None).unwrap(); + let EntityKind::MLeader(m3) = &back else { panic!() }; + let t3 = m3.text.as_ref().unwrap(); + assert!((t3.insert.y - m3.landing.y).abs() < 1e-9 && t3.insert.x > m3.landing.x); +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ef56e66023..fb9ed9d45e 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -13,6 +13,7 @@ mod dxf_table; mod dxf_write; mod dxf_xref; pub mod pdf; +pub mod pia; pub mod plotter; pub mod svg; mod svg_read; diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 09c1eb16e3..66a99e116a 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -415,8 +415,9 @@ struct SheetPage { /// Plot one space. fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String)]) -> Result { let page = page_for(d, space, o)?; - let unit_mm = paper::paper_unit_mm(d); - let sheet = Sheet::from_page(&page, unit_mm); + // The layout's own paper units (millimetres in an inch drawing, say) size the page. + let sheet = Sheet::from_page(&page, paper::paper_unit_mm(d)); + let unit_mm = sheet.unit_mm; let lineweights = o.lineweights.unwrap_or(if space.is_paper() { page.lineweights } else { true }); let plot_style_table = cadcraft_doc::plot_style_table(d, &page.plot_style_table).map(std::sync::Arc::new); let ropts = cadcraft_render::Options { diff --git a/crates/io/src/pia.rs b/crates/io/src/pia.rs new file mode 100644 index 0000000000..a76c4f0f7b --- /dev/null +++ b/crates/io/src/pia.rs @@ -0,0 +1,234 @@ +//! Plot style table files as AutoCAD writes them (`.ctb` colour-dependent, `.stb` named): a +//! `PIAFILEVERSION_2.0,CTBVER1,compress` header line, `pmzlibcodec`, two 32-bit words (a check +//! value and the text length), the compressed text length, then zlib-compressed text of nested +//! `key=value` and `name{ … }` blocks. Read into CADCraft's [`PlotStyleTable`] so a drawing whose +//! layouts name the user's own table plots with its colours and lineweights. + +use cadcraft_color::Rgb; +use cadcraft_doc::{EndStyle, JoinStyle, PlotStyle, PlotStyleKind, PlotStyleTable}; + +/// Largest file and decompressed text we accept. +const MAX_FILE: usize = 4 << 20; +const MAX_TEXT: usize = 16 << 20; +/// "Use the object's colour" values of a style's `color`. +const OBJECT_COLOR: i64 = -1; +const OBJECT_COLOR2: i64 = -1_006_632_961; + +/// Whether `bytes` look like an AutoCAD plot style table file. +pub fn is_pia(bytes: &[u8]) -> bool { + bytes.starts_with(b"PIAFILEVERSION") +} + +/// A node of the text: a value or a block of children, in file order. +enum Node { + Value(String), + Block(Vec<(String, Node)>), +} + +/// The decompressed text of a PIA file. +fn text(bytes: &[u8]) -> Result { + if bytes.len() > MAX_FILE { + return Err("the plot style table file is too large".into()); + } + if !is_pia(bytes) { + return Err("not a plot style table file".into()); + } + let marker = b"pmzlibcodec"; + let at = bytes.windows(marker.len()).position(|w| w == marker).ok_or("the plot style table is not compressed as expected")?; + let data = bytes.get(at + marker.len() + 12..).ok_or("the plot style table file is cut short")?; + let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, MAX_TEXT) + .map_err(|_| "the plot style table can't be decompressed".to_string())?; + Ok(String::from_utf8_lossy(&out).into_owned()) +} + +/// Parse the nested text. Lines are `key=value` (a value starting with `"` runs to the end of +/// the line, without a closing quote), `key{` opening a block and `}` closing it. +fn parse(text: &str) -> Vec<(String, Node)> { + let mut stack: Vec<(String, Vec<(String, Node)>)> = vec![(String::new(), Vec::new())]; + for line in text.lines().take(200_000) { + let l = line.trim(); + if l.is_empty() { + continue; + } + if l == "}" { + if stack.len() > 1 + && let Some((name, kids)) = stack.pop() + && let Some(top) = stack.last_mut() + { + top.1.push((name, Node::Block(kids))); + } + continue; + } + if let Some(name) = l.strip_suffix('{') { + if stack.len() < 8 { + stack.push((name.trim().to_string(), Vec::new())); + } + continue; + } + if let Some((k, v)) = l.split_once('=') + && let Some(top) = stack.last_mut() + { + let v = v.strip_prefix('"').unwrap_or(v); + top.1.push((k.trim().to_string(), Node::Value(v.to_string()))); + } + } + while stack.len() > 1 { + if let Some((name, kids)) = stack.pop() + && let Some(top) = stack.last_mut() + { + top.1.push((name, Node::Block(kids))); + } + } + stack.pop().map(|(_, k)| k).unwrap_or_default() +} + +fn value<'a>(nodes: &'a [(String, Node)], key: &str) -> Option<&'a str> { + nodes.iter().find_map(|(k, n)| match n { + Node::Value(v) if k == key => Some(v.as_str()), + _ => None, + }) +} + +fn block<'a>(nodes: &'a [(String, Node)], key: &str) -> Option<&'a [(String, Node)]> { + nodes.iter().find_map(|(k, n)| match n { + Node::Block(b) if k == key => Some(b.as_slice()), + _ => None, + }) +} + +fn int(nodes: &[(String, Node)], key: &str) -> Option { + value(nodes, key).and_then(|v| v.trim().parse().ok()) +} + +/// One style: its colour (object or RGB, grey, screened), lineweight (`0` = the object's, else +/// a 1-based index into the file's lineweight table, in millimetres), ends and joins. +fn style(nodes: &[(String, Node)], weights: &[f64]) -> PlotStyle { + let name = value(nodes, "name").unwrap_or("").to_string(); + let mut s = PlotStyle::object(&name); + s.description = value(nodes, "description").unwrap_or("").to_string(); + let policy = int(nodes, "color_policy").unwrap_or(1); + if let Some(c) = int(nodes, "color").or_else(|| int(nodes, "mode_color")) + && c != OBJECT_COLOR + && c != OBJECT_COLOR2 + { + let v = c as u32; + s.color = Some(Rgb(((v >> 16) & 0xFF) as u8, ((v >> 8) & 0xFF) as u8, (v & 0xFF) as u8)); + } + s.grayscale = policy & 2 != 0; + s.screening = int(nodes, "screen").map_or(100, |v| v.clamp(0, 100) as u8); + s.lineweight = match int(nodes, "lineweight") { + Some(i) if i > 0 => weights.get((i - 1) as usize).map(|mm| (mm * 100.0).round().clamp(0.0, 211.0) as u16), + _ => None, + }; + s.end = match int(nodes, "end_style") { + Some(0) => EndStyle::Butt, + Some(1) => EndStyle::Square, + Some(2) => EndStyle::Round, + Some(3) => EndStyle::Diamond, + _ => EndStyle::Object, + }; + s.join = match int(nodes, "join_style") { + Some(0) => JoinStyle::Miter, + Some(1) => JoinStyle::Bevel, + Some(2) => JoinStyle::Round, + Some(3) => JoinStyle::Diamond, + _ => JoinStyle::Object, + }; + s +} + +/// Read a `.ctb` or `.stb` file into a table named `name` (the file's name, as page setups +/// name it). +pub fn read(bytes: &[u8], name: &str) -> Result { + let t = text(bytes)?; + let nodes = parse(&t); + let named = bytes.get(..60).is_some_and(|h| h.windows(6).any(|w| w == b"STBVER")); + // Lineweights in millimetres; the file may list them in inches (display units 1). + let inches = int(&nodes, "custom_lineweight_display_units") == Some(1); + let mut weights: Vec<(usize, f64)> = block(&nodes, "custom_lineweight_table") + .unwrap_or(&[]) + .iter() + .filter_map(|(k, n)| match n { + Node::Value(v) => Some((k.parse().ok()?, v.trim().parse::().ok()?)), + Node::Block(_) => None, + }) + .filter(|(_, v)| v.is_finite() && *v >= 0.0) + .collect(); + weights.sort_by_key(|(i, _)| *i); + let weights: Vec = weights.into_iter().map(|(_, v)| if inches { v * 25.4 } else { v }).collect(); + let mut styles: Vec<(usize, PlotStyle)> = block(&nodes, "plot_style") + .unwrap_or(&[]) + .iter() + .filter_map(|(k, n)| match n { + Node::Block(b) => Some((k.parse().ok()?, style(b, &weights))), + Node::Value(_) => None, + }) + .collect(); + styles.sort_by_key(|(i, _)| *i); + if styles.is_empty() { + return Err("the plot style table has no styles".into()); + } + let table = PlotStyleTable { + name: name.to_string(), + description: value(&nodes, "description").unwrap_or("").to_string(), + kind: if named { PlotStyleKind::Named } else { PlotStyleKind::ColorDependent }, + styles: styles.into_iter().map(|(_, s)| s).collect(), + }; + Ok(table.sanitized()) +} + +#[cfg(test)] +mod tests { + /// A small table in the file format, made here (a colour-dependent table whose colour 1 is red + /// at 0.35 mm and colour 2 black at the object's lineweight). + fn file() -> Vec { + let mut text = String::from( + "description=\"Test\naci_table_available=TRUE\nscale_factor=1.0\napply_factor=FALSE\ncustom_lineweight_display_units=0\nplot_style{\n", + ); + for i in 0..255 { + let (color, lw) = match i { + 0 => ("-1006698496", 11), + 1 => ("-16777216", 0), + _ => ("-1", 0), + }; + text.push_str(&format!( + " {i}{{\n name=\"Color_{}\n color={color}\n color_policy=5\n screen=100\n linetype=31\n lineweight={lw}\n end_style=4\n join_style=5\n }}\n", + i + 1 + )); + } + text.push_str("}\ncustom_lineweight_table{\n"); + for (i, w) in [0.0, 0.05, 0.09, 0.1, 0.13, 0.15, 0.18, 0.2, 0.25, 0.3, 0.35, 0.4].iter().enumerate() { + text.push_str(&format!(" {i}={w}\n")); + } + text.push_str("}\n"); + let z = miniz_oxide::deflate::compress_to_vec_zlib(text.as_bytes(), 6); + let mut out = b"PIAFILEVERSION_2.0,CTBVER1,compress\r\npmzlibcodec".to_vec(); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&(text.len() as u32).to_le_bytes()); + out.extend_from_slice(&(z.len() as u32).to_le_bytes()); + out.extend_from_slice(&z); + out + } + + #[test] + fn a_color_table_file_gives_colours_and_lineweights() { + let t = super::read(&file(), "Mine.ctb").unwrap(); + assert!(t.is_color_dependent()); + let red = t.by_color(1).unwrap(); + assert_eq!(red.lineweight, Some(35)); + assert_eq!(red.color.map(|c| (c.0, c.1, c.2)), Some((255, 0, 0))); + let black = t.by_color(2).unwrap(); + assert_eq!(black.color.map(|c| (c.0, c.1, c.2)), Some((0, 0, 0))); + assert_eq!(black.lineweight, None); + assert!(t.by_color(3).unwrap().color.is_none()); + } + + #[test] + fn hostile_files_are_refused_not_panicked_on() { + assert!(super::read(b"PIAFILEVERSION_2.0,CTBVER1,compress\r\npmzlibcodec\x01\x02", "x.ctb").is_err()); + assert!(super::read(b"hello", "x.ctb").is_err()); + let mut f = file(); + f.truncate(f.len() / 2); + assert!(super::read(&f, "x.ctb").is_err()); + } +} diff --git a/crates/io/tests/tables_objects_roundtrip.rs b/crates/io/tests/tables_objects_roundtrip.rs index 5eb4b4798f..730c0b6045 100644 --- a/crates/io/tests/tables_objects_roundtrip.rs +++ b/crates/io/tests/tables_objects_roundtrip.rs @@ -279,3 +279,26 @@ fn foreign_and_hostile_tables_objects() { assert_eq!(again.groups, d.groups); assert_eq!(again.views, d.views); } + +#[test] +fn a_millimetre_layout_of_an_inch_drawing_plots_on_a_page_its_own_size() { + // The PDF page of an A3 layout set up in millimetres is A3 (1190.55 × 841.89 pt), not 25.4 + // times larger, so a printed line keeps its lineweight instead of shrinking 25.4 times. + let mut d = Drawing::new_imperial(); + let name = { + let l = d.layouts.get_mut(0).expect("Layout1"); + l.page.width_mm = 297.0; + l.page.height_mm = 420.0; + l.page.landscape = true; + l.page.margins_mm = [0.0; 4]; + l.page.mm_units = Some(true); + l.name.clone() + }; + d.add(&Space::Paper(name.clone()), Common::default(), EntityKind::Line(Line { a: Vec3::new(10.0, 10.0, 0.0), b: Vec3::new(400.0, 280.0, 0.0) })) + .expect("line"); + let pdf = cadcraft_io::pdf::pdf(&d, &Space::Paper(name), &cadcraft_io::PdfOptions::default()).expect("pdf"); + let text = String::from_utf8_lossy(&pdf); + let i = text.find("/MediaBox [0 0 ").expect("media box") + "/MediaBox [0 0 ".len(); + let dims: Vec = text[i..].split(']').next().unwrap_or("").split_whitespace().filter_map(|v| v.parse().ok()).collect(); + assert!(dims.len() == 2 && (dims[0] - 1190.55).abs() < 1.0 && (dims[1] - 841.89).abs() < 1.0, "{dims:?}"); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 16b05db5f7..2f7ee47219 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -643,10 +643,10 @@ fn viewport(b: &mut Builder, d: &Drawing, e: &Entity, vp: &cadcraft_doc::Viewpor return; } match &poly { - Some(p) => contents(b, d, vp, p.bounds(), &Clip::Poly(p)), + Some(p) => contents(b, d, vp, p.bounds(), &Clip::Poly(p), paper::unit_mm_of(d, e.handle)), None => { if let Some(rect) = viewport_rect(vp) { - contents(b, d, vp, rect, &Clip::Rect(rect)); + contents(b, d, vp, rect, &Clip::Rect(rect), paper::unit_mm_of(d, e.handle)); } } } @@ -684,13 +684,13 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); let mut b = Builder { list: DisplayList::default(), opts, plotting: false, styles: styler.as_ref(), named: None, shared_budget: None, transparency: 0 }; - contents(&mut b, d, vp, area, &Clip::Rect(area)); + contents(&mut b, d, vp, area, &Clip::Rect(area), paper::space_unit_mm(d, space)); b.list } /// Model space seen through `vp`, in paper units, appended to `b`'s list clipped to `clip`; /// `area` (the clip's bounds on paper) picks the model objects to draw. -fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bounds2, clip: &Clip) { +fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bounds2, clip: &Clip, unit_mm: f64) { if b.list.expanded >= MAX_BLOCK_EXPANSION || !vp.on { return; } @@ -784,7 +784,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou } } // The contents are in paper units now: draw their pens before clipping. - pen::apply(&mut sub.list, paper::paper_unit_mm(d)); + pen::apply(&mut sub.list, unit_mm); b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded); append_clipped(&mut b.list, &sub.list, clip); } diff --git a/crates/render/src/paper.rs b/crates/render/src/paper.rs index cc083e2e8f..fad67c612b 100644 --- a/crates/render/src/paper.rs +++ b/crates/render/src/paper.rs @@ -81,6 +81,23 @@ pub fn paper_unit_mm(d: &Drawing) -> f64 { if d.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 25.4 } } +/// Millimetres per paper unit of `space`: a layout's own paper units when its page setup names +/// them (a drawing in inches may have layouts set up in millimetres), else the drawing's. +pub fn space_unit_mm(d: &Drawing, space: &cadcraft_doc::Space) -> f64 { + match space.layout().and_then(|n| d.layout(n)) { + Some(l) => Sheet::from_page(&l.page, paper_unit_mm(d)).unit_mm, + None => paper_unit_mm(d), + } +} + +/// Millimetres per paper unit of the layout holding object `h` (the drawing's when none does). +pub fn unit_mm_of(d: &Drawing, h: cadcraft_doc::Handle) -> f64 { + match d.layouts.iter().find(|l| l.entities.get(h).is_some()) { + Some(l) => Sheet::from_page(&l.page, paper_unit_mm(d)).unit_mm, + None => paper_unit_mm(d), + } +} + /// The paper sheet of a layout, in paper-space units. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Sheet { diff --git a/crates/ui-egui/src/blockmgr.rs b/crates/ui-egui/src/blockmgr.rs index 612dbabcd9..1aaa0a216e 100644 --- a/crates/ui-egui/src/blockmgr.rs +++ b/crates/ui-egui/src/blockmgr.rs @@ -138,12 +138,22 @@ enum Act { Rename(String, String), Delete(String), Write(String), + /// Pin the window as a panel on the right; float the panel as a window. + ToPanel, + ToWindow, } -/// Format ▸ Blocks / the Blocks button: the Block Manager window. -pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { - let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); - let Ok(d) = app.session.doc() else { return }; +/// The data the Block Manager shows this frame. +struct View { + all: Vec, + selected: Option, + info: Option<(usize, usize, cadcraft_geom::Vec3, bool, String, Option)>, + pv: Option, + can_write: bool, +} + +fn view(app: &CadApp, ctx: &egui::Context, st: &mut State) -> Option { + let d = app.session.doc().ok()?; let all = names(d); if st.selected.as_ref().is_some_and(|s| !all.iter().any(|n| n == s)) { st.selected = None; @@ -158,167 +168,180 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { Some((b.entities.len(), reference_count(d, n), b.base, b.annotative, b.description.clone(), b.xref_path.clone())) }); let pv = selected.as_deref().and_then(|n| preview(app, ctx, n)); - let can_write = app.services.pick_save.is_some(); - let mut act = None; - egui::Window::new(crate::tl!("Block Manager")) - .id(egui::Id::new("Blocks")) - .open(open) - .default_size(vec2(640.0, 440.0)) - .min_size(vec2(480.0, 320.0)) - .resizable(true) - .show(ctx, |ui| { - let t = Tokens::get(); - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Search blocks")).desired_width(200.0)); - ui.label(egui::RichText::new(format!("{} {}", all.len(), crate::tl!("blocks"))).color(t.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { - act = Some(Act::Create); - } - }); - }); - ui.add_space(4.0); - let avail = ui.available_size(); - let list_w = 230.0_f32.min(avail.x * 0.45); - let height = (avail.y - 4.0).max(200.0); - ui.horizontal_top(|ui| { - // The list of blocks. - ui.allocate_ui_with_layout(vec2(list_w, height), egui::Layout::top_down(egui::Align::LEFT), |ui| { - egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(2.0).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("cc_block_list").auto_shrink([false, false]).max_height(height - 6.0).show(ui, |ui| { - ui.set_width(list_w - 8.0); - let filter = st.filter.trim().to_lowercase(); - let mut shown = 0; - for n in all.iter().filter(|n| filter.is_empty() || n.to_lowercase().contains(&filter)) { - shown += 1; - let on = selected.as_deref() == Some(n.as_str()); - let r = ui.selectable_label(on, n); - if r.clicked() { - st.selected = Some(n.clone()); - st.rename = None; - st.note = None; - } - if r.double_clicked() { - act = Some(Act::Insert(n.clone())); - } - r.on_hover_text(crate::tl!("Double-click to insert")); - } - if shown == 0 { - let msg = if all.is_empty() { - crate::tl!("No blocks defined in this drawing.") - } else { - crate::tl!("No blocks match the search.") - }; - ui.label(egui::RichText::new(msg).color(t.text_dim)); - } - }); - }); - }); - // Preview, details and actions of the selected block. - ui.vertical(|ui| { - let side = ui.available_width().min(height - 150.0).clamp(140.0, 320.0); - let (r, _) = ui.allocate_exact_size(vec2(ui.available_width().max(side), side), Sense::hover()); - match &pv { - Some(p) => paint_list(ui.painter(), r, &p.list, &p.bounds), - None => { - ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("Preview"), crate::theme::small(), t.text_faint); + Some(View { all, selected, info, pv, can_write: app.services.pick_save.is_some() }) +} + +/// The manager's contents: in a window the list sits left of the preview, in a panel above it. +fn body(ui: &mut egui::Ui, v: &View, st: &mut State, as_panel: bool, act: &mut Option) { + let View { all, selected, info, pv, can_write } = v; + let can_write = *can_write; + let t = Tokens::get(); + ui.horizontal(|ui| { + let w = if as_panel { (ui.available_width() - 70.0).max(80.0) } else { 200.0 }; + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Search blocks")).desired_width(w)); + if !as_panel { + ui.label(egui::RichText::new(format!("{} {}", all.len(), crate::tl!("blocks"))).color(t.text_dim)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + // Window ⇄ panel. + let (icon, tip) = if as_panel { + (crate::icons::Icon::Workspace, crate::tl!("Float as a window")) + } else { + (crate::icons::Icon::Properties, crate::tl!("Pin as a panel on the right")) + }; + if crate::icons::button(ui, icon, 20.0, tip, false).clicked() { + *act = Some(if as_panel { Act::ToWindow } else { Act::ToPanel }); + } + if !as_panel && ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { + *act = Some(Act::Create); + } + }); + }); + ui.add_space(4.0); + let avail = ui.available_size(); + let (list_w, height) = + if as_panel { (avail.x, (avail.y * 0.38).clamp(120.0, 320.0)) } else { (230.0_f32.min(avail.x * 0.45), (avail.y - 4.0).max(200.0)) }; + let list = |ui: &mut egui::Ui, st: &mut State, act: &mut Option| { + ui.allocate_ui_with_layout(vec2(list_w, height), egui::Layout::top_down(egui::Align::LEFT), |ui| { + egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(2.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("cc_block_list").auto_shrink([false, false]).max_height(height - 6.0).show(ui, |ui| { + ui.set_width(list_w - 8.0); + let filter = st.filter.trim().to_lowercase(); + let mut shown = 0; + for n in all.iter().filter(|n| filter.is_empty() || n.to_lowercase().contains(&filter)) { + shown += 1; + let on = selected.as_deref() == Some(n.as_str()); + let r = ui.selectable_label(on, n); + if r.clicked() { + st.selected = Some(n.clone()); + st.rename = None; + st.note = None; } - } - if pv.as_ref().is_some_and(|p| p.bounds.is_empty()) { - ui.painter().text( - r.center(), - egui::Align2::CENTER_CENTER, - crate::tl!("The block is empty"), - crate::theme::small(), - t.text_faint, - ); - } - ui.add_space(4.0); - let Some(name) = selected.clone() else { return }; - if let Some(mut new) = st.rename.take() { - let mut keep = true; - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut new).desired_width(160.0)); - if ui.button(crate::tl!("OK")).clicked() && !new.trim().is_empty() { - act = Some(Act::Rename(name.clone(), new.trim().to_string())); - } - if ui.button(crate::tl!("Cancel")).clicked() { - keep = false; - } - }); - if keep { - st.rename = Some(new); + if r.double_clicked() { + *act = Some(Act::Insert(n.clone())); } - } else { - ui.label(egui::RichText::new(&name).strong()); - } - if let Some((objects, refs, base, annotative, description, xref)) = &info { - egui::Grid::new("cc_block_info").num_columns(2).spacing(vec2(12.0, 2.0)).show(ui, |ui| { - ui.label(egui::RichText::new(crate::tl!("Objects")).color(t.text_dim)); - ui.label(objects.to_string()); - ui.end_row(); - ui.label(egui::RichText::new(crate::tl!("References")).color(t.text_dim)); - ui.label(refs.to_string()); - ui.end_row(); - ui.label(egui::RichText::new(crate::tl!("Base point")).color(t.text_dim)); - ui.label(format!("{:.4}, {:.4}", base.x, base.y)); - ui.end_row(); - ui.label(egui::RichText::new(crate::tl!("Annotative")).color(t.text_dim)); - ui.label(if *annotative { crate::tl!("Yes") } else { crate::tl!("No") }); - ui.end_row(); - if let Some(path) = xref { - ui.label(egui::RichText::new(crate::tl!("External reference")).color(t.text_dim)); - ui.label(path); - ui.end_row(); - } - if !description.is_empty() { - ui.label(egui::RichText::new(crate::tl!("Description")).color(t.text_dim)); - ui.label(description); - ui.end_row(); - } - }); + r.on_hover_text(crate::tl!("Double-click to insert")); } - ui.add_space(6.0); - ui.horizontal_wrapped(|ui| { - if ui.button(crate::tl!("Insert")).clicked() { - act = Some(Act::Insert(name.clone())); - } - if ui.button(crate::tl!("Edit Block")).on_hover_text(crate::tl!("Open in the Block Editor")).clicked() { - act = Some(Act::Edit(name.clone())); - } - if ui.button(crate::tl!("Rename...")).clicked() { - st.rename = Some(name.clone()); - } - if ui.button(crate::tl!("Delete")).on_hover_text(crate::tl!("Delete a block that no object uses")).clicked() { - act = Some(Act::Delete(name.clone())); - } - if can_write - && ui.button(crate::tl!("Save to File...")).on_hover_text(crate::tl!("Write the block as a drawing (WBLOCK)")).clicked() - { - act = Some(Act::Write(name.clone())); - } - }); - if let Some(n) = &st.note { - ui.label(egui::RichText::new(n).color(t.text_dim)); + if shown == 0 { + let msg = + if all.is_empty() { crate::tl!("No blocks defined in this drawing.") } else { crate::tl!("No blocks match the search.") }; + ui.label(egui::RichText::new(msg).color(t.text_dim)); } }); }); }); + }; + let details = |ui: &mut egui::Ui, st: &mut State, act: &mut Option| { + let side = if as_panel { ui.available_width().clamp(120.0, 360.0) } else { ui.available_width().min(height - 150.0).clamp(140.0, 320.0) }; + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width().max(side), side.min(if as_panel { 220.0 } else { side })), Sense::hover()); + match pv { + Some(p) => paint_list(ui.painter(), r, &p.list, &p.bounds), + None => { + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("Preview"), crate::theme::small(), t.text_faint); + } + } + if pv.as_ref().is_some_and(|p| p.bounds.is_empty()) { + ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, crate::tl!("The block is empty"), crate::theme::small(), t.text_faint); + } + ui.add_space(4.0); + let Some(name) = selected.clone() else { return }; + if let Some(mut new) = st.rename.take() { + let mut keep = true; + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut new).desired_width(160.0)); + if ui.button(crate::tl!("OK")).clicked() && !new.trim().is_empty() { + *act = Some(Act::Rename(name.clone(), new.trim().to_string())); + } + if ui.button(crate::tl!("Cancel")).clicked() { + keep = false; + } + }); + if keep { + st.rename = Some(new); + } + } else { + ui.label(egui::RichText::new(&name).strong()); + } + if let Some((objects, refs, base, annotative, description, xref)) = info { + egui::Grid::new("cc_block_info").num_columns(2).spacing(vec2(12.0, 2.0)).show(ui, |ui| { + ui.label(egui::RichText::new(crate::tl!("Objects")).color(t.text_dim)); + ui.label(objects.to_string()); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("References")).color(t.text_dim)); + ui.label(refs.to_string()); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("Base point")).color(t.text_dim)); + ui.label(format!("{:.4}, {:.4}", base.x, base.y)); + ui.end_row(); + ui.label(egui::RichText::new(crate::tl!("Annotative")).color(t.text_dim)); + ui.label(if *annotative { crate::tl!("Yes") } else { crate::tl!("No") }); + ui.end_row(); + if let Some(path) = xref { + ui.label(egui::RichText::new(crate::tl!("External reference")).color(t.text_dim)); + ui.label(path); + ui.end_row(); + } + if !description.is_empty() { + ui.label(egui::RichText::new(crate::tl!("Description")).color(t.text_dim)); + ui.label(description); + ui.end_row(); + } + }); + } + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + if ui.button(crate::tl!("Insert")).clicked() { + *act = Some(Act::Insert(name.clone())); + } + if ui.button(crate::tl!("Edit Block")).on_hover_text(crate::tl!("Open in the Block Editor")).clicked() { + *act = Some(Act::Edit(name.clone())); + } + if ui.button(crate::tl!("Rename...")).clicked() { + st.rename = Some(name.clone()); + } + if ui.button(crate::tl!("Delete")).on_hover_text(crate::tl!("Delete a block that no object uses")).clicked() { + *act = Some(Act::Delete(name.clone())); + } + if can_write && ui.button(crate::tl!("Save to File...")).on_hover_text(crate::tl!("Write the block as a drawing (WBLOCK)")).clicked() { + *act = Some(Act::Write(name.clone())); + } + if as_panel && ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { + *act = Some(Act::Create); + } + }); + if let Some(n) = &st.note { + ui.label(egui::RichText::new(n).color(t.text_dim)); + } + }; + if as_panel { + list(ui, st, act); + ui.add_space(6.0); + details(ui, st, act); + } else { + ui.horizontal_top(|ui| { + list(ui, st, act); + ui.vertical(|ui| details(ui, st, act)); + }); + } +} + +/// Do what a button asked; false when the manager should close (a command takes over). +fn apply(app: &mut CadApp, st: &mut State, act: Option) -> bool { match act { Some(Act::Insert(n)) => { - *open = false; crate::dialogs::insert_block(app, &n); + return false; } Some(Act::Edit(n)) => { - *open = false; if let Err(e) = app.run("bedit", json!({ "name": n })) { app.session.echo(e); } + return false; } Some(Act::Create) => { - *open = false; app.start("block"); + return false; } Some(Act::Rename(from, to)) => match app.run("rename", json!({ "table": "block", "from": from, "to": to })) { Ok(_) => { @@ -350,8 +373,79 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { st.note = Some(e); } } + Some(Act::ToPanel) => { + app.ui.blocks_window = false; + let _ = open_panel(app); + return false; + } + Some(Act::ToWindow) => { + app.ui.blocks_window = true; + let _ = crate::docking::command(app, false, &json!({ "operation": "close", "panel": crate::docking::Panel::Blocks.id() })); + app.ui.dialog = Some("blocks".into()); + } None => {} } + true +} + +/// Open the Block Manager the way it was last used: a panel pinned on the right (the first +/// time) or a window. +pub fn open(app: &mut CadApp) -> Result { + if app.ui.blocks_window { + app.ui.dialog = Some("blocks".into()); + return Ok(serde_json::Value::Null); + } + open_panel(app) +} + +/// Show the Blocks panel, docked on the right of the drawing. +fn open_panel(app: &mut CadApp) -> Result { + if app.ui.dialog.as_deref() == Some("blocks") { + app.ui.dialog = None; + } + let panel = crate::docking::Panel::Blocks; + let first = !app.ui.docking.layout.contains(&panel) && !app.ui.docking.hidden.iter().any(|(p, _)| *p == panel); + let r = crate::docking::command(app, false, &json!({ "operation": "open", "panel": panel.id() }))?; + // The first time: pinned at the right edge, beside the Layers and Properties palettes. + if first && app.ui.docking.layout.contains(&crate::docking::Panel::Properties) { + return crate::docking::command(app, false, &json!({ "operation": "move", "panel": panel.id(), "target": "properties", "zone": "right" })); + } + Ok(r) +} + +/// The Blocks panel. +pub fn panel(app: &mut CadApp, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); + let Some(v) = view(app, &ctx, &mut st) else { return }; + let mut act = None; + egui::ScrollArea::vertical().id_salt("dock-blocks").auto_shrink([false, false]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(6.0).show(ui, |ui| body(ui, &v, &mut st, true, &mut act)); + }); + // The panel stays open whatever the button did. + apply(app, &mut st, act); + ctx.data_mut(|d| d.insert_temp(state_id(), st)); +} + +/// The Block Manager as a window. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); + let Some(v) = view(app, ctx, &mut st) else { return }; + let mut act = None; + egui::Window::new(crate::tl!("Block Manager")) + .id(egui::Id::new("Blocks")) + .open(open) + .default_size(vec2(640.0, 440.0)) + .min_size(vec2(480.0, 320.0)) + .resizable(true) + .show(ctx, |ui| body(ui, &v, &mut st, false, &mut act)); + let to_panel = matches!(act, Some(Act::ToPanel)); + if !apply(app, &mut st, act) && !to_panel { + *open = false; + } + if to_panel { + *open = false; + } ctx.data_mut(|d| d.insert_temp(state_id(), st)); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index acbea01f89..be8a95ab85 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -379,7 +379,10 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { /// Start INSERT with `name` already given at its block name prompt, so the next prompt asks for /// the insertion point. pub(crate) fn insert_block(app: &mut CadApp, name: &str) { - app.start("insert"); + // The engine's INSERT itself (the UI's INSERT opens the Block Manager). + if let Err(e) = app.session.start("insert") { + app.session.echo(e.to_string()); + } if app.session.running.as_ref().is_none_or(|r| r.id != "insert") { return; } diff --git a/crates/ui-egui/src/dimstyles.rs b/crates/ui-egui/src/dimstyles.rs index 0a19d510ad..23b735f18f 100644 --- a/crates/ui-egui/src/dimstyles.rs +++ b/crates/ui-egui/src/dimstyles.rs @@ -362,6 +362,8 @@ pub struct Names { pub text_styles: Vec, /// User arrowhead blocks the drawing's dimension styles use. pub arrow_blocks: Vec, + /// Their shapes for the list's icons: the tip at the origin, pointing along -x, unit size. + pub arrow_shapes: Vec<(String, cadcraft_render::ArrowGeom)>, } impl Names { @@ -374,10 +376,15 @@ impl Names { arrow_blocks.push(n.trim().to_string()); } } + let arrow_shapes = arrow_blocks + .iter() + .map(|n| (n.clone(), cadcraft_render::named_arrow(d, n, cadcraft_geom::Vec2::ZERO, cadcraft_geom::Vec2::new(-1.0, 0.0), 1.0))) + .collect(); Names { linetypes: d.linetypes.iter().map(|l| l.name.clone()).collect(), text_styles: d.text_styles.iter().map(|s| s.name.clone()).collect(), arrow_blocks, + arrow_shapes, } } } @@ -442,7 +449,67 @@ fn shown_arrow(names: &Names, cur: &str) -> String { /// An arrowhead drop-down (built-in arrowheads and the drawing's user arrowhead blocks) showing /// `cur`; the name picked. pub fn arrow_combo(ui: &mut egui::Ui, id: egui::Id, names: &Names, cur: &str) -> Option { - combo(ui, id, &shown_arrow(names, cur), &arrow_items(names, cur)) + let current = shown_arrow(names, cur); + let items = arrow_items(names, cur); + let shown = items.iter().find(|(v, _)| *v == current).map_or_else(String::new, |(_, l)| l.clone()); + let mut picked = None; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let (r, _) = ui.allocate_exact_size(vec2(34.0, 18.0), egui::Sense::hover()); + paint_arrow(ui.painter(), r, names, ¤t); + egui::ComboBox::from_id_salt(id) + .width((ui.available_width() - 14.0).clamp(80.0, 170.0)) + .selected_text(crate::i18n::widget(ui, &shown, egui::TextStyle::Button)) + .height(360.0) + .show_ui(ui, |ui| { + for (v, l) in &items { + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(34.0, 18.0), egui::Sense::hover()); + paint_arrow(ui.painter(), r, names, v); + if ui.selectable_label(*v == current, crate::i18n::widget(ui, l, egui::TextStyle::Button)).clicked() && *v != current { + picked = Some(v.clone()); + } + }); + } + }); + }); + picked +} + +/// The arrowhead `name` as a small picture: a short line ending in the arrowhead at the left. +pub fn paint_arrow(p: &egui::Painter, r: egui::Rect, names: &Names, name: &str) { + use cadcraft_geom::Vec2; + thread_local! { + static BLANK: cadcraft_doc::Drawing = cadcraft_doc::Drawing::default(); + } + let g = match names.arrow_shapes.iter().find(|(n, _)| n.eq_ignore_ascii_case(name.trim())) { + Some((_, g)) => g.clone(), + None => BLANK.with(|d| cadcraft_render::named_arrow(d, name, Vec2::ZERO, Vec2::new(-1.0, 0.0), 1.0)), + }; + let col = crate::theme::Tokens::get().text; + // The arrowhead is one unit long: fit about 1.9 units (arrow and line) across the box. + let k = f64::from(r.width()) / 2.0; + let left = f64::from(r.left()) + 0.1 * k; + let at = |v: &Vec2| egui::pos2((left + v.x * k) as f32, (f64::from(r.center().y) - v.y * k) as f32); + let clip = p.with_clip_rect(r.expand(1.0)); + let stroke = egui::Stroke::new(1.2, col); + clip.line_segment([at(&Vec2::ZERO), at(&Vec2::new(1.85, 0.0))], stroke); + for l in &g.lines { + if l.len() >= 2 { + clip.add(egui::Shape::line(l.iter().map(at).collect(), stroke)); + } + } + let mut mesh = egui::Mesh::default(); + for t in g.tris.chunks_exact(3) { + let base = u32::try_from(mesh.vertices.len()).unwrap_or(u32::MAX); + for v in t { + mesh.colored_vertex(at(v), col); + } + mesh.add_triangle(base, base + 1, base + 2); + } + if !mesh.is_empty() { + clip.add(egui::Shape::mesh(mesh)); + } } /// The decimal places as AutoCAD shows them: `0`, `0.0`, `0.00`… diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 32147bdff0..23ea0dbe5a 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -16,6 +16,8 @@ pub enum Panel { Properties, #[serde(rename = "externalReferences")] ExternalRefs, + /// The Block Manager as a panel. + Blocks, } impl Panel { @@ -28,6 +30,7 @@ impl Panel { Self::Layers => "layers", Self::Properties => "properties", Self::ExternalRefs => "externalReferences", + Self::Blocks => "blocks", } } pub fn label(self) -> &'static str { @@ -38,6 +41,7 @@ impl Panel { Self::Layers => "Layers", Self::Properties => "Properties", Self::ExternalRefs => "External References", + Self::Blocks => "Blocks", } } fn default_side(self) -> Zone { @@ -48,10 +52,11 @@ impl Panel { Self::Layers => Zone::Right, Self::Properties => Zone::Right, Self::ExternalRefs => Zone::Right, + Self::Blocks => Zone::Right, } } /// Palettes outside the default arrangement, opened on request (QUICKCALC). - pub const ON_DEMAND: &[Self] = &[Self::QuickCalc]; + pub const ON_DEMAND: &[Self] = &[Self::QuickCalc, Self::Blocks]; fn parse(id: &str) -> Result { Self::ALL.iter().chain(Self::ON_DEMAND).copied().find(|panel| panel.id() == id).ok_or_else(|| format!("Unknown panel: {id}")) } @@ -353,6 +358,7 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) { } Panel::ToolSets => crate::palettes::toolsets(app, ui), Panel::QuickCalc => crate::palettes::quickcalc::show(app, ui), + Panel::Blocks => crate::blockmgr::panel(app, ui), Panel::Layers => { egui::ScrollArea::vertical() .id_salt("dock-layers") @@ -402,6 +408,7 @@ fn panel_limits(panel: &Panel) -> PanelLimits { let (min, max_width) = match panel { Panel::Canvas => (egui::vec2(300.0, 180.0), 1_000_000.0), Panel::QuickCalc => (egui::vec2(240.0, 160.0), 600.0), + Panel::Blocks => (egui::vec2(240.0, 200.0), 600.0), Panel::ToolSets => (egui::vec2(220.0, 150.0), 480.0), Panel::Layers | Panel::Properties | Panel::ExternalRefs => (egui::vec2(220.0, 100.0), 720.0), }; diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index 4fee0a2b67..e802ed2de2 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -159,7 +159,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if crate::icons::button(ui, crate::icons::Icon::ZoomOut, 22.0, crate::tl!("Zoom Out"), false).clicked() { zoom_by = Some(0.8); } - if crate::icons::button(ui, crate::icons::Icon::ZoomExtents, 22.0, crate::tl!("Zoom to Fit"), false).clicked() { + if crate::icons::button(ui, crate::icons::Icon::ZoomFit, 22.0, crate::tl!("Zoom to Fit"), false).clicked() { view.zoom = 1.0; view.offset = Some(egui::Vec2::ZERO); } diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3c095276ec..414d622db4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1390,3 +1390,8 @@ Zoom to Fit Показать целиком Move Higher Переместить выше Move Lower Переместить ниже + Float as a window Открепить как окно + Pin as a panel on the right Закрепить панелью справа + Text Style Текстовый стиль + Dimension Style Размерный стиль + Style Стиль diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 074ed93a62..195287bd6c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1695,3 +1695,8 @@ Zoom to Fit Показати повністю Move Higher Перемістити вище Move Lower Перемістити нижче + Float as a window Відкріпити як вікно + Pin as a panel on the right Закріпити панеллю праворуч + Text Style Текстовий стиль + Dimension Style Розмірний стиль + Style Стиль diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 101127c68d..7ad9ef9b1c 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -150,6 +150,9 @@ pub enum Icon { MoveUp, MoveDown, MoveBottom, + ZoomFit, + TextStyle, + DimStyle, } struct Pen<'a> { @@ -264,13 +267,27 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.tri([(12.6, 19.4), (15.6, 22.4), (10.8, 24.0)], a); } } - Undo => { - pen.arc(12.0, 13.0, 7.0, 150.0, -40.0, b); - pen.arrow_tip(5.0, 9.0, -1.0, 2.5, b); - } - Redo => { - pen.arc(12.0, 13.0, 7.0, 30.0, 220.0, b); - pen.arrow_tip(19.0, 9.0, 1.0, 2.5, b); + Undo | Redo => { + // A thick arc with a large arrowhead at its upper end: pointing left for Undo, right + // for Redo (the same picture mirrored). + let m = |x: f32| if icon == Undo { x } else { 24.0 - x }; + let (cx, cy, r) = (13.0_f32, 14.0_f32, 6.5_f32); + let a0 = 155.0_f32; + let pts: Vec = (0..=24) + .map(|i| { + let a = (a0 - (a0 + 60.0) * i as f32 / 24.0).to_radians(); + pen.at(m(cx + r * a.cos()), cy - r * a.sin()) + }) + .collect(); + p.add(egui::Shape::line(pts, Stroke::new(pen.w * 1.8, b))); + let a = a0.to_radians(); + let (sx, sy) = (cx + r * a.cos(), cy - r * a.sin()); + // Opposite to the arc's way round: down and out at its start. + let (dx, dy) = (-a.sin(), -a.cos()); + let (dx, dy) = (-dx, -dy); + let (tx, ty) = (sx + dx * 3.6, sy + dy * 3.6); + let ddx = if icon == Undo { dx } else { -dx }; + pen.big_arrow(m(tx), ty, ddx, dy, 6.5, 4.3, b); } Plot | Preview => { pen.rect(4.0, 9.0, 16.0, 8.0, b); @@ -815,15 +832,20 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.l(17.0, 13.0, 17.0, 21.0); } Gear => { - pen.c(12.0, 12.0, 4.0, b); + // A gear wheel: eight square teeth on a rim, and the hole in the middle. + let mut outline = Vec::new(); for i in 0..8 { - let ang = (i as f32 * 45.0).to_radians(); - p.line_segment( - [pen.at(12.0 + 6.0 * ang.cos(), 12.0 + 6.0 * ang.sin()), pen.at(12.0 + 9.0 * ang.cos(), 12.0 + 9.0 * ang.sin())], - Stroke::new(2.2 * pen.sc(), b), - ); + let c = i as f32 * 45.0; + for (da, rr) in [(-17.0, 7.0), (-11.0, 9.6), (11.0, 9.6), (17.0, 7.0)] { + let a = (c + da).to_radians(); + outline.push(pen.at(12.0 + rr * a.cos(), 12.0 + rr * a.sin())); + } + } + if let Some(f) = outline.first().copied() { + outline.push(f); } - pen.c(12.0, 12.0, 6.5, b); + p.add(egui::Shape::line(outline, Stroke::new(pen.w * 1.2, b))); + pen.c(12.0, 12.0, 3.2, b); } Annotation => { pen.poly(&[(12.0, 3.0), (21.0, 20.0), (3.0, 20.0)], true, b); @@ -868,6 +890,39 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { pen.l(12.0, 12.0 - 8.0 * dir, 12.0, 12.0 + 2.0 * dir); pen.big_arrow(12.0, 12.0 + 8.0 * dir, 0.0, dir, 7.0, 5.0, b); } + ZoomFit => { + // Four right-angle corners framing a rectangle. + let s = Stroke::new(pen.w * 1.6, b); + for (x, y, dx, dy) in [(3.0, 5.0, 1.0, 1.0), (21.0, 5.0, -1.0, 1.0), (3.0, 19.0, 1.0, -1.0), (21.0, 19.0, -1.0, -1.0)] { + p.line(vec![pen.at(x + dx * 5.0, y), pen.at(x, y), pen.at(x, y + dy * 4.5)], s); + } + pen.rect(8.0, 9.0, 8.0, 6.0, a); + } + TextStyle | DimStyle => { + if icon == TextStyle { + pen.text(9.5, 10.5, "A", 15.0, b); + } else { + pen.l(2.0, 4.0, 2.0, 12.0); + pen.l(15.0, 4.0, 15.0, 12.0); + pen.l(2.0, 8.0, 15.0, 8.0); + pen.arrow_tip(2.0, 8.0, -1.0, 0.0, b); + pen.arrow_tip(15.0, 8.0, 1.0, 0.0, b); + } + // A small gear: the style's settings. + let mut outline = Vec::new(); + for i in 0..6 { + let c = i as f32 * 60.0; + for (da, rr) in [(-20.0, 3.6), (-12.0, 5.0), (12.0, 5.0), (20.0, 3.6)] { + let ang = (c + da).to_radians(); + outline.push(pen.at(17.5 + rr * ang.cos(), 17.5 + rr * ang.sin())); + } + } + if let Some(f) = outline.first().copied() { + outline.push(f); + } + p.add(egui::Shape::line(outline, Stroke::new(pen.w, a))); + pen.c(17.5, 17.5, 1.5, a); + } Close => { pen.l(6.0, 6.0, 18.0, 18.0); pen.l(18.0, 6.0, 6.0, 18.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 376e884fe2..e6b62edc01 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -106,6 +106,8 @@ pub struct UiState { pub collapsed_groups: Vec, /// The folder the Hatch and Gradient dialog's Custom Patterns tab lists `.pat` files from. pub pattern_folder: String, + /// The Block Manager opens as a window (else as a panel pinned on the right). + pub blocks_window: bool, /// Tools the user took out of the Tool Sets palette (command ids); each category's gear /// menu puts them back. pub hidden_tools: Vec, @@ -194,6 +196,7 @@ impl Default for UiState { ribbon_tab: "Draw".into(), collapsed_groups: Vec::new(), pattern_folder: String::new(), + blocks_window: false, hidden_tools: Vec::new(), properties_all: true, in_window_menu: !cfg!(target_os = "macos"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d5ec4a8d10..664be9538f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -118,6 +118,11 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option Option { + match &e.kind { + EntityKind::Text(t) => Some(t.style.clone()), + EntityKind::MText(t) => Some(t.style.clone()), + EntityKind::AttDef(a) => Some(a.text.style.clone()), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| t.style.clone()), + _ => None, + } + }; + let text_styles: Option> = sel.iter().map(|h| d.entity(*h).and_then(|e| style_of(e))).collect(); + // One multileader shows it in its own Text group, below the leader properties. + let one_mleader = sel.len() == 1 && matches!(e.kind, EntityKind::MLeader(_)); + if let Some(styles) = text_styles.filter(|v| !v.is_empty() && !one_mleader) { + let cur = if styles.iter().all(|s| s.eq_ignore_ascii_case(&styles[0])) { styles[0].clone() } else { "*VARIES*".to_string() }; + group(ui, "Text"); + prop_row(ui, "Style", |ui| { + let names = d.text_styles.iter().map(|s| s.name.clone()); + if let Some(n) = pick_menu(ui, if cur == "*VARIES*" { crate::i18n::t(&cur) } else { &cur }, names) { + set = Some(json!({ "handles": ids, "textStyle": n })); + } + }); + } if sel.len() == 1 { group(ui, "Geometry"); let real = |v: f64| format!("{v:.4}"); @@ -1193,6 +1216,11 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Landing distance", "dogleg", real(ml.dogleg), &mut set, &mut bad, &ids); if let Some(t) = &ml.text { group(ui, "Text"); + prop_row(ui, "Style", |ui| { + if let Some(n) = pick_menu(ui, &t.style, d.text_styles.iter().map(|s| s.name.clone())) { + set = Some(json!({ "handles": ids, "textStyle": n })); + } + }); num(ui, "Text height", "textHeight", real(t.height), &mut set, &mut bad, &ids); } } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 57397df9e9..636b4c4c4b 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -271,6 +271,10 @@ const STANDARD: &[&[(Icon, &str, &str, Option<&str>)]] = &[ &[(Icon::Help, "ui.dialog.about", "Help", None)], ]; +/// Standard tools that are not on the bar at first but can be added to it. +const STANDARD_EXTRA: &[(Icon, &str, &str)] = + &[(Icon::TextStyle, "style", "Text Style"), (Icon::DimStyle, "dimstyle", "Dimension Style"), (Icon::Gear, "options", "Options")]; + /// The category of the [`STANDARD`] tools in the Customize dialog. const STANDARD_CATEGORY: &str = "Standard"; @@ -333,6 +337,9 @@ pub fn catalog() -> &'static [Tool] { push(&mut tools, Tool { icon: *icon, command, label, category: STANDARD_CATEGORY, shortcut: *shortcut }); } } + for (icon, command, label) in STANDARD_EXTRA { + push(&mut tools, Tool { icon: *icon, command, label, category: STANDARD_CATEGORY, shortcut: None }); + } for (icon, command, label) in LAYER_TOOLS { push(&mut tools, Tool { icon: *icon, command, label, category: LAYERS_CATEGORY, shortcut: None }); } From 95393e04ef7b6b04610c6a073ae67b6fd860eb2f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 18:55:19 +0300 Subject: [PATCH 04/23] b13: hatch background colour, SHX Hebrew detection, viewport view target, command-line formulas, options box at the cursor, cursor on paper/pan, batch plot multi-select and columns, undo/redo history lists, icons Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 88 +++++++ crates/engine/src/cmd/hatch.rs | 20 +- crates/engine/src/cmd/hatch/edit.rs | 3 + crates/engine/src/cmd/props.rs | 13 +- crates/engine/src/formula.rs | 130 +++++++++++ crates/engine/src/lib.rs | 17 ++ crates/engine/tests/formula_input.rs | 23 ++ crates/fonts/src/shx.rs | 94 +++++++- crates/io/src/dxf_ext.rs | 29 +++ crates/io/src/dxf_read.rs | 29 ++- crates/io/src/dxf_write.rs | 8 +- crates/io/tests/hatch_background.rs | 49 ++++ crates/io/tests/paperview_marker.rs | 33 +++ crates/ui-egui/src/batchplot.rs | 335 +++++++++++++++++++++------ crates/ui-egui/src/canvas.rs | 20 +- crates/ui-egui/src/cmdline.rs | 32 ++- crates/ui-egui/src/hatchdlg.rs | 78 +++++++ crates/ui-egui/src/i18n/ru.tsv | 11 + crates/ui-egui/src/i18n/uk.tsv | 11 + crates/ui-egui/src/icons.rs | 43 ++-- crates/ui-egui/src/palettes.rs | 7 + crates/ui-egui/src/toolbar.rs | 84 ++++++- 22 files changed, 1039 insertions(+), 118 deletions(-) create mode 100644 crates/engine/src/formula.rs create mode 100644 crates/engine/tests/formula_input.rs create mode 100644 crates/io/tests/hatch_background.rs diff --git a/WHATS_NEW.md b/WHATS_NEW.md index ce448440fd..5f7934a956 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,94 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 22.10.2026 (0.9.0-b13) + +### Русский + +**Штриховка: цвет фона** +- У штриховки появилось свойство «Цвет фона»: в палитре «Свойства», в окне «Штриховка и градиент» и в команде HATCHEDIT. Можно выбрать «Нет», «ПоСлою», «ПоБлоку», стандартный цвет или любой другой. +- Цвет фона, заданный в AutoCAD, читается из файла и записывается обратно, так что AutoCAD его тоже увидит. У сплошной заливки фона нет. + +**Иврит на чертеже вместо русского** +- Найдена причина. Шрифты SHX этого чертежа (romans, txt, simplex и др.) хранят буквы по кодам Unicode. Программа считала их «одноязычными» шрифтами, где иврит лежит на кодах 0xE0–0xFA, и брала оттуда знаки, а там в этих шрифтах русские буквы. Теперь иврит берётся из таких кодов только у настоящих ивритских шрифтов (кодировки 1255 и 862). В остальных шрифтах буквы ищутся по Unicode, а если буквы нет, используется встроенный шрифт CADCraft. +- Шрифты вроде GIL, в которых латинские буквы нарисованы как ивритские (ввод с английской раскладки), так и показываются — это задумано самим шрифтом. + +**Спецсимволы** +- Знаки ⌀ (%%c), ° (%%d) и ± (%%p) показываются при любом стиле и шрифте. Если в шрифте SHX такого знака нет, он рисуется встроенным шрифтом. Раньше в некоторых ивритских шрифтах вместо ⌀ появлялась «]». + +**Листы (Layout) чертежей AutoCAD** +- Найдена причина сдвига. Видовой экран AutoCAD смотрит не только в свою «центральную точку», но и со смещением на «цель вида», и программа это смещение не учитывала. Теперь учитывает: чертежи вернулись на листы на своё место (проверено на «אריה צוק»). + +**Формулы в командной строке** +- Везде, где программа спрашивает расстояние, длину, радиус или число, можно ввести формулу, начинающуюся с «=»: =1200+350*2, =(2400-50)/3. Работают + − * /, скобки, минус перед числом, десятичная запятая. Результат показывается в истории: «=1200+350*2 = 1900». +- Пробел внутри формулы — это пробел, а не Enter. + +**Выбор вариантов рядом с курсором** +- Когда команда спрашивает выбор между вариантами (например, ЗЕРКАЛО: «Удалить исходные объекты? [Да/Нет]»), рядом с курсором появляется окошко с вариантами. Вариант можно нажать мышью или выбрать стрелками ↑ ↓ и Enter. Вариант по умолчанию уже выделен. Можно и просто печатать, как раньше. + +**Курсор** +- При панорамировании средней кнопкой мыши курсор становится значком «Перемещение». +- Над бумагой листа (Layout) перекрестие курсора становится чёрным. + +**Пакетная печать** +- Пока окно открыто, остальная программа неактивна (затемнена). +- Несколько листов выделяются щелчком с Ctrl, диапазон — с Shift, рамкой мышью (начиная с пустого места под строками), все — Ctrl+A. Кнопки перемещения, удаления и копирования работают для всех выделенных листов сразу. +- Список разбит на столбцы «№», «Лист», «Чертёж», «Бумага» с разделителями. Названия обрезаются по ширине столбца и не наезжают друг на друга. + +**Отменить и повторить** +- Новые значки в стиле Office 2010: толстая синяя дуга с крупной стрелкой. +- Рядом с кнопками «Отменить» и «Повторить» есть маленькая кнопка со стрелкой вниз. Она открывает список последних шагов (до 100, с прокруткой). При наведении подсвечиваются все шаги, которые будут отменены, а щелчок отменяет (или повторяет) их все сразу. + +**Значок предварительного просмотра** +- Лупа отодвинута вправо и больше не закрывает принтер. + +**Пока не воспроизведено** +- Текст, печатающийся контуром без заливки, у нас не получился: в PDF текст и размеры выходят залитыми. Пришлите, пожалуйста, снимок или файл, где это видно, и скажите, через что печатали (PDF, принтер) и чем смотрели. + +### English + +**Hatch: background colour** +- Hatches have a "Background color" property: in the Properties palette, the Hatch and Gradient dialog, and HATCHEDIT. Choose None, ByLayer, ByBlock, a standard colour, or any other colour. +- A background colour set in AutoCAD is read from the file and written back, so AutoCAD sees it too. Solid fills have no background. + +**Hebrew turning into Russian on the drawing** +- Found the cause. This drawing's SHX fonts (romans, txt, simplex, …) store letters by their Unicode codes. CADCraft took them for single-language fonts that keep Hebrew at codes 0xE0–0xFA and drew the glyphs found there, which in these fonts are Russian letters. Now Hebrew is looked up at those codes only in real Hebrew fonts (code pages 1255 and 862). Other fonts are looked up by Unicode, and a missing letter is drawn with CADCraft's built-in font. +- Fonts such as GIL, which draw Latin letters as Hebrew ones (for typing on an English keyboard), keep showing that way, as the font intends. + +**Special symbols** +- ⌀ (%%c), ° (%%d) and ± (%%p) show with every style and font. If an SHX font has no such sign, it is drawn with the built-in font. Some Hebrew fonts used to show "]" instead of ⌀. + +**Layouts of AutoCAD drawings** +- Found the cause of the shift. An AutoCAD viewport looks at its view centre offset by its "view target", and CADCraft ignored that offset. It no longer does: the drawings are back in place on the sheets (checked with "אריה צוק"). + +**Formulas at the command line** +- Wherever a distance, length, radius or number is asked for, you can type a formula starting with "=": =1200+350*2, =(2400-50)/3. It takes + − * /, parentheses, a minus before a number and a decimal comma. The history shows the result: "=1200+350*2 = 1900". +- A space inside a formula is a space, not Enter. + +**Choices next to the cursor** +- When a command asks you to choose between options (for example MIRROR: "Erase source objects? [Yes/No]"), a small box with the options appears next to the cursor. Click one, or move with ↑ ↓ and press Enter. The default option is already highlighted. Typing works as before. + +**Cursor** +- While panning with the middle mouse button, the cursor shows the Move icon. +- Over the paper of a layout, the crosshair turns black. + +**Batch Plot** +- While the window is open, the rest of the program is inactive (dimmed). +- Select several sheets with Ctrl+click, a range with Shift+click, a rectangle dragged with the mouse (start in the empty space below the rows), or all with Ctrl+A. Move, remove and duplicate act on all selected sheets. +- The list has columns "#", "Sheet", "Drawing" and "Paper" with separators. Names are cut to the column width and never overlap. + +**Undo and Redo** +- New Office 2010-style icons: a thick blue arc with a big arrowhead. +- A small arrow button beside Undo and Redo opens a list of recent steps (up to 100, with a scrollbar). Hovering highlights all steps that will be undone, and a click undoes (or redoes) all of them at once. + +**Plot Preview icon** +- The magnifier moved right and no longer covers the printer. + +**Not reproduced yet** +- Text printing as an outline without fill didn't happen here: in PDF, text and dimensions come out filled. Please send a screenshot or a file where you see it, and say how you printed (PDF or printer) and what you viewed it with. + +--- + ## 22.10.2026 (0.9.0-b12) ### Русский diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index acfb42b698..600bbf528a 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -21,11 +21,11 @@ pub use pick::{HatchPicks, PickMode}; pub fn specs() -> Vec { vec![ - CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\", scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION)} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), + CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\", scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION), background?: colour | \"None\"} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))), CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"), - CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), + CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], style?, background?: colour | \"None\", origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick) .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") .enabled(has_doc) @@ -280,6 +280,19 @@ struct HatchSettings { origin: Vec2, origin_mode: OriginMode, style: u8, + /// Background colour under the pattern (`background`; none by default). + background: Option, +} + +/// A `background` parameter: a colour name, ACI number or `r,g,b`; `"None"`, `""` or null for +/// none. `None` when absent or not a colour. +pub(crate) fn background_param(p: &Value) -> Option> { + match p.get("background")? { + Value::Null => Some(None), + Value::String(t) if t.trim().is_empty() || t.trim().eq_ignore_ascii_case("none") || t.trim() == "." => Some(None), + Value::String(t) => cadcraft_color::Color::parse(t.trim()).map(Some), + v => v.as_i64().and_then(|i| i16::try_from(i).ok()).map(|i| Some(cadcraft_color::Color::from_aci(i))), + } } impl HatchSettings { @@ -317,6 +330,7 @@ impl HatchSettings { style: str_param(p, "style") .and_then(island_style) .unwrap_or_else(|| s.doc().map_or(0, |d| d.header.i64("HPISLANDDETECTION", 0).clamp(0, 2) as u8)), + background: background_param(p).flatten(), } } fn hatch(&self, mut loops: Vec) -> EntityKind { @@ -335,7 +349,7 @@ impl HatchSettings { style: self.style, elevation: 0.0, gradient: self.gradient.clone(), - background: None, + background: if solid { None } else { self.background }, pattern_lines: patfile::lines_for(&self.pattern), }) } diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index eeeb2dbd33..d869243ba9 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -315,6 +315,9 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result { if let Some(st) = style { h.style = st; } + if let Some(bg) = super::background_param(p) { + h.background = bg; + } if origin.is_some() || mode.is_some() { h.origin = mode.unwrap_or_default().origin(&h.loops, origin.unwrap_or(h.origin)); } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 70b5a39ecf..8f9ac4b82c 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; textStyle (text, multiline text, multileaders); multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; textStyle (text, multiline text, multileaders); hatches: pattern, scale, angle, background (colour | \"None\"); multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -464,6 +464,17 @@ fn run_set(s: &mut Session, p: &Value) -> Result { if let Some(x) = num("angle") { h.angle = x.to_radians(); } + // Background colour: a colour fills the area under the pattern; "None" none. + match p.get("background") { + Some(Value::Null) => h.background = None, + Some(v) if v.as_str().is_some_and(|s| s.trim().eq_ignore_ascii_case("none") || s.trim().is_empty()) => h.background = None, + Some(v) => { + if let Some(c) = parse_color(v) { + h.background = Some(c); + } + } + None => {} + } } _ => {} } diff --git a/crates/engine/src/formula.rs b/crates/engine/src/formula.rs new file mode 100644 index 0000000000..d751fe9c8d --- /dev/null +++ b/crates/engine/src/formula.rs @@ -0,0 +1,130 @@ +//! Formulas typed at a prompt: `=1200+350*2`, `=(2400-50)/3`. A value starting with `=` is +//! worked out with `+`, `-`, `*`, `/`, parentheses and unary minus, and the result is the answer +//! (a distance, a length, a number of items...). + +/// Longest formula read. +const MAX_LEN: usize = 256; +/// Deepest nesting of parentheses and signs. +const MAX_DEPTH: usize = 32; + +/// The value of `text` when it is a formula (`=` then an expression); `None` when it is not one, +/// `Some(Err)` with the reason when it is one that can't be worked out. +pub fn eval(text: &str) -> Option> { + let body = text.trim().strip_prefix('=')?; + if body.len() > MAX_LEN { + return Some(Err("The formula is too long.".into())); + } + let mut p = Parser { s: body.as_bytes(), i: 0, depth: 0 }; + let v = p.expr().and_then(|v| { + p.ws(); + if p.i < p.s.len() { Err(format!("Unexpected \"{}\" in the formula.", &body[p.i..])) } else { Ok(v) } + }); + Some(v.and_then(|v| if v.is_finite() { Ok(v) } else { Err("The formula has no finite value (division by zero?).".into()) })) +} + +struct Parser<'a> { + s: &'a [u8], + i: usize, + depth: usize, +} + +impl Parser<'_> { + fn ws(&mut self) { + while self.s.get(self.i).is_some_and(u8::is_ascii_whitespace) { + self.i += 1; + } + } + fn peek(&mut self) -> Option { + self.ws(); + self.s.get(self.i).copied() + } + fn expr(&mut self) -> Result { + let mut v = self.term()?; + while let Some(c @ (b'+' | b'-')) = self.peek() { + self.i += 1; + let r = self.term()?; + v = if c == b'+' { v + r } else { v - r }; + } + Ok(v) + } + fn term(&mut self) -> Result { + let mut v = self.factor()?; + while let Some(c @ (b'*' | b'/' | b'x' | b'X')) = self.peek() { + self.i += 1; + let r = self.factor()?; + v = if c == b'/' { v / r } else { v * r }; + } + Ok(v) + } + fn factor(&mut self) -> Result { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err("The formula is nested too deeply.".into()); + } + let r = match self.peek() { + Some(b'-') => { + self.i += 1; + self.factor().map(|v| -v) + } + Some(b'+') => { + self.i += 1; + self.factor() + } + Some(b'(') => { + self.i += 1; + let v = self.expr()?; + if self.peek() != Some(b')') { + return Err("A \")\" is missing in the formula.".into()); + } + self.i += 1; + Ok(v) + } + Some(c) if c.is_ascii_digit() || c == b'.' || c == b',' => self.number(), + Some(_) => Err("The formula takes numbers, + - * / and parentheses.".into()), + None => Err("The formula ends too soon.".into()), + }; + self.depth -= 1; + r + } + /// A number; a comma is read as the decimal separator (`2,5`). + fn number(&mut self) -> Result { + let start = self.i; + while self.s.get(self.i).is_some_and(|c| c.is_ascii_digit() || *c == b'.' || *c == b',') { + self.i += 1; + } + // An exponent: 1e3, 2.5E-2. + if self.s.get(self.i).is_some_and(|c| *c == b'e' || *c == b'E') + && self.s.get(self.i + 1).is_some_and(|c| c.is_ascii_digit() || *c == b'-' || *c == b'+') + { + self.i += 2; + while self.s.get(self.i).is_some_and(u8::is_ascii_digit) { + self.i += 1; + } + } + let t = String::from_utf8_lossy(self.s.get(start..self.i).unwrap_or_default()).replace(',', "."); + t.parse::().map_err(|_| format!("\"{t}\" is not a number.")) + } +} + +#[cfg(test)] +mod tests { + use super::eval; + + #[test] + fn formulas_work_out_with_precedence_and_parentheses() { + assert_eq!(eval("=1200+350*2"), Some(Ok(1900.0))); + assert_eq!(eval("= (2400 - 50) / 2"), Some(Ok(1175.0))); + assert_eq!(eval("=-3*-2"), Some(Ok(6.0))); + assert_eq!(eval("=2,5*2"), Some(Ok(5.0))); + assert_eq!(eval("=10/4"), Some(Ok(2.5))); + assert_eq!(eval("=1e3/4"), Some(Ok(250.0))); + assert_eq!(eval("1200"), None); + } + + #[test] + fn bad_formulas_say_why_and_never_panic() { + for f in ["=", "=1+", "=(1+2", "=1/0", "=abc", "=1)2", &format!("={}", "(".repeat(500)), &format!("={}1", "-".repeat(100))] { + assert!(matches!(eval(f), Some(Err(_))), "{f}"); + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b37444c646..215d054b92 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod blockedit; pub mod cmd; pub mod doc_path; mod finite; +pub mod formula; pub mod grip_dims; pub mod grips; mod guard; @@ -1509,6 +1510,22 @@ impl Session { if tt.starts_with('\'') { return self.start(tt); } + // A formula (`=1200+350*2`) where a distance or number is asked: its value is the answer. + if (prompt.accept.number || prompt.accept.point) + && let Some(r) = formula::eval(tt) + { + return match r { + Ok(v) => { + let v = if v.fract() == 0.0 && v.abs() < 1e15 { format!("{v:.0}") } else { format!("{v}") }; + self.echo(format!("{tt} = {v}")); + self.typed(&v) + } + Err(e) => { + self.echo(e); + Ok(()) + } + }; + } // A LISP expression typed at a command's prompt: its value is the answer. // Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2"). if lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() { diff --git a/crates/engine/tests/formula_input.rs b/crates/engine/tests/formula_input.rs new file mode 100644 index 0000000000..c2d68c5040 --- /dev/null +++ b/crates/engine/tests/formula_input.rs @@ -0,0 +1,23 @@ +//! A formula typed where a distance or number is asked (`=1200+350*2`) is worked out first. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; + +#[test] +fn a_formula_answers_a_distance_prompt() { + let mut s = Session::new(); + s.cmdline("circle 0,0").unwrap(); + s.cmdline("=(10+2)*3/4").unwrap(); + let r = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Circle(c) = &e.kind { Some(c.radius) } else { None }).unwrap(); + assert!((r - 9.0).abs() < 1e-12, "{r}"); +} + +#[test] +fn a_bad_formula_is_reported_and_asks_again() { + let mut s = Session::new(); + s.cmdline("circle 0,0").unwrap(); + s.cmdline("=10+").unwrap(); + assert!(s.running.is_some(), "the prompt is still waiting"); + s.cmdline("=5").unwrap(); + assert!(s.running.is_none()); +} diff --git a/crates/fonts/src/shx.rs b/crates/fonts/src/shx.rs index f229dbd1da..9555e0f631 100644 --- a/crates/fonts/src/shx.rs +++ b/crates/fonts/src/shx.rs @@ -164,18 +164,71 @@ impl ShxFont { self.shapes.contains_key(&code) } + /// How many of `codes` the font draws. + fn count(&self, codes: std::ops::RangeInclusive) -> usize { + codes.filter(|c| self.shapes.contains_key(c)).count() + } + + /// A one-byte font with Hebrew letters at their Windows-1255 places (0xE0..0xFA) and not a + /// Cyrillic Windows-1251 font (which fills 0xC0..0xDF with capitals as well). + fn hebrew_1255(&self) -> bool { + self.kind != Kind::Unifont && self.count(0xE0..=0xFA) >= 20 && self.count(0xC0..=0xDF) < 16 + } + + /// A one-byte font with Hebrew letters at their DOS 862 places (0x80..0x9A) and not a + /// Cyrillic DOS 866 font (which also has small letters at 0xA0..0xAF). + fn hebrew_862(&self) -> bool { + self.kind != Kind::Unifont && self.count(0x80..=0x9A) >= 20 && self.count(0xA0..=0xAF) < 8 + } + /// The shape that draws `c`: its code point, or for a one-byte font a Hebrew letter at /// its Windows-1255 or DOS (862) position, and the old AutoCAD positions of °, ± and ⌀. pub fn code_for(&self, c: char) -> Option { let u = u32::from(c); let mut tries: Vec = vec![u]; + // Only a font that holds Hebrew there: a Cyrillic font has its letters at the same + // places (Windows-1251 0xC0..0xFF, DOS 866 0x80..0xAF), and Hebrew text must not turn + // into Russian. if (0x05D0..=0x05EA).contains(&u) { - tries.extend([u - 0x05D0 + 0xE0, u - 0x05D0 + 0x80]); + if self.hebrew_1255() { + tries.push(u - 0x05D0 + 0xE0); + } + if self.hebrew_862() { + tries.push(u - 0x05D0 + 0x80); + } } + // °, ± and ⌀: their Unicode places in a Unicode font; in a one-byte font AutoCAD's own + // places (127, 128, 129) unless those hold Hebrew letters (DOS 862), and never a + // Windows code page place, which other code pages use for letters (Ш, ר…). A font + // without them draws them from the built-in font. + let unicode = self.kind == Kind::Unifont; + let legacy = !unicode && !self.hebrew_862(); match c { - '°' => tries.extend([0xB0, 0x7F]), - '±' => tries.extend([0xB1, 0x80]), - '⌀' | '∅' | 'Ø' => tries.extend([0x2205, 0x2300, 0xD8, 0x81]), + '°' => { + if unicode { + tries.push(0xB0); + } + if legacy { + tries.push(0x7F); + } + } + '±' => { + if unicode { + tries.push(0xB1); + } + if legacy { + tries.push(0x80); + } + } + '⌀' | '∅' | 'Ø' => { + tries.extend([0x2205, 0x2300]); + if unicode { + tries.push(0xD8); + } + if legacy { + tries.push(0x81); + } + } _ => {} } tries.into_iter().find(|t| self.has(*t)) @@ -703,3 +756,36 @@ mod tests { assert!(f.glyph(65).is_some()); } } + +#[cfg(test)] +mod survey { + /// `CADCRAFT_SHX_DIR=… cargo test -p cadcraft-fonts survey -- --ignored --nocapture`: how each + /// font of a folder is read (a look at real fonts; not run normally). + #[test] + #[ignore = "needs a folder of fonts"] + fn survey_fonts() { + let Ok(dir) = std::env::var("CADCRAFT_SHX_DIR") else { return }; + let mut v: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.path()).collect(); + v.sort(); + for p in v { + let b = std::fs::read(&p).unwrap(); + let name = p.file_name().unwrap().to_string_lossy().to_string(); + match super::ShxFont::parse(&name, &b) { + Some(f) => println!( + "{name}: {:?} 1255={} 862={} E0..FA={} C0..DF={} 80..9A={} A0..AF={} U+05D0={} U+0430={} E0~430={}", + f.kind, + f.hebrew_1255(), + f.hebrew_862(), + f.count(0xE0..=0xFA), + f.count(0xC0..=0xDF), + f.count(0x80..=0x9A), + f.count(0xA0..=0xAF), + f.has(0x05D0), + f.has(0x0430), + f.glyph(0xE0).map(|g| g.strokes) == f.glyph(0x430).map(|g| g.strokes) + ), + None => println!("{name}: unreadable"), + } + } + } +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index cb91534569..1e68dfc562 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -20,6 +20,35 @@ use serde_json::Value; /// Registered application name of CADCraft's extended data. pub(crate) const APP: &str = "CADCRAFT"; +/// AutoCAD's hatch background colour xdata application (one `1071` colour value). +pub(crate) const HATCH_BACKGROUND_APP: &str = "HATCHBACKGROUNDCOLOR"; + +/// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index +/// colour in the low byte, 0xC0 ByLayer, 0xC1 ByBlock; `None` for none or anything else. +pub(crate) fn acad_color(v: i64) -> Option { + let v = v as u32; + match v >> 24 { + 0xC2 => Some(cadcraft_color::Color::True(cadcraft_color::Rgb((v >> 16) as u8, (v >> 8) as u8, v as u8))), + 0xC3 => match (v & 0xFF) as u8 { + 0 => None, + i => Some(cadcraft_color::Color::Index(i)), + }, + 0xC0 => Some(cadcraft_color::Color::ByLayer), + 0xC1 => Some(cadcraft_color::Color::ByBlock), + _ => None, + } +} + +/// [`acad_color`] the other way. +pub(crate) fn acad_color_value(c: cadcraft_color::Color) -> i64 { + let v: u32 = match c { + cadcraft_color::Color::True(cadcraft_color::Rgb(r, g, b)) => 0xC200_0000 | (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b), + cadcraft_color::Color::Index(i) => 0xC300_0000 | u32::from(i), + cadcraft_color::Color::ByLayer => 0xC000_0000, + cadcraft_color::Color::ByBlock => 0xC100_0000, + }; + i64::from(v as i32) +} /// Named-object-dictionary key of the constraint XRECORD. pub(crate) const CONSTRAINTS_KEY: &str = "CADCRAFT_CONSTRAINTS"; /// Named-object-dictionary key of the saved layer states XRECORD. diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index e4b4a4086f..f139937b48 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -485,7 +485,13 @@ fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> { center: t.p(10), width: t.fd(40, 1.0), height: t.fd(41, 1.0), - view_center: Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)), + // The view centre (12/22) is relative to the view target (17/27): AutoCAD often keeps + // the centre near zero and the target where the drawing is. + view_center: { + let target = Vec2::new(t.fd(17, 0.0), t.fd(27, 0.0)); + let target = if target.is_finite() { target } else { Vec2::ZERO }; + Vec2::new(t.fd(12, 0.0), t.fd(22, 0.0)) + target + }, view_height: t.fd(45, 1.0), id: t.i(69).unwrap_or(0) as u32, locked: t.i(90).unwrap_or(0) & 16384 != 0, @@ -884,12 +890,21 @@ fn pattern_definition(tags: &[Tag], scale: f64, angle: f64, origin: Vec2) -> Vec fn hatch_xdata(tags: &[Tag]) -> (Vec2, Option) { let x = crate::dxf_ext::xdata(tags, crate::dxf_ext::APP); let Some(at) = x.windows(2).position(|w| matches!(w, [m, o] if m.code == 1000 && m.str() == "HATCH" && o.code == 1011)) else { - return (Vec2::ZERO, None); + return (Vec2::ZERO, acad_background(tags)); }; let val = |k: usize, code: i32| x.get(at + k).filter(|t| t.code == code); let coord = |k: usize, code: i32| val(k, code).map(Tag::f64).filter(|v| v.is_finite()).unwrap_or(0.0); let origin = Vec2::new(coord(1, 1011), coord(2, 1021)); - (origin, val(4, 1000).and_then(|t| Color::parse(&t.str()))) + (origin, val(4, 1000).and_then(|t| Color::parse(&t.str())).or_else(|| acad_background(tags))) +} + +/// The background colour AutoCAD keeps in `HATCHBACKGROUNDCOLOR` xdata (`1071`). +fn acad_background(tags: &[Tag]) -> Option { + crate::dxf_ext::xdata(tags, crate::dxf_ext::HATCH_BACKGROUND_APP) + .iter() + .find(|t| t.code == 1071 || t.code == 1070) + .and_then(|t| t.str().trim().parse::().ok()) + .and_then(crate::dxf_ext::acad_color) } /// Gradient values missing from a file fall back to the GRADIENT command's defaults. @@ -1517,7 +1532,9 @@ fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) { if name.is_empty() || !(h.is_finite() && w.is_finite() && h > 0.0 && w > 0.0) || d.views.len() >= MAX_OBJECTS { continue; } - let center = t.p(10).xy(); + // The centre is relative to the view target (12). + let target = t.p(12).xy(); + let center = t.p(10).xy() + if target.is_finite() { target } else { Vec2::ZERO }; if !(center.x.is_finite() && center.y.is_finite()) { continue; } @@ -1584,7 +1601,9 @@ const MAX_VPORT_TILES: usize = 64; /// are fractions of the drawing area; unusable tiles are skipped. fn vport_record(d: &mut Drawing, t: &T) { let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default(); - let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.p(12).xy()); + // The view centre (12) is relative to the view target (17). + let target = t.p(17).xy(); + let (min, max, center) = (t.p(10).xy(), t.p(11).xy(), t.p(12).xy() + if target.is_finite() { target } else { Vec2::ZERO }); let height = t.fd(40, 0.0); let unit = |v: f64| v.is_finite() && (-1e-9..=1.0 + 1e-9).contains(&v); let ok = [min.x, min.y, max.x, max.y].into_iter().all(unit) diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index bbccc4438f..9b0595cb66 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -1219,6 +1219,11 @@ fn hatch_xdata(w: &mut W, h: &Hatch) { w.s(1000, "HATCH"); w.p(1011, h.origin.to3(0.0)); w.s(1000, h.background.map(Color::name).unwrap_or_default()); + // As AutoCAD keeps it, so AutoCAD shows the background too. + if let Some(c) = h.background { + w.s(1001, dxf_ext::HATCH_BACKGROUND_APP); + w.i(1071, dxf_ext::acad_color_value(c)); + } } /// What happens to the anonymous `*D` blocks read from a file (#495): a dimension that still @@ -2032,7 +2037,8 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.f(146, 0.0); } w.s(0, "ENDTAB"); - let apps = ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP]; + let apps = + ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP, dxf_ext::HATCH_BACKGROUND_APP]; let th = table_head(&mut w, "APPID", apps.len()); for app in apps { record_head(&mut w, "APPID", &th, "AcDbRegAppTableRecord"); diff --git a/crates/io/tests/hatch_background.rs b/crates/io/tests/hatch_background.rs new file mode 100644 index 0000000000..d545f9b2a8 --- /dev/null +++ b/crates/io/tests/hatch_background.rs @@ -0,0 +1,49 @@ +//! A hatch's background colour is written as AutoCAD keeps it (HATCHBACKGROUNDCOLOR xdata) and +//! read back from it. + +use cadcraft_color::{Color, Rgb}; +use cadcraft_doc::*; +use cadcraft_geom::{PolyVertex, Vec2}; + +fn hatch(bg: Option) -> EntityKind { + let sq = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]; + EntityKind::Hatch(Hatch { + pattern: "ANSI31".into(), + solid: false, + loops: vec![HatchLoop { vertices: sq.iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(), outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: bg, + pattern_lines: Vec::new(), + }) +} + +#[test] +fn background_colour_round_trips_and_is_written_for_autocad() { + for bg in [Color::Index(3), Color::True(Rgb(250, 240, 10))] { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(bg))).unwrap(); + let text = cadcraft_io::write_dxf(&d); + assert!(text.contains("HATCHBACKGROUNDCOLOR")); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, Some(bg)); + } +} + +#[test] +fn autocads_background_xdata_alone_gives_the_colour() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(Color::Index(5)))).unwrap(); + // Without CADCraft's own xdata (a file AutoCAD wrote): only HATCHBACKGROUNDCOLOR is left. + let text = cadcraft_io::write_dxf(&d).replace("1000\r\nHATCH\r\n", "1000\r\nOTHER\r\n").replace("1000\nHATCH\n", "1000\nOTHER\n"); + assert!(text.contains("OTHER"), "CADCraft's own background is out of the way"); + let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, Some(Color::Index(5))); +} diff --git a/crates/io/tests/paperview_marker.rs b/crates/io/tests/paperview_marker.rs index 4159e14c39..5f1c464618 100644 --- a/crates/io/tests/paperview_marker.rs +++ b/crates/io/tests/paperview_marker.rs @@ -40,3 +40,36 @@ fn viewport_with_a_layer_named_paperview_survives_dxf_roundtrip() { assert_eq!(vps[0].frozen_layers, ["PAPERVIEW"]); assert_eq!(vps[1].layer_colors, [("PAPERVIEW".to_string(), Color::Index(1))]); } + +#[test] +fn a_viewport_looks_at_its_view_target_plus_its_view_centre() { + // AutoCAD often writes the view centre (12/22) near zero and the view target (17/27) where + // the drawing is: the model point at the viewport's middle is their sum. + let mut d = Drawing::new_metric(); + let sheet = Space::Paper(d.layouts[0].name.clone()); + d.add(&sheet, Common::default(), viewport(2, vec![], vec![])).unwrap(); + let text = cadcraft_io::write_dxf(&d); + // The viewport's view centre 10,10 becomes 2,3 with the target at 8,7: rewrite the group + // values after "12" and "22" in the viewport whose centre (10) is 50. + let lines: Vec<&str> = text.lines().collect(); + let mut out: Vec = lines.iter().map(|l| l.to_string()).collect(); + let start = lines.windows(2).position(|w| w[0].trim() == "10" && w[1].trim().parse::().ok() == Some(50.0)).expect("the viewport"); + let mut done = false; + let mut i = start; + while i + 1 < lines.len() && !done { + if lines[i].trim() == "12" { + out[i + 1] = "2.0".into(); + } + if lines[i].trim() == "22" { + out[i + 1] = "3.0".into(); + out[i + 1].push_str("\n 17\n8.0\n 27\n7.0"); + done = true; + } + i += 2; + } + assert!(done, "the writer's view centre groups"); + let edited = out.join("\n"); + let back = cadcraft_io::read_dxf(edited.as_bytes()).unwrap(); + let v = viewports(&back.layouts[0]).into_iter().find(|v| v.id == 2).unwrap(); + assert!((v.view_center.x - 10.0).abs() < 1e-9 && (v.view_center.y - 10.0).abs() < 1e-9, "{:?}", v.view_center); +} diff --git a/crates/ui-egui/src/batchplot.rs b/crates/ui-egui/src/batchplot.rs index da81a1994e..0cee7d3786 100644 --- a/crates/ui-egui/src/batchplot.rs +++ b/crates/ui-egui/src/batchplot.rs @@ -22,8 +22,14 @@ struct State { sheets: Vec, /// The drawing the list was filled from when the window opened. filled_for: Option, - selected: Option, - dragging: Option, + /// The picked rows (Ctrl and Shift pick several). + selected: Vec, + /// Where Shift+click extends from. + anchor: Option, + /// The picked rows are being dragged. + dragging: bool, + /// Where a selection rectangle started (in the list's empty space). + band_from: Option, /// The drawing whose sheets the Add section shows. add_from: Option, separate: bool, @@ -74,19 +80,47 @@ pub fn publish_params(app: &CadApp, sheets: &[Sheet], combine: bool, path: Optio Ok(p) } +/// Move the sheets at `picked` (any order) as one block to stand before `slot` (0..=len), keeping +/// their order; the indices they end up at. +pub fn move_sheets(v: &mut Vec, picked: &[usize], slot: usize) -> Vec { + let mut idx: Vec = picked.iter().copied().filter(|i| *i < v.len()).collect(); + idx.sort_unstable(); + idx.dedup(); + if idx.is_empty() { + return Vec::new(); + } + let before = idx.iter().filter(|i| **i < slot).count(); + let moved: Vec = idx.iter().filter_map(|i| v.get(*i).cloned()).collect(); + for i in idx.iter().rev() { + v.remove(*i); + } + let at = slot.saturating_sub(before).min(v.len()); + for (k, sh) in moved.into_iter().enumerate() { + v.insert(at + k, sh); + } + (at..at + idx.len()).collect() +} + /// What a click asked for, applied once the list is drawn. enum Act { - Select(usize), - Move(usize, usize), - Duplicate(usize), - Remove(usize), + /// A click on row `i`: with Ctrl it toggles, with Shift it extends from the anchor. + Click(usize, egui::Modifiers), + /// A rubber-band rectangle picked these rows (added to the selection with Ctrl). + Band(Vec, bool), + SelectAll, + /// The selected rows to stand before this slot. + MoveTo(usize), + Up, + Down, + Duplicate, + Remove, Add(Sheet), AddAll(String), Clear, Plot, } -/// File ▸ Batch Plot: the print manager window. +/// File ▸ Batch Plot: the print manager window. While it is open the rest of the program waits. pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); let current = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); @@ -94,12 +128,12 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if st.filled_for.as_deref() != Some(current.as_str()) { st.sheets = app.session.doc().map(|d| sheets_of(d, ¤t)).unwrap_or_default(); st.filled_for = Some(current.clone()); - st.selected = None; + st.selected.clear(); st.add_from = Some(current.clone()); st.note = None; } + st.selected.retain(|i| *i < st.sheets.len()); let titles: Vec = app.session.docs.iter().map(|d| d.title.clone()).collect(); - let several = st.sheets.iter().any(|s| s.drawing != current) || titles.len() > 1; let paper = |s: &Sheet| -> String { let Some(d) = app.session.docs.iter().find(|d| d.title == s.drawing) else { return crate::tl!("closed").to_string() }; if s.layout == "Model" { @@ -111,10 +145,17 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let can_plot = app.services.pick_save.is_some(); let mut act: Option = None; let mut close = false; + // Modal: a dimmed backdrop over the whole program takes every click outside the window. + let screen = ctx.content_rect(); + egui::Area::new(egui::Id::new("cc_batch_plot_backdrop")).order(egui::Order::Middle).fixed_pos(screen.min).interactable(true).show(ctx, |ui| { + let (r, _) = ui.allocate_exact_size(screen.size(), Sense::click_and_drag()); + ui.painter().rect_filled(r, 0.0, egui::Color32::from_black_alpha(110)); + }); egui::Window::new(crate::tl!("Batch Plot")) .id(egui::Id::new("cc_batch_plot_window")) + .order(egui::Order::Foreground) .open(open) - .default_size(vec2(680.0, 500.0)) + .default_size(vec2(700.0, 520.0)) .min_size(vec2(520.0, 380.0)) .resizable(true) .show(ctx, |ui| { @@ -125,47 +166,100 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let list_h = (ui.available_height() - 190.0).max(140.0); ui.allocate_ui_with_layout(vec2(list_w, list_h), egui::Layout::top_down(egui::Align::LEFT), |ui| { egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(2.0).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("cc_batch_list").auto_shrink([false, false]).max_height(list_h - 6.0).show(ui, |ui| { - let w = list_w - 10.0; + let w = list_w - 10.0; + // Columns: number, sheet, drawing, paper, with a separator between each. + let cols = [34.0_f32, (w - 34.0) * 0.36, (w - 34.0) * 0.34, (w - 34.0) * 0.30]; + let col_x = |k: usize| cols.iter().take(k).sum::(); + let (hr, _) = ui.allocate_exact_size(vec2(w, 20.0), Sense::hover()); + ui.painter().rect_filled(hr, 0.0, t.chrome_dark); + for (k, title) in ["#", crate::tl!("Sheet"), crate::tl!("Drawing"), crate::tl!("Paper")].into_iter().enumerate() { + let cell = Rect::from_min_size(pos2(hr.left() + col_x(k), hr.top()), vec2(cols[k], hr.height())); + ui.painter().with_clip_rect(cell.shrink2(vec2(3.0, 0.0))).text( + pos2(cell.left() + 5.0, cell.center().y), + egui::Align2::LEFT_CENTER, + title, + crate::theme::small(), + t.text_dim, + ); + if k > 0 { + ui.painter().vline(cell.left(), hr.y_range(), Stroke::new(1.0, t.border)); + } + } + let body_h = list_h - 30.0; + egui::ScrollArea::vertical().id_salt("cc_batch_list").auto_shrink([false, false]).max_height(body_h).show(ui, |ui| { ui.set_width(w); let mut rects: Vec = Vec::new(); for (i, (layout, drawing, paper)) in rows.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(w, 24.0), Sense::click_and_drag()); rects.push(r); - let on = st.selected == Some(i); + let on = st.selected.contains(&i); if on { ui.painter().rect_filled(r, 2.0, t.accent.gamma_multiply(0.35)); } else if resp.hovered() { ui.painter().rect_filled(r, 2.0, t.control_hover.gamma_multiply(0.6)); } - let p = ui.painter().with_clip_rect(r); let y = r.center().y; - // A grip that shows rows can be dragged. + let cell = |k: usize| Rect::from_min_size(pos2(r.left() + col_x(k), r.top()), vec2(cols[k], r.height())); + // A grip that shows rows can be dragged, and the number. + let c0 = cell(0); for dy in [-4.0, 0.0, 4.0] { - p.hline((r.left() + 5.0)..=(r.left() + 13.0), y + dy, Stroke::new(1.0, t.text_faint)); + ui.painter().hline((c0.left() + 3.0)..=(c0.left() + 9.0), y + dy, Stroke::new(1.0, t.text_faint)); } - p.text(pos2(r.left() + 20.0, y), egui::Align2::LEFT_CENTER, format!("{}.", i + 1), crate::theme::body(), t.text_dim); - p.text(pos2(r.left() + 48.0, y), egui::Align2::LEFT_CENTER, crate::i18n::t(layout), crate::theme::body(), t.text); - if several { - // Hebrew names read right to left, as in the file manager. - let job = crate::i18n::job(drawing, crate::theme::small(), t.text_dim); - let g = ui.ctx().fonts_mut(|f| f.layout_job(job)); - p.galley(pos2(r.left() + w * 0.45, y - g.size().y / 2.0), g, t.text_dim); + ui.painter().with_clip_rect(c0).text( + pos2(c0.left() + 12.0, y), + egui::Align2::LEFT_CENTER, + format!("{}", i + 1), + crate::theme::small(), + t.text_dim, + ); + let c1 = cell(1); + ui.painter().with_clip_rect(c1.shrink2(vec2(3.0, 0.0))).text( + pos2(c1.left() + 5.0, y), + egui::Align2::LEFT_CENTER, + crate::i18n::t(layout), + crate::theme::body(), + t.text, + ); + // Hebrew names read right to left, as in the file manager. + let c2 = cell(2); + let job = crate::i18n::job(drawing, crate::theme::small(), t.text_dim); + let g = ui.ctx().fonts_mut(|f| f.layout_job(job)); + ui.painter().with_clip_rect(c2.shrink2(vec2(3.0, 0.0))).galley( + pos2(c2.left() + 5.0, y - g.size().y / 2.0), + g, + t.text_dim, + ); + let c3 = cell(3); + ui.painter().with_clip_rect(c3.shrink2(vec2(3.0, 0.0))).text( + pos2(c3.left() + 5.0, y), + egui::Align2::LEFT_CENTER, + paper, + crate::theme::small(), + t.text_dim, + ); + for k in 1..4 { + ui.painter().vline(cell(k).left(), r.y_range(), Stroke::new(1.0, t.border.gamma_multiply(0.6))); } - p.text(pos2(r.right() - 6.0, y), egui::Align2::RIGHT_CENTER, paper, crate::theme::small(), t.text_dim); - if resp.clicked() || resp.drag_started() { - act = Some(Act::Select(i)); + if resp.clicked() { + act = Some(Act::Click(i, ui.input(|inp| inp.modifiers))); } if resp.drag_started() { - st.dragging = Some(i); + // Dragging an unselected row drags it alone. + if !on { + act = Some(Act::Click(i, egui::Modifiers::NONE)); + } + st.dragging = true; } resp.context_menu(|ui| { + if !on { + act = Some(Act::Click(i, egui::Modifiers::NONE)); + } if ui.button(crate::tl!("Duplicate")).clicked() { - act = Some(Act::Duplicate(i)); + act = Some(Act::Duplicate); ui.close(); } if ui.button(crate::tl!("Delete")).clicked() { - act = Some(Act::Remove(i)); + act = Some(Act::Remove); ui.close(); } }); @@ -173,8 +267,28 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { if rows.is_empty() { ui.label(RichText::new(crate::tl!("No sheets. Add sheets below.")).color(t.text_dim)); } - // Dragging a row: a line where it will land. - if let Some(from) = st.dragging { + // The space below the rows: a drag there draws a selection rectangle. + let rest = ui.available_size().max(vec2(w, 30.0)); + let (blank, bresp) = ui.allocate_exact_size(vec2(w, rest.y), Sense::click_and_drag()); + if bresp.clicked() && !ui.input(|i| i.modifiers.command || i.modifiers.shift) { + act = Some(Act::Band(Vec::new(), false)); + } + if bresp.drag_started() { + st.band_from = bresp.interact_pointer_pos(); + } + if let (Some(from), Some(to)) = (st.band_from, ui.ctx().pointer_latest_pos()) { + let band = Rect::from_two_pos(from, to); + ui.painter().rect_filled(band, 0.0, t.accent.gamma_multiply(0.15)); + ui.painter().rect_stroke(band, 0.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + let hit: Vec = rects.iter().enumerate().filter(|(_, r)| r.intersects(band)).map(|(i, _)| i).collect(); + if ui.input(|i| i.pointer.any_released()) { + act = Some(Act::Band(hit, ui.input(|i| i.modifiers.command))); + st.band_from = None; + } + } + let _ = blank; + // Dragging rows: a line where they will land. + if st.dragging { let pointer = ui.ctx().pointer_latest_pos(); let slot = pointer.map(|p| rects.iter().position(|r| p.y < r.center().y).unwrap_or(rects.len())); if let Some(slot) = slot { @@ -185,13 +299,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); if ui.input(|i| i.pointer.any_released()) { - if let Some(slot) = slot - && slot != from - && slot != from + 1 - { - act = Some(Act::Move(from, slot)); + if let Some(slot) = slot { + act = Some(Act::MoveTo(slot)); } - st.dragging = None; + st.dragging = false; } } }); @@ -200,8 +311,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { // The order and list buttons. ui.vertical(|ui| { ui.set_width(180.0); - let sel = st.selected.filter(|i| *i < st.sheets.len()); + let any = !st.selected.is_empty(); let n = st.sheets.len(); + let first = st.selected.iter().min().copied().unwrap_or(0); + let last = st.selected.iter().max().copied().unwrap_or(0); let row = |ui: &mut egui::Ui, icon: Icon, label: &str, enabled: bool| -> bool { ui.add_enabled_ui(enabled, |ui| { ui.horizontal(|ui| { @@ -222,40 +335,34 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }) .inner }; - if row(ui, Icon::MoveTop, crate::tl!("Move to Top"), sel.is_some_and(|i| i > 0)) - && let Some(i) = sel - { - act = Some(Act::Move(i, 0)); + if row(ui, Icon::MoveTop, crate::tl!("Move to Top"), any && first > 0) { + act = Some(Act::MoveTo(0)); } - if row(ui, Icon::MoveUp, crate::tl!("Move Higher"), sel.is_some_and(|i| i > 0)) - && let Some(i) = sel - { - act = Some(Act::Move(i, i.saturating_sub(1))); + if row(ui, Icon::MoveUp, crate::tl!("Move Higher"), any && first > 0) { + act = Some(Act::Up); } - if row(ui, Icon::MoveDown, crate::tl!("Move Lower"), sel.is_some_and(|i| i + 1 < n)) - && let Some(i) = sel - { - act = Some(Act::Move(i, i + 2)); + if row(ui, Icon::MoveDown, crate::tl!("Move Lower"), any && last + 1 < n) { + act = Some(Act::Down); } - if row(ui, Icon::MoveBottom, crate::tl!("Move to Bottom"), sel.is_some_and(|i| i + 1 < n)) - && let Some(i) = sel - { - act = Some(Act::Move(i, n)); + if row(ui, Icon::MoveBottom, crate::tl!("Move to Bottom"), any && last + 1 < n) { + act = Some(Act::MoveTo(n)); } ui.add_space(6.0); - if row(ui, Icon::Copy, crate::tl!("Duplicate"), sel.is_some()) - && let Some(i) = sel - { - act = Some(Act::Duplicate(i)); + if row(ui, Icon::Copy, crate::tl!("Duplicate"), any) { + act = Some(Act::Duplicate); } - if row(ui, Icon::Erase, crate::tl!("Delete"), sel.is_some()) - && let Some(i) = sel - { - act = Some(Act::Remove(i)); + if row(ui, Icon::Erase, crate::tl!("Delete"), any) { + act = Some(Act::Remove); } if row(ui, Icon::Close, crate::tl!("Clear List"), n > 0) { act = Some(Act::Clear); } + ui.add_space(4.0); + ui.label( + RichText::new(crate::tl!("Ctrl and Shift pick several sheets; drag in the empty space to pick with a rectangle.")) + .small() + .color(t.text_dim), + ); }); }); ui.add_space(6.0); @@ -313,25 +420,89 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } ui.label(RichText::new(format!("{} {}", st.sheets.len(), crate::tl!("sheets"))).color(t.text_dim)); }); + // Ctrl+A picks every sheet. + if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::A)) { + act = Some(Act::SelectAll); + } }); + let n = st.sheets.len(); match act { - Some(Act::Select(i)) => st.selected = Some(i), - Some(Act::Move(from, slot)) => st.selected = move_sheet(&mut st.sheets, from, slot), - Some(Act::Duplicate(i)) => { - if let Some(s) = st.sheets.get(i).cloned() { - st.sheets.insert(i + 1, s); - st.selected = Some(i + 1); + Some(Act::Click(i, m)) => { + if m.shift { + let a = st.anchor.unwrap_or(i).min(n.saturating_sub(1)); + let (lo, hi) = (a.min(i), a.max(i)); + if !m.command { + st.selected.clear(); + } + for k in lo..=hi { + if !st.selected.contains(&k) { + st.selected.push(k); + } + } + } else if m.command { + if let Some(p) = st.selected.iter().position(|k| *k == i) { + st.selected.remove(p); + } else { + st.selected.push(i); + } + st.anchor = Some(i); + } else { + st.selected = vec![i]; + st.anchor = Some(i); + } + } + Some(Act::Band(hit, add)) => { + if !add { + st.selected.clear(); + } + for k in hit { + if !st.selected.contains(&k) { + st.selected.push(k); + } + } + st.anchor = st.selected.first().copied(); + } + Some(Act::SelectAll) => st.selected = (0..n).collect(), + Some(Act::MoveTo(slot)) => { + let picked = st.selected.clone(); + st.selected = move_sheets(&mut st.sheets, &picked, slot); + } + Some(Act::Up) => { + let first = st.selected.iter().min().copied().unwrap_or(0); + let picked = st.selected.clone(); + st.selected = move_sheets(&mut st.sheets, &picked, first.saturating_sub(1)); + } + Some(Act::Down) => { + let last = st.selected.iter().max().copied().unwrap_or(0); + let picked = st.selected.clone(); + st.selected = move_sheets(&mut st.sheets, &picked, (last + 2).min(n)); + } + Some(Act::Duplicate) => { + // Each picked sheet gets its copy right after the block of picked sheets. + let mut idx = st.selected.clone(); + idx.sort_unstable(); + let copies: Vec = idx.iter().filter_map(|i| st.sheets.get(*i).cloned()).collect(); + let at = idx.last().map_or(n, |l| l + 1); + let k = copies.len(); + for (j, c) in copies.into_iter().enumerate() { + st.sheets.insert(at + j, c); } + st.selected = (at..at + k).collect(); } - Some(Act::Remove(i)) => { - if i < st.sheets.len() { - st.sheets.remove(i); - st.selected = if st.sheets.is_empty() { None } else { Some(i.min(st.sheets.len() - 1)) }; + Some(Act::Remove) => { + let mut idx = st.selected.clone(); + idx.sort_unstable(); + idx.dedup(); + for i in idx.iter().rev() { + if *i < st.sheets.len() { + st.sheets.remove(*i); + } } + st.selected = idx.first().filter(|_| !st.sheets.is_empty()).map(|f| vec![(*f).min(st.sheets.len() - 1)]).unwrap_or_default(); } Some(Act::Add(s)) => { st.sheets.push(s); - st.selected = Some(st.sheets.len() - 1); + st.selected = vec![st.sheets.len() - 1]; } Some(Act::AddAll(title)) => { if let Some(d) = app.session.docs.iter().find(|d| d.title == title) { @@ -340,7 +511,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } Some(Act::Clear) => { st.sheets.clear(); - st.selected = None; + st.selected.clear(); } Some(Act::Plot) => { let stem = std::path::Path::new(¤t) @@ -362,7 +533,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } None => {} } - if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) && st.dragging.is_none() { + if close || ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !st.dragging { *open = false; } if *open { @@ -375,7 +546,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { #[cfg(test)] mod tests { - use super::{Sheet, move_sheet}; + use super::{Sheet, move_sheet, move_sheets}; fn s(n: &str) -> Sheet { Sheet { drawing: "A.dwg".into(), layout: n.into() } @@ -392,4 +563,16 @@ mod tests { assert_eq!(v.iter().map(|x| x.layout.as_str()).collect::>(), ["1", "3", "2", "4"]); assert_eq!(move_sheet(&mut v, 9, 0), None); } + + #[test] + fn several_sheets_move_as_a_block() { + let names = |v: &[Sheet]| v.iter().map(|x| x.layout.clone()).collect::>().join(""); + let mut v = vec![s("1"), s("2"), s("3"), s("4"), s("5")]; + assert_eq!(move_sheets(&mut v, &[3, 1], 0), vec![0, 1]); + assert_eq!(names(&v), "24135"); + assert_eq!(move_sheets(&mut v, &[0, 1], 5), vec![3, 4]); + assert_eq!(names(&v), "13524"); + assert_eq!(move_sheets(&mut v, &[2], 1), vec![1]); + assert_eq!(names(&v), "15324"); + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2f72530016..e6cd859ed9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1870,9 +1870,19 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { // Crosshair cursor. if inside { // Hide the OS cursor under the drawn crosshair, unless assistive tech needs it (#39). - ui.ctx().set_cursor_icon(if app.ui.system_cursor { egui::CursorIcon::Crosshair } else { egui::CursorIcon::None }); - if let Some(hp) = hover_pos { - draw_crosshair(app, &painter, rect, hp, selecting); + // Panning with the middle button: the Move (four arrows) cursor instead of the crosshair. + let panning = app.canvas.pan_last.is_some() && middle_down; + if panning { + ui.ctx().set_cursor_icon(egui::CursorIcon::Move); + } else { + ui.ctx().set_cursor_icon(if app.ui.system_cursor { egui::CursorIcon::Crosshair } else { egui::CursorIcon::None }); + } + if let Some(hp) = hover_pos + && !panning + { + // Over the white paper of a layout the crosshair is black. + let on_paper = sheet.is_some_and(|s| s.bounds().contains(xf.to_world(hp))); + draw_crosshair(app, &painter, rect, hp, selecting, on_paper); } if !app.session.settings.dynmode && !app.cmd.buffer.is_empty() @@ -2055,8 +2065,8 @@ fn pickbox_half(pickbox: f64) -> Option { (half.is_finite() && half >= 1.0).then_some(half) } -fn draw_crosshair(app: &CadApp, p: &egui::Painter, rect: Rect, at: Pos2, pickbox: bool) { - let st = Stroke::new(1.0, Tokens::get().crosshair); +fn draw_crosshair(app: &CadApp, p: &egui::Painter, rect: Rect, at: Pos2, pickbox: bool, on_paper: bool) { + let st = Stroke::new(1.0, if on_paper { egui::Color32::BLACK } else { Tokens::get().crosshair }); let len = (rect.height() * app.session.settings.cursorsize as f32 / 100.0).max(12.0); let pb = if pickbox { pickbox_half(app.session.settings.pickbox) } else { None }; let gap = pb.unwrap_or(0.0); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index c136b70326..f8ce35a1c1 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -33,6 +33,9 @@ pub struct CmdLine { pub option_rows: Vec<(Rect, String)>, /// Where the Dynamic Input tooltip stays while the options menu is open. pub options_anchor: Option, + /// The prompt (message and keywords) the options menu last opened by itself for: it opens + /// once per prompt, so closing it (Escape, typing) keeps it closed. + options_auto: Option<(String, Vec)>, } /// The most history lines the command line shows above its bar. @@ -200,6 +203,29 @@ fn options_still_fit(app: &mut CadApp) { if app.cmd.options.as_ref().is_some_and(|m| !on || !m.fits(&kws)) { app.cmd.options = None; } + // A prompt that only asks to choose (Yes/No, an option list) shows its options by the + // cursor at once: click one, or move with the arrows and press Enter. + let Some(prompt) = app.session.current_prompt() else { + app.cmd.options_auto = None; + return; + }; + let key = (prompt.message.clone(), prompt.keywords.clone()); + let choose = !prompt.keywords.is_empty() && !prompt.accept.point && !prompt.accept.select; + if on + && choose + && app.cmd.options.is_none() + && app.cmd.buffer.is_empty() + && app.cmd.history_pos.is_none() + && app.cmd.options_auto.as_ref() != Some(&key) + { + if let Some(mut m) = crate::dyninput::OptionsMenu::open(&prompt.keywords) { + if let Some(i) = prompt.default.as_ref().and_then(|d| prompt.keywords.iter().position(|k| k.eq_ignore_ascii_case(d))) { + m.index = i; + } + app.cmd.options = Some(m); + } + app.cmd.options_auto = Some(key); + } } /// Down Arrow at a prompt with keywords (Dynamic Input on, DYNPROMPT on, not browsing the @@ -249,7 +275,8 @@ pub struct KeyPress { /// Handle keyboard input destined for the command line (when no text field has focus). pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { - if ctx.egui_wants_keyboard_input() { + // A modal window (Batch Plot) has the keyboard. + if ctx.egui_wants_keyboard_input() || app.ui.dialog.as_deref() == Some("publish") { return; } let events = ctx.input(|i| i.events.clone()); @@ -294,7 +321,8 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { egui::Event::Text(t) => { if t == "\t" { tab(app); - } else if t == " " && !text_prompt { + } else if t == " " && !text_prompt && !app.cmd.buffer.trim_start().starts_with('=') { + // Space is Enter, except inside a formula (`=1200 + 350`). submit(app); } else { app.cmd.buffer.push_str(&t); diff --git a/crates/ui-egui/src/hatchdlg.rs b/crates/ui-egui/src/hatchdlg.rs index 769b79e9d0..47cc1740ed 100644 --- a/crates/ui-egui/src/hatchdlg.rs +++ b/crates/ui-egui/src/hatchdlg.rs @@ -45,6 +45,8 @@ pub struct Fill { pub associative: bool, /// Island detection: 0 normal, 1 outer, 2 ignore. pub style: u8, + /// Background colour under a pattern (none: the drawing shows through). + pub background: Option, } /// The dialog while open (and while a pick it started runs). @@ -96,6 +98,7 @@ pub fn create_state(d: &Drawing, uid: u64, gradient: bool) -> HatchDlgState { origin_mode: origin_mode.into(), associative: h.i64("HPASSOC", 1) != 0, style: u8::try_from(h.i64("HPISLANDDETECTION", 0).clamp(0, 2)).unwrap_or(0), + background: None, }; HatchDlgState { opened: fill.clone(), @@ -128,6 +131,7 @@ pub fn edit_state(d: &Drawing, uid: u64, handles: Vec) -> Option Option<(&'static str, Value)> { p.insert("associative".into(), json!(f.associative)); p.insert("separate".into(), json!(st.separate)); p.insert("style".into(), json!(style_name(f.style))); + if let (Some(c), false) = (f.background, f.gradient) { + p.insert("background".into(), json!(c.name())); + } match (f.specified, f.origin) { (true, Some(o)) => p.insert("origin".into(), json!(o)), (true, None) => p.insert("originMode".into(), json!(f.origin_mode)), @@ -232,6 +239,9 @@ pub fn ok_call(st: &HatchDlgState) -> Option<(&'static str, Value)> { if f.style != o.style { p.insert("style".into(), json!(style_name(f.style))); } + if f.background != o.background && !f.gradient { + p.insert("background".into(), json!(f.background.map_or_else(|| "None".to_string(), |c| c.name()))); + } if f.specified { match f.origin { Some(q) => p.insert("origin".into(), json!(q)), @@ -391,6 +401,66 @@ enum Action { BrowseFolder, } +/// The hatch background colour picker: None, ByLayer/ByBlock, the standard colours and any +/// colour; the choice as HATCH takes it (a colour name or `"None"`). +pub fn background_menu(ui: &mut egui::Ui, current: Option) -> Option { + let shown = match current { + None => crate::tl!("None").to_string(), + Some(c) => crate::i18n::t(&c.name()).to_string(), + }; + let mut out = None; + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover()); + match current { + Some(c) => { + let rgb = c.resolve(Color::Index(7), Color::Index(7)); + ui.painter().rect_filled(r, 2.0, egui::Color32::from_rgb(rgb.0, rgb.1, rgb.2)); + } + None => { + ui.painter().rect_stroke(r, 2.0, egui::Stroke::new(1.0, crate::theme::Tokens::get().text_dim), egui::StrokeKind::Inside); + } + } + ui.menu_button(shown, |ui| { + if ui.button(crate::tl!("None")).clicked() { + out = Some("None".to_string()); + ui.close(); + } + ui.separator(); + for (n, c) in [ + ("ByLayer", Color::ByLayer), + ("ByBlock", Color::ByBlock), + ("Red", Color::Index(1)), + ("Yellow", Color::Index(2)), + ("Green", Color::Index(3)), + ("Cyan", Color::Index(4)), + ("Blue", Color::Index(5)), + ("Magenta", Color::Index(6)), + ("White", Color::Index(7)), + ("Color 8", Color::Index(8)), + ("Color 9", Color::Index(9)), + ] { + if ui.button(crate::i18n::t(n)).clicked() { + out = Some(c.name()); + ui.close(); + } + } + ui.separator(); + // Any colour. + let mut rgb = match current { + Some(Color::True(c)) => [c.0, c.1, c.2], + _ => [255, 255, 255], + }; + ui.horizontal(|ui| { + ui.label(crate::tl!("Other color")); + if ui.color_edit_button_srgb(&mut rgb).changed() { + out = Some(Color::True(cadcraft_color::Rgb(rgb[0], rgb[1], rgb[2])).name()); + } + }); + }); + }); + out +} + fn shape_label(name: &str) -> &'static str { match name { "CYLINDER" => crate::tl!("Cylinder"), @@ -610,6 +680,14 @@ fn options_ui(ui: &mut egui::Ui, st: &mut HatchDlgState, action: &mut Action) { if st.edit.is_empty() { ui.checkbox(&mut st.separate, crate::tl!("Create separate hatches")); } + if !st.fill.gradient { + ui.horizontal(|ui| { + ui.label(crate::tl!("Background color")); + if let Some(v) = background_menu(ui, st.fill.background) { + st.fill.background = if v == "None" { None } else { Color::parse(&v) }; + } + }); + } ui.label(crate::tl!("Island detection")); ui.radio_value(&mut st.fill.style, 0, crate::tl!("Normal")); ui.radio_value(&mut st.fill.style, 1, crate::tl!("Outer")); diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 414d622db4..0b7db8e0ac 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1395,3 +1395,14 @@ Text Style Текстовый стиль Dimension Style Размерный стиль Style Стиль + Sheet Лист + Drawing Чертёж + Paper Бумага + Ctrl and Shift pick several sheets; drag in the empty space to pick with a rectangle. Ctrl и Shift выбирают несколько листов; протяните рамку в пустом месте списка, чтобы выбрать прямоугольником. + Undo several steps Отменить несколько шагов + Redo several steps Повторить несколько шагов + Nothing to undo Нечего отменять + Nothing to redo Нечего повторять + Change Изменение + Background color Цвет фона + Other color Другой цвет diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 195287bd6c..6b13b56da5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1700,3 +1700,14 @@ Text Style Текстовий стиль Dimension Style Розмірний стиль Style Стиль + Sheet Аркуш + Drawing Креслення + Paper Папір + Ctrl and Shift pick several sheets; drag in the empty space to pick with a rectangle. Ctrl і Shift вибирають кілька аркушів; протягніть рамку в порожньому місці списку, щоб вибрати прямокутником. + Undo several steps Скасувати кілька кроків + Redo several steps Повторити кілька кроків + Nothing to undo Нічого скасовувати + Nothing to redo Нічого повторювати + Change Зміна + Background color Колір фону + Other color Інший колір diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 7ad9ef9b1c..e381bc345f 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -268,35 +268,38 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { } } Undo | Redo => { - // A thick arc with a large arrowhead at its upper end: pointing left for Undo, right - // for Redo (the same picture mirrored). + // As in Office 2010: a thick blue hook over the top, its arrowhead at the open end + // pointing down (Undo: on the left, Redo: mirrored on the right). let m = |x: f32| if icon == Undo { x } else { 24.0 - x }; - let (cx, cy, r) = (13.0_f32, 14.0_f32, 6.5_f32); - let a0 = 155.0_f32; - let pts: Vec = (0..=24) + let (cx, cy, r) = (12.5_f32, 13.5_f32, 6.5_f32); + let blue = if dim { a } else { Color32::from_rgb(0x3d, 0x8e, 0xe0) }; + let pts: Vec = (0..=28) .map(|i| { - let a = (a0 - (a0 + 60.0) * i as f32 / 24.0).to_radians(); - pen.at(m(cx + r * a.cos()), cy - r * a.sin()) + let ang = (-35.0 + 205.0 * i as f32 / 28.0).to_radians(); + pen.at(m(cx + r * ang.cos()), cy - r * ang.sin()) }) .collect(); - p.add(egui::Shape::line(pts, Stroke::new(pen.w * 1.8, b))); - let a = a0.to_radians(); - let (sx, sy) = (cx + r * a.cos(), cy - r * a.sin()); - // Opposite to the arc's way round: down and out at its start. - let (dx, dy) = (-a.sin(), -a.cos()); - let (dx, dy) = (-dx, -dy); - let (tx, ty) = (sx + dx * 3.6, sy + dy * 3.6); + p.add(egui::Shape::line(pts, Stroke::new(pen.w * 2.4, blue))); + // The arrowhead at the arc's open end (170°), pointing down and a little out. + let ang = 170.0_f32.to_radians(); + let (ex, ey) = (cx + r * ang.cos(), cy - r * ang.sin()); + let (dx, dy) = (-ang.sin(), -ang.cos()); + let (tx, ty) = (ex + dx * 4.6, ey + dy * 4.6); let ddx = if icon == Undo { dx } else { -dx }; - pen.big_arrow(m(tx), ty, ddx, dy, 6.5, 4.3, b); + pen.big_arrow(m(tx), ty, ddx, dy, 7.0, 4.8, blue); } - Plot | Preview => { + Plot => { pen.rect(4.0, 9.0, 16.0, 8.0, b); pen.rect(7.0, 4.0, 10.0, 5.0, b); pen.rect(7.0, 14.0, 10.0, 7.0, b); - if icon == Preview { - pen.c(17.0, 17.0, 3.0, a); - pen.la(19.0, 19.0, 22.0, 22.0); - } + } + Preview => { + // A smaller printer on the left and the magnifier clear of it on the right. + pen.rect(1.5, 8.0, 12.0, 6.5, b); + pen.rect(3.8, 4.0, 7.4, 4.0, b); + pen.rect(3.8, 12.0, 7.4, 6.0, b); + pen.c(17.5, 13.0, 4.0, a); + p.line_segment([pen.at(20.4, 15.9), pen.at(23.0, 18.5)], Stroke::new(pen.w * 1.8, a)); } Publish => { pen.rect(3.0, 10.0, 13.0, 7.0, b); diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 3d54686182..3e28b58aa7 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1137,6 +1137,13 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); num(ui, "Scale", "scale", real(hh.scale), &mut set, &mut bad, &ids); num(ui, "Angle", "angle", real(hh.angle.to_degrees()), &mut set, &mut bad, &ids); + if !hh.solid { + prop_row(ui, "Background color", |ui| { + if let Some(v) = crate::hatchdlg::background_menu(ui, hh.background) { + set = Some(json!({ "handles": ids, "background": v })); + } + }); + } } EntityKind::Dimension(dm) => { prop_row(ui, "Dim style", |ui| { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 636b4c4c4b..23465229ee 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -211,6 +211,57 @@ const STYLE_COMBO_W: f32 = 160.0; /// Most height a drop-down's list takes before it scrolls. const COMBO_LIST_H: f32 = 320.0; +/// Width of the steps arrow beside Undo and Redo. +const HISTORY_W: f32 = 13.0; +/// Most steps the Undo and Redo lists show. +const HISTORY_MAX: usize = 100; + +/// Whether the bar button for `command` has a list of steps beside it (Undo, Redo). +fn has_history(command: &str) -> bool { + matches!(command, "u" | "redo") +} + +/// The Undo (or Redo) steps, newest first, at most [`HISTORY_MAX`], in a scrolling list; hovering +/// a step highlights it and every step before it. The number of steps picked. +fn history_list(app: &CadApp, ui: &mut egui::Ui, undo: bool) -> Option { + let Ok(st) = app.session.state() else { return None }; + let steps: Vec<&str> = if undo { + st.undo.iter().rev().map(|s| s.label.as_str()).take(HISTORY_MAX).collect() + } else { + st.redo.iter().rev().map(|s| s.label.as_str()).take(HISTORY_MAX).collect() + }; + let t = Tokens::get(); + ui.set_min_width(220.0); + if steps.is_empty() { + ui.label(RichText::new(if undo { crate::tl!("Nothing to undo") } else { crate::tl!("Nothing to redo") }).color(t.text_dim)); + return None; + } + let hover_id = egui::Id::new(("cc_history_hover", undo)); + let hovered: Option = ui.data(|d| d.get_temp(hover_id)); + let mut now_hovered = None; + let mut picked = None; + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt(("cc_history", undo)).max_height(360.0).auto_shrink([false, true]).show(ui, |ui| { + for (i, label) in steps.iter().enumerate() { + let name = if label.trim().is_empty() { crate::tl!("Change").to_string() } else { label.to_ascii_uppercase() }; + let on = hovered.is_some_and(|h| i <= h); + let r = ui.selectable_label(on, format!("{} {name}", i + 1)); + if r.hovered() { + now_hovered = Some(i); + } + if r.clicked() { + picked = Some(i + 1); + } + } + }); + ui.data_mut(|d| d.insert_temp(hover_id, now_hovered)); + let n = now_hovered.or(hovered).map_or(0, |h| h + 1); + let what = if undo { crate::tl!("Undo") } else { crate::tl!("Redo") }; + ui.separator(); + ui.label(RichText::new(format!("{what}: {n}")).small().color(t.text_dim)); + picked +} + /// Whether `command` is one of the bars' drop-downs (not a command). pub fn is_combo(command: &str) -> bool { [LAYER_COMBO, TEXTSTYLE_COMBO, DIMSTYLE_COMBO, LINETYPE_COMBO].contains(&command) @@ -458,6 +509,8 @@ enum Action { LayerToggle(String, &'static str, bool), /// A style or linetype drop-down's choice: the drop-down and the name. SetCurrent(&'static str, String), + /// Undo (true) or redo this many steps. + History(bool, usize), } /// The bar's right-click menu; `item` is the button it was opened on. @@ -703,6 +756,8 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B SEP } else if is_combo(item) && !vertical { combo_width(item) + GAP + } else if has_history(item) && !vertical { + BUTTON + HISTORY_W + GAP } else { BUTTON + GAP } @@ -812,8 +867,27 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B if resp.drag_stopped() { drop_from = Some(index); } + // Undo and Redo: a narrow arrow beside the button lists the steps to go back (or forward) to. + let mut extra = 0.0; + if has_history(tool.command) && !vertical { + let hr = slot(pos + len, HISTORY_W, BUTTON); + let hresp = ui.interact(hr, id.with(("tb_history", tool.command)), Sense::click()); + if hresp.hovered() { + ui.painter().rect_filled(hr, 3.0, t.control_hover.gamma_multiply(0.6)); + } + icons::paint(ui.painter(), Rect::from_center_size(hr.center(), vec2(10.0, 10.0)), Icon::ChevronDown, false); + let undo = tool.command == "u"; + let hresp = hresp.on_hover_text(if undo { crate::tl!("Undo several steps") } else { crate::tl!("Redo several steps") }); + egui::Popup::menu(&hresp).align(egui::RectAlign::BOTTOM_START).show(|ui| { + if let Some(k) = history_list(app, ui, undo) { + action = Some(Action::History(undo, k)); + ui.close(); + } + }); + extra = HISTORY_W; + } placed.push((index, br)); - pos += len + GAP; + pos += len + extra + GAP; } // Dragging a button: show where it lands; dropping it on the bar moves it there. @@ -939,6 +1013,14 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B Some(Action::LayerToggle(name, key, on)) => { let _ = app.run("layer.set", json!({ "name": name, key: on })); } + Some(Action::History(undo, steps)) => { + for _ in 0..steps.min(HISTORY_MAX) { + if let Err(e) = app.run(if undo { "u" } else { "redo" }, json!({})) { + app.session.echo(e); + break; + } + } + } Some(Action::SetCurrent(combo, name)) => { let r = match combo { TEXTSTYLE_COMBO => app.run("style.current", json!({ "name": name })), From 152ef08ad3395a01d3db7f0c7b86a6381e8fbf6c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 18:57:12 +0300 Subject: [PATCH 05/23] fonts: Hebrew code page test with full-size fonts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/fonts/src/shx.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/fonts/src/shx.rs b/crates/fonts/src/shx.rs index 9555e0f631..1d3b04369e 100644 --- a/crates/fonts/src/shx.rs +++ b/crates/fonts/src/shx.rs @@ -703,13 +703,14 @@ mod tests { assert!(crate::ttf::available("tiny_test.shx")); } - #[test] - fn hebrew_letters_find_their_one_byte_positions() { + /// A shapes font with a dot glyph at each of `codes`. + fn font_with(codes: impl IntoIterator) -> ShxFont { + let mut shapes: Vec<(u16, Vec)> = vec![(0, b"H\0\x04\x01\x00\x00".to_vec())]; + shapes.extend(codes.into_iter().map(|c| (c, b"\0\x14\x00".to_vec()))); let mut b = b"AutoCAD-86 shapes 1.0\r\n\x1a".to_vec(); - let shapes: Vec<(u16, Vec)> = vec![(0, b"H\0\x04\x01\x00\x00".to_vec()), (0xE0, b"\0\x14\x00".to_vec())]; b.extend(0u16.to_le_bytes()); - b.extend(0xE0u16.to_le_bytes()); - b.extend(2u16.to_le_bytes()); + b.extend(shapes.last().map_or(0, |s| s.0).to_le_bytes()); + b.extend(u16::try_from(shapes.len()).unwrap_or(0).to_le_bytes()); for (n, d) in &shapes { b.extend(n.to_le_bytes()); b.extend(u16::try_from(d.len()).unwrap_or(0).to_le_bytes()); @@ -717,9 +718,21 @@ mod tests { for (_, d) in &shapes { b.extend(d); } - let f = ShxFont::parse("h", &b).expect("parses"); + ShxFont::parse("h", &b).expect("parses") + } + + #[test] + fn hebrew_letters_find_their_one_byte_positions() { + // Code page 1255: the 27 letters at 0xE0..0xFA. + let f = font_with((0xE0..=0xFA).filter(|c| *c != 0xE1)); assert_eq!(f.code_for('א'), Some(0xE0)); assert_eq!(f.code_for('ב'), None); + // Code page 862: the letters at 0x80..0x9A. + let f = font_with(0x80..=0x9A); + assert_eq!(f.code_for('א'), Some(0x80)); + // A Cyrillic-style font (0xC0..0xFF all drawn) is not taken for Hebrew. + let f = font_with(0xC0..=0xFF); + assert_eq!(f.code_for('א'), None); } #[test] From 0cd9f63d12550c36de53d30da65ab51ccf88201d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 20:37:54 +0300 Subject: [PATCH 06/23] b14: TrueType glyphs fill non-zero, editor in drawing fonts, RECTANG width/height boxes, options box below crosshair, DSETTINGS scroll, lineweight combo and previews, GRIPSNAP Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 60 ++++++++++ crates/engine/src/lib.rs | 4 + crates/engine/src/sysvars.rs | 3 + crates/fonts/src/lib.rs | 3 +- crates/render/src/lib.rs | 3 +- crates/render/src/text.rs | 58 +++++++++- crates/ui-egui/src/canvas.rs | 123 +++++++++++++++++++- crates/ui-egui/src/cmdline.rs | 4 +- crates/ui-egui/src/dialogs.rs | 170 ++++++++++++++-------------- crates/ui-egui/src/dyninput.rs | 54 +++++++-- crates/ui-egui/src/editor_glyphs.rs | 163 ++++++++++++++++++++++++++ crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/mtext_editor.rs | 117 +++++++++++++------ crates/ui-egui/src/toolbar.rs | 155 ++++++++++++++++++++++++- 16 files changed, 790 insertions(+), 139 deletions(-) create mode 100644 crates/ui-egui/src/editor_glyphs.rs diff --git a/WHATS_NEW.md b/WHATS_NEW.md index 5f7934a956..8cc9b8cee9 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,66 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 22.10.2026 (0.9.0-b14) + +### Русский + +**Текст без заливки при печати** +- Вероятная причина найдена. Шрифты TrueType заливаются по правилу «ненулевой обмотки»: если контуры буквы перекрываются, место перекрытия всё равно закрашивается. CADCraft заливал буквы по другому правилу («чёт-нечет»), и у букв из перекрывающихся контуров середина оставалась пустой — была видна только обводка. Так устроены многие шрифты, в том числе TrueType-версии штриховых шрифтов, которые AutoCAD ставит в Windows (romanc__.ttf, txt_____.ttf и т. п.). Теперь буквы заливаются так же, как их рисует Windows: на экране, в предварительном просмотре и при печати. +- Пожалуйста, проверьте лист «4» ещё раз. Если где-то текст всё ещё полый, пришлите снимок. + +**Редактор текста показывает шрифт чертежа** +- В окне редактирования текста (TEXT, MTEXT, мультивыноски) буквы рисуются тем же шрифтом, что и на чертеже: SHX, TrueType или встроенным, с коэффициентом ширины и наклоном стиля. Курсор и выделение совпадают с буквами. +- Текст в окне стал немного крупнее. + +**Прямоугольник: ширина и высота** +- После первого угла ПРЯМОУГОЛЬНИК (RECTANG) показывает два поля прямо у сторон: ширину под (или над) горизонтальной стороной и высоту рядом с вертикальной. Введите ширину, нажмите Tab, введите высоту, нажмите Enter. +- Прямоугольник строится в ту сторону от первого угла, где находится курсор. + +**Окошко с вариантами** +- Окошко с вариантами (например, «Да/Нет» в ЗЕРКАЛО) теперь открывается ниже перекрестия и не закрывает курсор. + +**Режимы рисования (DSETTINGS)** +- Окно стало ниже, его содержимое прокручивается, полоса прокрутки видна всегда. + +**Тип и вес линий на панели «Слои»** +- Рядом со списком типов линий появился список весов линий (ПоСлою, ПоБлоку, По умолчанию, 0.00–2.11 мм). Выбранный вес становится текущим для новых объектов. +- В обоих списках слева от названия нарисован образец: штрихи типа линии или линия нужной толщины, отделённые от названия разделителем. + +**Привязка курсора к ручкам** +- Раньше её не было. Теперь, когда никакая команда не выполняется, перекрестие «прилипает» к ручке выбранного объекта, на которую наведена мышь. Меню ручки появляется вдвое быстрее. +- Включается и выключается в «Режимах рисования» (DSETTINGS), флажок «Привязывать перекрестие к ручкам», или переменной GRIPSNAP (1/0). По умолчанию включена. + +### English + +**Text printing without fill** +- Likely cause found. TrueType fonts are filled by the non-zero winding rule: where a letter's contours overlap, the overlap is still ink. CADCraft filled letters by the even-odd rule instead, so letters made of overlapping contours came out hollow, showing only their outline. Many fonts are built that way, including the TrueType versions of stroke fonts that AutoCAD installs in Windows (romanc__.ttf, txt_____.ttf and so on). Letters are now filled the way Windows draws them: on screen, in Plot Preview and in plots. +- Please check sheet "4" again, and send a screenshot if any text is still hollow. + +**The text editor shows the drawing's font** +- The text editing box (TEXT, MTEXT, multileaders) draws letters in the drawing's own font: SHX, TrueType or the built-in one, with the style's width factor and oblique angle. The caret and selection line up with the letters. +- Text in the box is a little larger. + +**Rectangle: width and height** +- After the first corner, RECTANG shows two boxes right at the sides: the width under (or over) the horizontal side and the height beside the vertical side. Type the width, press Tab, type the height, press Enter. +- The rectangle goes from the first corner toward the side where the cursor is. + +**Options box** +- The options box (for example Yes/No in MIRROR) now opens below the crosshair and no longer covers the cursor. + +**Drafting Settings (DSETTINGS)** +- The window is shorter, its contents scroll, and the scrollbar is always visible. + +**Linetype and lineweight on the Layers bar** +- A lineweight list (ByLayer, ByBlock, Default, 0.00–2.11 mm) is now beside the linetype list. The weight you pick becomes current for new objects. +- Both lists show a sample left of each name, behind a separator: the linetype's dashes or a line of that weight. + +**Cursor snapping to grips** +- This didn't exist before. With no command running, the crosshair now locks onto the grip of a selected object under the mouse. The grip menu appears twice as fast. +- Turn it on or off in Drafting Settings (DSETTINGS) with "Snap the crosshair to grips", or with the GRIPSNAP variable (1/0). It is on by default. + +--- + ## 22.10.2026 (0.9.0-b13) ### Русский diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 215d054b92..9e3b70c7ec 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -398,6 +398,9 @@ pub struct Settings { /// with their boundaries (stored, not used yet). pub pickstyle: u8, pub gripsize: f64, + /// GRIPSNAP (CADCraft): with no command running, the crosshair locks onto a grip of the + /// selection under it, as onto a snap point. + pub gripsnap: bool, pub cursorsize: f64, /// MAXARRAY: the most objects one array command creates (items × selected objects). pub maxarray: u64, @@ -481,6 +484,7 @@ impl Default for Settings { pickadd: true, pickstyle: 1, gripsize: 5.0, + gripsnap: true, cursorsize: 5.0, maxarray: 100_000, isodraft: false, diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index 31451b6bc9..14127fd33c 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -56,6 +56,7 @@ const SESSION_VARS: &[&str] = &[ "PICKADD", "PICKSTYLE", "GRIPSIZE", + "GRIPSNAP", "CURSORSIZE", "MAXARRAY", "ZOOMFACTOR", @@ -124,6 +125,7 @@ pub fn get(s: &Session, name: &str) -> Option { "PICKADD" => json!(i32::from(st.pickadd)), "PICKSTYLE" => json!(st.pickstyle), "GRIPSIZE" => json!(st.gripsize), + "GRIPSNAP" => json!(i32::from(st.gripsnap)), "CURSORSIZE" => json!(st.cursorsize), "MAXARRAY" => json!(st.maxarray), "ZOOMFACTOR" => json!(st.zoomfactor), @@ -291,6 +293,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> { "PICKADD" => st.pickadd = as_bool(v).ok_or_else(bad)?, "PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?, "GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0), + "GRIPSNAP" => st.gripsnap = as_bool(v).ok_or_else(bad)?, "CURSORSIZE" => st.cursorsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 100.0), "MAXARRAY" => st.maxarray = as_f64(v).ok_or_else(bad)?.clamp(100.0, 10_000_000.0) as u64, "ZOOMFACTOR" => st.zoomfactor = as_i(v).filter(|z| (3..=100).contains(z)).ok_or_else(bad)? as u32, diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index 17b14ce222..dddfd06a43 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -383,7 +383,8 @@ impl TextFont { } /// Shaped text in local or world coordinates: open strokes (stroke-font glyphs, underlines, -/// fraction bars) and closed glyph outlines grouped per glyph (fill each group even-odd). +/// fraction bars) and closed glyph outlines grouped per glyph (fill each group by the non-zero rule, as +/// TrueType does). /// Outline glyphs also come as [`TextGlyph`]s, for output that keeps text as text (PDF). #[derive(Clone, Debug, Default, PartialEq)] pub struct Shaped { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2f7ee47219..20b0ff218d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -34,6 +34,7 @@ pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, d pub use fill::triangulate_evenodd; pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch}; pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet}; +pub use text::triangulate_placed as triangulate_glyph; pub use tolerance::{gdt_points, tolerance_in}; /// Handle carried by model-space geometry drawn inside a paper-space viewport (it belongs to no @@ -409,7 +410,7 @@ impl Builder<'_> { self.tris_at(ctx, color, &mesh.triangles, xf); mesh.triangles.len() } else { - let tris = fill::triangulate_evenodd(g); + let tris = crate::text::triangulate_placed(g); self.tris(ctx, color, &tris); tris.len() }; diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 6595e145ff..8f6872311e 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -163,10 +163,13 @@ fn simplify(contour: &[Vec2], tolerance: f64) -> Vec { if result.len() >= 4 { result } else { contour.to_vec() } } -/// Monotone tessellation with even-odd holes and intersections. Work in font units so f32 -/// precision is independent of drawing coordinates; the placement stays f64. The existing -/// slab filler remains the fallback when tessellation fails (including its u16 vertex limit). -fn triangulate(contours: &[Vec]) -> Vec { +/// Glyph contours filled by the non-zero winding rule, as TrueType and OpenType define it: a +/// glyph drawn from overlapping contours (AutoCAD's TrueType versions of its stroke fonts, many +/// modern fonts) is solid where they overlap, not hollow as the even-odd rule would leave it. +/// Work in font units so f32 precision is independent of drawing coordinates; the placement +/// stays f64. The slab filler (even-odd) remains the fallback when tessellation fails +/// (including its u16 vertex limit). +pub(crate) fn triangulate(contours: &[Vec]) -> Vec { let mut path = Path::builder(); for contour in contours { let Some(&first) = contour.first().filter(|_| contour.len() >= 3) else { continue }; @@ -179,7 +182,7 @@ fn triangulate(contours: &[Vec]) -> Vec { let mut buffers: VertexBuffers = VertexBuffers::new(); let result = FillTessellator::new().tessellate_path( &path.build(), - &FillOptions::even_odd(), + &FillOptions::non_zero(), &mut BuffersBuilder::new(&mut buffers, |v: FillVertex<'_>| { let p = v.position(); Vec2::new(f64::from(p.x), f64::from(p.y)) @@ -190,3 +193,48 @@ fn triangulate(contours: &[Vec]) -> Vec { } buffers.indices.into_iter().filter_map(|i| buffers.vertices.get(usize::from(i)).copied()).collect() } + +/// [`triangulate`] for contours placed in drawing coordinates (glyphs shaped without a font +/// glyph reference, such as right-to-left runs): tessellated about their own corner so large +/// coordinates keep their precision. +pub fn triangulate_placed(contours: &[Vec]) -> Vec { + let Some(o) = contours.iter().flatten().copied().find(|p| p.is_finite()) else { return Vec::new() }; + let local: Vec> = contours.iter().map(|c| c.iter().map(|p| *p - o).collect()).collect(); + triangulate(&local).into_iter().map(|p| p + o).collect() +} + +#[cfg(test)] +mod fill_rule_tests { + use cadcraft_geom::Vec2; + + fn area(tris: &[Vec2]) -> f64 { + tris.chunks(3) + .map(|t| match t { + [a, b, c] => ((*b - *a).x * (*c - *a).y - (*b - *a).y * (*c - *a).x).abs() / 2.0, + _ => 0.0, + }) + .sum() + } + + fn square(x: f64, y: f64, s: f64) -> Vec { + vec![Vec2::new(x, y), Vec2::new(x + s, y), Vec2::new(x + s, y + s), Vec2::new(x, y + s)] + } + + /// Two overlapping contours drawn the same way round (how many fonts build a glyph): the + /// overlap is ink, not a hole. + #[test] + fn overlapping_glyph_contours_fill_solid() { + let a = area(&super::triangulate(&[square(0.0, 0.0, 10.0), square(5.0, 0.0, 10.0)])); + assert!((a - 150.0).abs() < 1e-3, "union area, got {a}"); + // A counter (the hole of an "o") is drawn the other way round and stays a hole. + let mut hole = square(2.0, 2.0, 6.0); + hole.reverse(); + let a = area(&super::triangulate(&[square(0.0, 0.0, 10.0), hole])); + assert!((a - 64.0).abs() < 1e-3, "ring area, got {a}"); + // Far from the origin, as right-to-left glyphs are placed. + let far: Vec> = + [square(0.0, 0.0, 10.0), square(5.0, 0.0, 10.0)].iter().map(|c| c.iter().map(|p| *p + Vec2::new(-38653.0, 147552.0)).collect()).collect(); + let a = area(&super::triangulate_placed(&far)); + assert!((a - 150.0).abs() < 1e-2, "placed union area, got {a}"); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e6cd859ed9..a04e8850f0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1475,6 +1475,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.snap = None; app.canvas.track = None; } + if let Some((p, _)) = grip_snap(app, &xf, hover_pos) { + eff = p; + } app.canvas.cursor = Some(eff); app.session.cursor = eff; app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred); @@ -1880,6 +1883,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { if let Some(hp) = hover_pos && !panning { + // GRIPSNAP: with no command running the crosshair sits on the grip under it. + let hp = grip_snap(app, &xf, hover_pos).map_or(hp, |(_, at)| at); // Over the white paper of a layout the crosshair is black. let on_paper = sheet.is_some_and(|s| s.bounds().contains(xf.to_world(hp))); draw_crosshair(app, &painter, rect, hp, selecting, on_paper); @@ -2116,6 +2121,28 @@ fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2) { && let Some(c) = app.canvas.cursor { let message = if show_prompt { crate::i18n::t(&prompt.message) } else { "" }; + if f.dims + && e.format == crate::dyninput::Format::Cartesian + && let Some(xf) = app.canvas.xf + { + rectangle_dims(p, &xf, &f, &e, c, app.cmd.second_locked(), length_units(&app.session)); + let r = if show_prompt { + let t = Tokens::get(); + let g = p.layout_no_wrap(message.to_owned(), crate::theme::small(), t.text_dim); + let hint = if options { OPTIONS_HINT_W } else { 0.0 }; + let r = tooltip_frame(p, at, vec2(g.size().x + 12.0 + hint, g.size().y + 8.0)); + let gy = r.center().y - g.size().y / 2.0; + p.galley(pos2(r.left() + 6.0, gy), g, t.text_dim); + if options { + options_hint(p, r); + } + r + } else { + Rect::from_min_size(at, vec2(0.0, 0.0)) + }; + options_menu(app, p, r, hover); + return; + } let r = dynamic_input_boxes(p, at, message, &f, &e, c, app.cmd.second_locked(), options, length_units(&app.session)); options_menu(app, p, r, hover); return; @@ -2211,7 +2238,9 @@ fn options_menu(app: &mut CadApp, p: &egui::Painter, r: Rect, hover: Pos2) { let row_h = rows.iter().map(|g| g.size().y).fold(12.0, f32::max) + 6.0; let w = rows.iter().map(|g| g.size().x).fold(60.0, f32::max) + 28.0; let h = row_h * rows.len() as f32 + 4.0; - let m = Rect::from_min_size(pos2(r.left(), r.bottom() + 2.0), vec2(w, h)); + // Below the crosshair's horizontal arm (the tooltip sits above the cursor, its bottom 14 + // points above it), so the menu never covers the cursor. + let m = Rect::from_min_size(pos2(r.left(), r.bottom() + 28.0), vec2(w, h)); p.rect_filled(m, 3.0, t.cmd_bg); p.rect_stroke(m, 3.0, Stroke::new(1.0, t.cmd_border), egui::StrokeKind::Inside); let row_at = |i: usize| Rect::from_min_size(pos2(m.left() + 2.0, m.top() + 2.0 + row_h * i as f32), vec2(w - 4.0, row_h)); @@ -2344,6 +2373,79 @@ fn dynamic_input_boxes( r } +/// RECTANG's width and height boxes, each beside its side of the rubber-band rectangle (outside +/// it), like dimensions: the width under or over the horizontal side through the first corner, +/// the height beside the vertical side through the cursor. The active box (the one typing goes +/// to; Tab moves on) has the accent outline, a locked one a lock. +fn rectangle_dims( + p: &egui::Painter, + xf: &crate::canvas::Xf, + f: &crate::dyninput::Frame, + e: &crate::dyninput::Entry<'_>, + cursor: Vec2, + second_locked: bool, + (lu, lp): (i64, i64), +) { + let t = Tokens::get(); + let font = crate::theme::small(); + let o = f.origin(); + let held = crate::dyninput::constrain(e, f, cursor, second_locked); + let (w, h) = f.live(crate::dyninput::Format::Cartesian, held); + let dist = |v: f64| cadcraft_engine::units::format_distance(v, lu, lp); + let a = xf.to_screen(o); + let b = xf.to_screen(held); + let (left, right) = (a.x.min(b.x), a.x.max(b.x)); + let (top, bottom) = (a.y.min(b.y), a.y.max(b.y)); + // Outside the rectangle: below a side at its bottom, above one at its top; right of a side at + // its right, left of one at its left. + let width_y = if (a.y - bottom).abs() < 0.5 { a.y + 16.0 } else { a.y - 16.0 }; + let height_x = if (b.x - right).abs() < 0.5 { b.x + 10.0 } else { b.x - 10.0 }; + let cells = [ + ( + pos2((left + right) / 2.0, width_y), + if e.first.is_empty() { dist(w) } else { e.first.to_owned() }, + !e.first.is_empty(), + e.first_locked().is_some(), + !e.split, + 0.5, + ), + ( + pos2(height_x, (top + bottom) / 2.0), + if e.second.is_empty() { dist(h) } else { e.second.to_owned() }, + !e.second.is_empty(), + second_locked, + e.split && !second_locked, + if height_x > b.x { 0.0 } else { 1.0 }, + ), + ]; + // Dimension-like guides along the two sides. + let guide = Stroke::new(1.0, t.text_faint); + p.line_segment([pos2(left, width_y - 6.0), pos2(right, width_y - 6.0)], guide); + let gx = if height_x > b.x { height_x - 4.0 } else { height_x + 4.0 }; + p.line_segment([pos2(gx, top), pos2(gx, bottom)], guide); + let lock_w = 10.0; + for (at, text, typed, locked, active, anchor_x) in cells { + let value = p.layout_no_wrap(text, font.clone(), if typed { t.text } else { t.text_faint }); + let bw = (value.size().x + 10.0 + if locked { lock_w } else { 0.0 }).max(48.0); + let bh = value.size().y + 6.0; + let min = pos2(at.x - bw * anchor_x, at.y - bh / 2.0); + let r = Rect::from_min_size(min, vec2(bw, bh)); + p.rect_filled(r, 2.0, t.chrome_dark); + let stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) }; + p.rect_stroke(r, 2.0, stroke, egui::StrokeKind::Inside); + let vw = value.size().x; + let vh = value.size().y; + p.galley(pos2(r.left() + 5.0, r.center().y - vh / 2.0), value, t.text); + if active { + let cx = r.left() + 6.0 + vw; + p.line_segment([pos2(cx, r.top() + 3.0), pos2(cx, r.bottom() - 3.0)], Stroke::new(1.0, t.text)); + } + if locked { + draw_lock(p, pos2(r.right() - lock_w / 2.0 - 3.0, r.center().y), t.accent); + } + } +} + /// A small padlock, drawn in code: body plus shackle. fn draw_lock(p: &egui::Painter, c: Pos2, color: Color32) { p.rect_filled(Rect::from_center_size(c + vec2(0.0, 1.5), vec2(7.0, 5.0)), 1.0, color); @@ -2443,6 +2545,8 @@ fn grip_menu(app: &mut CadApp, resp: &egui::Response) { /// Seconds the cursor rests on a grip before its menu opens. const GRIP_HOVER_DELAY: f64 = 0.4; +/// The same with the crosshair locked onto grips (GRIPSNAP). +const GRIP_HOVER_DELAY_SNAPPED: f64 = 0.2; /// The grip menu that opens when the cursor rests on a grip with options (a dimension's text /// grip, a polyline vertex…); it closes when the cursor leaves the grip and the menu. @@ -2490,13 +2594,15 @@ fn hover_grip_menu(app: &mut CadApp, ui: &egui::Ui, xf: &Xf, hover: Option } match (over, app.canvas.grip_hover) { (Some(g), Some((h, since))) if h == g => { - if now - since >= GRIP_HOVER_DELAY { + // A crosshair locked onto the grip (GRIPSNAP) holds still: the menu can come sooner. + let delay = if app.session.settings.gripsnap { GRIP_HOVER_DELAY_SNAPPED } else { GRIP_HOVER_DELAY }; + if now - since >= delay { let point = app.session.grips_of(g.0).ok().and_then(|p| p.get(g.1).copied()); if let Some(p) = point { app.canvas.grip_popup = Some((g, xf.to_screen(p) + vec2(10.0, 10.0))); } } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(GRIP_HOVER_DELAY - (now - since) + 0.01)); + ctx.request_repaint_after(std::time::Duration::from_secs_f64(delay - (now - since) + 0.01)); } } (Some(g), _) => { @@ -2520,6 +2626,17 @@ fn apply_grip_choice(app: &mut CadApp, g: (Handle, usize), choice: Option) -> Option<(Vec2, Pos2)> { + if !app.session.settings.gripsnap || app.session.prompting() { + return None; + } + let g = grip_at(app, xf, hover)?; + let p = app.session.grips_of(g.0).ok()?.get(g.1).copied()?; + Some((p, xf.to_screen(p))) +} + /// The grip of a selected object under the cursor, if any: (object, grip index). fn grip_at(app: &CadApp, xf: &Xf, hover: Option) -> Option<(Handle, usize)> { let hp = hover?; diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index f8ce35a1c1..f5bab7a125 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -50,7 +50,9 @@ pub fn dyn_frame(app: &CadApp) -> Option { return None; } let p = app.session.current_prompt().filter(cadcraft_engine::pointmod::accepts)?; - Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute }) + // RECTANG's other corner: its width and height, in boxes beside the sides. + let dims = p.corner && p.base.is_some() && app.session.running.as_ref().is_some_and(|r| r.id == "rectang"); + Some(crate::dyninput::Frame { base: p.base, cartesian: st.dynpi_cartesian, absolute: st.dynpi_absolute, dims }) } /// Take Tab away from egui before it moves keyboard focus to the next widget (which would leave diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index be8a95ab85..923fdc97c0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -43,98 +43,104 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { fn dsettings(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let settings = app.session.drafting_settings(); let (mut snapunit, mut gridunit) = (settings.snapunit, settings.gridunit); + // Shorter than its contents: they scroll (the window fits small screens). + let max_h = (ctx.content_rect().height() * 0.6).clamp(240.0, 460.0); egui::Window::new(crate::tl!("Drafting Settings")).id(egui::Id::new("Drafting Settings")).open(open).resizable(false).show(ctx, |ui| { - let s = &mut app.session.settings; - ui.heading(crate::tl!("Snap and Grid")); - ui.checkbox(&mut s.snapmode, crate::tl!("Snap On (F9)")); - // SNAPSTYL: the isometric snap and grid (ISODRAFT). - ui.horizontal(|ui| { - ui.radio_value(&mut s.isodraft, false, crate::tl!("Rectangular snap")); - ui.radio_value(&mut s.isodraft, true, crate::tl!("Isometric snap")); - }); - ui.horizontal(|ui| { - ui.label(crate::tl!("Snap X spacing")); - ui.add(egui::DragValue::new(&mut snapunit.x).speed(0.05).range(0.0001..=1e6).clamp_existing_to_range(false)); - ui.label(crate::tl!("Y")); - ui.add(egui::DragValue::new(&mut snapunit.y).speed(0.05).range(0.0001..=1e6).clamp_existing_to_range(false)); - }); - // SNAPTYPE and POLARDIST. - ui.horizontal(|ui| { - ui.label(crate::tl!("Snap type")); - ui.radio_value(&mut s.polarsnap, false, crate::tl!("Grid snap")); - ui.radio_value(&mut s.polarsnap, true, crate::tl!("PolarSnap")); - }); - ui.add_enabled_ui(s.polarsnap, |ui| { + egui::ScrollArea::vertical().max_height(max_h).scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { + let s = &mut app.session.settings; + ui.heading(crate::tl!("Snap and Grid")); + ui.checkbox(&mut s.snapmode, crate::tl!("Snap On (F9)")); + // SNAPSTYL: the isometric snap and grid (ISODRAFT). ui.horizontal(|ui| { - ui.label(crate::tl!("Polar distance")); - ui.add(egui::DragValue::new(&mut s.polardist).speed(0.05).range(0.0..=1e6)); + ui.radio_value(&mut s.isodraft, false, crate::tl!("Rectangular snap")); + ui.radio_value(&mut s.isodraft, true, crate::tl!("Isometric snap")); }); - }); - ui.checkbox(&mut s.gridmode, crate::tl!("Grid On (F7)")); - ui.horizontal(|ui| { - ui.label(crate::tl!("Grid spacing")); - ui.add(egui::DragValue::new(&mut gridunit.x).speed(0.05).range(0.0..=1e6).clamp_existing_to_range(false)); - ui.label(crate::tl!("Major line every")); - ui.add(egui::DragValue::new(&mut s.gridmajor).range(1..=100)); - }); - ui.separator(); - ui.heading(crate::tl!("Polar Tracking")); - ui.checkbox(&mut s.polarmode, crate::tl!("Polar Tracking On (F10)")); - let mut deg = s.polarang.to_degrees(); - ui.horizontal(|ui| { - ui.label(crate::tl!("Increment angle")); - egui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| { - for a in [90.0, 45.0, 30.0, 22.5, 18.0, 15.0, 10.0, 5.0] { - ui.selectable_value(&mut deg, a, format!("{a}")); - } + ui.horizontal(|ui| { + ui.label(crate::tl!("Snap X spacing")); + ui.add(egui::DragValue::new(&mut snapunit.x).speed(0.05).range(0.0001..=1e6).clamp_existing_to_range(false)); + ui.label(crate::tl!("Y")); + ui.add(egui::DragValue::new(&mut snapunit.y).speed(0.05).range(0.0001..=1e6).clamp_existing_to_range(false)); }); - }); - s.polarang = deg.to_radians(); - tracking_options(ui, s); - ui.separator(); - ui.heading(crate::tl!("Object Snap")); - let mut on = s.osmode & cadcraft_engine::snap::mode::OFF == 0; - if ui.checkbox(&mut on, crate::tl!("Object Snap On (F3)")).changed() { - if on { - s.osmode &= !cadcraft_engine::snap::mode::OFF; - } else { - s.osmode |= cadcraft_engine::snap::mode::OFF; - } - } - egui::Grid::new("osnap_grid").num_columns(2).show(ui, |ui| { - for (i, (bit, name)) in cadcraft_engine::snap::mode::ALL.iter().enumerate() { - let mut v = s.osmode & bit != 0; - if ui.checkbox(&mut v, crate::i18n::t(name)).changed() { - if v { - s.osmode |= bit; - } else { - s.osmode &= !bit; + // SNAPTYPE and POLARDIST. + ui.horizontal(|ui| { + ui.label(crate::tl!("Snap type")); + ui.radio_value(&mut s.polarsnap, false, crate::tl!("Grid snap")); + ui.radio_value(&mut s.polarsnap, true, crate::tl!("PolarSnap")); + }); + ui.add_enabled_ui(s.polarsnap, |ui| { + ui.horizontal(|ui| { + ui.label(crate::tl!("Polar distance")); + ui.add(egui::DragValue::new(&mut s.polardist).speed(0.05).range(0.0..=1e6)); + }); + }); + ui.checkbox(&mut s.gridmode, crate::tl!("Grid On (F7)")); + ui.horizontal(|ui| { + ui.label(crate::tl!("Grid spacing")); + ui.add(egui::DragValue::new(&mut gridunit.x).speed(0.05).range(0.0..=1e6).clamp_existing_to_range(false)); + ui.label(crate::tl!("Major line every")); + ui.add(egui::DragValue::new(&mut s.gridmajor).range(1..=100)); + }); + ui.separator(); + ui.heading(crate::tl!("Polar Tracking")); + ui.checkbox(&mut s.polarmode, crate::tl!("Polar Tracking On (F10)")); + let mut deg = s.polarang.to_degrees(); + ui.horizontal(|ui| { + ui.label(crate::tl!("Increment angle")); + egui::ComboBox::from_id_salt("polarang").selected_text(format!("{deg}")).show_ui(ui, |ui| { + for a in [90.0, 45.0, 30.0, 22.5, 18.0, 15.0, 10.0, 5.0] { + ui.selectable_value(&mut deg, a, format!("{a}")); } - } - if i % 2 == 1 { - ui.end_row(); + }); + }); + s.polarang = deg.to_radians(); + tracking_options(ui, s); + ui.separator(); + ui.heading(crate::tl!("Object Snap")); + let mut on = s.osmode & cadcraft_engine::snap::mode::OFF == 0; + if ui.checkbox(&mut on, crate::tl!("Object Snap On (F3)")).changed() { + if on { + s.osmode &= !cadcraft_engine::snap::mode::OFF; + } else { + s.osmode |= cadcraft_engine::snap::mode::OFF; } } - }); - ui.separator(); - ui.checkbox(&mut s.dynmode, crate::tl!("Enable Dynamic Input (F12)")); - // Pointer input format for second and next points (DYNPIFORMAT, DYNPICOORDS). - ui.indent("dynpi", |ui| { - ui.add_enabled_ui(s.dynmode, |ui| { - ui.label(crate::tl!("Second and next points:")); - ui.horizontal(|ui| { - ui.radio_value(&mut s.dynpi_cartesian, false, crate::tl!("Polar (distance < angle)")); - ui.radio_value(&mut s.dynpi_cartesian, true, crate::tl!("Cartesian (x, y)")); - }); - ui.horizontal(|ui| { - ui.radio_value(&mut s.dynpi_absolute, false, crate::tl!("Relative")); - ui.radio_value(&mut s.dynpi_absolute, true, crate::tl!("Absolute")); + ui.checkbox(&mut s.gripsnap, crate::tl!("Snap the crosshair to grips")) + .on_hover_text(crate::tl!("With no command running, the crosshair locks onto a grip of the selected objects under it.")); + egui::Grid::new("osnap_grid").num_columns(2).show(ui, |ui| { + for (i, (bit, name)) in cadcraft_engine::snap::mode::ALL.iter().enumerate() { + let mut v = s.osmode & bit != 0; + if ui.checkbox(&mut v, crate::i18n::t(name)).changed() { + if v { + s.osmode |= bit; + } else { + s.osmode &= !bit; + } + } + if i % 2 == 1 { + ui.end_row(); + } + } + }); + ui.separator(); + ui.checkbox(&mut s.dynmode, crate::tl!("Enable Dynamic Input (F12)")); + // Pointer input format for second and next points (DYNPIFORMAT, DYNPICOORDS). + ui.indent("dynpi", |ui| { + ui.add_enabled_ui(s.dynmode, |ui| { + ui.label(crate::tl!("Second and next points:")); + ui.horizontal(|ui| { + ui.radio_value(&mut s.dynpi_cartesian, false, crate::tl!("Polar (distance < angle)")); + ui.radio_value(&mut s.dynpi_cartesian, true, crate::tl!("Cartesian (x, y)")); + }); + ui.horizontal(|ui| { + ui.radio_value(&mut s.dynpi_absolute, false, crate::tl!("Relative")); + ui.radio_value(&mut s.dynpi_absolute, true, crate::tl!("Absolute")); + }); + // DYNPROMPT: the prompt and its options (Down Arrow) beside the cursor. + ui.checkbox(&mut s.dynprompt, crate::tl!("Show command prompting near the crosshairs")); }); - // DYNPROMPT: the prompt and its options (Down Arrow) beside the cursor. - ui.checkbox(&mut s.dynprompt, crate::tl!("Show command prompting near the crosshairs")); }); + ui.checkbox(&mut s.orthomode, crate::tl!("Ortho (F8)")); }); - ui.checkbox(&mut s.orthomode, crate::tl!("Ortho (F8)")); }); // Drawing edits go through the same command as the CLI, including dirty state and undo. for (name, before, after) in [("SNAPUNIT", settings.snapunit, snapunit), ("GRIDUNIT", settings.gridunit, gridunit)] { diff --git a/crates/ui-egui/src/dyninput.rs b/crates/ui-egui/src/dyninput.rs index 229ba17391..aa98398b8c 100644 --- a/crates/ui-egui/src/dyninput.rs +++ b/crates/ui-egui/src/dyninput.rs @@ -48,33 +48,43 @@ pub struct Frame { pub cartesian: bool, /// DYNPICOORDS = 1: second and next points are absolute instead of relative. pub absolute: bool, + /// The other corner of a rectangle: the boxes are its width and height (lengths beside its + /// sides, Tab between them), applied in the direction of the cursor from the first corner. + pub dims: bool, } impl Frame { /// The format the boxes show before a separator is typed. pub fn default_format(&self) -> Format { - if self.base.is_some() && !self.cartesian { Format::Polar } else { Format::Cartesian } + if self.base.is_some() && !self.cartesian && !self.dims { Format::Polar } else { Format::Cartesian } } /// Where the typed values are measured from. pub fn origin(&self) -> Vec2 { match self.base { - Some(b) if !self.absolute => b, + Some(b) if !self.absolute || self.dims => b, _ => Vec2::ZERO, } } /// Whether values are offsets from the last point. pub fn relative(&self) -> bool { - self.base.is_some() && !self.absolute + self.base.is_some() && (!self.absolute || self.dims) } - /// The live (X, Y) or (distance, angle in radians) of `cursor`. + /// The live (X, Y) or (distance, angle in radians) of `cursor`; a rectangle's width and + /// height (lengths) in [`Frame::dims`]. pub fn live(&self, format: Format, cursor: Vec2) -> (f64, f64) { let d = cursor - self.origin(); match format { + Format::Cartesian if self.dims => (d.x.abs(), d.y.abs()), Format::Cartesian => (d.x, d.y), Format::Polar => (d.len(), d.y.atan2(d.x)), } } + + /// A typed width or height as an offset: its length, toward the cursor's side. + fn toward(&self, v: f64, cursor_offset: f64) -> f64 { + if self.dims { if cursor_offset < 0.0 { -v.abs() } else { v.abs() } } else { v } + } } /// The command-line text read as a pointer-input entry. @@ -148,7 +158,7 @@ pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) let o = frame.origin(); if second_locked && let Some(w) = entry.second_value() { let q = match entry.format { - Format::Cartesian => o + Vec2::new(v, w), + Format::Cartesian => o + Vec2::new(frame.toward(v, p.x - o.x), frame.toward(w, p.y - o.y)), Format::Polar => o + Vec2::from_angle(w) * v, }; if q.is_finite() { @@ -156,7 +166,7 @@ pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) } } match entry.format { - Format::Cartesian => Vec2::new(o.x + v, p.y), + Format::Cartesian => Vec2::new(o.x + frame.toward(v, p.x - o.x), p.y), Format::Polar => { let d = p - o; let l = d.len(); @@ -178,6 +188,14 @@ pub fn complete(entry: &Entry<'_>, frame: &Frame, cursor: Vec2, last: Vec2) -> O let (live_first, live_second) = frame.live(entry.format, constrain(entry, frame, cursor, false)); let first = entry.first_locked().unwrap_or(live_first); let second = entry.second_value().unwrap_or(live_second); + // A rectangle's width and height go toward the cursor's side of the first corner. + let (first, second) = match (frame.dims, entry.format) { + (true, Format::Cartesian) => { + let d = cursor - frame.origin(); + (frame.toward(first, d.x), frame.toward(second, d.y)) + } + _ => (first, second), + }; if frame.relative() && frame.base == Some(last) { return Some(match entry.format { Format::Cartesian => format!("@{first},{second}"), @@ -230,7 +248,7 @@ mod tests { use super::*; fn second_point(base: Vec2) -> Frame { - Frame { base: Some(base), cartesian: false, absolute: false } + Frame { base: Some(base), cartesian: false, absolute: false, dims: false } } fn sent(text: &str, frame: &Frame, cursor: Vec2, last: Vec2) -> Option { @@ -243,6 +261,26 @@ mod tests { a.is_some_and(|a| a.dist(b) < 1e-9) } + #[test] + fn rectangle_dimensions_go_toward_the_cursor() { + let f = Frame { base: Some(Vec2::new(10.0, 10.0)), cartesian: false, absolute: true, dims: true }; + // Width and height boxes (Cartesian), whatever DYNPIFORMAT / DYNPICOORDS say. + assert_eq!(f.default_format(), Format::Cartesian); + assert_eq!(f.live(Format::Cartesian, Vec2::new(4.0, 13.0)), (6.0, 3.0)); + assert_eq!(tab_separator("100", &f), Some(',')); + // Cursor down-left of the first corner: the rectangle goes that way. + let p = sent("100,50", &f, Vec2::new(0.0, 0.0), Vec2::new(10.0, 10.0)).unwrap(); + assert!(close(Some(p), Vec2::new(-90.0, -40.0)), "{p:?}"); + let p = sent("100,50", &f, Vec2::new(20.0, 30.0), Vec2::new(10.0, 10.0)).unwrap(); + assert!(close(Some(p), Vec2::new(110.0, 60.0)), "{p:?}"); + // A typed width holds the cursor on its side. + let e = parse("100,", &f).unwrap(); + assert!(close(Some(constrain(&e, &f, Vec2::new(0.0, 3.0), false)), Vec2::new(-90.0, 3.0))); + // Only the width typed: the height comes from the cursor. + let p = sent("100,", &f, Vec2::new(20.0, 4.0), Vec2::new(10.0, 10.0)).unwrap(); + assert!(close(Some(p), Vec2::new(110.0, 4.0)), "{p:?}"); + } + #[test] fn rectangle_corner_with_comma_is_relative() { // Corner snapped at (0,60); `40,40` Enter -> (40,100). @@ -276,7 +314,7 @@ mod tests { #[test] fn absolute_setting_measures_from_the_origin() { - let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true }; + let f = Frame { base: Some(Vec2::new(5.0, 5.0)), cartesian: true, absolute: true, dims: false }; assert!(close(sent("40,100", &f, Vec2::ZERO, Vec2::new(5.0, 5.0)), Vec2::new(40.0, 100.0))); } diff --git a/crates/ui-egui/src/editor_glyphs.rs b/crates/ui-egui/src/editor_glyphs.rs new file mode 100644 index 0000000000..9a505b973f --- /dev/null +++ b/crates/ui-egui/src/editor_glyphs.rs @@ -0,0 +1,163 @@ +//! The text editors show text in the drawing's own fonts: each character is drawn with the +//! drawing's shaping (SHX strokes, TrueType outlines, the built-in stroke font and its fallbacks) +//! over an invisible egui text box whose advances are set to the font's, so the caret, the +//! selection and the glyphs line up. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock, PoisonError}; + +use cadcraft_fonts::{Shaped, TextFont}; +use egui::{Color32, Pos2, Stroke}; + +/// Most characters kept shaped. +const MAX_CACHED: usize = 4096; +/// The egui font's cap height as a share of its size: drawing fonts are scaled so their cap +/// height (the text height) matches it. +pub const CAP: f32 = 0.7; +/// Slant of italic text (radians), as the style's oblique angle adds to. +const ITALIC: f64 = 0.2618; + +/// The font a run of the editor is set in. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct EditorFont { + /// Style font file or inline family (`romans.shx`, `arial.ttf`, `Arial`). + pub font: String, + pub big_font: String, + pub width_factor: f64, + /// Radians. + pub oblique: f64, +} + +impl EditorFont { + fn wf(&self) -> f64 { + if self.width_factor.is_finite() && self.width_factor > 0.01 { self.width_factor.min(100.0) } else { 1.0 } + } +} + +type Key = (String, String, u64, u64, char); + +struct Glyph { + shaped: Shaped, + /// Advance at cap height 1. + advance: f64, +} + +fn cache() -> &'static Mutex>> { + static C: OnceLock>>> = OnceLock::new(); + C.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn fonts() -> &'static Mutex> { + static F: OnceLock>> = OnceLock::new(); + F.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn resolve(font: &str, big: &str) -> TextFont { + let k = (font.to_string(), big.to_string()); + let mut f = fonts().lock().unwrap_or_else(PoisonError::into_inner); + if let Some(t) = f.get(&k) { + return t.clone(); + } + let t = TextFont::resolve_style(font, big); + if f.len() > 64 { + f.clear(); + } + f.insert(k, t.clone()); + t +} + +/// Forget resolved fonts (the user's font folders changed). +pub fn clear() { + fonts().lock().unwrap_or_else(PoisonError::into_inner).clear(); + cache().lock().unwrap_or_else(PoisonError::into_inner).clear(); +} + +fn glyph(f: &EditorFont, italic: bool, c: char) -> std::sync::Arc { + let oblique = f.oblique + if italic { ITALIC } else { 0.0 }; + let key = (f.font.clone(), f.big_font.clone(), f.wf().to_bits(), oblique.to_bits(), c); + if let Some(g) = cache().lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + return g.clone(); + } + let font = resolve(&f.font, &f.big_font); + let s = c.to_string(); + let shaped = if c.is_whitespace() { Shaped::default() } else { cadcraft_fonts::shape_line(&font, &s, 1.0, f.wf(), oblique) }; + // A line's width leaves out the gap after its last character: the advance is what a second + // copy of the character adds. + let two: String = [c, c].iter().collect(); + let mut advance = cadcraft_fonts::text_width(&font, &two, 1.0, f.wf()) - cadcraft_fonts::text_width(&font, &s, 1.0, f.wf()); + if !advance.is_finite() || advance <= 0.0 { + advance = if c.is_whitespace() { cadcraft_fonts::space_width(&font, 1.0, f.wf()) } else { shaped.width }; + } + let g = std::sync::Arc::new(Glyph { shaped, advance: if advance.is_finite() { advance.clamp(0.0, 20.0) } else { 0.6 } }); + let mut c2 = cache().lock().unwrap_or_else(PoisonError::into_inner); + if c2.len() >= MAX_CACHED { + c2.clear(); + } + c2.insert(key, g.clone()); + g +} + +/// Advance of `c` in `f`, in points, at egui font size `size`. +pub fn advance(f: &EditorFont, italic: bool, c: char, size: f32) -> f32 { + (glyph(f, italic, c).advance as f32) * size * CAP +} + +/// Draw `c` in `f` with its baseline-left at `at` (screen), at egui font size `size`. +pub fn paint(painter: &egui::Painter, f: &EditorFont, italic: bool, bold: bool, c: char, at: Pos2, size: f32, color: Color32) { + if c.is_whitespace() || c.is_control() { + return; + } + let g = glyph(f, italic, c); + let k = size * CAP; + let map = |p: cadcraft_geom::Vec2| Pos2::new(at.x + p.x as f32 * k, at.y - p.y as f32 * k); + let w = (k / if bold { 7.0 } else { 12.0 }).clamp(1.0, 4.0); + for s in &g.shaped.strokes { + let pts: Vec = s.iter().map(|p| map(*p)).collect(); + if pts.len() == 1 + && let Some(p) = pts.first() + { + painter.circle_filled(*p, w / 2.0, color); + } else if pts.len() >= 2 { + painter.add(egui::Shape::line(pts, Stroke::new(w, color))); + } + } + for contours in &g.shaped.glyphs { + let tris = cadcraft_render::triangulate_glyph(contours); + if tris.len() < 3 { + continue; + } + let mut mesh = egui::Mesh::default(); + for p in &tris { + mesh.colored_vertex(map(*p), color); + } + mesh.indices = (0..u32::try_from(mesh.vertices.len()).unwrap_or(0)).collect(); + painter.add(egui::Shape::mesh(mesh)); + if bold { + for ct in contours { + let mut pts: Vec = ct.iter().map(|p| map(*p)).collect(); + if let Some(first) = pts.first().copied() { + pts.push(first); + } + painter.add(egui::Shape::line(pts, Stroke::new((k / 30.0).clamp(0.5, 2.0), color))); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_stroke_font_gives_advances_and_strokes() { + let f = EditorFont { font: String::new(), big_font: String::new(), width_factor: 1.0, oblique: 0.0 }; + let a = advance(&f, false, 'A', 20.0); + let i = advance(&f, false, 'i', 20.0); + assert!(a > 5.0 && a < 30.0, "{a}"); + assert!(i < a, "an i is narrower than an A"); + let wide = EditorFont { width_factor: 2.0, ..f.clone() }; + assert!(advance(&wide, false, 'A', 20.0) > a * 1.5); + assert!(advance(&f, false, ' ', 20.0) > 0.0); + assert!(!glyph(&f, false, 'A').shaped.strokes.is_empty()); + } +} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 0b7db8e0ac..6c790e705a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1406,3 +1406,6 @@ Change Изменение Background color Цвет фона Other color Другой цвет + Current Lineweight Текущий вес линий + Snap the crosshair to grips Привязывать перекрестие к ручкам + With no command running, the crosshair locks onto a grip of the selected objects under it. Когда команда не выполняется, перекрестие притягивается к ручке выбранного объекта под курсором. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6b13b56da5..844e7a0b32 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1711,3 +1711,6 @@ Change Зміна Background color Колір фону Other color Інший колір + Current Lineweight Поточна товщина ліній + Snap the crosshair to grips Прив’язувати перехрестя до ручок + With no command running, the crosshair locks onto a grip of the selected objects under it. Коли команда не виконується, перехрестя притягується до ручки вибраного об’єкта під курсором. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e6b62edc01..2c9cea7780 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,7 @@ pub mod custom_patterns; pub mod dialogs; pub mod dimstyles; pub mod docking; +pub mod editor_glyphs; pub mod hatchdlg; mod mtext_editor; pub mod spacemouse; @@ -86,6 +87,10 @@ pub struct UiState { pub toolsets_bar: toolbar::BarState, /// The Layers bar (layer tools and the current layer): shown, dock, buttons. pub layers_bar: toolbar::BarState, + /// The current-lineweight drop-down was added to a Layers bar saved before it existed + /// (missing from saved settings: not yet). + #[serde(default)] + pub lweight_combo_added: bool, pub show_file_tabs: bool, pub show_status_bar: bool, pub show_command_line: bool, @@ -184,6 +189,7 @@ impl Default for UiState { toolbar_items: toolbar::default_items(), toolsets_bar: toolbar::Bar::ToolSets.default_state(), layers_bar: toolbar::Bar::Layers.default_state(), + lweight_combo_added: true, show_file_tabs: true, show_status_bar: true, show_command_line: true, diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 88daa03b49..f4f57b322c 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -21,7 +21,7 @@ use crate::CadApp; use crate::theme::Tokens; /// Smallest and largest size of the text in the box, in points: the box stays readable at any zoom. -const MIN_PX: f32 = 13.0; +const MIN_PX: f32 = 18.0; const MAX_PX: f32 = 36.0; /// Families the font list offers besides the one set in the text. const FAMILIES: [&str; 6] = ["Arial", "Times New Roman", "Courier New", "Verdana", "Georgia", "Calibri"]; @@ -47,6 +47,8 @@ struct State { key: String, /// Give the text box the keyboard in the next frame. focus: bool, + /// The text style's font: the text box shows the text in it. + font: crate::editor_glyphs::EditorFont, } fn state_id() -> egui::Id { @@ -89,14 +91,28 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } _ => Formatted::from_contents(&mt.contents), }; - if let Some(f) = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).map(|s| s.font.clone())) { + let style = app.session.doc().ok().and_then(|d| d.text_style(&mt.style).cloned()); + if let Some(f) = style.as_ref().map(|s| s.font.clone()) { // A family name, not a font file (`txt.shx`, `arial.ttf`). if !f.is_empty() && !f.contains('.') { fmt.base_font = f; } } + let font = style + .map(|s| crate::editor_glyphs::EditorFont { font: s.font, big_font: s.big_font, width_factor: s.width_factor, oblique: s.oblique }) + .unwrap_or_else(|| crate::editor_glyphs::EditorFont { width_factor: 1.0, ..Default::default() }); let end = fmt.len(); - State { fmt, typing: CharFmt::default(), typing_at: end, top: 70.0, sel: (end, end), caret: Some(end), key: editor.key.clone(), focus: true } + State { + fmt, + typing: CharFmt::default(), + typing_at: end, + top: 70.0, + sel: (end, end), + caret: Some(end), + key: editor.key.clone(), + focus: true, + font, + } }); let line = kind == EditorKind::Line; let cell = matches!(kind, EditorKind::TableCell { .. }); @@ -689,45 +705,45 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, } let fmt = st.fmt.clone(); let default_color = t.text; + let base = st.font.clone(); + // The font each character is drawn in: an inline family (`\f`) or the style's. + let font_of = move |f: &CharFmt| match &f.font { + Some(fam) if !fam.trim().is_empty() && !fam.eq_ignore_ascii_case(&fmt_base(&base)) => { + crate::editor_glyphs::EditorFont { font: fam.clone(), big_font: String::new(), ..base.clone() } + } + _ => base.clone(), + }; + let size_of = move |f: &CharFmt| f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); + let fmt_l = fmt.clone(); + let font_l = font_of.clone(); let mut layouter = move |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| -> Arc { let mut job = LayoutJob::default(); job.wrap.max_width = wrap; - let s = text.as_str(); - let mut run = String::new(); - let mut cur: Option = None; - let flush = |job: &mut LayoutJob, run: &mut String, f: &CharFmt| { - if run.is_empty() { - return; - } - let size = f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); + // One section per character, its advance set to the drawing font's (the difference is + // its leading space, so the caret after it lands where the drawing's would), the egui + // glyph itself invisible: the drawing font is painted over it (see `paint_glyphs`). + for (i, c) in text.as_str().chars().enumerate() { + let f = fmt_l.fmt_at(i); + let size = size_of(&f); let color = f.color.map_or(default_color, color32); + let font_id = FontId::proportional(size); + let spacing = if c == '\n' { + 0.0 + } else { + let real = crate::editor_glyphs::advance(&font_l(&f), f.italic, c, size); + let shown = ui.fonts_mut(|fs| fs.glyph_width(&font_id, c)); + real - shown + }; job.append( - run, - 0.0, + &c.to_string(), + spacing, TextFormat { - font_id: FontId::proportional(size), - color, - italics: f.italic, + font_id, + color: Color32::TRANSPARENT, underline: if f.underline { Stroke::new(1.0, color) } else { Stroke::NONE }, - // The editor has one weight of each font: bold is shown wider. - extra_letter_spacing: if f.bold { size * 0.06 } else { 0.0 }, ..TextFormat::default() }, ); - run.clear(); - }; - for (i, c) in s.chars().enumerate() { - let f = fmt.fmt_at(i); - if cur.as_ref() != Some(&f) { - if let Some(p) = &cur { - flush(&mut job, &mut run, p); - } - cur = Some(f); - } - run.push(c); - } - if let Some(p) = &cur { - flush(&mut job, &mut run, p); } ui.fonts_mut(|f| f.layout_job(job)) }; @@ -744,6 +760,7 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, out.response.request_focus(); } st.focus = false; + paint_glyphs(ui, &out, &fmt, &font_of, &size_of, default_color); if out.response.changed() { let typing = st.typing.clone(); st.fmt.set_text(&buf, &typing); @@ -763,6 +780,42 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, } } +/// The style font's family as an inline font switch would name it (`txt.shx` → `txt`). +fn fmt_base(f: &crate::editor_glyphs::EditorFont) -> String { + let n = f.font.trim(); + n.rsplit(['\\', '/']).next().unwrap_or(n).split('.').next().unwrap_or("").to_string() +} + +/// Draw the text box's characters in the drawing's fonts, where the box laid them out. +fn paint_glyphs( + ui: &egui::Ui, + out: &egui::text_edit::TextEditOutput, + fmt: &Formatted, + font_of: &impl Fn(&CharFmt) -> crate::editor_glyphs::EditorFont, + size_of: &impl Fn(&CharFmt) -> f32, + default_color: Color32, +) { + let painter = ui.painter().with_clip_rect(out.text_clip_rect); + let mut i = 0usize; + for row in &out.galley.rows { + for g in &row.row.glyphs { + let f = fmt.fmt_at(i); + // The glyph ends at its laid-out right edge (its leading space made up the width). + let font = font_of(&f); + let size = size_of(&f); + let real = crate::editor_glyphs::advance(&font, f.italic, g.chr, size); + let at = out.galley_pos + row.pos.to_vec2() + g.pos.to_vec2() + egui::vec2(g.advance_width - real, 0.0); + let color = f.color.map_or(default_color, color32); + crate::editor_glyphs::paint(&painter, &font, f.italic, f.bold, g.chr, at, size, color); + i += 1; + } + // The line break that ends a paragraph is a character of the text, not a glyph. + if row.ends_with_newline { + i += 1; + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 23465229ee..1378e1b1d3 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -160,6 +160,7 @@ impl Bar { TEXTSTYLE_COMBO, DIMSTYLE_COMBO, LINETYPE_COMBO, + LWEIGHT_COMBO, ], }; ids.iter().map(|s| s.to_string()).collect() @@ -204,6 +205,9 @@ pub const LAYER_COMBO: &str = "layer.combo"; pub const TEXTSTYLE_COMBO: &str = "textstyle.combo"; pub const DIMSTYLE_COMBO: &str = "dimstyle.combo"; pub const LINETYPE_COMBO: &str = "linetype.combo"; +pub const LWEIGHT_COMBO: &str = "lweight.combo"; +/// Width of a drop-down row's preview (a linetype's dashes, a lineweight's line). +const PREVIEW_W: f32 = 64.0; /// Width of the current-layer drop-down in a row. const COMBO_W: f32 = 220.0; /// Width of the style and linetype drop-downs in a row. @@ -264,7 +268,7 @@ fn history_list(app: &CadApp, ui: &mut egui::Ui, undo: bool) -> Option { /// Whether `command` is one of the bars' drop-downs (not a command). pub fn is_combo(command: &str) -> bool { - [LAYER_COMBO, TEXTSTYLE_COMBO, DIMSTYLE_COMBO, LINETYPE_COMBO].contains(&command) + [LAYER_COMBO, TEXTSTYLE_COMBO, DIMSTYLE_COMBO, LINETYPE_COMBO, LWEIGHT_COMBO].contains(&command) } /// A drop-down's width in a row. @@ -288,6 +292,7 @@ const LAYER_TOOLS: &[(Icon, &str, &str)] = &[ (Icon::Text, TEXTSTYLE_COMBO, "Current Text Style"), (Icon::DimLinear, DIMSTYLE_COMBO, "Current Dimension Style"), (Icon::Line, LINETYPE_COMBO, "Current Linetype"), + (Icon::Lineweight, LWEIGHT_COMBO, "Current Lineweight"), ]; /// The default bar: file, undo, output, exchange, navigation, palettes, inquiry and help groups. @@ -567,6 +572,15 @@ pub fn top(app: &mut CadApp, ui: &mut egui::Ui, row: Rect) { /// The other bars docked at the top: one row each, below the menu bar. pub fn top_panels(app: &mut CadApp, ui: &mut egui::Ui) { + // A Layers bar saved before the lineweight drop-down existed gets it after the linetype one. + if !app.ui.lweight_combo_added { + app.ui.lweight_combo_added = true; + let items = &mut app.ui.layers_bar.items; + if !items.iter().any(|i| i == LWEIGHT_COMBO) { + let at = items.iter().position(|i| i == LINETYPE_COMBO).map_or(items.len(), |i| i + 1); + items.insert(at, LWEIGHT_COMBO.to_string()); + } + } let t = Tokens::get(); for bar in [Bar::ToolSets, Bar::Layers] { let st = state(&app.ui, bar); @@ -627,19 +641,139 @@ fn combo_names(app: &CadApp, combo: &str) -> Option<(String, Vec)> { } (d.header.str("CELTYPE", "ByLayer").to_string(), names) } + LWEIGHT_COMBO => { + let mut names: Vec = ["ByLayer", "ByBlock", "Default"].iter().map(|s| s.to_string()).collect(); + names.extend(cadcraft_engine::doc::Lineweight::STANDARD.iter().map(|v| lweight_name(i64::from(*v)))); + (lweight_name(d.header.i64("CELWEIGHT", -1)), names) + } _ => return None, }) } +/// A CELWEIGHT value as the lineweight drop-down names it (`0.25 mm`, ByLayer...). +fn lweight_name(v: i64) -> String { + match v { + -1 => "ByLayer".into(), + -2 => "ByBlock".into(), + -3 => "Default".into(), + v => format!("{:.2} mm", v.clamp(0, 211) as f64 / 100.0), + } +} + +/// What a drop-down row previews beside its name. +enum Preview { + /// Linetype dash patterns (drawing units: dashes positive, gaps negative, dots 0) by + /// lower-case name; ByLayer shows the current layer's. + Linetypes(std::collections::HashMap>, Vec), + /// Lineweights (mm): ByLayer shows the current layer's, Default LWDEFAULT. + Lineweights { layer: f64, default: f64 }, +} + +/// The preview for the drop-down `combo`, if it has one. +fn combo_preview(app: &CadApp, combo: &str) -> Option { + let d = app.session.doc().ok()?; + let clayer = d.header.str("CLAYER", "0").to_string(); + let layer = d.layers.iter().find(|l| l.name.eq_ignore_ascii_case(&clayer)); + match combo { + LINETYPE_COMBO => { + let pattern = |name: &str| { + d.linetypes.iter().find(|l| l.name.eq_ignore_ascii_case(name)).map(|l| l.pattern.iter().map(|e| e.length).collect::>()) + }; + let map = d.linetypes.iter().map(|l| (l.name.to_lowercase(), l.pattern.iter().map(|e| e.length).collect())).collect(); + let by_layer = layer.and_then(|l| pattern(&l.linetype)).unwrap_or_default(); + Some(Preview::Linetypes(map, by_layer)) + } + LWEIGHT_COMBO => { + let default = d.header.i64("LWDEFAULT", 25).clamp(0, 211) as f64 / 100.0; + let layer = layer.map_or(default, |l| match l.lineweight.to_dxf() { + v if v >= 0 => f64::from(v) / 100.0, + _ => default, + }); + Some(Preview::Lineweights { layer, default }) + } + _ => None, + } +} + +/// Paint `name`'s preview in `r`. +fn paint_preview(p: &egui::Painter, r: Rect, preview: &Preview, name: &str, color: egui::Color32) { + let y = r.center().y; + match preview { + Preview::Lineweights { layer, default } => { + let mm = match name { + "ByLayer" => *layer, + "ByBlock" | "Default" => *default, + n => n.trim_end_matches(" mm").trim().parse().unwrap_or(*default), + }; + // Thicker than on screen (3.78 px per mm) so neighbouring weights tell apart. + let w = ((mm * 6.0) as f32).clamp(1.0, 12.0); + p.line_segment([pos2(r.left() + 2.0, y), pos2(r.right() - 2.0, y)], Stroke::new(w, color)); + } + Preview::Linetypes(map, by_layer) => { + let pattern: &[f64] = match name { + "ByLayer" => by_layer, + "ByBlock" => &[], + n => map.get(&n.to_lowercase()).map_or(&[], Vec::as_slice), + }; + let total: f64 = pattern.iter().map(|v| v.abs()).sum(); + let (x0, x1) = (r.left() + 2.0, r.right() - 2.0); + let st = Stroke::new(1.2, color); + if pattern.is_empty() || !(total.is_finite() && total > 1e-9) { + p.line_segment([pos2(x0, y), pos2(x1, y)], st); + return; + } + // About two and a half repeats of the pattern across the preview. + let k = f64::from(x1 - x0) / (2.5 * total); + let mut x = f64::from(x0); + let mut steps = 0; + 'draw: while x < f64::from(x1) { + for v in pattern { + steps += 1; + if steps > 400 || x >= f64::from(x1) { + break 'draw; + } + let len = v.abs() * k; + if *v > 0.0 { + let end = (x + len).min(f64::from(x1)); + p.line_segment([pos2(x as f32, y), pos2(end as f32, y)], st); + } else if *v == 0.0 { + p.circle_filled(pos2(x as f32, y), 1.0, color); + } + x += len.max(if *v == 0.0 { 0.0 } else { 0.5 }); + } + } + } + } +} + /// A drop-down's list of names: picking one makes it current. It scrolls when long. -fn name_list(ui: &mut egui::Ui, salt: &str, current: &str, names: &[String]) -> Option { +fn name_list(ui: &mut egui::Ui, salt: &str, current: &str, names: &[String], preview: Option<&Preview>) -> Option { let mut picked = None; + let t = Tokens::get(); // A scroll bar that is always there once the list is longer than the drop-down. ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt(("cc_combo_list", salt)).max_height(COMBO_LIST_H).auto_shrink([false, true]).show(ui, |ui| { for n in names { - let shown = if ["ByLayer", "ByBlock"].contains(&n.as_str()) { crate::i18n::t(n).to_string() } else { n.clone() }; - if ui.selectable_label(n.eq_ignore_ascii_case(current), shown).clicked() { + let shown = if ["ByLayer", "ByBlock", "Default"].contains(&n.as_str()) { crate::i18n::t(n).to_string() } else { n.clone() }; + let on = n.eq_ignore_ascii_case(current); + let Some(pv) = preview else { + if ui.selectable_label(on, shown).clicked() { + picked = Some(n.clone()); + } + continue; + }; + // Preview | separator | name. + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); + let p = ui.painter(); + if on || resp.hovered() { + p.rect_filled(r, 2.0, if on { t.accent.gamma_multiply(0.45) } else { t.control_hover }); + } + let pr = Rect::from_min_size(pos2(r.left() + 4.0, r.top()), vec2(PREVIEW_W, r.height())); + paint_preview(p, pr, pv, n, t.text); + let sep = pr.right() + 5.0; + p.vline(sep, (r.top() + 3.0)..=(r.bottom() - 3.0), Stroke::new(1.0, t.border)); + p.text(pos2(sep + 6.0, r.center().y), egui::Align2::LEFT_CENTER, shown, crate::theme::body(), t.text); + if resp.clicked() { picked = Some(n.clone()); } } @@ -847,12 +981,13 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B } else if combo { if let Some((cur, list)) = &names { let command = tool.command; + let preview = combo_preview(app, command); egui::Popup::from_toggle_button_response(&resp) .align(align) .width(STYLE_COMBO_W.max(200.0)) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { - if let Some(n) = name_list(ui, command, cur, list) { + if let Some(n) = name_list(ui, command, cur, list, preview.as_ref()) { action = Some(Action::SetCurrent(command, n)); ui.close(); } @@ -961,7 +1096,8 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B if is_combo(tool.command) { if let Some((cur, list)) = combo_names(app, tool.command) { ui.label(RichText::new(crate::i18n::t(tool.label)).weak()); - if let Some(n) = name_list(ui, tool.command, &cur, &list) { + let preview = combo_preview(app, tool.command); + if let Some(n) = name_list(ui, tool.command, &cur, &list, preview.as_ref()) { action = Some(Action::SetCurrent(tool.command, n)); ui.close(); } @@ -1025,6 +1161,13 @@ fn strip(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, vertical: bool, bar: B let r = match combo { TEXTSTYLE_COMBO => app.run("style.current", json!({ "name": name })), DIMSTYLE_COMBO => app.run("dimstyle.current", json!({ "name": name })), + LWEIGHT_COMBO => { + let v = match name.trim_end_matches(" mm").trim().parse::() { + Ok(mm) => json!(mm), + Err(_) => json!(name), + }; + app.run("lweight", json!({ "lineweight": v })) + } _ => app.run("linetype", json!({ "current": name })), }; if let Err(e) = r { From c8f5247c56395544070ffaaaa87c7942d9a3ac65 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 11:29:31 +0300 Subject: [PATCH 07/23] WIP b15: properties scroll lists, layout fit, recent previews, text justify/backwards/frame, bidi text editor, text formulas (in progress) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- Cargo.lock | 86 ++ apps/cadcraft-cli/src/main.rs | 3 + crates/constraints/src/tests.rs | 2 + crates/doc/src/entity.rs | 17 + crates/doc/src/extents.rs | 3 + crates/doc/src/tests.rs | 7 + crates/engine/Cargo.toml | 5 + crates/engine/src/cmd/annotate.rs | 4 + crates/engine/src/cmd/blocks.rs | 4 + crates/engine/src/cmd/draw.rs | 7 + crates/engine/src/cmd/file.rs | 7 + crates/engine/src/cmd/modify.rs | 5 + crates/engine/src/cmd/modify2.rs | 4 + crates/engine/src/cmd/mtext_opts.rs | 2 + crates/engine/src/cmd/props.rs | 112 ++- crates/engine/src/cmd/table/cells.rs | 2 + crates/engine/src/cmd/tolerance.rs | 3 + crates/engine/src/cmd/view.rs | 17 +- crates/engine/src/sample.rs | 5 +- crates/engine/src/spatial.rs | 3 + crates/engine/src/textformula.rs | 906 ++++++++++++++++++++ crates/engine/tests/attrib_modes.rs | 2 + crates/engine/tests/audit.rs | 2 + crates/engine/tests/mtext_columns.rs | 1 + crates/engine/tests/multiline_attributes.rs | 3 + crates/engine/tests/snap_annotations.rs | 2 + crates/engine/tests/text_justify.rs | 61 ++ crates/io/src/dxf_mleader.rs | 2 + crates/io/src/dxf_read.rs | 9 + crates/io/src/dxf_write.rs | 13 + crates/io/src/tests.rs | 11 + crates/io/tests/annotative_roundtrip.rs | 2 + crates/io/tests/attrib_modes.rs | 2 + crates/io/tests/attrib_props.rs | 2 + crates/io/tests/dxf_versions.rs | 2 + crates/io/tests/entity_props_roundtrip.rs | 2 + crates/io/tests/followups_626.rs | 3 + crates/io/tests/mleader_roundtrip.rs | 3 + crates/io/tests/mtext_columns_roundtrip.rs | 1 + crates/io/tests/mtext_embedded_object.rs | 1 + crates/io/tests/mtext_line_spacing.rs | 1 + crates/io/tests/pdf_text.rs | 4 + crates/io/tests/text_flags_roundtrip.rs | 44 + crates/render/src/lib.rs | 35 +- crates/render/src/raster.rs | 14 + crates/render/src/tests.rs | 25 +- crates/render/tests/annotative_viewport.rs | 2 + crates/render/tests/render_props.rs | 2 + crates/ui-egui/src/bidi_edit.rs | 629 ++++++++++++++ crates/ui-egui/src/chrome.rs | 167 +++- crates/ui-egui/src/layers.rs | 2 +- crates/ui-egui/src/lib.rs | 6 + crates/ui-egui/src/mtext_editor.rs | 138 +-- crates/ui-egui/src/palettes.rs | 114 ++- crates/ui-egui/src/quick.rs | 2 +- crates/ui-egui/src/thumbs.rs | 426 +++++++++ 56 files changed, 2789 insertions(+), 150 deletions(-) create mode 100644 crates/engine/src/textformula.rs create mode 100644 crates/engine/tests/text_justify.rs create mode 100644 crates/io/tests/text_flags_roundtrip.rs create mode 100644 crates/ui-egui/src/bidi_edit.rs create mode 100644 crates/ui-egui/src/thumbs.rs diff --git a/Cargo.lock b/Cargo.lock index 043ca01ecf..c2ee34137f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,6 +635,7 @@ dependencies = [ "cadcraft-io", "cadcraft-render", "craft-docpath", + "jiff", "log", "rstar", "serde", @@ -997,6 +998,37 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "defmt" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "defmt-parser" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "dify" version = "0.8.0" @@ -1949,6 +1981,60 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "jiff-tzdb-platform", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jiff-tzdb" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7" + +[[package]] +name = "jiff-tzdb-platform" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8" +dependencies = [ + "jiff-tzdb", +] + [[package]] name = "jni" version = "0.22.4" diff --git a/apps/cadcraft-cli/src/main.rs b/apps/cadcraft-cli/src/main.rs index 550d550e79..1db609955f 100644 --- a/apps/cadcraft-cli/src/main.rs +++ b/apps/cadcraft-cli/src/main.rs @@ -398,6 +398,9 @@ fn synthetic(n: usize, side: f64) -> Result EntityKind::Text(d::Text { + formula: None, + backwards: false, + upside_down: false, insert: v3(x, y), align_pt: None, height: s * 0.2, diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index 6db26c95eb..a3731dc297 100644 --- a/crates/constraints/src/tests.rs +++ b/crates/constraints/src/tests.rs @@ -318,6 +318,8 @@ fn invalid_references_and_purge() { let t = add_e( &mut d, EntityKind::Text(cadcraft_doc::Text { + backwards: false, + upside_down: false, insert: v(0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index df9ad57ee0..be37a5eca5 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -232,6 +232,16 @@ pub struct Text { pub halign: HAlign, #[serde(default)] pub valign: VAlign, + /// Mirrored left to right (DXF 71 bit 2; set from the style when the text is made). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub backwards: bool, + /// Mirrored top to bottom (DXF 71 bit 4). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub upside_down: bool, + /// The formula the text shows the result of: `=...` (CADCraft text formulas) or an AutoCAD + /// field code (`%<\AcVar date \f "dd.MM.yyyy">%`). `value` holds the last result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formula: Option, } impl Text { /// The point the text is placed by, as the Insertion snap and the grip show it: the alignment @@ -280,6 +290,13 @@ pub struct MText { /// one column. #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option, + /// A frame drawn around the text (DXF 90 bit 16, "Text frame"). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub frame: bool, + /// The formula the text shows the result of (see [`Text::formula`]); `contents` holds the + /// last result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formula: Option, } fn attach_tl() -> u8 { 1 diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index aed018a961..e84065a165 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -280,6 +280,8 @@ mod tests { fn text(halign: HAlign, valign: VAlign) -> Text { Text { + backwards: false, + upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: Some(Vec3::new(0.0, 0.0, 0.0)), height: 1.0, @@ -334,6 +336,7 @@ mod tests { #[test] fn multileader_text_is_inside_its_bounds() { let mtext = crate::MText { + frame: false, insert: Vec3::new(25.45, 0.0, 0.0), height: 5.0, width: 0.0, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 1d99de9750..352d99c2e1 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -86,6 +86,8 @@ fn visible_attributes_of_a_missing_block_still_count() { let attrib = |invisible: bool| Attrib { tag: "TAG".into(), text: Text { + backwards: false, + upside_down: false, insert: Vec3::new(1000.0, 1000.0, 0.0), align_pt: None, height: 10.0, @@ -424,6 +426,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() { EntityKind::AttDef(Attrib { tag: "TAG".into(), text: Text { + backwards: false, + upside_down: false, insert: Vec3::new(5000.0, 5000.0, 0.0), align_pt: None, height: 1.0, @@ -449,6 +453,8 @@ fn attdef_in_block_is_ignored_in_insert_extents() { fn text_kind(value: &str) -> EntityKind { EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::new(10.0, 10.0, 0.0), align_pt: None, height: 2.0, @@ -464,6 +470,7 @@ fn text_kind(value: &str) -> EntityKind { fn mtext_kind(contents: &str) -> EntityKind { EntityKind::MText(MText { + frame: false, insert: Vec3::new(10.0, 10.0, 0.0), height: 2.0, width: 0.0, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a19da90f97..af7f9ad3d9 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -24,6 +24,11 @@ log = { workspace = true } # R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0). rstar = { version = "0.12", default-features = false } +# The local date and time for date formulas and fields in text (MIT OR Unlicense). Native only: +# the web build uses UTC. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-bundle-platform", "tzdb-zoneinfo"] } + [dev-dependencies] # Real DXF files for the external reference tests (io is a lower layer). cadcraft-io = { workspace = true } diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 002a84c200..2e45cc51a5 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -441,6 +441,8 @@ fn mleader_kind(s: &Session, pts: &[Vec2], text: &str, landing: bool) -> Option< landing: v3(*landing_pt), dogleg, text: (!text.is_empty()).then(|| MText { + formula: None, + frame: false, insert: v3(tpos), height: th, width: 0.0, @@ -490,6 +492,8 @@ fn run_leader(s: &mut Session, p: &Value) -> Result { let th = s.doc()?.dim_style(&style(s)).map(|d| d.text_height).unwrap_or(0.18); out.push( s.add_entity(EntityKind::MText(MText { + formula: None, + frame: false, insert: v3(*last + Vec2::new(th * 0.5, th * 0.5)), height: th, width: 0.0, diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index c2caf136ae..5d3c9e414d 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -263,9 +263,13 @@ fn run_insert(s: &mut Session, p: &Value) -> Result { fn attdef_kind(s: &Session, tag: &str, prompt: &str, default: &str, at: Vec2, height: f64, invisible: bool) -> EntityKind { let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); + let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style).map(|st| (st.backwards, st.upside_down))).unwrap_or((false, false)); EntityKind::AttDef(Attrib { tag: tag.to_ascii_uppercase(), text: Text { + formula: None, + backwards, + upside_down, insert: v3(at), align_pt: None, height, diff --git a/crates/engine/src/cmd/draw.rs b/crates/engine/src/cmd/draw.rs index 54efa8b51b..71993878e3 100644 --- a/crates/engine/src/cmd/draw.rs +++ b/crates/engine/src/cmd/draw.rs @@ -327,9 +327,14 @@ pub(crate) fn justify(j: &str) -> Option<(HAlign, VAlign)> { pub(crate) fn make_text(s: &Session, at: Vec2, value: &str, height: f64, rotation: f64, j: (HAlign, VAlign)) -> EntityKind { let style = s.doc().map(|d| d.header.str("TEXTSTYLE", "Standard")).unwrap_or_else(|_| "Standard".into()); + // New text takes its style's Backwards and Upside down, as AutoCAD. + let (backwards, upside_down) = s.doc().ok().and_then(|d| d.text_style(&style).map(|st| (st.backwards, st.upside_down))).unwrap_or((false, false)); let (h, v) = j; let left = h == HAlign::Left && v == VAlign::Baseline; EntityKind::Text(Text { + formula: None, + backwards, + upside_down, insert: v3(at), align_pt: if left { None } else { Some(v3(at)) }, height, @@ -372,6 +377,8 @@ fn run_mtext(s: &mut Session, p: &Value) -> Result { }; let width = f64_or(p, "width", 0.0).max(0.0); let k = EntityKind::MText(MText { + formula: None, + frame: false, insert: v3(at), height, width, diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 20167175d8..8a8de3f407 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -333,6 +333,13 @@ pub struct ReadFile { path: Option, } +impl ReadFile { + /// The drawing read (for a preview of it before, or without, opening it). + pub fn drawing(&self) -> &Drawing { + &self.drawing + } +} + /// Read and decode `path` (the slow half of `OPEN {path}`). Needs no session; runs anywhere. pub fn read_file(path: &str) -> std::result::Result { #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 37533b13c2..f7a3442d72 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -1315,6 +1315,9 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option Option cadcraft_doc::MText { let left_baseline = t.halign == HAlign::Left && t.valign == VAlign::Baseline; let at = if left_baseline { t.insert } else { t.align_pt.unwrap_or(t.insert) }; cadcraft_doc::MText { + formula: None, + frame: false, insert: at, height: t.height, width: 0.0, @@ -2217,6 +2219,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { let g = cadcraft_render::dimension_in(d, dm); let measured = cadcraft_render::dimension_in(d, &cadcraft_doc::Dimension { text: String::new(), block: None, ..dm.clone() }).value; let mtext = cadcraft_doc::MText { + formula: None, + frame: false, insert: g.text_pos.to3(0.0), height: if g.text_height > 0.0 && g.text_height.is_finite() { g.text_height } else { 0.18 }, width: 0.0, diff --git a/crates/engine/src/cmd/mtext_opts.rs b/crates/engine/src/cmd/mtext_opts.rs index c234271bf8..9813639b60 100644 --- a/crates/engine/src/cmd/mtext_opts.rs +++ b/crates/engine/src/cmd/mtext_opts.rs @@ -79,6 +79,8 @@ impl MTextOpts { (None, w) => (first, w.unwrap_or(0.0)), }; MText { + formula: None, + frame: false, insert: Vec3::new(insert.x, insert.y, 0.0), height: self.height, width, diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 8f9ac4b82c..7f6c209797 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -16,7 +16,7 @@ use crate::{Result, Session}; pub fn specs() -> Vec { vec![ CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(), - CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; textStyle (text, multiline text, multileaders); hatches: pattern, scale, angle, background (colour | \"None\"); multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), + CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, ; textStyle (text, multiline text, multileaders); text: justify (L C R A M F TL TC TR ML MC MR BL BC BR; the letters stay in place), backwards, upsideDown; multiline text: justify (TL..BR), frame; hatches: pattern, scale, angle, background (colour | \"None\"); multileaders: mleaderStyle, arrow (arrowhead name or block; \"\" = the style's), arrowSize, leaderType: straight|spline|none, dogleg (landing distance; 0 = no landing), textHeight}"), CommandSpec::new("matchprop", "Match Properties", matchprop::run_matchprop) .menu(&["Modify", "Match Properties"]) .alias(&["ma", "painter"]) @@ -225,6 +225,23 @@ fn run_set(s: &mut Session, p: &Value) -> Result { let text_style = str_param(p, "textStyle") .map(|n| d.text_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("text style `{n}` not found")))) .transpose()?; + // Justification (text: L C R A M F TL..BR; multiline text: TL..BR), and the text styles it + // lays text out with to keep the letters in place. + let justify = str_param(p, "justify"); + let text_justify = justify.and_then(super::draw::justify); + let mtext_justify = justify.and_then(mtext_attach); + if let Some(j) = justify + && text_justify.is_none() + && mtext_justify.is_none() + { + return Err(bad("properties.set", format!("unknown justification `{j}`"))); + } + let style_doc = justify.map(|_| { + let mut x = cadcraft_doc::Drawing::default(); + x.text_styles = d.text_styles.clone(); + x.header = d.header.clone(); + x + }); let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { @@ -332,6 +349,15 @@ fn run_set(s: &mut Session, p: &Value) -> Result { if let Some(x) = num("widthFactor").filter(|x| *x > 0.0) { t.width_factor = x; } + if let Some(f) = p.get("backwards").and_then(Value::as_bool) { + t.backwards = f; + } + if let Some(f) = p.get("upsideDown").and_then(Value::as_bool) { + t.upside_down = f; + } + if let (Some((h, v)), Some(sd)) = (text_justify, &style_doc) { + rejustify_text(sd, t, h, v); + } // The position is the point the text is placed by: moving it moves the text. if let Some(to) = p.get("position").and_then(point_value) { let d = to - t.justify_point(); @@ -354,6 +380,12 @@ fn run_set(s: &mut Session, p: &Value) -> Result { if let Some(x) = num("rotation") { t.rotation = x.to_radians(); } + if let Some(f) = p.get("frame").and_then(Value::as_bool) { + t.frame = f; + } + if let (Some(a), Some(sd)) = (mtext_justify, &style_doc) { + rejustify_mtext(sd, t, a); + } } EntityKind::LwPolyline(pl) => { if let Some(x) = num("width").filter(|x| *x >= 0.0) { @@ -1156,3 +1188,81 @@ mod tests { } } } + +/// An MTEXT attachment (1..=9) from a justification code: TL TC TR ML MC MR BL BC BR (or 1..9). +fn mtext_attach(j: &str) -> Option { + let u = j.trim().to_ascii_uppercase(); + ["TL", "TC", "TR", "ML", "MC", "MR", "BL", "BC", "BR"] + .iter() + .position(|c| *c == u) + .and_then(|i| u8::try_from(i + 1).ok()) + .or_else(|| u.parse::().ok().filter(|a| (1..=9).contains(a))) +} + +/// Give text another justification without moving it: the point it is placed by moves so the +/// letters stay where they are (aligned and fit text span the text's own width). +fn rejustify_text(d: &cadcraft_doc::Drawing, t: &mut cadcraft_doc::Text, h: cadcraft_doc::HAlign, v: cadcraft_doc::VAlign) { + use cadcraft_doc::{HAlign, VAlign}; + let before = cadcraft_render::place_text_entity(d, t, &t.value).1; + // The baseline's start: where left-baseline text at the same spot would begin. + let mut left = t.clone(); + (left.halign, left.valign, left.align_pt) = (HAlign::Left, VAlign::Baseline, None); + let at = t.justify_point(); + left.insert = cadcraft_geom::Vec3::new(at.x, at.y, t.insert.z); + let lb = cadcraft_render::place_text_entity(d, &left, &t.value).1; + let start = if before.is_empty() || lb.is_empty() { t.insert.xy() } else { at + (before.min - lb.min) }; + let width = match t.halign { + HAlign::Aligned | HAlign::Fit => t.align_pt.map_or(0.0, |a| a.xy().dist(t.insert.xy())), + _ => { + let font = d.text_style(&t.style).map(|st| cadcraft_fonts::TextFont::resolve_style(&st.font, &st.big_font)).unwrap_or_default(); + cadcraft_fonts::text_width(&font, &t.value, t.height, t.width_factor) + } + }; + let z = t.insert.z; + let v3 = |p: Vec2| cadcraft_geom::Vec3::new(p.x, p.y, z); + t.halign = h; + t.valign = v; + t.insert = v3(start); + match (h, v) { + (HAlign::Left, VAlign::Baseline) => t.align_pt = None, + (HAlign::Aligned | HAlign::Fit, _) => { + t.valign = VAlign::Baseline; + t.align_pt = Some(v3(start + Vec2::from_angle(t.rotation) * width.max(t.height * 0.1))); + } + _ => { + // Place by the start, then shift by how far the letters moved. + t.align_pt = Some(v3(start)); + let after = cadcraft_render::place_text_entity(d, t, &t.value).1; + if !before.is_empty() && !after.is_empty() { + let shift = before.min - after.min; + if shift.is_finite() { + for q in std::iter::once(&mut t.insert).chain(t.align_pt.as_mut()) { + q.x += shift.x; + q.y += shift.y; + } + } + } + } + } +} + +/// Give multiline text another attachment without moving it: the insertion point moves to the +/// matching point of the text's box. +fn rejustify_mtext(d: &cadcraft_doc::Drawing, t: &mut cadcraft_doc::MText, attach: u8) { + // Laid out unrotated, at the same insertion point: the letters' shift between the two + // attachments, turned back by the rotation. + let mut flat = t.clone(); + flat.rotation = 0.0; + let before = cadcraft_render::layout_mtext_entity(d, &flat).bounds; + flat.attach = attach; + let after = cadcraft_render::layout_mtext_entity(d, &flat).bounds; + t.attach = attach; + if before.is_empty() || after.is_empty() { + return; + } + let shift = (before.min - after.min).rotate(t.rotation); + if shift.is_finite() { + t.insert.x += shift.x; + t.insert.y += shift.y; + } +} diff --git a/crates/engine/src/cmd/table/cells.rs b/crates/engine/src/cmd/table/cells.rs index cdeb8e62d0..7e9028620b 100644 --- a/crates/engine/src/cmd/table/cells.rs +++ b/crates/engine/src/cmd/table/cells.rs @@ -513,6 +513,8 @@ fn cell_editor(s: &Session, h: Handle, r: usize, c: usize) -> Option= 0.0 { margin.min(w * 0.25) } else { 0.0 }; let mtext = cadcraft_doc::MText { + formula: None, + frame: false, insert: (corner + Vec2::new(margin, -margin)).to3(t.insert.z), height, width: (w - 2.0 * margin).max(height), diff --git a/crates/engine/src/cmd/tolerance.rs b/crates/engine/src/cmd/tolerance.rs index 1a33a5670f..37d928fe25 100644 --- a/crates/engine/src/cmd/tolerance.rs +++ b/crates/engine/src/cmd/tolerance.rs @@ -296,6 +296,9 @@ pub(crate) fn explode(d: &Drawing, e: &Entity, t: &Tolerance) -> Vec { } for tx in &g.texts { v.push(mk(EntityKind::Text(cadcraft_doc::Text { + formula: None, + backwards: false, + upside_down: false, insert: v3(tx.pos), align_pt: None, height: tx.height, diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index e6051a6e9d..2f7caa1abc 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -282,6 +282,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { Space::Paper(l.name.clone()) }; s.pending_window = None; + let (px_w, px_h) = s.viewport_px; let st = s.state_mut()?; st.space = space.clone(); st.mspace = None; @@ -289,11 +290,17 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result { if let Space::Paper(n) = &space && !st.views.iter().any(|(sp, _)| sp == &space) { - // Default paper view: the sheet. - let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); - let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; - let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; - st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15 }); + // A layout shown for the first time: the whole sheet fits the screen, with a margin. + let b = cadcraft_render::sheet(&st.doc, n).map(|sh| sh.bounds()).filter(|b| !b.is_empty() && b.width() > 0.0 && b.height() > 0.0); + let b = b.unwrap_or_else(|| { + let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default(); + let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) }; + let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 }; + cadcraft_geom::Bounds2::new(Vec2::ZERO, Vec2::new(w * unit, h * unit)) + }); + let aspect = if px_w > 1.0 && px_h > 1.0 { px_w / px_h } else { 1.5 }; + let height = b.height().max(b.width() / aspect).max(1e-9) * 1.08; + st.set_view_quiet(View { center: b.center(), height }); } s.touch(); ok() diff --git a/crates/engine/src/sample.rs b/crates/engine/src/sample.rs index 85a222f64b..c59971f2bc 100644 --- a/crates/engine/src/sample.rs +++ b/crates/engine/src/sample.rs @@ -37,6 +37,9 @@ fn dim(kind: DimKind, p13: Vec2, p14: Vec2, defpt: Vec2) -> EntityKind { fn text(at: Vec2, h: f64, s: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, + backwards: false, + upside_down: false, insert: v3(at), align_pt: None, height: h, @@ -211,7 +214,7 @@ pub fn bracket() -> Drawing { add(on("Notes"), text(Vec2::new(4.1, -0.3), 0.16, "FRONT VIEW")); add( on("Notes"), - EntityKind::MText(MText { insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), + EntityKind::MText(MText { formula: None, frame: false, insert: v3(Vec2::new(14.2, 6.2)), height: 0.12, width: 3.4, attach: 1, rotation: 0.0, style: "Standard".into(), contents: "NOTES:\\P1. MATERIAL: 6061-T6 ALUMINUM.\\P2. BREAK ALL SHARP EDGES 0.02 MAX.\\P3. BORE %%c1.750 THRU, H7.\\P4. FINISH: CLEAR ANODIZE.".into(), line_spacing: 1.0, line_spacing_exact: false, columns: None }), ); let tb0 = Vec2::new(14.0, -0.5); add(on("Title"), lwpoly(rect_vertices(tb0, tb0 + Vec2::new(4.0, 2.0)), true)); diff --git a/crates/engine/src/spatial.rs b/crates/engine/src/spatial.rs index 98999b71f4..9c3be89ee4 100644 --- a/crates/engine/src/spatial.rs +++ b/crates/engine/src/spatial.rs @@ -330,6 +330,9 @@ mod tests { plinegen: false, }), 5 => EntityKind::Text(Text { + formula: None, + backwards: false, + upside_down: false, insert: v3(x, y), align_pt: None, height: s * 0.3, diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs new file mode 100644 index 0000000000..02dbd78cd2 --- /dev/null +++ b/crates/engine/src/textformula.rs @@ -0,0 +1,906 @@ +//! Formulas in text, as in a spreadsheet: a text whose value starts with `=` shows the result +//! of the formula (`=2400-2*18`, `=TEXT(TODAY(),"dd.mm.yyyy")`, `=ROUND(PI()*125^2/1000000,3)`). +//! The formula is kept with the text ([`cadcraft_doc::Text::formula`]) and worked out again +//! when the drawing is opened (dates follow the computer's clock) and when it is edited. +//! +//! AutoCAD fields read from drawings (`%<\AcVar date \f "dd.MM.yyyy">%`) are worked out the same +//! way when CADCraft knows them (dates, the file name); others keep the value AutoCAD saved. +//! +//! The functions are listed in [`FUNCTIONS`] (name, arguments, description), which the editor's +//! completion list and Help show. + +use cadcraft_doc::{Drawing, EntityKind}; + +/// Longest formula worked out. +const MAX_LEN: usize = 2000; +/// Deepest nesting. +const MAX_DEPTH: usize = 40; +/// Most arguments of one function. +const MAX_ARGS: usize = 255; + +/// The functions: (name, arguments, description). Shown by completion and Help. +pub const FUNCTIONS: &[(&str, &str, &str)] = &[ + ("ABS", "number", "The number without its sign."), + ("ACOS", "number", "Arccosine, in radians."), + ("AND", "logical1, logical2, ...", "TRUE when all arguments are true."), + ("ASIN", "number", "Arcsine, in radians."), + ("ATAN", "number", "Arctangent, in radians."), + ("AVERAGE", "number1, number2, ...", "The average of the numbers."), + ("CONCAT", "text1, text2, ...", "Joins texts (as the & operator)."), + ("COS", "angle", "Cosine of an angle in radians."), + ("DATE", "year, month, day", "A date."), + ("DAY", "date", "The day of the month of a date."), + ("DEGREES", "angle", "Radians to degrees."), + ("EXP", "number", "e raised to a power."), + ("FILENAME", "", "The drawing's file name."), + ("FIXED", "number, decimals", "A number as text with that many decimals."), + ("HOUR", "time", "The hour of a time."), + ("IF", "condition, value_if_true, value_if_false", "One of two values, by a condition."), + ("INT", "number", "Rounds down to an integer."), + ("LEFT", "text, count", "The first characters of a text."), + ("LEN", "text", "The number of characters of a text."), + ("LN", "number", "Natural logarithm."), + ("LOG10", "number", "Base-10 logarithm."), + ("LOWER", "text", "A text in lower case."), + ("MAX", "number1, number2, ...", "The largest number."), + ("MID", "text, start, count", "Characters from the middle of a text (start = 1 for the first)."), + ("MIN", "number1, number2, ...", "The smallest number."), + ("MINUTE", "time", "The minutes of a time."), + ("MOD", "number, divisor", "The remainder of a division."), + ("MONTH", "date", "The month of a date (1 to 12)."), + ("NOT", "logical", "The opposite of a logical value."), + ("NOW", "", "The current date and time (worked out again when the drawing is opened)."), + ("OR", "logical1, logical2, ...", "TRUE when any argument is true."), + ("PI", "", "The number π."), + ("POWER", "number, power", "A number raised to a power (as ^)."), + ("RADIANS", "angle", "Degrees to radians."), + ("RIGHT", "text, count", "The last characters of a text."), + ("ROUND", "number, decimals", "Rounds to that many decimals."), + ("ROUNDDOWN", "number, decimals", "Rounds toward zero."), + ("ROUNDUP", "number, decimals", "Rounds away from zero."), + ("SHEET", "", "The name of the current layout (\"Model\" in model space)."), + ("SIN", "angle", "Sine of an angle in radians."), + ("SQRT", "number", "Square root."), + ("SUM", "number1, number2, ...", "Adds the numbers."), + ("TAN", "angle", "Tangent of an angle in radians."), + ("TEXT", "value, format", "A value as text in a format: \"0.00\", \"#,##0\", \"0%\", \"dd.mm.yyyy\", \"hh:mm\"..."), + ("TODAY", "", "Today's date (worked out again when the drawing is opened)."), + ("TRIM", "text", "A text without spaces at its ends and double spaces."), + ("UPPER", "text", "A text in capitals."), + ("YEAR", "date", "The year of a date."), +]; + +/// What a formula can refer to: the time, the file and the layout. +#[derive(Clone, Debug, PartialEq)] +pub struct Env { + /// Local date and time: year, month, day, hour, minute, second. + pub now: (i32, u32, u32, u32, u32, u32), + pub file: String, + pub sheet: String, +} + +impl Default for Env { + fn default() -> Self { + Env { now: (2000, 1, 1, 0, 0, 0), file: String::new(), sheet: "Model".into() } + } +} + +/// The local date and time now (UTC where the time zone is unknown). +pub fn local_now() -> (i32, u32, u32, u32, u32, u32) { + #[cfg(not(target_arch = "wasm32"))] + { + let z = jiff::Zoned::now(); + let clamp = |v: i8| u32::try_from(v).unwrap_or(0); + (i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second())) + } + #[cfg(target_arch = "wasm32")] + { + (2000, 1, 1, 0, 0, 0) + } +} + +/// The environment of a session's drawing. +pub fn env(s: &crate::Session) -> Env { + let file = s + .state() + .ok() + .map(|st| match &st.path { + Some(p) => std::path::Path::new(p).file_name().map_or_else(|| p.clone(), |n| n.to_string_lossy().into_owned()), + None => st.title.clone(), + }) + .unwrap_or_default(); + Env { now: local_now(), file, sheet: s.space().tab_name().to_string() } +} + +/// Whether `text` is a formula (starts with `=`, after spaces). +pub fn is_formula(text: &str) -> bool { + text.trim_start().starts_with('=') && text.trim().len() > 1 +} + +/// Whether `text` holds AutoCAD field codes. +pub fn has_fields(text: &str) -> bool { + text.contains("%<\\") +} + +/// Work out a formula (`=...`) or the fields of a field template: the text to show, or `None` +/// for a field CADCraft doesn't know (the saved value stays). +pub fn evaluate(formula: &str, env: &Env) -> Option { + if is_formula(formula) { + return Some(match eval(formula.trim_start().trim_start_matches('='), env) { + Ok(v) => v.show(), + Err(e) => e.to_string(), + }); + } + if has_fields(formula) { + return fields(formula, env); + } + None +} + +// ---------- values ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Val { + Num(f64), + /// A date and time as a serial number (days since 30 December 1899, as spreadsheets). + Date(f64), + Text(String), + Bool(bool), +} + +/// Formula errors, shown as spreadsheets show them. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Err { + /// An unknown function or name. + Name, + /// A wrong kind of value. + Value, + Div0, + /// A number out of range (square root of -1...). + Num, + /// The formula can't be read. + Syntax, +} + +impl std::fmt::Display for Err { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Err::Name => "#NAME?", + Err::Value => "#VALUE!", + Err::Div0 => "#DIV/0!", + Err::Num => "#NUM!", + Err::Syntax => "#ERROR!", + }) + } +} + +type R = std::result::Result; + +impl Val { + fn num(&self) -> std::result::Result { + match self { + Val::Num(v) | Val::Date(v) => Ok(*v), + Val::Bool(b) => Ok(f64::from(u8::from(*b))), + Val::Text(t) => t.trim().replace(',', ".").parse::().map_err(|_| Err::Value), + } + } + fn text(&self) -> String { + self.show() + } + fn truth(&self) -> std::result::Result { + match self { + Val::Bool(b) => Ok(*b), + Val::Text(t) if t.eq_ignore_ascii_case("true") => Ok(true), + Val::Text(t) if t.eq_ignore_ascii_case("false") => Ok(false), + v => Ok(v.num()? != 0.0), + } + } + /// As the text shows it: numbers without trailing zeros (at most 10 decimals), dates as + /// dd.mm.yyyy (with the time when it has one), TRUE/FALSE. + fn show(&self) -> String { + match self { + Val::Num(v) => general(*v), + Val::Date(d) => { + if d.fract().abs() < 1e-9 { + format_date(*d, "dd.mm.yyyy") + } else { + format_date(*d, "dd.mm.yyyy hh:mm") + } + } + Val::Text(t) => t.clone(), + Val::Bool(b) => if *b { "TRUE" } else { "FALSE" }.into(), + } + } +} + +/// A number with at most 10 decimals, trailing zeros dropped. +fn general(v: f64) -> String { + if !v.is_finite() { + return Err::Num.to_string(); + } + if v.abs() >= 1e15 || (v != 0.0 && v.abs() < 1e-10) { + return format!("{v:e}"); + } + let s = format!("{v:.10}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +// ---------- dates ---------- + +/// Days from 1970-01-01 of a civil date (proleptic Gregorian). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn civil_from_days(z: i64) -> (i64, i64, i64) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// The spreadsheet serial of 1970-01-01. +const EPOCH_SERIAL: i64 = 25_569; + +fn serial(y: i64, m: i64, d: i64) -> f64 { + // Months beyond 1..12 roll into the next or previous years, as spreadsheets do. + let (y, m) = (y + (m - 1).div_euclid(12), (m - 1).rem_euclid(12) + 1); + (days_from_civil(y, m, 1) + d - 1 + EPOCH_SERIAL) as f64 +} + +/// (year, month, day, hour, minute, second) of a serial. +fn parts(s: f64) -> (i64, i64, i64, i64, i64, i64) { + let days = s.floor(); + let secs = ((s - days) * 86_400.0).round() as i64; + let (y, m, d) = civil_from_days(days as i64 - EPOCH_SERIAL); + (y, m, d, secs / 3600 % 24, secs / 60 % 60, secs % 60) +} + +const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +/// A date in a spreadsheet date format: d dd ddd? m mm mmm mmmm yy yyyy h hh mm (minutes after +/// h) ss; other characters as they are. +fn format_date(s: f64, fmt: &str) -> String { + let (y, mo, d, h, mi, se) = parts(s); + let chars: Vec = fmt.chars().collect(); + let mut out = String::new(); + let mut i = 0; + let mut after_hour = false; + while let Some(&c) = chars.get(i) { + let run = chars.get(i..).unwrap_or_default().iter().take_while(|x| x.eq_ignore_ascii_case(&c)).count(); + match c.to_ascii_lowercase() { + 'y' => { + out += &if run <= 2 { format!("{:02}", y.rem_euclid(100)) } else { format!("{y:04}") }; + after_hour = false; + } + 'm' if after_hour && run <= 2 => { + out += &if run == 1 { mi.to_string() } else { format!("{mi:02}") }; + after_hour = false; + } + 'm' => { + let name = MONTHS.get(usize::try_from(mo - 1).unwrap_or(0)).copied().unwrap_or(""); + out += &match run { + 1 => mo.to_string(), + 2 => format!("{mo:02}"), + 3 => name.chars().take(3).collect(), + _ => name.into(), + }; + } + 'd' => { + out += &if run == 1 { d.to_string() } else { format!("{d:02}") }; + after_hour = false; + } + 'h' => { + out += &if run == 1 { h.to_string() } else { format!("{h:02}") }; + after_hour = true; + } + 's' => { + out += &if run == 1 { se.to_string() } else { format!("{se:02}") }; + } + _ => { + out.extend(std::iter::repeat_n(c, run)); + } + } + i += run; + } + out +} + +/// A number in a spreadsheet number format: `0`, `0.00`, `#,##0.00`, `0%`, `0.0E+0`-less. +/// Text before and after the digits stays (`"L=" 0.0` → `L=12.5`, quotes dropped). +fn format_number(v: f64, fmt: &str) -> String { + let percent = fmt.contains('%'); + let v = if percent { v * 100.0 } else { v }; + let start = fmt.find(['0', '#']); + let end = fmt.rfind(['0', '#']).map(|e| e + 1); + let (Some(a), Some(b)) = (start, end) else { return fmt.replace('"', "") }; + let core = fmt.get(a..b).unwrap_or("0"); + let decimals = core.split_once('.').map_or(0, |(_, f)| f.chars().filter(|c| *c == '0' || *c == '#').count()); + let grouped = core.split_once('.').map_or(core, |(i, _)| i).contains(','); + let mut s = format!("{:.*}", decimals.min(15), v.abs()); + if grouped { + let (int, frac) = s.split_once('.').map_or((s.clone(), String::new()), |(i, f)| (i.to_string(), format!(".{f}"))); + let mut g = String::new(); + for (k, ch) in int.chars().enumerate() { + if k > 0 && (int.len() - k) % 3 == 0 { + g.push(','); + } + g.push(ch); + } + s = g + &frac; + } + let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') { "-" } else { "" }; + let pre = fmt.get(..a).unwrap_or("").replace('"', ""); + let post = fmt.get(b..).unwrap_or("").replace('"', ""); + format!("{pre}{sign}{s}{post}") +} + +fn looks_like_date_format(f: &str) -> bool { + let l = f.to_ascii_lowercase(); + l.contains('y') || l.contains('d') || l.contains("mm") && !l.contains('0') || l.contains('h') +} + +// ---------- parsing and evaluation ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Num(f64), + Str(String), + Name(String), + Op(&'static str), + LParen, + RParen, + Comma, +} + +fn lex(s: &str) -> std::result::Result, Err> { + let c: Vec = s.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while let Some(&ch) = c.get(i) { + match ch { + ' ' | '\t' => i += 1, + '0'..='9' | '.' => { + let st = i; + while c.get(i).is_some_and(|x| x.is_ascii_digit() || *x == '.') { + i += 1; + } + if c.get(i).is_some_and(|x| *x == 'e' || *x == 'E') && c.get(i + 1).is_some_and(|x| x.is_ascii_digit() || *x == '-' || *x == '+') { + i += 2; + while c.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + let t: String = c.get(st..i).unwrap_or_default().iter().collect(); + out.push(Tok::Num(t.parse().map_err(|_| Err::Syntax)?)); + } + '"' => { + i += 1; + let mut t = String::new(); + loop { + match c.get(i) { + None => return Err(Err::Syntax), + Some('"') if c.get(i + 1) == Some(&'"') => { + t.push('"'); + i += 2; + } + Some('"') => { + i += 1; + break; + } + Some(x) => { + t.push(*x); + i += 1; + } + } + } + out.push(Tok::Str(t)); + } + '(' => { + out.push(Tok::LParen); + i += 1; + } + ')' => { + out.push(Tok::RParen); + i += 1; + } + // `;` separates arguments too (spreadsheets in languages with a decimal comma). + ',' | ';' => { + out.push(Tok::Comma); + i += 1; + } + '<' | '>' => { + let two: String = c.get(i..i + 2).unwrap_or_default().iter().collect(); + let op = match two.as_str() { + "<=" => "<=", + ">=" => ">=", + "<>" => "<>", + _ if ch == '<' => "<", + _ => ">", + }; + i += op.len(); + out.push(Tok::Op(op)); + } + '+' | '-' | '*' | '/' | '^' | '&' | '=' | '%' => { + out.push(Tok::Op(match ch { + '+' => "+", + '-' => "-", + '*' => "*", + '/' => "/", + '^' => "^", + '&' => "&", + '=' => "=", + _ => "%", + })); + i += 1; + } + x if x.is_alphabetic() || x == '_' => { + let st = i; + while c.get(i).is_some_and(|y| y.is_alphanumeric() || *y == '_' || *y == '.') { + i += 1; + } + out.push(Tok::Name(c.get(st..i).unwrap_or_default().iter().collect::().to_ascii_uppercase())); + } + _ => return Err(Err::Syntax), + } + if out.len() > MAX_LEN { + return Err(Err::Syntax); + } + } + Ok(out) +} + +struct P<'a> { + t: Vec, + i: usize, + depth: usize, + env: &'a Env, +} + +fn eval(src: &str, env: &Env) -> R { + if src.len() > MAX_LEN { + return Err(Err::Syntax); + } + let mut p = P { t: lex(src)?, i: 0, depth: 0, env }; + let v = p.compare()?; + if p.i < p.t.len() { + return Err(Err::Syntax); + } + Ok(v) +} + +impl P<'_> { + fn peek(&self) -> Option<&Tok> { + self.t.get(self.i) + } + fn is_op(&self, ops: &[&str]) -> Option<&'static str> { + match self.peek() { + Some(Tok::Op(o)) if ops.contains(o) => Some(o), + _ => None, + } + } + fn compare(&mut self) -> R { + let a = self.concat()?; + if let Some(op) = self.is_op(&["=", "<>", "<", ">", "<=", ">="]) { + self.i += 1; + let b = self.concat()?; + let ord = match (&a, &b) { + (Val::Text(x), Val::Text(y)) => x.to_lowercase().cmp(&y.to_lowercase()), + _ => a.num()?.partial_cmp(&b.num()?).ok_or(Err::Num)?, + }; + use std::cmp::Ordering::*; + return Ok(Val::Bool(match op { + "=" => ord == Equal, + "<>" => ord != Equal, + "<" => ord == Less, + ">" => ord == Greater, + "<=" => ord != Greater, + _ => ord != Less, + })); + } + Ok(a) + } + fn concat(&mut self) -> R { + let mut a = self.sum()?; + while self.is_op(&["&"]).is_some() { + self.i += 1; + let b = self.sum()?; + a = Val::Text(a.text() + &b.text()); + } + Ok(a) + } + fn sum(&mut self) -> R { + let mut a = self.product()?; + while let Some(op) = self.is_op(&["+", "-"]) { + self.i += 1; + let b = self.product()?; + let v = if op == "+" { a.num()? + b.num()? } else { a.num()? - b.num()? }; + // A date plus or minus days is a date; the difference of two dates is a number. + a = match (&a, &b) { + (Val::Date(_), Val::Date(_)) => Val::Num(v), + (Val::Date(_), _) | (_, Val::Date(_)) => Val::Date(v), + _ => Val::Num(v), + }; + } + Ok(a) + } + fn product(&mut self) -> R { + let mut a = self.power()?; + while let Some(op) = self.is_op(&["*", "/"]) { + self.i += 1; + let b = self.power()?; + let (x, y) = (a.num()?, b.num()?); + a = Val::Num(if op == "*" { + x * y + } else { + if y == 0.0 { + return Err(Err::Div0); + } + x / y + }); + } + Ok(a) + } + fn power(&mut self) -> R { + let a = self.unary()?; + if self.is_op(&["^"]).is_some() { + self.i += 1; + let b = self.power()?; + let v = a.num()?.powf(b.num()?); + return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + } + Ok(a) + } + fn unary(&mut self) -> R { + if let Some(op) = self.is_op(&["-", "+"]) { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + self.i += 1; + let v = self.unary()?; + self.depth -= 1; + return Ok(Val::Num(if op == "-" { -v.num()? } else { v.num()? })); + } + let mut v = self.atom()?; + while self.is_op(&["%"]).is_some() { + self.i += 1; + v = Val::Num(v.num()? / 100.0); + } + Ok(v) + } + fn atom(&mut self) -> R { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + let tok = self.peek().cloned(); + self.i += 1; + let r = match tok { + Some(Tok::Num(v)) => Ok(Val::Num(v)), + Some(Tok::Str(s)) => Ok(Val::Text(s)), + Some(Tok::LParen) => { + let v = self.compare()?; + if self.peek() != Some(&Tok::RParen) { + return Err(Err::Syntax); + } + self.i += 1; + Ok(v) + } + Some(Tok::Name(n)) if n == "TRUE" => Ok(Val::Bool(true)), + Some(Tok::Name(n)) if n == "FALSE" => Ok(Val::Bool(false)), + Some(Tok::Name(n)) => { + if self.peek() != Some(&Tok::LParen) { + return Err(Err::Name); + } + self.i += 1; + let mut args = Vec::new(); + if self.peek() != Some(&Tok::RParen) { + loop { + args.push(self.compare()?); + if args.len() > MAX_ARGS { + return Err(Err::Value); + } + match self.peek() { + Some(Tok::Comma) => self.i += 1, + Some(Tok::RParen) => break, + _ => return Err(Err::Syntax), + } + } + } + self.i += 1; + call(&n, &args, self.env) + } + _ => Err(Err::Syntax), + }; + self.depth -= 1; + r + } +} + +fn round_to(x: f64, n: f64, how: fn(f64) -> f64) -> f64 { + let k = 10f64.powi(n.clamp(-15.0, 15.0) as i32); + how(x * k) / k +} + +fn arg(a: &[Val], i: usize) -> std::result::Result<&Val, Err> { + a.get(i).ok_or(Err::Value) +} + +fn nums(a: &[Val]) -> std::result::Result, Err> { + a.iter().map(Val::num).collect() +} + +fn call(name: &str, a: &[Val], env: &Env) -> R { + let n0 = |a: &[Val]| arg(a, 0).and_then(Val::num); + let n1 = |a: &[Val]| arg(a, 1).and_then(Val::num); + let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + let chars = |v: &Val| v.text().chars().collect::>(); + let count = |v: f64| usize::try_from(v.max(0.0).min(1e6) as i64).unwrap_or(0); + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name { + "ABS" => Ok(Val::Num(n0(a)?.abs())), + "ACOS" => checked(n0(a)?.acos()), + "ASIN" => checked(n0(a)?.asin()), + "ATAN" => Ok(Val::Num(n0(a)?.atan())), + "AND" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().all(|b| *b))), + "OR" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().any(|b| *b))), + "NOT" => Ok(Val::Bool(!arg(a, 0)?.truth()?)), + "AVERAGE" => { + let v = nums(a)?; + if v.is_empty() { Err(Err::Div0) } else { Ok(Val::Num(v.iter().sum::() / v.len() as f64)) } + } + "SUM" => Ok(Val::Num(nums(a)?.iter().sum())), + "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()).and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))).and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "CONCAT" => Ok(Val::Text(a.iter().map(Val::text).collect())), + "COS" => Ok(Val::Num(n0(a)?.cos())), + "SIN" => Ok(Val::Num(n0(a)?.sin())), + "TAN" => checked(n0(a)?.tan()), + "DEGREES" => Ok(Val::Num(n0(a)?.to_degrees())), + "RADIANS" => Ok(Val::Num(n0(a)?.to_radians())), + "EXP" => checked(n0(a)?.exp()), + "LN" => checked(n0(a)?.ln()), + "LOG10" => checked(n0(a)?.log10()), + "SQRT" => checked(n0(a)?.sqrt()), + "POWER" => checked(n0(a)?.powf(n1(a)?)), + "MOD" => { + let (x, m) = (n0(a)?, n1(a)?); + if m == 0.0 { Err(Err::Div0) } else { Ok(Val::Num(x - m * (x / m).floor())) } + } + "INT" => Ok(Val::Num(n0(a)?.floor())), + "PI" => Ok(Val::Num(std::f64::consts::PI)), + "ROUND" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::round))), + "ROUNDUP" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), |x| if x < 0.0 { x.floor() } else { x.ceil() }))), + "ROUNDDOWN" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::trunc))), + "FIXED" => Ok(Val::Text(format!("{:.*}", count(n1(a).unwrap_or(2.0)).min(15), n0(a)?))), + "IF" => { + let c = arg(a, 0)?.truth()?; + Ok(if c { a.get(1).cloned().unwrap_or(Val::Bool(true)) } else { a.get(2).cloned().unwrap_or(Val::Bool(false)) }) + } + "LEN" => Ok(Val::Num(chars(arg(a, 0)?).len() as f64)), + "UPPER" => Ok(Val::Text(arg(a, 0)?.text().to_uppercase())), + "LOWER" => Ok(Val::Text(arg(a, 0)?.text().to_lowercase())), + "TRIM" => Ok(Val::Text(arg(a, 0)?.text().split_whitespace().collect::>().join(" "))), + "LEFT" => Ok(Val::Text(chars(arg(a, 0)?).into_iter().take(count(n1(a).unwrap_or(1.0))).collect())), + "RIGHT" => { + let c = chars(arg(a, 0)?); + let k = count(n1(a).unwrap_or(1.0)).min(c.len()); + Ok(Val::Text(c.get(c.len() - k..).unwrap_or_default().iter().collect())) + } + "MID" => { + let c = chars(arg(a, 0)?); + let st = count(n1(a)? - 1.0); + let k = count(arg(a, 2)?.num()?); + Ok(Val::Text(c.into_iter().skip(st).take(k).collect())) + } + "TEXT" => { + let v = arg(a, 0)?; + let f = arg(a, 1)?.text(); + Ok(Val::Text(match v { + Val::Date(x) => format_date(*x, &f), + _ if looks_like_date_format(&f) => format_date(v.num()?, &f), + Val::Text(t) if t.trim().parse::().is_err() => t.clone(), + _ => format_number(v.num()?, &f), + })) + } + "TODAY" => Ok(Val::Date(now.floor())), + "NOW" => Ok(Val::Date(now)), + "DATE" => { + let (yy, mm, dd) = (n0(a)?, n1(a)?, arg(a, 2)?.num()?); + if !(yy.is_finite() && mm.is_finite() && dd.is_finite()) || yy.abs() > 9999.0 || mm.abs() > 12_000.0 || dd.abs() > 1e6 { + return Err(Err::Num); + } + Ok(Val::Date(serial(yy as i64, mm as i64, dd as i64))) + } + "YEAR" => Ok(Val::Num(parts(n0(a)?).0 as f64)), + "MONTH" => Ok(Val::Num(parts(n0(a)?).1 as f64)), + "DAY" => Ok(Val::Num(parts(n0(a)?).2 as f64)), + "HOUR" => Ok(Val::Num(parts(n0(a)?).3 as f64)), + "MINUTE" => Ok(Val::Num(parts(n0(a)?).4 as f64)), + "FILENAME" => Ok(Val::Text(env.file.clone())), + "SHEET" => Ok(Val::Text(env.sheet.clone())), + _ => Err(Err::Name), + } +} + +// ---------- AutoCAD fields ---------- + +/// The fields of a field template worked out (`%<\AcVar date \f "dd.MM.yyyy">%` and the file +/// name ones); `None` when one is a field CADCraft doesn't know. +fn fields(template: &str, env: &Env) -> Option { + let mut out = String::new(); + let mut rest = template; + let mut guard = 0; + while let Some(a) = rest.find("%<") { + guard += 1; + if guard > 64 { + return None; + } + out.push_str(rest.get(..a)?); + let tail = rest.get(a + 2..)?; + let b = tail.find(">%")?; + out.push_str(&field(tail.get(..b)?, env)?); + rest = tail.get(b + 2..)?; + } + out.push_str(rest); + Some(out) +} + +/// One field code (between `%<` and `>%`). +fn field(code: &str, env: &Env) -> Option { + let code = code.trim(); + let body = code.strip_prefix("\\AcVar")?.trim(); + let (name, fmt) = match body.split_once("\\f") { + Some((n, f)) => (n.trim(), Some(f.trim().trim_matches('"'))), + None => (body, None), + }; + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name.to_ascii_lowercase().as_str() { + // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. + "date" => Some(format_date(now, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), + "filename" => Some(env.file.clone()), + _ => None, + } +} + +/// A .NET date format (`dd.MM.yyyy HH:mm`) as a spreadsheet one (`dd.mm.yyyy hh:mm`). +fn net_to_sheet(f: &str) -> String { + // .NET: M month, m minute; spreadsheet: m month, m after h minute. Minutes become "mm" after + // an hour, months stay "mm" otherwise. + f.replace("HH", "hh").replace('H', "h").replace("MMMM", "mmmm").replace("MMM", "mmm").replace("MM", "mm").replace('M', "m") +} + +// ---------- applying to a drawing ---------- + +/// A text object's formula, worked out into what it shows: a text value starting with `=` +/// becomes its formula; a formula's result becomes the value. `edited` is a value just typed: +/// typing over an AutoCAD field turns it into plain text, typing a value without `=` drops the +/// formula. +pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { + let (value, formula): (&mut String, &mut Option) = match kind { + EntityKind::Text(t) => (&mut t.value, &mut t.formula), + EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula), + EntityKind::MText(t) => (&mut t.contents, &mut t.formula), + _ => return, + }; + if edited { + let plain = cadcraft_fonts::plain_mtext(value); + if is_formula(&plain) { + *formula = Some(plain.trim().to_string()); + } else { + *formula = None; + return; + } + } + if let Some(f) = formula.as_deref() + && let Some(v) = evaluate(f, env) + { + *value = v; + } +} + +/// Whether an entity has a formula or field to work out. +fn has_formula(k: &EntityKind) -> bool { + match k { + EntityKind::Text(t) => t.formula.is_some(), + EntityKind::AttDef(a) => a.text.formula.is_some(), + EntityKind::MText(t) => t.formula.is_some(), + _ => false, + } +} + +/// Work out every formula and known field of a drawing again (when it is opened): model space, +/// layouts and block definitions. The number of texts worked out. +pub fn refresh(d: &mut Drawing, env: &Env) -> usize { + let mut n = 0; + let fix = |store: &mut cadcraft_doc::EntityStore, n: &mut usize| { + let hs: Vec = store.iter().filter(|e| has_formula(&e.kind)).map(|e| e.handle).collect(); + for h in hs { + store.modify(h, |e| apply(&mut e.kind, env, false)); + *n += 1; + } + }; + fix(&mut d.model, &mut n); + for l in &mut d.layouts { + fix(&mut l.entities, &mut n); + } + let names: Vec = d.blocks.iter().filter(|(_, b)| b.entities.iter().any(|e| has_formula(&e.kind))).map(|(k, _)| k.clone()).collect(); + for k in names { + if let Some(b) = d.blocks.get_mut(&k) { + fix(&mut std::sync::Arc::make_mut(b).entities, &mut n); + } + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env() -> Env { + Env { now: (2026, 10, 23, 14, 5, 9), file: "plan.dwg".into(), sheet: "4".into() } + } + + fn ev(f: &str) -> String { + evaluate(f, &env()).unwrap_or_default() + } + + #[test] + fn arithmetic_and_functions() { + assert_eq!(ev("=2400-2*18"), "2364"); + assert_eq!(ev("=(1+2)^2/4"), "2.25"); + assert_eq!(ev("=ROUND(PI()*2,3)"), "6.283"); + assert_eq!(ev("=SUM(1,2,3)&\" mm\""), "6 mm"); + assert_eq!(ev("=IF(5>3,\"big\",\"small\")"), "big"); + assert_eq!(ev("=MAX(4;9;2)"), "9"); + assert_eq!(ev("=TEXT(1234.5,\"#,##0.00\")"), "1,234.50"); + assert_eq!(ev("=TEXT(0.25,\"0%\")"), "25%"); + assert_eq!(ev("=UPPER(LEFT(\"abc\",2))"), "AB"); + assert_eq!(ev("=MID(\"Hello\",2,3)"), "ell"); + assert_eq!(ev("=50%*10"), "5"); + } + + #[test] + fn dates_follow_the_clock() { + assert_eq!(ev("=TODAY()"), "23.10.2026"); + assert_eq!(ev("=TEXT(TODAY(),\"yyyy-mm-dd\")"), "2026-10-23"); + assert_eq!(ev("=TEXT(NOW(),\"hh:mm\")"), "14:05"); + assert_eq!(ev("=TODAY()+10"), "02.11.2026"); + assert_eq!(ev("=YEAR(DATE(2025,14,1))"), "2026"); + assert_eq!(ev("=TEXT(DATE(2026,1,5),\"d mmm yyyy\")"), "5 Jan 2026"); + assert_eq!(ev("%<\\AcVar date \\f \"dd.MM.yyyy\">%"), "23.10.2026"); + assert_eq!(ev("Date: %<\\AcVar Date \\f \"yyyy-MM-dd HH:mm\">%"), "Date: 2026-10-23 14:05"); + assert_eq!(ev("=FILENAME()&\" / \"&SHEET()"), "plan.dwg / 4"); + assert_eq!(evaluate("%<\\AcObjProp Object(%<\\_ObjId 1>%).Area>%", &env()), None, "unknown fields keep their value"); + } + + #[test] + fn errors_show_as_in_spreadsheets_and_never_panic() { + assert_eq!(ev("=1/0"), "#DIV/0!"); + assert_eq!(ev("=FOO(1)"), "#NAME?"); + assert_eq!(ev("=\"a\"*2"), "#VALUE!"); + assert_eq!(ev("=SQRT(-1)"), "#NUM!"); + assert_eq!(ev("=(1+"), "#ERROR!"); + for f in ["=", "==", "=(((((", &format!("={}", "-".repeat(500)), &format!("={}1", "(".repeat(100)), "=\"", "=MID(\"a\",-5,1e300)", "=DATE(1e300,1,1)"] { + let _ = evaluate(f, &env()); + } + assert!(!is_formula("plain")); + assert!(!is_formula("=")); + } +} diff --git a/crates/engine/tests/attrib_modes.rs b/crates/engine/tests/attrib_modes.rs index 65238823aa..52f8b4cb1f 100644 --- a/crates/engine/tests/attrib_modes.rs +++ b/crates/engine/tests/attrib_modes.rs @@ -12,6 +12,8 @@ use serde_json::json; fn references_take_lock_position_from_the_definition() { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.0, diff --git a/crates/engine/tests/audit.rs b/crates/engine/tests/audit.rs index 5f93f13593..fbe6184d9b 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -57,6 +57,8 @@ fn corrupt(d: &mut Drawing) -> (Handle, Handle) { &Space::Model, on("0"), EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/engine/tests/mtext_columns.rs b/crates/engine/tests/mtext_columns.rs index 25c9f9b3be..91ff4c1956 100644 --- a/crates/engine/tests/mtext_columns.rs +++ b/crates/engine/tests/mtext_columns.rs @@ -85,6 +85,7 @@ fn scale_scales_multileader_text_width_and_columns() { // #709: SCALE 2 on a multileader's text doubles its width and column lengths like it does // for a standalone MTEXT, not only its height. let text = MText { + frame: false, insert: Default::default(), height: 2.0, width: 10.0, diff --git a/crates/engine/tests/multiline_attributes.rs b/crates/engine/tests/multiline_attributes.rs index b7a7a7d0f5..bdf9d3d388 100644 --- a/crates/engine/tests/multiline_attributes.rs +++ b/crates/engine/tests/multiline_attributes.rs @@ -12,6 +12,8 @@ use serde_json::json; fn session() -> Session { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + backwards: false, + upside_down: false, insert: Vec3::new(2.0, 2.0, 0.0), align_pt: None, height: 2.0, @@ -24,6 +26,7 @@ fn session() -> Session { valign: Default::default(), }; let mtext = MText { + frame: false, insert: Vec3::new(10.0, 3.0, 0.0), height: 2.0, width: 0.0, diff --git a/crates/engine/tests/snap_annotations.rs b/crates/engine/tests/snap_annotations.rs index 97bf0ac289..71894c3aae 100644 --- a/crates/engine/tests/snap_annotations.rs +++ b/crates/engine/tests/snap_annotations.rs @@ -44,6 +44,8 @@ fn justified_text_snaps_and_grips_at_its_alignment_point() { let mut s = Session::new(); // As read from DXF: a right-justified text keeps group 10 (start) and group 11 (alignment). let t = Text { + backwards: false, + upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: Some(Vec3::new(10.0, 0.0, 0.0)), height: 1.0, diff --git a/crates/engine/tests/text_justify.rs b/crates/engine/tests/text_justify.rs new file mode 100644 index 0000000000..c2a01f9746 --- /dev/null +++ b/crates/engine/tests/text_justify.rs @@ -0,0 +1,61 @@ +//! Text and multiline text take another justification in place (the letters don't move), and +//! keep their Backwards / Upside down / Text frame settings. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::EntityKind; +use serde_json::json; + +fn bounds(s: &Session, h: &str) -> cadcraft_engine::geom::Bounds2 { + let d = s.doc().unwrap(); + let e = d.model.iter().find(|e| e.handle.hex() == h).unwrap(); + match &e.kind { + EntityKind::Text(t) => cadcraft_render::place_text_entity(d, t, &t.value).1, + EntityKind::MText(t) => cadcraft_render::layout_mtext_entity(d, t).bounds, + _ => panic!("not text"), + } +} + +fn near(a: cadcraft_engine::geom::Bounds2, b: cadcraft_engine::geom::Bounds2) -> bool { + a.min.dist(b.min) < 1e-6 && a.max.dist(b.max) < 1e-6 +} + +#[test] +fn text_justification_changes_keep_the_letters_in_place() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [10, 5], "height": 2.5, "text": "Hello 20", "rotation": 30 })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let b0 = bounds(&s, &h); + for j in ["MC", "TR", "BL", "C", "R", "M", "L"] { + s.execute("properties.set", &json!({ "handles": [h], "justify": j })).unwrap(); + assert!(near(bounds(&s, &h), b0), "{j} moved the text"); + } + let d = s.doc().unwrap(); + let EntityKind::Text(t) = &d.model.iter().next().unwrap().kind else { panic!() }; + assert_eq!(t.halign, cadcraft_engine::doc::HAlign::Left); + assert!(s.execute("properties.set", &json!({ "handles": [h], "justify": "XX" })).is_err()); +} + +#[test] +fn backwards_upside_down_and_frame_are_properties() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "AB" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("properties.set", &json!({ "handles": [h], "backwards": true, "upsideDown": true })).unwrap(); + let EntityKind::Text(t) = &s.doc().unwrap().model.iter().next().unwrap().kind else { panic!() }; + assert!(t.backwards && t.upside_down); + + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "Line one\\Pline two" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let b0 = bounds(&s, &m); + s.execute("properties.set", &json!({ "handles": [m], "justify": "MC", "frame": true })).unwrap(); + assert!(near(bounds(&s, &m), b0), "multiline text stays in place"); + let d = s.doc().unwrap(); + let mt = d.model.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.clone()), + _ => None, + }); + let mt = mt.unwrap(); + assert!(mt.frame && mt.attach == 5); + let frame = cadcraft_render::mtext_frame(d, &mt).unwrap(); + assert_eq!(frame.len(), 5); +} diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index ab57d5a864..faa0f97783 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -305,6 +305,8 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { _ => p.text_rotation.unwrap_or(0.0), }; MText { + formula: None, + frame: false, insert: text_location.unwrap_or(landing), height: pos(p.text_height).unwrap_or(def.text_height), width: p.text_width.unwrap_or(0.0).max(0.0), diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index f139937b48..d5e00d069b 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -162,6 +162,9 @@ fn mtext_from(tags: &[Tag], c: &Common) -> MText { }; } MText { + formula: None, + // Background flags (90): 16 = a frame around the text. + frame: own.i(90).is_some_and(|f| f & 16 != 0), insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), width: match &columns { @@ -194,7 +197,11 @@ fn text_from(t: &T) -> Text { _ => VAlign::Baseline, }; let align = if t.f(11).is_some() { Some(t.p(11)) } else { None }; + // Text generation flags (71: 2 backwards, 4 upside down), from the text's own groups (an + // attribute's embedded multiline text, after 101, has a 71 of its own). + let generation = t.0.iter().take_while(|g| g.code != 101).find(|g| g.code == 71).map_or(0, |g| g.i64()); let mut text = Text { + formula: None, insert: t.p(10), align_pt: if h == HAlign::Left && v == VAlign::Baseline { None } else { align }, height: t.fd(40, 0.2).max(1e-9), @@ -205,6 +212,8 @@ fn text_from(t: &T) -> Text { style: t.s(7).unwrap_or_else(|| "Standard".into()), halign: h, valign: v, + backwards: generation & 2 != 0, + upside_down: generation & 4 != 0, }; let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0)); if n.z < 0.0 { diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 9b0595cb66..59c7471d6a 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -472,6 +472,10 @@ fn text_tags(w: &mut W, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_pro w.f(51, t.oblique.to_degrees()); } w.s(7, &t.style); + let generation = i64::from(t.backwards) * 2 + i64::from(t.upside_down) * 4; + if generation != 0 { + w.i(71, generation); + } let h = match t.halign { HAlign::Left => 0, HAlign::Center => 1, @@ -742,6 +746,11 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx // Line spacing style: 1 = at least, 2 = exactly. w.i(73, if t.line_spacing_exact { 2 } else { 1 }); w.f(44, t.line_spacing); + if t.frame { + // Background flags: a text frame, no fill (border offset factor 1.5). + w.i(90, 16); + w.f(45, 1.5); + } w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t)); } EntityKind::Insert(i) => { @@ -1313,6 +1322,8 @@ fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec { handle: Handle(0), common: c, kind: EntityKind::MText(MText { + formula: None, + frame: false, insert: g.text_pos.to3(0.0), height: g.text_height, width: 0.0, @@ -1364,6 +1375,8 @@ fn table_block_entities(d: &Drawing, t: &Table, layer: &str) -> Vec { handle: Handle(0), common: Common { color: cell.color, ..c.clone() }, kind: EntityKind::MText(MText { + formula: None, + frame: false, insert: cell.at.to3(0.0), height: cell.height, width: 0.0, diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index fbbbbb7d44..710be1e1a0 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -27,6 +27,8 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 0.25, @@ -44,6 +46,7 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::MText(MText { + frame: false, insert: Vec3::new(5.0, 5.0, 0.0), height: 0.2, width: 3.0, @@ -255,6 +258,8 @@ fn block_definition_properties_and_constant_attdefs_roundtrip() { let mut b = Block::new("Title"); (b.description, b.units, b.explodable) = ("Drawing title block".into(), 4, false); let text = Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.5, @@ -1269,6 +1274,8 @@ const INTL: &str = "图号 İø Ø 😀"; fn intl_text(value: &str) -> Text { Text { + backwards: false, + upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 2.5, @@ -1293,6 +1300,7 @@ fn intl_sample() -> Drawing { &Space::Model, on.clone(), EntityKind::MText(MText { + frame: false, insert: Vec3::new(5.0, 5.0, 0.0), height: 2.5, width: 30.0, @@ -1534,6 +1542,7 @@ fn dwg_roundtrip_keeps_extension_data() { fn mleader_is_written_as_multileader() { let mut d = Drawing::new_metric(); let text = cadcraft_doc::MText { + frame: false, insert: Vec3::new(12.0, 5.0, 0.0), height: 2.5, width: 0.0, @@ -1570,6 +1579,8 @@ fn mleader_is_written_as_multileader() { fn attdef_prompt_survives_dxf_roundtrip() { let mut d = Drawing::new_metric(); let text = Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.0, diff --git a/crates/io/tests/annotative_roundtrip.rs b/crates/io/tests/annotative_roundtrip.rs index b7fb62384e..684e00143c 100644 --- a/crates/io/tests/annotative_roundtrip.rs +++ b/crates/io/tests/annotative_roundtrip.rs @@ -10,6 +10,8 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/io/tests/attrib_modes.rs b/crates/io/tests/attrib_modes.rs index 625ead9392..de067ba132 100644 --- a/crates/io/tests/attrib_modes.rs +++ b/crates/io/tests/attrib_modes.rs @@ -9,6 +9,8 @@ use cadcraft_io::{read_dxf, write_dxf}; fn attrib(tag: &str, modes: AttribModes) -> Attrib { let text = Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 1.0, diff --git a/crates/io/tests/attrib_props.rs b/crates/io/tests/attrib_props.rs index 32dac11012..73c50d4557 100644 --- a/crates/io/tests/attrib_props.rs +++ b/crates/io/tests/attrib_props.rs @@ -10,6 +10,8 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(x: f64, value: &str) -> Text { Text { + backwards: false, + upside_down: false, insert: Vec3::new(x, 0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/io/tests/dxf_versions.rs b/crates/io/tests/dxf_versions.rs index 3fc2f1c73c..663def61a3 100644 --- a/crates/io/tests/dxf_versions.rs +++ b/crates/io/tests/dxf_versions.rs @@ -9,6 +9,8 @@ const INTL: &str = "图号 Café Ø 😀"; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 2.5, diff --git a/crates/io/tests/entity_props_roundtrip.rs b/crates/io/tests/entity_props_roundtrip.rs index d86d0b4b86..aa49b973ab 100644 --- a/crates/io/tests/entity_props_roundtrip.rs +++ b/crates/io/tests/entity_props_roundtrip.rs @@ -29,6 +29,8 @@ fn thickness_roundtrips_on_every_entity_that_has_one() { let mut d = Drawing::new_metric(); let p = |x, y| Vec3::new(x, y, 0.0); let text = Text { + backwards: false, + upside_down: false, insert: p(0.0, 0.0), align_pt: None, height: 2.5, diff --git a/crates/io/tests/followups_626.rs b/crates/io/tests/followups_626.rs index eba7c64646..07afb8a0ad 100644 --- a/crates/io/tests/followups_626.rs +++ b/crates/io/tests/followups_626.rs @@ -35,6 +35,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + frame: false, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, width: 6.0, @@ -164,6 +165,8 @@ fn code_page_is_kept_before_2007() { &Space::Model, Common::default(), EntityKind::Text(Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/io/tests/mleader_roundtrip.rs b/crates/io/tests/mleader_roundtrip.rs index 8bb8085aad..2dbb8c4bef 100644 --- a/crates/io/tests/mleader_roundtrip.rs +++ b/crates/io/tests/mleader_roundtrip.rs @@ -22,6 +22,7 @@ fn text_mleader() -> MLeader { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + frame: false, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, width: 6.0, @@ -80,6 +81,8 @@ fn spline_leader_with_block_content_and_attributes() { let mut blk = Block::new("BUBBLE"); blk.entities.push(Entity::new(Handle(0x200), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); let tag_text = Text { + backwards: false, + upside_down: false, insert: Vec3::new(-0.2, -0.1, 0.0), align_pt: None, height: 0.25, diff --git a/crates/io/tests/mtext_columns_roundtrip.rs b/crates/io/tests/mtext_columns_roundtrip.rs index 7db9ed685b..c6812aa80c 100644 --- a/crates/io/tests/mtext_columns_roundtrip.rs +++ b/crates/io/tests/mtext_columns_roundtrip.rs @@ -7,6 +7,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn mtext(contents: &str, rotation: f64, columns: Option) -> MText { MText { + frame: false, insert: Vec3::new(1.0, 2.0, 0.0), height: 0.5, width: 6.0, diff --git a/crates/io/tests/mtext_embedded_object.rs b/crates/io/tests/mtext_embedded_object.rs index 4bd95cb778..7308ae0eee 100644 --- a/crates/io/tests/mtext_embedded_object.rs +++ b/crates/io/tests/mtext_embedded_object.rs @@ -12,6 +12,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String { let mut d = Drawing::new_metric(); let t = MText { + frame: false, insert: Vec3::new(30.0, 17.0, 0.0), height: 0.5, width: 6.0, diff --git a/crates/io/tests/mtext_line_spacing.rs b/crates/io/tests/mtext_line_spacing.rs index 8a030cbc7f..539c6f2091 100644 --- a/crates/io/tests/mtext_line_spacing.rs +++ b/crates/io/tests/mtext_line_spacing.rs @@ -8,6 +8,7 @@ fn line_spacing_style_roundtrips() { for exact in [false, true] { let mut d = Drawing::new_metric(); let t = MText { + frame: false, insert: Vec3::new(1.0, 2.0, 0.0), height: 2.5, width: 40.0, diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 4863ee6284..35d37774bd 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -159,6 +159,8 @@ fn style(d: &mut Drawing, name: &str, font: &str) { fn text(d: &mut Drawing, space: &Space, style: &str, at: (f64, f64), value: &str, rotation: f64, width_factor: f64, oblique: f64) { let t = Text { + backwards: false, + upside_down: false, insert: Vec3::new(at.0, at.1, 0.0), align_pt: None, height: 10.0, @@ -354,6 +356,8 @@ fn hostile_text_never_panics() { [("A".repeat(5000), 10.0, 0.0), ("AB".into(), 1e300, 0.0), ("AB".into(), 1e-300, 1e300), ("\u{0}A\u{FFFF}B".into(), 5.0, f64::NAN)] { let t = Text { + backwards: false, + upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), align_pt: None, height: h, diff --git a/crates/io/tests/text_flags_roundtrip.rs b/crates/io/tests/text_flags_roundtrip.rs new file mode 100644 index 0000000000..70d2f26c56 --- /dev/null +++ b/crates/io/tests/text_flags_roundtrip.rs @@ -0,0 +1,44 @@ +//! TEXT generation flags (71: backwards, upside down) and the MTEXT Text frame (90 bit 16) +//! round-trip through DXF. + +use cadcraft_doc::{Common, Drawing, EntityKind, HAlign, MText, Space, Text, VAlign}; +use cadcraft_geom::Vec3; + +#[test] +fn text_flags_and_mtext_frame_roundtrip() { + let mut d = Drawing::new_metric(); + let t = Text { + insert: Vec3::new(1.0, 2.0, 0.0), + align_pt: None, + height: 2.5, + value: "AB".into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: HAlign::Left, + valign: VAlign::Baseline, + backwards: true, + upside_down: true, + }; + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); + let m = MText { + frame: true, + insert: Vec3::new(0.0, 10.0, 0.0), + height: 2.5, + width: 40.0, + attach: 1, + rotation: 0.0, + style: "Standard".into(), + contents: "framed".into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(m)).unwrap(); + let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); + let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); + let kinds: Vec = back.model.iter().map(|e| e.kind.clone()).collect(); + assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.backwards && t.upside_down))); + assert!(kinds.iter().any(|k| matches!(k, EntityKind::MText(m) if m.frame))); +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 20b0ff218d..2a9371ff06 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1306,8 +1306,9 @@ pub fn place_text_entity(d: &Drawing, t: &cadcraft_doc::Text, value: &str) -> (c oblique: t.oblique, h, v, - backwards: ts.backwards, - upside_down: ts.upside_down, + // The text's own generation flags (set from its style when it was made), as AutoCAD. + backwards: t.backwards, + upside_down: t.upside_down, }; cadcraft_fonts::place(&font, value, &p) } @@ -1355,6 +1356,36 @@ fn mtext(b: &mut Builder, ctx: &Ctx, t: &cadcraft_doc::MText, rgb: Ink, lw: f32) for p in &l.pieces { b.shaped(ctx, mtext_color(p.color, rgb), lw, &p.shaped); } + if t.frame + && let Some(r) = mtext_frame(ctx.d, t) + { + b.polyline(ctx, rgb, lw, &r); + } +} + +/// The Text frame of multiline text: its box (the defined width, the text's height) with a margin +/// of a quarter of the text height (border offset factor 1.5), turned with the text; closed. +pub fn mtext_frame(d: &Drawing, t: &cadcraft_doc::MText) -> Option> { + let mut flat = t.clone(); + flat.rotation = 0.0; + let bb = layout_mtext_entity(d, &flat).bounds; + if bb.is_empty() { + return None; + } + let ins = t.insert.xy(); + let col = f64::from((t.attach.clamp(1, 9) - 1) % 3); + let (x0, x1) = if t.width > 0.0 { + let left = ins.x - col * t.width / 2.0; + (left.min(bb.min.x), (left + t.width).max(bb.max.x)) + } else { + (bb.min.x, bb.max.x) + }; + let m = t.height * 0.25; + let corners = + [Vec2::new(x0 - m, bb.min.y - m), Vec2::new(x1 + m, bb.min.y - m), Vec2::new(x1 + m, bb.max.y + m), Vec2::new(x0 - m, bb.max.y + m)]; + let mut pts: Vec = corners.iter().map(|c| ins + (*c - ins).rotate(t.rotation)).collect(); + pts.push(*pts.first()?); + pts.iter().all(|p| p.is_finite()).then_some(pts) } /// The font settings of a dimension style's text style. diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 379c083e6a..6f508424a6 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -155,6 +155,20 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option Option<(u32, u32, Vec)> { + let pm = Pixmap::decode_png(bytes).ok()?; + (pm.width() <= 4096 && pm.height() <= 4096).then(|| (pm.width(), pm.height(), pm.data().to_vec())) +} + +/// Encode premultiplied RGBA pixels as a PNG. +pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option> { + let size = tiny_skia::IntSize::from_wh(width, height)?; + let pm = Pixmap::from_vec(rgba.to_vec(), size)?; + pm.encode_png().ok() +} + /// Render and encode as PNG. pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { render(list, view, o)?.encode_png().ok() diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ee22abb3c1..ab7afba90a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -48,6 +48,8 @@ fn text_produces_strokes() { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 1.0, @@ -255,6 +257,8 @@ fn text_doc(style_font: &str, value: &str) -> Drawing { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 1.0, @@ -309,13 +313,22 @@ fn backwards_and_upside_down_mirror_text() { let mut d = text_doc("CADCraft Stroke", "ABC"); let normal = build(&d, &Space::Model, &Options::default()).bounds; assert!(normal.min.x >= -1e-9 && normal.min.y >= -1e-9); + // The text's own flags mirror it (as AutoCAD: the style's only seed new text). + let flags = |d: &mut Drawing, b: bool, u: bool| { + let h = d.model.iter().next().map(|e| e.handle).unwrap(); + d.modify_entity(h, |e| { + if let EntityKind::Text(t) = &mut e.kind { + (t.backwards, t.upside_down) = (b, u); + } + }); + }; d.text_styles.iter_mut().for_each(|s| s.backwards = true); + let styled = build(&d, &Space::Model, &Options::default()).bounds; + assert!((styled.min.x - normal.min.x).abs() < 1e-9, "a backwards style alone does not mirror existing text"); + flags(&mut d, true, false); let back = build(&d, &Space::Model, &Options::default()).bounds; assert!(back.max.x <= 1e-9 && (back.width() - normal.width()).abs() < 1e-9, "mirrored to the left"); - d.text_styles.iter_mut().for_each(|s| { - s.backwards = false; - s.upside_down = true; - }); + flags(&mut d, false, true); let up = build(&d, &Space::Model, &Options::default()).bounds; assert!(up.max.y <= 1e-9 && up.min.y < -0.9, "mirrored below the baseline"); } @@ -329,6 +342,7 @@ fn truetype_mtext_and_dimension_text() { &Space::Model, Common::default(), EntityKind::MText(cadcraft_doc::MText { + frame: false, insert: Vec3::ZERO, height: 1.0, width: 0.0, @@ -764,6 +778,8 @@ fn attrib(tag: &str) -> cadcraft_doc::Attrib { cadcraft_doc::Attrib { tag: tag.into(), text: cadcraft_doc::Text { + backwards: false, + upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), align_pt: None, height: 1.0, @@ -861,6 +877,7 @@ fn attributes_follow_the_reference_layer_and_have_no_definition() { fn mtext_exact_spacing_ignores_taller_lines() { // #711: a doubled middle line pushes the next baseline down with At least, not with Exactly. let mtext = |contents: &str, line_spacing: f64, line_spacing_exact: bool| cadcraft_doc::MText { + frame: false, insert: Vec3::ZERO, height: 1.0, width: 10.0, diff --git a/crates/render/tests/annotative_viewport.rs b/crates/render/tests/annotative_viewport.rs index 1e93b1a6b5..466e7cb26c 100644 --- a/crates/render/tests/annotative_viewport.rs +++ b/crates/render/tests/annotative_viewport.rs @@ -25,6 +25,8 @@ fn drawing(scale: f64, all_visible: bool) -> Drawing { d.header.set_i64("ANNOALLVISIBLE", i64::from(all_visible)); let anno = Common { anno_scales: vec![AnnoScale::new("1:50", 1.0, 50.0), AnnoScale::new("1:100", 1.0, 100.0)], ..Default::default() }; let text = Text { + backwards: false, + upside_down: false, insert: Vec3::ZERO, align_pt: None, height: 2.5, diff --git a/crates/render/tests/render_props.rs b/crates/render/tests/render_props.rs index f210dc4e14..3ec854a9d1 100644 --- a/crates/render/tests/render_props.rs +++ b/crates/render/tests/render_props.rs @@ -99,6 +99,8 @@ fn leader_arrows_use_their_style_dimscale() { fn text(x: f64, value: &str) -> Text { Text { + backwards: false, + upside_down: false, insert: Vec3::new(x, 0.0, 0.0), align_pt: None, height: 1.0, diff --git a/crates/ui-egui/src/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs new file mode 100644 index 0000000000..134718a142 --- /dev/null +++ b/crates/ui-egui/src/bidi_edit.rs @@ -0,0 +1,629 @@ +//! The text box of the text editors: text in the drawing's fonts, laid out as the drawing lays it +//! out, with left-to-right and right-to-left scripts mixed on one line the way word processors +//! do it (the Unicode Bidirectional Algorithm, each paragraph's direction from its first strong +//! character). +//! +//! The text is kept in logical order (the order it is typed and stored). Each line is shown in +//! display order; the caret sits after the character before it (at its right edge in +//! left-to-right text, its left edge in right-to-left text); Left and Right move the caret one +//! place left or right on screen, whatever the direction of the text under it; a selection +//! covers a range of the logical text and lights up every character in it, wherever it is shown. + +use egui::{Color32, Event, Key, Pos2, Rect, Sense, Stroke, pos2, vec2}; + +use crate::editor_glyphs::{self, EditorFont}; + +/// Most undo steps kept. +const MAX_UNDO: usize = 100; + +/// How a character looks. +#[derive(Clone, Debug, PartialEq)] +pub struct Look { + pub font: EditorFont, + pub italic: bool, + pub bold: bool, + pub underline: bool, + /// Size in points (the cap height is [`editor_glyphs::CAP`] of it). + pub size: f32, + pub color: Color32, +} + +/// The caret and selection (character indices into the text), kept between frames. +#[derive(Clone, Debug, Default)] +pub struct EditState { + pub cursor: usize, + pub anchor: usize, + /// Horizontal scroll of a one-line box. + scroll_x: f32, + /// For Up and Down: the x the caret aims at. + preferred_x: Option, + undo: Vec<(String, usize)>, + redo: Vec<(String, usize)>, +} + +impl EditState { + pub fn at(i: usize) -> Self { + EditState { cursor: i, anchor: i, ..Default::default() } + } + /// The selection, low to high. + pub fn range(&self) -> (usize, usize) { + (self.cursor.min(self.anchor), self.cursor.max(self.anchor)) + } +} + +/// What a frame of the box did. +pub struct Output { + pub response: egui::Response, + pub changed: bool, +} + +/// A character placed on a line. +#[derive(Clone, Copy, Debug)] +struct Cell { + /// Index in the text. + idx: usize, + /// Left edge and width (box coordinates). + x: f32, + w: f32, + rtl: bool, +} + +#[derive(Clone, Debug)] +struct Line { + /// Logical range of the line's characters (a paragraph's `\n` is not in it). + start: usize, + end: usize, + top: f32, + height: f32, + baseline: f32, + /// The paragraph runs right to left. + rtl: bool, + /// The characters in display order, left to right. + cells: Vec, +} + +struct Layout { + lines: Vec, + width: f32, + height: f32, +} + +/// Characters laid out in lines: wrapped at spaces to `wrap` (one line: no wrapping), each line +/// put in display order. +fn layout(chars: &[char], look: &dyn Fn(usize) -> Look, wrap: Option, default_size: f32) -> Layout { + let adv: Vec = chars + .iter() + .enumerate() + .map(|(i, c)| { + if *c == '\n' { + 0.0 + } else { + let l = look(i); + editor_glyphs::advance(&l.font, l.italic, *c, l.size) + } + }) + .collect(); + let sizes: Vec = (0..chars.len()).map(|i| look(i).size).collect(); + // Logical lines: paragraphs split at `\n`, wrapped. + let mut ranges: Vec<(usize, usize, bool)> = Vec::new(); + let mut p0 = 0usize; + let mut para_rtl = false; + for p1 in (0..=chars.len()).filter(|i| *i == chars.len() || chars.get(*i) == Some(&'\n')) { + let par: String = chars.get(p0..p1).unwrap_or_default().iter().collect(); + // A paragraph without strong characters keeps the direction of the one before. + para_rtl = cadcraft_fonts::bidi::base_rtl(&par).unwrap_or(para_rtl); + let mut s = p0; + while s < p1 { + let mut w = 0.0; + let mut e = s; + let mut last_space = None; + while e < p1 { + let a = adv.get(e).copied().unwrap_or(0.0); + if let Some(limit) = wrap + && w + a > limit + && e > s + && chars.get(e) != Some(&' ') + { + break; + } + if chars.get(e) == Some(&' ') { + last_space = Some(e + 1); + } + w += a; + e += 1; + } + if e < p1 + && let Some(b) = last_space.filter(|b| *b > s && *b < e) + { + e = b; + } + ranges.push((s, e, para_rtl)); + s = e; + } + if p0 == p1 { + ranges.push((p0, p1, para_rtl)); + } + p0 = p1 + 1; + } + if ranges.is_empty() { + ranges.push((0, 0, false)); + } + let mut lines = Vec::with_capacity(ranges.len()); + let mut y = 0.0; + let mut width: f32 = 0.0; + for (s, e, rtl) in ranges { + let max = (s..e).filter_map(|i| sizes.get(i).copied()).fold(0.0f32, f32::max); + let size = if max > 0.0 { max } else { default_size }; + let height = size * 1.45; + let baseline = y + size * 1.05; + let text: String = chars.get(s..e).unwrap_or_default().iter().collect(); + let order: Vec = if cadcraft_fonts::bidi::has_rtl(&text) { + let levels = cadcraft_fonts::bidi::char_levels(&text, Some(rtl)); + cadcraft_fonts::bidi::reorder(&levels).into_iter().map(|k| k + s).collect::>() + } else { + (s..e).collect() + }; + let levels = if cadcraft_fonts::bidi::has_rtl(&text) { cadcraft_fonts::bidi::char_levels(&text, Some(rtl)) } else { Vec::new() }; + let mut x = 0.0; + let mut cells = Vec::with_capacity(order.len()); + for i in order { + let w = adv.get(i).copied().unwrap_or(0.0); + let r = levels.get(i - s).is_some_and(|l| l % 2 == 1); + cells.push(Cell { idx: i, x, w, rtl: r }); + x += w; + } + width = width.max(x); + lines.push(Line { start: s, end: e, top: y, height, baseline, rtl, cells }); + y += height; + } + Layout { lines, width, height: y } +} + +impl Layout { + /// The line the caret at `c` is on: the last line holding `c` (a wrapped line's end is the + /// next line's start). + fn line_of(&self, c: usize) -> usize { + self.lines.iter().rposition(|l| l.start <= c && c <= l.end).unwrap_or(0) + } + fn cell(&self, line: usize, idx: usize) -> Option { + self.lines.get(line)?.cells.iter().find(|k| k.idx == idx).copied() + } + /// The caret's x at `c`: after the character before it (its right edge in left-to-right + /// text, its left edge in right-to-left text); at a line's start, before its first + /// character. + fn caret_x(&self, c: usize) -> (usize, f32) { + let li = self.line_of(c); + let Some(l) = self.lines.get(li) else { return (0, 0.0) }; + if c > l.start + && let Some(k) = self.cell(li, c - 1) + { + return (li, if k.rtl { k.x } else { k.x + k.w }); + } + if let Some(k) = self.cell(li, c) { + return (li, if k.rtl { k.x + k.w } else { k.x }); + } + // An empty line: at its start side. + let right = l.cells.iter().map(|k| k.x + k.w).fold(0.0, f32::max); + (li, if l.rtl { right } else { 0.0 }) + } + /// The caret position nearest `x` on line `li`. + fn index_at(&self, li: usize, x: f32) -> usize { + let Some(l) = self.lines.get(li) else { return 0 }; + let mut best = (f32::INFINITY, l.start); + for c in l.start..=l.end { + let (cl, cx) = self.caret_x(c); + if cl != li { + continue; + } + let d = (cx - x).abs(); + if d < best.0 { + best = (d, c); + } + } + best.1 + } + /// The caret position one place left (`dir` −1) or right (+1) on screen from `c`. + fn step(&self, c: usize, dir: f32) -> usize { + let (li, x) = self.caret_x(c); + let Some(l) = self.lines.get(li) else { return c }; + let mut best: Option<(f32, usize)> = None; + for k in l.start..=l.end { + let (kl, kx) = self.caret_x(k); + if kl != li || k == c { + continue; + } + let d = (kx - x) * dir; + if d > 0.5 && best.is_none_or(|(bd, bk)| d < bd - 0.01 || ((d - bd).abs() <= 0.01 && k.abs_diff(c) < bk.abs_diff(c))) { + best = Some((d, k)); + } + } + if let Some((_, k)) = best { + return k; + } + // Off the end of the line: the neighbouring line, in reading order. + let forward = (dir > 0.0) != l.rtl; + if forward { + if li + 1 < self.lines.len() { + return self.lines.get(li + 1).map_or(c, |n| n.start); + } + } else if li > 0 { + return self.lines.get(li - 1).map_or(c, |p| p.end); + } + c + } +} + +/// Character classes for word moves and double clicks. +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +fn word_left(chars: &[char], mut c: usize) -> usize { + while c > 0 && chars.get(c - 1).is_some_and(|ch| !is_word(*ch)) { + c -= 1; + } + while c > 0 && chars.get(c - 1).is_some_and(|ch| is_word(*ch)) { + c -= 1; + } + c +} + +fn word_right(chars: &[char], mut c: usize) -> usize { + let n = chars.len(); + while c < n && chars.get(c).is_some_and(|ch| is_word(*ch)) { + c += 1; + } + while c < n && chars.get(c).is_some_and(|ch| !is_word(*ch)) { + c += 1; + } + c +} + +/// Replace the selection by `s` (an empty `s` deletes it). +fn replace(chars: &mut Vec, st: &mut EditState, s: &str, max_chars: usize) -> bool { + let (a, b) = st.range(); + let ins: Vec = s.chars().collect(); + if a == b && ins.is_empty() { + return false; + } + let room = max_chars.saturating_sub(chars.len() - (b - a)); + let ins: Vec = ins.into_iter().take(room).collect(); + let b = b.min(chars.len()); + let a = a.min(b); + chars.splice(a..b, ins.iter().copied()); + st.cursor = a + ins.len(); + st.anchor = st.cursor; + true +} + +/// Show the box: `width` wide, at least `min_rows` lines tall (one line: `single_line`), the +/// characters looking as `look` says. Returns whether the text changed. +#[allow(clippy::too_many_arguments)] +pub fn show( + ui: &mut egui::Ui, + id: egui::Id, + text: &mut String, + st: &mut EditState, + single_line: bool, + width: f32, + min_rows: usize, + look: &dyn Fn(usize) -> Look, + default_size: f32, + max_chars: usize, +) -> Output { + let t = crate::theme::Tokens::get(); + let margin = 5.0; + let mut chars: Vec = text.chars().collect(); + let n0 = chars.len(); + st.cursor = st.cursor.min(n0); + st.anchor = st.anchor.min(n0); + let inner_w = (width - 2.0 * margin).max(20.0); + let lay = layout(&chars, look, (!single_line).then_some(inner_w), default_size); + let row_h = default_size * 1.45; + let h = lay.height.max(row_h * min_rows.max(1) as f32) + 2.0 * margin; + let (rect, _) = ui.allocate_exact_size(vec2(width, h), Sense::hover()); + let focused = ui.memory(|m| m.has_focus(id)); + let response = ui.interact(rect, id, Sense::click_and_drag()); + if response.clicked() || response.drag_started() { + ui.memory_mut(|m| m.request_focus(id)); + } + if focused { + ui.memory_mut(|m| { + m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false }) + }); + } + // Box coordinates → screen. + let origin = |sx: f32| pos2(rect.left() + margin + sx, rect.top() + margin); + let scroll = if single_line { st.scroll_x } else { 0.0 }; + // Mouse: place the caret, drag to select, double-click a word. + let hit = |p: Pos2, lay: &Layout| -> usize { + let y = p.y - rect.top() - margin; + let li = lay.lines.iter().position(|l| y < l.top + l.height).unwrap_or(lay.lines.len().saturating_sub(1)); + lay.index_at(li, p.x - rect.left() - margin + scroll) + }; + let shift = ui.input(|i| i.modifiers.shift); + if let Some(p) = response.interact_pointer_pos() { + if response.double_clicked() { + let c = hit(p, &lay); + st.anchor = word_left(&chars, (c + 1).min(chars.len())); + st.cursor = word_right(&chars, st.anchor).min(chars.len()); + while st.cursor > st.anchor && chars.get(st.cursor - 1).is_some_and(|c| !is_word(*c)) { + st.cursor -= 1; + } + } else if response.drag_started() || response.clicked() { + st.cursor = hit(p, &lay); + if !shift { + st.anchor = st.cursor; + } + st.preferred_x = None; + } else if response.dragged() { + st.cursor = hit(p, &lay); + } + } + let mut changed = false; + if focused { + let events = ui.input(|i| i.events.clone()); + let before = text.clone(); + let before_cursor = st.cursor; + let mut edited = false; + for ev in events { + let lay = layout(&chars, look, (!single_line).then_some(inner_w), default_size); + match ev { + Event::Text(s) | Event::Paste(s) | Event::Ime(egui::ImeEvent::Commit(s)) => { + let s: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !single_line)).collect(); + let s = if single_line { s.replace('\n', " ") } else { s }; + edited |= replace(&mut chars, st, &s, max_chars); + } + Event::Copy | Event::Cut => { + let (a, b) = st.range(); + if a < b { + ui.ctx().copy_text(chars.get(a..b).unwrap_or_default().iter().collect()); + if matches!(ev, Event::Cut) { + edited |= replace(&mut chars, st, "", max_chars); + } + } + } + Event::Key { key, pressed: true, modifiers, .. } => { + let word = modifiers.command || modifiers.alt; + let mut moved = None; + match key { + Key::ArrowLeft | Key::ArrowRight => { + let dir = if key == Key::ArrowLeft { -1.0 } else { 1.0 }; + let (a, b) = st.range(); + moved = Some(if word { + // A word in reading order: right is forward in left-to-right text. + let li = lay.line_of(st.cursor); + let rtl = lay.lines.get(li).is_some_and(|l| l.rtl); + if (dir > 0.0) != rtl { word_right(&chars, st.cursor) } else { word_left(&chars, st.cursor) } + } else if a != b && !modifiers.shift { + // Collapse the selection at its left or right end on screen. + let (xa, xb) = (lay.caret_x(a).1, lay.caret_x(b).1); + if (xa < xb) == (dir < 0.0) { a } else { b } + } else { + lay.step(st.cursor, dir) + }); + st.preferred_x = None; + } + Key::ArrowUp | Key::ArrowDown => { + let (li, x) = lay.caret_x(st.cursor); + let px = *st.preferred_x.get_or_insert(x); + let to = if key == Key::ArrowUp { li.checked_sub(1) } else { Some(li + 1).filter(|n| *n < lay.lines.len()) }; + moved = Some(match to { + Some(n) => lay.index_at(n, px), + None if key == Key::ArrowUp => 0, + None => chars.len(), + }); + } + Key::Home => { + moved = Some(if modifiers.command { 0 } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.start) }); + st.preferred_x = None; + } + Key::End => { + moved = Some(if modifiers.command { chars.len() } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.end) }); + st.preferred_x = None; + } + Key::Backspace => { + if st.cursor == st.anchor && st.cursor > 0 { + st.anchor = if word { word_left(&chars, st.cursor) } else { st.cursor - 1 }; + } + edited |= replace(&mut chars, st, "", max_chars); + } + Key::Delete => { + if st.cursor == st.anchor && st.cursor < chars.len() { + st.anchor = if word { word_right(&chars, st.cursor) } else { st.cursor + 1 }; + } + edited |= replace(&mut chars, st, "", max_chars); + } + Key::Enter if !single_line && !modifiers.command => { + edited |= replace(&mut chars, st, "\n", max_chars); + } + Key::A if modifiers.command => { + st.anchor = 0; + st.cursor = chars.len(); + } + Key::Z | Key::Y if modifiers.command => { + let redo = key == Key::Y || modifiers.shift; + let (from, to) = if redo { (&mut st.redo, &mut st.undo) } else { (&mut st.undo, &mut st.redo) }; + if let Some((prev, c)) = from.pop() { + to.push((chars.iter().collect(), st.cursor)); + chars = prev.chars().collect(); + st.cursor = c.min(chars.len()); + st.anchor = st.cursor; + changed = true; + } + } + _ => {} + } + if let Some(c) = moved { + st.cursor = c.min(chars.len()); + if !modifiers.shift { + st.anchor = st.cursor; + } + } + } + _ => {} + } + } + if edited { + st.undo.push((before, before_cursor)); + if st.undo.len() > MAX_UNDO { + st.undo.remove(0); + } + st.redo.clear(); + st.preferred_x = None; + changed = true; + } + } + if changed { + *text = chars.iter().collect(); + } + // Paint: the box, the selection, the characters, the caret. + let lay = layout(&chars, look, (!single_line).then_some(inner_w), default_size); + let p = ui.painter_at(rect); + p.rect_filled(rect, 2.0, t.field); + p.rect_stroke(rect, 2.0, Stroke::new(if focused { 1.5 } else { 1.0 }, if focused { t.accent } else { t.border }), egui::StrokeKind::Inside); + let (cl, cx) = lay.caret_x(st.cursor); + // A one-line box scrolls to keep the caret in sight. + if single_line { + let view = inner_w; + if cx - st.scroll_x > view - 2.0 { + st.scroll_x = cx - view + 2.0; + } else if cx - st.scroll_x < 0.0 { + st.scroll_x = cx; + } + st.scroll_x = st.scroll_x.clamp(0.0, (lay.width - view + 4.0).max(0.0)); + } + let scroll = if single_line { st.scroll_x } else { 0.0 }; + let clip = p.with_clip_rect(rect.shrink(2.0)); + let at = |x: f32, y: f32| origin(x - scroll) + vec2(0.0, y); + let (a, b) = st.range(); + let sel_fill = if focused { t.accent.gamma_multiply(0.45) } else { t.accent.gamma_multiply(0.25) }; + for l in &lay.lines { + for k in &l.cells { + if k.idx >= a && k.idx < b { + clip.rect_filled(Rect::from_min_max(at(k.x, l.top), at(k.x + k.w, l.top + l.height)), 0.0, sel_fill); + } + } + // A selected paragraph break: a sliver at the line's end. + if l.end >= a && l.end < b && chars.get(l.end) == Some(&'\n') { + let ex = if l.rtl { 0.0 } else { l.cells.iter().map(|k| k.x + k.w).fold(0.0, f32::max) }; + let x0 = if l.rtl { ex - 6.0 } else { ex }; + clip.rect_filled(Rect::from_min_max(at(x0, l.top), at(x0 + 6.0, l.top + l.height)), 0.0, sel_fill); + } + for k in &l.cells { + let Some(c) = chars.get(k.idx).copied() else { continue }; + let lk = look(k.idx); + let c = if k.rtl { cadcraft_fonts::bidi::mirror(c) } else { c }; + editor_glyphs::paint(&clip, &lk.font, lk.italic, lk.bold, c, at(k.x, l.baseline), lk.size, lk.color); + if lk.underline { + let y = l.baseline + lk.size * 0.15; + clip.line_segment([at(k.x, y), at(k.x + k.w, y)], Stroke::new(1.0, lk.color)); + } + } + } + if focused { + let l = lay.lines.get(cl); + let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); + let blink = ui.input(|i| i.time) % 1.0 < 0.6; + if blink { + clip.line_segment([at(cx, top + 2.0), at(cx, top + hgt - 2.0)], Stroke::new(1.5, t.text)); + } + ui.ctx().request_repaint_after(std::time::Duration::from_millis(300)); + let caret_rect = Rect::from_min_max(at(cx, top), at(cx + 1.0, top + hgt)); + ui.ctx().output_mut(|o| { + o.ime = Some(egui::output::IMEOutput { + purpose: egui::IMEPurpose::Normal, + rect, + cursor_rect: caret_rect, + should_interrupt_composition: false, + }) + }); + } + Output { response, changed } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn look(_: usize) -> Look { + Look { + font: EditorFont { width_factor: 1.0, ..Default::default() }, + italic: false, + bold: false, + underline: false, + size: 20.0, + color: Color32::WHITE, + } + } + + fn lay(s: &str) -> (Vec, Layout) { + let c: Vec = s.chars().collect(); + let l = layout(&c, &look, None, 20.0); + (c, l) + } + + #[test] + fn mixed_scripts_show_in_display_order() { + // Hebrew paragraph with an English word: the English word sits at the left, in its own + // order, the Hebrew reads from the right. + let (_, l) = lay("שלום abc"); + let line = &l.lines[0]; + assert!(line.rtl); + let order: Vec = line.cells.iter().map(|k| k.idx).collect(); + assert_eq!(order, vec![5, 6, 7, 4, 3, 2, 1, 0]); + // English paragraph with a Hebrew word: the Hebrew word reversed in place. + let (_, l) = lay("ab שלום cd"); + let order: Vec = l.lines[0].cells.iter().map(|k| k.idx).collect(); + assert_eq!(order, vec![0, 1, 2, 6, 5, 4, 3, 7, 8, 9]); + } + + #[test] + fn arrows_move_visually_and_reach_every_place() { + let (c, l) = lay("ab שלום cd"); + // From the start, Right walks every caret place once, left to right on screen. + let mut at = 0; + let mut seen = vec![at]; + let mut xs = vec![l.caret_x(at).1]; + for _ in 0..c.len() + 2 { + let n = l.step(at, 1.0); + if n == at { + break; + } + at = n; + seen.push(at); + xs.push(l.caret_x(at).1); + } + assert!(xs.windows(2).all(|w| w[1] > w[0]), "{xs:?}"); + assert!(seen.len() >= c.len() - 1, "{seen:?}"); + // In a right-to-left line, Right from the logical start goes toward the end of the text + // on screen (left to right), i.e. back in reading order. + let (_, l) = lay("שלום"); + let x0 = l.caret_x(0).1; + assert!(x0 > l.caret_x(4).1, "the start of Hebrew text is at the right"); + assert_eq!(l.step(0, -1.0), 1, "Left from the start of Hebrew reads on"); + } + + #[test] + fn typing_replaces_the_selection_and_undo_restores() { + let mut chars: Vec = "hello".chars().collect(); + let mut st = EditState { cursor: 1, anchor: 4, ..Default::default() }; + assert!(replace(&mut chars, &mut st, "XY", 100)); + assert_eq!(chars.iter().collect::(), "hXYo"); + assert_eq!((st.cursor, st.anchor), (3, 3)); + let mut st = EditState::at(4); + assert!(replace(&mut chars, &mut st, "123456", 6), "capped at the limit"); + assert_eq!(chars.len(), 6); + assert_eq!(word_left(&"one two".chars().collect::>(), 7), 4); + } + + #[test] + fn wrapping_breaks_at_spaces() { + let c: Vec = "aaaa bbbb cccc".chars().collect(); + let one = editor_glyphs::advance(&look(0).font, false, 'a', 20.0); + let l = layout(&c, &look, Some(one * 6.5), 20.0); + assert!(l.lines.len() >= 2); + assert_eq!(l.lines[0].start, 0); + assert_eq!(c[l.lines[1].start], 'b'); + } +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 6936626fdb..a4f564d070 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -410,6 +410,83 @@ pub fn status_bar(app: &mut CadApp, ui: &mut egui::Ui) { }); } +/// Recent files as cards: a preview of the drawing (or the "file not found" picture), its name +/// and folder. A click opens it. +fn recent_grid(ui: &mut egui::Ui, files: &[String], recent: &mut Option) { + let t = Tokens::get(); + let card = vec2(crate::thumbs::W as f32 + 16.0, crate::thumbs::H as f32 + 58.0); + let per_row = ((ui.available_width() + 12.0) / (card.x + 12.0)).floor().max(1.0) as usize; + let ctx = ui.ctx().clone(); + for chunk in files.chunks(per_row) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 12.0; + for path in chunk { + let (r, resp) = ui.allocate_exact_size(card, Sense::click()); + let p = ui.painter(); + p.rect_filled(r, 4.0, if resp.hovered() { t.control_hover } else { t.chrome_dark }); + let img = Rect::from_min_size(r.min + vec2(8.0, 8.0), vec2(crate::thumbs::W as f32, crate::thumbs::H as f32)); + let thumb = crate::thumbs::get(&ctx, path); + match &thumb { + crate::thumbs::Thumb::Ready(tex) => { + // Kept in proportion (a file's own preview has its own size). + let [tw, th] = tex.size(); + let k = (img.width() / tw.max(1) as f32).min(img.height() / th.max(1) as f32); + let fit = Rect::from_center_size(img.center(), vec2(tw as f32 * k, th as f32 * k)); + p.rect_filled(img, 2.0, egui::Color32::BLACK); + p.image(tex.id(), fit, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + crate::thumbs::Thumb::Missing => { + p.rect_filled(img, 2.0, t.chrome); + crate::thumbs::paint_missing(p, img.shrink(14.0), t.text_dim); + } + crate::thumbs::Thumb::Pending => { + p.rect_filled(img, 2.0, t.chrome); + p.text(img.center(), egui::Align2::CENTER_CENTER, crate::tl!("Making a preview..."), crate::theme::small(), t.text_faint); + } + crate::thumbs::Thumb::Failed => { + p.rect_filled(img, 2.0, t.chrome); + icons::paint(p, Rect::from_center_size(img.center(), vec2(48.0, 48.0)), Icon::Open, true); + } + } + p.rect_stroke(img, 2.0, Stroke::new(1.0, t.border), egui::StrokeKind::Outside); + let missing = matches!(thumb, crate::thumbs::Thumb::Missing); + let clip = p.with_clip_rect(Rect::from_min_max(pos2(r.left() + 6.0, img.bottom()), pos2(r.right() - 6.0, r.bottom()))); + let name_color = if missing { t.text_faint } else { t.text }; + crate::i18n::paint( + &clip, + pos2(img.left(), img.bottom() + 16.0), + egui::Align2::LEFT_CENTER, + &crate::menus::file_name(path), + crate::theme::body(), + name_color, + ); + let second = if missing { + crate::tl!("File not found").to_string() + } else { + std::path::Path::new(path).parent().map(|d| d.display().to_string()).unwrap_or_default() + }; + crate::i18n::paint( + &clip, + pos2(img.left(), img.bottom() + 34.0), + egui::Align2::LEFT_CENTER, + &second, + crate::theme::small(), + t.text_faint, + ); + if resp + .on_hover_ui(|ui| { + ui.label(crate::i18n::widget(ui, path, egui::TextStyle::Body)); + }) + .clicked() + { + *recent = Some(path.clone()); + } + } + }); + ui.add_space(12.0); + } +} + /// The Start page (no drawing open, or the Start tab). pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -440,35 +517,73 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) { } let main = Rect::from_min_max(pos2(left.right() + 36.0, r.top() + 40.0), r.max); p.text(main.min, egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text); - let mut recent = None; - let mut y = main.top() + 44.0; - for (i, path) in app.ui.recent_files.iter().enumerate() { - let row = Rect::from_min_size(pos2(main.left(), y), vec2((r.right() - main.left() - 36.0).clamp(0.0, 640.0), 42.0)); - let resp = ui.interact(row, ui.id().with(("recent", i)), Sense::click()); - if resp.hovered() { - p.rect_filled(row, 2.0, t.control_hover.gamma_multiply(0.5)); - } - let dir = std::path::Path::new(path).parent().map(|d| d.display().to_string()).unwrap_or_default(); - let clip = p.with_clip_rect(row.shrink(2.0)); - crate::i18n::paint( - &clip, - pos2(row.left() + 10.0, row.top() + 13.0), - egui::Align2::LEFT_CENTER, - &crate::menus::file_name(path), - crate::theme::body(), - t.text, - ); - crate::i18n::paint(&clip, pos2(row.left() + 10.0, row.top() + 30.0), egui::Align2::LEFT_CENTER, &dir, crate::theme::small(), t.text_faint); - if resp - .on_hover_ui(|ui| { - ui.label(crate::i18n::widget(ui, path, egui::TextStyle::Body)); - }) - .clicked() + // List or grid of previews: two toggle buttons right of the heading. + if !app.ui.recent_files.is_empty() { + for (i, (grid, icon, tip)) in + [(false, Icon::List, crate::tl!("List")), (true, Icon::Grid, crate::tl!("Grid with previews"))].into_iter().enumerate() { - recent = Some(path.clone()); + let br = Rect::from_min_size(pos2(main.left() + 110.0 + i as f32 * 30.0, main.top() + 1.0), vec2(26.0, 26.0)); + let resp = ui.interact(br, ui.id().with(("recent_view", i)), Sense::click()).on_hover_text(tip); + let on = app.ui.recent_grid == grid; + if on || resp.hovered() { + p.rect_filled(br, 3.0, if on { t.accent.gamma_multiply(0.45) } else { t.control_hover }); + } + icons::paint(&p, br.shrink(4.0), icon, false); + if resp.clicked() { + app.ui.recent_grid = grid; + } } - y += 46.0; } + let mut recent = None; + let body = Rect::from_min_max(pos2(main.left(), main.top() + 44.0), pos2(r.right() - 12.0, r.bottom() - 8.0)); + let files = app.ui.recent_files.clone(); + let grid = app.ui.recent_grid; + let now = ui.input(|i| i.time); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::top_down(egui::Align::Min))); + egui::ScrollArea::vertical().id_salt("cc_recent").auto_shrink([false, false]).show(&mut child, |ui| { + if grid { + recent_grid(ui, &files, &mut recent); + } else { + for (i, path) in files.iter().enumerate() { + let w = (ui.available_width() - 24.0).clamp(0.0, 640.0); + let (row, resp) = ui.allocate_exact_size(vec2(w, 42.0), Sense::click()); + ui.add_space(4.0); + let _ = i; + let p = ui.painter(); + if resp.hovered() { + p.rect_filled(row, 2.0, t.control_hover.gamma_multiply(0.5)); + } + let there = crate::thumbs::exists(path, now); + let dir = std::path::Path::new(path).parent().map(|d| d.display().to_string()).unwrap_or_default(); + let clip = p.with_clip_rect(row.shrink(2.0)); + let name_color = if there { t.text } else { t.text_faint }; + let x = if there { + row.left() + 10.0 + } else { + crate::thumbs::paint_missing(&clip, Rect::from_min_size(pos2(row.left() + 4.0, row.top() + 3.0), vec2(30.0, 36.0)), t.text_dim); + row.left() + 42.0 + }; + crate::i18n::paint( + &clip, + pos2(x, row.top() + 13.0), + egui::Align2::LEFT_CENTER, + &crate::menus::file_name(path), + crate::theme::body(), + name_color, + ); + let second = if there { dir } else { format!("{} — {dir}", crate::tl!("File not found")) }; + crate::i18n::paint(&clip, pos2(x, row.top() + 30.0), egui::Align2::LEFT_CENTER, &second, crate::theme::small(), t.text_faint); + if resp + .on_hover_ui(|ui| { + ui.label(crate::i18n::widget(ui, path, egui::TextStyle::Body)); + }) + .clicked() + { + recent = Some(path.clone()); + } + } + } + }); if let Some(path) = recent { app.open_path(&path); } else if app.ui.recent_files.is_empty() { diff --git a/crates/ui-egui/src/layers.rs b/crates/ui-egui/src/layers.rs index 93e40c06bc..6f134ec292 100644 --- a/crates/ui-egui/src/layers.rs +++ b/crates/ui-egui/src/layers.rs @@ -532,7 +532,7 @@ fn row( } if !library.is_empty() { ui.separator(); - ui.menu_button("Load...", |ui| { + crate::palettes::menu_list(ui, "Load...", |ui| { egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| { for n in library { if ui.button(n).clicked() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2c9cea7780..390984fe45 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod animation; pub mod autosave; pub mod batchplot; pub mod bedit; +pub mod bidi_edit; pub mod blockmgr; pub mod canvas; pub mod chrome; @@ -29,6 +30,7 @@ pub mod editor_glyphs; pub mod hatchdlg; mod mtext_editor; pub mod spacemouse; +pub mod thumbs; // The External References palette. pub mod xrefs; @@ -134,6 +136,9 @@ pub struct UiState { pub save_version: String, /// Drawings opened from a path, newest first (File ▸ Open Recent and the Start page). pub recent_files: Vec, + /// The Start page shows recent files as a grid of previews instead of a list. + #[serde(default)] + pub recent_grid: bool, } /// A DXF/DWG file version (2000 … 2018). @@ -214,6 +219,7 @@ impl Default for UiState { save_format: SaveFormat::default(), save_version: SaveVersion::default().year().to_string(), recent_files: Vec::new(), + recent_grid: false, } } } diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index f4f57b322c..9e2fcda3c6 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -10,12 +10,9 @@ //! the measured value) or a table cell (Tab and Shift+Tab move to the next and previous cell, //! Alt+↑ and Alt+↓ to the cell above and below). -use std::sync::Arc; - use cadcraft_engine::EditorKind; use cadcraft_engine::mtext_edit::{CharFmt, Flag, Formatted, ListStyle, MTextColor, ParaAlign, TabKind}; -use egui::text::{CCursor, CCursorRange, LayoutJob}; -use egui::{Align2, Color32, FontId, Rect, RichText, Sense, Shape, Stroke, TextFormat, pos2, vec2}; +use egui::{Align2, Color32, FontId, Rect, RichText, Sense, Shape, Stroke, pos2, vec2}; use crate::CadApp; use crate::theme::Tokens; @@ -49,6 +46,8 @@ struct State { focus: bool, /// The text style's font: the text box shows the text in it. font: crate::editor_glyphs::EditorFont, + /// The text box's caret and selection. + edit: crate::bidi_edit::EditState, } fn state_id() -> egui::Id { @@ -112,6 +111,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { key: editor.key.clone(), focus: true, font, + edit: crate::bidi_edit::EditState::at(end), } }); let line = kind == EditorKind::Line; @@ -697,85 +697,63 @@ fn ruler(ui: &mut egui::Ui, st: &mut State, px: f32, width: f32, base_h: f64) { fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, t: &Tokens, line: bool) { let id = edit_id(); - if let Some(at) = st.caret.take() - && let Some(mut s) = egui::TextEdit::load_state(ui.ctx(), id) - { - s.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(at)))); - s.store(ui.ctx(), id); + if let Some(at) = st.caret.take() { + st.edit.cursor = at; + st.edit.anchor = at; } let fmt = st.fmt.clone(); let default_color = t.text; let base = st.font.clone(); // The font each character is drawn in: an inline family (`\f`) or the style's. - let font_of = move |f: &CharFmt| match &f.font { + let font_of = |f: &CharFmt| match &f.font { Some(fam) if !fam.trim().is_empty() && !fam.eq_ignore_ascii_case(&fmt_base(&base)) => { crate::editor_glyphs::EditorFont { font: fam.clone(), big_font: String::new(), ..base.clone() } } _ => base.clone(), }; - let size_of = move |f: &CharFmt| f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); - let fmt_l = fmt.clone(); - let font_l = font_of.clone(); - let mut layouter = move |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| -> Arc { - let mut job = LayoutJob::default(); - job.wrap.max_width = wrap; - // One section per character, its advance set to the drawing font's (the difference is - // its leading space, so the caret after it lands where the drawing's would), the egui - // glyph itself invisible: the drawing font is painted over it (see `paint_glyphs`). - for (i, c) in text.as_str().chars().enumerate() { - let f = fmt_l.fmt_at(i); - let size = size_of(&f); - let color = f.color.map_or(default_color, color32); - let font_id = FontId::proportional(size); - let spacing = if c == '\n' { - 0.0 - } else { - let real = crate::editor_glyphs::advance(&font_l(&f), f.italic, c, size); - let shown = ui.fonts_mut(|fs| fs.glyph_width(&font_id, c)); - real - shown - }; - job.append( - &c.to_string(), - spacing, - TextFormat { - font_id, - color: Color32::TRANSPARENT, - underline: if f.underline { Stroke::new(1.0, color) } else { Stroke::NONE }, - ..TextFormat::default() - }, - ); + let size_of = |f: &CharFmt| f.height.map_or(px, |h| (px * (h / base_h) as f32).clamp(6.0, 120.0)); + let look = |i: usize| { + let f = fmt.fmt_at(i); + crate::bidi_edit::Look { + font: font_of(&f), + italic: f.italic, + bold: f.bold, + underline: f.underline, + size: size_of(&f), + color: f.color.map_or(default_color, color32), } - ui.fonts_mut(|f| f.layout_job(job)) }; let mut buf = st.fmt.text().to_string(); - let edit = if line { egui::TextEdit::singleline(&mut buf) } else { egui::TextEdit::multiline(&mut buf).desired_rows(5).lock_focus(true) }; - let out = edit - .id(id) - .desired_width(width) - .margin(egui::Margin::symmetric(4, 4)) - .char_limit(cadcraft_engine::mtext_edit::MAX_CHARS) - .layouter(&mut layouter) - .show(ui); - if !out.response.has_focus() && (st.focus || (buf.is_empty() && st.fmt.is_empty())) { - out.response.request_focus(); + let out = crate::bidi_edit::show( + ui, + id, + &mut buf, + &mut st.edit, + line, + width, + if line { 1 } else { 5 }, + &look, + px, + cadcraft_engine::mtext_edit::MAX_CHARS, + ); + let focused = ui.memory(|m| m.has_focus(id)); + if !focused && (st.focus || (buf.is_empty() && st.fmt.is_empty())) { + ui.memory_mut(|m| m.request_focus(id)); } st.focus = false; - paint_glyphs(ui, &out, &fmt, &font_of, &size_of, default_color); - if out.response.changed() { + if out.changed { let typing = st.typing.clone(); st.fmt.set_text(&buf, &typing); } - if let Some(r) = out.cursor_range { - let (a, b) = (r.primary.index.0, r.secondary.index.0); - st.sel = (a, b); - if a == b { - if out.response.changed() { - st.typing_at = a; - } else if a != st.typing_at { - // The caret moved: typing continues the formatting of the character before it. - st.typing = st.fmt.fmt_at(a.saturating_sub(1)); - st.typing_at = a; - } + let (a, b) = (st.edit.cursor, st.edit.anchor); + st.sel = (a, b); + if a == b { + if out.changed { + st.typing_at = a; + } else if a != st.typing_at { + // The caret moved: typing continues the formatting of the character before it. + st.typing = st.fmt.fmt_at(a.saturating_sub(1)); + st.typing_at = a; } } } @@ -786,36 +764,6 @@ fn fmt_base(f: &crate::editor_glyphs::EditorFont) -> String { n.rsplit(['\\', '/']).next().unwrap_or(n).split('.').next().unwrap_or("").to_string() } -/// Draw the text box's characters in the drawing's fonts, where the box laid them out. -fn paint_glyphs( - ui: &egui::Ui, - out: &egui::text_edit::TextEditOutput, - fmt: &Formatted, - font_of: &impl Fn(&CharFmt) -> crate::editor_glyphs::EditorFont, - size_of: &impl Fn(&CharFmt) -> f32, - default_color: Color32, -) { - let painter = ui.painter().with_clip_rect(out.text_clip_rect); - let mut i = 0usize; - for row in &out.galley.rows { - for g in &row.row.glyphs { - let f = fmt.fmt_at(i); - // The glyph ends at its laid-out right edge (its leading space made up the width). - let font = font_of(&f); - let size = size_of(&f); - let real = crate::editor_glyphs::advance(&font, f.italic, g.chr, size); - let at = out.galley_pos + row.pos.to_vec2() + g.pos.to_vec2() + egui::vec2(g.advance_width - real, 0.0); - let color = f.color.map_or(default_color, color32); - crate::editor_glyphs::paint(&painter, &font, f.italic, f.bold, g.chr, at, size, color); - i += 1; - } - // The line break that ends a paragraph is a character of the text, not a glyph. - if row.ends_with_newline { - i += 1; - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 3e28b58aa7..181239f2c1 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -487,7 +487,7 @@ pub(crate) fn layers_section(app: &mut CadApp, ui: &mut egui::Ui) { } icons::paint(p, Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), vec2(12.0, 12.0)), Icon::ChevronDown, false); egui::Popup::from_toggle_button_response(&resp).width(w).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - layer_list(ui, &layers, &cur, &mut set_current, &mut toggle); + scroll_list(ui, "cc_props_layers", |ui| layer_list(ui, &layers, &cur, &mut set_current, &mut toggle)); }); }); ui.add_space(4.0); @@ -624,12 +624,76 @@ fn report_bad(app: &mut CadApp, bad: Option) { } } +/// Text justifications: (code, horizontal, vertical, name). +const TEXT_JUSTIFY: [(&str, cadcraft_doc::HAlign, cadcraft_doc::VAlign, &str); 15] = { + use cadcraft_doc::{HAlign as H, VAlign as V}; + [ + ("L", H::Left, V::Baseline, "Left"), + ("C", H::Center, V::Baseline, "Center"), + ("R", H::Right, V::Baseline, "Right"), + ("A", H::Aligned, V::Baseline, "Aligned"), + ("M", H::Middle, V::Baseline, "Middle"), + ("F", H::Fit, V::Baseline, "Fit"), + ("TL", H::Left, V::Top, "Top left"), + ("TC", H::Center, V::Top, "Top center"), + ("TR", H::Right, V::Top, "Top right"), + ("ML", H::Left, V::Middle, "Middle left"), + ("MC", H::Center, V::Middle, "Middle center"), + ("MR", H::Right, V::Middle, "Middle right"), + ("BL", H::Left, V::Bottom, "Bottom left"), + ("BC", H::Center, V::Bottom, "Bottom center"), + ("BR", H::Right, V::Bottom, "Bottom right"), + ] +}; + +/// Multiline text attachments 1..=9: (code, name). +const MTEXT_JUSTIFY: [(&str, &str); 9] = [ + ("TL", "Top left"), + ("TC", "Top center"), + ("TR", "Top right"), + ("ML", "Middle left"), + ("MC", "Middle center"), + ("MR", "Middle right"), + ("BL", "Bottom left"), + ("BC", "Bottom center"), + ("BR", "Bottom right"), +]; + +/// A Yes / No property row setting `key`. +fn yes_no(ui: &mut egui::Ui, label: &str, key: &str, on: bool, ids: &[String], set: &mut Option) { + prop_row(ui, label, |ui| { + let cur = if on { crate::tl!("Yes") } else { crate::tl!("No") }; + if let Some(n) = pick_menu(ui, cur, [crate::tl!("Yes").to_string(), crate::tl!("No").to_string()]) { + *set = Some(json!({ "handles": ids, key: n == crate::tl!("Yes") })); + } + }); +} + +/// Most height a drop-down list of the palettes takes before it scrolls. +const LIST_H: f32 = 360.0; + +/// A list in a drop-down: it scrolls, with a scroll bar always shown, once it is taller than +/// [`LIST_H`]. +pub(crate) fn scroll_list(ui: &mut egui::Ui, salt: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt(salt).max_height(LIST_H).auto_shrink([true, true]).show(ui, add).inner +} + +/// A menu button whose list scrolls when it is long (layers, linetypes, styles...). +pub(crate) fn menu_list( + ui: &mut egui::Ui, + text: impl Into, + add: impl FnOnce(&mut egui::Ui) -> R, +) -> egui::InnerResponse> { + ui.menu_button(text, |ui| scroll_list(ui, "cc_menu_list", add)) +} + /// A drop-down of `items` showing `current`; returns the item clicked. fn pick_menu(ui: &mut egui::Ui, current: &str, items: impl IntoIterator) -> Option { // Names are the drawing's own; only the ByLayer/ByBlock keywords are translated. let shown = |s: &str| if ["ByLayer", "ByBlock"].contains(&s) { crate::i18n::t(s).to_string() } else { s.to_string() }; let mut out = None; - ui.menu_button(shown(current), |ui| { + menu_list(ui, shown(current), |ui| { for it in items { if ui.button(shown(&it)).clicked() { out = Some(it); @@ -710,11 +774,13 @@ fn properties_header(app: &mut CadApp, ui: &mut egui::Ui) { if count > 0 { // Narrow the selection to one object type. egui::Popup::from_toggle_button_response(&resp).width(w - 10.0).close_behavior(egui::PopupCloseBehavior::CloseOnClick).show(|ui| { - for (ty, hs) in &types { - if ui.button(format!("{} ({})", crate::i18n::t(ty), hs.len())).clicked() { - run = Some(("select", json!({ "handles": hs }))); + scroll_list(ui, "cc_props_types", |ui| { + for (ty, hs) in &types { + if ui.button(format!("{} ({})", crate::i18n::t(ty), hs.len())).clicked() { + run = Some(("select", json!({ "handles": hs }))); + } } - } + }); }); } let tip = if pickadd { @@ -762,7 +828,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { let mut action: Option<(&str, Value)> = None; let mut act = |c: &'static str, p: Value| action = Some((c, p)); prop_row(ui, "Color", |ui| { - ui.menu_button(format!("■ {}", crate::i18n::t(&Color::from_aci(h.i64("CECOLOR", 256) as i16).name())), |ui| { + menu_list(ui, format!("■ {}", crate::i18n::t(&Color::from_aci(h.i64("CECOLOR", 256) as i16).name())), |ui| { for (n, c) in [ ("ByLayer", 256), ("ByBlock", 0), @@ -801,7 +867,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); prop_row(ui, "Lineweight", |ui| { - ui.menu_button(crate::i18n::t(&cadcraft_doc::Lineweight::from_dxf(h.i64("CELWEIGHT", -1) as i16).name()), |ui| { + menu_list(ui, crate::i18n::t(&cadcraft_doc::Lineweight::from_dxf(h.i64("CELWEIGHT", -1) as i16).name()), |ui| { for n in ["ByLayer", "ByBlock", "Default"] { if ui.button(crate::i18n::t(n)).clicked() { act("lweight", json!({ "lineweight": n })); @@ -914,7 +980,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }; group(ui, "General"); prop_row(ui, "Color", |ui| { - ui.menu_button(format!("■ {}", crate::i18n::t(&color)), |ui| { + menu_list(ui, format!("■ {}", crate::i18n::t(&color)), |ui| { for (n, c) in [ ("ByLayer", 256), ("ByBlock", 0), @@ -936,7 +1002,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); prop_row(ui, "Layer", |ui| { - ui.menu_button(layer.clone(), |ui| { + menu_list(ui, layer.clone(), |ui| { for l in &layers { if ui.button(l).clicked() { set = Some(json!({ "handles": ids, "layer": l })); @@ -946,7 +1012,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); prop_row(ui, "Linetype", |ui| { - ui.menu_button(if ["ByLayer", "ByBlock", "*VARIES*"].contains(&linetype.as_str()) { crate::i18n::t(&linetype) } else { &linetype }, |ui| { + menu_list(ui, if ["ByLayer", "ByBlock", "*VARIES*"].contains(&linetype.as_str()) { crate::i18n::t(&linetype) } else { &linetype }, |ui| { for l in std::iter::once("ByLayer".to_string()) .chain(std::iter::once("ByBlock".to_string())) .chain(linetypes.iter().filter(|l| !["ByLayer", "ByBlock"].contains(&l.as_str())).cloned()) @@ -964,7 +1030,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } }); prop_row(ui, "Lineweight", |ui| { - ui.menu_button(crate::i18n::t(&lw), |ui| { + menu_list(ui, crate::i18n::t(&lw), |ui| { for n in ["ByLayer", "ByBlock", "Default"] { if ui.button(crate::i18n::t(n)).clicked() { set = Some(json!({ "handles": ids, "lineweight": n })); @@ -980,7 +1046,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); }); prop_row(ui, "Transparency", |ui| { - ui.menu_button(crate::i18n::t(&tr), |ui| { + menu_list(ui, crate::i18n::t(&tr), |ui| { for v in ["ByLayer", "ByBlock"] { if ui.button(crate::i18n::t(v)).clicked() { set = Some(json!({ "handles": ids, "transparency": v })); @@ -1101,6 +1167,16 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Height", "height", len(tx.height), &mut set, &mut bad, &ids); num(ui, "Rotation", "rotation", real(tx.rotation.to_degrees()), &mut set, &mut bad, &ids); num(ui, "Width factor", "widthFactor", real(tx.width_factor), &mut set, &mut bad, &ids); + prop_row(ui, "Justify", |ui| { + let cur = TEXT_JUSTIFY.iter().find(|(_, h, v, _)| *h == tx.halign && *v == tx.valign).map_or("Left", |j| j.3); + if let Some(n) = pick_menu(ui, crate::i18n::t(cur), TEXT_JUSTIFY.iter().map(|j| crate::i18n::t(j.3).to_string())) + && let Some(j) = TEXT_JUSTIFY.iter().find(|j| crate::i18n::t(j.3) == n) + { + set = Some(json!({ "handles": ids, "justify": j.0 })); + } + }); + yes_no(ui, "Backwards", "backwards", tx.backwards, &ids, &mut set); + yes_no(ui, "Upside down", "upsideDown", tx.upside_down, &ids, &mut set); } EntityKind::MText(tx) => { prop_row(ui, "Contents", |ui| { @@ -1110,6 +1186,16 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { }); num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, &ids); + num(ui, "Rotation", "rotation", real(tx.rotation.to_degrees()), &mut set, &mut bad, &ids); + prop_row(ui, "Justify", |ui| { + let cur = MTEXT_JUSTIFY.get(usize::from(tx.attach.clamp(1, 9) - 1)).map_or("Top left", |j| j.1); + if let Some(n) = pick_menu(ui, crate::i18n::t(cur), MTEXT_JUSTIFY.iter().map(|j| crate::i18n::t(j.1).to_string())) + && let Some(j) = MTEXT_JUSTIFY.iter().find(|j| crate::i18n::t(j.1) == n) + { + set = Some(json!({ "handles": ids, "justify": j.0 })); + } + }); + yes_no(ui, "Text frame", "frame", tx.frame, &ids, &mut set); } EntityKind::LwPolyline(pl) => { num(ui, "Global width", "width", len(pl.const_width), &mut set, &mut bad, &ids); @@ -1128,7 +1214,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { } EntityKind::Hatch(hh) => { prop_row(ui, "Pattern", |ui| { - ui.menu_button(hh.pattern.clone(), |ui| { + menu_list(ui, hh.pattern.clone(), |ui| { if let Some(name) = patterns::menu(ui, &hh.pattern) { set = Some(json!({ "handles": ids, "pattern": name })); ui.close(); diff --git a/crates/ui-egui/src/quick.rs b/crates/ui-egui/src/quick.rs index afad707342..4feb789453 100644 --- a/crates/ui-egui/src/quick.rs +++ b/crates/ui-egui/src/quick.rs @@ -154,7 +154,7 @@ pub fn qselect_dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut st.value).desired_width(if choices.is_empty() { 220.0 } else { 190.0 })); if !choices.is_empty() { - ui.menu_button("▼", |ui| { + crate::palettes::menu_list(ui, "▼", |ui| { egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| { for c in &choices { if ui diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs new file mode 100644 index 0000000000..629c6eeeb7 --- /dev/null +++ b/crates/ui-egui/src/thumbs.rs @@ -0,0 +1,426 @@ +//! Small previews of recent drawings for the Start page's grid. A preview is made once on a +//! worker thread (the file is read and its model space drawn at [`W`] × [`H`] pixels) and kept as +//! a small PNG in the user's settings folder, named after the file's path, size and date, so a +//! changed file gets a new one. Whether a file is still there is checked every few seconds. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock, PoisonError}; + +/// Preview size in pixels: small files (a few tens of kilobytes), large enough to tell drawings +/// apart. +pub const W: u32 = 240; +pub const H: u32 = 160; +/// How often a file's presence is checked again. +const RECHECK_S: f64 = 5.0; + +/// What the grid shows for a recent file. +#[derive(Clone)] +pub enum Thumb { + /// Not made yet (being made, or waiting its turn). + Pending, + Ready(egui::TextureHandle), + /// The file is not at its path. + Missing, + /// The file is there but could not be read or drawn. + Failed, +} + +#[derive(Default)] +struct Store { + thumbs: HashMap, + /// When each path was last checked, and whether it existed. + seen: HashMap, + /// The path being made now, and the channel its PNG arrives on. + #[cfg(not(target_arch = "wasm32"))] + job: Option<(String, std::sync::mpsc::Receiver>>)>, +} + +fn store() -> &'static Mutex { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| Mutex::new(Store::default())) +} + +/// Whether `path` is a file that exists (checked at most every [`RECHECK_S`] seconds). +pub fn exists(path: &str, now: f64) -> bool { + let mut s = store().lock().unwrap_or_else(PoisonError::into_inner); + if let Some((at, ok)) = s.seen.get(path) + && now - at < RECHECK_S + { + return *ok; + } + #[cfg(not(target_arch = "wasm32"))] + let ok = std::path::Path::new(path).is_file(); + #[cfg(target_arch = "wasm32")] + let ok = true; + if s.seen.len() > 256 { + s.seen.clear(); + } + if s.seen.get(path).is_some_and(|(_, was)| *was != ok) { + // Back (or gone): make or drop its preview again. + s.thumbs.remove(path); + } + s.seen.insert(path.to_string(), (now, ok)); + ok +} + +/// The preview of `path`, starting to make it when there is none. +pub fn get(ctx: &egui::Context, path: &str) -> Thumb { + let now = ctx.input(|i| i.time); + if !exists(path, now) { + return Thumb::Missing; + } + let mut s = store().lock().unwrap_or_else(PoisonError::into_inner); + poll(&mut s, ctx); + if let Some(t) = s.thumbs.get(path) { + return t.clone(); + } + #[cfg(not(target_arch = "wasm32"))] + { + if let Some(png) = cache_file(path).and_then(|f| std::fs::read(f).ok()) { + let t = texture(ctx, path, &png).map_or(Thumb::Failed, Thumb::Ready); + s.thumbs.insert(path.to_string(), t.clone()); + return t; + } + if s.job.is_none() { + let (tx, rx) = std::sync::mpsc::channel(); + let p = path.to_string(); + let c = ctx.clone(); + let spawned = std::thread::Builder::new().name("cadcraft-thumb".into()).spawn(move || { + let png = std::panic::catch_unwind(|| make(&p)).ok().flatten(); + let _ = tx.send(png); + c.request_repaint(); + }); + if spawned.is_ok() { + s.job = Some((path.to_string(), rx)); + } else { + s.thumbs.insert(path.to_string(), Thumb::Failed); + } + } + ctx.request_repaint_after(std::time::Duration::from_millis(300)); + } + Thumb::Pending +} + +/// Take a finished preview. +#[cfg(not(target_arch = "wasm32"))] +fn poll(s: &mut Store, ctx: &egui::Context) { + let Some((path, rx)) = &s.job else { return }; + let got = match rx.try_recv() { + Ok(png) => Some(png), + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(None), + }; + let path = path.clone(); + s.job = None; + let t = match got.flatten() { + Some(png) => { + if let Some(f) = cache_file(&path) { + if let Some(dir) = f.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(f, &png); + } + texture(ctx, &path, &png).map_or(Thumb::Failed, Thumb::Ready) + } + None => Thumb::Failed, + }; + if s.thumbs.len() > 64 { + s.thumbs.clear(); + } + s.thumbs.insert(path, t); +} + +#[cfg(target_arch = "wasm32")] +fn poll(_s: &mut Store, _ctx: &egui::Context) {} + +fn texture(ctx: &egui::Context, path: &str, png: &[u8]) -> Option { + let (w, h, rgba) = cadcraft_render::raster::decode_png(png)?; + let img = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &rgba); + Some(ctx.load_texture(format!("cc-thumb:{path}"), img, egui::TextureOptions::LINEAR)) +} + +/// The preview of `path` as a small PNG: the one the file carries (a DWG's preview image, a +/// DXF's THUMBNAILIMAGE), else its model space drawn. +#[cfg(not(target_arch = "wasm32"))] +fn make(path: &str) -> Option> { + if let Some(png) = embedded(path) { + return Some(png); + } + let f = cadcraft_engine::cmd::file::read_file(path).ok()?; + let d = f.drawing(); + let space = cadcraft_engine::doc::Space::Model; + let opts = cadcraft_render::Options { min_dash: 0.0, ..cadcraft_render::Options::default() }; + let list = cadcraft_render::build(d, &space, &opts); + let view = cadcraft_render::raster::View::fit(&list.bounds, W, H, 0.06); + cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default()) +} + +/// Most bytes read looking for a file's own preview. +#[cfg(not(target_arch = "wasm32"))] +const MAX_PREVIEW_BYTES: u64 = 8 << 20; + +/// The preview image a drawing file carries, as a PNG; `None` when it has none (or only a blank +/// one). +#[cfg(not(target_arch = "wasm32"))] +fn embedded(path: &str) -> Option> { + use std::io::{Read, Seek, SeekFrom}; + let lower = path.to_ascii_lowercase(); + let mut f = std::fs::File::open(path).ok()?; + if lower.ends_with(".dwg") { + // The preview's address is at 0x0D (Open Design Alliance DWG specification, "Image data"). + let mut head = [0u8; 0x11]; + f.read_exact(&mut head).ok()?; + let at = u64::from(u32::from_le_bytes(head.get(0x0D..0x11)?.try_into().ok()?)); + f.seek(SeekFrom::Start(at)).ok()?; + let mut sec = Vec::new(); + f.take(MAX_PREVIEW_BYTES).read_to_end(&mut sec).ok()?; + return dwg_preview(&sec, at).and_then(|img| finish(img)); + } + if lower.ends_with(".dxf") { + let mut text = String::new(); + // The THUMBNAILIMAGE section comes after the header, classes and tables: read a bounded + // amount from the start. + f.take(MAX_PREVIEW_BYTES * 4).read_to_string(&mut text).ok()?; + return dxf_preview(&text).and_then(|bmp| dib(&bmp)).and_then(finish); + } + None +} + +#[cfg(not(target_arch = "wasm32"))] +/// An image as (width, height, straight RGBA). +type Rgba = (u32, u32, Vec); + +/// A DWG preview section starting at file offset `at`: a PNG kept as is, a bitmap decoded. +#[cfg(not(target_arch = "wasm32"))] +fn dwg_preview(sec: &[u8], at: u64) -> Option { + const SENTINEL: [u8; 16] = [0x1F, 0x25, 0x6D, 0x07, 0xD4, 0x36, 0x28, 0x28, 0x9D, 0x57, 0xCA, 0x3F, 0x9D, 0x44, 0x10, 0x2B]; + if sec.get(..16)? != SENTINEL { + return None; + } + let count = *sec.get(20)?; + let mut i = 21usize; + let mut bmp = None; + let mut png = None; + for _ in 0..count.min(8) { + let code = *sec.get(i)?; + let start = u64::from(u32::from_le_bytes(sec.get(i + 1..i + 5)?.try_into().ok()?)); + let size = u32::from_le_bytes(sec.get(i + 5..i + 9)?.try_into().ok()?) as usize; + i += 9; + let off = usize::try_from(start.checked_sub(at)?).ok()?; + let data = sec.get(off..off.checked_add(size)?); + match code { + 2 => bmp = data, + 6 => png = data, + _ => {} + } + } + if let Some(p) = png + && let Some((w, h, rgba)) = cadcraft_render::raster::decode_png(p) + { + return Some((w, h, unpremultiply(rgba))); + } + dib(bmp?) +} + +/// The THUMBNAILIMAGE section's bitmap (hex in group 310 lines). +#[cfg(not(target_arch = "wasm32"))] +fn dxf_preview(text: &str) -> Option> { + let at = text.find("THUMBNAILIMAGE")?; + let mut lines = text.get(at..)?.lines().map(str::trim); + let mut out = Vec::new(); + while let Some(code) = lines.next() { + let value = lines.next()?; + match code { + "310" => { + let b = value.as_bytes(); + for pair in b.chunks(2) { + let s = std::str::from_utf8(pair).ok()?; + out.push(u8::from_str_radix(s, 16).ok()?); + } + } + "0" if value == "ENDSEC" => break, + _ => {} + } + } + (!out.is_empty()).then_some(out) +} + +#[cfg(not(target_arch = "wasm32"))] +/// A device-independent bitmap (BITMAPINFOHEADER, then a palette, then rows bottom up): 8, 24 +/// or 32 bits a pixel, uncompressed. +fn dib(b: &[u8]) -> Option { + let u32_at = |i: usize| b.get(i..i + 4).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes); + let u16_at = |i: usize| b.get(i..i + 2).and_then(|s| s.try_into().ok()).map(u16::from_le_bytes); + let header = u32_at(0)? as usize; + let w = i32::from_le_bytes(b.get(4..8)?.try_into().ok()?); + let h = i32::from_le_bytes(b.get(8..12)?.try_into().ok()?); + let bits = u16_at(14)?; + if u32_at(16)? != 0 || w <= 0 || h == 0 || w > 2048 || h.unsigned_abs() > 2048 { + return None; + } + let (w, top_down, h) = (w as usize, h < 0, h.unsigned_abs() as usize); + let colors = match (bits, u32_at(32)?) { + (8, 0) => 256, + (8, n) => (n as usize).min(256), + _ => 0, + }; + let palette = header.checked_add(colors * 4)?; + let stride = (w * usize::from(bits)).div_ceil(32) * 4; + let mut out = vec![0u8; w * h * 4]; + for y in 0..h { + let src_row = if top_down { y } else { h - 1 - y }; + let row = palette.checked_add(src_row.checked_mul(stride)?)?; + for x in 0..w { + let (r, g, bl) = match bits { + 8 => { + let i = usize::from(*b.get(row + x)?); + let p = header + i * 4; + (*b.get(p + 2)?, *b.get(p + 1)?, *b.get(p)?) + } + 24 => { + let p = row + x * 3; + (*b.get(p + 2)?, *b.get(p + 1)?, *b.get(p)?) + } + 32 => { + let p = row + x * 4; + (*b.get(p + 2)?, *b.get(p + 1)?, *b.get(p)?) + } + _ => return None, + }; + let o = (y * w + x) * 4; + out.get_mut(o..o + 4)?.copy_from_slice(&[r, g, bl, 255]); + } + } + Some((w as u32, h as u32, out)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn unpremultiply(mut rgba: Vec) -> Vec { + for px in rgba.chunks_mut(4) { + if let [r, g, b, a] = px + && *a > 0 + && *a < 255 + { + let k = |v: u8| ((u32::from(v) * 255 + u32::from(*a) / 2) / u32::from(*a)).min(255) as u8; + (*r, *g, *b) = (k(*r), k(*g), k(*b)); + } + } + rgba +} + +#[cfg(not(target_arch = "wasm32"))] +/// A carried preview as a PNG, or `None` when it is blank (one colour). +fn finish((w, h, rgba): Rgba) -> Option> { + let first = rgba.get(..4)?.to_vec(); + if rgba.chunks(4).all(|p| p == first.as_slice()) { + return None; + } + // Opaque pixels: straight and premultiplied are the same. + let opaque: Vec = + rgba.chunks(4).flat_map(|p| [p.first().copied().unwrap_or(0), p.get(1).copied().unwrap_or(0), p.get(2).copied().unwrap_or(0), 255]).collect(); + cadcraft_render::raster::encode_png(w, h, &opaque) +} + +/// The settings folder (as the app keeps its settings): `CADCRAFT_CONFIG_DIR`, `%APPDATA%\CADCraft`, +/// `$XDG_CONFIG_HOME/cadcraft` or `~/.config/cadcraft`. +#[cfg(not(target_arch = "wasm32"))] +fn config_dir() -> Option { + let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(std::path::PathBuf::from); + if let Some(d) = var("CADCRAFT_CONFIG_DIR") { + return Some(d); + } + if cfg!(windows) { + return var("APPDATA").map(|a| a.join("CADCraft")); + } + if cfg!(target_os = "macos") { + return var("HOME").map(|h| h.join("Library/Application Support/CADCraft")); + } + var("XDG_CONFIG_HOME").map(|x| x.join("cadcraft")).or_else(|| var("HOME").map(|h| h.join(".config/cadcraft"))) +} + +/// The cached preview file of `path`: named after the path, the file's size and its date. +#[cfg(not(target_arch = "wasm32"))] +fn cache_file(path: &str) -> Option { + use std::hash::{Hash, Hasher}; + let m = std::fs::metadata(path).ok()?; + let mtime = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs()); + // FNV-1a: stable across builds (the std hasher is not promised to be). + let mut h = Fnv(0xcbf2_9ce4_8422_2325); + path.hash(&mut h); + m.len().hash(&mut h); + mtime.hash(&mut h); + Some(config_dir()?.join("thumbnails").join(format!("{:016x}.png", h.finish()))) +} + +#[cfg(not(target_arch = "wasm32"))] +struct Fnv(u64); + +#[cfg(not(target_arch = "wasm32"))] +impl std::hash::Hasher for Fnv { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 ^= u64::from(*b); + self.0 = self.0.wrapping_mul(0x0100_0000_01b3); + } + } +} + +/// The "file not found" picture: a page with a folded corner drawn in dashes (it is not there), +/// a red circle with a question mark on it. +pub fn paint_missing(p: &egui::Painter, r: egui::Rect, ink: egui::Color32) { + use egui::{Stroke, pos2, vec2}; + let h = r.height().min(r.width() * 1.3) * 0.82; + let w = h * 0.76; + let page = egui::Rect::from_center_size(r.center(), vec2(w, h)); + let fold = w * 0.3; + let pts = [ + page.left_top(), + pos2(page.right() - fold, page.top()), + pos2(page.right(), page.top() + fold), + page.right_bottom(), + page.left_bottom(), + page.left_top(), + ]; + let st = Stroke::new((h / 40.0).clamp(1.5, 3.0), ink); + for seg in pts.windows(2) { + if let [a, b] = seg { + p.extend(egui::Shape::dashed_line(&[*a, *b], st, h / 14.0, h / 22.0)); + } + } + p.line_segment([pos2(page.right() - fold, page.top()), pos2(page.right() - fold, page.top() + fold)], st); + p.line_segment([pos2(page.right() - fold, page.top() + fold), pos2(page.right(), page.top() + fold)], st); + let red = egui::Color32::from_rgb(0xd9, 0x3f, 0x3f); + let c = pos2(page.right() - w * 0.12, page.bottom() - w * 0.12); + let rad = w * 0.3; + p.circle_filled(c, rad, red); + p.circle_stroke(c, rad, Stroke::new(2.0, egui::Color32::WHITE)); + p.text(c, egui::Align2::CENTER_CENTER, "?", egui::FontId::proportional(rad * 1.5), egui::Color32::WHITE); +} + +#[cfg(test)] +mod tests { + #[test] + fn a_bitmap_decodes_bottom_up_with_its_palette() { + // 2×2, 8 bits, two palette colours: bottom row red/green, top row green/red. + let mut b = Vec::new(); + b.extend(40u32.to_le_bytes()); + b.extend(2i32.to_le_bytes()); + b.extend(2i32.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(8u16.to_le_bytes()); + b.extend([0u8; 16]); + b.extend(2u32.to_le_bytes()); + b.extend(0u32.to_le_bytes()); + b.extend([0, 0, 255, 0, 0, 255, 0, 0]); // BGRA: red, green + b.extend([0, 1, 0, 0, 1, 0, 0, 0]); + let (w, h, px) = super::dib(&b).unwrap(); + assert_eq!((w, h), (2, 2)); + assert_eq!(&px[0..4], &[0, 255, 0, 255], "top-left is the last row in the file"); + assert_eq!(&px[8..12], &[255, 0, 0, 255]); + assert!(super::dib(&b[..20]).is_none()); + assert!(super::finish((1, 1, vec![9, 9, 9, 255])).is_none(), "a blank preview is no preview"); + } +} From 57f68a880c2afb18270cce107b53421f360ddc18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 11:48:52 +0300 Subject: [PATCH 08/23] doc: text formula field Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/constraints/src/tests.rs | 1 + crates/doc/src/extents.rs | 2 ++ crates/doc/src/tests.rs | 4 ++++ crates/engine/tests/attrib_modes.rs | 1 + crates/engine/tests/audit.rs | 1 + crates/engine/tests/mtext_columns.rs | 1 + crates/engine/tests/multiline_attributes.rs | 2 ++ crates/engine/tests/snap_annotations.rs | 1 + crates/io/src/tests.rs | 7 +++++++ crates/io/tests/annotative_roundtrip.rs | 1 + crates/io/tests/attrib_modes.rs | 1 + crates/io/tests/attrib_props.rs | 1 + crates/io/tests/dxf_versions.rs | 1 + crates/io/tests/entity_props_roundtrip.rs | 1 + crates/io/tests/followups_626.rs | 2 ++ crates/io/tests/mleader_roundtrip.rs | 2 ++ crates/io/tests/mtext_columns_roundtrip.rs | 1 + crates/io/tests/mtext_embedded_object.rs | 1 + crates/io/tests/mtext_line_spacing.rs | 1 + crates/io/tests/pdf_text.rs | 2 ++ crates/io/tests/text_flags_roundtrip.rs | 2 ++ crates/render/src/tests.rs | 5 +++++ crates/render/tests/annotative_viewport.rs | 1 + crates/render/tests/render_props.rs | 1 + 24 files changed, 43 insertions(+) diff --git a/crates/constraints/src/tests.rs b/crates/constraints/src/tests.rs index a3731dc297..2c650bda2c 100644 --- a/crates/constraints/src/tests.rs +++ b/crates/constraints/src/tests.rs @@ -318,6 +318,7 @@ fn invalid_references_and_purge() { let t = add_e( &mut d, EntityKind::Text(cadcraft_doc::Text { + formula: None, backwards: false, upside_down: false, insert: v(0.0, 0.0), diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index e84065a165..eaf63ba697 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -280,6 +280,7 @@ mod tests { fn text(halign: HAlign, valign: VAlign) -> Text { Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), @@ -336,6 +337,7 @@ mod tests { #[test] fn multileader_text_is_inside_its_bounds() { let mtext = crate::MText { + formula: None, frame: false, insert: Vec3::new(25.45, 0.0, 0.0), height: 5.0, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 352d99c2e1..71524c2c01 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -86,6 +86,7 @@ fn visible_attributes_of_a_missing_block_still_count() { let attrib = |invisible: bool| Attrib { tag: "TAG".into(), text: Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(1000.0, 1000.0, 0.0), @@ -426,6 +427,7 @@ fn attdef_in_block_is_ignored_in_insert_extents() { EntityKind::AttDef(Attrib { tag: "TAG".into(), text: Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(5000.0, 5000.0, 0.0), @@ -453,6 +455,7 @@ fn attdef_in_block_is_ignored_in_insert_extents() { fn text_kind(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(10.0, 10.0, 0.0), @@ -470,6 +473,7 @@ fn text_kind(value: &str) -> EntityKind { fn mtext_kind(contents: &str) -> EntityKind { EntityKind::MText(MText { + formula: None, frame: false, insert: Vec3::new(10.0, 10.0, 0.0), height: 2.0, diff --git a/crates/engine/tests/attrib_modes.rs b/crates/engine/tests/attrib_modes.rs index 52f8b4cb1f..74faf36812 100644 --- a/crates/engine/tests/attrib_modes.rs +++ b/crates/engine/tests/attrib_modes.rs @@ -12,6 +12,7 @@ use serde_json::json; fn references_take_lock_position_from_the_definition() { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/engine/tests/audit.rs b/crates/engine/tests/audit.rs index fbe6184d9b..374635bc82 100644 --- a/crates/engine/tests/audit.rs +++ b/crates/engine/tests/audit.rs @@ -57,6 +57,7 @@ fn corrupt(d: &mut Drawing) -> (Handle, Handle) { &Space::Model, on("0"), EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/engine/tests/mtext_columns.rs b/crates/engine/tests/mtext_columns.rs index 91ff4c1956..bcbb9c9f23 100644 --- a/crates/engine/tests/mtext_columns.rs +++ b/crates/engine/tests/mtext_columns.rs @@ -85,6 +85,7 @@ fn scale_scales_multileader_text_width_and_columns() { // #709: SCALE 2 on a multileader's text doubles its width and column lengths like it does // for a standalone MTEXT, not only its height. let text = MText { + formula: None, frame: false, insert: Default::default(), height: 2.0, diff --git a/crates/engine/tests/multiline_attributes.rs b/crates/engine/tests/multiline_attributes.rs index bdf9d3d388..d7cb1986c7 100644 --- a/crates/engine/tests/multiline_attributes.rs +++ b/crates/engine/tests/multiline_attributes.rs @@ -12,6 +12,7 @@ use serde_json::json; fn session() -> Session { let mut d = cadcraft_engine::doc::Drawing::new_imperial(); let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(2.0, 2.0, 0.0), @@ -26,6 +27,7 @@ fn session() -> Session { valign: Default::default(), }; let mtext = MText { + formula: None, frame: false, insert: Vec3::new(10.0, 3.0, 0.0), height: 2.0, diff --git a/crates/engine/tests/snap_annotations.rs b/crates/engine/tests/snap_annotations.rs index 71894c3aae..865690d9ba 100644 --- a/crates/engine/tests/snap_annotations.rs +++ b/crates/engine/tests/snap_annotations.rs @@ -44,6 +44,7 @@ fn justified_text_snaps_and_grips_at_its_alignment_point() { let mut s = Session::new(); // As read from DXF: a right-justified text keeps group 10 (start) and group 11 (alignment). let t = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 710be1e1a0..48c2e8d425 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -27,6 +27,7 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), @@ -46,6 +47,7 @@ fn sample() -> Drawing { &Space::Model, c("0"), EntityKind::MText(MText { + formula: None, frame: false, insert: Vec3::new(5.0, 5.0, 0.0), height: 0.2, @@ -258,6 +260,7 @@ fn block_definition_properties_and_constant_attdefs_roundtrip() { let mut b = Block::new("Title"); (b.description, b.units, b.explodable) = ("Drawing title block".into(), 4, false); let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, @@ -1274,6 +1277,7 @@ const INTL: &str = "图号 İø Ø 😀"; fn intl_text(value: &str) -> Text { Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), @@ -1300,6 +1304,7 @@ fn intl_sample() -> Drawing { &Space::Model, on.clone(), EntityKind::MText(MText { + formula: None, frame: false, insert: Vec3::new(5.0, 5.0, 0.0), height: 2.5, @@ -1542,6 +1547,7 @@ fn dwg_roundtrip_keeps_extension_data() { fn mleader_is_written_as_multileader() { let mut d = Drawing::new_metric(); let text = cadcraft_doc::MText { + formula: None, frame: false, insert: Vec3::new(12.0, 5.0, 0.0), height: 2.5, @@ -1579,6 +1585,7 @@ fn mleader_is_written_as_multileader() { fn attdef_prompt_survives_dxf_roundtrip() { let mut d = Drawing::new_metric(); let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/io/tests/annotative_roundtrip.rs b/crates/io/tests/annotative_roundtrip.rs index 684e00143c..5a24bd1749 100644 --- a/crates/io/tests/annotative_roundtrip.rs +++ b/crates/io/tests/annotative_roundtrip.rs @@ -10,6 +10,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/io/tests/attrib_modes.rs b/crates/io/tests/attrib_modes.rs index de067ba132..9815481137 100644 --- a/crates/io/tests/attrib_modes.rs +++ b/crates/io/tests/attrib_modes.rs @@ -9,6 +9,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn attrib(tag: &str, modes: AttribModes) -> Attrib { let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/io/tests/attrib_props.rs b/crates/io/tests/attrib_props.rs index 73c50d4557..1fbb590194 100644 --- a/crates/io/tests/attrib_props.rs +++ b/crates/io/tests/attrib_props.rs @@ -10,6 +10,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn text(x: f64, value: &str) -> Text { Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(x, 0.0, 0.0), diff --git a/crates/io/tests/dxf_versions.rs b/crates/io/tests/dxf_versions.rs index 663def61a3..e59a85c5d0 100644 --- a/crates/io/tests/dxf_versions.rs +++ b/crates/io/tests/dxf_versions.rs @@ -9,6 +9,7 @@ const INTL: &str = "图号 Café Ø 😀"; fn text(value: &str) -> EntityKind { EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), diff --git a/crates/io/tests/entity_props_roundtrip.rs b/crates/io/tests/entity_props_roundtrip.rs index aa49b973ab..34b6c0f0f3 100644 --- a/crates/io/tests/entity_props_roundtrip.rs +++ b/crates/io/tests/entity_props_roundtrip.rs @@ -29,6 +29,7 @@ fn thickness_roundtrips_on_every_entity_that_has_one() { let mut d = Drawing::new_metric(); let p = |x, y| Vec3::new(x, y, 0.0); let text = Text { + formula: None, backwards: false, upside_down: false, insert: p(0.0, 0.0), diff --git a/crates/io/tests/followups_626.rs b/crates/io/tests/followups_626.rs index 07afb8a0ad..e257a859f0 100644 --- a/crates/io/tests/followups_626.rs +++ b/crates/io/tests/followups_626.rs @@ -35,6 +35,7 @@ fn mleader_drawing() -> (Drawing, MLeader) { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + formula: None, frame: false, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, @@ -165,6 +166,7 @@ fn code_page_is_kept_before_2007() { &Space::Model, Common::default(), EntityKind::Text(Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/io/tests/mleader_roundtrip.rs b/crates/io/tests/mleader_roundtrip.rs index 2dbb8c4bef..75ac01bce0 100644 --- a/crates/io/tests/mleader_roundtrip.rs +++ b/crates/io/tests/mleader_roundtrip.rs @@ -22,6 +22,7 @@ fn text_mleader() -> MLeader { landing: Vec3::new(5.0, 4.0, 0.0), dogleg: 0.75, text: Some(MText { + formula: None, frame: false, insert: Vec3::new(5.9, 4.0, 0.0), height: 0.4, @@ -81,6 +82,7 @@ fn spline_leader_with_block_content_and_attributes() { let mut blk = Block::new("BUBBLE"); blk.entities.push(Entity::new(Handle(0x200), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 }))); let tag_text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(-0.2, -0.1, 0.0), diff --git a/crates/io/tests/mtext_columns_roundtrip.rs b/crates/io/tests/mtext_columns_roundtrip.rs index c6812aa80c..6e8831e13c 100644 --- a/crates/io/tests/mtext_columns_roundtrip.rs +++ b/crates/io/tests/mtext_columns_roundtrip.rs @@ -7,6 +7,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn mtext(contents: &str, rotation: f64, columns: Option) -> MText { MText { + formula: None, frame: false, insert: Vec3::new(1.0, 2.0, 0.0), height: 0.5, diff --git a/crates/io/tests/mtext_embedded_object.rs b/crates/io/tests/mtext_embedded_object.rs index 7308ae0eee..f277dc6ada 100644 --- a/crates/io/tests/mtext_embedded_object.rs +++ b/crates/io/tests/mtext_embedded_object.rs @@ -12,6 +12,7 @@ use cadcraft_io::{read_dxf, write_dxf}; fn with_embedded_object(rotation: f64, dir: (f64, f64)) -> String { let mut d = Drawing::new_metric(); let t = MText { + formula: None, frame: false, insert: Vec3::new(30.0, 17.0, 0.0), height: 0.5, diff --git a/crates/io/tests/mtext_line_spacing.rs b/crates/io/tests/mtext_line_spacing.rs index 539c6f2091..f90935f1cc 100644 --- a/crates/io/tests/mtext_line_spacing.rs +++ b/crates/io/tests/mtext_line_spacing.rs @@ -8,6 +8,7 @@ fn line_spacing_style_roundtrips() { for exact in [false, true] { let mut d = Drawing::new_metric(); let t = MText { + formula: None, frame: false, insert: Vec3::new(1.0, 2.0, 0.0), height: 2.5, diff --git a/crates/io/tests/pdf_text.rs b/crates/io/tests/pdf_text.rs index 35d37774bd..1ef1240715 100644 --- a/crates/io/tests/pdf_text.rs +++ b/crates/io/tests/pdf_text.rs @@ -159,6 +159,7 @@ fn style(d: &mut Drawing, name: &str, font: &str) { fn text(d: &mut Drawing, space: &Space, style: &str, at: (f64, f64), value: &str, rotation: f64, width_factor: f64, oblique: f64) { let t = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(at.0, at.1, 0.0), @@ -356,6 +357,7 @@ fn hostile_text_never_panics() { [("A".repeat(5000), 10.0, 0.0), ("AB".into(), 1e300, 0.0), ("AB".into(), 1e-300, 1e300), ("\u{0}A\u{FFFF}B".into(), 5.0, f64::NAN)] { let t = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/io/tests/text_flags_roundtrip.rs b/crates/io/tests/text_flags_roundtrip.rs index 70d2f26c56..120e13ca93 100644 --- a/crates/io/tests/text_flags_roundtrip.rs +++ b/crates/io/tests/text_flags_roundtrip.rs @@ -8,6 +8,7 @@ use cadcraft_geom::Vec3; fn text_flags_and_mtext_frame_roundtrip() { let mut d = Drawing::new_metric(); let t = Text { + formula: None, insert: Vec3::new(1.0, 2.0, 0.0), align_pt: None, height: 2.5, @@ -23,6 +24,7 @@ fn text_flags_and_mtext_frame_roundtrip() { }; d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); let m = MText { + formula: None, frame: true, insert: Vec3::new(0.0, 10.0, 0.0), height: 2.5, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index ab7afba90a..d322ae86c3 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -48,6 +48,7 @@ fn text_produces_strokes() { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, @@ -257,6 +258,7 @@ fn text_doc(style_font: &str, value: &str) -> Drawing { &Space::Model, Common::default(), EntityKind::Text(cadcraft_doc::Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, @@ -342,6 +344,7 @@ fn truetype_mtext_and_dimension_text() { &Space::Model, Common::default(), EntityKind::MText(cadcraft_doc::MText { + formula: None, frame: false, insert: Vec3::ZERO, height: 1.0, @@ -778,6 +781,7 @@ fn attrib(tag: &str) -> cadcraft_doc::Attrib { cadcraft_doc::Attrib { tag: tag.into(), text: cadcraft_doc::Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(1.0, 1.0, 0.0), @@ -877,6 +881,7 @@ fn attributes_follow_the_reference_layer_and_have_no_definition() { fn mtext_exact_spacing_ignores_taller_lines() { // #711: a doubled middle line pushes the next baseline down with At least, not with Exactly. let mtext = |contents: &str, line_spacing: f64, line_spacing_exact: bool| cadcraft_doc::MText { + formula: None, frame: false, insert: Vec3::ZERO, height: 1.0, diff --git a/crates/render/tests/annotative_viewport.rs b/crates/render/tests/annotative_viewport.rs index 466e7cb26c..0d7e541846 100644 --- a/crates/render/tests/annotative_viewport.rs +++ b/crates/render/tests/annotative_viewport.rs @@ -25,6 +25,7 @@ fn drawing(scale: f64, all_visible: bool) -> Drawing { d.header.set_i64("ANNOALLVISIBLE", i64::from(all_visible)); let anno = Common { anno_scales: vec![AnnoScale::new("1:50", 1.0, 50.0), AnnoScale::new("1:100", 1.0, 100.0)], ..Default::default() }; let text = Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::ZERO, diff --git a/crates/render/tests/render_props.rs b/crates/render/tests/render_props.rs index 3ec854a9d1..ab870ec8f2 100644 --- a/crates/render/tests/render_props.rs +++ b/crates/render/tests/render_props.rs @@ -99,6 +99,7 @@ fn leader_arrows_use_their_style_dimscale() { fn text(x: f64, value: &str) -> Text { Text { + formula: None, backwards: false, upside_down: false, insert: Vec3::new(x, 0.0, 0.0), From 6922915ed4a88d11b50fa53e7f210ea7190880e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 12:19:24 +0300 Subject: [PATCH 09/23] b15: text formulas and AutoCAD date fields, completion, help, UPDATEFIELD Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/file.rs | 3 + crates/engine/src/cmd/modify2.rs | 38 +++++++- crates/engine/src/lib.rs | 7 ++ crates/engine/src/textformula.rs | 17 +++- crates/engine/tests/text_justify.rs | 22 +++++ crates/io/src/dxf_ext.rs | 15 +++ crates/io/src/dxf_fields.rs | 122 ++++++++++++++++++++++++ crates/io/src/dxf_raw.rs | 2 +- crates/io/src/dxf_read.rs | 5 +- crates/io/src/dxf_write.rs | 22 ++++- crates/io/src/lib.rs | 1 + crates/io/tests/text_flags_roundtrip.rs | 4 +- crates/ui-egui/src/bidi_edit.rs | 9 +- crates/ui-egui/src/dialogs.rs | 24 +++++ crates/ui-egui/src/i18n/ru.tsv | 67 +++++++++++++ crates/ui-egui/src/i18n/uk.tsv | 15 +++ crates/ui-egui/src/menus.rs | 2 + crates/ui-egui/src/mtext_editor.rs | 96 +++++++++++++++++++ 18 files changed, 458 insertions(+), 13 deletions(-) create mode 100644 crates/io/src/dxf_fields.rs diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8a8de3f407..8312f48832 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -380,6 +380,9 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result) -> usize { crate::grips::adopt_file_dim_text(&mut drawing); + // Formulas and fields (dates) worked out for today. + let env = crate::textformula::Env { now: crate::textformula::local_now(), file: file_name(name), sheet: "Model".into() }; + crate::textformula::refresh(&mut drawing, &env); let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); if let Some(st) = s.docs.get_mut(i) { diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index 2cdf45eace..d0b447df2e 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -73,6 +73,9 @@ pub fn specs() -> Vec { .menu(&["Modify", "Array", "Path Array"]) .params("{handles?, path (handle), count? (default 6) | spacing?, align?: bool (default true)}") .interactive(|_| Ok(Box::new(PathArrayM::default()))), + CommandSpec::new("updatefield", "Update Fields", run_updatefield) + .menu(&["Tools", "Update Fields"]) + .params("{} (works out every text formula and known field again: dates, file name)"), CommandSpec::new("textedit", "Edit Text...", run_textedit) .menu(&["Modify", "Object", "Edit Text..."]) .alias(&["ed", "ddedit"]) @@ -2211,9 +2214,22 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { let d = s.doc().ok()?; let key = h.hex(); match &d.entity(h)?.kind { - EntityKind::MText(t) => Some(TextEditor { mtext: t.clone(), kind: EditorKind::MText, key }), + // A text with a formula is edited as its formula. + EntityKind::MText(t) => { + let mut m = t.clone(); + if let Some(f) = t.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + m.contents.clone_from(f); + } + Some(TextEditor { mtext: m, kind: EditorKind::MText, key }) + } EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key }), - EntityKind::Text(t) => Some(TextEditor { mtext: line_box(t), kind: EditorKind::Line, key }), + EntityKind::Text(t) => { + let mut b = line_box(t); + if let Some(f) = t.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { + b.contents.clone_from(f); + } + Some(TextEditor { mtext: b, kind: EditorKind::Line, key }) + } EntityKind::AttDef(a) => Some(TextEditor { mtext: line_box(&a.text), kind: EditorKind::Line, key }), EntityKind::Dimension(dm) => { let g = cadcraft_render::dimension_in(d, dm); @@ -2243,6 +2259,15 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { return Err(other("The object is on a locked layer.")); } let mut k = curves::entity(s, h)?.kind; + // The text as the editor showed it (a formula, else the value): unchanged, it keeps its + // formula or AutoCAD field. + let shown = match &k { + EntityKind::Text(t) => t.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| t.value.clone()), + EntityKind::AttDef(a) => a.text.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| a.text.value.clone()), + EntityKind::MText(t) => t.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| t.contents.clone()), + _ => String::new(), + }; + let unchanged = shown == text || shown == text.replace('\n', "\\P"); match &mut k { EntityKind::Text(t) => t.value = text.to_string(), EntityKind::AttDef(a) => a.text.value = text.to_string(), @@ -2257,9 +2282,18 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { }, _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), } + let env = crate::textformula::env(s); + crate::textformula::apply(&mut k, &env, !unchanged); set_kind(s, h, k) } +fn run_updatefield(s: &mut Session, _p: &Value) -> Result { + let env = crate::textformula::env(s); + let n = crate::textformula::refresh(s.doc_mut()?, &env); + s.echo(format!("{n} field(s) updated")); + Ok(json!({ "updated": n })) +} + fn run_textedit(s: &mut Session, p: &Value) -> Result { let h = targets(s, p)?.first().copied().ok_or_else(|| bad("textedit", "`handle` is required"))?; let text = str_param(p, "text").ok_or_else(|| bad("textedit", "`text` is required"))?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9e3b70c7ec..12ea824e24 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ pub mod select; pub mod snap; pub mod spatial; pub mod sysvars; +pub mod textformula; pub mod undoctl; pub mod units; @@ -840,6 +841,12 @@ impl Session { /// Add an entity to the current space with current properties. pub fn add_entity(&mut self, kind: EntityKind) -> Result { + // Text starting with `=` is a formula: it keeps the formula and shows the result. + let mut kind = kind; + if matches!(kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)) { + let env = textformula::env(self); + textformula::apply(&mut kind, &env, true); + } let common = self.current_common(); let space = self.space(); let true_color = self.doc()?.header.get("CECOLOR_RGB").and_then(|v| v.as_i64()); diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index 02dbd78cd2..c873af9d89 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -665,8 +665,10 @@ fn call(name: &str, a: &[Val], env: &Env) -> R { if v.is_empty() { Err(Err::Div0) } else { Ok(Val::Num(v.iter().sum::() / v.len() as f64)) } } "SUM" => Ok(Val::Num(nums(a)?.iter().sum())), - "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()).and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), - "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))).and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), "CONCAT" => Ok(Val::Text(a.iter().map(Val::text).collect())), "COS" => Ok(Val::Num(n0(a)?.cos())), "SIN" => Ok(Val::Num(n0(a)?.sin())), @@ -897,7 +899,16 @@ mod tests { assert_eq!(ev("=\"a\"*2"), "#VALUE!"); assert_eq!(ev("=SQRT(-1)"), "#NUM!"); assert_eq!(ev("=(1+"), "#ERROR!"); - for f in ["=", "==", "=(((((", &format!("={}", "-".repeat(500)), &format!("={}1", "(".repeat(100)), "=\"", "=MID(\"a\",-5,1e300)", "=DATE(1e300,1,1)"] { + for f in [ + "=", + "==", + "=(((((", + &format!("={}", "-".repeat(500)), + &format!("={}1", "(".repeat(100)), + "=\"", + "=MID(\"a\",-5,1e300)", + "=DATE(1e300,1,1)", + ] { let _ = evaluate(f, &env()); } assert!(!is_formula("plain")); diff --git a/crates/engine/tests/text_justify.rs b/crates/engine/tests/text_justify.rs index c2a01f9746..1fb2042940 100644 --- a/crates/engine/tests/text_justify.rs +++ b/crates/engine/tests/text_justify.rs @@ -59,3 +59,25 @@ fn backwards_upside_down_and_frame_are_properties() { let frame = cadcraft_render::mtext_frame(d, &mt).unwrap(); assert_eq!(frame.len(), 5); } + +#[test] +fn text_formulas_show_their_result_and_edit_as_formulas() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=2400-2*18" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let get = |s: &Session| match &s.doc().unwrap().model.iter().next().unwrap().kind { + EntityKind::Text(t) => (t.value.clone(), t.formula.clone()), + _ => panic!(), + }; + assert_eq!(get(&s), ("2364".to_string(), Some("=2400-2*18".to_string()))); + // Edited as the formula; plain text drops it. + s.execute("textedit", &json!({ "handle": h, "text": "=ROUND(10/3,2)" })).unwrap(); + assert_eq!(get(&s).0, "3.33"); + s.execute("textedit", &json!({ "handle": h, "text": "plain" })).unwrap(); + assert_eq!(get(&s), ("plain".to_string(), None)); + // Dates follow the clock when fields are updated. + s.execute("textedit", &json!({ "handle": h, "text": "=TEXT(TODAY(),\"yyyy\")" })).unwrap(); + let year = get(&s).0; + assert!(year.len() == 4 && year.starts_with("20"), "{year}"); + assert_eq!(s.execute("updatefield", &json!({})).unwrap()["updated"], 1); +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 1e68dfc562..c1add8c551 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -22,6 +22,21 @@ use serde_json::Value; pub(crate) const APP: &str = "CADCRAFT"; /// AutoCAD's hatch background colour xdata application (one `1071` colour value). pub(crate) const HATCH_BACKGROUND_APP: &str = "HATCHBACKGROUNDCOLOR"; +/// Extended data of a text's formula (`=...`), in 1000 strings of at most 250 characters. +pub(crate) const FORMULA_APP: &str = "CADCRAFTFORMULA"; + +/// A text's formula from its `CADCRAFTFORMULA` extended data. +pub(crate) fn formula(tags: &[Tag]) -> Option { + let x = xdata(tags, FORMULA_APP); + let s: String = x.iter().filter(|t| t.code == 1000).map(|t| t.str()).collect(); + (!s.is_empty()).then_some(s) +} + +/// A formula as 1000 strings of at most 250 characters (whole characters). +pub(crate) fn formula_chunks(f: &str) -> Vec { + let chars: Vec = f.chars().take(4000).collect(); + chars.chunks(250).map(|c| c.iter().collect()).collect() +} /// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index /// colour in the low byte, 0xC0 ByLayer, 0xC1 ByBlock; `None` for none or anything else. diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs new file mode 100644 index 0000000000..fa3dd793a1 --- /dev/null +++ b/crates/io/src/dxf_fields.rs @@ -0,0 +1,122 @@ +//! AutoCAD fields in text: a TEXT or MTEXT whose extension dictionary holds `ACAD_FIELD` → +//! `TEXT` → a FIELD object. That field's code is the text's template (`Date: %<\_FldIdx 0>%`) +//! and its child fields fill the `\_FldIdx` places (`\AcVar date \f "dd.MM.yyyy"`). The +//! resolved template becomes the text's formula, which the engine works out when the drawing is +//! opened (dates follow the clock); the field objects themselves are kept and written back as +//! they were read. + +use std::collections::HashMap; + +use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle}; +use cadcraft_dxf::{Section, Tag, records}; + +/// Deepest nesting of fields followed. +const MAX_DEPTH: usize = 8; +/// Longest template kept. +const MAX_LEN: usize = 16_384; + +fn handle_of(tags: &[Tag]) -> Option { + tags.iter().find(|t| t.code == 5).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// The extension dictionary of a record (`102 {ACAD_XDICTIONARY` `360 handle`). +fn xdict(tags: &[Tag]) -> Option { + let at = tags.iter().position(|t| t.code == 102 && t.str().trim().eq_ignore_ascii_case("{ACAD_XDICTIONARY"))?; + tags.get(at + 1).filter(|t| t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// A dictionary's entry (`3 name` then `350`/`360 handle`). +fn entry(tags: &[Tag], name: &str) -> Option { + let at = tags.iter().position(|t| t.code == 3 && t.str().trim().eq_ignore_ascii_case(name))?; + tags.get(at + 1).filter(|t| t.code == 350 || t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()) +} + +/// A field's code (2, continued in 3s) with its `\_FldIdx n` places filled from its children. +fn code(objects: &HashMap>, h: &str, depth: usize) -> Option { + if depth > MAX_DEPTH { + return None; + } + let tags = objects.get(h)?; + let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbField").unwrap_or(0); + let body = tags.get(start..)?; + // The code and its overflow come before the value data (the first 7 ACFD_FIELD_VALUE). + let end = body.iter().position(|t| t.code == 7).unwrap_or(body.len()); + let own = body.get(..end)?; + let mut s = String::new(); + for t in own.iter().filter(|t| t.code == 2 || t.code == 3) { + s.push_str(&t.str()); + if s.len() > MAX_LEN { + return None; + } + } + let children: Vec = own.iter().filter(|t| t.code == 360).map(|t| t.str().trim().to_ascii_uppercase()).collect(); + for (i, c) in children.iter().enumerate().take(64) { + let place = format!("%<\\_FldIdx {i}>%"); + if s.contains(&place) { + let inner = code(objects, c, depth + 1)?; + s = s.replace(&place, &format!("%<{inner}>%")); + } + } + Some(s) +} + +/// Give the texts with AutoCAD fields their templates as formulas. +pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { + let mut objects: HashMap> = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "OBJECTS") { + for (kind, tags) in records(&s.tags) { + if (kind == "DICTIONARY" || kind == "FIELD") + && let Some(h) = handle_of(&tags) + { + objects.insert(h, tags); + } + } + } + if !objects.values().any(|t| t.iter().any(|g| g.code == 100 && g.str().trim() == "AcDbField")) { + return; + } + let mut formulas: HashMap = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { + for (kind, tags) in records(&s.tags) { + if !matches!(kind.as_str(), "TEXT" | "MTEXT") { + continue; + } + let found = (|| { + let x = xdict(&tags)?; + let fd = entry(objects.get(&x)?, "ACAD_FIELD")?; + let f = entry(objects.get(&fd)?, "TEXT")?; + let c = code(&objects, &f, 0)?; + let h = Handle::parse_hex(&handle_of(&tags)?)?; + Some((h, c)) + })(); + if let Some((h, c)) = found.filter(|(_, c)| c.contains("%<\\")) { + formulas.insert(h, c); + } + } + } + if formulas.is_empty() { + return; + } + let set = |store: &mut EntityStore| { + let hs: Vec = store.iter().filter(|e| formulas.contains_key(&e.handle)).map(|e| e.handle).collect(); + for h in hs { + let f = formulas.get(&h).cloned(); + store.modify(h, |e| match &mut e.kind { + EntityKind::Text(t) => t.formula = f, + EntityKind::MText(t) => t.formula = f, + _ => {} + }); + } + }; + set(&mut d.model); + for l in &mut d.layouts { + set(&mut l.entities); + } + let names: Vec = + d.blocks.iter().filter(|(_, b)| b.entities.iter().any(|e| formulas.contains_key(&e.handle))).map(|(k, _)| k.clone()).collect(); + for k in names { + if let Some(b) = d.blocks.get_mut(&k) { + set(&mut std::sync::Arc::make_mut(b).entities); + } + } +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index 05e88403b9..b48c7298c7 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -43,7 +43,7 @@ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCO /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides /// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. -const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD"]; +const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD", "CADCRAFTFORMULA"]; /// Most objects kept from one file. const MAX_OBJECTS: usize = 1_000_000; diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index d5e00d069b..a55601a54e 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -162,9 +162,9 @@ fn mtext_from(tags: &[Tag], c: &Common) -> MText { }; } MText { - formula: None, // Background flags (90): 16 = a frame around the text. frame: own.i(90).is_some_and(|f| f & 16 != 0), + formula: crate::dxf_ext::formula(tags), insert: t.p(10), height: t.fd(40, 0.2).max(1e-9), width: match &columns { @@ -201,7 +201,6 @@ fn text_from(t: &T) -> Text { // attribute's embedded multiline text, after 101, has a 71 of its own). let generation = t.0.iter().take_while(|g| g.code != 101).find(|g| g.code == 71).map_or(0, |g| g.i64()); let mut text = Text { - formula: None, insert: t.p(10), align_pt: if h == HAlign::Left && v == VAlign::Baseline { None } else { align }, height: t.fd(40, 0.2).max(1e-9), @@ -214,6 +213,7 @@ fn text_from(t: &T) -> Text { valign: v, backwards: generation & 2 != 0, upside_down: generation & 4 != 0, + formula: crate::dxf_ext::formula(t.0), }; let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0)); if n.z < 0.0 { @@ -1858,6 +1858,7 @@ pub fn read(bytes: &[u8]) -> Result { d.layers.insert(0, Layer::default()); } crate::dxf_raw::read(&secs, &mut d); + crate::dxf_fields::resolve(&secs, &mut d); d.skipped_records = skipped; Ok(d) } diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 59c7471d6a..80755bff88 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -458,6 +458,15 @@ fn attrib_flags(a: &Attrib) -> i64 { /// A TEXT's groups, or an attribute's (`attrib`, in a file of version `target`) with its /// subclass: the subclass version (`280 0`, 2010 and later), prompt, tag, flags and alignment, /// then Lock position (`280`, 2007 and later; readers take the 280 after the tag as it). +/// A text's own formula (`=...`) as extended data; AutoCAD fields stay in their own objects. +fn formula_xdata(w: &mut W, f: Option<&str>) { + let Some(f) = f.filter(|f| f.trim_start().starts_with('=')) else { return }; + w.s(1001, dxf_ext::FORMULA_APP); + for c in dxf_ext::formula_chunks(f) { + w.s(1000, c); + } +} + fn text_tags(w: &mut W, t: &Text, attrib: Option<(&Attrib, Version)>, attdef_prompt: Option<&str>) { w.p(10, t.insert); w.f(40, t.height); @@ -697,6 +706,7 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx common(w, e, owner, paper, "AcDbText"); thickness(w, e); text_tags(w, t, None, None); + formula_xdata(w, t.formula.as_deref()); } // Closed polylines, one per loop (`dxf_region`): REGION's own data is ACIS. EntityKind::Region(r) => { @@ -752,6 +762,7 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx w.f(45, 1.5); } w.t.extend(crate::dxf_read::mtext_dxf::column_tags(t)); + formula_xdata(w, t.formula.as_deref()); } EntityKind::Insert(i) => { w.s(0, "INSERT"); @@ -2050,8 +2061,15 @@ fn tags_for(d: &Drawing, version: Version, target: Version) -> Vec { w.f(146, 0.0); } w.s(0, "ENDTAB"); - let apps = - ["ACAD", dxf_ext::APP, "AcadAnnotative", dxf_ext::LAYER_TRANSPARENCY_APP, dxf_ext::LAYER_DESCRIPTION_APP, dxf_ext::HATCH_BACKGROUND_APP]; + let apps = [ + "ACAD", + dxf_ext::APP, + "AcadAnnotative", + dxf_ext::LAYER_TRANSPARENCY_APP, + dxf_ext::LAYER_DESCRIPTION_APP, + dxf_ext::HATCH_BACKGROUND_APP, + dxf_ext::FORMULA_APP, + ]; let th = table_head(&mut w, "APPID", apps.len()); for app in apps { record_head(&mut w, "APPID", &th, "AcDbRegAppTableRecord"); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index fb9ed9d45e..5e5ef90b5c 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -6,6 +6,7 @@ mod dxf_raw; mod dxf_ext; +mod dxf_fields; mod dxf_image; mod dxf_mleader; mod dxf_read; diff --git a/crates/io/tests/text_flags_roundtrip.rs b/crates/io/tests/text_flags_roundtrip.rs index 120e13ca93..94efe00161 100644 --- a/crates/io/tests/text_flags_roundtrip.rs +++ b/crates/io/tests/text_flags_roundtrip.rs @@ -8,7 +8,6 @@ use cadcraft_geom::Vec3; fn text_flags_and_mtext_frame_roundtrip() { let mut d = Drawing::new_metric(); let t = Text { - formula: None, insert: Vec3::new(1.0, 2.0, 0.0), align_pt: None, height: 2.5, @@ -21,6 +20,7 @@ fn text_flags_and_mtext_frame_roundtrip() { valign: VAlign::Baseline, backwards: true, upside_down: true, + formula: Some("=1+1".into()), }; d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); let m = MText { @@ -41,6 +41,6 @@ fn text_flags_and_mtext_frame_roundtrip() { let bytes = cadcraft_io::write(&d, "a.dxf").unwrap(); let back = cadcraft_io::read(&bytes, "a.dxf").unwrap(); let kinds: Vec = back.model.iter().map(|e| e.kind.clone()).collect(); - assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.backwards && t.upside_down))); + assert!(kinds.iter().any(|k| matches!(k, EntityKind::Text(t) if t.backwards && t.upside_down && t.formula.as_deref() == Some("=1+1")))); assert!(kinds.iter().any(|k| matches!(k, EntityKind::MText(m) if m.frame))); } diff --git a/crates/ui-egui/src/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs index 134718a142..e672b68e08 100644 --- a/crates/ui-egui/src/bidi_edit.rs +++ b/crates/ui-egui/src/bidi_edit.rs @@ -55,6 +55,8 @@ impl EditState { pub struct Output { pub response: egui::Response, pub changed: bool, + /// The caret's bottom on screen (where a completion list goes). + pub caret: Pos2, } /// A character placed on a line. @@ -521,6 +523,11 @@ pub fn show( } } } + let caret_bottom = { + let l = lay.lines.get(cl); + let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); + at(cx, top + hgt) + }; if focused { let l = lay.lines.get(cl); let (top, hgt) = l.map_or((0.0, row_h), |l| (l.top, l.height)); @@ -539,7 +546,7 @@ pub fn show( }) }); } - Output { response, changed } + Output { response, changed, caret: caret_bottom } } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 923fdc97c0..a35c24703a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -27,6 +27,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "preview" => crate::exchange::dialog(app, ctx, &mut open), "publish" => crate::batchplot::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), + "formulas" => formulas(ctx, &mut open), "blocks" => crate::blockmgr::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), @@ -342,6 +343,29 @@ fn about(ctx: &egui::Context, open: &mut bool) { }); } +/// Help ▸ Text Formulas: how formulas in text work and the functions they use. +fn formulas(ctx: &egui::Context, open: &mut bool) { + egui::Window::new(crate::tl!("Text Formulas")).id(egui::Id::new("Text Formulas")).open(open).default_size(vec2(680.0, 520.0)).show(ctx, |ui| { + ui.label(crate::tl!( + "A text that starts with = shows the result of a formula, as in a spreadsheet: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();\"dd.mm.yyyy\"). The formula stays with the text: editing the text edits the formula. Dates and times follow the computer's clock and are worked out again when the drawing is opened (Tools ▸ Update Fields does it at once). Date fields in AutoCAD drawings are updated the same way." + )); + ui.add_space(4.0); + ui.label(crate::tl!( + "Operators: + - * / ^ (power), % (percent), & (joins texts), = <> < > <= >= (compare). Texts in double quotes. Arguments are separated by commas or semicolons. While typing a formula, a list of functions appears: the arrows choose, Tab or Enter inserts." + )); + ui.separator(); + egui::ScrollArea::vertical().show(ui, |ui| { + egui::Grid::new("formula_functions").striped(true).num_columns(2).show(ui, |ui| { + for (name, args, what) in cadcraft_engine::textformula::FUNCTIONS { + ui.label(egui::RichText::new(format!("{name}({args})")).monospace()); + ui.label(crate::i18n::t(what)); + ui.end_row(); + } + }); + }); + }); +} + fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut start = None; egui::Window::new(crate::tl!("Command Reference")).id(egui::Id::new("Command Reference")).open(open).default_size(vec2(640.0, 480.0)).show( diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 6c790e705a..d6a447871b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1409,3 +1409,70 @@ Current Lineweight Текущий вес линий Snap the crosshair to grips Привязывать перекрестие к ручкам With no command running, the crosshair locks onto a grip of the selected objects under it. Когда команда не выполняется, перекрестие притягивается к ручке выбранного объекта под курсором. + Grid with previews Сетка с эскизами + File not found Файл не найден + Making a preview... Создаётся эскиз... + Backwards Справа налево (зеркально) + Upside down Вверх ногами + Top left Вверху слева + Top center Вверху по центру + Top right Вверху справа + Middle left Посередине слева + Middle center Посередине по центру + Middle right Посередине справа + Bottom left Внизу слева + Bottom center Внизу по центру + Bottom right Внизу справа + Text Formulas Формулы в тексте + Update Fields Обновить поля + Tab or Enter: insert · Esc: close Tab или Enter: вставить · Esc: закрыть + A text that starts with = shows the result of a formula, as in a spreadsheet: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). The formula stays with the text: editing the text edits the formula. Dates and times follow the computer's clock and are worked out again when the drawing is opened (Tools ▸ Update Fields does it at once). Date fields in AutoCAD drawings are updated the same way. Текст, который начинается со знака =, показывает результат формулы, как в электронной таблице: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). Формула хранится вместе с текстом: при редактировании текста редактируется формула. Даты и время берутся из часов компьютера и пересчитываются при открытии чертежа (Сервис ▸ Обновить поля делает это сразу). Поля даты в чертежах AutoCAD обновляются так же. + Operators: + - * / ^ (power), % (percent), & (joins texts), = <> < > <= >= (compare). Texts in double quotes. Arguments are separated by commas or semicolons. While typing a formula, a list of functions appears: the arrows choose, Tab or Enter inserts. Операции: + - * / ^ (степень), % (процент), & (соединяет тексты), = <> < > <= >= (сравнение). Тексты пишутся в двойных кавычках. Аргументы разделяются запятыми или точками с запятой. Пока вы набираете формулу, появляется список функций: стрелки выбирают, Tab или Enter вставляет. + The number without its sign. Число без знака. + Arccosine, in radians. Арккосинус в радианах. + TRUE when all arguments are true. TRUE, если все аргументы истинны. + Arcsine, in radians. Арксинус в радианах. + Arctangent, in radians. Арктангенс в радианах. + The average of the numbers. Среднее значение чисел. + Joins texts (as the & operator). Соединяет тексты (как операция &). + Cosine of an angle in radians. Косинус угла в радианах. + A date. Дата. + The day of the month of a date. День месяца даты. + Radians to degrees. Радианы в градусы. + e raised to a power. Число e в степени. + The drawing's file name. Имя файла чертежа. + A number as text with that many decimals. Число как текст с заданным числом знаков после запятой. + The hour of a time. Час времени. + One of two values, by a condition. Одно из двух значений, в зависимости от условия. + Rounds down to an integer. Округляет вниз до целого. + The first characters of a text. Первые символы текста. + The number of characters of a text. Число символов в тексте. + Natural logarithm. Натуральный логарифм. + Base-10 logarithm. Десятичный логарифм. + A text in lower case. Текст строчными буквами. + The largest number. Наибольшее число. + Characters from the middle of a text (start = 1 for the first). Символы из середины текста (start = 1 — первый символ). + The smallest number. Наименьшее число. + The minutes of a time. Минуты времени. + The remainder of a division. Остаток от деления. + The month of a date (1 to 12). Месяц даты (от 1 до 12). + The opposite of a logical value. Противоположное логическое значение. + The current date and time (worked out again when the drawing is opened). Текущие дата и время (пересчитываются при открытии чертежа). + TRUE when any argument is true. TRUE, если хотя бы один аргумент истинен. + The number π. Число π. + A number raised to a power (as ^). Число в степени (как ^). + Degrees to radians. Градусы в радианы. + The last characters of a text. Последние символы текста. + Rounds to that many decimals. Округляет до заданного числа знаков после запятой. + Rounds toward zero. Округляет к нулю. + Rounds away from zero. Округляет от нуля. + The name of the current layout ("Model" in model space). Имя текущего листа ("Model" в пространстве модели). + Sine of an angle in radians. Синус угла в радианах. + Square root. Квадратный корень. + Adds the numbers. Сумма чисел. + Tangent of an angle in radians. Тангенс угла в радианах. + A value as text in a format: "0.00", "#,##0", "0%", "dd.mm.yyyy", "hh:mm"... Значение как текст в формате: "0.00", "#,##0", "0%", "dd.mm.yyyy", "hh:mm"... + Today's date (worked out again when the drawing is opened). Сегодняшняя дата (пересчитывается при открытии чертежа). + A text without spaces at its ends and double spaces. Текст без пробелов по краям и двойных пробелов. + A text in capitals. Текст прописными буквами. + The year of a date. Год даты. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 844e7a0b32..00f85a1e39 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1714,3 +1714,18 @@ Current Lineweight Поточна товщина ліній Snap the crosshair to grips Прив’язувати перехрестя до ручок With no command running, the crosshair locks onto a grip of the selected objects under it. Коли команда не виконується, перехрестя притягується до ручки вибраного об’єкта під курсором. + Grid with previews Сітка з ескізами + File not found Файл не знайдено + Making a preview... Створюється ескіз... + Backwards Справа наліво (дзеркально) + Upside down Догори ногами + Top center Угорі по центру + Middle left Посередині ліворуч + Middle center Посередині по центру + Middle right Посередині праворуч + Bottom center Унизу по центру + Text Formulas Формули в тексті + Update Fields Оновити поля + Tab or Enter: insert · Esc: close Tab або Enter: вставити · Esc: закрити + A text that starts with = shows the result of a formula, as in a spreadsheet: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). The formula stays with the text: editing the text edits the formula. Dates and times follow the computer's clock and are worked out again when the drawing is opened (Tools ▸ Update Fields does it at once). Date fields in AutoCAD drawings are updated the same way. Текст, що починається зі знака =, показує результат формули, як в електронній таблиці: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). Формула зберігається разом із текстом: під час редагування тексту редагується формула. Дати й час беруться з годинника комп’ютера та перераховуються під час відкриття креслення (Сервіс ▸ Оновити поля робить це одразу). Поля дати в кресленнях AutoCAD оновлюються так само. + Operators: + - * / ^ (power), % (percent), & (joins texts), = <> < > <= >= (compare). Texts in double quotes. Arguments are separated by commas or semicolons. While typing a formula, a list of functions appears: the arrows choose, Tab or Enter inserts. Операції: + - * / ^ (степінь), % (відсоток), & (з’єднує тексти), = <> < > <= >= (порівняння). Тексти пишуться в подвійних лапках. Аргументи розділяються комами або крапками з комою. Поки ви набираєте формулу, з’являється список функцій: стрілки вибирають, Tab або Enter вставляє. diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 664be9538f..1a56841cb5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -76,6 +76,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.dialog.dsettings", "Drafting Settings...", &[], None), ("ui.dialog.about", "About CADCraft", &["Help", "About CADCraft"], None), ("ui.dialog.commands", "Command Reference", &["Help", "CADCraft Help"], Some("F1")), + ("ui.dialog.formulas", "Text Formulas", &["Help", "Text Formulas"], None), ("ui.toggle.history", "Command History", &["Window", "Command History"], Some("F2")), ("ui.cmdline.lines", "Command Line History Lines", &[], None), ("ui.cmdline.clear", "Clear Command History", &[], None), @@ -361,6 +362,7 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { app.ui.dialog = Some(id.trim_start_matches("ui.dialog.").to_string()); diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 9e2fcda3c6..f00daa3fa9 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -48,6 +48,11 @@ struct State { font: crate::editor_glyphs::EditorFont, /// The text box's caret and selection. edit: crate::bidi_edit::EditState, + /// Formula completion: the highlighted function, and the text it was closed for (Escape). + fx_index: usize, + fx_closed: Option, + /// Where the completion list goes (the caret's bottom, last frame). + fx_at: egui::Pos2, } fn state_id() -> egui::Id { @@ -112,6 +117,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { focus: true, font, edit: crate::bidi_edit::EditState::at(end), + fx_index: 0, + fx_closed: None, + fx_at: pos2(0.0, 0.0), } }); let line = kind == EditorKind::Line; @@ -133,6 +141,27 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } }); } + // Formula completion: the arrows choose a function, Tab or Enter puts it in, Escape closes + // the list (taken before the text box and before Enter finishes one line of text). + let fx = completion(&st); + if let Some((_, list)) = &fx { + let n = list.len().max(1); + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown) { + st.fx_index = (st.fx_index + 1) % n; + } + if i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp) { + st.fx_index = (st.fx_index + n - 1) % n; + } + }); + let pick = ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Tab) || i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + if pick { + let k = st.fx_index; + accept_completion(&mut st, k); + } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + st.fx_closed = Some(st.fmt.text().to_string()); + } + } if line && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { done = Done::Ok; } @@ -205,6 +234,28 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { }); }); }); + if let Some((_, list)) = completion(&st) { + let mut clicked = None; + egui::Area::new(egui::Id::new("mtext_formula_list")).order(egui::Order::Tooltip).fixed_pos(st.fx_at + vec2(0.0, 4.0)).show(ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_min_width(260.0); + for (k, (name, args, _)) in list.iter().enumerate().take(10) { + let r = ui.selectable_label(k == st.fx_index, RichText::new(format!("{name}({args})")).monospace()); + if r.clicked() { + clicked = Some(k); + } + } + if let Some((_, _, what)) = list.get(st.fx_index) { + ui.separator(); + ui.label(RichText::new(crate::i18n::t(what)).small().color(t.text_dim)); + } + ui.label(RichText::new(crate::tl!("Tab or Enter: insert · Esc: close")).small().color(t.text_faint)); + }); + }); + if let Some(k) = clicked { + accept_completion(&mut st, k); + } + } if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { done = Done::Cancel; } @@ -736,6 +787,7 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, px, cadcraft_engine::mtext_edit::MAX_CHARS, ); + st.fx_at = out.caret; let focused = ui.memory(|m| m.has_focus(id)); if !focused && (st.focus || (buf.is_empty() && st.fmt.is_empty())) { ui.memory_mut(|m| m.request_focus(id)); @@ -758,6 +810,50 @@ fn text_box(ui: &mut egui::Ui, st: &mut State, base_h: f64, px: f32, width: f32, } } +/// The formula functions whose names start with the word before the caret, when the text is +/// a formula (`=...`) and the caret is not inside a quoted string: (the word's start, the +/// functions). +fn completion(st: &State) -> Option<(usize, Vec<&'static (&'static str, &'static str, &'static str)>)> { + let text = st.fmt.text(); + if !text.trim_start().starts_with('=') || st.edit.cursor != st.edit.anchor || st.fx_closed.as_deref() == Some(text) { + return None; + } + let chars: Vec = text.chars().collect(); + let at = st.edit.cursor.min(chars.len()); + if chars.get(..at)?.iter().filter(|c| **c == '"').count() % 2 == 1 { + return None; + } + let mut s = at; + while s > 0 && chars.get(s - 1).is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_') { + s -= 1; + } + let word: String = chars.get(s..at)?.iter().collect::().to_ascii_uppercase(); + if word.is_empty() || !word.starts_with(|c: char| c.is_ascii_alphabetic()) { + return None; + } + let list: Vec<_> = cadcraft_engine::textformula::FUNCTIONS.iter().filter(|(n, _, _)| n.starts_with(&word) && *n != word).collect(); + (!list.is_empty()).then_some((s, list)) +} + +/// Put function `k` of the completion list in place of the word before the caret, with its +/// opening parenthesis (and the closing one when it takes no arguments). +fn accept_completion(st: &mut State, k: usize) { + let Some((start, list)) = completion(st) else { return }; + let Some((name, args, _)) = list.get(k).map(|f| **f) else { return }; + let mut chars: Vec = st.fmt.text().chars().collect(); + let at = st.edit.cursor.min(chars.len()); + let ins: Vec = format!("{name}({}", if args.is_empty() { ")" } else { "" }).chars().collect(); + let n = ins.len(); + chars.splice(start..at, ins); + let text: String = chars.iter().collect(); + let typing = st.typing.clone(); + st.fmt.set_text(&text, &typing); + st.edit.cursor = start + n; + st.edit.anchor = st.edit.cursor; + st.typing_at = st.edit.cursor; + st.fx_index = 0; +} + /// The style font's family as an inline font switch would name it (`txt.shx` → `txt`). fn fmt_base(f: &crate::editor_glyphs::EditorFont) -> String { let n = f.font.trim(); From baecf64226b17fd25d11c29a8d487673036eec7b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 12:20:33 +0300 Subject: [PATCH 10/23] b15: clippy fixes, notes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 74 ++++++++++++++++++++++++++++++++ crates/engine/src/cmd/props.rs | 7 +-- crates/engine/src/textformula.rs | 2 +- 3 files changed, 76 insertions(+), 7 deletions(-) diff --git a/WHATS_NEW.md b/WHATS_NEW.md index 8cc9b8cee9..a7555af6f1 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,80 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 23.10.2026 (0.9.0-b15) + +### Русский + +**Палитра «Свойства»: прокрутка длинных списков** +- Выпадающие списки в «Свойствах» (слои, типы линий, стили, выбор объектов по типу и другие), а также список «Загрузить…» типов линий и списки быстрых свойств теперь прокручиваются, если они слишком длинные. Полоса прокрутки видна всегда. + +**Лист при первом открытии вписывается в экран** +- Когда вкладку листа открывают впервые, лист целиком вписывается в окно с небольшим отступом. Раньше для листов в миллиметрах внутри дюймового чертежа (как в «אריה צוק») масштаб получался в 25,4 раза неверным. + +**Стартовая страница: недавние файлы списком или сеткой** +- Рядом с заголовком «Недавние» есть две кнопки: «Список» и «Сетка с эскизами». +- В сетке у каждого файла есть эскиз. Для DWG и DXF берётся эскиз, сохранённый в самом файле (AutoCAD его записывает). Если его нет, CADCraft рисует пространство модели сам. Эскизы маленькие (обычно 10–25 КБ) и хранятся в папке настроек программы. Когда файл меняется, эскиз создаётся заново. +- Если файла по прежнему пути нет, вместо эскиза показан крупный значок: пунктирный лист с красным кругом и вопросительным знаком, а под именем написано «Файл не найден». В режиме списка рядом с таким файлом стоит маленький такой же значок. + +**Текст: выравнивание, «справа налево», «вверх ногами», рамка** +- В «Свойствах» у текста появились «Выравнивание» (все 15 вариантов AutoCAD: Влево, По центру, Вправо, Вписанный, Посередине, По ширине и девять вариантов «Вверху/Посередине/Внизу слева/по центру/справа»), «Справа налево (зеркально)» и «Вверх ногами». +- При смене выравнивания текст остаётся на месте: перемещается только точка, по которой он выровнен. +- У многострочного текста: «Выравнивание» (9 вариантов, текст тоже остаётся на месте), «Поворот» и «Рамка текста». Рамка рисуется вокруг текста и сохраняется так, что AutoCAD её тоже видит. +- Флаги «Справа налево» и «Вверх ногами» читаются из чертежей AutoCAD для каждого текста отдельно, как в AutoCAD. Раньше CADCraft брал их из текстового стиля. Из-за этого тексты в «зеркальных» стилях (в «אריה צוק» это, например, стиль T-NEW) могли показываться зеркально, хотя в AutoCAD они нормальные. Новый текст, как и в AutoCAD, получает эти флаги от своего стиля. +- Выравнивание существующих текстов читалось правильно и раньше: группы 72/73 и точка выравнивания. + +**Окно редактирования текста: иврит и английский в одной строке** +- Убран «второй» текст другим шрифтом, который был виден при выделении. +- Окно редактирования теперь своё, а не стандартное: текст в нём расположен так же, как на чертеже. Каждый абзац получает направление по первой «сильной» букве. Абзац, начинающийся на иврите, читается справа налево, на английском — слева направо. Внутри абзаца английские слова, числа, пробелы и знаки становятся на свои места по правилам Unicode, как в Word, и больше не «перепрыгивают». +- Стрелки ← и → двигают курсор туда, куда они указывают на экране, в любом направлении текста. Ctrl+стрелки переходят по словам, Shift+стрелки выделяют, выделение подсвечивает именно выбранные буквы. Работают Home/End, Ctrl+A, копирование, вырезание, вставка, отмена (Ctrl+Z) и возврат (Ctrl+Y), выделение мышью и двойной щелчок по слову. + +**Формулы в тексте (как в Excel)** +- Текст, который начинается со знака «=», показывает результат формулы: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). +- Формула хранится вместе с текстом. При двойном щелчке открывается формула, а не результат. Если ввести обычный текст без «=», формула удаляется. +- Пока набирается имя функции, рядом с курсором появляется список подходящих функций с описанием. Стрелки выбирают, Tab или Enter вставляют, Esc закрывает. +- Доступные функции: ABS, ACOS, AND, ASIN, ATAN, AVERAGE, CONCAT, COS, DATE, DAY, DEGREES, EXP, FILENAME, FIXED, HOUR, IF, INT, LEFT, LEN, LN, LOG10, LOWER, MAX, MID, MIN, MINUTE, MOD, MONTH, NOT, NOW, OR, PI, POWER, RADIANS, RIGHT, ROUND, ROUNDDOWN, ROUNDUP, SHEET, SIN, SQRT, SUM, TAN, TEXT, TODAY, TRIM, UPPER, YEAR. Операции: + - * / ^ % & и сравнения. Аргументы разделяются запятой или точкой с запятой. Ошибки показываются как в Excel: #DIV/0!, #NAME?, #VALUE!. +- Описание всех функций: «Справка ▸ Формулы в тексте». +- Дата и время берутся из часов Windows и пересчитываются при каждом открытии чертежа. Пересчитать сразу: «Сервис ▸ Обновить поля» (команда UPDATEFIELD). +- Поля даты из AutoCAD тоже работают. На листе «4» в «אריה צוק» дата в правом нижнем углу — это поле AutoCAD «дата» в формате dd.MM.yyyy. Теперь CADCraft его понимает и при открытии показывает сегодняшнюю дату, как AutoCAD. Само поле сохраняется в файле, и в AutoCAD оно продолжит работать. +- Формулы CADCraft записываются в файл так, что AutoCAD увидит их результат как обычный текст. + +### English + +**Properties palette: long lists scroll** +- Drop-down lists in Properties (layers, linetypes, styles, select by type and others), as well as the linetype "Load…" list and the Quick Properties lists, now scroll when they are too long. The scrollbar is always visible. + +**A layout fits the screen the first time it is shown** +- When a layout tab is opened for the first time, the whole sheet fits the window with a small margin. Before, layouts in millimetres inside an inch drawing (as in "אריה צוק") came out 25.4 times off. + +**Start page: recent files as a list or a grid** +- Two buttons next to the "Recent" heading: "List" and "Grid with previews". +- In the grid, each file has a preview. For DWG and DXF it is the preview saved in the file itself (AutoCAD writes one). When a file has none, CADCraft draws its model space. Previews are small (usually 10–25 KB) and kept in the program's settings folder. A changed file gets a new preview. +- If a file is no longer at its path, a large icon shows instead of the preview: a dashed page with a red circle and a question mark, and "File not found" under its name. In the list, such a file has the same small icon next to it. + +**Text: justification, backwards, upside down, frame** +- Text in Properties now has "Justify" (all 15 AutoCAD options: Left, Center, Right, Aligned, Middle, Fit, and the nine Top/Middle/Bottom left/center/right ones), "Backwards" and "Upside down". +- Changing the justification keeps the text in place: only the point it is justified by moves. +- Multiline text: "Justify" (9 options; the text also stays in place), "Rotation" and "Text frame". The frame is drawn around the text and saved so that AutoCAD shows it too. +- Backwards and Upside down are read from AutoCAD drawings for each text, as AutoCAD does. CADCraft used to take them from the text style, which could mirror texts in "backwards" styles (in "אריה צוק", style T-NEW for example) that AutoCAD shows normally. As in AutoCAD, new text takes these settings from its style. +- The justification of existing texts was already read correctly (groups 72/73 and the alignment point). + +**The text editing box: Hebrew and English on one line** +- The "second" text in another font that showed up while selecting is gone. +- The editing box is now CADCraft's own, not the standard one: text in it is laid out the same way as on the drawing. Each paragraph takes its direction from its first strong letter. A paragraph that starts in Hebrew reads right to left, one that starts in English left to right. Within a paragraph, English words, numbers, spaces and punctuation fall into place by the Unicode rules, as in Word, and no longer jump around. +- ← and → move the caret where they point on screen, whatever the text direction. Ctrl+arrows move by words, Shift+arrows select, and a selection highlights exactly the selected letters. Home/End, Ctrl+A, copy, cut, paste, undo (Ctrl+Z) and redo (Ctrl+Y), mouse selection and double-clicking a word all work. + +**Formulas in text (as in Excel)** +- A text that starts with "=" shows the result of a formula: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). +- The formula stays with the text. Double-clicking opens the formula, not the result. Typing plain text without "=" removes the formula. +- While a function name is typed, a list of matching functions with descriptions appears next to the caret. The arrows choose, Tab or Enter inserts, Esc closes. +- Available functions: ABS, ACOS, AND, ASIN, ATAN, AVERAGE, CONCAT, COS, DATE, DAY, DEGREES, EXP, FILENAME, FIXED, HOUR, IF, INT, LEFT, LEN, LN, LOG10, LOWER, MAX, MID, MIN, MINUTE, MOD, MONTH, NOT, NOW, OR, PI, POWER, RADIANS, RIGHT, ROUND, ROUNDDOWN, ROUNDUP, SHEET, SIN, SQRT, SUM, TAN, TEXT, TODAY, TRIM, UPPER, YEAR. Operators: + - * / ^ % & and comparisons. Arguments are separated by commas or semicolons. Errors show as in Excel: #DIV/0!, #NAME?, #VALUE!. +- All functions are described in Help ▸ Text Formulas. +- Dates and times come from the Windows clock and are worked out again every time the drawing is opened. To do it at once: Tools ▸ Update Fields (the UPDATEFIELD command). +- AutoCAD date fields work too. On sheet "4" in "אריה צוק", the date in the bottom right corner is an AutoCAD "date" field in the dd.MM.yyyy format. CADCraft now understands it and shows today's date when the drawing is opened, as AutoCAD does. The field itself is kept in the file and keeps working in AutoCAD. +- CADCraft formulas are saved so that AutoCAD shows their result as ordinary text. + +--- + ## 22.10.2026 (0.9.0-b14) ### Русский diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 7f6c209797..50fe114c01 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -236,12 +236,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { { return Err(bad("properties.set", format!("unknown justification `{j}`"))); } - let style_doc = justify.map(|_| { - let mut x = cadcraft_doc::Drawing::default(); - x.text_styles = d.text_styles.clone(); - x.header = d.header.clone(); - x - }); + let style_doc = justify.map(|_| cadcraft_doc::Drawing { text_styles: d.text_styles.clone(), header: d.header.clone(), ..Default::default() }); let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index c873af9d89..190caf5969 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -649,7 +649,7 @@ fn call(name: &str, a: &[Val], env: &Env) -> R { let n1 = |a: &[Val]| arg(a, 1).and_then(Val::num); let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; let chars = |v: &Val| v.text().chars().collect::>(); - let count = |v: f64| usize::try_from(v.max(0.0).min(1e6) as i64).unwrap_or(0); + let count = |v: f64| if v.is_finite() { usize::try_from(v.clamp(0.0, 1e6) as i64).unwrap_or(0) } else { 0 }; let (y, mo, d, h, mi, s) = env.now; let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; match name { From b5a9b7bd83e1108ff5a6e800444c1977939e62fa Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 12:23:15 +0300 Subject: [PATCH 11/23] b15: clippy Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/props.rs | 46 +++++++++++++++++----------------- crates/render/src/tests.rs | 2 +- crates/ui-egui/src/thumbs.rs | 2 +- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 50fe114c01..482bac0051 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -1161,29 +1161,6 @@ fn run_rename(s: &mut Session, p: &Value) -> Result { ok() } -#[cfg(test)] -mod tests { - use serde_json::json; - - use crate::Session; - - #[test] - fn properties_set_rejects_unloaded_linetype() { - let mut s = Session::new(); - s.execute("linetype", &json!({ "load": "DASHED" })).unwrap(); - s.execute("line", &json!({ "points": [[0, 0], [50, 0]] })).unwrap(); - let h = s.doc().unwrap().model.last().unwrap().handle.hex(); - s.execute("properties.set", &json!({ "handles": [h], "linetype": "DASHED" })).unwrap(); - assert!(s.execute("properties.set", &json!({ "handles": [h], "linetype": "NOPE" })).is_err()); - let lt = |s: &Session| s.doc().unwrap().model.last().unwrap().common.linetype.clone(); - assert_eq!(lt(&s), "DASHED"); - for ok in ["ByBlock", "ByLayer"] { - s.execute("properties.set", &json!({ "handles": [h], "linetype": ok })).unwrap(); - assert_eq!(lt(&s), ok); - } - } -} - /// An MTEXT attachment (1..=9) from a justification code: TL TC TR ML MC MR BL BC BR (or 1..9). fn mtext_attach(j: &str) -> Option { let u = j.trim().to_ascii_uppercase(); @@ -1261,3 +1238,26 @@ fn rejustify_mtext(d: &cadcraft_doc::Drawing, t: &mut cadcraft_doc::MText, attac t.insert.y += shift.y; } } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::Session; + + #[test] + fn properties_set_rejects_unloaded_linetype() { + let mut s = Session::new(); + s.execute("linetype", &json!({ "load": "DASHED" })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [50, 0]] })).unwrap(); + let h = s.doc().unwrap().model.last().unwrap().handle.hex(); + s.execute("properties.set", &json!({ "handles": [h], "linetype": "DASHED" })).unwrap(); + assert!(s.execute("properties.set", &json!({ "handles": [h], "linetype": "NOPE" })).is_err()); + let lt = |s: &Session| s.doc().unwrap().model.last().unwrap().common.linetype.clone(); + assert_eq!(lt(&s), "DASHED"); + for ok in ["ByBlock", "ByLayer"] { + s.execute("properties.set", &json!({ "handles": [h], "linetype": ok })).unwrap(); + assert_eq!(lt(&s), ok); + } + } +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d322ae86c3..ef8a8d8196 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -318,7 +318,7 @@ fn backwards_and_upside_down_mirror_text() { // The text's own flags mirror it (as AutoCAD: the style's only seed new text). let flags = |d: &mut Drawing, b: bool, u: bool| { let h = d.model.iter().next().map(|e| e.handle).unwrap(); - d.modify_entity(h, |e| { + let _ = d.modify_entity(h, |e| { if let EntityKind::Text(t) = &mut e.kind { (t.backwards, t.upside_down) = (b, u); } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 629c6eeeb7..d71b3310c2 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -174,7 +174,7 @@ fn embedded(path: &str) -> Option> { f.seek(SeekFrom::Start(at)).ok()?; let mut sec = Vec::new(); f.take(MAX_PREVIEW_BYTES).read_to_end(&mut sec).ok()?; - return dwg_preview(&sec, at).and_then(|img| finish(img)); + return dwg_preview(&sec, at).and_then(finish); } if lower.ends_with(".dxf") { let mut text = String::new(); From 59289e08a5599489f666782ee7fae58d4f025b97 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 18:58:39 +0300 Subject: [PATCH 12/23] b16: editor select-all/undo/redo/I-beam; formulas in dimensions, leaders, edited mtext (one line) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- Cargo.lock | 2 +- crates/doc/src/entity.rs | 4 + crates/engine/Cargo.toml | 4 - crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/modify2.rs | 27 +- crates/engine/src/textformula.rs | 879 ++-------------------------- crates/engine/tests/text_justify.rs | 40 ++ crates/io/src/dxf_read.rs | 1 + crates/io/src/dxf_write.rs | 1 + crates/render/Cargo.toml | 3 + crates/render/src/dim.rs | 13 + crates/render/src/lib.rs | 1 + crates/render/src/textformula.rs | 854 +++++++++++++++++++++++++++ crates/ui-egui/src/bidi_edit.rs | 8 + crates/ui-egui/src/mtext_editor.rs | 74 ++- 15 files changed, 1055 insertions(+), 858 deletions(-) create mode 100644 crates/render/src/textformula.rs diff --git a/Cargo.lock b/Cargo.lock index c2ee34137f..5f3e1ef322 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,7 +635,6 @@ dependencies = [ "cadcraft-io", "cadcraft-render", "craft-docpath", - "jiff", "log", "rstar", "serde", @@ -698,6 +697,7 @@ dependencies = [ "cadcraft-doc", "cadcraft-fonts", "cadcraft-geom", + "jiff", "lyon_tessellation", "rayon", "serde_json", diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index be37a5eca5..09a1f3219b 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -608,6 +608,10 @@ pub struct DimMarks { /// Inspection frame, label and rate (DIMINSPECT). #[serde(skip_serializing_if = "Option::is_none")] pub inspect: Option, + /// A formula for the dimension text (`=<>/2`, `=TEXT(<>,"0.0")&" mm"`; `<>` is the + /// measurement); `Dimension::text` holds the last result. + #[serde(skip_serializing_if = "Option::is_none")] + pub formula: Option, } impl DimMarks { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index af7f9ad3d9..abf350ffeb 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -24,10 +24,6 @@ log = { workspace = true } # R-tree spatial index for picking, window selection and object snaps (MIT OR Apache-2.0). rstar = { version = "0.12", default-features = false } -# The local date and time for date formulas and fields in text (MIT OR Unlicense). Native only: -# the web build uses UTC. -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-bundle-platform", "tzdb-zoneinfo"] } [dev-dependencies] # Real DXF files for the external reference tests (io is a lower layer). diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 8312f48832..efb8cdb614 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -381,7 +381,7 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option) -> Result) -> usize { crate::grips::adopt_file_dim_text(&mut drawing); // Formulas and fields (dates) worked out for today. - let env = crate::textformula::Env { now: crate::textformula::local_now(), file: file_name(name), sheet: "Model".into() }; + let env = crate::textformula::Env { now: crate::textformula::local_now(), file: file_name(name), sheet: "Model".into(), measured: None }; crate::textformula::refresh(&mut drawing, &env); let notes = drawing.read_notes.clone(); let i = s.open_drawing(drawing, &file_name(name), path); diff --git a/crates/engine/src/cmd/modify2.rs b/crates/engine/src/cmd/modify2.rs index d0b447df2e..24ca6b3fb5 100644 --- a/crates/engine/src/cmd/modify2.rs +++ b/crates/engine/src/cmd/modify2.rs @@ -2222,7 +2222,12 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { } Some(TextEditor { mtext: m, kind: EditorKind::MText, key }) } - EntityKind::MLeader(m) => m.text.clone().map(|mtext| TextEditor { mtext, kind: EditorKind::MText, key }), + EntityKind::MLeader(m) => m.text.clone().map(|mut mtext| { + if let Some(f) = mtext.formula.clone().filter(|f| crate::textformula::is_formula(f)) { + mtext.contents = f; + } + TextEditor { mtext, kind: EditorKind::MText, key } + }), EntityKind::Text(t) => { let mut b = line_box(t); if let Some(f) = t.formula.as_ref().filter(|f| crate::textformula::is_formula(f)) { @@ -2243,7 +2248,11 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option { attach: 5, rotation: g.text_angle, style: d.dim_style(&dm.style).map(|st| st.text_style.clone()).unwrap_or_else(|| dm.style.clone()), - contents: if dm.text.is_empty() { "<>".into() } else { dm.text.clone() }, + contents: match dm.marks.formula.clone().filter(|f| crate::textformula::is_formula(f)) { + Some(f) => f, + None if dm.text.is_empty() => "<>".into(), + None => dm.text.clone(), + }, line_spacing: 1.0, line_spacing_exact: false, columns: None, @@ -2261,10 +2270,13 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { let mut k = curves::entity(s, h)?.kind; // The text as the editor showed it (a formula, else the value): unchanged, it keeps its // formula or AutoCAD field. + let f = |x: &Option| x.clone().filter(|f| crate::textformula::is_formula(f)); let shown = match &k { - EntityKind::Text(t) => t.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| t.value.clone()), - EntityKind::AttDef(a) => a.text.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| a.text.value.clone()), - EntityKind::MText(t) => t.formula.clone().filter(|f| crate::textformula::is_formula(f)).unwrap_or_else(|| t.contents.clone()), + EntityKind::Text(t) => f(&t.formula).unwrap_or_else(|| t.value.clone()), + EntityKind::AttDef(a) => f(&a.text.formula).unwrap_or_else(|| a.text.value.clone()), + EntityKind::MText(t) => f(&t.formula).unwrap_or_else(|| t.contents.clone()), + EntityKind::MLeader(m) => m.text.as_ref().map(|t| f(&t.formula).unwrap_or_else(|| t.contents.clone())).unwrap_or_default(), + EntityKind::Dimension(d) => f(&d.marks.formula).unwrap_or_else(|| d.text.clone()), _ => String::new(), }; let unchanged = shown == text || shown == text.replace('\n', "\\P"); @@ -2282,7 +2294,10 @@ pub(crate) fn set_text(s: &mut Session, h: Handle, text: &str) -> Result<()> { }, _ => return Err(other("Select a text, mtext, attribute definition or dimension.")), } - let env = crate::textformula::env(s); + let mut env = crate::textformula::env(s); + if let EntityKind::Dimension(dm) = &k { + env.measured = crate::textformula::measured(s.doc()?, dm); + } crate::textformula::apply(&mut k, &env, !unchanged); set_kind(s, h, k) } diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index 190caf5969..c565cf8c76 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -1,103 +1,10 @@ -//! Formulas in text, as in a spreadsheet: a text whose value starts with `=` shows the result -//! of the formula (`=2400-2*18`, `=TEXT(TODAY(),"dd.mm.yyyy")`, `=ROUND(PI()*125^2/1000000,3)`). -//! The formula is kept with the text ([`cadcraft_doc::Text::formula`]) and worked out again -//! when the drawing is opened (dates follow the computer's clock) and when it is edited. -//! -//! AutoCAD fields read from drawings (`%<\AcVar date \f "dd.MM.yyyy">%`) are worked out the same -//! way when CADCraft knows them (dates, the file name); others keep the value AutoCAD saved. -//! -//! The functions are listed in [`FUNCTIONS`] (name, arguments, description), which the editor's -//! completion list and Help show. +//! Formulas in text applied to drawings: a text, multiline text, multileader or dimension text +//! whose value is a formula (`=...`, one line) keeps the formula and shows its result; formulas and +//! AutoCAD fields are worked out again when a drawing is opened. The evaluator and the function +//! list are [`cadcraft_render::textformula`]. use cadcraft_doc::{Drawing, EntityKind}; - -/// Longest formula worked out. -const MAX_LEN: usize = 2000; -/// Deepest nesting. -const MAX_DEPTH: usize = 40; -/// Most arguments of one function. -const MAX_ARGS: usize = 255; - -/// The functions: (name, arguments, description). Shown by completion and Help. -pub const FUNCTIONS: &[(&str, &str, &str)] = &[ - ("ABS", "number", "The number without its sign."), - ("ACOS", "number", "Arccosine, in radians."), - ("AND", "logical1, logical2, ...", "TRUE when all arguments are true."), - ("ASIN", "number", "Arcsine, in radians."), - ("ATAN", "number", "Arctangent, in radians."), - ("AVERAGE", "number1, number2, ...", "The average of the numbers."), - ("CONCAT", "text1, text2, ...", "Joins texts (as the & operator)."), - ("COS", "angle", "Cosine of an angle in radians."), - ("DATE", "year, month, day", "A date."), - ("DAY", "date", "The day of the month of a date."), - ("DEGREES", "angle", "Radians to degrees."), - ("EXP", "number", "e raised to a power."), - ("FILENAME", "", "The drawing's file name."), - ("FIXED", "number, decimals", "A number as text with that many decimals."), - ("HOUR", "time", "The hour of a time."), - ("IF", "condition, value_if_true, value_if_false", "One of two values, by a condition."), - ("INT", "number", "Rounds down to an integer."), - ("LEFT", "text, count", "The first characters of a text."), - ("LEN", "text", "The number of characters of a text."), - ("LN", "number", "Natural logarithm."), - ("LOG10", "number", "Base-10 logarithm."), - ("LOWER", "text", "A text in lower case."), - ("MAX", "number1, number2, ...", "The largest number."), - ("MID", "text, start, count", "Characters from the middle of a text (start = 1 for the first)."), - ("MIN", "number1, number2, ...", "The smallest number."), - ("MINUTE", "time", "The minutes of a time."), - ("MOD", "number, divisor", "The remainder of a division."), - ("MONTH", "date", "The month of a date (1 to 12)."), - ("NOT", "logical", "The opposite of a logical value."), - ("NOW", "", "The current date and time (worked out again when the drawing is opened)."), - ("OR", "logical1, logical2, ...", "TRUE when any argument is true."), - ("PI", "", "The number π."), - ("POWER", "number, power", "A number raised to a power (as ^)."), - ("RADIANS", "angle", "Degrees to radians."), - ("RIGHT", "text, count", "The last characters of a text."), - ("ROUND", "number, decimals", "Rounds to that many decimals."), - ("ROUNDDOWN", "number, decimals", "Rounds toward zero."), - ("ROUNDUP", "number, decimals", "Rounds away from zero."), - ("SHEET", "", "The name of the current layout (\"Model\" in model space)."), - ("SIN", "angle", "Sine of an angle in radians."), - ("SQRT", "number", "Square root."), - ("SUM", "number1, number2, ...", "Adds the numbers."), - ("TAN", "angle", "Tangent of an angle in radians."), - ("TEXT", "value, format", "A value as text in a format: \"0.00\", \"#,##0\", \"0%\", \"dd.mm.yyyy\", \"hh:mm\"..."), - ("TODAY", "", "Today's date (worked out again when the drawing is opened)."), - ("TRIM", "text", "A text without spaces at its ends and double spaces."), - ("UPPER", "text", "A text in capitals."), - ("YEAR", "date", "The year of a date."), -]; - -/// What a formula can refer to: the time, the file and the layout. -#[derive(Clone, Debug, PartialEq)] -pub struct Env { - /// Local date and time: year, month, day, hour, minute, second. - pub now: (i32, u32, u32, u32, u32, u32), - pub file: String, - pub sheet: String, -} - -impl Default for Env { - fn default() -> Self { - Env { now: (2000, 1, 1, 0, 0, 0), file: String::new(), sheet: "Model".into() } - } -} - -/// The local date and time now (UTC where the time zone is unknown). -pub fn local_now() -> (i32, u32, u32, u32, u32, u32) { - #[cfg(not(target_arch = "wasm32"))] - { - let z = jiff::Zoned::now(); - let clamp = |v: i8| u32::try_from(v).unwrap_or(0); - (i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second())) - } - #[cfg(target_arch = "wasm32")] - { - (2000, 1, 1, 0, 0, 0) - } -} +pub use cadcraft_render::textformula::{Env, FUNCTIONS, evaluate, has_fields, is_formula, local_now}; /// The environment of a session's drawing. pub fn env(s: &crate::Session) -> Env { @@ -109,696 +16,34 @@ pub fn env(s: &crate::Session) -> Env { None => st.title.clone(), }) .unwrap_or_default(); - Env { now: local_now(), file, sheet: s.space().tab_name().to_string() } -} - -/// Whether `text` is a formula (starts with `=`, after spaces). -pub fn is_formula(text: &str) -> bool { - text.trim_start().starts_with('=') && text.trim().len() > 1 -} - -/// Whether `text` holds AutoCAD field codes. -pub fn has_fields(text: &str) -> bool { - text.contains("%<\\") -} - -/// Work out a formula (`=...`) or the fields of a field template: the text to show, or `None` -/// for a field CADCraft doesn't know (the saved value stays). -pub fn evaluate(formula: &str, env: &Env) -> Option { - if is_formula(formula) { - return Some(match eval(formula.trim_start().trim_start_matches('='), env) { - Ok(v) => v.show(), - Err(e) => e.to_string(), - }); - } - if has_fields(formula) { - return fields(formula, env); - } - None -} - -// ---------- values ---------- - -#[derive(Clone, Debug, PartialEq)] -enum Val { - Num(f64), - /// A date and time as a serial number (days since 30 December 1899, as spreadsheets). - Date(f64), - Text(String), - Bool(bool), -} - -/// Formula errors, shown as spreadsheets show them. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Err { - /// An unknown function or name. - Name, - /// A wrong kind of value. - Value, - Div0, - /// A number out of range (square root of -1...). - Num, - /// The formula can't be read. - Syntax, -} - -impl std::fmt::Display for Err { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - Err::Name => "#NAME?", - Err::Value => "#VALUE!", - Err::Div0 => "#DIV/0!", - Err::Num => "#NUM!", - Err::Syntax => "#ERROR!", - }) - } -} - -type R = std::result::Result; - -impl Val { - fn num(&self) -> std::result::Result { - match self { - Val::Num(v) | Val::Date(v) => Ok(*v), - Val::Bool(b) => Ok(f64::from(u8::from(*b))), - Val::Text(t) => t.trim().replace(',', ".").parse::().map_err(|_| Err::Value), - } - } - fn text(&self) -> String { - self.show() - } - fn truth(&self) -> std::result::Result { - match self { - Val::Bool(b) => Ok(*b), - Val::Text(t) if t.eq_ignore_ascii_case("true") => Ok(true), - Val::Text(t) if t.eq_ignore_ascii_case("false") => Ok(false), - v => Ok(v.num()? != 0.0), - } - } - /// As the text shows it: numbers without trailing zeros (at most 10 decimals), dates as - /// dd.mm.yyyy (with the time when it has one), TRUE/FALSE. - fn show(&self) -> String { - match self { - Val::Num(v) => general(*v), - Val::Date(d) => { - if d.fract().abs() < 1e-9 { - format_date(*d, "dd.mm.yyyy") - } else { - format_date(*d, "dd.mm.yyyy hh:mm") - } - } - Val::Text(t) => t.clone(), - Val::Bool(b) => if *b { "TRUE" } else { "FALSE" }.into(), - } - } -} - -/// A number with at most 10 decimals, trailing zeros dropped. -fn general(v: f64) -> String { - if !v.is_finite() { - return Err::Num.to_string(); - } - if v.abs() >= 1e15 || (v != 0.0 && v.abs() < 1e-10) { - return format!("{v:e}"); - } - let s = format!("{v:.10}"); - let s = s.trim_end_matches('0').trim_end_matches('.'); - if s == "-0" { "0".into() } else { s.into() } -} - -// ---------- dates ---------- - -/// Days from 1970-01-01 of a civil date (proleptic Gregorian). -fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { - let y = if m <= 2 { y - 1 } else { y }; - let era = y.div_euclid(400); - let yoe = y - era * 400; - let mp = (m + 9) % 12; - let doy = (153 * mp + 2) / 5 + d - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - era * 146_097 + doe - 719_468 -} - -fn civil_from_days(z: i64) -> (i64, i64, i64) { - let z = z + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - (if m <= 2 { y + 1 } else { y }, m, d) -} - -/// The spreadsheet serial of 1970-01-01. -const EPOCH_SERIAL: i64 = 25_569; - -fn serial(y: i64, m: i64, d: i64) -> f64 { - // Months beyond 1..12 roll into the next or previous years, as spreadsheets do. - let (y, m) = (y + (m - 1).div_euclid(12), (m - 1).rem_euclid(12) + 1); - (days_from_civil(y, m, 1) + d - 1 + EPOCH_SERIAL) as f64 -} - -/// (year, month, day, hour, minute, second) of a serial. -fn parts(s: f64) -> (i64, i64, i64, i64, i64, i64) { - let days = s.floor(); - let secs = ((s - days) * 86_400.0).round() as i64; - let (y, m, d) = civil_from_days(days as i64 - EPOCH_SERIAL); - (y, m, d, secs / 3600 % 24, secs / 60 % 60, secs % 60) -} - -const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; - -/// A date in a spreadsheet date format: d dd ddd? m mm mmm mmmm yy yyyy h hh mm (minutes after -/// h) ss; other characters as they are. -fn format_date(s: f64, fmt: &str) -> String { - let (y, mo, d, h, mi, se) = parts(s); - let chars: Vec = fmt.chars().collect(); - let mut out = String::new(); - let mut i = 0; - let mut after_hour = false; - while let Some(&c) = chars.get(i) { - let run = chars.get(i..).unwrap_or_default().iter().take_while(|x| x.eq_ignore_ascii_case(&c)).count(); - match c.to_ascii_lowercase() { - 'y' => { - out += &if run <= 2 { format!("{:02}", y.rem_euclid(100)) } else { format!("{y:04}") }; - after_hour = false; - } - 'm' if after_hour && run <= 2 => { - out += &if run == 1 { mi.to_string() } else { format!("{mi:02}") }; - after_hour = false; - } - 'm' => { - let name = MONTHS.get(usize::try_from(mo - 1).unwrap_or(0)).copied().unwrap_or(""); - out += &match run { - 1 => mo.to_string(), - 2 => format!("{mo:02}"), - 3 => name.chars().take(3).collect(), - _ => name.into(), - }; - } - 'd' => { - out += &if run == 1 { d.to_string() } else { format!("{d:02}") }; - after_hour = false; - } - 'h' => { - out += &if run == 1 { h.to_string() } else { format!("{h:02}") }; - after_hour = true; - } - 's' => { - out += &if run == 1 { se.to_string() } else { format!("{se:02}") }; - } - _ => { - out.extend(std::iter::repeat_n(c, run)); - } - } - i += run; - } - out -} - -/// A number in a spreadsheet number format: `0`, `0.00`, `#,##0.00`, `0%`, `0.0E+0`-less. -/// Text before and after the digits stays (`"L=" 0.0` → `L=12.5`, quotes dropped). -fn format_number(v: f64, fmt: &str) -> String { - let percent = fmt.contains('%'); - let v = if percent { v * 100.0 } else { v }; - let start = fmt.find(['0', '#']); - let end = fmt.rfind(['0', '#']).map(|e| e + 1); - let (Some(a), Some(b)) = (start, end) else { return fmt.replace('"', "") }; - let core = fmt.get(a..b).unwrap_or("0"); - let decimals = core.split_once('.').map_or(0, |(_, f)| f.chars().filter(|c| *c == '0' || *c == '#').count()); - let grouped = core.split_once('.').map_or(core, |(i, _)| i).contains(','); - let mut s = format!("{:.*}", decimals.min(15), v.abs()); - if grouped { - let (int, frac) = s.split_once('.').map_or((s.clone(), String::new()), |(i, f)| (i.to_string(), format!(".{f}"))); - let mut g = String::new(); - for (k, ch) in int.chars().enumerate() { - if k > 0 && (int.len() - k) % 3 == 0 { - g.push(','); - } - g.push(ch); - } - s = g + &frac; - } - let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') { "-" } else { "" }; - let pre = fmt.get(..a).unwrap_or("").replace('"', ""); - let post = fmt.get(b..).unwrap_or("").replace('"', ""); - format!("{pre}{sign}{s}{post}") -} - -fn looks_like_date_format(f: &str) -> bool { - let l = f.to_ascii_lowercase(); - l.contains('y') || l.contains('d') || l.contains("mm") && !l.contains('0') || l.contains('h') -} - -// ---------- parsing and evaluation ---------- - -#[derive(Clone, Debug, PartialEq)] -enum Tok { - Num(f64), - Str(String), - Name(String), - Op(&'static str), - LParen, - RParen, - Comma, -} - -fn lex(s: &str) -> std::result::Result, Err> { - let c: Vec = s.chars().collect(); - let mut out = Vec::new(); - let mut i = 0; - while let Some(&ch) = c.get(i) { - match ch { - ' ' | '\t' => i += 1, - '0'..='9' | '.' => { - let st = i; - while c.get(i).is_some_and(|x| x.is_ascii_digit() || *x == '.') { - i += 1; - } - if c.get(i).is_some_and(|x| *x == 'e' || *x == 'E') && c.get(i + 1).is_some_and(|x| x.is_ascii_digit() || *x == '-' || *x == '+') { - i += 2; - while c.get(i).is_some_and(char::is_ascii_digit) { - i += 1; - } - } - let t: String = c.get(st..i).unwrap_or_default().iter().collect(); - out.push(Tok::Num(t.parse().map_err(|_| Err::Syntax)?)); - } - '"' => { - i += 1; - let mut t = String::new(); - loop { - match c.get(i) { - None => return Err(Err::Syntax), - Some('"') if c.get(i + 1) == Some(&'"') => { - t.push('"'); - i += 2; - } - Some('"') => { - i += 1; - break; - } - Some(x) => { - t.push(*x); - i += 1; - } - } - } - out.push(Tok::Str(t)); - } - '(' => { - out.push(Tok::LParen); - i += 1; - } - ')' => { - out.push(Tok::RParen); - i += 1; - } - // `;` separates arguments too (spreadsheets in languages with a decimal comma). - ',' | ';' => { - out.push(Tok::Comma); - i += 1; - } - '<' | '>' => { - let two: String = c.get(i..i + 2).unwrap_or_default().iter().collect(); - let op = match two.as_str() { - "<=" => "<=", - ">=" => ">=", - "<>" => "<>", - _ if ch == '<' => "<", - _ => ">", - }; - i += op.len(); - out.push(Tok::Op(op)); - } - '+' | '-' | '*' | '/' | '^' | '&' | '=' | '%' => { - out.push(Tok::Op(match ch { - '+' => "+", - '-' => "-", - '*' => "*", - '/' => "/", - '^' => "^", - '&' => "&", - '=' => "=", - _ => "%", - })); - i += 1; - } - x if x.is_alphabetic() || x == '_' => { - let st = i; - while c.get(i).is_some_and(|y| y.is_alphanumeric() || *y == '_' || *y == '.') { - i += 1; - } - out.push(Tok::Name(c.get(st..i).unwrap_or_default().iter().collect::().to_ascii_uppercase())); - } - _ => return Err(Err::Syntax), - } - if out.len() > MAX_LEN { - return Err(Err::Syntax); - } - } - Ok(out) -} - -struct P<'a> { - t: Vec, - i: usize, - depth: usize, - env: &'a Env, -} - -fn eval(src: &str, env: &Env) -> R { - if src.len() > MAX_LEN { - return Err(Err::Syntax); - } - let mut p = P { t: lex(src)?, i: 0, depth: 0, env }; - let v = p.compare()?; - if p.i < p.t.len() { - return Err(Err::Syntax); - } - Ok(v) -} - -impl P<'_> { - fn peek(&self) -> Option<&Tok> { - self.t.get(self.i) - } - fn is_op(&self, ops: &[&str]) -> Option<&'static str> { - match self.peek() { - Some(Tok::Op(o)) if ops.contains(o) => Some(o), - _ => None, - } - } - fn compare(&mut self) -> R { - let a = self.concat()?; - if let Some(op) = self.is_op(&["=", "<>", "<", ">", "<=", ">="]) { - self.i += 1; - let b = self.concat()?; - let ord = match (&a, &b) { - (Val::Text(x), Val::Text(y)) => x.to_lowercase().cmp(&y.to_lowercase()), - _ => a.num()?.partial_cmp(&b.num()?).ok_or(Err::Num)?, - }; - use std::cmp::Ordering::*; - return Ok(Val::Bool(match op { - "=" => ord == Equal, - "<>" => ord != Equal, - "<" => ord == Less, - ">" => ord == Greater, - "<=" => ord != Greater, - _ => ord != Less, - })); - } - Ok(a) - } - fn concat(&mut self) -> R { - let mut a = self.sum()?; - while self.is_op(&["&"]).is_some() { - self.i += 1; - let b = self.sum()?; - a = Val::Text(a.text() + &b.text()); - } - Ok(a) - } - fn sum(&mut self) -> R { - let mut a = self.product()?; - while let Some(op) = self.is_op(&["+", "-"]) { - self.i += 1; - let b = self.product()?; - let v = if op == "+" { a.num()? + b.num()? } else { a.num()? - b.num()? }; - // A date plus or minus days is a date; the difference of two dates is a number. - a = match (&a, &b) { - (Val::Date(_), Val::Date(_)) => Val::Num(v), - (Val::Date(_), _) | (_, Val::Date(_)) => Val::Date(v), - _ => Val::Num(v), - }; - } - Ok(a) - } - fn product(&mut self) -> R { - let mut a = self.power()?; - while let Some(op) = self.is_op(&["*", "/"]) { - self.i += 1; - let b = self.power()?; - let (x, y) = (a.num()?, b.num()?); - a = Val::Num(if op == "*" { - x * y - } else { - if y == 0.0 { - return Err(Err::Div0); - } - x / y - }); - } - Ok(a) - } - fn power(&mut self) -> R { - let a = self.unary()?; - if self.is_op(&["^"]).is_some() { - self.i += 1; - let b = self.power()?; - let v = a.num()?.powf(b.num()?); - return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; - } - Ok(a) - } - fn unary(&mut self) -> R { - if let Some(op) = self.is_op(&["-", "+"]) { - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Err::Syntax); - } - self.i += 1; - let v = self.unary()?; - self.depth -= 1; - return Ok(Val::Num(if op == "-" { -v.num()? } else { v.num()? })); - } - let mut v = self.atom()?; - while self.is_op(&["%"]).is_some() { - self.i += 1; - v = Val::Num(v.num()? / 100.0); - } - Ok(v) - } - fn atom(&mut self) -> R { - self.depth += 1; - if self.depth > MAX_DEPTH { - return Err(Err::Syntax); - } - let tok = self.peek().cloned(); - self.i += 1; - let r = match tok { - Some(Tok::Num(v)) => Ok(Val::Num(v)), - Some(Tok::Str(s)) => Ok(Val::Text(s)), - Some(Tok::LParen) => { - let v = self.compare()?; - if self.peek() != Some(&Tok::RParen) { - return Err(Err::Syntax); - } - self.i += 1; - Ok(v) - } - Some(Tok::Name(n)) if n == "TRUE" => Ok(Val::Bool(true)), - Some(Tok::Name(n)) if n == "FALSE" => Ok(Val::Bool(false)), - Some(Tok::Name(n)) => { - if self.peek() != Some(&Tok::LParen) { - return Err(Err::Name); - } - self.i += 1; - let mut args = Vec::new(); - if self.peek() != Some(&Tok::RParen) { - loop { - args.push(self.compare()?); - if args.len() > MAX_ARGS { - return Err(Err::Value); - } - match self.peek() { - Some(Tok::Comma) => self.i += 1, - Some(Tok::RParen) => break, - _ => return Err(Err::Syntax), - } - } - } - self.i += 1; - call(&n, &args, self.env) - } - _ => Err(Err::Syntax), - }; - self.depth -= 1; - r - } -} - -fn round_to(x: f64, n: f64, how: fn(f64) -> f64) -> f64 { - let k = 10f64.powi(n.clamp(-15.0, 15.0) as i32); - how(x * k) / k -} - -fn arg(a: &[Val], i: usize) -> std::result::Result<&Val, Err> { - a.get(i).ok_or(Err::Value) -} - -fn nums(a: &[Val]) -> std::result::Result, Err> { - a.iter().map(Val::num).collect() + Env { now: local_now(), file, sheet: s.space().tab_name().to_string(), measured: None } } -fn call(name: &str, a: &[Val], env: &Env) -> R { - let n0 = |a: &[Val]| arg(a, 0).and_then(Val::num); - let n1 = |a: &[Val]| arg(a, 1).and_then(Val::num); - let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; - let chars = |v: &Val| v.text().chars().collect::>(); - let count = |v: f64| if v.is_finite() { usize::try_from(v.clamp(0.0, 1e6) as i64).unwrap_or(0) } else { 0 }; - let (y, mo, d, h, mi, s) = env.now; - let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; - match name { - "ABS" => Ok(Val::Num(n0(a)?.abs())), - "ACOS" => checked(n0(a)?.acos()), - "ASIN" => checked(n0(a)?.asin()), - "ATAN" => Ok(Val::Num(n0(a)?.atan())), - "AND" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().all(|b| *b))), - "OR" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().any(|b| *b))), - "NOT" => Ok(Val::Bool(!arg(a, 0)?.truth()?)), - "AVERAGE" => { - let v = nums(a)?; - if v.is_empty() { Err(Err::Div0) } else { Ok(Val::Num(v.iter().sum::() / v.len() as f64)) } - } - "SUM" => Ok(Val::Num(nums(a)?.iter().sum())), - "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()) - .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), - "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))) - .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), - "CONCAT" => Ok(Val::Text(a.iter().map(Val::text).collect())), - "COS" => Ok(Val::Num(n0(a)?.cos())), - "SIN" => Ok(Val::Num(n0(a)?.sin())), - "TAN" => checked(n0(a)?.tan()), - "DEGREES" => Ok(Val::Num(n0(a)?.to_degrees())), - "RADIANS" => Ok(Val::Num(n0(a)?.to_radians())), - "EXP" => checked(n0(a)?.exp()), - "LN" => checked(n0(a)?.ln()), - "LOG10" => checked(n0(a)?.log10()), - "SQRT" => checked(n0(a)?.sqrt()), - "POWER" => checked(n0(a)?.powf(n1(a)?)), - "MOD" => { - let (x, m) = (n0(a)?, n1(a)?); - if m == 0.0 { Err(Err::Div0) } else { Ok(Val::Num(x - m * (x / m).floor())) } - } - "INT" => Ok(Val::Num(n0(a)?.floor())), - "PI" => Ok(Val::Num(std::f64::consts::PI)), - "ROUND" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::round))), - "ROUNDUP" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), |x| if x < 0.0 { x.floor() } else { x.ceil() }))), - "ROUNDDOWN" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::trunc))), - "FIXED" => Ok(Val::Text(format!("{:.*}", count(n1(a).unwrap_or(2.0)).min(15), n0(a)?))), - "IF" => { - let c = arg(a, 0)?.truth()?; - Ok(if c { a.get(1).cloned().unwrap_or(Val::Bool(true)) } else { a.get(2).cloned().unwrap_or(Val::Bool(false)) }) - } - "LEN" => Ok(Val::Num(chars(arg(a, 0)?).len() as f64)), - "UPPER" => Ok(Val::Text(arg(a, 0)?.text().to_uppercase())), - "LOWER" => Ok(Val::Text(arg(a, 0)?.text().to_lowercase())), - "TRIM" => Ok(Val::Text(arg(a, 0)?.text().split_whitespace().collect::>().join(" "))), - "LEFT" => Ok(Val::Text(chars(arg(a, 0)?).into_iter().take(count(n1(a).unwrap_or(1.0))).collect())), - "RIGHT" => { - let c = chars(arg(a, 0)?); - let k = count(n1(a).unwrap_or(1.0)).min(c.len()); - Ok(Val::Text(c.get(c.len() - k..).unwrap_or_default().iter().collect())) - } - "MID" => { - let c = chars(arg(a, 0)?); - let st = count(n1(a)? - 1.0); - let k = count(arg(a, 2)?.num()?); - Ok(Val::Text(c.into_iter().skip(st).take(k).collect())) - } - "TEXT" => { - let v = arg(a, 0)?; - let f = arg(a, 1)?.text(); - Ok(Val::Text(match v { - Val::Date(x) => format_date(*x, &f), - _ if looks_like_date_format(&f) => format_date(v.num()?, &f), - Val::Text(t) if t.trim().parse::().is_err() => t.clone(), - _ => format_number(v.num()?, &f), - })) - } - "TODAY" => Ok(Val::Date(now.floor())), - "NOW" => Ok(Val::Date(now)), - "DATE" => { - let (yy, mm, dd) = (n0(a)?, n1(a)?, arg(a, 2)?.num()?); - if !(yy.is_finite() && mm.is_finite() && dd.is_finite()) || yy.abs() > 9999.0 || mm.abs() > 12_000.0 || dd.abs() > 1e6 { - return Err(Err::Num); - } - Ok(Val::Date(serial(yy as i64, mm as i64, dd as i64))) - } - "YEAR" => Ok(Val::Num(parts(n0(a)?).0 as f64)), - "MONTH" => Ok(Val::Num(parts(n0(a)?).1 as f64)), - "DAY" => Ok(Val::Num(parts(n0(a)?).2 as f64)), - "HOUR" => Ok(Val::Num(parts(n0(a)?).3 as f64)), - "MINUTE" => Ok(Val::Num(parts(n0(a)?).4 as f64)), - "FILENAME" => Ok(Val::Text(env.file.clone())), - "SHEET" => Ok(Val::Text(env.sheet.clone())), - _ => Err(Err::Name), - } -} - -// ---------- AutoCAD fields ---------- - -/// The fields of a field template worked out (`%<\AcVar date \f "dd.MM.yyyy">%` and the file -/// name ones); `None` when one is a field CADCraft doesn't know. -fn fields(template: &str, env: &Env) -> Option { - let mut out = String::new(); - let mut rest = template; - let mut guard = 0; - while let Some(a) = rest.find("%<") { - guard += 1; - if guard > 64 { - return None; - } - out.push_str(rest.get(..a)?); - let tail = rest.get(a + 2..)?; - let b = tail.find(">%")?; - out.push_str(&field(tail.get(..b)?, env)?); - rest = tail.get(b + 2..)?; - } - out.push_str(rest); - Some(out) -} - -/// One field code (between `%<` and `>%`). -fn field(code: &str, env: &Env) -> Option { - let code = code.trim(); - let body = code.strip_prefix("\\AcVar")?.trim(); - let (name, fmt) = match body.split_once("\\f") { - Some((n, f)) => (n.trim(), Some(f.trim().trim_matches('"'))), - None => (body, None), - }; - let (y, mo, d, h, mi, s) = env.now; - let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; - match name.to_ascii_lowercase().as_str() { - // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. - "date" => Some(format_date(now, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), - "filename" => Some(env.file.clone()), - _ => None, - } -} +// ---------- applying to a drawing ---------- -/// A .NET date format (`dd.MM.yyyy HH:mm`) as a spreadsheet one (`dd.mm.yyyy hh:mm`). -fn net_to_sheet(f: &str) -> String { - // .NET: M month, m minute; spreadsheet: m month, m after h minute. Minutes become "mm" after - // an hour, months stay "mm" otherwise. - f.replace("HH", "hh").replace('H', "h").replace("MMMM", "mmmm").replace("MMM", "mmm").replace("MM", "mm").replace('M', "m") +/// The measurement a dimension shows (for `<>` in its formula). +pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { + let plain = cadcraft_doc::Dimension { text: String::new(), block: None, marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, ..dm.clone() }; + let v = cadcraft_render::dimension_in(d, &plain).value; + let s: String = v.chars().skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.').take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')).collect(); + s.replace(' ', "").replace(',', ".").parse().ok() } -// ---------- applying to a drawing ---------- - -/// A text object's formula, worked out into what it shows: a text value starting with `=` -/// becomes its formula; a formula's result becomes the value. `edited` is a value just typed: -/// typing over an AutoCAD field turns it into plain text, typing a value without `=` drops the -/// formula. +/// A text object's formula, worked out into what it shows: a value that is a formula (one line +/// starting with `=`) becomes its formula; a formula's result becomes the value. `edited` is a +/// value just typed: typing over an AutoCAD field turns it into plain text, typing a value that +/// is not a formula drops the formula. Text, attribute definitions, multiline text, +/// multileader text and dimension text (whose `<>` is its measurement, `env.measured`). pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { let (value, formula): (&mut String, &mut Option) = match kind { EntityKind::Text(t) => (&mut t.value, &mut t.formula), EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula), EntityKind::MText(t) => (&mut t.contents, &mut t.formula), + EntityKind::MLeader(m) => match &mut m.text { + Some(t) => (&mut t.contents, &mut t.formula), + None => return, + }, + EntityKind::Dimension(d) => (&mut d.text, &mut d.marks.formula), _ => return, }; if edited { @@ -823,6 +68,8 @@ fn has_formula(k: &EntityKind) -> bool { EntityKind::Text(t) => t.formula.is_some(), EntityKind::AttDef(a) => a.text.formula.is_some(), EntityKind::MText(t) => t.formula.is_some(), + EntityKind::MLeader(m) => m.text.as_ref().is_some_and(|t| t.formula.is_some()), + EntityKind::Dimension(d) => d.marks.formula.is_some(), _ => false, } } @@ -831,10 +78,20 @@ fn has_formula(k: &EntityKind) -> bool { /// layouts and block definitions. The number of texts worked out. pub fn refresh(d: &mut Drawing, env: &Env) -> usize { let mut n = 0; + // Dimensions' measurements first (they need the whole drawing). + let mut measures: std::collections::HashMap> = std::collections::HashMap::new(); + for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())) { + if let EntityKind::Dimension(dm) = &e.kind + && dm.marks.formula.is_some() + { + measures.insert(e.handle, measured(d, dm)); + } + } let fix = |store: &mut cadcraft_doc::EntityStore, n: &mut usize| { let hs: Vec = store.iter().filter(|e| has_formula(&e.kind)).map(|e| e.handle).collect(); for h in hs { - store.modify(h, |e| apply(&mut e.kind, env, false)); + let env = Env { measured: measures.get(&h).copied().flatten(), ..env.clone() }; + store.modify(h, |e| apply(&mut e.kind, &env, false)); *n += 1; } }; @@ -851,67 +108,3 @@ pub fn refresh(d: &mut Drawing, env: &Env) -> usize { n } -#[cfg(test)] -mod tests { - use super::*; - - fn env() -> Env { - Env { now: (2026, 10, 23, 14, 5, 9), file: "plan.dwg".into(), sheet: "4".into() } - } - - fn ev(f: &str) -> String { - evaluate(f, &env()).unwrap_or_default() - } - - #[test] - fn arithmetic_and_functions() { - assert_eq!(ev("=2400-2*18"), "2364"); - assert_eq!(ev("=(1+2)^2/4"), "2.25"); - assert_eq!(ev("=ROUND(PI()*2,3)"), "6.283"); - assert_eq!(ev("=SUM(1,2,3)&\" mm\""), "6 mm"); - assert_eq!(ev("=IF(5>3,\"big\",\"small\")"), "big"); - assert_eq!(ev("=MAX(4;9;2)"), "9"); - assert_eq!(ev("=TEXT(1234.5,\"#,##0.00\")"), "1,234.50"); - assert_eq!(ev("=TEXT(0.25,\"0%\")"), "25%"); - assert_eq!(ev("=UPPER(LEFT(\"abc\",2))"), "AB"); - assert_eq!(ev("=MID(\"Hello\",2,3)"), "ell"); - assert_eq!(ev("=50%*10"), "5"); - } - - #[test] - fn dates_follow_the_clock() { - assert_eq!(ev("=TODAY()"), "23.10.2026"); - assert_eq!(ev("=TEXT(TODAY(),\"yyyy-mm-dd\")"), "2026-10-23"); - assert_eq!(ev("=TEXT(NOW(),\"hh:mm\")"), "14:05"); - assert_eq!(ev("=TODAY()+10"), "02.11.2026"); - assert_eq!(ev("=YEAR(DATE(2025,14,1))"), "2026"); - assert_eq!(ev("=TEXT(DATE(2026,1,5),\"d mmm yyyy\")"), "5 Jan 2026"); - assert_eq!(ev("%<\\AcVar date \\f \"dd.MM.yyyy\">%"), "23.10.2026"); - assert_eq!(ev("Date: %<\\AcVar Date \\f \"yyyy-MM-dd HH:mm\">%"), "Date: 2026-10-23 14:05"); - assert_eq!(ev("=FILENAME()&\" / \"&SHEET()"), "plan.dwg / 4"); - assert_eq!(evaluate("%<\\AcObjProp Object(%<\\_ObjId 1>%).Area>%", &env()), None, "unknown fields keep their value"); - } - - #[test] - fn errors_show_as_in_spreadsheets_and_never_panic() { - assert_eq!(ev("=1/0"), "#DIV/0!"); - assert_eq!(ev("=FOO(1)"), "#NAME?"); - assert_eq!(ev("=\"a\"*2"), "#VALUE!"); - assert_eq!(ev("=SQRT(-1)"), "#NUM!"); - assert_eq!(ev("=(1+"), "#ERROR!"); - for f in [ - "=", - "==", - "=(((((", - &format!("={}", "-".repeat(500)), - &format!("={}1", "(".repeat(100)), - "=\"", - "=MID(\"a\",-5,1e300)", - "=DATE(1e300,1,1)", - ] { - let _ = evaluate(f, &env()); - } - assert!(!is_formula("plain")); - assert!(!is_formula("=")); - } -} diff --git a/crates/engine/tests/text_justify.rs b/crates/engine/tests/text_justify.rs index 1fb2042940..2112561e53 100644 --- a/crates/engine/tests/text_justify.rs +++ b/crates/engine/tests/text_justify.rs @@ -81,3 +81,43 @@ fn text_formulas_show_their_result_and_edit_as_formulas() { assert!(year.len() == 4 && year.starts_with("20"), "{year}"); assert_eq!(s.execute("updatefield", &json!({})).unwrap()["updated"], 1); } + +#[test] +fn formulas_work_when_editing_multiline_text_dimensions_and_leaders() { + let mut s = Session::new(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "abc" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": m, "text": "{\\fArial|b0;=1200+350*2}" })).unwrap(); + let mt = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.clone()), + _ => None, + }); + let mt = mt.unwrap(); + assert!(cadcraft_fonts::plain_mtext(&mt.contents).contains("1900"), "{}", mt.contents); + // Two lines: not a formula. + s.execute("textedit", &json!({ "handle": m, "text": "=1+1\\Psecond" })).unwrap(); + let mt = s.doc().unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::MText(t) => Some(t.clone()), + _ => None, + }); + assert!(mt.unwrap().formula.is_none()); +} + +#[test] +fn dimension_and_leader_text_take_formulas() { + let mut s = Session::new(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!(dm.marks.formula.as_deref(), Some("=<>/2")); + assert_eq!(dm.text, "625"); + assert_eq!(cadcraft_render::dimension_in(d, dm).value, "625"); + let r = s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap(); + let m = r["handle"].as_str().unwrap().to_string(); + s.execute("textedit", &json!({ "handle": m, "text": "=2*21" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::MLeader(ml) = &d.model.iter().find(|e| e.handle.hex() == m).unwrap().kind else { panic!() }; + assert_eq!(ml.text.as_ref().unwrap().contents, "42"); +} diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index a55601a54e..6109a75951 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -1077,6 +1077,7 @@ fn entity_extras(kind: &str, tags: &[Tag], h: Handle, k: &mut EntityKind, rx: &m dm.p15 = center; } dm.marks = crate::dxf_ext::read_marks(tags); + dm.marks.formula = crate::dxf_ext::formula(tags); // Group 52: the extension lines' angle relative to the dimension line (DIMEDIT Oblique). let base = match dm.kind { DimKind::Linear { rotation } => Some(rotation), diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 80755bff88..f5e450d4ab 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -886,6 +886,7 @@ fn entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx } } dim_xdata(w, dm, cx); + formula_xdata(w, dm.marks.formula.as_deref()); } EntityKind::Table(t) => { // Tables without a generated block (none expected) are not written. diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index d62af23b9d..5a7578907d 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,9 @@ lyon_tessellation = { workspace = true } # Display lists of large drawings are built on all cores (not on the web, which has no threads). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } +# The local date and time for date formulas and fields in text (MIT OR Unlicense); the web build +# uses UTC. +jiff = { version = "0.2", default-features = false, features = ["std", "tz-system", "tzdb-bundle-platform", "tzdb-zoneinfo"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index 0d83346892..7de0222d1b 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -417,7 +417,20 @@ fn post(template: &str, meas: &str) -> String { if template.contains("<>") { template.replace("<>", meas) } else { format!("{meas}{template}") } } +/// The first number in a formatted measurement (`R12.5` → 12.5, `1 250,5` → 1250.5). +fn measured_number(base: &str) -> Option { + let s: String = base.chars().skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.').take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')).collect(); + s.replace(' ', "").replace(',', ".").parse().ok() +} + fn apply_override(base: &str, d: &Dimension) -> String { + // A formula: worked out with `<>` as the measurement (shown as the dimension shows it). + if let Some(f) = d.marks.formula.as_deref().filter(|f| crate::textformula::is_formula(f)) { + let env = crate::textformula::Env { measured: measured_number(base), now: crate::textformula::local_now(), ..Default::default() }; + if let Some(v) = crate::textformula::evaluate(f, &env) { + return v; + } + } if d.text.is_empty() { base.to_string() } else if d.text.trim().is_empty() { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2a9371ff06..8131c6da53 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -21,6 +21,7 @@ mod plotstyle; mod point; pub mod raster; mod text; +pub mod textformula; mod tolerance; pub mod units; mod wide; diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs new file mode 100644 index 0000000000..c2f2ccbb43 --- /dev/null +++ b/crates/render/src/textformula.rs @@ -0,0 +1,854 @@ +//! Formulas in text, as in a spreadsheet (the evaluator; the engine applies it to drawings): a text whose value starts with `=` shows the result +//! of the formula (`=2400-2*18`, `=TEXT(TODAY(),"dd.mm.yyyy")`, `=ROUND(PI()*125^2/1000000,3)`). +//! The formula is kept with the text ([`cadcraft_doc::Text::formula`]) and worked out again +//! when the drawing is opened (dates follow the computer's clock) and when it is edited. +//! +//! AutoCAD fields read from drawings (`%<\AcVar date \f "dd.MM.yyyy">%`) are worked out the same +//! way when CADCraft knows them (dates, the file name); others keep the value AutoCAD saved. +//! +//! The functions are listed in [`FUNCTIONS`] (name, arguments, description), which the editor's +//! completion list and Help show. + + +/// Longest formula worked out. +const MAX_LEN: usize = 2000; +/// Deepest nesting. +const MAX_DEPTH: usize = 40; +/// Most arguments of one function. +const MAX_ARGS: usize = 255; + +/// The functions: (name, arguments, description). Shown by completion and Help. +pub const FUNCTIONS: &[(&str, &str, &str)] = &[ + ("ABS", "number", "The number without its sign."), + ("ACOS", "number", "Arccosine, in radians."), + ("AND", "logical1, logical2, ...", "TRUE when all arguments are true."), + ("ASIN", "number", "Arcsine, in radians."), + ("ATAN", "number", "Arctangent, in radians."), + ("AVERAGE", "number1, number2, ...", "The average of the numbers."), + ("CONCAT", "text1, text2, ...", "Joins texts (as the & operator)."), + ("COS", "angle", "Cosine of an angle in radians."), + ("DATE", "year, month, day", "A date."), + ("DAY", "date", "The day of the month of a date."), + ("DEGREES", "angle", "Radians to degrees."), + ("EXP", "number", "e raised to a power."), + ("FILENAME", "", "The drawing's file name."), + ("FIXED", "number, decimals", "A number as text with that many decimals."), + ("HOUR", "time", "The hour of a time."), + ("IF", "condition, value_if_true, value_if_false", "One of two values, by a condition."), + ("INT", "number", "Rounds down to an integer."), + ("LEFT", "text, count", "The first characters of a text."), + ("LEN", "text", "The number of characters of a text."), + ("LN", "number", "Natural logarithm."), + ("LOG10", "number", "Base-10 logarithm."), + ("LOWER", "text", "A text in lower case."), + ("MAX", "number1, number2, ...", "The largest number."), + ("MID", "text, start, count", "Characters from the middle of a text (start = 1 for the first)."), + ("MIN", "number1, number2, ...", "The smallest number."), + ("MINUTE", "time", "The minutes of a time."), + ("MOD", "number, divisor", "The remainder of a division."), + ("MONTH", "date", "The month of a date (1 to 12)."), + ("NOT", "logical", "The opposite of a logical value."), + ("NOW", "", "The current date and time (worked out again when the drawing is opened)."), + ("OR", "logical1, logical2, ...", "TRUE when any argument is true."), + ("PI", "", "The number π."), + ("POWER", "number, power", "A number raised to a power (as ^)."), + ("RADIANS", "angle", "Degrees to radians."), + ("RIGHT", "text, count", "The last characters of a text."), + ("ROUND", "number, decimals", "Rounds to that many decimals."), + ("ROUNDDOWN", "number, decimals", "Rounds toward zero."), + ("ROUNDUP", "number, decimals", "Rounds away from zero."), + ("SHEET", "", "The name of the current layout (\"Model\" in model space)."), + ("SIN", "angle", "Sine of an angle in radians."), + ("SQRT", "number", "Square root."), + ("SUM", "number1, number2, ...", "Adds the numbers."), + ("TAN", "angle", "Tangent of an angle in radians."), + ("TEXT", "value, format", "A value as text in a format: \"0.00\", \"#,##0\", \"0%\", \"dd.mm.yyyy\", \"hh:mm\"..."), + ("TODAY", "", "Today's date (worked out again when the drawing is opened)."), + ("TRIM", "text", "A text without spaces at its ends and double spaces."), + ("UPPER", "text", "A text in capitals."), + ("YEAR", "date", "The year of a date."), +]; + +/// What a formula can refer to: the time, the file and the layout. +#[derive(Clone, Debug, PartialEq)] +pub struct Env { + /// Local date and time: year, month, day, hour, minute, second. + pub now: (i32, u32, u32, u32, u32, u32), + pub file: String, + pub sheet: String, + /// A dimension's measurement, which `<>` stands for in its formula. + pub measured: Option, +} + +impl Default for Env { + fn default() -> Self { + Env { now: (2000, 1, 1, 0, 0, 0), file: String::new(), sheet: "Model".into(), measured: None } + } +} + +/// The local date and time now (UTC where the time zone is unknown). +pub fn local_now() -> (i32, u32, u32, u32, u32, u32) { + #[cfg(not(target_arch = "wasm32"))] + { + let z = jiff::Zoned::now(); + let clamp = |v: i8| u32::try_from(v).unwrap_or(0); + (i32::from(z.year()), clamp(z.month()), clamp(z.day()), clamp(z.hour()), clamp(z.minute()), clamp(z.second())) + } + #[cfg(target_arch = "wasm32")] + { + (2000, 1, 1, 0, 0, 0) + } +} + +/// Whether `text` is a formula: one line starting with `=` (after spaces). +pub fn is_formula(text: &str) -> bool { + let t = text.trim(); + t.starts_with('=') && t.len() > 1 && !t.contains(['\n', '\r']) +} + +/// Whether `text` holds AutoCAD field codes. +pub fn has_fields(text: &str) -> bool { + text.contains("%<\\") +} + +/// Work out a formula (`=...`) or the fields of a field template: the text to show, or `None` +/// for a field CADCraft doesn't know (the saved value stays). +pub fn evaluate(formula: &str, env: &Env) -> Option { + if is_formula(formula) { + return Some(match eval(formula.trim_start().trim_start_matches('='), env) { + Ok(v) => v.show(), + Err(e) => e.to_string(), + }); + } + if has_fields(formula) { + return fields(formula, env); + } + None +} + +// ---------- values ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Val { + Num(f64), + /// A date and time as a serial number (days since 30 December 1899, as spreadsheets). + Date(f64), + Text(String), + Bool(bool), +} + +/// Formula errors, shown as spreadsheets show them. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Err { + /// An unknown function or name. + Name, + /// A wrong kind of value. + Value, + Div0, + /// A number out of range (square root of -1...). + Num, + /// The formula can't be read. + Syntax, +} + +impl std::fmt::Display for Err { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Err::Name => "#NAME?", + Err::Value => "#VALUE!", + Err::Div0 => "#DIV/0!", + Err::Num => "#NUM!", + Err::Syntax => "#ERROR!", + }) + } +} + +type R = std::result::Result; + +impl Val { + fn num(&self) -> std::result::Result { + match self { + Val::Num(v) | Val::Date(v) => Ok(*v), + Val::Bool(b) => Ok(f64::from(u8::from(*b))), + Val::Text(t) => t.trim().replace(',', ".").parse::().map_err(|_| Err::Value), + } + } + fn text(&self) -> String { + self.show() + } + fn truth(&self) -> std::result::Result { + match self { + Val::Bool(b) => Ok(*b), + Val::Text(t) if t.eq_ignore_ascii_case("true") => Ok(true), + Val::Text(t) if t.eq_ignore_ascii_case("false") => Ok(false), + v => Ok(v.num()? != 0.0), + } + } + /// As the text shows it: numbers without trailing zeros (at most 10 decimals), dates as + /// dd.mm.yyyy (with the time when it has one), TRUE/FALSE. + fn show(&self) -> String { + match self { + Val::Num(v) => general(*v), + Val::Date(d) => { + if d.fract().abs() < 1e-9 { + format_date(*d, "dd.mm.yyyy") + } else { + format_date(*d, "dd.mm.yyyy hh:mm") + } + } + Val::Text(t) => t.clone(), + Val::Bool(b) => if *b { "TRUE" } else { "FALSE" }.into(), + } + } +} + +/// A number with at most 10 decimals, trailing zeros dropped. +fn general(v: f64) -> String { + if !v.is_finite() { + return Err::Num.to_string(); + } + if v.abs() >= 1e15 || (v != 0.0 && v.abs() < 1e-10) { + return format!("{v:e}"); + } + let s = format!("{v:.10}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +// ---------- dates ---------- + +/// Days from 1970-01-01 of a civil date (proleptic Gregorian). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (m + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +fn civil_from_days(z: i64) -> (i64, i64, i64) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// The spreadsheet serial of 1970-01-01. +const EPOCH_SERIAL: i64 = 25_569; + +fn serial(y: i64, m: i64, d: i64) -> f64 { + // Months beyond 1..12 roll into the next or previous years, as spreadsheets do. + let (y, m) = (y + (m - 1).div_euclid(12), (m - 1).rem_euclid(12) + 1); + (days_from_civil(y, m, 1) + d - 1 + EPOCH_SERIAL) as f64 +} + +/// (year, month, day, hour, minute, second) of a serial. +fn parts(s: f64) -> (i64, i64, i64, i64, i64, i64) { + let days = s.floor(); + let secs = ((s - days) * 86_400.0).round() as i64; + let (y, m, d) = civil_from_days(days as i64 - EPOCH_SERIAL); + (y, m, d, secs / 3600 % 24, secs / 60 % 60, secs % 60) +} + +const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +/// A date in a spreadsheet date format: d dd ddd? m mm mmm mmmm yy yyyy h hh mm (minutes after +/// h) ss; other characters as they are. +fn format_date(s: f64, fmt: &str) -> String { + let (y, mo, d, h, mi, se) = parts(s); + let chars: Vec = fmt.chars().collect(); + let mut out = String::new(); + let mut i = 0; + let mut after_hour = false; + while let Some(&c) = chars.get(i) { + let run = chars.get(i..).unwrap_or_default().iter().take_while(|x| x.eq_ignore_ascii_case(&c)).count(); + match c.to_ascii_lowercase() { + 'y' => { + out += &if run <= 2 { format!("{:02}", y.rem_euclid(100)) } else { format!("{y:04}") }; + after_hour = false; + } + 'm' if after_hour && run <= 2 => { + out += &if run == 1 { mi.to_string() } else { format!("{mi:02}") }; + after_hour = false; + } + 'm' => { + let name = MONTHS.get(usize::try_from(mo - 1).unwrap_or(0)).copied().unwrap_or(""); + out += &match run { + 1 => mo.to_string(), + 2 => format!("{mo:02}"), + 3 => name.chars().take(3).collect(), + _ => name.into(), + }; + } + 'd' => { + out += &if run == 1 { d.to_string() } else { format!("{d:02}") }; + after_hour = false; + } + 'h' => { + out += &if run == 1 { h.to_string() } else { format!("{h:02}") }; + after_hour = true; + } + 's' => { + out += &if run == 1 { se.to_string() } else { format!("{se:02}") }; + } + _ => { + out.extend(std::iter::repeat_n(c, run)); + } + } + i += run; + } + out +} + +/// A number in a spreadsheet number format: `0`, `0.00`, `#,##0.00`, `0%`, `0.0E+0`-less. +/// Text before and after the digits stays (`"L=" 0.0` → `L=12.5`, quotes dropped). +fn format_number(v: f64, fmt: &str) -> String { + let percent = fmt.contains('%'); + let v = if percent { v * 100.0 } else { v }; + let start = fmt.find(['0', '#']); + let end = fmt.rfind(['0', '#']).map(|e| e + 1); + let (Some(a), Some(b)) = (start, end) else { return fmt.replace('"', "") }; + let core = fmt.get(a..b).unwrap_or("0"); + let decimals = core.split_once('.').map_or(0, |(_, f)| f.chars().filter(|c| *c == '0' || *c == '#').count()); + let grouped = core.split_once('.').map_or(core, |(i, _)| i).contains(','); + let mut s = format!("{:.*}", decimals.min(15), v.abs()); + if grouped { + let (int, frac) = s.split_once('.').map_or((s.clone(), String::new()), |(i, f)| (i.to_string(), format!(".{f}"))); + let mut g = String::new(); + for (k, ch) in int.chars().enumerate() { + if k > 0 && (int.len() - k) % 3 == 0 { + g.push(','); + } + g.push(ch); + } + s = g + &frac; + } + let sign = if v < 0.0 && s.chars().any(|c| c.is_ascii_digit() && c != '0') { "-" } else { "" }; + let pre = fmt.get(..a).unwrap_or("").replace('"', ""); + let post = fmt.get(b..).unwrap_or("").replace('"', ""); + format!("{pre}{sign}{s}{post}") +} + +fn looks_like_date_format(f: &str) -> bool { + let l = f.to_ascii_lowercase(); + l.contains('y') || l.contains('d') || l.contains("mm") && !l.contains('0') || l.contains('h') +} + +// ---------- parsing and evaluation ---------- + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Num(f64), + Str(String), + Name(String), + Op(&'static str), + LParen, + RParen, + Comma, +} + +fn lex(s: &str) -> std::result::Result, Err> { + let c: Vec = s.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while let Some(&ch) = c.get(i) { + match ch { + ' ' | '\t' => i += 1, + '0'..='9' | '.' => { + let st = i; + while c.get(i).is_some_and(|x| x.is_ascii_digit() || *x == '.') { + i += 1; + } + if c.get(i).is_some_and(|x| *x == 'e' || *x == 'E') && c.get(i + 1).is_some_and(|x| x.is_ascii_digit() || *x == '-' || *x == '+') { + i += 2; + while c.get(i).is_some_and(char::is_ascii_digit) { + i += 1; + } + } + let t: String = c.get(st..i).unwrap_or_default().iter().collect(); + out.push(Tok::Num(t.parse().map_err(|_| Err::Syntax)?)); + } + '"' => { + i += 1; + let mut t = String::new(); + loop { + match c.get(i) { + None => return Err(Err::Syntax), + Some('"') if c.get(i + 1) == Some(&'"') => { + t.push('"'); + i += 2; + } + Some('"') => { + i += 1; + break; + } + Some(x) => { + t.push(*x); + i += 1; + } + } + } + out.push(Tok::Str(t)); + } + '(' => { + out.push(Tok::LParen); + i += 1; + } + ')' => { + out.push(Tok::RParen); + i += 1; + } + // `;` separates arguments too (spreadsheets in languages with a decimal comma). + ',' | ';' => { + out.push(Tok::Comma); + i += 1; + } + '<' | '>' => { + let two: String = c.get(i..i + 2).unwrap_or_default().iter().collect(); + let op = match two.as_str() { + "<=" => "<=", + ">=" => ">=", + "<>" => "<>", + _ if ch == '<' => "<", + _ => ">", + }; + i += op.len(); + out.push(Tok::Op(op)); + } + '+' | '-' | '*' | '/' | '^' | '&' | '=' | '%' => { + out.push(Tok::Op(match ch { + '+' => "+", + '-' => "-", + '*' => "*", + '/' => "/", + '^' => "^", + '&' => "&", + '=' => "=", + _ => "%", + })); + i += 1; + } + x if x.is_alphabetic() || x == '_' => { + let st = i; + while c.get(i).is_some_and(|y| y.is_alphanumeric() || *y == '_' || *y == '.') { + i += 1; + } + out.push(Tok::Name(c.get(st..i).unwrap_or_default().iter().collect::().to_ascii_uppercase())); + } + _ => return Err(Err::Syntax), + } + if out.len() > MAX_LEN { + return Err(Err::Syntax); + } + } + Ok(out) +} + +struct P<'a> { + t: Vec, + i: usize, + depth: usize, + env: &'a Env, +} + +fn eval(src: &str, env: &Env) -> R { + if src.len() > MAX_LEN { + return Err(Err::Syntax); + } + let mut p = P { t: lex(src)?, i: 0, depth: 0, env }; + let v = p.compare()?; + if p.i < p.t.len() { + return Err(Err::Syntax); + } + Ok(v) +} + +impl P<'_> { + fn peek(&self) -> Option<&Tok> { + self.t.get(self.i) + } + fn is_op(&self, ops: &[&str]) -> Option<&'static str> { + match self.peek() { + Some(Tok::Op(o)) if ops.contains(o) => Some(o), + _ => None, + } + } + fn compare(&mut self) -> R { + let a = self.concat()?; + if let Some(op) = self.is_op(&["=", "<>", "<", ">", "<=", ">="]) { + self.i += 1; + let b = self.concat()?; + let ord = match (&a, &b) { + (Val::Text(x), Val::Text(y)) => x.to_lowercase().cmp(&y.to_lowercase()), + _ => a.num()?.partial_cmp(&b.num()?).ok_or(Err::Num)?, + }; + use std::cmp::Ordering::*; + return Ok(Val::Bool(match op { + "=" => ord == Equal, + "<>" => ord != Equal, + "<" => ord == Less, + ">" => ord == Greater, + "<=" => ord != Greater, + _ => ord != Less, + })); + } + Ok(a) + } + fn concat(&mut self) -> R { + let mut a = self.sum()?; + while self.is_op(&["&"]).is_some() { + self.i += 1; + let b = self.sum()?; + a = Val::Text(a.text() + &b.text()); + } + Ok(a) + } + fn sum(&mut self) -> R { + let mut a = self.product()?; + while let Some(op) = self.is_op(&["+", "-"]) { + self.i += 1; + let b = self.product()?; + let v = if op == "+" { a.num()? + b.num()? } else { a.num()? - b.num()? }; + // A date plus or minus days is a date; the difference of two dates is a number. + a = match (&a, &b) { + (Val::Date(_), Val::Date(_)) => Val::Num(v), + (Val::Date(_), _) | (_, Val::Date(_)) => Val::Date(v), + _ => Val::Num(v), + }; + } + Ok(a) + } + fn product(&mut self) -> R { + let mut a = self.power()?; + while let Some(op) = self.is_op(&["*", "/"]) { + self.i += 1; + let b = self.power()?; + let (x, y) = (a.num()?, b.num()?); + a = Val::Num(if op == "*" { + x * y + } else { + if y == 0.0 { + return Err(Err::Div0); + } + x / y + }); + } + Ok(a) + } + fn power(&mut self) -> R { + let a = self.unary()?; + if self.is_op(&["^"]).is_some() { + self.i += 1; + let b = self.power()?; + let v = a.num()?.powf(b.num()?); + return if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + } + Ok(a) + } + fn unary(&mut self) -> R { + if let Some(op) = self.is_op(&["-", "+"]) { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + self.i += 1; + let v = self.unary()?; + self.depth -= 1; + return Ok(Val::Num(if op == "-" { -v.num()? } else { v.num()? })); + } + let mut v = self.atom()?; + while self.is_op(&["%"]).is_some() { + self.i += 1; + v = Val::Num(v.num()? / 100.0); + } + Ok(v) + } + fn atom(&mut self) -> R { + self.depth += 1; + if self.depth > MAX_DEPTH { + return Err(Err::Syntax); + } + let tok = self.peek().cloned(); + self.i += 1; + let r = match tok { + Some(Tok::Num(v)) => Ok(Val::Num(v)), + Some(Tok::Str(s)) => Ok(Val::Text(s)), + Some(Tok::LParen) => { + let v = self.compare()?; + if self.peek() != Some(&Tok::RParen) { + return Err(Err::Syntax); + } + self.i += 1; + Ok(v) + } + // In a dimension's formula, `<>` is its measurement. + Some(Tok::Op("<>")) if self.env.measured.is_some() => Ok(Val::Num(self.env.measured.unwrap_or(0.0))), + Some(Tok::Name(n)) if n == "TRUE" => Ok(Val::Bool(true)), + Some(Tok::Name(n)) if n == "FALSE" => Ok(Val::Bool(false)), + Some(Tok::Name(n)) => { + if self.peek() != Some(&Tok::LParen) { + return Err(Err::Name); + } + self.i += 1; + let mut args = Vec::new(); + if self.peek() != Some(&Tok::RParen) { + loop { + args.push(self.compare()?); + if args.len() > MAX_ARGS { + return Err(Err::Value); + } + match self.peek() { + Some(Tok::Comma) => self.i += 1, + Some(Tok::RParen) => break, + _ => return Err(Err::Syntax), + } + } + } + self.i += 1; + call(&n, &args, self.env) + } + _ => Err(Err::Syntax), + }; + self.depth -= 1; + r + } +} + +fn round_to(x: f64, n: f64, how: fn(f64) -> f64) -> f64 { + let k = 10f64.powi(n.clamp(-15.0, 15.0) as i32); + how(x * k) / k +} + +fn arg(a: &[Val], i: usize) -> std::result::Result<&Val, Err> { + a.get(i).ok_or(Err::Value) +} + +fn nums(a: &[Val]) -> std::result::Result, Err> { + a.iter().map(Val::num).collect() +} + +fn call(name: &str, a: &[Val], env: &Env) -> R { + let n0 = |a: &[Val]| arg(a, 0).and_then(Val::num); + let n1 = |a: &[Val]| arg(a, 1).and_then(Val::num); + let checked = |v: f64| if v.is_finite() { Ok(Val::Num(v)) } else { Err(Err::Num) }; + let chars = |v: &Val| v.text().chars().collect::>(); + let count = |v: f64| if v.is_finite() { usize::try_from(v.clamp(0.0, 1e6) as i64).unwrap_or(0) } else { 0 }; + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name { + "ABS" => Ok(Val::Num(n0(a)?.abs())), + "ACOS" => checked(n0(a)?.acos()), + "ASIN" => checked(n0(a)?.asin()), + "ATAN" => Ok(Val::Num(n0(a)?.atan())), + "AND" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().all(|b| *b))), + "OR" => Ok(Val::Bool(a.iter().map(Val::truth).collect::, _>>()?.iter().any(|b| *b))), + "NOT" => Ok(Val::Bool(!arg(a, 0)?.truth()?)), + "AVERAGE" => { + let v = nums(a)?; + if v.is_empty() { Err(Err::Div0) } else { Ok(Val::Num(v.iter().sum::() / v.len() as f64)) } + } + "SUM" => Ok(Val::Num(nums(a)?.iter().sum())), + "MIN" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::INFINITY, f64::min)).clone()) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "MAX" => Ok(Val::Num(nums(a)?.into_iter().fold(f64::NEG_INFINITY, f64::max))) + .and_then(|v| if v.num()?.is_finite() { Ok(v) } else { Ok(Val::Num(0.0)) }), + "CONCAT" => Ok(Val::Text(a.iter().map(Val::text).collect())), + "COS" => Ok(Val::Num(n0(a)?.cos())), + "SIN" => Ok(Val::Num(n0(a)?.sin())), + "TAN" => checked(n0(a)?.tan()), + "DEGREES" => Ok(Val::Num(n0(a)?.to_degrees())), + "RADIANS" => Ok(Val::Num(n0(a)?.to_radians())), + "EXP" => checked(n0(a)?.exp()), + "LN" => checked(n0(a)?.ln()), + "LOG10" => checked(n0(a)?.log10()), + "SQRT" => checked(n0(a)?.sqrt()), + "POWER" => checked(n0(a)?.powf(n1(a)?)), + "MOD" => { + let (x, m) = (n0(a)?, n1(a)?); + if m == 0.0 { Err(Err::Div0) } else { Ok(Val::Num(x - m * (x / m).floor())) } + } + "INT" => Ok(Val::Num(n0(a)?.floor())), + "PI" => Ok(Val::Num(std::f64::consts::PI)), + "ROUND" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::round))), + "ROUNDUP" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), |x| if x < 0.0 { x.floor() } else { x.ceil() }))), + "ROUNDDOWN" => Ok(Val::Num(round_to(n0(a)?, n1(a).unwrap_or(0.0), f64::trunc))), + "FIXED" => Ok(Val::Text(format!("{:.*}", count(n1(a).unwrap_or(2.0)).min(15), n0(a)?))), + "IF" => { + let c = arg(a, 0)?.truth()?; + Ok(if c { a.get(1).cloned().unwrap_or(Val::Bool(true)) } else { a.get(2).cloned().unwrap_or(Val::Bool(false)) }) + } + "LEN" => Ok(Val::Num(chars(arg(a, 0)?).len() as f64)), + "UPPER" => Ok(Val::Text(arg(a, 0)?.text().to_uppercase())), + "LOWER" => Ok(Val::Text(arg(a, 0)?.text().to_lowercase())), + "TRIM" => Ok(Val::Text(arg(a, 0)?.text().split_whitespace().collect::>().join(" "))), + "LEFT" => Ok(Val::Text(chars(arg(a, 0)?).into_iter().take(count(n1(a).unwrap_or(1.0))).collect())), + "RIGHT" => { + let c = chars(arg(a, 0)?); + let k = count(n1(a).unwrap_or(1.0)).min(c.len()); + Ok(Val::Text(c.get(c.len() - k..).unwrap_or_default().iter().collect())) + } + "MID" => { + let c = chars(arg(a, 0)?); + let st = count(n1(a)? - 1.0); + let k = count(arg(a, 2)?.num()?); + Ok(Val::Text(c.into_iter().skip(st).take(k).collect())) + } + "TEXT" => { + let v = arg(a, 0)?; + let f = arg(a, 1)?.text(); + Ok(Val::Text(match v { + Val::Date(x) => format_date(*x, &f), + _ if looks_like_date_format(&f) => format_date(v.num()?, &f), + Val::Text(t) if t.trim().parse::().is_err() => t.clone(), + _ => format_number(v.num()?, &f), + })) + } + "TODAY" => Ok(Val::Date(now.floor())), + "NOW" => Ok(Val::Date(now)), + "DATE" => { + let (yy, mm, dd) = (n0(a)?, n1(a)?, arg(a, 2)?.num()?); + if !(yy.is_finite() && mm.is_finite() && dd.is_finite()) || yy.abs() > 9999.0 || mm.abs() > 12_000.0 || dd.abs() > 1e6 { + return Err(Err::Num); + } + Ok(Val::Date(serial(yy as i64, mm as i64, dd as i64))) + } + "YEAR" => Ok(Val::Num(parts(n0(a)?).0 as f64)), + "MONTH" => Ok(Val::Num(parts(n0(a)?).1 as f64)), + "DAY" => Ok(Val::Num(parts(n0(a)?).2 as f64)), + "HOUR" => Ok(Val::Num(parts(n0(a)?).3 as f64)), + "MINUTE" => Ok(Val::Num(parts(n0(a)?).4 as f64)), + "FILENAME" => Ok(Val::Text(env.file.clone())), + "SHEET" => Ok(Val::Text(env.sheet.clone())), + _ => Err(Err::Name), + } +} + +// ---------- AutoCAD fields ---------- + +/// The fields of a field template worked out (`%<\AcVar date \f "dd.MM.yyyy">%` and the file +/// name ones); `None` when one is a field CADCraft doesn't know. +fn fields(template: &str, env: &Env) -> Option { + let mut out = String::new(); + let mut rest = template; + let mut guard = 0; + while let Some(a) = rest.find("%<") { + guard += 1; + if guard > 64 { + return None; + } + out.push_str(rest.get(..a)?); + let tail = rest.get(a + 2..)?; + let b = tail.find(">%")?; + out.push_str(&field(tail.get(..b)?, env)?); + rest = tail.get(b + 2..)?; + } + out.push_str(rest); + Some(out) +} + +/// One field code (between `%<` and `>%`). +fn field(code: &str, env: &Env) -> Option { + let code = code.trim(); + let body = code.strip_prefix("\\AcVar")?.trim(); + let (name, fmt) = match body.split_once("\\f") { + Some((n, f)) => (n.trim(), Some(f.trim().trim_matches('"'))), + None => (body, None), + }; + let (y, mo, d, h, mi, s) = env.now; + let now = serial(i64::from(y), i64::from(mo), i64::from(d)) + (f64::from(h) * 3600.0 + f64::from(mi) * 60.0 + f64::from(s)) / 86_400.0; + match name.to_ascii_lowercase().as_str() { + // AutoCAD's date formats are .NET's: MM month, mm minutes, HH hours. + "date" => Some(format_date(now, &net_to_sheet(fmt.unwrap_or("dd.MM.yyyy")))), + "filename" => Some(env.file.clone()), + _ => None, + } +} + +/// A .NET date format (`dd.MM.yyyy HH:mm`) as a spreadsheet one (`dd.mm.yyyy hh:mm`). +fn net_to_sheet(f: &str) -> String { + // .NET: M month, m minute; spreadsheet: m month, m after h minute. Minutes become "mm" after + // an hour, months stay "mm" otherwise. + f.replace("HH", "hh").replace('H', "h").replace("MMMM", "mmmm").replace("MMM", "mmm").replace("MM", "mm").replace('M', "m") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env() -> Env { + Env { now: (2026, 10, 23, 14, 5, 9), file: "plan.dwg".into(), sheet: "4".into(), measured: None } + } + + fn ev(f: &str) -> String { + evaluate(f, &env()).unwrap_or_default() + } + + #[test] + fn arithmetic_and_functions() { + assert_eq!(ev("=2400-2*18"), "2364"); + assert_eq!(ev("=(1+2)^2/4"), "2.25"); + assert_eq!(ev("=ROUND(PI()*2,3)"), "6.283"); + assert_eq!(ev("=SUM(1,2,3)&\" mm\""), "6 mm"); + assert_eq!(ev("=IF(5>3,\"big\",\"small\")"), "big"); + assert_eq!(ev("=MAX(4;9;2)"), "9"); + assert_eq!(ev("=TEXT(1234.5,\"#,##0.00\")"), "1,234.50"); + assert_eq!(ev("=TEXT(0.25,\"0%\")"), "25%"); + assert_eq!(ev("=UPPER(LEFT(\"abc\",2))"), "AB"); + assert_eq!(ev("=MID(\"Hello\",2,3)"), "ell"); + assert_eq!(ev("=50%*10"), "5"); + } + + #[test] + fn dates_follow_the_clock() { + assert_eq!(ev("=TODAY()"), "23.10.2026"); + assert_eq!(ev("=TEXT(TODAY(),\"yyyy-mm-dd\")"), "2026-10-23"); + assert_eq!(ev("=TEXT(NOW(),\"hh:mm\")"), "14:05"); + assert_eq!(ev("=TODAY()+10"), "02.11.2026"); + assert_eq!(ev("=YEAR(DATE(2025,14,1))"), "2026"); + assert_eq!(ev("=TEXT(DATE(2026,1,5),\"d mmm yyyy\")"), "5 Jan 2026"); + assert_eq!(ev("%<\\AcVar date \\f \"dd.MM.yyyy\">%"), "23.10.2026"); + assert_eq!(ev("Date: %<\\AcVar Date \\f \"yyyy-MM-dd HH:mm\">%"), "Date: 2026-10-23 14:05"); + assert_eq!(ev("=FILENAME()&\" / \"&SHEET()"), "plan.dwg / 4"); + assert_eq!(evaluate("%<\\AcObjProp Object(%<\\_ObjId 1>%).Area>%", &env()), None, "unknown fields keep their value"); + } + + #[test] + fn a_dimension_formula_uses_its_measurement() { + let e = Env { measured: Some(1250.0), ..env() }; + assert_eq!(evaluate("=<>/2", &e).as_deref(), Some("625")); + assert_eq!(evaluate("=TEXT(<>+30,\"0.0\")&\" mm\"", &e).as_deref(), Some("1280.0 mm")); + assert_eq!(evaluate("=IF(<><>0,1,2)", &e).as_deref(), Some("1")); + assert!(!is_formula("=1+1\nsecond line")); + } + + #[test] + fn errors_show_as_in_spreadsheets_and_never_panic() { + assert_eq!(ev("=1/0"), "#DIV/0!"); + assert_eq!(ev("=FOO(1)"), "#NAME?"); + assert_eq!(ev("=\"a\"*2"), "#VALUE!"); + assert_eq!(ev("=SQRT(-1)"), "#NUM!"); + assert_eq!(ev("=(1+"), "#ERROR!"); + for f in [ + "=", + "==", + "=(((((", + &format!("={}", "-".repeat(500)), + &format!("={}1", "(".repeat(100)), + "=\"", + "=MID(\"a\",-5,1e300)", + "=DATE(1e300,1,1)", + ] { + let _ = evaluate(f, &env()); + } + assert!(!is_formula("plain")); + assert!(!is_formula("=")); + } +} diff --git a/crates/ui-egui/src/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs index e672b68e08..ae73db9ca9 100644 --- a/crates/ui-egui/src/bidi_edit.rs +++ b/crates/ui-egui/src/bidi_edit.rs @@ -45,6 +45,10 @@ impl EditState { pub fn at(i: usize) -> Self { EditState { cursor: i, anchor: i, ..Default::default() } } + /// Everything selected, the caret at the end. + pub fn all(len: usize) -> Self { + EditState { cursor: len, anchor: 0, ..Default::default() } + } /// The selection, low to high. pub fn range(&self) -> (usize, usize) { (self.cursor.min(self.anchor), self.cursor.max(self.anchor)) @@ -329,6 +333,10 @@ pub fn show( if response.clicked() || response.drag_started() { ui.memory_mut(|m| m.request_focus(id)); } + // The text cursor (I-beam) over the text, as in any text box. + if response.hovered() || response.dragged() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Text); + } if focused { ui.memory_mut(|m| { m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false }) diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index f00daa3fa9..fc4c63dfab 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -53,6 +53,11 @@ struct State { fx_closed: Option, /// Where the completion list goes (the caret's bottom, last frame). fx_at: egui::Pos2, + /// Undo and redo steps of the whole editor (text and formatting), with the selection then. + undo: Vec<(Formatted, usize, usize)>, + redo: Vec<(Formatted, usize, usize)>, + /// When the last undo step was recorded (typing within a second makes one step). + undo_at: f64, } fn state_id() -> egui::Id { @@ -106,20 +111,25 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { .map(|s| crate::editor_glyphs::EditorFont { font: s.font, big_font: s.big_font, width_factor: s.width_factor, oblique: s.oblique }) .unwrap_or_else(|| crate::editor_glyphs::EditorFont { width_factor: 1.0, ..Default::default() }); let end = fmt.len(); + // Existing text opens selected as a whole: typing replaces it, an arrow key keeps it. + let existing = !matches!(kind, EditorKind::NewMText) && end > 0; State { fmt, typing: CharFmt::default(), typing_at: end, top: 70.0, - sel: (end, end), - caret: Some(end), + sel: if existing { (end, 0) } else { (end, end) }, + caret: (!existing).then_some(end), key: editor.key.clone(), focus: true, font, - edit: crate::bidi_edit::EditState::at(end), + edit: if existing { crate::bidi_edit::EditState::all(end) } else { crate::bidi_edit::EditState::at(end) }, fx_index: 0, fx_closed: None, fx_at: pos2(0.0, 0.0), + undo: Vec::new(), + redo: Vec::new(), + undo_at: 0.0, } }); let line = kind == EditorKind::Line; @@ -141,6 +151,16 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } }); } + // Undo and redo (Ctrl+Z, Ctrl+Y / Ctrl+Shift+Z, ⌘ on a Mac), taken before the text box. + let before = (st.fmt.clone(), st.edit.cursor, st.edit.anchor); + let mut undo_redo: Option = None; + ctx.input_mut(|i| { + if i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::Z) || i.consume_key(egui::Modifiers::COMMAND, egui::Key::Y) { + undo_redo = Some(false); + } else if i.consume_key(egui::Modifiers::COMMAND, egui::Key::Z) { + undo_redo = Some(true); + } + }); // Formula completion: the arrows choose a function, Tab or Enter puts it in, Escape closes // the list (taken before the text box and before Enter finishes one line of text). let fx = completion(&st); @@ -217,6 +237,27 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { if ui.button(crate::tl!("Cancel")).clicked() { done = Done::Cancel; } + ui.add_space(6.0); + let mac = ui.ctx().os().is_mac(); + let tip = |undo: bool| { + match (undo, mac) { + (true, true) => crate::tl!("Undo (⌘Z)"), + (true, false) => crate::tl!("Undo (Ctrl+Z)"), + (false, true) => crate::tl!("Redo (⇧⌘Z)"), + (false, false) => crate::tl!("Redo (Ctrl+Y)"), + } + }; + for (undo, icon) in [(true, crate::icons::Icon::Undo), (false, crate::icons::Icon::Redo)] { + let any = if undo { !st.undo.is_empty() } else { !st.redo.is_empty() }; + let (r, resp) = ui.allocate_exact_size(vec2(24.0, 22.0), Sense::click()); + if resp.hovered() && any { + ui.painter().rect_filled(r, 3.0, t.control_hover); + } + crate::icons::paint(ui.painter(), r.shrink(3.0), icon, !any); + if resp.on_hover_text(tip(undo)).clicked() && any { + undo_redo = Some(undo); + } + } if cell { if icon_button(ui, false, crate::tl!("Previous cell (Shift+Tab)"), |p, r, c| paint_triangle(p, r, c, -1.0)).clicked() { done = Done::Move("Previous"); @@ -234,6 +275,33 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { }); }); }); + let now = ctx.input(|i| i.time); + match undo_redo { + Some(undo) => { + let (from, to) = if undo { (&mut st.undo, &mut st.redo) } else { (&mut st.redo, &mut st.undo) }; + if let Some((f, c, a)) = from.pop() { + to.push((st.fmt.clone(), st.edit.cursor, st.edit.anchor)); + st.fmt = f; + st.edit.cursor = c.min(st.fmt.len()); + st.edit.anchor = a.min(st.fmt.len()); + st.sel = (st.edit.cursor, st.edit.anchor); + st.typing_at = st.edit.cursor; + st.undo_at = 0.0; + } + } + None if st.fmt != before.0 => { + // Typing within a second of the last change is one step. + if now - st.undo_at > 1.0 || st.undo.is_empty() { + st.undo.push(before); + if st.undo.len() > 200 { + st.undo.remove(0); + } + } + st.undo_at = now; + st.redo.clear(); + } + None => {} + } if let Some((_, list)) = completion(&st) { let mut clicked = None; egui::Area::new(egui::Id::new("mtext_formula_list")).order(egui::Order::Tooltip).fixed_pos(st.fx_at + vec2(0.0, 4.0)).show(ctx, |ui| { From c49f0c80fc8da3bee14450fb6c5ef201d137a500 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 19:10:54 +0300 Subject: [PATCH 13/23] b16: command history on hover, tool descriptions in tooltips Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/cmdline.rs | 23 +++++- crates/ui-egui/src/i18n/ru.tsv | 124 ++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/uk.tsv | 124 ++++++++++++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 142 ++++++++++++++++++++++++++++++++- 4 files changed, 411 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index f5bab7a125..0ddb016659 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -432,8 +432,29 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { let bar = Rect::from_min_size(pos2(canvas.center().x - w / 2.0, canvas.bottom() - h - 10.0), vec2(w, h)); let p = ui.painter_at(canvas); history(app, ui, canvas, bar); - // History lines above the bar (the expanded window replaces them). + // History lines above the bar (the expanded window replaces them), shown while the pointer is + // over the bar or over them. let n = if app.cmd.expanded { 0 } else { visible_lines(app, canvas, bar) }; + let shown = n.min(app.session.log.len()); + let over = { + let lines_h = 16.0 * shown as f32 + 6.0; + let zone = Rect::from_min_max(pos2(bar.left(), bar.top() - lines_h), bar.max).expand(2.0); + let now = ui.input(|i| i.time); + let hover_id = egui::Id::new("cc_cmd_history_hover"); + if ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| zone.contains(p)) { + ui.data_mut(|d| d.insert_temp(hover_id, now)); + true + } else { + // A moment's grace, so the lines don't flicker at the edge. + let last: f64 = ui.data(|d| d.get_temp(hover_id)).unwrap_or(f64::NEG_INFINITY); + let left = now - last < 0.3; + if left { + ui.ctx().request_repaint_after(std::time::Duration::from_millis(100)); + } + left + } + }; + let n = if over { n } else { 0 }; let lines: Vec = app.session.log.iter().rev().take(n).rev().cloned().collect(); if !lines.is_empty() { let lh = 16.0; diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d6a447871b..22eae5b14a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1476,3 +1476,127 @@ A text without spaces at its ends and double spaces. Текст без пробелов по краям и двойных пробелов. A text in capitals. Текст прописными буквами. The year of a date. Год даты. + Starts a new drawing from the default template. Создаёт новый чертёж по шаблону по умолчанию. + Opens a drawing (DWG, DXF) from a file. Открывает чертёж (DWG, DXF) из файла. + Saves the drawing to its file (asks for a name the first time). Сохраняет чертёж в его файл (при первом сохранении спрашивает имя). + Saves the drawing under a new name, format or version. Сохраняет чертёж под новым именем, в другом формате или версии. + Undoes the last action. The arrow beside it undoes several at once. Отменяет последнее действие. Стрелка рядом отменяет сразу несколько. + Redoes what was undone. The arrow beside it redoes several at once. Возвращает отменённое действие. Стрелка рядом возвращает сразу несколько. + Prints the current layout or model space to a printer or a PDF file. Печатает текущий лист или пространство модели на принтер или в PDF. + Prints several sheets at once, to separate files or one PDF. Печатает сразу несколько листов: в отдельные файлы или в один PDF. + Sets the paper, printer and plot settings of layouts. Задаёт бумагу, принтер и параметры печати листов. + Shows the page as it will be printed. Показывает страницу так, как она будет напечатана. + Brings another file's contents (DXF, SVG...) into this drawing. Добавляет в чертёж содержимое другого файла (DXF, SVG...). + Saves the drawing or part of it as PDF, SVG, PNG or another format. Сохраняет чертёж или его часть в PDF, SVG, PNG или другой формат. + Attaches an external reference: a drawing, image or PDF shown in this one. Прикрепляет внешнюю ссылку: чертёж, изображение или PDF, которые показываются в этом чертеже. + Shares the drawing with others. Отправляет чертёж другим людям. + Zooms to a rectangle you draw. Увеличивает область, которую вы обведёте рамкой. + Moves the view without changing its scale. Сдвигает вид, не меняя масштаб. + Turns the view around the drawing in 3D. Поворачивает вид вокруг чертежа в 3D. + Zooms to show the whole drawing. Показывает весь чертёж целиком. + Shows or hides the Properties and Layers palettes. Показывает или прячет палитры «Свойства» и «Слои». + Opens the Layer Properties Manager: create layers, set their colour, linetype and state. Открывает диспетчер слоёв: создание слоёв, их цвет, тип линий и состояние. + Opens the block manager: insert, edit and manage blocks. Открывает диспетчер блоков: вставка, редактирование и управление блоками. + Measures the distance and angle between two points. Измеряет расстояние и угол между двумя точками. + Lists everything about the selected objects in the command history. Выводит в историю команд все сведения о выбранных объектах. + Measures the area and perimeter of an object or of points you pick. Измеряет площадь и периметр объекта или указанных точек. + About CADCraft and help. О программе CADCraft и справка. + Creates and changes text styles: font, height, width factor. Создаёт и изменяет текстовые стили: шрифт, высота, коэффициент ширины. + Creates and changes dimension styles: arrows, text, lines, units. Создаёт и изменяет размерные стили: стрелки, текст, линии, единицы. + Opens the program's settings. Открывает настройки программы. + The current layer: new objects are drawn on it. Pick another from the list. Текущий слой: на нём рисуются новые объекты. Выберите другой из списка. + Makes the layer of the object you pick the current layer. Делает текущим слой выбранного объекта. + Moves the selected objects to the layer of another object. Переносит выбранные объекты на слой другого объекта. + Undoes the last change to layer settings. Отменяет последнее изменение настроек слоёв. + Hides or locks every layer except those of the selected objects. Скрывает или блокирует все слои, кроме слоёв выбранных объектов. + Turns off the layer of the object you pick. Отключает слой выбранного объекта. + Freezes the layer of the object you pick: hidden and not regenerated. Замораживает слой выбранного объекта: он скрыт и не пересчитывается. + Locks the layer of the object you pick: its objects can't be changed. Блокирует слой выбранного объекта: его объекты нельзя изменить. + Unlocks the layer of the object you pick. Разблокирует слой выбранного объекта. + The current text style, used by new text. Текущий текстовый стиль для нового текста. + The current dimension style, used by new dimensions. Текущий размерный стиль для новых размеров. + The linetype of new objects. Тип линий новых объектов. + The lineweight of new objects. Вес линий новых объектов. + Draws straight line segments, one after another. Рисует прямые отрезки, один за другим. + Draws a polyline: connected straight and arc segments that form one object. Рисует полилинию: связанные прямые и дуговые сегменты, образующие один объект. + Draws a circle by its centre and radius, or by points. Рисует окружность по центру и радиусу или по точкам. + Draws a rectangle by two corners, or by its width and height. Рисует прямоугольник по двум углам или по ширине и высоте. + Draws an arc through three points, or by centre, start and end. Рисует дугу по трём точкам или по центру, началу и концу. + Draws a smooth curve through or near the points you pick. Рисует плавную кривую через указанные точки или рядом с ними. + Draws an infinite construction line, for alignment. Рисует бесконечную вспомогательную прямую для выравнивания. + Draws a line that starts at a point and runs on without end. Рисует луч: линию, которая начинается в точке и уходит в бесконечность. + Draws an ellipse or an elliptical arc. Рисует эллипс или эллиптическую дугу. + Draws a regular polygon with as many sides as you like. Рисует правильный многоугольник с любым числом сторон. + Places points, one after another. Ставит точки, одну за другой. + Draws a filled ring or a filled circle. Рисует закрашенное кольцо или закрашенный круг. + Draws a revision cloud around something to mark a change. Рисует облако вокруг объекта, чтобы отметить изменение. + Turns closed shapes into regions (areas you can combine and measure). Превращает замкнутые контуры в области (их можно объединять и измерять). + Covers what is behind an area with the background colour. Закрывает то, что под областью, цветом фона. + Fills an enclosed area with a pattern or a solid colour. Заполняет замкнутую область штриховкой или сплошным цветом. + Fills an enclosed area with a colour gradient. Заполняет замкнутую область градиентом. + Draws a polyline around an enclosed area you click inside. Рисует полилинию по контуру замкнутой области, внутри которой вы щёлкнули. + Groups selected objects into a block that can be inserted again and again. Объединяет выбранные объекты в блок, который можно вставлять много раз. + Inserts a block (opens the block manager). Вставляет блок (открывает диспетчер блоков). + Opens a block to change what it contains. Открывает блок, чтобы изменить его содержимое. + Defines an attribute: text asked for each time the block is inserted. Определяет атрибут: текст, который запрашивается при каждой вставке блока. + Moves objects by a distance, from a base point to another point. Перемещает объекты от базовой точки к другой точке. + Copies objects to other places. Копирует объекты в другие места. + Turns objects around a base point. Поворачивает объекты вокруг базовой точки. + Cuts off the parts of objects that cross other objects. Hover to see what goes. Отрезает части объектов, пересекающие другие объекты. Наведите курсор, чтобы увидеть, что будет удалено. + Rounds the corner between two objects with an arc. Скругляет угол между двумя объектами дугой. + Copies objects in rows and columns. Копирует объекты рядами и столбцами. + Makes a mirror copy of objects across a line (and can erase the originals). Создаёт зеркальную копию объектов относительно линии (и может удалить исходные). + Makes objects larger or smaller from a base point. Увеличивает или уменьшает объекты относительно базовой точки. + Lengthens objects to meet other objects. Hover to see the extension. Удлиняет объекты до других объектов. Наведите курсор, чтобы увидеть удлинение. + Makes a parallel copy of a line, curve or outline at a distance. Создаёт параллельную копию линии, кривой или контура на заданном расстоянии. + Copies objects around a centre point. Копирует объекты по кругу вокруг центра. + Stretches objects crossed by a selection window, moving their points inside it. Растягивает объекты, пересечённые рамкой: точки внутри рамки сдвигаются. + Bevels the corner between two lines. Срезает угол между двумя линиями фаской. + Breaks a compound object (block, polyline, dimension) into its parts. Разбивает составной объект (блок, полилинию, размер) на части. + Breaks an object in two, or removes a part between two points. Разрывает объект на два или удаляет часть между двумя точками. + Joins lines, arcs and polylines that touch into one object. Соединяет касающиеся линии, дуги и полилинии в один объект. + Deletes the selected objects. Удаляет выбранные объекты. + Changes the length of lines and arcs. Изменяет длину отрезков и дуг. + Copies the properties of one object (layer, colour, style...) to others. Копирует свойства одного объекта (слой, цвет, стиль...) на другие. + Writes single-line text. A text starting with = shows a formula's result. Создаёт однострочный текст. Текст, начинающийся с =, показывает результат формулы. + Writes multiline text in a box, with formatting. Создаёт многострочный текст в рамке, с форматированием. + Inserts a table of rows and columns. Вставляет таблицу из строк и столбцов. + Finds text in the drawing and replaces it. Ищет текст в чертеже и заменяет его. + A horizontal or vertical dimension between two points. Горизонтальный или вертикальный размер между двумя точками. + A dimension parallel to the line between two points. Размер, параллельный линии между двумя точками. + The radius of a circle or arc. Радиус окружности или дуги. + The diameter of a circle or arc. Диаметр окружности или дуги. + The angle between two lines, or of an arc. Угол между двумя линиями или угол дуги. + The length along an arc. Длина дуги. + The X or Y coordinate of a point. Координата X или Y точки. + More dimensions from the same base line as the last one. Новые размеры от той же базы, что и последний. + More dimensions continuing from the end of the last one. Новые размеры, продолжающие последний (цепочкой). + Dimensions several objects at once. Проставляет размеры сразу для нескольких объектов. + A note with an arrow pointing at something (multileader). Выноска: текст со стрелкой, указывающей на объект. + Adds another leader line to a multileader. Добавляет ещё одну линию к выноске. + Removes a leader line from a multileader. Удаляет линию выноски. + Lines up several multileaders. Выравнивает несколько выносок. + Adds geometric constraints to the selected objects automatically. Автоматически накладает геометрические зависимости на выбранные объекты. + Keeps two points together. Удерживает две точки вместе. + Keeps two lines parallel. Удерживает две линии параллельными. + Keeps two lines at right angles. Удерживает две линии под прямым углом. + Keeps a line horizontal. Удерживает линию горизонтальной. + Keeps a line vertical. Удерживает линию вертикальной. + Keeps a curve tangent to another object. Удерживает кривую касательной к другому объекту. + Keeps circles and arcs on one centre. Удерживает окружности и дуги на общем центре. + Keeps two lines the same length, or two circles the same size. Удерживает равными длины двух линий или размеры двух окружностей. + Draws a 3D box. Создаёт 3D-параллелепипед. + Draws a 3D cylinder. Создаёт 3D-цилиндр. + Draws a 3D pyramid. Создаёт 3D-пирамиду. + Draws a 3D sphere. Создаёт 3D-шар. + Draws a 3D torus (a ring). Создаёт 3D-тор (кольцо). + Draws a 3D cone. Создаёт 3D-конус. + Pulls a closed shape into a 3D solid. Вытягивает замкнутый контур в 3D-тело. + Turns a shape around an axis into a 3D solid. Вращает контур вокруг оси и создаёт 3D-тело. + Sweeps a shape along a path into a 3D solid. Протягивает контур вдоль траектории и создаёт 3D-тело. + Makes a 3D solid through several cross sections. Создаёт 3D-тело по нескольким сечениям. + Joins 3D solids or regions into one. Объединяет 3D-тела или области в одно. + Cuts 3D solids or regions out of others. Вычитает одни 3D-тела или области из других. + Keeps only the part 3D solids or regions share. Оставляет только общую часть 3D-тел или областей. + Undo (Ctrl+Z) Отменить (Ctrl+Z) + Redo (Ctrl+Y) Вернуть (Ctrl+Y) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 00f85a1e39..5b77816643 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1729,3 +1729,127 @@ Tab or Enter: insert · Esc: close Tab або Enter: вставити · Esc: закрити A text that starts with = shows the result of a formula, as in a spreadsheet: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). The formula stays with the text: editing the text edits the formula. Dates and times follow the computer's clock and are worked out again when the drawing is opened (Tools ▸ Update Fields does it at once). Date fields in AutoCAD drawings are updated the same way. Текст, що починається зі знака =, показує результат формули, як в електронній таблиці: =2400-2*18, =ROUND(PI()*125^2/1000000;3), =TEXT(TODAY();"dd.mm.yyyy"). Формула зберігається разом із текстом: під час редагування тексту редагується формула. Дати й час беруться з годинника комп’ютера та перераховуються під час відкриття креслення (Сервіс ▸ Оновити поля робить це одразу). Поля дати в кресленнях AutoCAD оновлюються так само. Operators: + - * / ^ (power), % (percent), & (joins texts), = <> < > <= >= (compare). Texts in double quotes. Arguments are separated by commas or semicolons. While typing a formula, a list of functions appears: the arrows choose, Tab or Enter inserts. Операції: + - * / ^ (степінь), % (відсоток), & (з’єднує тексти), = <> < > <= >= (порівняння). Тексти пишуться в подвійних лапках. Аргументи розділяються комами або крапками з комою. Поки ви набираєте формулу, з’являється список функцій: стрілки вибирають, Tab або Enter вставляє. + Starts a new drawing from the default template. Створює нове креслення за типовим шаблоном. + Opens a drawing (DWG, DXF) from a file. Відкриває креслення (DWG, DXF) з файлу. + Saves the drawing to its file (asks for a name the first time). Зберігає креслення у його файл (уперше запитує ім’я). + Saves the drawing under a new name, format or version. Зберігає креслення під новим ім’ям, в іншому форматі чи версії. + Undoes the last action. The arrow beside it undoes several at once. Скасовує останню дію. Стрілка поруч скасовує одразу кілька. + Redoes what was undone. The arrow beside it redoes several at once. Повертає скасовану дію. Стрілка поруч повертає одразу кілька. + Prints the current layout or model space to a printer or a PDF file. Друкує поточний аркуш або простір моделі на принтер чи в PDF. + Prints several sheets at once, to separate files or one PDF. Друкує одразу кілька аркушів: в окремі файли або в один PDF. + Sets the paper, printer and plot settings of layouts. Задає папір, принтер і параметри друку аркушів. + Shows the page as it will be printed. Показує сторінку так, як її буде надруковано. + Brings another file's contents (DXF, SVG...) into this drawing. Додає до креслення вміст іншого файлу (DXF, SVG...). + Saves the drawing or part of it as PDF, SVG, PNG or another format. Зберігає креслення або його частину в PDF, SVG, PNG чи інший формат. + Attaches an external reference: a drawing, image or PDF shown in this one. Прикріплює зовнішнє посилання: креслення, зображення чи PDF, що показуються в цьому кресленні. + Shares the drawing with others. Надсилає креслення іншим людям. + Zooms to a rectangle you draw. Збільшує область, яку ви обведете рамкою. + Moves the view without changing its scale. Зсуває вигляд, не змінюючи масштаб. + Turns the view around the drawing in 3D. Повертає вигляд навколо креслення в 3D. + Zooms to show the whole drawing. Показує все креслення цілком. + Shows or hides the Properties and Layers palettes. Показує або ховає палітри «Властивості» та «Шари». + Opens the Layer Properties Manager: create layers, set their colour, linetype and state. Відкриває диспетчер шарів: створення шарів, їхній колір, тип ліній і стан. + Opens the block manager: insert, edit and manage blocks. Відкриває диспетчер блоків: вставлення, редагування й керування блоками. + Measures the distance and angle between two points. Вимірює відстань і кут між двома точками. + Lists everything about the selected objects in the command history. Виводить до історії команд усі відомості про вибрані об’єкти. + Measures the area and perimeter of an object or of points you pick. Вимірює площу й периметр об’єкта або вказаних точок. + About CADCraft and help. Про CADCraft і довідка. + Creates and changes text styles: font, height, width factor. Створює та змінює текстові стилі: шрифт, висота, коефіцієнт ширини. + Creates and changes dimension styles: arrows, text, lines, units. Створює та змінює розмірні стилі: стрілки, текст, лінії, одиниці. + Opens the program's settings. Відкриває налаштування програми. + The current layer: new objects are drawn on it. Pick another from the list. Поточний шар: на ньому малюються нові об’єкти. Виберіть інший зі списку. + Makes the layer of the object you pick the current layer. Робить поточним шар вибраного об’єкта. + Moves the selected objects to the layer of another object. Переносить вибрані об’єкти на шар іншого об’єкта. + Undoes the last change to layer settings. Скасовує останню зміну налаштувань шарів. + Hides or locks every layer except those of the selected objects. Ховає або блокує всі шари, крім шарів вибраних об’єктів. + Turns off the layer of the object you pick. Вимикає шар вибраного об’єкта. + Freezes the layer of the object you pick: hidden and not regenerated. Заморожує шар вибраного об’єкта: він прихований і не перераховується. + Locks the layer of the object you pick: its objects can't be changed. Блокує шар вибраного об’єкта: його об’єкти не можна змінити. + Unlocks the layer of the object you pick. Розблоковує шар вибраного об’єкта. + The current text style, used by new text. Поточний текстовий стиль для нового тексту. + The current dimension style, used by new dimensions. Поточний розмірний стиль для нових розмірів. + The linetype of new objects. Тип ліній нових об’єктів. + The lineweight of new objects. Товщина ліній нових об’єктів. + Draws straight line segments, one after another. Малює прямі відрізки, один за одним. + Draws a polyline: connected straight and arc segments that form one object. Малює полілінію: з’єднані прямі й дугові сегменти, що утворюють один об’єкт. + Draws a circle by its centre and radius, or by points. Малює коло за центром і радіусом або за точками. + Draws a rectangle by two corners, or by its width and height. Малює прямокутник за двома кутами або за шириною й висотою. + Draws an arc through three points, or by centre, start and end. Малює дугу за трьома точками або за центром, початком і кінцем. + Draws a smooth curve through or near the points you pick. Малює плавну криву через вказані точки або поруч із ними. + Draws an infinite construction line, for alignment. Малює нескінченну допоміжну пряму для вирівнювання. + Draws a line that starts at a point and runs on without end. Малює промінь: лінію, що починається в точці й іде в нескінченність. + Draws an ellipse or an elliptical arc. Малює еліпс або еліптичну дугу. + Draws a regular polygon with as many sides as you like. Малює правильний багатокутник із будь-якою кількістю сторін. + Places points, one after another. Ставить точки, одну за одною. + Draws a filled ring or a filled circle. Малює зафарбоване кільце або зафарбований круг. + Draws a revision cloud around something to mark a change. Малює хмару навколо об’єкта, щоб позначити зміну. + Turns closed shapes into regions (areas you can combine and measure). Перетворює замкнені контури на області (їх можна об’єднувати й вимірювати). + Covers what is behind an area with the background colour. Закриває те, що під областю, кольором фону. + Fills an enclosed area with a pattern or a solid colour. Заповнює замкнену область штрихуванням або суцільним кольором. + Fills an enclosed area with a colour gradient. Заповнює замкнену область градієнтом. + Draws a polyline around an enclosed area you click inside. Малює полілінію по контуру замкненої області, всередині якої ви клацнули. + Groups selected objects into a block that can be inserted again and again. Об’єднує вибрані об’єкти в блок, який можна вставляти багато разів. + Inserts a block (opens the block manager). Вставляє блок (відкриває диспетчер блоків). + Opens a block to change what it contains. Відкриває блок, щоб змінити його вміст. + Defines an attribute: text asked for each time the block is inserted. Визначає атрибут: текст, що запитується під час кожного вставлення блока. + Moves objects by a distance, from a base point to another point. Переміщує об’єкти від базової точки до іншої точки. + Copies objects to other places. Копіює об’єкти в інші місця. + Turns objects around a base point. Повертає об’єкти навколо базової точки. + Cuts off the parts of objects that cross other objects. Hover to see what goes. Відрізає частини об’єктів, що перетинають інші об’єкти. Наведіть курсор, щоб побачити, що буде видалено. + Rounds the corner between two objects with an arc. Заокруглює кут між двома об’єктами дугою. + Copies objects in rows and columns. Копіює об’єкти рядами й стовпцями. + Makes a mirror copy of objects across a line (and can erase the originals). Створює дзеркальну копію об’єктів відносно лінії (і може видалити вихідні). + Makes objects larger or smaller from a base point. Збільшує або зменшує об’єкти відносно базової точки. + Lengthens objects to meet other objects. Hover to see the extension. Подовжує об’єкти до інших об’єктів. Наведіть курсор, щоб побачити подовження. + Makes a parallel copy of a line, curve or outline at a distance. Створює паралельну копію лінії, кривої чи контуру на заданій відстані. + Copies objects around a centre point. Копіює об’єкти по колу навколо центру. + Stretches objects crossed by a selection window, moving their points inside it. Розтягує об’єкти, перетнуті рамкою: точки всередині рамки зсуваються. + Bevels the corner between two lines. Зрізає кут між двома лініями фаскою. + Breaks a compound object (block, polyline, dimension) into its parts. Розбиває складений об’єкт (блок, полілінію, розмір) на частини. + Breaks an object in two, or removes a part between two points. Розриває об’єкт на два або видаляє частину між двома точками. + Joins lines, arcs and polylines that touch into one object. З’єднує дотичні лінії, дуги й полілінії в один об’єкт. + Deletes the selected objects. Видаляє вибрані об’єкти. + Changes the length of lines and arcs. Змінює довжину відрізків і дуг. + Copies the properties of one object (layer, colour, style...) to others. Копіює властивості одного об’єкта (шар, колір, стиль...) на інші. + Writes single-line text. A text starting with = shows a formula's result. Створює однорядковий текст. Текст, що починається з =, показує результат формули. + Writes multiline text in a box, with formatting. Створює багаторядковий текст у рамці, з форматуванням. + Inserts a table of rows and columns. Вставляє таблицю з рядків і стовпців. + Finds text in the drawing and replaces it. Шукає текст у кресленні та замінює його. + A horizontal or vertical dimension between two points. Горизонтальний або вертикальний розмір між двома точками. + A dimension parallel to the line between two points. Розмір, паралельний лінії між двома точками. + The radius of a circle or arc. Радіус кола або дуги. + The diameter of a circle or arc. Діаметр кола або дуги. + The angle between two lines, or of an arc. Кут між двома лініями або кут дуги. + The length along an arc. Довжина дуги. + The X or Y coordinate of a point. Координата X або Y точки. + More dimensions from the same base line as the last one. Нові розміри від тієї ж бази, що й останній. + More dimensions continuing from the end of the last one. Нові розміри, що продовжують останній (ланцюжком). + Dimensions several objects at once. Проставляє розміри одразу для кількох об’єктів. + A note with an arrow pointing at something (multileader). Виноска: текст зі стрілкою, що вказує на об’єкт. + Adds another leader line to a multileader. Додає ще одну лінію до виноски. + Removes a leader line from a multileader. Видаляє лінію виноски. + Lines up several multileaders. Вирівнює кілька виносок. + Adds geometric constraints to the selected objects automatically. Автоматично накладає геометричні залежності на вибрані об’єкти. + Keeps two points together. Утримує дві точки разом. + Keeps two lines parallel. Утримує дві лінії паралельними. + Keeps two lines at right angles. Утримує дві лінії під прямим кутом. + Keeps a line horizontal. Утримує лінію горизонтальною. + Keeps a line vertical. Утримує лінію вертикальною. + Keeps a curve tangent to another object. Утримує криву дотичною до іншого об’єкта. + Keeps circles and arcs on one centre. Утримує кола й дуги на спільному центрі. + Keeps two lines the same length, or two circles the same size. Утримує рівними довжини двох ліній або розміри двох кіл. + Draws a 3D box. Створює 3D-паралелепіпед. + Draws a 3D cylinder. Створює 3D-циліндр. + Draws a 3D pyramid. Створює 3D-піраміду. + Draws a 3D sphere. Створює 3D-кулю. + Draws a 3D torus (a ring). Створює 3D-тор (кільце). + Draws a 3D cone. Створює 3D-конус. + Pulls a closed shape into a 3D solid. Видавлює замкнений контур у 3D-тіло. + Turns a shape around an axis into a 3D solid. Обертає контур навколо осі й створює 3D-тіло. + Sweeps a shape along a path into a 3D solid. Протягує контур уздовж траєкторії й створює 3D-тіло. + Makes a 3D solid through several cross sections. Створює 3D-тіло за кількома перерізами. + Joins 3D solids or regions into one. Об’єднує 3D-тіла або області в одне. + Cuts 3D solids or regions out of others. Віднімає одні 3D-тіла або області від інших. + Keeps only the part 3D solids or regions share. Залишає лише спільну частину 3D-тіл або областей. + Undo (Ctrl+Z) Скасувати (Ctrl+Z) + Redo (Ctrl+Y) Повернути (Ctrl+Y) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 1378e1b1d3..78da8bf3b3 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -470,9 +470,143 @@ pub fn add_item(items: &mut Vec, command: &str, index: Option) -> } /// The tooltip of a tool button: name, command and alias, shortcut. +/// Short descriptions of the tools, shown in their tooltips: (command, what it does). +pub const DESCRIPTIONS: &[(&str, &str)] = &[ + ("new", "Starts a new drawing from the default template."), + ("open", "Opens a drawing (DWG, DXF) from a file."), + ("qsave", "Saves the drawing to its file (asks for a name the first time)."), + ("saveas", "Saves the drawing under a new name, format or version."), + ("u", "Undoes the last action. The arrow beside it undoes several at once."), + ("redo", "Redoes what was undone. The arrow beside it redoes several at once."), + ("plot", "Prints the current layout or model space to a printer or a PDF file."), + ("publish", "Prints several sheets at once, to separate files or one PDF."), + ("pagesetup", "Sets the paper, printer and plot settings of layouts."), + ("preview", "Shows the page as it will be printed."), + ("import", "Brings another file's contents (DXF, SVG...) into this drawing."), + ("export", "Saves the drawing or part of it as PDF, SVG, PNG or another format."), + ("attach", "Attaches an external reference: a drawing, image or PDF shown in this one."), + ("share", "Shares the drawing with others."), + ("zoom.window", "Zooms to a rectangle you draw."), + ("pan", "Moves the view without changing its scale."), + ("3dorbit", "Turns the view around the drawing in 3D."), + ("zoom.extents", "Zooms to show the whole drawing."), + ("ui.toggle.palettes", "Shows or hides the Properties and Layers palettes."), + ("ui.dialog.layers", "Opens the Layer Properties Manager: create layers, set their colour, linetype and state."), + ("ui.dialog.blocks", "Opens the block manager: insert, edit and manage blocks."), + ("dist", "Measures the distance and angle between two points."), + ("list", "Lists everything about the selected objects in the command history."), + ("area", "Measures the area and perimeter of an object or of points you pick."), + ("ui.dialog.about", "About CADCraft and help."), + ("style", "Creates and changes text styles: font, height, width factor."), + ("dimstyle", "Creates and changes dimension styles: arrows, text, lines, units."), + ("options", "Opens the program's settings."), + ("layer.combo", "The current layer: new objects are drawn on it. Pick another from the list."), + ("laymcur", "Makes the layer of the object you pick the current layer."), + ("laymch", "Moves the selected objects to the layer of another object."), + ("layerp", "Undoes the last change to layer settings."), + ("layiso", "Hides or locks every layer except those of the selected objects."), + ("layoff", "Turns off the layer of the object you pick."), + ("layfrz", "Freezes the layer of the object you pick: hidden and not regenerated."), + ("laylck", "Locks the layer of the object you pick: its objects can't be changed."), + ("layulk", "Unlocks the layer of the object you pick."), + ("textstyle.combo", "The current text style, used by new text."), + ("dimstyle.combo", "The current dimension style, used by new dimensions."), + ("linetype.combo", "The linetype of new objects."), + ("lweight.combo", "The lineweight of new objects."), + ("line", "Draws straight line segments, one after another."), + ("pline", "Draws a polyline: connected straight and arc segments that form one object."), + ("circle", "Draws a circle by its centre and radius, or by points."), + ("rectang", "Draws a rectangle by two corners, or by its width and height."), + ("arc", "Draws an arc through three points, or by centre, start and end."), + ("spline", "Draws a smooth curve through or near the points you pick."), + ("xline", "Draws an infinite construction line, for alignment."), + ("ray", "Draws a line that starts at a point and runs on without end."), + ("ellipse", "Draws an ellipse or an elliptical arc."), + ("polygon", "Draws a regular polygon with as many sides as you like."), + ("point.multiple", "Places points, one after another."), + ("donut", "Draws a filled ring or a filled circle."), + ("revcloud", "Draws a revision cloud around something to mark a change."), + ("region", "Turns closed shapes into regions (areas you can combine and measure)."), + ("wipeout", "Covers what is behind an area with the background colour."), + ("hatch", "Fills an enclosed area with a pattern or a solid colour."), + ("gradient", "Fills an enclosed area with a colour gradient."), + ("boundary", "Draws a polyline around an enclosed area you click inside."), + ("block", "Groups selected objects into a block that can be inserted again and again."), + ("insert", "Inserts a block (opens the block manager)."), + ("bedit", "Opens a block to change what it contains."), + ("attdef", "Defines an attribute: text asked for each time the block is inserted."), + ("move", "Moves objects by a distance, from a base point to another point."), + ("copy", "Copies objects to other places."), + ("rotate", "Turns objects around a base point."), + ("trim", "Cuts off the parts of objects that cross other objects. Hover to see what goes."), + ("fillet", "Rounds the corner between two objects with an arc."), + ("arrayrect", "Copies objects in rows and columns."), + ("mirror", "Makes a mirror copy of objects across a line (and can erase the originals)."), + ("scale", "Makes objects larger or smaller from a base point."), + ("extend", "Lengthens objects to meet other objects. Hover to see the extension."), + ("offset", "Makes a parallel copy of a line, curve or outline at a distance."), + ("arraypolar", "Copies objects around a centre point."), + ("stretch", "Stretches objects crossed by a selection window, moving their points inside it."), + ("chamfer", "Bevels the corner between two lines."), + ("explode", "Breaks a compound object (block, polyline, dimension) into its parts."), + ("break", "Breaks an object in two, or removes a part between two points."), + ("join", "Joins lines, arcs and polylines that touch into one object."), + ("erase", "Deletes the selected objects."), + ("lengthen", "Changes the length of lines and arcs."), + ("matchprop", "Copies the properties of one object (layer, colour, style...) to others."), + ("text", "Writes single-line text. A text starting with = shows a formula's result."), + ("mtext", "Writes multiline text in a box, with formatting."), + ("table", "Inserts a table of rows and columns."), + ("find", "Finds text in the drawing and replaces it."), + ("dimlinear", "A horizontal or vertical dimension between two points."), + ("dimaligned", "A dimension parallel to the line between two points."), + ("dimradius", "The radius of a circle or arc."), + ("dimdiameter", "The diameter of a circle or arc."), + ("dimangular", "The angle between two lines, or of an arc."), + ("dimarc", "The length along an arc."), + ("dimordinate", "The X or Y coordinate of a point."), + ("dimbaseline", "More dimensions from the same base line as the last one."), + ("dimcontinue", "More dimensions continuing from the end of the last one."), + ("qdim", "Dimensions several objects at once."), + ("mleader", "A note with an arrow pointing at something (multileader)."), + ("mleaderedit", "Adds another leader line to a multileader."), + ("mleaderedit.remove", "Removes a leader line from a multileader."), + ("mleaderalign", "Lines up several multileaders."), + ("autoconstrain", "Adds geometric constraints to the selected objects automatically."), + ("gccoincident", "Keeps two points together."), + ("gcparallel", "Keeps two lines parallel."), + ("gcperpendicular", "Keeps two lines at right angles."), + ("gchorizontal", "Keeps a line horizontal."), + ("gcvertical", "Keeps a line vertical."), + ("gctangent", "Keeps a curve tangent to another object."), + ("gcconcentric", "Keeps circles and arcs on one centre."), + ("gcequal", "Keeps two lines the same length, or two circles the same size."), + ("box", "Draws a 3D box."), + ("cylinder", "Draws a 3D cylinder."), + ("pyramid", "Draws a 3D pyramid."), + ("sphere", "Draws a 3D sphere."), + ("torus", "Draws a 3D torus (a ring)."), + ("cone", "Draws a 3D cone."), + ("extrude", "Pulls a closed shape into a 3D solid."), + ("revolve", "Turns a shape around an axis into a 3D solid."), + ("sweep", "Sweeps a shape along a path into a 3D solid."), + ("loft", "Makes a 3D solid through several cross sections."), + ("union", "Joins 3D solids or regions into one."), + ("subtract", "Cuts 3D solids or regions out of others."), + ("intersect", "Keeps only the part 3D solids or regions share."), +]; + +/// The short description of a command for its tooltip. +pub fn description(command: &str) -> Option<&'static str> { + DESCRIPTIONS.iter().find(|(c, _)| *c == command).map(|(_, d)| *d) +} + pub fn tooltip(ui: &mut egui::Ui, tool: &Tool, mac: bool) { - ui.set_max_width(280.0); + ui.set_max_width(300.0); ui.label(RichText::new(crate::i18n::t(tool.label)).strong()); + if let Some(d) = description(tool.command) { + ui.label(crate::i18n::t(d)); + } if !tool.command.starts_with("ui.") && !is_combo(tool.command) { let name = tool.command.split('.').next().unwrap_or(tool.command).to_ascii_uppercase(); let mut line = format!("{} {name}", crate::tl!("Command:")); @@ -1648,6 +1782,12 @@ mod tests { assert_eq!(sanitize(&items), items, "the default bar is already clean"); } + #[test] + fn every_tool_has_a_description() { + let missing: Vec<&str> = catalog().iter().map(|t| t.command).filter(|c| description(c).is_none()).collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + #[test] fn sanitize_drops_unknown_repeated_and_stray_separators() { let items = strings(&["|", "line", "nonsense", "line", "|", "|", "circle", "|"]); From d86a252804de9069a9b52aeb427425e6db128b9c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 19:31:45 +0300 Subject: [PATCH 14/23] b16: TRIM/EXTEND hover glow, TRIM on hatch areas Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/mod.rs | 1 + crates/engine/src/cmd/modify.rs | 70 ++++-- crates/engine/src/cmd/trim_hatch.rs | 279 +++++++++++++++++++++ crates/engine/src/cmd/trimextend.rs | 192 +++++++++++++- crates/engine/src/guard.rs | 9 + crates/engine/src/lib.rs | 14 +- crates/engine/src/prompt.rs | 13 + crates/engine/src/textformula.rs | 14 +- crates/engine/tests/trim_extend_options.rs | 66 +++++ crates/render/src/dim.rs | 6 +- crates/render/src/textformula.rs | 1 - crates/ui-egui/src/canvas.rs | 25 ++ crates/ui-egui/src/mtext_editor.rs | 12 +- 13 files changed, 658 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/cmd/trim_hatch.rs diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 29bbb838b0..15d03933c8 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -39,6 +39,7 @@ mod settings; mod spline_opts; mod table; mod tolerance; +mod trim_hatch; mod trimextend; mod utility; mod view; diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index f7a3442d72..d5da608660 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -782,13 +782,18 @@ pub(crate) struct Edges<'a> { } /// All primitives of the cutting edges (excluding `exclude`). -fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { +pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { + Ok(edge_segments_owned(s, edges)?.into_iter().filter(|(h, _)| *h != exclude).map(|(_, sg)| sg).collect()) +} + +/// [`edge_segments`] of every edge object, each with the object it comes from. +pub(crate) fn edge_segments_owned(s: &Session, edges: Edges) -> Result> { let d = s.doc()?; let space = s.space(); let store = d.space(&space).ok_or(EngineError::NoDocument)?; let mut out = Vec::new(); for e in store.iter() { - if e.handle == exclude || !d.is_visible(e) { + if !d.is_visible(e) { continue; } if let Some(es) = edges.only @@ -799,11 +804,11 @@ fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result Option> { } } -fn prim_to_segments(p: &Prim) -> Vec { +pub(crate) fn prim_to_segments(p: &Prim) -> Vec { match p { Prim::Seg(s) => vec![*s], Prim::Circle(c) => vec![Segment::Arc { arc: Arc { center: c.center, radius: c.radius, start: 0.0, end: TAU - 1e-12 }, ccw: true }], @@ -862,8 +867,27 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu if super::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } - let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let cut = edge_segments(s, edges, h)?; + let (e, pieces) = trim_result(s, h, pick, &cut)?; + let common = e.common.clone(); + let space = s.space(); + let d = s.doc_mut()?; + d.remove_entity(h); + let mut out = Vec::new(); + for k in pieces { + let nh = d.new_handle(); + if let Some(st) = d.space_mut(&space) { + st.push(Entity { handle: nh, common: common.clone(), kind: k }); + out.push(nh); + } + } + Ok(out) +} + +/// What trimming `h` at `pick` against the cutting edges `cut` leaves: the object and the +/// pieces that replace it (the drawing is not changed). +pub(crate) fn trim_result(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<(Entity, Vec)> { + let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let pieces: Vec = match &e.kind { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); @@ -933,22 +957,11 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu } keep.into_iter().collect() } - EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?, - k => super::modify2::trim_other(k, &cut, pick)?, + EntityKind::LwPolyline(p) => trim_polyline(p, cut, pick)?, + EntityKind::Hatch(hatch) => super::trim_hatch::trim_hatch(hatch, cut, pick)?.0.into_iter().collect(), + k => super::modify2::trim_other(k, cut, pick)?, }; - let common = e.common.clone(); - let space = s.space(); - let d = s.doc_mut()?; - d.remove_entity(h); - let mut out = Vec::new(); - for k in pieces { - let nh = d.new_handle(); - if let Some(st) = d.space_mut(&space) { - st.push(Entity { handle: nh, common: common.clone(), kind: k }); - out.push(nh); - } - } - Ok(out) + Ok((e, pieces)) } /// Sub-polyline between length parameters `a` and `b` (open polylines). @@ -1054,8 +1067,16 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re if super::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } - let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let cut = edge_segments(s, edges, h)?; + let new_kind = extend_result(s, h, pick, &cut)?.1; + s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?; + Ok(()) +} + +/// What extending `h` at `pick` to the boundary edges `cut` makes of it: the object and its +/// new geometry (the drawing is not changed). +pub(crate) fn extend_result(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> Result<(Entity, EntityKind)> { + let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?; let new_kind = match &e.kind { EntityKind::Line(l) => { let (a, b) = (l.a.xy(), l.b.xy()); @@ -1105,10 +1126,9 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re } lwpoly(vs, false) } - k => super::modify2::extend_other(k, &cut, pick)?, + k => super::modify2::extend_other(k, cut, pick)?, }; - s.doc_mut()?.modify_entity(h, |e| e.kind = new_kind)?; - Ok(()) + Ok((e, new_kind)) } // ---------------- fillet / chamfer ---------------- diff --git a/crates/engine/src/cmd/trim_hatch.rs b/crates/engine/src/cmd/trim_hatch.rs new file mode 100644 index 0000000000..7a486540b3 --- /dev/null +++ b/crates/engine/src/cmd/trim_hatch.rs @@ -0,0 +1,279 @@ +//! TRIM on a hatch: the cutting edges divide the hatched area, and the part picked is taken out +//! of it. The area left is traced again as boundary loops (arcs in the boundary become short +//! lines), and the hatch stops being associative, as AutoCAD's does. + +use cadcraft_doc::{EntityKind, Hatch, HatchLoop}; +use cadcraft_geom::{Bounds2, Line, PolyVertex, Segment, Vec2, point_in_polygon, region}; + +use crate::{EngineError, Result}; + +/// Most cutting-edge points taken into the area tracing (hostile drawings). +const MAX_CUT_POINTS: usize = 200_000; +/// Most boundary edges handled. +const MAX_EDGES: usize = 200_000; + +fn no_cut() -> EngineError { + EngineError::Other("Object does not intersect a cutting edge.".into()) +} + +/// Closed polygon edges as (a, b) pairs. +fn edges_of(poly: &[Vec2]) -> Vec<(Vec2, Vec2)> { + let n = poly.len(); + if n < 2 { + return Vec::new(); + } + (0..n).filter_map(|i| Some((*poly.get(i)?, *poly.get((i + 1) % n)?))).filter(|(a, b)| a.dist(*b) > 0.0).collect() +} + +/// Split the edge a→b at the points of `pts` lying on it (within `tol`). +fn split_at(a: Vec2, b: Vec2, pts: &[Vec2], tol: f64, out: &mut Vec<(Vec2, Vec2)>) { + let ln = Line::new(a, b); + let len = a.dist(b); + let mut ts: Vec = + pts.iter().filter(|p| ln.dist(**p) <= tol).map(|p| ln.param_of(*p)).filter(|t| *t * len > tol && (1.0 - *t) * len > tol).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|x, y| (*x - *y).abs() * len <= tol); + let mut prev = a; + for t in ts { + let q = ln.at(t); + out.push((prev, q)); + prev = q; + } + out.push((prev, b)); +} + +/// A face's outline without the dangling curves it runs out along and back (A→B→A). +fn despike(mut poly: Vec, tol: f64) -> Vec { + let mut changed = true; + while changed && poly.len() >= 3 { + changed = false; + let n = poly.len(); + for i in 0..n { + let (Some(prev), Some(next)) = (poly.get((i + n - 1) % n), poly.get((i + 1) % n)) else { continue }; + if prev.near(*next, tol) { + // Drop the tip and one of the two equal neighbours. + let (a, b) = if (i + 1) % n > i { (i, i + 1) } else { (0, i) }; + poly.remove(b); + poly.remove(a); + changed = true; + break; + } + } + } + poly +} + +/// Chain directed edges into closed loops (start of one = end of the last). +fn chain(mut edges: Vec<(Vec2, Vec2)>, tol: f64) -> Vec> { + let mut loops = Vec::new(); + while let Some((a, b)) = edges.pop() { + let mut pts = vec![a]; + let mut end = b; + let mut guard = 0usize; + while !end.near(a, tol) && guard < MAX_EDGES { + guard += 1; + let Some(i) = edges.iter().position(|(p, _)| p.near(end, tol)) else { break }; + let (p, q) = edges.swap_remove(i); + pts.push(p); + end = q; + } + if end.near(a, tol) && pts.len() >= 3 { + loops.push(pts); + } + } + loops +} + +/// Trim the hatch at `pick` against the cutting edges `cut`: the hatch that is left (`None`: none +/// of its area is) and the outline of the part taken away (its outer loop, then its islands). +pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Option, Vec>)> { + let raw: Vec> = + h.loops.iter().map(|l| cadcraft_geom::Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e300)).collect(); + let bounds = Bounds2::from_points(raw.iter().flatten().copied()); + let size = bounds.width().hypot(bounds.height()); + if !size.is_finite() || size <= 0.0 { + return Err(EngineError::Other("Cannot trim that object.".into())); + } + let tess = size * 2e-4; + let tol = size * 1e-9; + let mut loops = cadcraft_render::hatch_fill_loops(h, tess); + for l in &mut loops { + if l.len() > 1 && l.first().zip(l.last()).is_some_and(|(f, z)| f.near(*z, tol)) { + l.pop(); + } + } + let in_hatch = |p: Vec2| loops.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1; + if !in_hatch(pick) { + return Err(no_cut()); + } + // The cutting edges near the hatch, as polylines. + let near = bounds.expand(size * 0.01); + let mut cuts: Vec> = Vec::new(); + let mut n = 0usize; + for c in cut { + let mut pts = Vec::new(); + c.tessellate(tess, &mut pts); + let cb = Bounds2::from_points(pts.iter().copied()); + if !cb.intersects(&near) { + continue; + } + n += pts.len(); + if n > MAX_CUT_POINTS { + return Err(EngineError::Other("Too many cutting edges near the hatch.".into())); + } + cuts.push(pts); + } + let mut polys: Vec> = loops + .iter() + .map(|l| { + let mut c = l.clone(); + c.extend(l.first().copied()); + c + }) + .collect(); + polys.extend(cuts); + let b = region::boundary_at(&polys, pick, tol.max(size * 1e-7)).ok_or_else(no_cut)?; + let snap = size * 1e-7; + let face: Vec> = std::iter::once(b.outer.clone()) + .chain(b.islands.iter().map(|i| i.outline.clone())) + .map(|l| despike(l, snap)) + .filter(|l| l.len() >= 3) + .collect(); + let Some(outer) = face.first().cloned() else { return Err(no_cut()) }; + let in_face = |p: Vec2| point_in_polygon(&outer, p) && !face.iter().skip(1).any(|i| point_in_polygon(i, p)); + // A face made of the hatch's own boundary only: no cutting edge crosses this area. + let on_hatch = |a: Vec2, z: Vec2| { + let m = (a + z) * 0.5; + loops.iter().any(|l| edges_of(l).iter().any(|(p, q)| Line::new(*p, *q).dist(m) <= snap * 10.0)) + }; + if face.iter().all(|f| edges_of(f).iter().all(|(a, z)| on_hatch(*a, *z))) { + return Err(no_cut()); + } + // Every candidate edge: the hatch's loops split where the face's corners touch them, and the + // face's own edges. + let corners: Vec = face.iter().flatten().copied().collect(); + let mut cand: Vec<(Vec2, Vec2)> = Vec::new(); + for l in &loops { + for (a, z) in edges_of(l) { + split_at(a, z, &corners, snap, &mut cand); + if cand.len() > MAX_EDGES { + return Err(EngineError::Other("The hatch is too complex to trim.".into())); + } + } + } + cand.extend(face.iter().flat_map(|f| edges_of(f))); + // Keep the edges with the area left on exactly one side, turned to have it on the left. + let off = size * 1e-6; + let left_over = |p: Vec2| in_hatch(p) && !in_face(p); + let mut kept: Vec<(Vec2, Vec2)> = Vec::new(); + for (a, z) in cand { + let d = (z - a).normalized(); + let m = (a + z) * 0.5; + let nrm = Vec2::new(-d.y, d.x) * off; + let (l, r) = (left_over(m + nrm), left_over(m - nrm)); + if l == r { + continue; + } + let e = if l { (a, z) } else { (z, a) }; + // The same piece of boundary twice (a loop edge that is also a face edge). + if kept.iter().any(|(p, q)| p.near(e.0, snap) && q.near(e.1, snap)) { + continue; + } + kept.push(e); + } + let outlines = chain(kept, snap * 10.0); + if outlines.is_empty() { + return Ok((None, face)); + } + let depth = |i: usize, l: &[Vec2]| { + let Some(p) = l.first().zip(l.get(1)).map(|(a, z)| (*a + *z) * 0.5) else { return 0 }; + outlines.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count() + }; + let new_loops: Vec = outlines + .iter() + .enumerate() + .map(|(i, l)| HatchLoop { vertices: l.iter().map(|p| PolyVertex::new(*p)).collect(), outer: depth(i, l) == 0, sources: Vec::new() }) + .collect(); + let out = Hatch { loops: new_loops, associative: false, style: 0, ..h.clone() }; + Ok((Some(EntityKind::Hatch(out)), face)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square(lo: f64, hi: f64) -> HatchLoop { + let vertices = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + HatchLoop { vertices, outer: true, sources: Vec::new() } + } + + fn hatch(loops: Vec) -> Hatch { + Hatch { + pattern: "SOLID".into(), + solid: true, + loops, + scale: 1.0, + angle: 0.0, + associative: true, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + } + } + + fn area(k: &EntityKind) -> f64 { + let EntityKind::Hatch(h) = k else { return f64::NAN }; + let ls = cadcraft_render::hatch_fill_loops(h, 1e-3); + // Odd-parity area by sampling. + let mut n = 0; + for i in 0..200 { + for j in 0..200 { + let p = Vec2::new(-1.0 + i as f64 * 0.06 + 0.03, -1.0 + j as f64 * 0.06 + 0.03); + if ls.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1 { + n += 1; + } + } + } + f64::from(n) * 0.06 * 0.06 + } + + #[test] + fn a_line_across_a_hatch_trims_the_picked_half() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(4.0, -5.0), Vec2::new(4.0, 15.0)))]; + let (left, face) = trim_hatch(&h, &cut, Vec2::new(2.0, 5.0)).unwrap(); + let left = left.unwrap(); + assert!((area(&left) - 60.0).abs() < 1.0, "{}", area(&left)); + let EntityKind::Hatch(lh) = &left else { panic!() }; + assert!(!lh.associative); + assert!(face.first().is_some_and(|f| f.iter().all(|p| p.x <= 4.0 + 1e-6))); + } + + #[test] + fn a_hole_cut_out_of_a_hatch() { + let h = hatch(vec![square(0.0, 10.0)]); + // A closed square of cutting edges inside the hatch: picking inside it takes it out. + let c = [(3.0, 3.0), (6.0, 3.0), (6.0, 6.0), (3.0, 6.0), (3.0, 3.0)]; + let cut: Vec = c.windows(2).map(|w| Segment::Line(Line::new(Vec2::new(w[0].0, w[0].1), Vec2::new(w[1].0, w[1].1)))).collect(); + let (left, _) = trim_hatch(&h, &cut, Vec2::new(4.5, 4.5)).unwrap(); + assert!((area(&left.unwrap()) - 91.0).abs() < 1.0); + } + + #[test] + fn no_cutting_edge_no_trim() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(20.0, 0.0), Vec2::new(20.0, 10.0)))]; + assert!(trim_hatch(&h, &cut, Vec2::new(5.0, 5.0)).is_err()); + } + + #[test] + fn hostile_hatches_do_not_panic() { + let h = hatch(vec![HatchLoop { vertices: vec![PolyVertex::new(Vec2::new(f64::NAN, 0.0))], outer: true, sources: Vec::new() }]); + let _ = trim_hatch(&h, &[], Vec2::ZERO); + let h = hatch(Vec::new()); + let _ = trim_hatch(&h, &[], Vec2::ZERO); + } +} diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 29aca81ef5..b9791a704e 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -2,16 +2,16 @@ //! (TRIMEXTENDMODE), cutting/boundary edges, Fence, Crossing, Project (PROJMODE), Edge (EDGEMODE), //! eRase and Undo. The geometry of one trim or extend is in modify.rs. -use std::sync::Arc; +use std::sync::{Arc, Mutex}; -use cadcraft_doc::{Drawing, EntityKind, Handle}; -use cadcraft_geom::{Bounds2, Line, Vec2, line_line}; +use cadcraft_doc::{Drawing, EntityKind, Handle, Space}; +use cadcraft_geom::{Bounds2, Line, PolyVertex, Segment, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, extend, trim}; +use super::modify::{Edges, edge_segments_owned, extend, extend_result, prim_to_segments, trim, trim_result}; use super::{bad, point_param, points_param}; -use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; +use crate::{Accept, EngineError, Glow, Input, Interactive, Prompt, Result, Session, Step}; /// Most fence points the JSON form takes. const MAX_FENCE: usize = 10_000; @@ -231,6 +231,12 @@ enum Stage { Erase(Vec), } +/// The cutting (boundary) edges of one drawing and space, kept while the cursor moves: the +/// drawing (by address), the space, whether edges are implied, and the edges with their objects. +type EdgeCache = (usize, Space, bool, Arc>); +/// The last glow worked out: the drawing (by address), the cursor and the result. +type GlowCache = (usize, (u64, u64), Option); + pub(crate) struct TrimM { extend: bool, /// Cutting/boundary edges; `None`: all objects. @@ -238,11 +244,159 @@ pub(crate) struct TrimM { stage: Stage, /// The drawing before each trim, extend or erase, for Undo. undo: Vec>, + edge_cache: Mutex>, + glow_cache: Mutex>, +} + +/// Samples along an object when finding the part of it a trim takes away or an extend adds. +const GLOW_SAMPLES: f64 = 512.0; + +/// The parts of `orig` that `others` don't run along, as open polylines: what a trim takes away +/// (`others` the pieces left) or an extend adds (`orig` the extended object, `others` it before). +fn uncovered(orig: &EntityKind, others: &[EntityKind]) -> Vec { + let segs: Vec = orig.prims().iter().flat_map(prim_to_segments).collect(); + let total: f64 = segs.iter().map(Segment::len).sum(); + if !total.is_finite() || total <= 0.0 { + return Vec::new(); + } + let other: Vec = others.iter().flat_map(|k| k.prims()).flat_map(|p| prim_to_segments(&p)).collect(); + let tol = total * 2e-4; + let covered = |p: Vec2| other.iter().any(|sg| sg.closest(p).dist(p) <= tol); + let step = total / GLOW_SAMPLES; + let mut out: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + let flush = |cur: &mut Vec, out: &mut Vec>| { + if cur.len() >= 2 { + out.push(std::mem::take(cur)); + } else { + cur.clear(); + } + }; + for sg in &segs { + let len = sg.len(); + if !len.is_finite() || len <= 0.0 { + continue; + } + if cur.last().is_some_and(|l| !l.near(sg.at(0.0), tol)) { + flush(&mut cur, &mut out); + } + let n = (len / step).ceil().clamp(1.0, 4096.0) as usize; + let mut prev: Option<(f64, bool)> = None; + for i in 0..=n { + let t = i as f64 / n as f64; + let c = covered(sg.at(t)); + if let Some((pt, pc)) = prev + && pc != c + { + // Where coverage changes between the samples. + let (mut lo, mut hi) = (pt, t); + for _ in 0..20 { + let mid = (lo + hi) * 0.5; + if covered(sg.at(mid)) == pc { + lo = mid; + } else { + hi = mid; + } + } + let x = sg.at((lo + hi) * 0.5); + // The transition lies `tol` off the end of the piece that covers the rest: snap + // to that end. + let x = other + .iter() + .flat_map(|o| [o.at(0.0), o.at(1.0)]) + .filter(|e| e.dist(x) <= 3.0 * tol) + .min_by(|a, b| a.dist(x).total_cmp(&b.dist(x))) + .unwrap_or(x); + if c { + cur.push(x); + flush(&mut cur, &mut out); + } else { + cur.push(x); + } + } + if !c { + cur.push(sg.at(t)); + } + prev = Some((t, c)); + } + if prev.is_some_and(|(_, c)| c) { + flush(&mut cur, &mut out); + } + } + flush(&mut cur, &mut out); + out.into_iter().map(|pts| lwpoly(pts.into_iter().map(PolyVertex::new).collect(), false)).collect() } impl TrimM { pub(crate) fn new(extend: bool) -> Self { - TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new() } + TrimM { extend, edges: None, stage: Stage::Pick, undo: Vec::new(), edge_cache: Mutex::new(None), glow_cache: Mutex::new(None) } + } + /// The cutting (boundary) edges with their objects, from the cache while the drawing is the + /// same. + fn cached_edges(&self, s: &Session, implied: bool) -> Option>> { + let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; + let space = s.space(); + let mut cache = self.edge_cache.lock().ok()?; + if let Some((d, sp, i, e)) = cache.as_ref() + && *d == doc + && *sp == space + && *i == implied + { + return Some(e.clone()); + } + let e = Arc::new(edge_segments_owned(s, Edges { only: self.edges.as_deref(), implied }).ok()?); + *cache = Some((doc, space, implied, e.clone())); + Some(e) + } + /// What a pick at `c` would trim away or extend by. + fn work_out_glow(&self, s: &Session, c: Vec2) -> Option { + let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5; + let space = s.space(); + let d = s.doc().ok()?; + let h = crate::select::pick(d, &space, c, ap)?; + if super::curves::is_locked(s, h) { + return None; + } + let quick = quick_mode(s); + let implied = !quick && edge_mode(s); + let edges = self.cached_edges(s, implied)?; + let cut: Vec = edges.iter().filter(|(o, _)| *o != h).map(|(_, sg)| *sg).collect(); + if self.extend { + let (e, new) = extend_result(s, h, c, &cut).ok()?; + let kinds = uncovered(&new, std::slice::from_ref(&e.kind)); + return (!kinds.is_empty()).then_some(Glow { kinds, removing: false }); + } + let kinds = match trim_result(s, h, c, &cut) { + Ok((e, pieces)) => match &e.kind { + EntityKind::Hatch(hatch) => { + let (_, face) = super::trim_hatch::trim_hatch(hatch, &cut, c).ok()?; + // The outline of the part taken away, and the part filled. + let mut out: Vec = face.iter().map(|l| lwpoly(l.iter().copied().map(PolyVertex::new).collect(), true)).collect(); + let loops = face + .into_iter() + .map(|l| cadcraft_doc::HatchLoop { + vertices: l.into_iter().map(PolyVertex::new).collect(), + outer: false, + sources: Vec::new(), + }) + .collect(); + out.push(EntityKind::Hatch(cadcraft_doc::Hatch { + pattern: "SOLID".into(), + solid: true, + loops, + gradient: None, + style: 0, + ..hatch.clone() + })); + out + } + k => uncovered(k, &pieces), + }, + // A Quick-mode trim of an object no edge crosses erases all of it. + Err(err) if quick && misses_edges(&err) => vec![d.entity(h)?.kind.clone()], + Err(_) => return None, + }; + (!kinds.is_empty()).then_some(Glow { kinds, removing: true }) } fn edges(&self, quick: bool, implied: bool) -> Edges<'_> { Edges { only: self.edges.as_deref(), implied: !quick && implied } @@ -397,6 +551,13 @@ impl Interactive for TrimM { } } fn input(&mut self, s: &mut Session, i: Input) -> Result { + // Edges and settings may change: work the glow out afresh. + if let Ok(c) = self.edge_cache.get_mut() { + *c = None; + } + if let Ok(c) = self.glow_cache.get_mut() { + *c = None; + } let quick = quick_mode(s); let implied = edge_mode(s); let extending = self.extend; @@ -554,6 +715,25 @@ impl Interactive for TrimM { }, } } + fn glow(&self, s: &Session, c: Vec2) -> Option { + if self.stage != Stage::Pick { + return None; + } + let doc = Arc::as_ptr(&s.state().ok()?.doc) as usize; + let key = (c.x.to_bits(), c.y.to_bits()); + if let Ok(cache) = self.glow_cache.lock() + && let Some((d, k, g)) = cache.as_ref() + && *d == doc + && *k == key + { + return g.clone(); + } + let g = self.work_out_glow(s, c); + if let Ok(mut cache) = self.glow_cache.lock() { + *cache = Some((doc, key, g.clone())); + } + g + } fn preview(&self, _s: &Session, c: Vec2) -> Vec { match &self.stage { Stage::Fence(pts) if !pts.is_empty() => pts diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index ec980cb0a9..e88db724f2 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -75,6 +75,15 @@ impl Interactive for Guarded { Vec::new() }) } + fn glow(&self, s: &Session, cursor: Vec2) -> Option { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.glow(s, cursor))).unwrap_or_else(|_| { + self.broken.set(Some("panic in preview")); + None + }) + } fn drag(&self, s: &Session, cursor: Vec2) -> Option { if self.broken.get().is_some() { return None; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 12ea824e24..16e4bd9ec3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,7 +45,7 @@ pub use cadcraft_geom as geom; pub use cadcraft_render as render; pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices}; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; -pub use prompt::{Accept, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor}; +pub use prompt::{Accept, Drag, EditorKind, Glow, Input, Interactive, Picker, Prompt, Step, TextEditor}; #[derive(Debug, thiserror::Error)] pub enum EngineError { @@ -1430,6 +1430,18 @@ impl Session { kinds.into_iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k }).collect() } + /// What the active command shows glowing under the cursor ([`Interactive::glow`]), as + /// entities with the current properties, and whether it is what a pick would take away. + pub fn glow(&self, cursor: Vec2) -> Option<(Vec, bool)> { + if self.lisp_prompt().is_some() { + return None; + } + let r = self.running.as_ref()?; + let g = r.machine.glow(self, cursor)?; + let common = self.current_common(); + Some((g.kinds.into_iter().map(|k| Entity { handle: Handle(0), common: common.clone(), kind: k }).collect(), g.removing)) + } + /// The active command's preview as a transform of existing objects (see /// [`Interactive::drag`]), with its extra rubber-band geometry as entities. pub fn drag(&self, cursor: Vec2) -> Option<(Drag, Vec)> { diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index 9995bcd5e7..19a3f35a36 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -209,6 +209,11 @@ pub trait Interactive: Send { fn preview(&self, _s: &Session, _cursor: Vec2) -> Vec { Vec::new() } + /// Geometry shown glowing under the cursor: what picking there would take away or add + /// (TRIM, EXTEND), drawn over the drawing as a highlight. + fn glow(&self, _s: &Session, _cursor: Vec2) -> Option { + None + } /// The preview as existing objects under one transform, when it is that (MOVE, COPY, /// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding /// the transformed copies every frame; `None` falls back to [`Interactive::preview`]. @@ -255,6 +260,14 @@ pub enum EditorKind { TableCell { name: String }, } +/// See [`Interactive::glow`]. +#[derive(Clone, Debug, PartialEq)] +pub struct Glow { + pub kinds: Vec, + /// The geometry is what a pick takes away (a trim), not what it adds (an extend). + pub removing: bool, +} + /// See [`Interactive::drag`]. #[derive(Clone, Debug)] pub struct Drag { diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index c565cf8c76..21dc681257 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -23,9 +23,18 @@ pub fn env(s: &crate::Session) -> Env { /// The measurement a dimension shows (for `<>` in its formula). pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { - let plain = cadcraft_doc::Dimension { text: String::new(), block: None, marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, ..dm.clone() }; + let plain = cadcraft_doc::Dimension { + text: String::new(), + block: None, + marks: cadcraft_doc::DimMarks { formula: None, ..dm.marks.clone() }, + ..dm.clone() + }; let v = cadcraft_render::dimension_in(d, &plain).value; - let s: String = v.chars().skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.').take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')).collect(); + let s: String = v + .chars() + .skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.') + .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')) + .collect(); s.replace(' ', "").replace(',', ".").parse().ok() } @@ -107,4 +116,3 @@ pub fn refresh(d: &mut Drawing, env: &Env) -> usize { } n } - diff --git a/crates/engine/tests/trim_extend_options.rs b/crates/engine/tests/trim_extend_options.rs index 43aa722d9d..60d1e6f80b 100644 --- a/crates/engine/tests/trim_extend_options.rs +++ b/crates/engine/tests/trim_extend_options.rs @@ -248,3 +248,69 @@ fn a_pick_in_empty_space_draws_a_fence_line_and_trims_what_it_crosses() { with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (0.0, 2.0)), ((10.0, 0.0), (15.0, 0.0)), ((10.0, 2.0), (15.0, 2.0))]) ); } + +/// The glow under the cursor: its polylines' points (rounded). +fn glow_points(s: &Session, at: (f64, f64)) -> Option<(Vec>, bool)> { + let (ents, removing) = s.glow(cadcraft_engine::geom::Vec2::new(at.0, at.1))?; + let pts = ents + .iter() + .filter_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect()) } else { None }) + .collect(); + Some((pts, removing)) +} + +#[test] +fn trim_glows_the_part_a_pick_takes_away() { + let mut s = ladder(); + s.cmdline("TRIM").unwrap(); + let (pts, removing) = glow_points(&s, (5.0, 0.0)).expect("a glow over the line"); + assert!(removing); + assert_eq!(pts.len(), 1); + let run = &pts[0]; + let (lo, hi) = run.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + assert!((lo - 0.0).abs() < 1e-3 && (hi - 10.0).abs() < 1e-3, "{lo} {hi}"); + assert!(run.iter().all(|p| p.1 == 0.0)); + // Nothing under the cursor: no glow. Nothing changes in the drawing. + assert!(s.glow(cadcraft_engine::geom::Vec2::new(5.0, 30.0)).is_none()); + assert_eq!(lines(&s).len(), 4); +} + +#[test] +fn extend_glows_the_part_a_pick_adds() { + let mut s = session(&["0,0 5,0", "10,-5 10,5"]); + s.cmdline("EXTEND").unwrap(); + let (pts, removing) = glow_points(&s, (4.0, 0.0)).expect("a glow over the line"); + assert!(!removing); + let (lo, hi) = pts.iter().flatten().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.0), hi.max(p.0))); + assert!((lo - 5.0).abs() < 1e-2 && (hi - 10.0).abs() < 1e-3, "{lo} {hi}"); +} + +#[test] +fn trim_cuts_a_hatch_area() { + use cadcraft_engine::doc::{Common, Hatch, HatchLoop, Space}; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let mut s = session(&["4,-5 4,15"]); + let vertices = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + s.execute("trim", &json!({ "handle": h.hex(), "pick": [2.0, 5.0] })).unwrap(); + let left: Vec<_> = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).collect(); + assert_eq!(left.len(), 1); + let xs: Vec = left[0].loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p.x)).collect(); + assert!(xs.iter().all(|x| *x >= 4.0 - 1e-6), "{xs:?}"); + assert!(xs.iter().any(|x| (*x - 10.0).abs() < 1e-6)); +} diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index 7de0222d1b..6d6af6adb7 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -419,7 +419,11 @@ fn post(template: &str, meas: &str) -> String { /// The first number in a formatted measurement (`R12.5` → 12.5, `1 250,5` → 1250.5). fn measured_number(base: &str) -> Option { - let s: String = base.chars().skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.').take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')).collect(); + let s: String = base + .chars() + .skip_while(|c| !c.is_ascii_digit() && *c != '-' && *c != '.') + .take_while(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | ' ')) + .collect(); s.replace(' ', "").replace(',', ".").parse().ok() } diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs index c2f2ccbb43..053d963dad 100644 --- a/crates/render/src/textformula.rs +++ b/crates/render/src/textformula.rs @@ -9,7 +9,6 @@ //! The functions are listed in [`FUNCTIONS`] (name, arguments, description), which the editor's //! completion list and Help show. - /// Longest formula worked out. const MAX_LEN: usize = 2000; /// Deepest nesting. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a04e8850f0..9ec7e5f554 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1621,6 +1621,16 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.hover_at = None; } + // What a pick would trim away or extend by (TRIM, EXTEND) glows instead of the whole object + // under the cursor highlighting. + let glow = match (app.canvas.cursor, app.session.prompting()) { + (Some(c), true) => app.session.glow(c), + _ => None, + }; + if glow.is_some() { + app.canvas.hover = None; + } + // ---------- paint ---------- painter.rect_filled(rect, 0.0, t.canvas); let t0 = crate::now_ms(); @@ -1807,6 +1817,21 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } crate::dyngrips::draw(app, &painter, &xf, rect, hover_pos); } + // What a pick would trim away or extend by (TRIM, EXTEND), glowing under the cursor. + if let Some((ents, removing)) = glow + && let Ok(st) = app.session.state() + { + let list = rebuilt_preview(&st.doc, ents.iter(), scale); + let all: Vec = (0..list.prims.len()).collect(); + // The halo around lines only; a filled area (a hatch) is tinted once. + let lines: Vec = + all.iter().copied().filter(|&i| list.prims.get(i).is_some_and(|p| !matches!(p.kind, Kind::Tris | Kind::Mask))).collect(); + let col = if removing { Color32::from_rgb(0xff, 0x5a, 0x3c) } else { Color32::from_rgb(0x3c, 0xc8, 0xff) }; + for (width, alpha) in [(11.0, 0.12), (7.0, 0.22)] { + draw_highlight(&painter, &xf, &list, &lines, col.gamma_multiply(alpha), Look { width, dashed: false }); + } + draw_highlight(&painter, &xf, &list, &all, col, Look { width: 2.0, dashed: false }); + } // Rubber band preview of the active command. // `xf` is the space being edited: paper space, or model space inside the active viewport. let drag = match (app.canvas.cursor, app.canvas.gpu.is_some()) { diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index fc4c63dfab..2922375163 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -239,13 +239,11 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } ui.add_space(6.0); let mac = ui.ctx().os().is_mac(); - let tip = |undo: bool| { - match (undo, mac) { - (true, true) => crate::tl!("Undo (⌘Z)"), - (true, false) => crate::tl!("Undo (Ctrl+Z)"), - (false, true) => crate::tl!("Redo (⇧⌘Z)"), - (false, false) => crate::tl!("Redo (Ctrl+Y)"), - } + let tip = |undo: bool| match (undo, mac) { + (true, true) => crate::tl!("Undo (⌘Z)"), + (true, false) => crate::tl!("Undo (Ctrl+Z)"), + (false, true) => crate::tl!("Redo (⇧⌘Z)"), + (false, false) => crate::tl!("Redo (Ctrl+Y)"), }; for (undo, icon) in [(true, crate::icons::Icon::Undo), (false, crate::icons::Icon::Redo)] { let any = if undo { !st.undo.is_empty() } else { !st.redo.is_empty() }; From d0b9b2a84181c1d99971c3a1e222a4cc346d4195 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 19:36:32 +0300 Subject: [PATCH 15/23] b16: dimension style previews use the drawing's arrow blocks, text styles and linetypes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/dimstyles.rs | 59 ++++++++++++++++++++++++++++----- 1 file changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dimstyles.rs b/crates/ui-egui/src/dimstyles.rs index 23b735f18f..bcacb9a90e 100644 --- a/crates/ui-egui/src/dimstyles.rs +++ b/crates/ui-egui/src/dimstyles.rs @@ -780,8 +780,24 @@ thread_local! { /// The preview drawing of `st`: a part with linear, aligned, radius and angular dimensions in /// that style, sized to its text height. -fn build_preview(st: &DimStyle) -> Option { +fn build_preview(st: &DimStyle, src: Option<&cadcraft_doc::Drawing>) -> Option { let mut s = cadcraft_engine::Session::new(); + // The drawing's own blocks (user arrowheads), text styles (fonts), linetypes and layers, so + // the preview draws the style as the drawing's dimensions are drawn. + if let Some(src) = src + && let Ok(d) = s.doc_mut() + { + d.blocks = src.blocks.clone(); + d.text_styles = src.text_styles.clone(); + d.linetypes = src.linetypes.clone(); + d.layers = src.layers.iter().map(|l| cadcraft_doc::Layer { frozen: false, on: true, ..l.clone() }).collect(); + d.handseed = d.handseed.max(src.handseed); + for k in ["LTSCALE", "PSLTSCALE", "MEASUREMENT", "INSUNITS", "DIMASSOC"] { + if let Some(v) = src.header.get(k) { + d.header.set(k, v.clone()); + } + } + } let mut fields = style_map(st); fields.insert("name".into(), json!("Preview")); fields.insert("current".into(), json!(true)); @@ -790,11 +806,11 @@ fn build_preview(st: &DimStyle) -> Option { let th = st.text_height * if st.scale > 0.0 { st.scale } else { 1.0 }; let f = if th.is_finite() && th > 0.0 { th / 0.18 } else { 1.0 }; let p = |x: f64, y: f64| json!([x * f, y * f]); - let _ = s.execute("layer.new", &json!({ "name": "Part", "color": 40, "current": true })); + let _ = s.execute("layer.new", &json!({ "name": "CADCraft preview part", "color": 40, "current": true })); let outline = [(0.0, 0.0), (3.0, 0.0), (2.0, 1.7), (1.0, 1.7), (1.0, 2.2), (0.0, 2.2), (0.0, 0.0)]; s.execute("line", &json!({ "points": outline.iter().map(|(x, y)| p(*x, *y)).collect::>() })).ok()?; let circle = s.execute("circle", &json!({ "center": p(0.55, 0.85), "radius": 0.4 * f })).ok()?; - let _ = s.execute("layer.new", &json!({ "name": "Dims", "color": 7, "current": true })); + let _ = s.execute("layer.new", &json!({ "name": "CADCraft preview dims", "color": 7, "current": true })); let _ = s.execute("dimlinear", &json!({ "p1": p(0.0, 2.2), "p2": p(1.0, 2.2), "at": p(0.5, 2.75) })); let _ = s.execute("dimlinear", &json!({ "p1": p(0.0, 0.0), "p2": p(0.0, 2.2), "at": p(-0.55, 1.1) })); let _ = s.execute("dimaligned", &json!({ "p1": p(3.0, 0.0), "p2": p(2.0, 1.7), "at": p(3.05, 1.2) })); @@ -807,18 +823,18 @@ fn build_preview(st: &DimStyle) -> Option { } /// Draw the preview of `st` in a `size` box. -pub fn preview(ui: &mut egui::Ui, st: &DimStyle, size: egui::Vec2) { +pub fn preview(ui: &mut egui::Ui, st: &DimStyle, size: egui::Vec2, src: Option<&cadcraft_doc::Drawing>) { let t = Tokens::get(); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); let p = ui.painter_at(rect); p.rect_filled(rect, 2.0, t.canvas); - let key = serde_json::to_string(st).unwrap_or_default(); + let key = format!("{:p}{}", src.map_or(std::ptr::null(), |d| d as *const _), serde_json::to_string(st).unwrap_or_default()); let list = PREVIEWS.with(|c| { let mut c = c.borrow_mut(); if c.len() > 64 { c.clear(); } - c.entry(key).or_insert_with(|| build_preview(st)).clone() + c.entry(key).or_insert_with(|| build_preview(st, src)).clone() }); let Some(list) = list else { return }; let b = list.bounds; @@ -913,6 +929,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { *open = false; return; }; + // The drawing the previews take user arrowheads, text styles and linetypes from. + let src = app.session.state().ok().map(|s| s.doc.clone()); + let src = src.as_deref(); let mut st: State = ctx.data(|m| m.get_temp(state_id())).unwrap_or_default(); let current = d.header.str("DIMSTYLE", "Standard"); let used = styles_in_use(d); @@ -1013,7 +1032,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { // Preview and description. ui.vertical(|ui| { ui.label(format!("{} {sel}", crate::tl!("Preview of:"))); - preview(ui, &sel_style, vec2(320.0, 230.0)); + preview(ui, &sel_style, vec2(320.0, 230.0), src); ui.add_space(4.0); ui.label(crate::tl!("Description")); egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(6.0).show(ui, |ui| { @@ -1185,7 +1204,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { ); }); ui.vertical(|ui| { - preview(ui, &map_style(&ed.style), vec2(300.0, 240.0)); + preview(ui, &map_style(&ed.style), vec2(300.0, 240.0), src); if ed.mode == Mode::Override { ui.label(RichText::new(crate::tl!("Overrides apply to new dimensions in the current style.")).small().color(t.text_dim)); } @@ -1312,3 +1331,27 @@ fn show_value(v: Option<&Value>) -> String { Some(v) => v.to_string(), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A user arrowhead (a block of the drawing) shows in the preview: a big square block as + /// both arrows adds geometry the built-in arrowheads don't have. + #[test] + fn the_preview_draws_the_drawings_user_arrowheads() { + let mut s = cadcraft_engine::Session::new(); + let r = s.execute("rectang", &json!({ "p1": [-0.5, -0.5], "p2": [0.5, 0.5] })).unwrap(); + let h = r["handle"].as_str().unwrap().to_string(); + s.execute("block", &json!({ "name": "MYARROW", "base": [0, 0], "handles": [h], "keep": "delete" })).unwrap(); + let mut st = s.doc().unwrap().dim_style("Standard").cloned().unwrap(); + st.apply_fields(&serde_json::Map::from_iter([("arrowBlock".to_string(), json!("MYARROW"))])); + let plain = build_preview(&st, None).unwrap(); + let with = build_preview(&st, Some(s.doc().unwrap())).unwrap(); + // The square arrows: closed polylines of five points in the preview drawn with the + // drawing's blocks, none without them. + let squares = + |l: &DisplayList| l.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Polyline) && l.points(p).len() == 5).count(); + assert!(squares(&with) > squares(&plain), "{} {}", squares(&with), squares(&plain)); + } +} From 6d117f903b35ca09a0824916c1b64bc16238b3cb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 19:49:20 +0300 Subject: [PATCH 16/23] b16: WHATS_NEW, text editing test opens selected Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 64 ++++++++++++++++++++++++++++ crates/ui-egui/tests/text_editing.rs | 2 + 2 files changed, 66 insertions(+) diff --git a/WHATS_NEW.md b/WHATS_NEW.md index a7555af6f1..692a7941e2 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,70 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 23.10.2026 (0.9.0-b16) + +### Русский + +**Окно редактирования текста** +- Когда открываете существующий текст, весь текст сразу выделен: можно сразу печатать новый. +- Отмена и возврат: кнопки со стрелками рядом с «ОК» и «Отмена», а также Ctrl+Z (отменить), Ctrl+Y и Ctrl+Shift+Z (вернуть). Текст, набранный без пауз, отменяется одним шагом, а не по одной букве. +- Над текстом курсор мыши становится текстовым (I-образным). + +**Формулы в размерах, выносках и многострочном тексте** +- Формулы теперь работают и при редактировании: в многострочном тексте, в тексте размера и в тексте выноски, а не только при создании нового текста. +- Формула работает, только если весь текст — одна строка, начинающаяся с «=». +- В размере знак <> в формуле означает сам измеренный размер. Например, =<>/2 у размера 1250 покажет 625, а =ROUND(<>/1000;2) покажет метры. При изменении геометрии значение пересчитывается. + +**Обрезать и Удлинить: подсветка того, что произойдёт** +- Во время команд «Обрезать» (TRIM) и «Удлинить» (EXTEND) наведите курсор на объект. Часть, которая будет удалена, светится красным. Часть, которая будет добавлена, светится голубым. Так видно заранее, что сделает щелчок. +- В быстром режиме объект, который ничто не пересекает, удаляется целиком. В этом случае светится весь объект. + +**Обрезка штриховки** +- «Обрезать» теперь работает и со штриховкой. Линии, пересекающие штриховку, делят её на части. Щелчок по части удаляет её из штриховки, остальное остаётся. Как и в AutoCAD, после обрезки штриховка перестаёт быть ассоциативной. +- При наведении удаляемая часть штриховки подсвечивается красной заливкой. +- Дуги в контуре обрезанной штриховки заменяются короткими отрезками. + +**Командная строка** +- Последние команды над командной строкой показываются только при наведении мыши на командную строку. Раньше они были видны всегда. + +**Подсказки к инструментам** +- В подсказке у каждой кнопки инструмента теперь есть короткое описание того, что делает команда (на русском, английском и украинском). + +**Диспетчер размерных стилей: правильный предпросмотр** +- Предпросмотр берёт из чертежа пользовательские стрелки (блоки), текстовые стили со шрифтами и типы линий. Раньше пользовательские стрелки (например, засечки в стилях «1-50», «1-100» чертежа «אריה צוק») в предпросмотре заменялись обычными стрелками. + +### English + +**Text editing window** +- Editing existing text opens it fully selected, so you can type over it right away. +- Undo and redo: arrow buttons next to OK and Cancel, plus Ctrl+Z (undo) and Ctrl+Y or Ctrl+Shift+Z (redo). Text typed without a pause is undone in one step, not letter by letter. +- The mouse pointer becomes a text (I-beam) cursor over the text. + +**Formulas in dimensions, leaders and multiline text** +- Formulas now also work when editing multiline text, dimension text and leader text, not only when creating new text. +- A formula works only if the whole text is one line starting with "=". +- In a dimension, <> in a formula stands for the measured value. For example, =<>/2 on a 1250 dimension shows 625, and =ROUND(<>/1000;2) shows meters. The value updates when the geometry changes. + +**Trim and Extend: see what will happen** +- During TRIM and EXTEND, hover over an object. The part that will be removed glows red. The part that will be added glows blue. You see the result before you click. +- In Quick mode an object that nothing crosses is erased entirely. In that case the whole object glows. + +**Trimming hatches** +- TRIM now works on hatches. Lines crossing a hatch split it into parts. Clicking a part removes it from the hatch, and the rest stays. As in AutoCAD, the trimmed hatch is no longer associative. +- On hover, the part to be removed is highlighted with a red fill. +- Arcs in a trimmed hatch's boundary are replaced by short straight segments. + +**Command line** +- Recent commands above the command line now appear only while the mouse is over the command line. Before, they were always visible. + +**Tool tooltips** +- Each tool button's tooltip now includes a short description of what the command does (in Russian, English and Ukrainian). + +**Dimension Style Manager: correct preview** +- The preview now uses the drawing's own user arrowheads (blocks), text styles with their fonts, and linetypes. Before, user arrowheads (for example, the ticks in the "1-50" and "1-100" styles of the "אריה צוק" drawing) were replaced with plain arrows in the preview. + +--- + ## 23.10.2026 (0.9.0-b15) ### Русский diff --git a/crates/ui-egui/tests/text_editing.rs b/crates/ui-egui/tests/text_editing.rs index ad132c88ee..6eb27eec07 100644 --- a/crates/ui-egui/tests/text_editing.rs +++ b/crates/ui-egui/tests/text_editing.rs @@ -56,6 +56,8 @@ fn one_line_of_text_is_edited_in_place_and_enter_finishes() { app.session.input(Input::Point(cadcraft_geom::Vec2::new(0.5, 0.5))).unwrap(); }); assert_eq!(h.state().session.text_editor().map(|e| e.kind), Some(EditorKind::Line)); + // The text opens selected: End goes past it, then the typing adds to it. + key(&mut h, Key::End, Modifiers::NONE); type_text(&mut h, " B"); key(&mut h, Key::Enter, Modifiers::NONE); assert!(h.state().session.running.is_none(), "{}", h.state().session.prompt_text()); From 6d7f91a3d8a3e9b2e664d1ed3d59f08efca9c8f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 09:58:05 +0300 Subject: [PATCH 17/23] b17: HATCH pick points near the view with boundary warnings, select objects from open curves, blocks as cutting edges, hatch edge picks trim Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- WHATS_NEW.md | 42 +++ crates/engine/src/cmd/hatch.rs | 378 +++++++++++++++++++-- crates/engine/src/cmd/hatch/pick.rs | 91 +++-- crates/engine/src/cmd/modify.rs | 12 + crates/engine/src/cmd/trim_hatch.rs | 45 ++- crates/engine/src/lib.rs | 36 +- crates/engine/src/tests.rs | 3 +- crates/engine/tests/trim_extend_options.rs | 32 ++ crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/notices.rs | 51 +++ crates/ui-egui/src/theme.rs | 3 + 13 files changed, 652 insertions(+), 57 deletions(-) create mode 100644 crates/ui-egui/src/notices.rs diff --git a/WHATS_NEW.md b/WHATS_NEW.md index 692a7941e2..ab79e11c66 100644 --- a/WHATS_NEW.md +++ b/WHATS_NEW.md @@ -8,6 +8,48 @@ Please try what is described here and tell us what doesn't work as expected, wha --- +## 24.10.2026 (0.9.0-b17) + +### Русский + +**Штриховка: «Добавить: Указать точки»** +- Контур вокруг указанной точки теперь находится и в больших чертежах. Раньше в поиске участвовали все 17 тысяч объектов чертежа, и в «אריה צוק» контур часто не находился. Теперь, как в AutoCAD, контур ищется среди объектов на экране и рядом с ним. +- Текст, размеры и рамки вокруг блоков и выносок больше не мешают. Раньше прямоугольник вокруг текста выноски или вокруг блока мог разрезать комнату или ящик пополам. Теперь блоки и выноски ограничивают штриховку только своими линиями. +- Если область вокруг точки не замкнута, появляется окно «Штриховка — ошибка определения контура» с объяснением, и ничего не создаётся. +- Если найденный контур уходит далеко за пределы экрана (обычно это значит, что в границе есть разрыв и область «вытекла» наружу), появляется такое же окно с предупреждением. Если область действительно большая, уменьшите масштаб, чтобы она была видна целиком, и укажите точку ещё раз. + +**Штриховка: «Добавить: Выбрать объекты»** +- Выбранные объекты подсвечиваются, пока выбор не закончен. +- Теперь подходят не только замкнутые полилинии и окружности, но и отрезки, дуги и незамкнутые полилинии, которые вместе образуют замкнутую область. Их можно выбирать по одному: например, четыре отрезка, образующих прямоугольник. Выступающие концы на углах не мешают. +- Пока выбранные объекты ещё не замыкают область, в командной строке написано «не ограничивают область». Если нажать Enter, появится окно с предупреждением, а команда подождёт недостающие объекты. +- Если часть выбранных объектов не участвует в контуре, штриховка создаётся по остальным, и появляется предупреждение. + +**Обрезка штриховки** +- Линии внутри блоков теперь тоже служат режущими кромками, для штриховки и для любых других объектов. Раньше блоки при обрезке не учитывались, поэтому в чертежах, где стенки и полки нарисованы блоками, «Обрезать» не находило пересечений и в быстром режиме удаляло штриховку целиком. +- Щелчок по краю штриховки обрезает часть, прилегающую к этому месту. Раньше такой щелчок удалял штриховку целиком. +- Штриховка удаляется целиком, только когда её действительно ничто не пересекает. Линия, которая заходит в штриховку и обрывается внутри, не делит её на части, как и в AutoCAD. + +### English + +**Hatch: Add: Pick points** +- The boundary around a picked point is now found in large drawings too. Before, all 17,000 objects of the drawing took part in the search, and in "אריה צוק" the boundary was often not found. Now, as in AutoCAD, the boundary is looked for among the objects on screen and near it. +- Text, dimensions, and the boxes around blocks and leaders no longer get in the way. Before, the box around a leader's text or around a block could cut a room or a drawer in two. Now blocks and leaders bound a hatch only with their own lines. +- If the area around the point is not closed, a "Hatch - Boundary Definition Error" window explains it, and nothing is created. +- If the boundary found reaches far outside the screen (usually a gap that let the area run out), the same window warns about it. If the area really is that large, zoom out to show all of it and pick again. + +**Hatch: Add: Select objects** +- The selected objects are highlighted while you select. +- Not only closed polylines and circles work now, but also lines, arcs and open polylines that together form a closed area. You can pick them one by one, for example four lines forming a rectangle. Ends running past the corners don't matter. +- While the selected objects don't close an area yet, the command line says "not enclosing an area yet". Pressing Enter shows a warning window, and the command waits for the missing objects. +- If some of the selected objects take no part in the boundary, the hatch is made from the others, with a warning. + +**Trimming hatches** +- Lines inside blocks now also act as cutting edges, for hatches and for any other object. Before, blocks were ignored by TRIM, so in drawings where walls and shelves are blocks, TRIM found no crossings and in Quick mode erased the whole hatch. +- Clicking the edge of a hatch trims the part next to that spot. Before, such a click erased the whole hatch. +- A hatch is erased entirely only when nothing crosses it. A line that enters a hatch and ends inside it does not split it, as in AutoCAD. + +--- + ## 23.10.2026 (0.9.0-b16) ### Русский diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 600bbf528a..ca70143139 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -21,13 +21,13 @@ pub use pick::{HatchPicks, PickMode}; pub fn specs() -> Vec { vec![ - CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects), pattern?: \"ANSI31\", scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION), background?: colour | \"None\"} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), + CommandSpec::new("hatch", "Hatch...", run_hatch).menu(&["Draw", "Hatch..."]).alias(&["h", "bh", "-hatch"]).params("{points?: [[x,y]] (internal points) and/or handles?: [hex] (closed objects, or objects that together enclose an area), pattern?: \"ANSI31\", scale?, angle? (degrees), associative? (HPASSOC), separate? (HPSEPARATE: a hatch per point/object), origin?: [x,y] (HPORIGIN) | originMode?: \"current\"|\"bottomLeft\"|\"bottomRight\"|\"topLeft\"|\"topRight\"|\"center\" (HPORIGINMODE), style?: \"normal\"|\"outer\"|\"ignore\" (HPISLANDDETECTION), background?: colour | \"None\"} — gaps up to HPGAPTOL close").interactive(|s| Ok(Box::new(HatchM::new(s, false)))), CommandSpec::new("gradient", "Gradient...", run_gradient).menu(&["Draw", "Gradient..."]).alias(&["gd"]).params("{points? and/or handles?, name?: \"LINEAR\"|\"CYLINDER\"|\"CURVED\"|\"SPHERICAL\"|\"HEMISPHERICAL\" or INV… (colours swapped), color1?, color2?, angle? (degrees), centered? (default true)}").interactive(|s| Ok(Box::new(HatchM::new(s, true)))), CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"), CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], style?, background?: colour | \"None\", origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick) - .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") + .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects, or objects that together enclose an area)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") .enabled(has_doc) .noundo() .interactive(|_| Ok(Box::new(pick::HatchPickM::default()))), @@ -35,11 +35,13 @@ pub fn specs() -> Vec { } /// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each -/// with the handle of the object it came from. +/// with the handle of the object it came from: only the objects reaching into `near` when given, +/// tessellated finely enough for that area. fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec>, Vec) { let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) }; let ext = d.extents(space); - let tol = (ext.width() + ext.height()).max(1e-9) / 20000.0; + let area = near.unwrap_or(ext); + let tol = (area.width() + area.height()).max(1e-9) / 20000.0; let mut out = Vec::new(); let mut owners = Vec::new(); for e in store.iter() { @@ -62,7 +64,27 @@ fn outlines(d: &Drawing, space: &Space, near: Option) -> (Vec /// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous /// box around the extents `ext`. fn object_polys(d: &Drawing, e: &Entity, tol: f64, ext: Bounds2) -> Vec> { - let mut polys = crate::select::hit_polylines(d, e, tol); + let mut polys = match &e.kind { + // Text and annotation never bound a hatch: their boxes would cut areas in two. + EntityKind::Text(_) + | EntityKind::MText(_) + | EntityKind::AttDef(_) + | EntityKind::Dimension(_) + | EntityKind::Tolerance(_) + | EntityKind::Hatch(_) + | EntityKind::Image(_) => return Vec::new(), + // Blocks, multileaders and tables bound by the lines they draw, not by the box around + // them, and not by their text. + EntityKind::Insert(_) | EntityKind::MLeader(_) | EntityKind::Table(_) => { + let list = cadcraft_render::build_entities( + d, + std::iter::once(e), + &cadcraft_render::Options { tolerance: tol, text: false, fill: false, ..Default::default() }, + ); + return list.prims.iter().filter(|p| matches!(p.kind, cadcraft_render::Kind::Polyline)).map(|p| list.points(p).to_vec()).collect(); + } + _ => crate::select::hit_polylines(d, e, tol), + }; if matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_)) { let r = (ext.width() + ext.height()).max(1.0) * 4.0; for pl in &mut polys { @@ -197,17 +219,60 @@ pub(crate) fn island_style(t: &str) -> Option { } } -/// Boundary loops (outer + islands) around an internal point. +/// The title of the window that explains why a boundary wasn't found. +pub(crate) const BOUNDARY_ERROR: &str = "Hatch - Boundary Definition Error"; + +/// Boundary loops (outer + islands) around an internal point. With a view on screen around the +/// point, the boundary is looked for among the objects in and near the view (as AutoCAD does), +/// and a boundary reaching far outside it is refused: it is almost always a gap that let the +/// area run out into the rest of the drawing. pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { + loops_near(s, p, false) +} + +/// [`loops_at`] for a pick on screen (`picked`): a boundary reaching far outside the view is +/// refused. Otherwise (scripts, JSON) the whole space is searched when the boundary runs out of +/// the area around the view. +pub(crate) fn loops_picked(s: &Session, p: Vec2) -> Result> { + loops_near(s, p, true) +} + +fn loops_near(s: &Session, p: Vec2, picked: bool) -> Result> { + let near = s.view_box().filter(|v| v.contains(p)).map(|v| v.expand(v.width().max(v.height()) * 0.5)); + match loops_in(s, p, near) { + Err(e) if !picked && near.is_some() => loops_in(s, p, None).map_err(|_| e), + r => r, + } +} + +/// Boundary loops around `p` among the objects reaching into `near` (all objects when `None`). +fn loops_in(s: &Session, p: Vec2, near: Option) -> Result> { let d = s.doc()?; let space = s.space(); let ext = d.extents(&space); let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9); - let (polys, owners) = outlines(d, &space, None); - let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d)) - .ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?; + let (polys, owners) = outlines(d, &space, near); + let segments: usize = polys.iter().map(|pl| pl.len().saturating_sub(1)).sum(); + if segments > cadcraft_geom::region::MAX_SEGMENTS { + return Err(EngineError::Other( + "There are too many objects in the view to find the boundary. Zoom in closer to the area to hatch and pick again.".into(), + )); + } + let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d)).ok_or_else(|| { + EngineError::Other( + "Valid hatch boundary not found: the area around the picked point is not closed. Close the gaps in its boundary and pick again.".into(), + ) + })?; let outer = found.outer; let ob = Bounds2::from_points(outer.iter().copied()); + if let Some(n) = near + && !n.contains_box(&ob) + { + return Err(EngineError::Other( + "The boundary around the picked point reaches far outside the visible area. The area is probably not closed: check its boundary for gaps, or zoom out to show the whole area and pick again." + .into(), + )); + } let sources = handles_of(&owners, &found.outer_sources); let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, sources }]; // Islands: closed objects entirely inside the outer loop that don't contain the pick point. @@ -243,18 +308,132 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result> { Ok(loops) } +/// Most open objects whose shared boundary is traced in one selection. +const MAX_OPEN_OBJECTS: usize = 2000; + +/// Boundary loops from selected objects: each closed object is a loop; open objects (lines, +/// arcs, open polylines…) that together enclose an area make a loop of their outline, as many +/// as there are separate groups of them. Groups that enclose nothing are left out; when nothing +/// at all encloses an area, the selection is refused. pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result> { + loops_from_selection(s, hs).map(|(l, _)| l) +} + +/// [`loops_from_handles`] with the selected objects that were left out (enclosing nothing). +pub(crate) fn loops_from_selection(s: &Session, hs: &[Handle]) -> Result<(Vec, Vec)> { let d = s.doc()?; let mut loops = Vec::new(); + let mut open: Vec = Vec::new(); + let mut left_out: Vec = Vec::new(); for h in hs { - if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) { + let Some(e) = d.entity(*h) else { continue }; + if let Some(vs) = closed_loop(d, e) { loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), sources: vec![*h] }); + } else if island_curve(d, e) { + if !open.contains(h) { + open.push(*h); + } + } else if !left_out.contains(h) { + left_out.push(*h); + } + } + if open.len() > MAX_OPEN_OBJECTS { + return Err(EngineError::Other(format!("Select at most {MAX_OPEN_OBJECTS} open objects for one boundary."))); + } + if !open.is_empty() { + let space = s.space(); + let ext = d.extents(&space); + let b = open.iter().filter_map(|h| d.entity(*h)).fold(Bounds2::EMPTY, |b, e| b.union(&entity_bounds(d, e, 0))); + let size = (b.width() + b.height()).max(1e-9); + let ttol = size / 20000.0; + let polys: Vec<(Handle, Vec)> = + open.iter().filter_map(|h| d.entity(*h)).flat_map(|e| object_polys(d, e, ttol, ext).into_iter().map(move |pl| (e.handle, pl))).collect(); + let tol = (size * 1e-9).max(1e-9); + let gap = gap_tolerance(d); + for group in touching_groups(&polys, (tol * 100.0).max(gap)) { + let pls: Vec> = group.iter().filter_map(|&i| polys.get(i).map(|(_, pl)| pl.clone())).collect(); + let mut sources: Vec = group.iter().filter_map(|&i| polys.get(i).map(|(h, _)| *h)).collect(); + sources.sort_unstable(); + sources.dedup(); + match cadcraft_geom::region::outline(&pls, tol, gap).filter(|o| o.len() >= 3) { + Some(outline) => { + loops.push(HatchLoop { vertices: outline.into_iter().map(PolyVertex::new).collect(), outer: loops.is_empty(), sources }) + } + None => left_out.extend(sources), + } } } if loops.is_empty() { - return Err(EngineError::Other("No closed boundary objects selected.".into())); + let msg = if left_out.is_empty() { + "No boundary objects selected: select closed objects, or objects that together enclose an area." + } else { + "The selected objects don't enclose an area: together they must form a closed boundary. Select the missing objects or close the gaps." + }; + return Err(EngineError::Other(msg.into())); } - Ok(loops) + Ok((loops, left_out)) +} + +/// The warning for selected objects left out of a hatch because they enclose nothing. +pub(crate) const LEFT_OUT: &str = + "Some of the selected objects don't enclose an area and were left out of the hatch. Together, objects must form a closed boundary."; + +/// Groups of polylines that touch or cross each other (directly or through others), as indices. +fn touching_groups(polys: &[(Handle, Vec)], tol: f64) -> Vec> { + let n = polys.len(); + let mut parent: Vec = (0..n).collect(); + fn root(parent: &mut [usize], mut i: usize) -> usize { + while let Some(&p) = parent.get(i) { + if p == i { + break; + } + let gp = parent.get(p).copied().unwrap_or(p); + if let Some(slot) = parent.get_mut(i) { + *slot = gp; + } + i = p; + } + i + } + let bounds: Vec = polys.iter().map(|(_, pl)| Bounds2::from_points(pl.iter().copied()).expand(tol)).collect(); + let touch = |a: &[Vec2], b: &[Vec2]| { + a.windows(2).any(|wa| { + let (Some(a0), Some(a1)) = (wa.first(), wa.get(1)) else { return false }; + let la = cadcraft_geom::Line::new(*a0, *a1); + b.windows(2).any(|wb| { + let (Some(b0), Some(b1)) = (wb.first(), wb.get(1)) else { return false }; + let lb = cadcraft_geom::Line::new(*b0, *b1); + cadcraft_geom::line_line(&la, &lb).is_some() + || la.dist(*b0) <= tol + || la.dist(*b1) <= tol + || lb.dist(*a0) <= tol + || lb.dist(*a1) <= tol + }) + }) + }; + for i in 0..n { + for j in (i + 1)..n { + let (Some(bi), Some(bj)) = (bounds.get(i), bounds.get(j)) else { continue }; + if !bi.intersects(bj) { + continue; + } + let (Some((_, pi)), Some((_, pj))) = (polys.get(i), polys.get(j)) else { continue }; + if touch(pi, pj) { + let (ri, rj) = (root(&mut parent, i), root(&mut parent, j)); + if ri != rj + && let Some(slot) = parent.get_mut(ri) + { + *slot = rj; + } + } + } + } + let mut groups: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for i in 0..n { + let r = root(&mut parent, i); + groups.entry(r).or_default().push(i); + } + groups.into_values().collect() } /// Gradient fills by name: the shapes the renderer draws (`render/src/hatch.rs`); the INV forms @@ -555,6 +734,11 @@ struct HatchM { asking: Option, /// "Select objects" mode instead of "Pick internal point"; the next HATCH starts in it again. selecting: bool, + /// The boundary objects selected so far (highlighted): their loops are traced together, so + /// lines selected one by one can close an area between them. + objects: Vec, + /// The loops of `objects`, when they enclose an area yet (for the preview). + object_loops: Vec, } impl HatchM { @@ -565,6 +749,8 @@ impl HatchM { loops: Vec::new(), asking: None, selecting: s.last_used.hatch_select, + objects: Vec::new(), + object_loops: Vec::new(), } } fn set_mode(&mut self, s: &mut Session, selecting: bool) { @@ -572,9 +758,40 @@ impl HatchM { s.last_used.hatch_select = selecting; } fn finish(&mut self, s: &mut Session) -> Result { + if !self.objects.is_empty() { + match loops_from_selection(s, &self.objects) { + Ok((l, left_out)) => { + if !left_out.is_empty() { + s.notice(BOUNDARY_ERROR, LEFT_OUT); + } + if self.settings.separate { + self.loops.extend(l.into_iter().map(|l| vec![HatchLoop { outer: true, ..l }])); + } else { + self.loops.push(l); + } + } + Err(e) => { + // Stay: more objects can still close the area. + s.notice(BOUNDARY_ERROR, e.to_string()); + return Ok(Step::Continue); + } + } + } + s.set_selection(Vec::new()); add_hatches(s, &self.settings, std::mem::take(&mut self.loops))?; Ok(Step::Done) } + /// Add selected boundary objects: they show highlighted, and their loops are traced again. + fn add_objects(&mut self, s: &mut Session, hs: Vec) { + for h in hs { + if !self.objects.contains(&h) { + self.objects.push(h); + } + } + s.set_selection(self.objects.clone()); + self.object_loops = loops_from_handles(s, &self.objects).unwrap_or_default(); + s.echo(format!("{} object(s) selected{}", self.objects.len(), if self.object_loops.is_empty() { ", not enclosing an area yet" } else { "" })); + } fn set_origin(&mut self, s: &mut Session, origin: Option, mode: OriginMode) -> Result<()> { let h = &mut s.doc_mut()?.header; if let Some(o) = origin.filter(|o| o.is_finite()) { @@ -698,34 +915,33 @@ impl Interactive for HatchM { } match i { Input::Point(p) if !self.selecting => { - match loops_at(s, p) { + match loops_picked(s, p) { Ok(l) => { s.echo(format!("Analyzing the selected data... {} loop(s)", l.len())); self.loops.push(l); } - Err(e) => s.echo(e.to_string()), + Err(e) => s.notice(BOUNDARY_ERROR, e.to_string()), } Ok(Step::Continue) } Input::Pick(hs) => { - match loops_from_handles(s, &hs) { - Ok(l) => { - s.echo(format!("{} found", hs.len())); - if self.settings.separate { - self.loops.extend(l.into_iter().map(|l| vec![HatchLoop { outer: true, ..l }])); - } else { - self.loops.push(l); - } - } - Err(e) => s.echo(e.to_string()), - } + self.add_objects(s, hs); Ok(Step::Continue) } + Input::Cancel => { + s.set_selection(Vec::new()); + Ok(Step::Cancel) + } Input::Keyword(k) => { match k.as_str() { "Select objects" => self.set_mode(s, true), "picK internal point" => self.set_mode(s, false), - "Undo" => self.loops.clear(), + "Undo" => { + self.loops.clear(); + self.objects.clear(); + self.object_loops.clear(); + s.set_selection(Vec::new()); + } "Pattern" | "seTtings" => self.asking = Some(HatchAsk::Pattern), "sCale" => self.asking = Some(HatchAsk::Scale), "Angle" => self.asking = Some(HatchAsk::Angle), @@ -750,10 +966,11 @@ impl Interactive for HatchM { } } fn preview(&self, _s: &Session, _c: Vec2) -> Vec { - if self.loops.is_empty() { + let loops: Vec = self.loops.iter().flatten().chain(self.object_loops.iter()).cloned().collect(); + if loops.is_empty() { return Vec::new(); } - vec![self.settings.hatch(self.loops.iter().flatten().cloned().collect())] + vec![self.settings.hatch(loops)] } } @@ -930,4 +1147,109 @@ mod tests { let (_, hg) = only_hatch(&s); assert_eq!(hg.loops.len(), 1, "gradient with repeated picks in same region must deduplicate loops"); } + + fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap() + } + + #[test] + fn selected_lines_that_close_an_area_bound_a_hatch() { + let mut s = Session::new(); + // A square of four lines running past each other at the corners. + let hs = vec![ + line(&mut s, [-2.0, 0.0], [12.0, 0.0]), + line(&mut s, [10.0, -2.0], [10.0, 12.0]), + line(&mut s, [12.0, 10.0], [-2.0, 10.0]), + line(&mut s, [0.0, 12.0], [0.0, -2.0]), + ]; + let hex: Vec = hs.iter().map(|h| h.hex()).collect(); + s.execute("hatch", &json!({ "handles": hex, "pattern": "SOLID" })).unwrap(); + let (_, h) = only_hatch(&s); + assert_eq!(h.loops.len(), 1); + let b = Bounds2::from_points(h.loops[0].vertices.iter().map(|v| v.p)); + assert!(b.min.near(Vec2::new(0.0, 0.0), 1e-6) && b.max.near(Vec2::new(10.0, 10.0), 1e-6), "{b:?}"); + let mut src = h.loops[0].sources.clone(); + src.sort_unstable(); + let mut want = hs.clone(); + want.sort_unstable(); + assert_eq!(src, want); + } + + #[test] + fn selected_lines_that_leave_a_gap_are_refused() { + let mut s = Session::new(); + let hs = [line(&mut s, [0.0, 0.0], [10.0, 0.0]), line(&mut s, [10.0, 0.0], [10.0, 10.0]), line(&mut s, [10.0, 10.0], [0.0, 10.0])]; + let hex: Vec = hs.iter().map(|h| h.hex()).collect(); + let e = s.execute("hatch", &json!({ "handles": hex })).unwrap_err().to_string(); + assert!(e.contains("don't enclose an area"), "{e}"); + } + + #[test] + fn select_objects_highlights_them_and_warns_when_they_dont_close() { + let mut s = Session::new(); + let a = line(&mut s, [0.0, 0.0], [10.0, 0.0]); + let b = line(&mut s, [10.0, 0.0], [10.0, 10.0]); + let c = line(&mut s, [10.0, 10.0], [0.0, 10.0]); + let d = line(&mut s, [0.0, 10.0], [0.0, 0.0]); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Keyword("Select objects".into())).unwrap(); + s.input(Input::Pick(vec![a])).unwrap(); + s.input(Input::Pick(vec![b, c])).unwrap(); + assert_eq!(s.selection(), &[a, b, c]); + // Three lines: Enter warns in a window and the command waits for more. + s.input(Input::Enter).unwrap(); + assert!(s.running.is_some()); + assert_eq!(s.notices.len(), 1); + assert_eq!(s.notices[0].title, BOUNDARY_ERROR); + s.notices.clear(); + s.input(Input::Pick(vec![d])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + assert!(s.selection().is_empty()); + let (_, h) = only_hatch(&s); + assert_eq!(h.loops.len(), 1); + } + + #[test] + fn a_pick_in_an_open_area_warns_and_creates_nothing() { + let mut s = Session::new(); + line(&mut s, [0.0, 0.0], [10.0, 0.0]); + line(&mut s, [10.0, 0.0], [10.0, 10.0]); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + assert_eq!(s.notices.len(), 1); + assert!(s.notices[0].message.contains("not closed"), "{}", s.notices[0].message); + } + + #[test] + fn a_boundary_far_outside_the_view_is_refused() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10000, 10000] })).unwrap(); + // A small window on screen inside the big rectangle. + s.execute("zoom", &json!({ "mode": "window", "p1": [100, 100], "p2": [110, 110] })).unwrap(); + s.cmdline("-HATCH").unwrap(); + s.input(Input::Point(Vec2::new(105.0, 105.0))).unwrap(); + assert!(s.notices.first().is_some_and(|n| n.message.contains("far outside the visible area")), "{:?}", s.notices); + s.cancel(); + // Zoomed out to show it, the same pick hatches; a script's pick isn't refused. + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + s.execute("hatch", &json!({ "points": [[105, 105]] })).unwrap(); + s.execute("zoom", &json!({ "mode": "window", "p1": [100, 100], "p2": [110, 110] })).unwrap(); + s.execute("hatch", &json!({ "points": [[105, 105]] })).unwrap(); + } + + #[test] + fn text_and_block_boxes_do_not_bound_a_hatch() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 50] })).unwrap(); + // A multileader whose text box crosses the room. + s.execute("mleader", &json!({ "points": [[50, 25], [130, 25]], "text": "Glass glass glass glass" })).unwrap(); + s.execute("text", &json!({ "at": [-20, 20], "text": "A very long label running into the room", "height": 5.0 })).unwrap(); + s.execute("zoom", &json!({ "mode": "extents" })).unwrap(); + s.execute("hatch", &json!({ "points": [[20, 10]], "pattern": "SOLID" })).unwrap(); + let (_, h) = only_hatch(&s); + let b = Bounds2::from_points(h.loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + assert!(b.min.near(Vec2::new(0.0, 0.0), 1e-6) && b.max.near(Vec2::new(100.0, 50.0), 1e-6), "{b:?}"); + } } diff --git a/crates/engine/src/cmd/hatch/pick.rs b/crates/engine/src/cmd/hatch/pick.rs index b5fc607c26..fa10ea12e9 100644 --- a/crates/engine/src/cmd/hatch/pick.rs +++ b/crates/engine/src/cmd/hatch/pick.rs @@ -6,7 +6,7 @@ use cadcraft_doc::{EntityKind, Handle, HatchLoop}; use cadcraft_geom::Vec2; use serde_json::{Value, json}; -use super::{HatchSettings, closed_loop, loops_at, loops_from_handles}; +use super::{BOUNDARY_ERROR, HatchSettings, LEFT_OUT, loops_at, loops_from_handles, loops_from_selection, loops_picked}; use crate::cmd::{bad, points_param, targets}; use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; @@ -73,13 +73,8 @@ pub(super) fn run_hatchpick(s: &mut Session, p: &Value) -> Result { if hs.len() > MAX_PICKS { return Err(bad("hatchpick", format!("at most {MAX_PICKS} objects"))); } - let d = s.doc()?; - for h in hs { - match d.entity(h) { - Some(e) if closed_loop(d, e).is_some() => picks.handles.push(h), - _ => return Err(bad("hatchpick", format!("{} is not a closed object", h.hex()))), - } - } + let (loops, _) = loops_from_selection(s, &hs).map_err(|e| bad("hatchpick", e.to_string()))?; + picks.handles = hs.into_iter().filter(|h| loops.iter().any(|l| l.sources.contains(h))).collect(); if picks.points.is_empty() { picks.mode = PickMode::Objects; } @@ -102,6 +97,8 @@ enum Pick { pub(super) struct HatchPickM { mode: Option, picks: Vec, + /// The loops of all the objects picked so far, traced together (for the preview). + object_loops: Vec, } impl HatchPickM { @@ -114,6 +111,21 @@ impl HatchPickM { }) .sum() } + fn objects(&self) -> Vec { + let mut out: Vec = Vec::new(); + for p in &self.picks { + if let Pick::Objects(hs, _) = p { + out.extend(hs.iter().copied().filter(|h| !out.contains(h)).collect::>()); + } + } + out + } + /// Show the picked objects highlighted and trace their loops again. + fn objects_changed(&mut self, s: &mut Session) { + let all = self.objects(); + s.set_selection(all.clone()); + self.object_loops = if all.is_empty() { Vec::new() } else { loops_from_handles(s, &all).unwrap_or_default() }; + } fn keep(&self, s: &mut Session, mode: PickMode) { let mut out = HatchPicks { mode, ..HatchPicks::default() }; for p in &self.picks { @@ -149,14 +161,48 @@ impl Interactive for HatchPickM { return Ok(Step::Continue); }; match (mode, i) { - (_, Input::Cancel) => Ok(Step::Cancel), + (_, Input::Cancel) => { + if mode == PickMode::Objects { + s.set_selection(Vec::new()); + } + Ok(Step::Cancel) + } (PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => { if self.picks.pop().is_none() { s.echo("Nothing to undo."); } + if mode == PickMode::Objects { + self.objects_changed(s); + } Ok(Step::Continue) } - (PickMode::Points | PickMode::Objects, Input::Enter) => { + (PickMode::Objects, Input::Enter) => { + let all = self.objects(); + // Only the objects that bound an area are kept. + let mut used: Vec = Vec::new(); + if !all.is_empty() { + match loops_from_selection(s, &all) { + Ok((loops, left_out)) => { + if !left_out.is_empty() { + s.notice(BOUNDARY_ERROR, LEFT_OUT); + } + used = all.into_iter().filter(|h| loops.iter().any(|l| l.sources.contains(h))).collect(); + } + Err(e) => { + // Stay: more objects can still close the area. + s.notice(BOUNDARY_ERROR, e.to_string()); + return Ok(Step::Continue); + } + } + } + s.set_selection(Vec::new()); + self.keep(s, mode); + if let Some(p) = s.hatch_picks.as_mut() { + p.handles = used; + } + Ok(Step::Done) + } + (PickMode::Points, Input::Enter) => { self.keep(s, mode); Ok(Step::Done) } @@ -165,27 +211,29 @@ impl Interactive for HatchPickM { s.echo(format!("At most {MAX_PICKS} picks.")); return Ok(Step::Continue); } - match loops_at(s, q) { + match loops_picked(s, q) { Ok(l) => { s.echo(format!("Analyzing the selected data... {} loop(s)", l.len())); self.picks.push(Pick::Point(q, l)); } - Err(e) => s.echo(e.to_string()), + Err(e) => s.notice(BOUNDARY_ERROR, e.to_string()), } Ok(Step::Continue) } (PickMode::Objects, Input::Pick(hs)) => { let room = MAX_PICKS.saturating_sub(self.count()); - let closed: Vec = { - let d = s.doc()?; - hs.iter().copied().filter(|h| d.entity(*h).is_some_and(|e| closed_loop(d, e).is_some())).take(room).collect() - }; - let others = hs.len().saturating_sub(closed.len()); - if !closed.is_empty() { - let loops = loops_from_handles(s, &closed)?; - self.picks.push(Pick::Objects(closed.clone(), loops)); + let known = self.objects(); + let new: Vec = hs.into_iter().filter(|h| !known.contains(h)).take(room).collect(); + if !new.is_empty() { + self.picks.push(Pick::Objects(new, Vec::new())); } - s.echo(if others == 0 { format!("{} found", closed.len()) } else { format!("{} found, {others} not closed", closed.len()) }); + self.objects_changed(s); + let n = self.objects().len(); + s.echo(if self.object_loops.is_empty() { + format!("{n} object(s) selected, not enclosing an area yet") + } else { + format!("{n} object(s) selected, {} loop(s)", self.object_loops.len()) + }); Ok(Step::Continue) } (PickMode::Origin, Input::Point(q)) => { @@ -215,6 +263,7 @@ impl Interactive for HatchPickM { .flat_map(|p| match p { Pick::Point(_, l) | Pick::Objects(_, l) => l.iter().cloned(), }) + .chain(self.object_loops.iter().cloned()) .collect(); if loops.is_empty() { return Vec::new(); diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index d5da608660..18d83695a5 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -807,6 +807,18 @@ pub(crate) fn edge_segments_owned(s: &Session, edges: Edges) -> Result Result<(Opti } } let in_hatch = |p: Vec2| loops.iter().filter(|l| point_in_polygon(l, p)).count() % 2 == 1; - if !in_hatch(pick) { - return Err(no_cut()); - } + // A pick on the hatch's edge (the hatch is picked along its boundary too) trims the part + // just inside it. + let pick = if in_hatch(pick) { + pick + } else { + [1e-3, 3e-3, 1e-2, 3e-2] + .iter() + .flat_map(|r| (0..16).map(move |k| Vec2::polar(pick, size * r, std::f64::consts::TAU * f64::from(k) / 16.0))) + .find(|q| in_hatch(*q)) + .ok_or_else(|| EngineError::Other("Pick the hatch inside its area.".into()))? + }; // The cutting edges near the hatch, as polylines. let near = bounds.expand(size * 0.01); let mut cuts: Vec> = Vec::new(); @@ -132,7 +140,8 @@ pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Opti }) .collect(); polys.extend(cuts); - let b = region::boundary_at(&polys, pick, tol.max(size * 1e-7)).ok_or_else(no_cut)?; + let b = region::boundary_at(&polys, pick, tol.max(size * 1e-7)) + .ok_or_else(|| EngineError::Other("Could not work out the part of the hatch to trim.".into()))?; let snap = size * 1e-7; let face: Vec> = std::iter::once(b.outer.clone()) .chain(b.islands.iter().map(|i| i.outline.clone())) @@ -276,4 +285,32 @@ mod tests { let h = hatch(Vec::new()); let _ = trim_hatch(&h, &[], Vec2::ZERO); } + + #[test] + fn walls_along_the_hatch_boundary_do_not_stop_the_trim() { + // The hatch fills a room whose walls run along its boundary and past its corners; a + // line crosses the room. + let h = hatch(vec![square(0.0, 10.0)]); + let l = |a: (f64, f64), b: (f64, f64)| Segment::Line(Line::new(Vec2::new(a.0, a.1), Vec2::new(b.0, b.1))); + let cut = [ + l((-5.0, 0.0), (15.0, 0.0)), + l((10.0, -5.0), (10.0, 15.0)), + l((15.0, 10.0), (-5.0, 10.0)), + l((0.0, 15.0), (0.0, -5.0)), + // A wall piece covering part of an edge only. + l((2.0, 0.0), (6.0, 0.0)), + l((4.0, -5.0), (4.0, 15.0)), + ]; + let (left, _) = trim_hatch(&h, &cut, Vec2::new(2.0, 5.0)).unwrap(); + assert!((area(&left.unwrap()) - 60.0).abs() < 1.0); + } + + #[test] + fn a_pick_on_the_hatch_edge_trims_the_part_inside() { + let h = hatch(vec![square(0.0, 10.0)]); + let cut = [Segment::Line(Line::new(Vec2::new(4.0, -5.0), Vec2::new(4.0, 15.0)))]; + // On the left edge of the hatch. + let (left, _) = trim_hatch(&h, &cut, Vec2::new(0.0, 5.0)).unwrap(); + assert!((area(&left.unwrap()) - 60.0).abs() < 1.0); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 16e4bd9ec3..58adf165d1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -678,6 +678,16 @@ pub struct Session { lisp_last: Option>, /// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks). pub hatch_picks: Option, + /// Warnings a command shows in a window (a hatch boundary that isn't closed): the UI shows + /// the first one and takes it off when it is closed. + pub notices: Vec, +} + +/// A warning shown in a window ([`Session::notices`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notice { + pub title: String, + pub message: String, } impl Default for Session { @@ -726,6 +736,7 @@ impl Session { lisp: lisp::LispState::default(), lisp_last: None, hatch_picks: None, + notices: Vec::new(), } } pub fn new_drawing(&mut self, metric: bool) -> usize { @@ -815,6 +826,15 @@ impl Session { } /// Message on the command line history. + /// Show a warning in a window (and on the command line). + pub fn notice(&mut self, title: impl Into, message: impl Into) { + let message = message.into(); + self.echo(message.clone()); + if self.notices.len() < 8 { + self.notices.push(Notice { title: title.into(), message }); + } + } + pub fn echo(&mut self, msg: impl Into) { let m = msg.into(); log::debug!("{m}"); @@ -865,6 +885,16 @@ impl Session { } /// World units per pixel at the current view. + /// The area of the space being edited shown on screen (the canvas, or the active viewport's + /// model view), or `None` without a drawing. + pub fn view_box(&self) -> Option { + let v = self.state().ok()?.view(); + let h = v.height; + let w = h * self.viewport_px.0.max(1.0) / self.viewport_px.1.max(1.0); + let b = cadcraft_geom::Bounds2::new(v.center - Vec2::new(w, h) * 0.5, v.center + Vec2::new(w, h) * 0.5); + (w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0).then_some(b) + } + pub fn pixel_size(&self) -> f64 { let v = self.state().map(|s| s.view()).unwrap_or_default(); v.height / self.viewport_px.1.max(1.0) @@ -1281,9 +1311,9 @@ impl Session { } self.pending_window = None; self.select_mode = None; - // TRIM and EXTEND keep their edges selected (highlighted) while they run; they stay - // selected no longer than the command, however it ends. - if matches!(run.id.as_str(), "trim" | "extend") { + // TRIM and EXTEND keep their edges selected (highlighted) while they run, and HATCH its + // boundary objects; they stay selected no longer than the command, however it ends. + if matches!(run.id.as_str(), "trim" | "extend" | "hatch" | "gradient" | "hatchpick") { self.set_selection(Vec::new()); } let label = find_command(&run.id).map(|c| c.label).unwrap_or("Command"); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 93eba77019..c5aaac0274 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -872,8 +872,9 @@ fn hatch_pick_point_keeps_island_of_separate_lines() { } } } - // The interactive form finds the same island. + // The interactive form finds the same island (picked on screen, with the area in view). let mut s = square_hole_fixture(true); + s.execute("zoom", &json!({"mode": "extents"})).unwrap(); s.cmdline("hatch 2,2").unwrap(); s.cmdline("").unwrap(); let e = only_hatch(&s); diff --git a/crates/engine/tests/trim_extend_options.rs b/crates/engine/tests/trim_extend_options.rs index 60d1e6f80b..a0ee4e366a 100644 --- a/crates/engine/tests/trim_extend_options.rs +++ b/crates/engine/tests/trim_extend_options.rs @@ -314,3 +314,35 @@ fn trim_cuts_a_hatch_area() { assert!(xs.iter().all(|x| *x >= 4.0 - 1e-6), "{xs:?}"); assert!(xs.iter().any(|x| (*x - 10.0).abs() < 1e-6)); } + +#[test] +fn lines_inside_a_block_cut_a_hatch() { + use cadcraft_engine::doc::{Common, Hatch, HatchLoop, Space}; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let mut s = Session::new(); + // A block whose line crosses the hatch at x = 4. + let l = s.execute("line", &json!({ "points": [[4, -5], [4, 15]] })).unwrap()["handles"][0].as_str().unwrap().to_string(); + s.execute("block", &json!({ "name": "DIVIDER", "base": [0, 0], "handles": [l], "keep": "convert" })).unwrap(); + let vertices = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(); + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![HatchLoop { vertices, outer: true, sources: Vec::new() }], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let h = s.doc_mut().unwrap().add(&Space::Model, Common::default(), EntityKind::Hatch(hatch)).unwrap(); + // Quick mode: a hatch no edge crossed would be erased. + s.execute("trim", &json!({ "handle": h.hex(), "pick": [2.0, 5.0], "mode": "quick" })).unwrap(); + let left: Vec<_> = + s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).collect(); + assert_eq!(left.len(), 1, "trimmed, not erased"); + assert!(left[0].loops.iter().flat_map(|l| l.vertices.iter()).all(|v| v.p.x >= 4.0 - 1e-6)); +} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 22eae5b14a..21dd090af4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1600,3 +1600,10 @@ Keeps only the part 3D solids or regions share. Оставляет только общую часть 3D-тел или областей. Undo (Ctrl+Z) Отменить (Ctrl+Z) Redo (Ctrl+Y) Вернуть (Ctrl+Y) + Hatch - Boundary Definition Error Штриховка — ошибка определения контура + There are too many objects in the view to find the boundary. Zoom in closer to the area to hatch and pick again. На экране слишком много объектов, чтобы найти контур. Увеличьте область, которую нужно заштриховать, и укажите точку ещё раз. + Valid hatch boundary not found: the area around the picked point is not closed. Close the gaps in its boundary and pick again. Не найден правильный контур штриховки: область вокруг указанной точки не замкнута. Закройте разрывы в её границе и укажите точку ещё раз. + The boundary around the picked point reaches far outside the visible area. The area is probably not closed: check its boundary for gaps, or zoom out to show the whole area and pick again. Контур вокруг указанной точки уходит далеко за пределы видимой области. Скорее всего, область не замкнута: проверьте, нет ли разрывов в её границе, или уменьшите масштаб, чтобы область была видна целиком, и укажите точку ещё раз. + The selected objects don't enclose an area: together they must form a closed boundary. Select the missing objects or close the gaps. Выбранные объекты не ограничивают область: вместе они должны образовывать замкнутый контур. Выберите недостающие объекты или закройте разрывы. + No boundary objects selected: select closed objects, or objects that together enclose an area. Не выбраны объекты контура: выберите замкнутые объекты или объекты, которые вместе ограничивают область. + Some of the selected objects don't enclose an area and were left out of the hatch. Together, objects must form a closed boundary. Некоторые выбранные объекты не ограничивают область и не вошли в штриховку. Вместе объекты должны образовывать замкнутый контур. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5b77816643..e67ed1c3cc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1853,3 +1853,10 @@ Keeps only the part 3D solids or regions share. Залишає лише спільну частину 3D-тіл або областей. Undo (Ctrl+Z) Скасувати (Ctrl+Z) Redo (Ctrl+Y) Повернути (Ctrl+Y) + Hatch - Boundary Definition Error Штрихування — помилка визначення контуру + There are too many objects in the view to find the boundary. Zoom in closer to the area to hatch and pick again. На екрані забагато об'єктів, щоб знайти контур. Збільште область, яку потрібно заштрихувати, і вкажіть точку ще раз. + Valid hatch boundary not found: the area around the picked point is not closed. Close the gaps in its boundary and pick again. Не знайдено правильний контур штрихування: область навколо вказаної точки не замкнена. Закрийте розриви в її межі та вкажіть точку ще раз. + The boundary around the picked point reaches far outside the visible area. The area is probably not closed: check its boundary for gaps, or zoom out to show the whole area and pick again. Контур навколо вказаної точки виходить далеко за межі видимої області. Найімовірніше, область не замкнена: перевірте, чи немає розривів у її межі, або зменште масштаб, щоб область було видно повністю, і вкажіть точку ще раз. + The selected objects don't enclose an area: together they must form a closed boundary. Select the missing objects or close the gaps. Вибрані об'єкти не обмежують область: разом вони мають утворювати замкнений контур. Виберіть відсутні об'єкти або закрийте розриви. + No boundary objects selected: select closed objects, or objects that together enclose an area. Не вибрано об'єкти контуру: виберіть замкнені об'єкти або об'єкти, які разом обмежують область. + Some of the selected objects don't enclose an area and were left out of the hatch. Together, objects must form a closed boundary. Деякі вибрані об'єкти не обмежують область і не увійшли до штрихування. Разом об'єкти мають утворювати замкнений контур. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 390984fe45..b84022adc2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -43,6 +43,7 @@ pub mod icons; pub mod layers; pub mod managers; pub mod menus; +pub mod notices; pub mod opening; pub mod options; pub mod palettes; @@ -716,6 +717,7 @@ impl CadApp { closing::prompt(self, ui.ctx()); autosave::show(self, ui.ctx()); autosave::gpu_notice(self, ui.ctx()); + notices::show(self, ui.ctx()); self.frame_ms = now_ms() - t0; } diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs new file mode 100644 index 0000000000..3c7ea3ef4b --- /dev/null +++ b/crates/ui-egui/src/notices.rs @@ -0,0 +1,51 @@ +//! Warnings commands show in a window ([`cadcraft_engine::Session::notices`]): a hatch boundary +//! that isn't closed, selected objects that don't enclose an area. The first one shows until OK +//! closes it; the keys stay with the command line. + +use egui::vec2; + +use crate::CadApp; +use crate::theme::Tokens; + +pub fn show(app: &mut CadApp, ctx: &egui::Context) { + let Some(n) = app.session.notices.first().cloned() else { return }; + let t = Tokens::get(); + let mut close = false; + egui::Window::new(crate::i18n::t(&n.title)) + .id(egui::Id::new("cc_notice")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, -60.0)) + .show(ctx, |ui| { + ui.set_width(420.0); + ui.horizontal(|ui| { + // A warning triangle with an exclamation mark. + let (r, _) = ui.allocate_exact_size(vec2(30.0, 28.0), egui::Sense::hover()); + let p = ui.painter(); + let pts = vec![ + egui::pos2(r.center().x, r.top() + 1.0), + egui::pos2(r.right() - 1.0, r.bottom() - 1.0), + egui::pos2(r.left() + 1.0, r.bottom() - 1.0), + ]; + p.add(egui::Shape::convex_polygon(pts, t.warning, egui::Stroke::NONE)); + p.text( + egui::pos2(r.center().x, r.center().y + 3.0), + egui::Align2::CENTER_CENTER, + "!", + egui::FontId::proportional(17.0), + egui::Color32::BLACK, + ); + ui.add_space(6.0); + ui.add(egui::Label::new(crate::i18n::t(&n.message)).wrap()); + }); + ui.add_space(6.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("OK")).clicked() { + close = true; + } + }); + }); + if close { + app.session.notices.remove(0); + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 5b0f481e07..572b39de97 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -135,6 +135,8 @@ pub struct Tokens { /// Grips of dynamic block references (AutoCAD's GRIPDYNCOLOR). pub grip_dyn: Color32, pub snap: Color32, + /// The warning sign of notice windows. + pub warning: Color32, /// COMPARE: objects only in this drawing, only in the other one, and the areas of change. pub compare_this: Color32, pub compare_other: Color32, @@ -194,6 +196,7 @@ impl Tokens { grip_hot: Color32::from_rgb(0xff, 0x3b, 0x3b), grip_dyn: Color32::from_rgb(0x26, 0xc6, 0xe8), snap: Color32::from_rgb(0x2f, 0xd0, 0x62), + warning: Color32::from_rgb(0xf2, 0xb2, 0x33), compare_this: Color32::from_rgb(0x4c, 0xd9, 0x7b), compare_other: Color32::from_rgb(0xff, 0x5c, 0x5c), compare_area: Color32::from_rgb(0xff, 0xb4, 0x3c), From 4df9e7b5ac5408cb6fd008e8aabd1af4ae345096 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 10:07:57 +0300 Subject: [PATCH 18/23] b17: trim looks for cutting edges around the object only Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/modify.rs | 35 ++++++++++++++++++++++++----- crates/engine/src/cmd/trimextend.rs | 10 +++++---- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 18d83695a5..f093695ac7 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -783,16 +783,41 @@ pub(crate) struct Edges<'a> { /// All primitives of the cutting edges (excluding `exclude`). pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { - Ok(edge_segments_owned(s, edges)?.into_iter().filter(|(h, _)| *h != exclude).map(|(_, sg)| sg).collect()) + Ok(edge_segments_owned(s, edges, None)?.into_iter().filter(|(h, _)| *h != exclude).map(|(_, sg)| sg).collect()) } -/// [`edge_segments`] of every edge object, each with the object it comes from. -pub(crate) fn edge_segments_owned(s: &Session, edges: Edges) -> Result> { +/// The cutting edges a trim of `h` can meet: only the objects reaching its extents (all of them +/// with implied edges, which run on without end). +pub(crate) fn trim_edges(s: &Session, edges: Edges, h: Handle) -> Result> { + let d = s.doc()?; + let near = d.entity(h).map(|e| { + let b = cadcraft_doc::entity_bounds(d, e, 0); + b.expand((b.width() + b.height()) * 0.01 + 1e-6) + }); + Ok(edge_segments_owned(s, edges, near)?.into_iter().filter(|(o, _)| *o != h).map(|(_, sg)| sg).collect()) +} + +/// [`edge_segments`] of every edge object (only those reaching `near` when given), each with +/// the object it comes from. +pub(crate) fn edge_segments_owned(s: &Session, edges: Edges, near: Option) -> Result> { let d = s.doc()?; let space = s.space(); let store = d.space(&space).ok_or(EngineError::NoDocument)?; + let ix = near.filter(|n| !edges.implied && !n.is_empty()).and_then(|_| crate::spatial::index(d, &space)); + let picked: Option>> = match (&ix, near) { + (Some(ix), Some(n)) => ix.query(&n, true).map(|v| v.into_iter().filter_map(|i| ix.entity(i).cloned()).collect()), + _ => None, + }; + let all: Vec>; + let ents: &[std::sync::Arc] = match &picked { + Some(v) => v, + None => { + all = store.iter().cloned().collect(); + &all + } + }; let mut out = Vec::new(); - for e in store.iter() { + for e in ents { if !d.is_visible(e) { continue; } @@ -879,7 +904,7 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu if super::curves::is_locked(s, h) { return Err(EngineError::Other("The object is on a locked layer.".into())); } - let cut = edge_segments(s, edges, h)?; + let cut = trim_edges(s, edges, h)?; let (e, pieces) = trim_result(s, h, pick, &cut)?; let common = e.common.clone(); let space = s.space(); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index b9791a704e..8ae182114d 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -9,7 +9,7 @@ use cadcraft_geom::{Bounds2, Line, PolyVertex, Segment, Vec2, line_line}; use serde_json::{Value, json}; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{Edges, edge_segments_owned, extend, extend_result, prim_to_segments, trim, trim_result}; +use super::modify::{Edges, edge_segments_owned, extend, extend_result, prim_to_segments, trim, trim_edges, trim_result}; use super::{bad, point_param, points_param}; use crate::{Accept, EngineError, Glow, Input, Interactive, Prompt, Result, Session, Step}; @@ -344,7 +344,7 @@ impl TrimM { { return Some(e.clone()); } - let e = Arc::new(edge_segments_owned(s, Edges { only: self.edges.as_deref(), implied }).ok()?); + let e = Arc::new(edge_segments_owned(s, Edges { only: self.edges.as_deref(), implied }, None).ok()?); *cache = Some((doc, space, implied, e.clone())); Some(e) } @@ -359,13 +359,15 @@ impl TrimM { } let quick = quick_mode(s); let implied = !quick && edge_mode(s); - let edges = self.cached_edges(s, implied)?; - let cut: Vec = edges.iter().filter(|(o, _)| *o != h).map(|(_, sg)| *sg).collect(); if self.extend { + let edges = self.cached_edges(s, implied)?; + let cut: Vec = edges.iter().filter(|(o, _)| *o != h).map(|(_, sg)| *sg).collect(); let (e, new) = extend_result(s, h, c, &cut).ok()?; let kinds = uncovered(&new, std::slice::from_ref(&e.kind)); return (!kinds.is_empty()).then_some(Glow { kinds, removing: false }); } + // A trim only meets the edges around the object. + let cut = trim_edges(s, Edges { only: self.edges.as_deref(), implied }, h).ok()?; let kinds = match trim_result(s, h, c, &cut) { Ok((e, pieces)) => match &e.kind { EntityKind::Hatch(hatch) => { From 50b9cfcf68a923525e1ae35fb8e2cb97f52984a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 11:25:42 +0300 Subject: [PATCH 19/23] Hebrew text in the command line and Properties fields reads in reading order Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/ui-egui/src/cmdline.rs | 36 +++++++++++++++++++++++----------- crates/ui-egui/src/palettes.rs | 13 +++++++++++- 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 0ddb016659..a31d296dfb 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -425,6 +425,13 @@ fn visible_lines(app: &CadApp, canvas: Rect, bar: Rect) -> usize { app.ui.history_lines.min(MAX_LINES).min(available) } +/// One line of command-line text laid out in reading order: text holding right-to-left letters +/// (a Hebrew text or layer name in a prompt, history line or typed value) would otherwise be +/// turned around as a whole by the shaper, English words and numbers included. +fn lay(p: &egui::Painter, s: String, font: egui::FontId, color: egui::Color32) -> std::sync::Arc { + p.layout_job(crate::i18n::job(&s, font, color)) +} + pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { let t = Tokens::get(); let w = (canvas.width() * 0.48).clamp(360.0, 760.0).min((canvas.width() - 8.0).max(0.0)); @@ -461,7 +468,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { let hr = Rect::from_min_size(pos2(bar.left(), bar.top() - lh * lines.len() as f32 - 4.0), vec2(w, lh * lines.len() as f32 + 2.0)); p.rect_filled(hr, 3.0, t.cmd_history); for (i, l) in lines.iter().enumerate() { - p.text(pos2(hr.left() + 8.0, hr.top() + 1.0 + lh * i as f32), egui::Align2::LEFT_TOP, l, crate::theme::small(), t.text_dim); + crate::i18n::paint( + &p, + pos2(hr.left() + 8.0, hr.top() + 1.0 + lh * i as f32), + egui::Align2::LEFT_TOP, + l, + crate::theme::small(), + t.text_dim, + ); } } p.rect_filled(bar, 3.0, t.cmd_bg); @@ -475,24 +489,24 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { Some(pr) => { // The grip modes name themselves ("** STRETCH **…"). let name = app.session.running.as_ref().filter(|r| r.id != "grip").map(|r| r.id.to_ascii_uppercase() + " ").unwrap_or_default(); - let g = p.layout_no_wrap(name, font.clone(), t.text_faint); + let g = lay(&p, name, font.clone(), t.text_faint); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text_faint); x += gw; // A LISP `get…` prompt shows as the routine wrote it (no keywords, default or colon added). let message = if pr.raw { pr.display() } else { crate::i18n::t(&pr.message).to_string() }; - let g = p.layout_no_wrap(message, font.clone(), t.text); + let g = lay(&p, message, font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; if !pr.raw && !pr.keywords.is_empty() { - let g = p.layout_no_wrap(if pr.message.is_empty() { " [".into() } else { crate::tl!(" or [").into() }, font.clone(), t.text); + let g = lay(&p, if pr.message.is_empty() { " [".into() } else { crate::tl!(" or [").into() }, font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; let kws = pr.keywords.clone(); for (i, k) in kws.iter().enumerate() { - let g = p.layout_no_wrap(k.clone(), font.clone(), t.cmd_keyword); + let g = lay(&p, k.clone(), font.clone(), t.cmd_keyword); let r = Rect::from_min_size(pos2(x, bar.top() + 3.0), vec2(g.size().x, h - 6.0)); let resp = ui.interact(r, ui.id().with(("kw", i)), Sense::click()); if resp.hovered() { @@ -505,25 +519,25 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { let _ = app.session.input(Input::Keyword(k.clone())); } if i + 1 < kws.len() { - let g = p.layout_no_wrap("/".into(), font.clone(), t.text); + let g = lay(&p, "/".into(), font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; } } - let g = p.layout_no_wrap("]".into(), font.clone(), t.text); + let g = lay(&p, "]".into(), font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; } if let Some(d) = pr.default.as_ref().filter(|_| !pr.raw) { - let g = p.layout_no_wrap(format!(" <{d}>"), font.clone(), t.text); + let g = lay(&p, format!(" <{d}>"), font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; } if !pr.raw { - let g = p.layout_no_wrap(": ".into(), font.clone(), t.text); + let g = lay(&p, ": ".into(), font.clone(), t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); x += gw; @@ -543,7 +557,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { } } } - let g = p.layout_no_wrap(app.cmd.buffer.clone(), font, t.text); + let g = lay(&p, app.cmd.buffer.clone(), font, t.text); let gw = g.size().x; p.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, t.text); // Caret. @@ -688,7 +702,7 @@ fn history_window(app: &CadApp, ui: &mut egui::Ui, r: Rect) { for l in log.get(rows).into_iter().flatten() { let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_H), Sense::hover()); let p = ui.painter().with_clip_rect(row.intersect(ui.clip_rect())); - p.text(pos2(row.left(), row.center().y), egui::Align2::LEFT_CENTER, l, crate::theme::small(), t.text_dim); + crate::i18n::paint(&p, pos2(row.left(), row.center().y), egui::Align2::LEFT_CENTER, l, crate::theme::small(), t.text_dim); } }, ); diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index 9c044b46d6..b8e4efb59f 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -621,7 +621,18 @@ fn edit_field(ui: &mut egui::Ui, id: egui::Id, value: String) -> Option let mut buf = ui.data_mut(|d| d.get_temp::(id)).unwrap_or_else(|| value.clone()); let w = ui.available_width() - 10.0; let te = id.with("te"); - let resp = ui.add_sized([w, 20.0], egui::TextEdit::singleline(&mut buf).id(te).font(crate::theme::body())); + let focused = ui.memory(|m| m.has_focus(te)); + // Unfocused, a value holding right-to-left letters (a Hebrew text) shows in reading order; + // the shaper would otherwise turn it around as a whole, English words and numbers included. + let mut reading_order = |ui: &egui::Ui, text: &dyn egui::TextBuffer, _wrap: f32| { + let job = crate::i18n::job(text.as_str(), crate::theme::body(), ui.visuals().text_color()); + ui.fonts_mut(|f| f.layout_job(job)) + }; + let mut edit = egui::TextEdit::singleline(&mut buf).id(te).font(crate::theme::body()); + if !focused && crate::i18n::has_rtl(&value) { + edit = edit.layouter(&mut reading_order); + } + let resp = ui.add_sized([w, 20.0], edit); let mut out = None; // Keyboard focus from memory: `Response::has_focus` is false while the window itself is // unfocused, which dropped the typed text every frame. From 759bf93c3bfc354e2097213219c119658f9a8bdd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 12:34:22 +0300 Subject: [PATCH 20/23] Russian interface translations, tool descriptions for the constraint tools, hatch picks in scripts, stored text insertion points kept - ru: the 172 interface strings that had no Russian translation, and the Properties palette's Justification row (it took the mtext editor's paragraph Justify). - Tooltips describe the parametric constraint tools added upstream (EN/RU/UK). - HATCH: a boundary that runs out of the area around the view is looked for in the whole space; a pick on screen refuses it only when it is many times the view's size. - DXF: a stored text insertion point is kept when it matches the baseline start mirrored as the text says or as its style lays it out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/hatch.rs | 18 ++- crates/io/src/dxf_write.rs | 34 +++--- crates/ui-egui/src/i18n/ru.tsv | 184 +++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tests.rs | 2 +- crates/ui-egui/src/i18n/uk.tsv | 12 ++ crates/ui-egui/src/palettes.rs | 4 +- crates/ui-egui/src/toolbar.rs | 11 ++ 7 files changed, 246 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index 9681093756..c4f28a2ba4 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -244,13 +244,27 @@ pub(crate) fn loops_picked(s: &Session, p: Vec2) -> Result> { } fn loops_near(s: &Session, p: Vec2, picked: bool) -> Result> { - let near = s.view_box().filter(|v| v.contains(p)).map(|v| v.expand(v.width().max(v.height()) * 0.5)); + let view = s.view_box().filter(|v| v.contains(p)); + let near = view.map(|v| v.expand(v.width().max(v.height()) * 0.5)); match loops_in(s, p, near) { - Err(e) if !picked && near.is_some() => loops_in(s, p, None).map_err(|_| e), + // The boundary runs out of the area around the view: look in the whole space. A pick + // on screen keeps it only when it is not many times the view's size (a gap that let + // the area run out into the rest of the drawing is refused). + Err(e) if near.is_some() => match loops_in(s, p, None) { + Ok(l) => { + let b = Bounds2::from_points(l.iter().flat_map(|l| l.vertices.iter().map(|v| v.p))); + let size = view.map_or(f64::INFINITY, |v| v.width().max(v.height())); + if !picked || b.width().max(b.height()) <= size * FAR_FACTOR { Ok(l) } else { Err(e) } + } + Err(_) => Err(e), + }, r => r, } } +/// How many times larger than the view a boundary found by a pick on screen may be. +const FAR_FACTOR: f64 = 4.0; + /// Boundary loops around `p` among the objects reaching into `near` (all objects when `None`). fn loops_in(s: &Session, p: Vec2, near: Option) -> Result> { let d = s.doc()?; diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index eab9e41033..ddd2352e57 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -528,25 +528,31 @@ fn formula_xdata(w: &mut W, f: Option<&str>) { /// alignment point is only half or a third of a height from the baseline start, must not pass /// for AutoCAD's. fn text_insert(d: &Drawing, t: &Text) -> Vec3 { - let computed = computed_text_insert(d, t); + let computed = computed_text_insert(d, t, t.backwards, t.upside_down); if t.align_pt.is_some_and(|a| a.xy() == t.insert.xy()) { return computed; } let h = t.height.abs(); - let off = (t.insert.xy() - computed.xy()).rotate(-t.rotation); - let close = if t.value.contains('\n') { - // A multiline attribute's lines are placed by its embedded MTEXT: a one-line baseline - // start says little about them, so only the distance counts. - let width = t.align_pt.map_or(0.0, |a| 2.0 * a.xy().dist(computed.xy())); - off.len() <= 0.1 * width + 0.5 * h - } else { - let width = cadcraft_fonts::line_width(&t.value, h, t.width_factor.abs()); - off.x.abs() <= 0.1 * width + 0.5 * h && off.y.abs() <= 0.2 * h + let close = |computed: Vec3| { + let off = (t.insert.xy() - computed.xy()).rotate(-t.rotation); + if t.value.contains('\n') { + // A multiline attribute's lines are placed by its embedded MTEXT: a one-line baseline + // start says little about them, so only the distance counts. + let width = t.align_pt.map_or(0.0, |a| 2.0 * a.xy().dist(computed.xy())); + off.len() <= 0.1 * width + 0.5 * h + } else { + let width = cadcraft_fonts::line_width(&t.value, h, t.width_factor.abs()); + off.x.abs() <= 0.1 * width + 0.5 * h && off.y.abs() <= 0.2 * h + } }; - if close { t.insert } else { computed } + // The stored point is kept when it is where the text's baseline starts read either way: + // mirrored as the text says, or as its style lays it out (files that set the flags on the + // text but placed it by the style). + let ts = d.text_style(&t.style).cloned().unwrap_or_default(); + if close(computed) || close(computed_text_insert(d, t, ts.backwards, ts.upside_down)) { t.insert } else { computed } } -fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { +fn computed_text_insert(d: &Drawing, t: &Text, backwards: bool, upside_down: bool) -> Vec3 { let justified = !matches!((t.halign, t.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)); let Some(a) = t.align_pt.filter(|_| justified) else { return t.insert }; let ts = d.text_style(&t.style).cloned().unwrap_or_default(); @@ -560,8 +566,8 @@ fn computed_text_insert(d: &Drawing, t: &Text) -> Vec3 { oblique: t.oblique, h, v, - backwards: t.backwards, - upside_down: t.upside_down, + backwards, + upside_down, }; let q = cadcraft_fonts::baseline_start(&cadcraft_fonts::TextFont::resolve(&ts.font), &t.value, &p); if q.is_finite() { Vec3::new(q.x, q.y, a.z) } else { t.insert } diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7d95776042..6fc0578ab4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1608,3 +1608,187 @@ No boundary objects selected: select closed objects, or objects that together enclose an area. Не выбраны объекты контура: выберите замкнутые объекты или объекты, которые вместе ограничивают область. Some of the selected objects don't enclose an area and were left out of the hatch. Together, objects must form a closed boundary. Некоторые выбранные объекты не ограничивают область и не вошли в штриховку. Вместе объекты должны образовывать замкнутый контур. Analyze Shapes Анализ фигур + 3D Mouse 3D-мышь + A drawing opened from a file keeps that file's format. Чертёж, открытый из файла, сохраняется в формате этого файла. + A variable name starts with a letter and has only letters, digits and _ Имя переменной начинается с буквы и содержит только буквы, цифры и _ + Add: Pick points Добавить: указать точки + Add: Select objects Добавить: выбрать объекты + Additional angles Дополнительные углы + Add… Добавить… + Alias Псевдоним + An array that would create more objects than this is refused. Массив, который создал бы больше объектов, не выполняется. + Apply Применить + Associative Ассоциативная + Attach DWG... Вставить DWG как внешнюю ссылку... + Automatic save every Автосохранение каждые + Automatic save file location Папка файлов автосохранения + Bind Внедрить + Block to create or edit Блок для создания или редактирования + Boundaries Контуры + Bulleted list Маркированный список + CADCraft CADCraft + Calibrate Калибровать + Choose the command the alias starts. Выберите команду, которую запускает псевдоним. + Clear History Очистить историю + Click the ruler to add a tab stop, right-click to remove one Щёлкните по линейке, чтобы добавить позицию табуляции, правый щелчок — удалить + Click to set new origin Щёлкните, чтобы задать новое начало + Close Block Editor Закрыть редактор блоков + Close Comparison Закрыть сравнение + Collapse Palettes Свернуть палитры + Color 1 Цвет 1 + Color 2 Цвет 2 + Command Команда + Command Aliases Псевдонимы команд + Command line history История командной строки + Convert Преобразовать + Copy as JSON Копировать как JSON + Create separate hatches Отдельные штриховки + Crosshair size Размер перекрестия + Crossing selection color: Цвет секущей рамки: + Curved Изогнутый + Default save version Версия сохранения по умолчанию + Default to boundary extents По границам контура + Define each corner of the selection window with a separate click. Каждый угол рамки выбора задаётся отдельным щелчком. + Detach Отсоединить + Discard Отменить изменения + Don't Save Не сохранять + Drawings with no file yet are saved in the default version. 0 minutes turns automatic save off. Чертежи, у которых ещё нет файла, сохраняются в версии по умолчанию. 0 минут отключает автосохранение. + Edit Block Definition Редактировать описание блока + Edit… Изменить… + Enable 3D mouse navigation Навигация 3D-мышью + Evaluate Вычислить + Exclude: Исключить: + Get from the Drawing Взять из чертежа + Grid snap Шаговая привязка + Grip size Размер ручек + Grips Ручки + Groups Группы + Hatch and Gradient Штриховка и градиент + Hatch origin Исходная точка штриховки + Hatches Штриховки + Hemispherical Полусферический + History История + Hold Shift to add to the selection Shift — добавить к набору + Ignore Игнорировать + Imperial (inches) Британские (дюймы) + Indicate selection area Показывать область выбора + Interface language Язык интерфейса + Interface scale Масштаб интерфейса + Interface theme Тема интерфейса + Inverted Обратный + Island Островок + Island detection Обнаружение островков + Isometric snap Изометрическая привязка + Italic Курсив + Keep the system cursor visible over the drawing area Показывать системный курсор над областью чертежа + Largest array Наибольший массив + Layout paper Бумага листа + Left device button: zoom extents. Right device button: calibrate. Левая кнопка устройства — показать всё. Правая — калибровка. + Lock viewport Заблокировать видовой экран + Make it a block of this drawing, keeping its layer names Сделать блоком этого чертежа, сохранив имена слоёв + Make it a block of this drawing; its layers become NAME$0$LAYER Сделать блоком этого чертежа; слои станут ИМЯ$0$СЛОЙ + Metric (millimetres) Метрические (миллиметры) + Model background Фон модели + Move sideways to pan; push/pull or twist to zoom. Сдвиг вбок — панорамирование; нажатие, вытягивание или поворот — масштаб. + Multiline text Многострочный текст + New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Новые чертежи и первый чертёж при запуске используют эти единицы, если не задан шаблон по умолчанию (QNEWTEMPLATE). + New block Новый блок + Next Change Следующее изменение + No alias file loaded. REINIT replaces these aliases with a file's. Файл псевдонимов не загружен. REINIT заменяет эти псевдонимы псевдонимами из файла. + No external references are attached. Внешние ссылки не вставлены. + Normal Обычное + Numbered list Нумерованный список + Object Snap Tracking Settings Параметры объектного отслеживания + Object grouping Группирование объектов + Object selection limit for display of grips Предел числа выбранных объектов для показа ручек + Object snap aperture Апертура объектной привязки + Object snap marker size Размер маркера объектной привязки + Objects on locked layers Объекты на заблокированных слоях + Open in Block Editor Открыть в редакторе блоков + Outer Внешнее + Over-constrained Переопределено зависимостями + Overlay Наложение + Overline Надчёркивание + Pan sensitivity Чувствительность панорамирования + Paste to Command Line Вставить в командную строку + Pickbox size Размер прицела + Polar angle measurement Отсчёт полярных углов + Polar distance Полярное расстояние + PolarSnap Полярная привязка + Previous Change Предыдущее изменение + Rectangular snap Прямоугольная привязка + Reference Name Имя ссылки + Relative to last segment Относительно последнего сегмента + Reload All Обновить все + Reset keeps the interface language. Сброс сохраняет язык интерфейса. + Reset to Defaults Сбросить по умолчанию + Reverse zoom direction Обратное направление масштабирования + Save Block Сохранить блок + Save Block As Сохранить блок как + Save alias Сохранить псевдоним + Save new drawings as Сохранять новые чертежи как + Saved Path Сохранённый путь + Screen magnifiers, screen readers and recorders follow the system cursor. Экранные лупы, программы чтения экрана и записи следуют за системным курсором. + Select boundaries to remove Выберите контуры для удаления + Select objects first, then choose a command Сначала выбрать объекты, затем команду + Select using two clicks only Выбор только двумя щелчками + Selection Area Effect Эффект области выбора + Selection Preview Filter Фильтр предварительного выбора + Selection area opacity: Непрозрачность области выбора: + Selection effect color Цвет эффекта выбора + Selection modes Режимы выбора + Selection preview Предварительный выбор + Shape Форма + Show Quick Properties for selected objects Показывать быстрые свойства выбранных объектов + Show and hide the tools of this category Показать или скрыть инструменты этой категории + Show command prompting near the crosshairs Показывать запросы команд у перекрестия + Show grips Показывать ручки + Show in Tool Sets Показывать в наборах инструментов + Snap type Тип привязки + Snap, grid, polar tracking and Dynamic Input: Шаг, сетка, полярное отслеживание и динамический ввод: + Specified origin Заданное начало + Spherical Сферический + Tables Таблицы + The aperture is how near the cursor must come to a point for an object snap to find it. Апертура — насколько близко к точке должен подойти курсор, чтобы привязка её нашла. + Time-sensitive right-click: a quick click is Enter, holding opens the menu Правый щелчок с учётом времени: быстрый щелчок — Enter, удержание открывает меню + To В + Track orthogonally only Отслеживать только ортогонально + Track using all polar angle settings Отслеживать по всем полярным углам + Turned off, a right-click while a command runs always opens the shortcut menu. Если выключено, правый щелчок во время команды всегда открывает контекстное меню. + Type an alias name. Введите имя псевдонима. + Underline Подчёркивание + Units Conversion Преобразование единиц + Units of new drawings Единицы новых чертежей + Unload Выгрузить + Unlock viewport Разблокировать видовой экран + Unsaved changes Несохранённые изменения + Use current origin Текущее начало + Variables Переменные + Viewport is locked Видовой экран заблокирован + Viewport scale Масштаб видового экрана + Visual Effect Settings Параметры визуальных эффектов + Visual Effect Settings... Параметры визуальных эффектов... + When a command is active Когда команда выполняется + When no command is active Когда команда не выполняется + Window selection color: Цвет рамки выбора: + X X + Xrefs Внешние ссылки + Y Y + Your changes will be lost if you don't save them. Если не сохранить изменения, они будут потеряны. + Zoom sensitivity Чувствительность масштабирования + built-in встроенный + min мин + objects объектов + overrides built-in заменяет встроенный + Justification Выравнивание + Keeps two lines on one straight line. Удерживает два отрезка на одной прямой. + Joins a spline smoothly to another curve. Плавно сопрягает сплайн с другой кривой. + Keeps two objects symmetric about a line. Удерживает два объекта симметричными относительно линии. + Fixes a point or an object in place. Закрепляет точку или объект на месте. + Removes the constraints from the selected objects. Удаляет зависимости у выбранных объектов. + Opens the Parameters Manager: named values and expressions that drive dimensions. Открывает диспетчер параметров: именованные значения и выражения, управляющие размерами. + Fixes a horizontal or vertical distance with a dimensional constraint. Задаёт горизонтальное или вертикальное расстояние размерной зависимостью. + Fixes the distance between two points with a dimensional constraint. Задаёт расстояние между двумя точками размерной зависимостью. + Fixes an angle with a dimensional constraint. Задаёт угол размерной зависимостью. + Fixes the radius of a circle or arc with a dimensional constraint. Задаёт радиус окружности или дуги размерной зависимостью. + Fixes the diameter of a circle or arc with a dimensional constraint. Задаёт диаметр окружности или дуги размерной зависимостью. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f6cf93df1f..32f6137820 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -361,7 +361,7 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() { ("dsettings", "Drafting Settings"), ("about", "About CADCraft"), ("commands", "Command Reference"), - ("blocks", "Blocks"), + ("blocks", "Block Manager"), ("layers", "Layer Properties Manager"), ("qselect", "Quick Select"), ("parameters", "Parameters Manager"), diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e1b1a7db51..ecf08c894b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1895,3 +1895,15 @@ Discard Скасувати зміни Customize Налаштування інтерфейсу Edit Command Aliases (PGP)... Редагувати псевдоніми команд (PGP)... + Justification Вирівнювання + Keeps two lines on one straight line. Утримує два відрізки на одній прямій. + Joins a spline smoothly to another curve. Плавно спряжує сплайн з іншою кривою. + Keeps two objects symmetric about a line. Утримує два об'єкти симетричними відносно лінії. + Fixes a point or an object in place. Закріплює точку або об'єкт на місці. + Removes the constraints from the selected objects. Видаляє залежності вибраних об'єктів. + Opens the Parameters Manager: named values and expressions that drive dimensions. Відкриває диспетчер параметрів: іменовані значення й вирази, що керують розмірами. + Fixes a horizontal or vertical distance with a dimensional constraint. Задає горизонтальну або вертикальну відстань розмірною залежністю. + Fixes the distance between two points with a dimensional constraint. Задає відстань між двома точками розмірною залежністю. + Fixes an angle with a dimensional constraint. Задає кут розмірною залежністю. + Fixes the radius of a circle or arc with a dimensional constraint. Задає радіус кола або дуги розмірною залежністю. + Fixes the diameter of a circle or arc with a dimensional constraint. Задає діаметр кола або дуги розмірною залежністю. diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index b8e4efb59f..35033a0759 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -1215,7 +1215,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Height", "height", len(tx.height), &mut set, &mut bad, &ids); num(ui, "Rotation", "rotation", real(angles.shown(tx.rotation).to_degrees()), &mut set, &mut bad, &ids); num(ui, "Width factor", "widthFactor", real(tx.width_factor), &mut set, &mut bad, &ids); - prop_row(ui, "Justify", |ui| { + prop_row(ui, "Justification", |ui| { let cur = TEXT_JUSTIFY.iter().find(|(_, h, v, _)| *h == tx.halign && *v == tx.valign).map_or("Left", |j| j.3); if let Some(n) = pick_menu(ui, crate::i18n::t(cur), TEXT_JUSTIFY.iter().map(|j| crate::i18n::t(j.3).to_string())) && let Some(j) = TEXT_JUSTIFY.iter().find(|j| crate::i18n::t(j.3) == n) @@ -1235,7 +1235,7 @@ pub(crate) fn properties_section(app: &mut CadApp, ui: &mut egui::Ui) { num(ui, "Text height", "height", len(tx.height), &mut set, &mut bad, &ids); num(ui, "Defined width", "width", len(tx.width), &mut set, &mut bad, &ids); num(ui, "Rotation", "rotation", real(tx.rotation.to_degrees()), &mut set, &mut bad, &ids); - prop_row(ui, "Justify", |ui| { + prop_row(ui, "Justification", |ui| { let cur = MTEXT_JUSTIFY.get(usize::from(tx.attach.clamp(1, 9) - 1)).map_or("Top left", |j| j.1); if let Some(n) = pick_menu(ui, crate::i18n::t(cur), MTEXT_JUSTIFY.iter().map(|j| crate::i18n::t(j.1).to_string())) && let Some(j) = MTEXT_JUSTIFY.iter().find(|j| crate::i18n::t(j.1) == n) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 78da8bf3b3..45e890ab3f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -581,6 +581,17 @@ pub const DESCRIPTIONS: &[(&str, &str)] = &[ ("gctangent", "Keeps a curve tangent to another object."), ("gcconcentric", "Keeps circles and arcs on one centre."), ("gcequal", "Keeps two lines the same length, or two circles the same size."), + ("gccollinear", "Keeps two lines on one straight line."), + ("gcsmooth", "Joins a spline smoothly to another curve."), + ("gcsymmetric", "Keeps two objects symmetric about a line."), + ("gcfix", "Fixes a point or an object in place."), + ("delconstraint", "Removes the constraints from the selected objects."), + ("parameters", "Opens the Parameters Manager: named values and expressions that drive dimensions."), + ("dclinear", "Fixes a horizontal or vertical distance with a dimensional constraint."), + ("dcaligned", "Fixes the distance between two points with a dimensional constraint."), + ("dcangular", "Fixes an angle with a dimensional constraint."), + ("dcradius", "Fixes the radius of a circle or arc with a dimensional constraint."), + ("dcdiameter", "Fixes the diameter of a circle or arc with a dimensional constraint."), ("box", "Draws a 3D box."), ("cylinder", "Draws a 3D cylinder."), ("pyramid", "Draws a 3D pyramid."), From e3ded3f8071352fcf6b6019c92327fb9928e599f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 15:08:58 +0300 Subject: [PATCH 21/23] Fix the six major CodeRabbit review findings - Dimension text grip: a drag starts from where the text is drawn, so after Reset Text Position (or Above Dim Line / Center Vertically) the text lands where it is dropped instead of at the old stored position plus the drag (grip.stretch, the multi-grip form and the hot-grip STRETCH). - Font lists and family searches read a file's names into a temporary buffer and cache only the names; they no longer keep the bytes or use up the shared 256 MB font load budget. Only the file whose face is used is kept. - DXF fields: the expanded field code stays within MAX_LEN after every substitution and each child field is expanded once (memoised), so a crafted file of multiplying nested fields cannot exhaust memory or time. - Hatch background: HATCHBACKGROUNDCOLOR xdata on hatches is written from the hatch itself, so a cleared background no longer comes back from a kept copy. - PNG: the size is read from the IHDR header and checked before decoding. - Options menu at the cursor opens by itself only for prompts that just ask to choose: not when a number is accepted or the default is not an option (Enter would otherwise pick the first option instead of the default). Each fix has a regression test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/gripcmds.rs | 27 +++++++++--- crates/engine/tests/it/grip_options.rs | 33 ++++++++++++++ crates/fonts/src/ttf.rs | 56 +++++++++++++++++++---- crates/io/src/dxf_fields.rs | 61 +++++++++++++++++++++++++- crates/io/src/dxf_raw.rs | 9 +++- crates/io/tests/it/hatch_background.rs | 21 +++++++++ crates/render/src/raster.rs | 34 ++++++++++++++ crates/ui-egui/src/cmdline.rs | 11 ++++- 8 files changed, 234 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/gripcmds.rs b/crates/engine/src/cmd/gripcmds.rs index b6ca5f862b..023e4b0878 100644 --- a/crates/engine/src/cmd/gripcmds.rs +++ b/crates/engine/src/cmd/gripcmds.rs @@ -30,6 +30,21 @@ pub fn specs() -> Vec { ] } +/// `kind` with a dimension's stored text position set to where the text is drawn (its grip), +/// which differs while the text is not user-positioned. Grip drags then start from the shown +/// text, not from a stale stored position. +fn as_shown(d: &cadcraft_doc::Drawing, kind: &EntityKind) -> EntityKind { + let mut k = kind.clone(); + if let EntityKind::Dimension(dm) = &mut k + && let Some(t) = crate::grips::grip_points(d, kind).get(3).copied() + && t.is_finite() + { + dm.text_mid.x = t.x; + dm.text_mid.y = t.y; + } + k +} + fn index_param(cmd: &str, p: &Value) -> Result { let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(cmd, "`index` (grip number) is required"))?; usize::try_from(i).map_err(|_| bad(cmd, "index out of range")) @@ -48,8 +63,10 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result { // `to` is where the grip as shown goes; a dimension's text grip shows where the text is drawn, // which its stored position may not be. let from = crate::grips::grip_points(s.doc()?, &e.kind).get(i).copied().unwrap_or(to); - let raw = e.kind.grips().get(i).copied().unwrap_or(from); - let k = stretch_grip(&e.kind, i, raw + (to - from)).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?; + // Start from the text where it is drawn, so the grip lands where it was dropped. + let base = as_shown(s.doc()?, &e.kind); + let raw = base.grips().get(i).copied().unwrap_or(from); + let k = stretch_grip(&base, i, raw + (to - from)).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?; let mut edits = vec![(h, k)]; // The other `handles` with a grip on the same point stretch with it (connected objects stay // connected); locked ones and edits that would be degenerate are left alone. @@ -172,14 +189,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], None => moves.push((h, vec![(i, to)])), }; for &(h, i) in hot.iter().take(MAX_GRIPS) { - let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue }; + let Some(from) = d.entity(h).and_then(|e| as_shown(d, &e.kind).grips().get(i).copied()) else { continue }; add(h, i, from + delta); let tol = 1e-9 * (1.0 + from.len()); for &o in others.iter().take(MAX_GRIPS) { if o == h { continue; } - if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) { + if let Some(j) = d.entity(o).and_then(|e| as_shown(d, &e.kind).grips().iter().position(|g| g.near(from, tol))) { add(o, j, from + delta); } } @@ -190,7 +207,7 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], continue; } let Some(e) = d.entity(h) else { continue }; - let mut k = e.kind.clone(); + let mut k = as_shown(d, &e.kind); let mut changed = false; for (i, to) in mv { if let Some(nk) = stretch_grip(&k, i, to) { diff --git a/crates/engine/tests/it/grip_options.rs b/crates/engine/tests/it/grip_options.rs index 502cdc0ad4..afcd874224 100644 --- a/crates/engine/tests/it/grip_options.rs +++ b/crates/engine/tests/it/grip_options.rs @@ -325,3 +325,36 @@ fn grip_option_json_form() { assert!(s.execute("grip.option", &p).is_err(), "{p}"); } } + +/// The text grip of a dimension whose text is not user-positioned (after Reset Text Position, +/// with an old moved position still stored) lands where it is dropped, not at the old +/// position plus the drag. +#[test] +fn dimension_text_grip_lands_where_dropped_after_reset() { + for multi in [false, true] { + let mut s = Session::new(); + s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap(); + let c = s.doc().unwrap().model.last().unwrap().handle.hex(); + let r = s.execute("dimradius", &json!({ "handle": c })).unwrap(); + let h = r["handles"][0].as_str().map(str::to_string).unwrap_or_else(|| s.doc().unwrap().model.last().unwrap().handle.hex()); + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "moveTextOnly", "to": [5, 8] })).unwrap(); + s.execute("grip.option", &json!({ "handle": h, "index": 3, "option": "resetTextPosition" })).unwrap(); + let shown = { + let d = s.doc().unwrap(); + let e = d.model.last().unwrap(); + cadcraft_engine::grips::grip_points(d, &e.kind)[3] + }; + assert!(shown.dist(Vec2::new(5.0, 8.0)) > 1.0, "reset moved the text back: {shown:?}"); + let to = Vec2::new(12.0, 3.0); + if multi { + let delta = to - shown; + s.execute("grip.stretch", &json!({ "grips": [[h, 3]], "delta": [delta.x, delta.y] })).unwrap(); + } else { + s.execute("grip.stretch", &json!({ "handle": h, "index": 3, "to": [to.x, to.y] })).unwrap(); + } + let d = s.doc().unwrap(); + let e = d.model.last().unwrap(); + let now = cadcraft_engine::grips::grip_points(d, &e.kind)[3]; + assert!(now.dist(to) < 1e-6, "multi={multi}: text at {now:?}, dropped at {to:?}"); + } +} diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index 13d233a95c..91201015d8 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -198,6 +198,18 @@ struct Db { loaded_bytes: usize, /// Stems of the fonts found in the user's font folders. user: std::collections::HashSet, + /// Names read from user font files for lists and family searches, by stem. Reading them + /// does not keep the file's bytes, so it does not use up `MAX_LOADED_BYTES`. + face_names: HashMap>, +} + +/// The names inside one font file. +#[derive(Default)] +struct FaceNames { + /// The first face's family name. + family: Option, + /// Each face's normalized names (family, typographic family, full name). + faces: Vec>, } /// State of the missing-glyph search. @@ -374,6 +386,7 @@ pub fn rescan() { g.fallback = Fallback::default(); g.loaded_bytes = 0; g.user.clear(); + g.face_names.clear(); drop(g); GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } @@ -413,7 +426,7 @@ pub fn installed() -> Vec { .map(|(stem, name, user)| { let family = if user && named < MAX_NAMED { named += 1; - g.file(&stem).and_then(|b| faces(&b).into_iter().next()).and_then(|f| f.family_name()) + g.face_names(&stem).and_then(|n| n.family.clone()) } else { None }; @@ -455,15 +468,35 @@ impl Db { if self.loaded_bytes >= MAX_LOADED_BYTES { return None; } - let bytes = Arc::new(match self.paths.get(stem)? { - Source::File(path) => read_file(path)?, - Source::Static(bytes) => bytes.to_vec(), - }); + let bytes = self.peek(stem)?; self.loaded_bytes = self.loaded_bytes.saturating_add(bytes.len()); self.files.insert(stem.to_string(), bytes.clone()); Some(bytes) } + /// Bytes of the font file with this stem, without keeping them or charging the load budget. + fn peek(&self, stem: &str) -> Option>> { + if let Some(b) = self.files.get(stem) { + return Some(b.clone()); + } + Some(Arc::new(match self.paths.get(stem)? { + Source::File(path) => read_file(path)?, + Source::Static(bytes) => bytes.to_vec(), + })) + } + + /// The names inside the font file with this stem, read once (the bytes are dropped after). + fn face_names(&mut self, stem: &str) -> Option> { + if let Some(n) = self.face_names.get(stem) { + return Some(n.clone()); + } + let bytes = self.peek(stem)?; + let all = faces(&bytes); + let names = Arc::new(FaceNames { family: all.first().and_then(Face::family_name), faces: all.iter().map(Face::names).collect() }); + self.face_names.insert(stem.to_string(), names.clone()); + Some(names) + } + fn lookup(&mut self, k: &str) -> Option { let candidates = [k.to_string(), k.replace(' ', ""), format!("{k} regular"), format!("{}-regular", k.replace(' ', ""))]; for c in &candidates { @@ -484,10 +517,11 @@ impl Db { let mut stems: Vec = self.user.iter().cloned().collect(); stems.sort(); for stem in stems.into_iter().take(200) { - let Some(bytes) = self.file(&stem) else { continue }; - if let Some(face) = faces(&bytes).into_iter().find(|f| f.names().iter().any(|n| *n == want || format!("{n}regular") == want)) { - return Some(face); - } + let Some(names) = self.face_names(&stem) else { continue }; + let Some(i) = names.faces.iter().position(|f| f.iter().any(|n| *n == want || format!("{n}regular") == want)) else { continue }; + // Only the file that has the face is kept (and charged to the load budget). + let bytes = self.file(&stem).or_else(|| self.peek(&stem))?; + return faces(&bytes).into_iter().nth(i); } None } @@ -1120,6 +1154,10 @@ mod family_tests { let before = generation(); set_font_dirs(&[dir.to_string_lossy().to_string()]); assert!(generation() > before); + // Listing reads the family name without keeping the file (or using up the load budget). + let early = installed(); + assert!(early.iter().any(|f| f.name == "CadcraftTestFace.ttf" && f.family.is_some())); + assert!(!lock().files.contains_key("cadcrafttestface"), "listing keeps no font bytes"); assert!(find("CadcraftTestFace.ttf").is_some()); let listed = installed(); let entry = listed.iter().find(|f| f.name == "CadcraftTestFace.ttf"); diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs index fa3dd793a1..46dd3a3189 100644 --- a/crates/io/src/dxf_fields.rs +++ b/crates/io/src/dxf_fields.rs @@ -33,9 +33,24 @@ fn entry(tags: &[Tag], name: &str) -> Option { /// A field's code (2, continued in 3s) with its `\_FldIdx n` places filled from its children. fn code(objects: &HashMap>, h: &str, depth: usize) -> Option { + code_in(objects, h, depth, &mut HashMap::new()) +} + +/// [`code`], with the codes already worked out (by handle and depth) in `seen`: a file whose +/// fields share children is expanded once per child, not once per reference. +fn code_in(objects: &HashMap>, h: &str, depth: usize, seen: &mut HashMap<(String, usize), Option>) -> Option { if depth > MAX_DEPTH { return None; } + if let Some(done) = seen.get(&(h.to_string(), depth)) { + return done.clone(); + } + let out = expand(objects, h, depth, seen); + seen.insert((h.to_string(), depth), out.clone()); + out +} + +fn expand(objects: &HashMap>, h: &str, depth: usize, seen: &mut HashMap<(String, usize), Option>) -> Option { let tags = objects.get(h)?; let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbField").unwrap_or(0); let body = tags.get(start..)?; @@ -53,8 +68,15 @@ fn code(objects: &HashMap>, h: &str, depth: usize) -> Option%"); if s.contains(&place) { - let inner = code(objects, c, depth + 1)?; + let inner = code_in(objects, c, depth + 1, seen)?; + // The filled-in code stays within the limit too (nested fields can multiply it). + if inner.len() > MAX_LEN { + return None; + } s = s.replace(&place, &format!("%<{inner}>%")); + if s.len() > MAX_LEN { + return None; + } } } Some(s) @@ -120,3 +142,40 @@ pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use cadcraft_dxf::Tag; + + fn field(code: &str, children: &[&str]) -> Vec { + let mut t = vec![Tag::s(100, "AcDbField"), Tag::s(2, code)]; + t.extend(children.iter().map(|c| Tag::s(360, *c))); + t + } + + #[test] + fn nested_fields_fill_their_places() { + let mut o = HashMap::new(); + o.insert("A".to_string(), field("Date: %<\\_FldIdx 0>%", &["B"])); + o.insert("B".to_string(), field("\\AcVar date", &[])); + assert_eq!(code(&o, "A", 0).as_deref(), Some("Date: %<\\AcVar date>%")); + } + + /// A hostile file whose fields each use the next one 60 times, 8 deep: the expansion would + /// be 60^8 times the text. It is refused, quickly and without the memory. + #[test] + fn fields_that_multiply_are_refused_without_blowing_up() { + let places: String = (0..60).map(|i| format!("%<\\_FldIdx {i}>%")).collect(); + let mut o = HashMap::new(); + for k in 0..=MAX_DEPTH { + let next = format!("L{}", k + 1); + let kids: Vec<&str> = (0..60).map(|_| next.as_str()).collect(); + o.insert(format!("L{k}"), field(&places, &kids)); + } + o.insert(format!("L{}", MAX_DEPTH + 1), field("x", &[])); + let t = std::time::Instant::now(); + assert_eq!(code(&o, "L0", 0), None); + assert!(t.elapsed().as_secs() < 5, "took {:?}", t.elapsed()); + } +} diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index fc60843a02..54a3ac7ba1 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -42,7 +42,8 @@ const MODELLED_KEYS: &[&str] = &[ const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"]; /// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides -/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept. +/// (DSTYLE) on dimensions and dimension styles, `HATCHBACKGROUNDCOLOR` the background of +/// hatches; elsewhere they are kept. const OWN_APPS: &[&str] = &["CADCRAFT", "ACADANNOTATIVE", "ACCMTRANSPARENCY", "ACAECLAYERSTANDARD", "CADCRAFTFORMULA"]; /// Most objects kept from one file. @@ -234,7 +235,11 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec { let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]); i += 1 + len; let app = up(&first.str()); - let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")); + // A hatch's background colour is written from the hatch (none once it is cleared), so a + // kept copy would bring a cleared background back. + let own = OWN_APPS.contains(&app.as_str()) + || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE")) + || (app == crate::dxf_ext::HATCH_BACKGROUND_APP && kind == "HATCH"); if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS { continue; } diff --git a/crates/io/tests/it/hatch_background.rs b/crates/io/tests/it/hatch_background.rs index d545f9b2a8..6032044deb 100644 --- a/crates/io/tests/it/hatch_background.rs +++ b/crates/io/tests/it/hatch_background.rs @@ -47,3 +47,24 @@ fn autocads_background_xdata_alone_gives_the_colour() { let h = back.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); assert_eq!(h.background, Some(Color::Index(5))); } + +#[test] +fn a_cleared_background_stays_cleared() { + let mut d = Drawing::new_metric(); + d.add(&Space::Model, Common::default(), hatch(Some(Color::Index(3)))).unwrap(); + let mut back = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&d).as_bytes()).unwrap(); + let h = back.model.iter().next().unwrap().handle; + back.modify_entity(h, |e| { + if let EntityKind::Hatch(x) = &mut e.kind { + x.background = None; + } + }) + .unwrap(); + let text = cadcraft_io::write_dxf(&back); + // Only the application's registration is left; no hatch carries the colour any more. + let groups = text.lines().map(str::trim).collect::>(); + assert!(!groups.windows(2).any(|w| w[0] == "1001" && w[1] == "HATCHBACKGROUNDCOLOR"), "the old background is not written again"); + let again = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); + let h = again.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h.clone()) } else { None }).unwrap(); + assert_eq!(h.background, None); +} diff --git a/crates/render/src/raster.rs b/crates/render/src/raster.rs index 6f508424a6..ebc14039df 100644 --- a/crates/render/src/raster.rs +++ b/crates/render/src/raster.rs @@ -158,10 +158,25 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option Option<(u32, u32, Vec)> { + // The size is checked from the header first, so a huge image is never decoded. + let (w, h) = png_size(bytes)?; + if w == 0 || h == 0 || w > 4096 || h > 4096 { + return None; + } let pm = Pixmap::decode_png(bytes).ok()?; (pm.width() <= 4096 && pm.height() <= 4096).then(|| (pm.width(), pm.height(), pm.data().to_vec())) } +/// A PNG's width and height from its header (`IHDR`, the first chunk), without decoding it. +fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { + const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + if bytes.get(..8)? != SIGNATURE || bytes.get(12..16)? != b"IHDR" { + return None; + } + let be = |at: usize| bytes.get(at..at + 4).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes); + Some((be(16)?, be(20)?)) +} + /// Encode premultiplied RGBA pixels as a PNG. pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option> { let size = tiny_skia::IntSize::from_wh(width, height)?; @@ -173,3 +188,22 @@ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option> { pub fn render_png(list: &DisplayList, view: &View, o: &RasterOptions) -> Option> { render(list, view, o)?.encode_png().ok() } + +#[cfg(test)] +mod png_tests { + use super::*; + + #[test] + fn a_huge_png_is_refused_from_its_header() { + let ok = encode_png(2, 3, &[255; 2 * 3 * 4]).unwrap_or_default(); + assert_eq!(png_size(&ok), Some((2, 3))); + assert_eq!(decode_png(&ok).map(|(w, h, _)| (w, h)), Some((2, 3))); + // The header says 100000 x 100000: refused before any pixel is decoded. + let mut big = ok.clone(); + big[16..20].copy_from_slice(&100_000u32.to_be_bytes()); + big[20..24].copy_from_slice(&100_000u32.to_be_bytes()); + assert_eq!(decode_png(&big), None); + assert_eq!(decode_png(b"not a png"), None); + assert_eq!(png_size(&ok[..10]), None); + } +} diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index a31d296dfb..df5d9ff579 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -212,7 +212,16 @@ fn options_still_fit(app: &mut CadApp) { return; }; let key = (prompt.message.clone(), prompt.keywords.clone()); - let choose = !prompt.keywords.is_empty() && !prompt.accept.point && !prompt.accept.select; + // Not when the prompt also takes a value Enter would otherwise give (a number, or a default + // that is not one of the options): the menu would turn Enter into its first option. A prompt + // that also takes text opens it only when its default is an option (Yes/No ). + let default_kw = prompt.default.as_ref().map(|d| prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(d))); + let choose = !prompt.keywords.is_empty() + && !prompt.accept.point + && !prompt.accept.select + && !prompt.accept.number + && default_kw != Some(false) + && (!prompt.accept.text || default_kw == Some(true)); if on && choose && app.cmd.options.is_none() From e3b81d31e7c3b316483d0863ddb45cd02b279263 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 21:22:21 +0200 Subject: [PATCH 22/23] Fix the nine findings of FredApps' review (#2034) P1 - Hatch trim: the cutting edges near a hatch are found from its exact extents, arcs included; a round hatch kept as two half-circle arcs is no longer a flat sliver, so a line across it trims the cap (Standard) instead of reporting no cut, or erasing the hatch (Quick). - Dimension Style editor: bound to the drawing it was opened in (DocState uid); when another drawing becomes active it is cancelled, so its OK can never write one drawing's style into another. P2 - Batch Plot: sheets keep their drawing's identity, not its title, so two open plan.dwg files from different folders plot their own sheets; a closed drawing is an error. The Add list shows the folder where titles repeat. - In-place editor: Left (and Shift+Left) crosses back over a soft wrap. - SHX unifont: a sub-shape number after code 7 is read low byte first (a font that wrote it high byte first still finds its shape). - Plot style tables: a named table is told by aci_table_available=FALSE (both kinds share the CTBVER1 header), so .stb style names are kept; a lineweight index reads the table at that index (0.35 mm, not 0.30 mm); stored lineweights stay in millimetres whatever the display units. - Hatch boundaries and trim edges taken from blocks use the continuous geometry (new render option `continuous`), not the dashes a linetype draws, so a dashed closed outline in a block bounds a hatch and cuts across gaps. Each fix has a regression test built on the reviewer's example. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- crates/engine/src/cmd/hatch.rs | 40 ++++++++++- crates/engine/src/cmd/modify.rs | 2 +- crates/engine/src/cmd/trim_hatch.rs | 35 +++++++++- crates/fonts/src/shx.rs | 38 ++++++++++- crates/io/src/pdf.rs | 1 + crates/io/src/pia.rs | 55 ++++++++++++---- crates/render/src/lib.rs | 7 +- crates/render/src/mline.rs | 2 +- crates/ui-egui/src/batchplot.rs | 99 ++++++++++++++++++---------- crates/ui-egui/src/bidi_edit.rs | 27 +++++++- crates/ui-egui/src/canvas.rs | 2 + crates/ui-egui/src/dimstyles.rs | 16 +++-- crates/ui-egui/tests/it/dimstyles.rs | 25 +++++++ 13 files changed, 290 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index c4f28a2ba4..7a7d369b2a 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -83,7 +83,7 @@ fn object_polys(d: &Drawing, e: &Entity, tol: f64, ext: Bounds2) -> Vec = s + .doc() + .unwrap() + .model + .iter() + .filter_map(|e| match &e.kind { + EntityKind::Line(l) if (l.a.y - 5.5).abs() < 1e-9 => Some(l.clone()), + _ => None, + }) + .collect(); + let [line] = lines.as_slice() else { panic!("one trimmed line is left: {lines:?}") }; + assert!((line.a.x.max(line.b.x) - 5.0).abs() < 1e-6, "cut at the dashed line: {line:?}"); + } + /// The drawing's only hatch and its handle (hatches go to the back of the draw order, so not the last entity). fn only_hatch(s: &Session) -> (String, Hatch) { let d = s.doc().unwrap(); diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index b014cdac99..e06f3d6129 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -887,7 +887,7 @@ pub(crate) fn edge_segments_owned(s: &Session, edges: Edges, near: Option, tol: f64) -> Vec> { /// Trim the hatch at `pick` against the cutting edges `cut`: the hatch that is left (`None`: none /// of its area is) and the outline of the part taken away (its outer loop, then its islands). pub(crate) fn trim_hatch(h: &Hatch, cut: &[Segment], pick: Vec2) -> Result<(Option, Vec>)> { - let raw: Vec> = - h.loops.iter().map(|l| cadcraft_geom::Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e300)).collect(); - let bounds = Bounds2::from_points(raw.iter().flatten().copied()); + // The exact extents, arcs included: a circle kept as two half-circle arcs is as tall as it is + // wide, not the flat sliver its chords make. + let bounds = Bounds2::from_points( + h.loops + .iter() + .map(|l| cadcraft_geom::Polyline { vertices: l.vertices.clone(), closed: true }.bounds()) + .flat_map(|b| [b.min, b.max]) + .filter(|p| p.is_finite()), + ); let size = bounds.width().hypot(bounds.height()); if !size.is_finite() || size <= 0.0 { return Err(EngineError::Other("Cannot trim that object.".into())); @@ -261,6 +267,29 @@ mod tests { assert!(face.first().is_some_and(|f| f.iter().all(|p| p.x <= 4.0 + 1e-6))); } + /// A round hatch kept as two half-circle arcs (bulge 1): a line across its top is found as a + /// cutting edge and only the cap above it is taken away (#2034 review). + #[test] + fn a_line_across_a_circular_hatch_trims_the_cap() { + let circle = HatchLoop { + vertices: vec![ + PolyVertex { p: Vec2::new(10.0, 0.0), bulge: 1.0, ..PolyVertex::new(Vec2::ZERO) }, + PolyVertex { p: Vec2::new(-10.0, 0.0), bulge: 1.0, ..PolyVertex::new(Vec2::ZERO) }, + ], + outer: true, + sources: Vec::new(), + }; + let h = hatch(vec![circle]); + let cut = [Segment::Line(Line::new(Vec2::new(-20.0, 5.0), Vec2::new(20.0, 5.0)))]; + let (left, _) = trim_hatch(&h, &cut, Vec2::new(0.0, 8.0)).unwrap(); + let Some(EntityKind::Hatch(left)) = left else { panic!("the hatch below the line is left") }; + let pts: Vec = cadcraft_render::hatch_fill_loops(&left, 1e-2).into_iter().flatten().collect(); + let top = pts.iter().map(|p| p.y).fold(f64::MIN, f64::max); + let bottom = pts.iter().map(|p| p.y).fold(f64::MAX, f64::min); + assert!((top - 5.0).abs() < 1e-3, "the cap above y=5 is gone: top {top}"); + assert!((bottom + 10.0).abs() < 0.05, "the rest stays: bottom {bottom}"); + } + #[test] fn a_hole_cut_out_of_a_hatch() { let h = hatch(vec![square(0.0, 10.0)]); diff --git a/crates/fonts/src/shx.rs b/crates/fonts/src/shx.rs index 1d3b04369e..2119bdd9ea 100644 --- a/crates/fonts/src/shx.rs +++ b/crates/fonts/src/shx.rs @@ -304,7 +304,14 @@ impl ShxFont { 7 => { let (num, extra) = match self.kind { Kind::Shapes => (u32::from(byte(i).unwrap_or(0)), 1), - Kind::Unifont => (u32::from(u16::from_be_bytes([byte(i).unwrap_or(0), byte(i + 1).unwrap_or(0)])), 2), + // Little-endian, like every number in a unifont file; a font that wrote + // it high byte first still finds its shape. + Kind::Unifont => { + let (lo, hi) = (byte(i).unwrap_or(0), byte(i + 1).unwrap_or(0)); + let le = u32::from(u16::from_le_bytes([lo, hi])); + let be = u32::from(u16::from_be_bytes([lo, hi])); + (if self.shapes.contains_key(&le) || !self.shapes.contains_key(&be) { le } else { be }, 2) + } Kind::Bigfont => match byte(i) { Some(0) => (u32::from(u16::from_be_bytes([byte(i + 1).unwrap_or(0), byte(i + 2).unwrap_or(0)])), 7), _ => (u32::from(byte(i).unwrap_or(0)), 1), @@ -671,6 +678,35 @@ mod tests { b } + /// A tiny `unifont 1.0` font of our own: `A` up 4, `C` sub-shape `A` (code 7 then the shape + /// number as two bytes, low byte first). + fn unifont_sample() -> Vec { + let mut b = b"AutoCAD-86 unifont 1.0\r\n\x1a".to_vec(); + let shapes: Vec<(u16, Vec)> = vec![ + (u16::from(b'A'), [b"A\0".to_vec(), vec![0x44, 0x20, 0]].concat()), + (u16::from(b'C'), [b"C\0".to_vec(), vec![7, b'A', 0, 0]].concat()), + ]; + let info = [b"U\0".to_vec(), vec![4, 1, 0, 0, 0, 0]].concat(); + b.extend(u32::try_from(shapes.len() + 1).unwrap_or(0).to_le_bytes()); + b.extend(u16::try_from(info.len()).unwrap_or(0).to_le_bytes()); + b.extend(&info); + for (n, d) in &shapes { + b.extend(n.to_le_bytes()); + b.extend(u16::try_from(d.len()).unwrap_or(0).to_le_bytes()); + b.extend(d); + } + b + } + + #[test] + fn a_unifont_subshape_number_is_little_endian() { + let f = ShxFont::parse("u", &unifont_sample()).expect("parses"); + assert_eq!(f.kind, Kind::Unifont); + let c = f.glyph(u32::from(b'C')).expect("C"); + assert_eq!(c.strokes, f.glyph(u32::from(b'A')).expect("A").strokes, "C draws its sub-shape A"); + assert_eq!(c.advance, 2.0); + } + #[test] fn reads_a_shapes_font_and_runs_its_programs() { let f = ShxFont::parse("t", &sample()).expect("parses"); diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 39e240edf7..20c37ce3d8 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -573,6 +573,7 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String view: None, skip_viewport: None, cancel: None, + continuous: false, }; let k = unit_mm * PT_PER_MM; let window = o.window.filter(|w| matches!(space, Space::Model) && !w.is_empty()); diff --git a/crates/io/src/pia.rs b/crates/io/src/pia.rs index a76c4f0f7b..29644ad5f0 100644 --- a/crates/io/src/pia.rs +++ b/crates/io/src/pia.rs @@ -101,7 +101,7 @@ fn int(nodes: &[(String, Node)], key: &str) -> Option { } /// One style: its colour (object or RGB, grey, screened), lineweight (`0` = the object's, else -/// a 1-based index into the file's lineweight table, in millimetres), ends and joins. +/// an index into the file's lineweight table, in millimetres), ends and joins. fn style(nodes: &[(String, Node)], weights: &[f64]) -> PlotStyle { let name = value(nodes, "name").unwrap_or("").to_string(); let mut s = PlotStyle::object(&name); @@ -117,7 +117,7 @@ fn style(nodes: &[(String, Node)], weights: &[f64]) -> PlotStyle { s.grayscale = policy & 2 != 0; s.screening = int(nodes, "screen").map_or(100, |v| v.clamp(0, 100) as u8); s.lineweight = match int(nodes, "lineweight") { - Some(i) if i > 0 => weights.get((i - 1) as usize).map(|mm| (mm * 100.0).round().clamp(0.0, 211.0) as u16), + Some(i) if i > 0 => usize::try_from(i).ok().and_then(|i| weights.get(i)).map(|mm| (mm * 100.0).round().clamp(0.0, 211.0) as u16), _ => None, }; s.end = match int(nodes, "end_style") { @@ -142,9 +142,13 @@ fn style(nodes: &[(String, Node)], weights: &[f64]) -> PlotStyle { pub fn read(bytes: &[u8], name: &str) -> Result { let t = text(bytes)?; let nodes = parse(&t); - let named = bytes.get(..60).is_some_and(|h| h.windows(6).any(|w| w == b"STBVER")); - // Lineweights in millimetres; the file may list them in inches (display units 1). - let inches = int(&nodes, "custom_lineweight_display_units") == Some(1); + // A named table says it has no colour (ACI) table; both kinds share the CTBVER1 header. + let named = match value(&nodes, "aci_table_available") { + Some(v) => v.trim().eq_ignore_ascii_case("FALSE"), + None => bytes.get(..60).is_some_and(|h| h.windows(6).any(|w| w == b"STBVER")), + }; + // Lineweights are stored in millimetres; `custom_lineweight_display_units` only says how the + // plot style editor shows them. let mut weights: Vec<(usize, f64)> = block(&nodes, "custom_lineweight_table") .unwrap_or(&[]) .iter() @@ -155,7 +159,7 @@ pub fn read(bytes: &[u8], name: &str) -> Result { .filter(|(_, v)| v.is_finite() && *v >= 0.0) .collect(); weights.sort_by_key(|(i, _)| *i); - let weights: Vec = weights.into_iter().map(|(_, v)| if inches { v * 25.4 } else { v }).collect(); + let weights: Vec = weights.into_iter().map(|(_, v)| v).collect(); let mut styles: Vec<(usize, PlotStyle)> = block(&nodes, "plot_style") .unwrap_or(&[]) .iter() @@ -182,18 +186,26 @@ mod tests { /// A small table in the file format, made here (a colour-dependent table whose colour 1 is red /// at 0.35 mm and colour 2 black at the object's lineweight). fn file() -> Vec { - let mut text = String::from( - "description=\"Test\naci_table_available=TRUE\nscale_factor=1.0\napply_factor=FALSE\ncustom_lineweight_display_units=0\nplot_style{\n", + made(true, 0) + } + + /// The test table: colour-dependent (`aci`) or named, lineweights shown in millimetres (0) or + /// inches (1). Style 0 plots at lineweight index 10, 0.35 mm. + fn made(aci: bool, units: u8) -> Vec { + let mut text = format!( + "description=\"Test\naci_table_available={}\nscale_factor=1.0\napply_factor=FALSE\ncustom_lineweight_display_units={units}\nplot_style{{\n", + if aci { "TRUE" } else { "FALSE" } ); - for i in 0..255 { + let count = if aci { 255 } else { 3 }; + for i in 0..count { let (color, lw) = match i { - 0 => ("-1006698496", 11), + 0 => ("-1006698496", 10), 1 => ("-16777216", 0), _ => ("-1", 0), }; + let name = if aci { format!("Color_{}", i + 1) } else { ["Normal", "Walls", "Hidden"].get(i).copied().unwrap_or("Style").to_string() }; text.push_str(&format!( - " {i}{{\n name=\"Color_{}\n color={color}\n color_policy=5\n screen=100\n linetype=31\n lineweight={lw}\n end_style=4\n join_style=5\n }}\n", - i + 1 + " {i}{{\n name=\"{name}\n color={color}\n color_policy=5\n screen=100\n linetype=31\n lineweight={lw}\n end_style=4\n join_style=5\n }}\n" )); } text.push_str("}\ncustom_lineweight_table{\n"); @@ -223,6 +235,25 @@ mod tests { assert!(t.by_color(3).unwrap().color.is_none()); } + /// A named table has the same CTBVER1 header as a colour one; it says `aci_table_available=FALSE`. + /// Its style names are kept, and a lineweight index reads the table at that index. + #[test] + fn a_named_table_is_read_as_named_with_its_style_names() { + let t = super::read(&made(false, 0), "Mine.stb").unwrap(); + assert!(!t.is_color_dependent()); + let names: Vec<&str> = t.styles.iter().map(|s| s.name.as_str()).collect(); + assert!(names.contains(&"Walls") && names.contains(&"Hidden"), "{names:?}"); + let normal = t.styles.iter().find(|s| s.name == "Normal").unwrap(); + assert_eq!(normal.lineweight, Some(35), "index 10 is 0.35 mm, not the one before it"); + } + + /// Lineweights shown in inches are still stored in millimetres. + #[test] + fn inch_display_units_do_not_scale_stored_lineweights() { + let t = super::read(&made(true, 1), "Inch.ctb").unwrap(); + assert_eq!(t.by_color(1).unwrap().lineweight, Some(35)); + } + #[test] fn hostile_files_are_refused_not_panicked_on() { assert!(super::read(b"PIAFILEVERSION_2.0,CTBVER1,compress\r\npmzlibcodec\x01\x02", "x.ctb").is_err()); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 1a5a8fe16d..7ac82e7aad 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -228,6 +228,9 @@ pub struct Options { /// rebuild the view no longer needs). A cancelled build returns a partial list, which the /// caller must discard; see [`Options::cancelled`]. pub cancel: Option>, + /// Draw every curve as one continuous stroke, without its linetype's dashes: the geometry + /// itself, for hatch boundaries and cutting edges taken from what blocks draw. + pub continuous: bool, } impl Options { @@ -251,6 +254,7 @@ impl Default for Options { skip_viewport: None, transparency: false, cancel: None, + continuous: false, } } } @@ -1079,6 +1083,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { Some(over) => over, None => lt, }; + let lt = if b.opts.continuous { None } else { lt }; let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12); let lw = if b.opts.lineweights { lw } else { 0.0 }; // Stroke a polyline with the entity's linetype. @@ -1613,7 +1618,7 @@ pub fn dimension_in(d: &Drawing, dm: &cadcraft_doc::Dimension) -> DimGeometry { /// Draw a polyline with a linetype (None: continuous). fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, ltscale: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| !b.opts.continuous) { Some(lt) => { let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12); for dash in linetype::apply(pts, lt, ltscale, min) { diff --git a/crates/render/src/mline.rs b/crates/render/src/mline.rs index bbaacb5cc7..ba0e9cb624 100644 --- a/crates/render/src/mline.rs +++ b/crates/render/src/mline.rs @@ -59,7 +59,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink, #[allow(clippy::too_many_arguments)] fn stroke(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, scale: f64, min: f64, pts: &[Vec2]) { - match lt { + match lt.filter(|_| !b.opts.continuous) { Some(lt) => { for dash in linetype::apply(pts, lt, scale, min) { match dash.as_slice() { diff --git a/crates/ui-egui/src/batchplot.rs b/crates/ui-egui/src/batchplot.rs index 7f0fc6c892..6dfd6f06ba 100644 --- a/crates/ui-egui/src/batchplot.rs +++ b/crates/ui-egui/src/batchplot.rs @@ -9,9 +9,13 @@ use crate::CadApp; use crate::icons::{self, Icon}; use crate::theme::Tokens; -/// One sheet in the list: the drawing it belongs to (its title) and the layout (or `Model`). +/// One sheet in the list: the drawing it belongs to and the layout (or `Model`). The drawing is +/// known by its identity ([`cadcraft_engine::DocState::uid`]), not its title: two open files can +/// both be `plan.dwg`. #[derive(Clone, Debug, PartialEq)] pub struct Sheet { + pub doc: u64, + /// The drawing's title, for the list. pub drawing: String, pub layout: String, } @@ -21,7 +25,7 @@ pub struct Sheet { struct State { sheets: Vec, /// The drawing the list was filled from when the window opened. - filled_for: Option, + filled_for: Option, /// The picked rows (Ctrl and Shift pick several). selected: Vec, /// Where Shift+click extends from. @@ -31,7 +35,7 @@ struct State { /// Where a selection rectangle started (in the list's empty space). band_from: Option, /// The drawing whose sheets the Add section shows. - add_from: Option, + add_from: Option, separate: bool, note: Option, } @@ -41,11 +45,11 @@ fn state_id() -> egui::Id { } /// The sheets of drawing `d` in tab order: Model when it has objects, then the layouts. -pub fn sheets_of(d: &cadcraft_doc::Drawing, title: &str) -> Vec { +pub fn sheets_of(d: &cadcraft_doc::Drawing, doc: u64, title: &str) -> Vec { let mut layouts: Vec<_> = d.layouts.iter().collect(); layouts.sort_by_key(|l| l.tab_order); let model = (!d.model.is_empty()).then(|| "Model".to_string()); - model.into_iter().chain(layouts.iter().map(|l| l.name.clone())).map(|layout| Sheet { drawing: title.to_string(), layout }).collect() + model.into_iter().chain(layouts.iter().map(|l| l.name.clone())).map(|layout| Sheet { doc, drawing: title.to_string(), layout }).collect() } /// Move the sheet at `from` to stand before `slot` (0..=len). @@ -59,17 +63,13 @@ pub fn move_sheet(v: &mut Vec, from: usize, slot: usize) -> Option Some(to) } -/// The PUBLISH parameters for `sheets` (drawing titles resolved to open drawings). -pub fn publish_params(app: &CadApp, sheets: &[Sheet], combine: bool, path: Option<&str>) -> Result { +/// The PUBLISH parameters for `sheets`, each resolved to the open drawing it came from (`docs`: +/// the open drawings' identities in order); an error names a sheet whose drawing was closed. +pub fn publish_params(docs: &[u64], sheets: &[Sheet], combine: bool, path: Option<&str>) -> Result { let list: Vec = sheets .iter() .map(|s| { - let i = app - .session - .docs - .iter() - .position(|d| d.title == s.drawing) - .ok_or_else(|| format!("{}: {}", crate::tl!("The drawing is closed"), s.drawing))?; + let i = docs.iter().position(|d| *d == s.doc).ok_or_else(|| format!("{}: {}", crate::tl!("The drawing is closed"), s.drawing))?; Ok(json!({ "drawing": i, "layout": s.layout })) }) .collect::>()?; @@ -115,7 +115,7 @@ enum Act { Duplicate, Remove, Add(Sheet), - AddAll(String), + AddAll(u64), Clear, Plot, } @@ -124,18 +124,34 @@ enum Act { pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); let current = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); + let current_doc = app.session.state().map_or(0, |s| s.uid); // Opened for a drawing: its sheets, in tab order (others are added by hand). - if st.filled_for.as_deref() != Some(current.as_str()) { - st.sheets = app.session.doc().map(|d| sheets_of(d, ¤t)).unwrap_or_default(); - st.filled_for = Some(current.clone()); + if st.filled_for != Some(current_doc) { + st.sheets = app.session.doc().map(|d| sheets_of(d, current_doc, ¤t)).unwrap_or_default(); + st.filled_for = Some(current_doc); st.selected.clear(); - st.add_from = Some(current.clone()); + st.add_from = Some(current_doc); st.note = None; } st.selected.retain(|i| *i < st.sheets.len()); - let titles: Vec = app.session.docs.iter().map(|d| d.title.clone()).collect(); + let uids: Vec = app.session.docs.iter().map(|d| d.uid).collect(); + // The open drawings as the Add list names them: the folder too where two share a title. + let titles: Vec<(u64, String)> = app + .session + .docs + .iter() + .map(|d| { + let twin = app.session.docs.iter().filter(|o| o.title == d.title).count() > 1; + let folder = d.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(|f| f.display().to_string()); + let name = match folder { + Some(f) if twin => format!("{} — {f}", d.title), + _ => d.title.clone(), + }; + (d.uid, name) + }) + .collect(); let paper = |s: &Sheet| -> String { - let Some(d) = app.session.docs.iter().find(|d| d.title == s.drawing) else { return crate::tl!("closed").to_string() }; + let Some(d) = app.session.docs.iter().find(|d| d.uid == s.doc) else { return crate::tl!("closed").to_string() }; if s.layout == "Model" { return String::new(); } @@ -370,22 +386,23 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { // Adding sheets: from any open drawing. ui.horizontal(|ui| { ui.label(crate::tl!("Add sheets from")); - let from = st.add_from.clone().filter(|f| titles.contains(f)).unwrap_or_else(|| current.clone()); - let shown = crate::i18n::widget(ui, &from, egui::TextStyle::Body); + let from = st.add_from.filter(|f| uids.contains(f)).unwrap_or(current_doc); + let from_name = titles.iter().find(|(u, _)| *u == from).map(|(_, n)| n.clone()).unwrap_or_default(); + let shown = crate::i18n::widget(ui, &from_name, egui::TextStyle::Body); egui::ComboBox::from_id_salt("cc_batch_from").selected_text(shown).width(220.0).show_ui(ui, |ui| { - for title in &titles { + for (uid, title) in &titles { let name = crate::i18n::widget(ui, title, egui::TextStyle::Body); - if ui.selectable_label(*title == from, name).clicked() { - st.add_from = Some(title.clone()); + if ui.selectable_label(*uid == from, name).clicked() { + st.add_from = Some(*uid); } } }); if ui.button(crate::tl!("Add All")).clicked() { - act = Some(Act::AddAll(from.clone())); + act = Some(Act::AddAll(from)); } }); - let from = st.add_from.clone().filter(|f| titles.contains(f)).unwrap_or_else(|| current.clone()); - let available = app.session.docs.iter().find(|d| d.title == from).map(|d| sheets_of(&d.doc, &from)).unwrap_or_default(); + let from = st.add_from.filter(|f| uids.contains(f)).unwrap_or(current_doc); + let available = app.session.docs.iter().find(|d| d.uid == from).map(|d| sheets_of(&d.doc, d.uid, &d.title)).unwrap_or_default(); egui::ScrollArea::horizontal().id_salt("cc_batch_add").max_height(34.0).show(ui, |ui| { ui.horizontal(|ui| { for s in available { @@ -504,9 +521,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { st.sheets.push(s); st.selected = vec![st.sheets.len() - 1]; } - Some(Act::AddAll(title)) => { - if let Some(d) = app.session.docs.iter().find(|d| d.title == title) { - st.sheets.extend(sheets_of(&d.doc, &title)); + Some(Act::AddAll(uid)) => { + if let Some(d) = app.session.docs.iter().find(|d| d.uid == uid) { + st.sheets.extend(sheets_of(&d.doc, d.uid, &d.title)); } } Some(Act::Clear) => { @@ -521,7 +538,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { .unwrap_or_else(|| "Drawing".into()); let picked = app.services.pick_save.as_ref().and_then(|pick| pick(&format!("{stem}.pdf"))); if let Some(path) = picked { - match publish_params(app, &st.sheets, !st.separate, Some(&path)).and_then(|p| app.run("publish", p)) { + match publish_params(&app.session.docs.iter().map(|d| d.uid).collect::>(), &st.sheets, !st.separate, Some(&path)) + .and_then(|p| app.run("publish", p)) + { Ok(r) => { let msg = r["message"].as_str().unwrap_or("").to_string(); app.session.echo(msg); @@ -546,10 +565,10 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { #[cfg(test)] mod tests { - use super::{Sheet, move_sheet, move_sheets}; + use super::{Sheet, move_sheet, move_sheets, publish_params}; fn s(n: &str) -> Sheet { - Sheet { drawing: "A.dwg".into(), layout: n.into() } + Sheet { doc: 1, drawing: "A.dwg".into(), layout: n.into() } } #[test] @@ -575,4 +594,16 @@ mod tests { assert_eq!(move_sheets(&mut v, &[2], 1), vec![1]); assert_eq!(names(&v), "15324"); } + + /// Two open files with the same name (`/A/plan.dwg`, `/B/plan.dwg`): each sheet plots from + /// the drawing it was added from, and a closed drawing is an error, not another drawing. + #[test] + fn sheets_resolve_by_drawing_identity_not_title() { + let a = Sheet { doc: 7, drawing: "plan.dwg".into(), layout: "A1".into() }; + let b = Sheet { doc: 9, drawing: "plan.dwg".into(), layout: "A1".into() }; + let p = publish_params(&[7, 9], &[b.clone(), a.clone()], true, None).unwrap(); + assert_eq!(p["sheets"][0]["drawing"], 1); + assert_eq!(p["sheets"][1]["drawing"], 0); + assert!(publish_params(&[7], &[b], true, None).is_err()); + } } diff --git a/crates/ui-egui/src/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs index d9b05610b5..dc400aa8ac 100644 --- a/crates/ui-egui/src/bidi_edit.rs +++ b/crates/ui-egui/src/bidi_edit.rs @@ -256,7 +256,9 @@ impl Layout { return self.lines.get(li + 1).map_or(c, |n| n.start); } } else if li > 0 { - return self.lines.get(li - 1).map_or(c, |p| p.end); + // At a soft wrap the previous line ends where this one starts: the same caret place, + // which belongs to this line. Go one character into the previous line instead. + return self.lines.get(li - 1).map_or(c, |p| if p.end == c { c.saturating_sub(1).max(p.start) } else { p.end }); } c } @@ -649,6 +651,29 @@ mod tests { assert_eq!(word_left(&"one two".chars().collect::>(), 7), 4); } + /// Left (and Right) walk through a soft-wrapped paragraph, across the wrap, end to end. + #[test] + fn arrows_cross_a_soft_wrap_both_ways() { + let c: Vec = "aaaa bbbb cccc dddd".chars().collect(); + let one = editor_glyphs::advance(&look(0).font, false, 'a', 20.0); + let l = layout(&c, &look, Some(one * 6.5), 20.0); + assert!(l.lines.len() >= 2, "wrapped"); + assert!(l.lines.windows(2).any(|w| w[0].end == w[1].start), "a soft wrap shares its caret place"); + let walk = |from: usize, dir: f32| { + let mut at = from; + for _ in 0..c.len() * 2 { + let n = l.step(at, dir); + if n == at { + break; + } + at = n; + } + at + }; + assert_eq!(walk(c.len(), -1.0), 0, "Left from the end reaches the start"); + assert_eq!(walk(0, 1.0), c.len(), "Right from the start reaches the end"); + } + #[test] fn wrapping_breaks_at_spaces() { let c: Vec = "aaaa bbbb cccc".chars().collect(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b26830c1aa..4a59038f96 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -363,6 +363,7 @@ fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], ctx: &egui:: transparency: app.session.settings.transparency_display, skip_viewport: split, cancel: None, + continuous: false, }; if view_only { let t = Tokens::get(); @@ -524,6 +525,7 @@ fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Context) -> Op skip_viewport: None, transparency, cancel: None, + continuous: false, }; c.list = cadcraft_render::viewport_content(&st.doc, &st.space, h, area, &opts); c.key = Some(key); diff --git a/crates/ui-egui/src/dimstyles.rs b/crates/ui-egui/src/dimstyles.rs index efdb7a6bc9..7ca7d1bda6 100644 --- a/crates/ui-egui/src/dimstyles.rs +++ b/crates/ui-egui/src/dimstyles.rs @@ -879,6 +879,9 @@ struct Editor { base: Map, style: Map, tab: usize, + /// The drawing the style was read from ([`cadcraft_engine::DocState::uid`]): the editor is + /// cancelled when another drawing becomes active, so OK never writes this style into it. + doc: u64, } #[derive(Clone)] @@ -946,6 +949,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { }; // The drawing the previews take user arrowheads, text styles and linetypes from. let src = app.session.state().ok().map(|s| s.doc.clone()); + let doc = app.session.state().map_or(0, |s| s.uid); let src = src.as_deref(); let mut st: State = ctx.data(|m| m.get_temp(state_id())).unwrap_or_default(); let current = d.header.str("DIMSTYLE", "Standard"); @@ -1078,7 +1082,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } if ui.add(egui::Button::new(crate::tl!("Modify...")).min_size(w)).clicked() { let m = style_map(&sel_style); - st.editor = Some(Editor { mode: Mode::Modify, name: sel.clone(), base: m.clone(), style: m, tab: 0 }); + st.editor = Some(Editor { mode: Mode::Modify, name: sel.clone(), base: m.clone(), style: m, tab: 0, doc }); } let cur_style = styles.iter().find(|x| x.name.eq_ignore_ascii_case(¤t)).cloned().unwrap_or_default(); if ui @@ -1089,7 +1093,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let base = style_map(&cur_style); let mut with = base.clone(); with.extend(overrides.clone()); - st.editor = Some(Editor { mode: Mode::Override, name: current.clone(), base, style: with, tab: 0 }); + st.editor = Some(Editor { mode: Mode::Override, name: current.clone(), base, style: with, tab: 0, doc }); } if ui.add(egui::Button::new(crate::tl!("Compare...")).min_size(w)).clicked() { st.compare = Some((sel.clone(), current.clone())); @@ -1155,14 +1159,18 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { let mut m = style_map(&from); m.insert("name".into(), json!(n.name.trim())); m.insert("annotative".into(), json!(n.annotative)); - st.editor = Some(Editor { mode: Mode::New, name: n.name.trim().to_string(), base: m.clone(), style: m, tab: 0 }); + st.editor = Some(Editor { mode: Mode::New, name: n.name.trim().to_string(), base: m.clone(), style: m, tab: 0, doc }); st.new = None; } else { st.new = keep.then_some(n); } } - // The style editor. + // The style editor, for the drawing it was opened in only. + if st.editor.as_ref().is_some_and(|ed| ed.doc != doc) { + st.editor = None; + app.set_status(crate::tl!("Another drawing became active: the dimension style changes were not applied.")); + } if let Some(mut ed) = st.editor.clone() { let mut close = false; let mut ok = false; diff --git a/crates/ui-egui/tests/it/dimstyles.rs b/crates/ui-egui/tests/it/dimstyles.rs index 04f9ca9f1d..bb59633283 100644 --- a/crates/ui-egui/tests/it/dimstyles.rs +++ b/crates/ui-egui/tests/it/dimstyles.rs @@ -64,6 +64,31 @@ fn modify_and_set_current_and_compare() { assert!(h.query_by_label_contains("The two styles are the same.").is_some()); } +/// The style editor belongs to the drawing it was opened in: switching to another drawing +/// cancels it, so its OK can't write the first drawing's style into the second (#2034 review). +#[test] +fn the_style_editor_is_cancelled_when_another_drawing_becomes_active() { + let mut h = harness(|app| { + app.run("dimstyle", json!({ "name": "Standard", "textHeight": 7.0 })).unwrap(); + app.run("new", json!({})).unwrap(); + app.run("dimstyle", json!({ "name": "Standard", "textHeight": 3.0 })).unwrap(); + // The manager opens on the first of the two drawings. + app.session.active = app.session.docs.len() - 2; + app.ui.dialog = Some("dimstyle".into()); + }); + click(&mut h, "Standard"); + click(&mut h, "Modify..."); + assert!(h.query_by_label_contains("Modify Dimension Style:").is_some(), "the editor opens"); + // Another drawing becomes active (its file tab), the editor still on screen. + let other = h.state().session.docs.len() - 1; + h.state_mut().session.active = other; + h.run_steps(4); + assert!(h.query_by_label_contains("Modify Dimension Style:").is_none(), "the editor is cancelled"); + assert!(h.query_all_by_label("OK").next().is_none(), "no OK left to press"); + let second = h.state().session.doc().unwrap().dim_style("Standard").unwrap().text_height; + assert_eq!(second, 3.0, "the second drawing keeps its own style"); +} + #[test] fn a_selected_dimension_shows_its_style_settings_in_properties() { let mut hx = String::new(); From 517f716d05a36380a6218da0d36b8f79fd1b95f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 26 Oct 2026 21:26:51 +0200 Subject: [PATCH 23/23] Fix FredApps' second review and CodeRabbit's remaining findings (#2034) FredApps (8) - MTEXT editor: the width never orders its bounds the wrong way round, so a canvas 400 px wide or narrower no longer panics (editor_width). - Formulas: IF works out only the branch it picks (=IF(TRUE;1;1/0) is 1); arguments are parsed to their end whatever error their value gave. - SHEET() is each text's own layout name ("Model" in model space) when fields are worked out on open and by UPDATEFIELD. - User arrowheads: a solid hatch's loops are filled together even-odd (an island stays a hole); a wide polyline keeps its tapers (a tip is a triangle). - In-place editor fonts follow a font-folder change or rescan. - DXF thumbnails: the THUMBNAILIMAGE section is read in group pairs from the line after its name (and capped). - properties.set replacing a text works out its formula like typed text: plain text drops the old formula, a formula is taken. CodeRabbit, 25.10 (9) - MLEADERSTYLE sets the style's arrowhead (arrowBlock). - Cutting edges from blocks use a size-aware chord tolerance. - properties.set refuses a justification the selected type doesn't have. - fonts.missing reports a missing big font. - User arrowheads are no longer cached by block address. - A paste into a one-line box turns line breaks (\r\n too) into spaces. - The Block Manager preview cache is keyed by drawing too. - Options > Fonts lists the SHX fonts in the user's folders; the hint says so. - Customize Tool Bar keeps separators where they are while editing. CodeRabbit, 24.10 (remaining minors and nitpicks) - PUBLISH: a non-list `layouts` is refused when combining too; PDFs are written through write_atomic (no fixed temporary name, CWE-59). - TRIM glow over a hatch works the trim out once. - HATCH/HATCHEDIT refuse a `background` that is not a colour. - A trimmed hatch goes back behind the lines. - Formula xdata strings are cut at 250 bytes, between letters. - New multileaders and dimensions take formulas as edited ones do; results in multiline text keep \, { and } as letters. - Date serials are clamped (=YEAR(1E300) can't overflow). - Dimensions in block definitions get their measurement for `<>`; a dimension formula's `<>` is the measurement as shown, not the first number of the formatted text (a DIMPOST "2X<>" prefix). - Leader type None keeps the leader lines (hidden) on import. - The Tool Sets ribbon and its tab are saved in workspace.json. - Editor: per-event layout only for the keys that need it; custom pattern folders: a shared list, read errors reported, symlinks skipped, sorted before the cap; separate tests for the field length cap and sharing. Each fix has a regression test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V --- apps/cadcraft/src/workspace.rs | 18 ++++ crates/engine/src/cmd/exchange.rs | 13 ++- crates/engine/src/cmd/hatch.rs | 29 ++++++ crates/engine/src/cmd/hatch/edit.rs | 1 + crates/engine/src/cmd/modify.rs | 12 ++- crates/engine/src/cmd/props.rs | 51 +++++++++-- crates/engine/src/cmd/trimextend.rs | 46 +++++----- crates/engine/src/lib.rs | 9 +- crates/engine/src/textformula.rs | 34 ++++--- crates/engine/tests/it/text_justify.rs | 113 ++++++++++++++++++++++++ crates/io/src/dxf_ext.rs | 30 ++++++- crates/io/src/dxf_fields.rs | 23 +++++ crates/io/src/dxf_mleader.rs | 8 +- crates/io/tests/it/mleader_roundtrip.rs | 18 ++++ crates/render/src/dim.rs | 21 +++-- crates/render/src/lib.rs | 46 +++------- crates/render/src/tests.rs | 50 +++++++++++ crates/render/src/textformula.rs | 66 +++++++++++++- crates/ui-egui/src/bidi_edit.rs | 37 +++++++- crates/ui-egui/src/blockmgr.rs | 7 +- crates/ui-egui/src/custom_patterns.rs | 39 +++++--- crates/ui-egui/src/editor_glyphs.rs | 24 +++++ crates/ui-egui/src/i18n/ru.tsv | 3 +- crates/ui-egui/src/i18n/uk.tsv | 3 +- crates/ui-egui/src/mtext_editor.rs | 30 ++++++- crates/ui-egui/src/options/dialog.rs | 7 +- crates/ui-egui/src/thumbs.rs | 18 +++- crates/ui-egui/src/toolbar.rs | 31 ++++++- 28 files changed, 662 insertions(+), 125 deletions(-) diff --git a/apps/cadcraft/src/workspace.rs b/apps/cadcraft/src/workspace.rs index 7430750432..93ef0c3626 100644 --- a/apps/cadcraft/src/workspace.rs +++ b/apps/cadcraft/src/workspace.rs @@ -55,6 +55,8 @@ fn snapshot(ui: &UiState) -> Result { "docking": ui.docking, "dockingVersion": cadcraft_ui_egui::docking::LAYOUT_VERSION, "showToolsets": ui.show_toolsets, + "toolsetsRibbon": ui.toolsets_ribbon, + "ribbonTab": ui.ribbon_tab, "showPalettes": ui.show_palettes, "showToolbar": ui.show_toolbar, "toolbarDock": ui.toolbar_dock, @@ -298,6 +300,22 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + /// The Tool Sets ribbon and its open tab come back after a restart (#2034 review). + #[test] + fn the_tool_sets_ribbon_and_its_tab_survive_a_restart() { + let directory = temp_dir(); + let path = directory.join("workspace.json"); + let (mut store, _, _) = Workspace::at(Some(path.clone())); + let ui = UiState { toolsets_ribbon: true, ribbon_tab: "Modify".into(), ..UiState::default() }; + store.save_if_changed(&ui, Instant::now()).unwrap(); + let (_, reloaded, error) = Workspace::at(Some(path)); + assert!(error.is_none(), "{error:?}"); + let reloaded = reloaded.unwrap(); + assert!(reloaded.toolsets_ribbon); + assert_eq!(reloaded.ribbon_tab, "Modify"); + fs::remove_dir_all(directory).unwrap(); + } + #[test] fn split_frame_layout_file_loads_as_the_dock_default_with_its_other_settings() { use cadcraft_ui_egui::docking::default_workspace; diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 41bb9c521d..dc3d3aedeb 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -421,9 +421,9 @@ fn publish_sheets(s: &Session, v: &Value) -> Result> { fn write_pdf(path: &str, bytes: &[u8]) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { - let tmp = format!("{path}.cadcraft-tmp"); - std::fs::write(&tmp, bytes).map_err(|e| bad("publish", format!("{path}: {e}")))?; - std::fs::rename(&tmp, path).map_err(|e| bad("publish", format!("{path}: {e}"))) + // Through an unpredictable temporary file, as files are saved: a planted symlink at a + // fixed temporary name can't redirect the write (CWE-59). + crate::atomic_write::write_atomic(std::path::Path::new(path), bytes).map_err(|e| bad("publish", format!("{path}: {e}"))) } #[cfg(target_arch = "wasm32")] { @@ -520,7 +520,8 @@ fn run_publish(s: &mut Session, p: &Value) -> Result { if p.get("combine").and_then(Value::as_bool) == Some(true) { let names: Vec = match p.get("layouts") { Some(Value::Array(a)) => a.iter().map(|n| json!({ "layout": n })).collect(), - _ => { + Some(_) => return Err(bad("publish", "`layouts` must be a list of layout names")), + None => { let d = s.doc()?; let mut layouts: Vec<_> = d.layouts.iter().collect(); layouts.sort_by_key(|l| l.tab_order); @@ -940,6 +941,10 @@ mod tests { for p in [json!({ "layouts": [] }), json!({ "layouts": ["Nope"] }), json!({ "layouts": "Layout1" }), json!({ "layouts": [1] })] { assert!(s.execute("publish", &p).is_err(), "{p}"); } + // Combined into one PDF: the same check, not every layout instead. + let path = temp("combined.pdf"); + assert!(s.execute("publish", &json!({ "combine": true, "layouts": "Layout1", "path": path.to_string_lossy() })).is_err()); + assert!(!path.exists()); } #[test] diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index cbda1342fc..8fe7378560 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -489,6 +489,14 @@ struct HatchSettings { /// A `background` parameter: a colour name, ACI number or `r,g,b`; `"None"`, `""` or null for /// none. `None` when absent or not a colour. +/// A `background` given that is not a colour, `none` or null: an error, not a silent no-background. +pub(crate) fn check_background(cmd: &str, p: &Value) -> Result<()> { + if p.get("background").is_some() && background_param(p).is_none() { + return Err(bad(cmd, "`background` must be a colour (an ACI number, a name, \"r,g,b\"), \"none\" or null")); + } + Ok(()) +} + pub(crate) fn background_param(p: &Value) -> Option> { match p.get("background")? { Value::Null => Some(None), @@ -669,6 +677,7 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec>) } fn run_hatch(s: &mut Session, p: &Value) -> Result { + check_background("hatch", p)?; patfile::load_param(p)?; // Like the prompt: a name without a definition would be drawn as ANSI31. if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase) @@ -1030,6 +1039,26 @@ mod tests { use super::*; + /// A background that is not a colour is an error, not a quiet "no background"; a trimmed + /// hatch stays behind the lines it touches (#2034 review). + #[test] + fn a_bad_background_is_refused_and_a_trimmed_hatch_stays_at_the_back() { + let mut s = Session::new(); + s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap(); + for bad in [json!("blu"), json!(true), json!({})] { + assert!(s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "ANSI31", "background": bad })).is_err(), "{bad}"); + } + s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap(); + let (h, _) = only_hatch(&s); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "blu" })).is_err()); + assert!(s.execute("hatchedit", &json!({ "handles": [h], "background": "none" })).is_ok()); + let l = s.execute("line", &json!({ "points": [[4, -1], [4, 11]] })).unwrap(); + let l = l["handles"][0].as_str().unwrap().to_string(); + s.execute("trim", &json!({ "handle": h, "pick": [2, 5], "edges": [l] })).unwrap(); + let first = s.doc().unwrap().model.iter().next().map(|e| matches!(e.kind, EntityKind::Hatch(_))); + assert_eq!(first, Some(true), "the trimmed hatch is drawn first, under the lines"); + } + /// A block whose lines are drawn with a dashed linetype: its outline still bounds a hatch, and /// its lines still cut, across the gaps between dashes (#2034 review). #[test] diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index ed65a0fe49..8181fc6046 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -362,6 +362,7 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<( pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result { check_numbers(p)?; + super::check_background("hatchedit", p)?; let hs = hatches(s, p)?; let (added, removed) = boundary_changes(s, p, &hs)?; let style = match str_param(p, "style") { diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index 7f425d30af..89a6db69fb 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -885,11 +885,14 @@ pub(crate) fn edge_segments_owned(s: &Session, edges: Edges, near: Option Resu let mut out = Vec::new(); for k in pieces { let nh = d.new_handle(); + // A hatch goes behind the lines again, as a new hatch does. + let hatch = matches!(k, EntityKind::Hatch(_)); if let Some(st) = d.space_mut(&space) { st.push(Entity { handle: nh, common: common.clone(), kind: k }); + if hatch { + st.send_to_back(nh); + } out.push(nh); } } diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 75a347bc19..8cf9f0b106 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -74,7 +74,7 @@ pub fn specs() -> Vec { CommandSpec::new("mleaderstyle", "Multileader Style...", run_mleaderstyle) .menu(&["Format", "Multileader Style..."]) .alias(&["mls"]) - .params("{name, arrowSize?, textHeight?, landingGap?, dogleg?, textStyle?, annotative?, current?} → styles"), + .params("{name, arrowSize?, arrowBlock? (\"\" = closed filled, a built-in `_Open`… or a block), textHeight?, landingGap?, dogleg?, textStyle?, annotative?, current?} → styles"), CommandSpec::new("ddptype", "Point Style...", run_ptype) .menu(&["Format", "Point Style..."]) .alias(&["ptype"]) @@ -206,6 +206,9 @@ fn run_set(s: &mut Session, p: &Value) -> Result { .map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number"))) .transpose()?; let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?; + // A new text is worked out like a typed one: a formula becomes the text's formula, other + // text drops the one it had. + let formula_env = crate::textformula::env(s); let d = s.doc_mut()?; // An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires). let linetype = str_param(p, "linetype") @@ -241,17 +244,28 @@ fn run_set(s: &mut Session, p: &Value) -> Result { let justify = str_param(p, "justify"); let text_justify = justify.and_then(super::draw::justify); let mtext_justify = justify.and_then(mtext_attach); - if let Some(j) = justify - && text_justify.is_none() - && mtext_justify.is_none() - { - return Err(bad("properties.set", format!("unknown justification `{j}`"))); + if let Some(j) = justify { + if text_justify.is_none() && mtext_justify.is_none() { + return Err(bad("properties.set", format!("unknown justification `{j}`"))); + } + // Each selected object must have it: multiline text has no baseline justifications (C, A...). + for e in hs.iter().filter_map(|h| d.entity(*h)) { + let missing = match &e.kind { + EntityKind::Text(_) => text_justify.is_none(), + EntityKind::MText(_) => mtext_justify.is_none(), + _ => false, + }; + if missing { + return Err(bad("properties.set", format!("justification `{j}` does not apply to {}", e.kind.type_name()))); + } + } } let style_doc = justify.map(|_| cadcraft_doc::Drawing { text_styles: d.text_styles.clone(), header: d.header.clone(), ..Default::default() }); let dim_over = dim_overrides(p)?; let anno_scale = d.current_anno_scale(); for h in &hs { d.modify_entity(*h, |e| { + let mut new_text = false; // The text style of text, multiline text and a multileader's text. if let Some(st) = &text_style { match &mut e.kind { @@ -349,6 +363,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::Text(t) => { if let Some(v) = str_param(p, "text") { t.value = v.to_string(); + new_text = true; } if let Some(x) = num("height").filter(|x| *x > 0.0) { t.height = x; @@ -380,6 +395,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result { EntityKind::MText(t) => { if let Some(v) = str_param(p, "text") { t.contents = v.replace('\n', "\\P"); + new_text = true; } if let Some(x) = num("height").filter(|x| *x > 0.0) { t.height = x; @@ -524,6 +540,9 @@ fn run_set(s: &mut Session, p: &Value) -> Result { } _ => {} } + if new_text { + crate::textformula::apply(&mut e.kind, &formula_env, true); + } })?; } Ok(json!({ "changed": hs.len() })) @@ -821,9 +840,14 @@ pub fn substitute_font() -> String { pub fn missing_fonts(d: &cadcraft_doc::Drawing) -> Vec<(String, String)> { let mut out: Vec<(String, String)> = Vec::new(); for st in &d.text_styles { + // The font, and the big font (Asian characters) an SHX style may add. let font = st.font.trim(); - if !cadcraft_fonts::ttf::available(font) && !out.iter().any(|(_, f)| f.eq_ignore_ascii_case(font)) { - out.push((st.name.clone(), font.to_string())); + let big = st.big_font.trim(); + let missing_big = !big.is_empty() && cadcraft_fonts::shx::find(big).is_none(); + for (f, missing) in [(font, !cadcraft_fonts::ttf::available(font)), (big, missing_big)] { + if missing && !out.iter().any(|(_, o)| o.eq_ignore_ascii_case(f)) { + out.push((st.name.clone(), f.to_string())); + } } } out @@ -1202,6 +1226,14 @@ fn run_tablestyle(s: &mut Session, p: &Value) -> Result { fn run_mleaderstyle(s: &mut Session, p: &Value) -> Result { let d = s.doc_mut()?; + // The arrowhead: closed filled (empty or `_ClosedFilled`), a built-in one or a block of the + // drawing. + let arrow = match str_param(p, "arrowBlock").map(str::trim) { + None => None, + Some(a) if a.is_empty() || a.eq_ignore_ascii_case("_ClosedFilled") || a.eq_ignore_ascii_case("ClosedFilled") => Some(String::new()), + Some(a) if a.starts_with('_') || d.blocks.keys().any(|k| k.eq_ignore_ascii_case(a)) => Some(a.to_string()), + Some(a) => return Err(bad("mleaderstyle", format!("arrowhead block `{a}` not found"))), + }; if let Some(name) = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) { let idx = match d.mleader_styles.iter().position(|t| t.name.eq_ignore_ascii_case(name)) { Some(i) => i, @@ -1227,6 +1259,9 @@ fn run_mleaderstyle(s: &mut Session, p: &Value) -> Result { if let Some(t) = str_param(p, "textStyle") { st.text_style = t.to_string(); } + if let Some(a) = &arrow { + st.arrow_block.clone_from(a); + } if let Some(a) = p.get("annotative").and_then(Value::as_bool) { st.annotative = a; } diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 8ae182114d..211c8f65a6 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -31,6 +31,18 @@ fn proj_mode(s: &Session) -> i64 { } /// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it). +/// What trimming a hatch takes away, as the glow shows it: the outline of that part and the +/// part filled. +fn hatch_glow(hatch: &cadcraft_doc::Hatch, face: Vec>) -> Vec { + let mut out: Vec = face.iter().map(|l| lwpoly(l.iter().copied().map(PolyVertex::new).collect(), true)).collect(); + let loops = face + .into_iter() + .map(|l| cadcraft_doc::HatchLoop { vertices: l.into_iter().map(PolyVertex::new).collect(), outer: false, sources: Vec::new() }) + .collect(); + out.push(EntityKind::Hatch(cadcraft_doc::Hatch { pattern: "SOLID".into(), solid: true, loops, gradient: None, style: 0, ..hatch.clone() })); + out +} + fn misses_edges(e: &EngineError) -> bool { e.to_string().contains("intersect") } @@ -368,32 +380,14 @@ impl TrimM { } // A trim only meets the edges around the object. let cut = trim_edges(s, Edges { only: self.edges.as_deref(), implied }, h).ok()?; - let kinds = match trim_result(s, h, c, &cut) { - Ok((e, pieces)) => match &e.kind { - EntityKind::Hatch(hatch) => { - let (_, face) = super::trim_hatch::trim_hatch(hatch, &cut, c).ok()?; - // The outline of the part taken away, and the part filled. - let mut out: Vec = face.iter().map(|l| lwpoly(l.iter().copied().map(PolyVertex::new).collect(), true)).collect(); - let loops = face - .into_iter() - .map(|l| cadcraft_doc::HatchLoop { - vertices: l.into_iter().map(PolyVertex::new).collect(), - outer: false, - sources: Vec::new(), - }) - .collect(); - out.push(EntityKind::Hatch(cadcraft_doc::Hatch { - pattern: "SOLID".into(), - solid: true, - loops, - gradient: None, - style: 0, - ..hatch.clone() - })); - out - } - k => uncovered(k, &pieces), - }, + // A hatch's trim is worked out once, for the part it takes away (`trim_result` would + // work it out again only to drop that part). + let result = match &d.entity(h)?.kind { + EntityKind::Hatch(hatch) => super::trim_hatch::trim_hatch(hatch, &cut, c).map(|(_, face)| hatch_glow(hatch, face)), + _ => trim_result(s, h, c, &cut).map(|(e, pieces)| uncovered(&e.kind, &pieces)), + }; + let kinds = match result { + Ok(kinds) => kinds, // A Quick-mode trim of an object no edge crosses erases all of it. Err(err) if quick && misses_edges(&err) => vec![d.entity(h)?.kind.clone()], Err(_) => return None, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 65576503bf..cd5a8130cb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -914,8 +914,13 @@ impl Session { pub fn add_entity(&mut self, kind: EntityKind) -> Result { // Text starting with `=` is a formula: it keeps the formula and shows the result. let mut kind = kind; - if matches!(kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)) { - let env = textformula::env(self); + // Multileader and dimension text too, as when it is edited (a dimension's `<>` is its + // measurement). + if matches!(kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::MLeader(_) | EntityKind::Dimension(_)) { + let mut env = textformula::env(self); + if let EntityKind::Dimension(dm) = &kind { + env.measured = textformula::measured(self.doc()?, dm); + } textformula::apply(&mut kind, &env, true); } let common = self.current_common(); diff --git a/crates/engine/src/textformula.rs b/crates/engine/src/textformula.rs index 21dc681257..c3532bff4c 100644 --- a/crates/engine/src/textformula.rs +++ b/crates/engine/src/textformula.rs @@ -44,15 +44,16 @@ pub fn measured(d: &Drawing, dm: &cadcraft_doc::Dimension) -> Option { /// is not a formula drops the formula. Text, attribute definitions, multiline text, /// multileader text and dimension text (whose `<>` is its measurement, `env.measured`). pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { - let (value, formula): (&mut String, &mut Option) = match kind { - EntityKind::Text(t) => (&mut t.value, &mut t.formula), - EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula), - EntityKind::MText(t) => (&mut t.contents, &mut t.formula), + // Multiline text keeps a result's `\`, `{` and `}` as letters, not formatting codes. + let (value, formula, mtext): (&mut String, &mut Option, bool) = match kind { + EntityKind::Text(t) => (&mut t.value, &mut t.formula, false), + EntityKind::AttDef(a) => (&mut a.text.value, &mut a.text.formula, false), + EntityKind::MText(t) => (&mut t.contents, &mut t.formula, true), EntityKind::MLeader(m) => match &mut m.text { - Some(t) => (&mut t.contents, &mut t.formula), + Some(t) => (&mut t.contents, &mut t.formula, true), None => return, }, - EntityKind::Dimension(d) => (&mut d.text, &mut d.marks.formula), + EntityKind::Dimension(d) => (&mut d.text, &mut d.marks.formula, false), _ => return, }; if edited { @@ -67,7 +68,7 @@ pub fn apply(kind: &mut EntityKind, env: &Env, edited: bool) { if let Some(f) = formula.as_deref() && let Some(v) = evaluate(f, env) { - *value = v; + *value = if mtext { cadcraft_doc::mtext_literal(&v) } else { v }; } } @@ -89,29 +90,36 @@ pub fn refresh(d: &mut Drawing, env: &Env) -> usize { let mut n = 0; // Dimensions' measurements first (they need the whole drawing). let mut measures: std::collections::HashMap> = std::collections::HashMap::new(); - for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())) { + // Dimensions in block definitions too: their `<>` is their own measurement. + for e in d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) { if let EntityKind::Dimension(dm) = &e.kind && dm.marks.formula.is_some() { measures.insert(e.handle, measured(d, dm)); } } - let fix = |store: &mut cadcraft_doc::EntityStore, n: &mut usize| { + // Each space with its own sheet name (SHEET()): model space is "Model", a layout its name; + // block definitions keep the name given. + let fix = |store: &mut cadcraft_doc::EntityStore, sheet: Option<&str>, n: &mut usize| { let hs: Vec = store.iter().filter(|e| has_formula(&e.kind)).map(|e| e.handle).collect(); for h in hs { - let env = Env { measured: measures.get(&h).copied().flatten(), ..env.clone() }; + let mut env = Env { measured: measures.get(&h).copied().flatten(), ..env.clone() }; + if let Some(sheet) = sheet { + env.sheet = sheet.to_string(); + } store.modify(h, |e| apply(&mut e.kind, &env, false)); *n += 1; } }; - fix(&mut d.model, &mut n); + fix(&mut d.model, Some("Model"), &mut n); for l in &mut d.layouts { - fix(&mut l.entities, &mut n); + let name = l.name.clone(); + fix(&mut l.entities, Some(&name), &mut n); } let names: Vec = d.blocks.iter().filter(|(_, b)| b.entities.iter().any(|e| has_formula(&e.kind))).map(|(k, _)| k.clone()).collect(); for k in names { if let Some(b) = d.blocks.get_mut(&k) { - fix(&mut std::sync::Arc::make_mut(b).entities, &mut n); + fix(&mut std::sync::Arc::make_mut(b).entities, None, &mut n); } } n diff --git a/crates/engine/tests/it/text_justify.rs b/crates/engine/tests/it/text_justify.rs index 2112561e53..0961af432b 100644 --- a/crates/engine/tests/it/text_justify.rs +++ b/crates/engine/tests/it/text_justify.rs @@ -121,3 +121,116 @@ fn dimension_and_leader_text_take_formulas() { let EntityKind::MLeader(ml) = &d.model.iter().find(|e| e.handle.hex() == m).unwrap().kind else { panic!() }; assert_eq!(ml.text.as_ref().unwrap().contents, "42"); } + +/// properties.set replacing a text drops the formula it had (or takes the new one), like +/// typing over it; UPDATEFIELD does not bring the old result back (#2034 review). +#[test] +fn replacing_text_in_properties_updates_its_formula() { + let mut s = Session::new(); + let r = s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=1+1" })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "=2+2" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("properties.set", &json!({ "handles": [h, m], "text": "replacement" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + for e in s.doc().unwrap().model.iter() { + match &e.kind { + EntityKind::Text(t) => assert_eq!((t.value.as_str(), t.formula.as_deref()), ("replacement", None)), + EntityKind::MText(t) => assert_eq!((t.contents.as_str(), t.formula.as_deref()), ("replacement", None)), + _ => {} + } + } + // A formula given there is worked out. + s.execute("properties.set", &json!({ "handles": [h], "text": "=3*3" })).unwrap(); + let t = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!((t.value.as_str(), t.formula.as_deref()), ("9", Some("=3*3"))); +} + +/// SHEET() in a layout is that layout's name, in model space "Model", whichever is active when +/// fields are updated (#2034 review). +#[test] +fn sheet_is_each_texts_own_layout() { + let mut s = Session::new(); + s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=SHEET()" })).unwrap(); + let layout = s.doc().unwrap().layouts.first().map(|l| l.name.clone()).unwrap(); + s.execute("layout.set", &json!({ "name": layout })).unwrap(); + s.execute("text", &json!({ "at": [0, 0], "height": 1, "text": "=SHEET()" })).unwrap(); + s.execute("updatefield", &json!({})).unwrap(); + let d = s.doc().unwrap(); + let value = |e: &std::sync::Arc| if let EntityKind::Text(t) = &e.kind { t.value.clone() } else { String::new() }; + assert_eq!(d.model.iter().map(value).collect::>(), ["Model"]); + let l = d.layouts.iter().find(|l| l.name == layout).unwrap(); + assert_eq!(l.entities.iter().map(value).collect::>(), std::slice::from_ref(&layout)); +} + +/// properties.set refuses a justification the selected object type does not have (multiline +/// text has no baseline justifications) instead of reporting a change it did not make. +#[test] +fn a_justification_must_suit_the_selected_objects() { + let mut s = Session::new(); + let r = s.execute("mtext", &json!({ "at": [0, 10], "height": 1, "width": 20, "text": "abc" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + assert!(s.execute("properties.set", &json!({ "handles": [m], "justify": "C" })).is_err()); + assert!(s.execute("properties.set", &json!({ "handles": [m], "justify": "TL" })).is_ok()); +} + +/// MLEADERSTYLE sets the style's arrowhead: a built-in one, a block, or back to closed filled. +#[test] +fn a_multileader_styles_arrowhead_is_set_by_the_command() { + let mut s = Session::new(); + let arrow = |s: &Session| s.doc().unwrap().mleader_styles.iter().find(|m| m.name == "Standard").map(|m| m.arrow_block.clone()); + s.execute("mleaderstyle", &json!({ "name": "Standard", "arrowBlock": "_Open" })).unwrap(); + assert_eq!(arrow(&s).as_deref(), Some("_Open")); + assert!(s.execute("mleaderstyle", &json!({ "name": "Standard", "arrowBlock": "NOSUCHBLOCK" })).is_err()); + s.execute("mleaderstyle", &json!({ "name": "Standard", "arrowBlock": "" })).unwrap(); + assert_eq!(arrow(&s).as_deref(), Some("")); +} + +/// A missing big font is reported with the drawing's other missing fonts. +#[test] +fn a_missing_big_font_is_reported() { + let mut s = Session::new(); + { + let d = s.doc_mut().unwrap(); + let mut st = d.text_styles.first().cloned().unwrap(); + st.name = "ASIAN".into(); + st.font = "txt.shx".into(); + st.big_font = "cadcraft_no_such_bigfont.shx".into(); + d.text_styles.push(st); + } + let r = s.execute("fonts.missing", &json!({})).unwrap(); + let fonts: Vec<&str> = r.as_array().unwrap().iter().filter_map(|f| f["font"].as_str()).collect(); + assert!(fonts.contains(&"cadcraft_no_such_bigfont.shx"), "{fonts:?}"); + assert!(!fonts.contains(&"txt.shx"), "the stroke font stands in for txt.shx"); +} + +/// A new multileader's text that is a formula is worked out as when it is edited; a multiline +/// result keeps `\`, `{` and `}` as letters (#2034 review). +#[test] +fn new_multileader_formulas_and_literal_results() { + let mut s = Session::new(); + s.execute("mleader", &json!({ "points": [[0, 0], [10, 10]], "text": "=2*3" })).unwrap(); + let ml = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::MLeader(m) = &e.kind { m.text.clone() } else { None }).unwrap(); + assert_eq!((cadcraft_fonts::plain_mtext(&ml.contents).as_str(), ml.formula.as_deref()), ("6", Some("=2*3"))); + // In multiline text a brace is written `\{`: the formula is =UPPER("{a}"). + let r = s.execute("mtext", &json!({ "at": [0, 20], "height": 1, "width": 20, "text": "=UPPER(\"\\{a\\}\")" })).unwrap(); + let m = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + let mt = s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&m).unwrap()).map(|e| e.kind.clone()); + let Some(EntityKind::MText(mt)) = mt else { panic!() }; + assert_eq!(mt.formula.as_deref(), Some("=UPPER(\"{a}\")")); + assert_eq!(cadcraft_fonts::plain_mtext(&mt.contents), "{A}", "{}", mt.contents); +} + +/// A dimension formula's `<>` is the measurement itself, not the first number in the shown text: +/// a DIMPOST prefix with a digit (`2X<>`) does not become the value (#2034 review). +#[test] +fn a_dimension_formula_uses_the_measurement_not_the_shown_text() { + let mut s = Session::new(); + s.execute("setvar", &json!({ "name": "DIMPOST", "value": "2X<>" })).unwrap(); + let r = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [1250, 0], "at": [600, 100] })).unwrap(); + let h = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + s.execute("textedit", &json!({ "handle": h, "text": "=<>/2" })).unwrap(); + let d = s.doc().unwrap(); + let EntityKind::Dimension(dm) = &d.model.iter().find(|e| e.handle.hex() == h).unwrap().kind else { panic!() }; + assert_eq!(cadcraft_render::dimension_in(d, dm).value, "625"); +} diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index d05a7fffd6..c0cddf54f1 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -32,10 +32,34 @@ pub(crate) fn formula(tags: &[Tag]) -> Option { (!s.is_empty()).then_some(s) } -/// A formula as 1000 strings of at most 250 characters (whole characters). +/// A formula as 1000 strings of at most 250 bytes (whole characters). pub(crate) fn formula_chunks(f: &str) -> Vec { - let chars: Vec = f.chars().take(4000).collect(); - chars.chunks(250).map(|c| c.iter().collect()).collect() + // An xdata string holds at most 255 bytes: Hebrew, Cyrillic or Chinese letters take 2 to 4 + // bytes each, so the pieces are cut by bytes, between letters. + let mut out = Vec::new(); + let mut cur = String::new(); + for c in f.chars().take(4000) { + if cur.len() + c.len_utf8() > 250 { + out.push(std::mem::take(&mut cur)); + } + cur.push(c); + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +#[cfg(test)] +mod formula_chunk_tests { + #[test] + fn chunks_fit_an_xdata_string_in_bytes() { + let f = format!("=\"{}\"", "שלום ".repeat(200)); + let chunks = super::formula_chunks(&f); + assert!(chunks.iter().all(|c| c.len() <= 250), "{:?}", chunks.iter().map(String::len).collect::>()); + assert_eq!(chunks.concat(), f, "nothing lost, no letter cut"); + assert_eq!(super::formula_chunks("=1+1"), ["=1+1"]); + } } /// An AutoCAD colour value (`1071`/`420`-style, top byte the method): 0xC2 RGB, 0xC3 an index diff --git a/crates/io/src/dxf_fields.rs b/crates/io/src/dxf_fields.rs index 46dd3a3189..e340b3252c 100644 --- a/crates/io/src/dxf_fields.rs +++ b/crates/io/src/dxf_fields.rs @@ -178,4 +178,27 @@ mod tests { assert_eq!(code(&o, "L0", 0), None); assert!(t.elapsed().as_secs() < 5, "took {:?}", t.elapsed()); } + + /// The length cap alone: one level whose filled-in code would pass MAX_LEN is refused. + #[test] + fn a_filled_in_code_past_the_limit_is_refused() { + let mut o = HashMap::new(); + o.insert("A".to_string(), field("%<\\_FldIdx 0>%%<\\_FldIdx 1>%%<\\_FldIdx 2>%", &["B", "B", "B"])); + o.insert("B".to_string(), field(&"x".repeat(MAX_LEN / 2), &[])); + assert_eq!(code(&o, "A", 0), None); + } + + /// Shared children alone: eight levels of two places using one child each fit the limit and + /// are worked out (each child once per level, not 2^8 times). + #[test] + fn shared_children_are_filled_in() { + let mut o = HashMap::new(); + for k in 0..MAX_DEPTH { + let next = format!("L{}", k + 1); + o.insert(format!("L{k}"), field("%<\\_FldIdx 0>%%<\\_FldIdx 1>%", &[next.as_str(), next.as_str()])); + } + o.insert(format!("L{MAX_DEPTH}"), field("x", &[])); + let c = code(&o, "L0", 0).expect("fits the limit"); + assert_eq!(c.matches('x').count(), 1 << MAX_DEPTH); + } } diff --git a/crates/io/src/dxf_mleader.rs b/crates/io/src/dxf_mleader.rs index faa0f97783..8b0b408819 100644 --- a/crates/io/src/dxf_mleader.rs +++ b/crates/io/src/dxf_mleader.rs @@ -285,14 +285,12 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { leaders.push(l); } } + // Leader type None: the leader lines are kept (written back as they were) but not drawn. let none = p.leader_type == Some(0); - if none { - leaders.clear(); - } let text_location = p.text_location.get(); let block_location = p.block_location.get(); let landing = p.roots.iter().find_map(|r| r.landing.get()).or(p.base.get()).or(text_location).or(block_location).unwrap_or(Vec3::ZERO); - let dogleg = if leaders.is_empty() || p.dogleg_on == Some(false) { + let dogleg = if none || leaders.is_empty() || p.dogleg_on == Some(false) { 0.0 } else { p.roots.iter().find_map(|r| r.dogleg).or(p.dogleg).filter(|d| *d >= 0.0).unwrap_or(0.0) @@ -334,7 +332,7 @@ pub(crate) fn read(tags: &[Tag]) -> MLeader { row_spacing: 0.0, } }); - let no_leader = p.leader_type == Some(0) && !leaders.is_empty(); + let no_leader = none && !leaders.is_empty(); MLeader { leaders, landing, diff --git a/crates/io/tests/it/mleader_roundtrip.rs b/crates/io/tests/it/mleader_roundtrip.rs index 75ac01bce0..83891abc9b 100644 --- a/crates/io/tests/it/mleader_roundtrip.rs +++ b/crates/io/tests/it/mleader_roundtrip.rs @@ -293,3 +293,21 @@ fn a_multileaders_own_arrowhead_survives() { let got: Vec = mleaders(&back).iter().map(|m| m.arrow.to_ascii_uppercase()).collect(); assert_eq!(got, ["HATZ", "_OPEN30", ""], "own arrowheads kept, the style's left to the style"); } + +/// Leader type None with leader lines in the file: the lines are kept (hidden), not thrown away, +/// so the multileader comes back as it was (#2034 review). +#[test] +fn hidden_leader_lines_are_kept() { + let mut d = Drawing::new_metric(); + let mut m = text_mleader(); + m.no_leader = true; + m.dogleg = 0.0; + m.style = "Standard".into(); + d.add(&Space::Model, Common::default(), EntityKind::MLeader(m.clone())).unwrap(); + let (_, back) = roundtrip(&d); + let got = mleaders(&back); + assert_eq!(got.len(), 1); + assert!(got[0].no_leader, "still hidden"); + assert_eq!(got[0].leaders, m.leaders, "the lines are kept"); + assert!(got[0].leader_paths().is_empty(), "and not drawn"); +} diff --git a/crates/render/src/dim.rs b/crates/render/src/dim.rs index 0edda40c6e..50aa2bb040 100644 --- a/crates/render/src/dim.rs +++ b/crates/render/src/dim.rs @@ -428,7 +428,15 @@ fn linear_text(meas: f64, d: &Dimension, st: &DimStyle, prefix: &str) -> String let alt = format_linear(v * st.alt_factor, &af).1; s += &format!(" [{}]", post(&st.alt_post, &alt)); } - inspected(apply_override(&s, d), d) + inspected(apply_override(&s, d, Some(shown_value(v, nf.decimals))), d) +} + +/// A measurement rounded as the dimension shows it (`decimals` places), for a formula's `<>`: +/// `=<>/2` of a 1250 dimension is 625, not 624.99995. +fn shown_value(v: f64, decimals: u8) -> f64 { + let k = 10f64.powi(i32::from(decimals.min(8))); + let r = (v * k).round() / k; + if r.is_finite() { r } else { v } } /// DIMINSPECT: the label and the rate either side of the value, two spaces apart. @@ -468,10 +476,13 @@ fn measured_number(base: &str) -> Option { } /// Apply dimension text overrides: empty uses the base, whitespace suppresses text, and other text substitutes it. -fn apply_override(base: &str, d: &Dimension) -> String { - // A formula: worked out with `<>` as the measurement (shown as the dimension shows it). +/// `value`: the measurement as a number (in the dimension's units, degrees for an angle), which a +/// formula's `<>` stands for; read back from the formatted text when not given. +fn apply_override(base: &str, d: &Dimension, value: Option) -> String { + // A formula: worked out with `<>` as the measurement. if let Some(f) = d.marks.formula.as_deref().filter(|f| crate::textformula::is_formula(f)) { - let env = crate::textformula::Env { measured: measured_number(base), now: crate::textformula::local_now(), ..Default::default() }; + let measured = value.filter(|v| v.is_finite()).or_else(|| measured_number(base)); + let env = crate::textformula::Env { measured, now: crate::textformula::local_now(), ..Default::default() }; if let Some(v) = crate::textformula::evaluate(f, &env) { return v; } @@ -1002,7 +1013,7 @@ pub fn dimension_geometry_with(d: &Dimension, st: &DimStyle, dimscale: f64, font let azin = (st.angular_zero_suppression & 3) * 4; let txt = format_angle_with_separator(sweep, st.angular_unit, st.angular_decimals, azin, &st.decimal_separator); // DIMPOST is a linear-dimension prefix/suffix; angles have their own format only. - g.mtext = inspected(apply_override(&txt, d), d); + g.mtext = inspected(apply_override(&txt, d, Some(shown_value(sweep.to_degrees(), st.angular_decimals))), d); let mut pts = Vec::new(); arc.tessellate(r * 1e-3, &mut pts); g.dim(pts); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7ac82e7aad..cc28f48798 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1508,27 +1508,15 @@ pub fn named_arrow(d: &Drawing, name: &str, tip: Vec2, dir: Vec2, size: f64) -> /// the arrow pointing along +x at unit size). Built-in arrowhead blocks (`_Oblique`…) are /// drawn in code instead, so they are left out. fn user_arrow(d: &Drawing, name: &str) -> Option { - use std::collections::HashMap; - use std::sync::{Mutex, OnceLock, PoisonError}; if name.starts_with('_') { return None; } - let b = arrow_block(d, name)?; - static CACHE: OnceLock>>> = OnceLock::new(); - let key = (b as *const cadcraft_doc::Block as usize, b.entities.len(), name.to_string()); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Some(g) = cache.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { - return g.clone(); - } - let g = arrow_geometry(b); - let mut c = cache.lock().unwrap_or_else(PoisonError::into_inner); - if c.len() > 512 { - c.clear(); - } - c.insert(key, g.clone()); - g + // Worked out from the block each time (at most 512 of its objects): a cache keyed by the + // block's address could hand one drawing's arrowhead to another, or keep an edited one. + arrow_geometry(arrow_block(d, name)?) } +/// The geometry of a user arrowhead block (see [`user_arrow`]). fn arrow_geometry(b: &cadcraft_doc::Block) -> Option { use cadcraft_doc::EntityKind as K; const SEGS: usize = 32; @@ -1573,17 +1561,15 @@ fn arrow_geometry(b: &cadcraft_doc::Block) -> Option { g.lines.push(arc_pts(a.center.xy(), a.radius, a.start, sweep)); } K::LwPolyline(p) => { - let pts = poly_pts(&p.vertices, p.closed); let w = p.const_width.max(p.vertices.iter().map(|v| v.start_width.max(v.end_width)).fold(0.0, f64::max)); if w > 1e-12 { - // A wide polyline: each piece a filled band. - for s in pts.windows(2) { - let (a, c) = (s[0], s[1]); - let n = (c - a).perp().normalized() * (w / 2.0); - g.tris.extend([a - n, c - n, c + n, a - n, c + n, a + n]); - } + // A wide polyline with its widths as drawn, tapers included (a tip from width + // 0 to 1 is a triangle, not a band). + let size = Bounds2::from_points(p.vertices.iter().map(|v| v.p)); + let tol = ((size.width() + size.height()).max(w) / 2000.0).max(1e-9); + g.tris.extend(fill::wide_polyline(p, tol).into_iter().map(|q| q - base)); } else { - g.lines.push(pts); + g.lines.push(poly_pts(&p.vertices, p.closed)); } } K::Solid(s) | K::Trace(s) => { @@ -1593,14 +1579,10 @@ fn arrow_geometry(b: &cadcraft_doc::Block) -> Option { } } K::Hatch(h) if h.solid => { - for l in &h.loops { - let pts = poly_pts(&l.vertices, true); - if let Some((&first, rest)) = pts.split_first() { - for s in rest.windows(2) { - g.tris.extend([first, s[0], s[1]]); - } - } - } + // Its loops together, even-odd: an island stays a hole, a concave outline is + // filled as it is. + let loops: Vec> = h.loops.iter().map(|l| poly_pts(&l.vertices, true)).collect(); + g.tris.extend(fill::triangulate_evenodd(&loops)); } _ => {} } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 1961322609..a7ef9a9643 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1021,3 +1021,53 @@ fn wide_polyline_centre_line_is_drawn_on_screen_only() { assert_eq!(lines(&see_through), 0, "{lt}: a transparent band gets no hairline"); } } + +/// A user arrowhead block: a solid hatch with an island keeps its hole; a polyline that tapers +/// from width 0 to 1 is a triangle, not a band (#2034 review). +#[test] +fn user_arrowheads_keep_holes_and_tapers() { + use cadcraft_doc::{Block, Entity, EntityKind, Handle, Hatch, HatchLoop, LwPolyline}; + use cadcraft_geom::PolyVertex; + let sq = |a: f64, b: f64| HatchLoop { + vertices: [(a, a), (b, a), (b, b), (a, b)].iter().map(|(x, y)| PolyVertex::new(Vec2::new(*x, *y))).collect(), + outer: a == 0.0, + sources: Vec::new(), + }; + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops: vec![sq(0.0, 1.0), sq(0.25, 0.75)], + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + let mut b = Block::new("HOLE"); + b.entities.push(Entity::new(Handle(1), EntityKind::Hatch(hatch))); + let g = super::arrow_geometry(&b).expect("geometry"); + let area: f64 = g.tris.chunks(3).map(|t| ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs()).sum(); + assert!((area - 0.75).abs() < 1e-6, "the island stays a hole: {area}"); + let inside = |p: Vec2| { + g.tris.chunks(3).any(|t| { + let s = |a: Vec2, b: Vec2| (b - a).cross(p - a); + let (d1, d2, d3) = (s(t[0], t[1]), s(t[1], t[2]), s(t[2], t[0])); + !((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0)) + }) + }; + assert!(!inside(Vec2::new(0.5, 0.5)) && inside(Vec2::new(0.1, 0.5))); + // The tip: from (0,0) width 0 to (-1,0) width 1. + let mut v0 = PolyVertex::new(Vec2::ZERO); + v0.end_width = 1.0; + let tip = + LwPolyline { vertices: vec![v0, PolyVertex::new(Vec2::new(-1.0, 0.0))], closed: false, const_width: 0.0, elevation: 0.0, plinegen: false }; + let mut b = Block::new("TIP"); + b.entities.push(Entity::new(Handle(1), EntityKind::LwPolyline(tip))); + let g = super::arrow_geometry(&b).expect("geometry"); + let area: f64 = g.tris.chunks(3).map(|t| ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs()).sum(); + assert!((area - 0.5).abs() < 1e-6, "a triangle of base 1 and length 1: {area}"); +} diff --git a/crates/render/src/textformula.rs b/crates/render/src/textformula.rs index 053d963dad..9bf6d62d00 100644 --- a/crates/render/src/textformula.rs +++ b/crates/render/src/textformula.rs @@ -251,6 +251,9 @@ fn serial(y: i64, m: i64, d: i64) -> f64 { /// (year, month, day, hour, minute, second) of a serial. fn parts(s: f64) -> (i64, i64, i64, i64, i64, i64) { + // About ±8000 years around 1900: the calendar arithmetic stays far from overflowing (a + // file's formula can hold any number, `=YEAR(1E300)`). + let s = if s.is_finite() { s.clamp(-3_000_000.0, 3_000_000.0) } else { 0.0 }; let days = s.floor(); let secs = ((s - days) * 86_400.0).round() as i64; let (y, m, d) = civil_from_days(days as i64 - EPOCH_SERIAL); @@ -570,6 +573,21 @@ impl P<'_> { } Ok(v) } + /// Where the argument starting here ends: the next comma or closing parenthesis outside + /// any parentheses it opens (`None`: the formula ends first). + fn arg_end(&self) -> Option { + let mut level = 0usize; + for (k, t) in self.t.iter().enumerate().skip(self.i) { + match t { + Tok::LParen => level += 1, + Tok::RParen if level == 0 => return Some(k), + Tok::RParen => level -= 1, + Tok::Comma if level == 0 => return Some(k), + _ => {} + } + } + None + } fn atom(&mut self) -> R { self.depth += 1; if self.depth > MAX_DEPTH { @@ -597,10 +615,22 @@ impl P<'_> { return Err(Err::Name); } self.i += 1; - let mut args = Vec::new(); + // Each argument's value or the error working it out gave: IF uses only the branch + // it picks, so an error in the other one (`=IF(TRUE;1;1/0)`) doesn't count. + let mut args: Vec = Vec::new(); if self.peek() != Some(&Tok::RParen) { loop { - args.push(self.compare()?); + let end = self.arg_end().ok_or(Err::Syntax)?; + let depth = self.depth; + let v = self.compare(); + self.depth = depth; + match v { + Err(Err::Syntax) => return Err(Err::Syntax), + Ok(_) if self.i != end => return Err(Err::Syntax), + _ => {} + } + self.i = end; + args.push(v); if args.len() > MAX_ARGS { return Err(Err::Value); } @@ -612,7 +642,15 @@ impl P<'_> { } } self.i += 1; - call(&n, &args, self.env) + if n == "IF" { + let mut it = args.into_iter(); + let c = it.next().unwrap_or(Err(Err::Value))?.truth()?; + let (yes, no) = (it.next(), it.next()); + if c { yes.unwrap_or(Ok(Val::Bool(true))) } else { no.unwrap_or(Ok(Val::Bool(false))) } + } else { + let args: Vec = args.into_iter().collect::>()?; + call(&n, &args, self.env) + } } _ => Err(Err::Syntax), }; @@ -790,6 +828,28 @@ mod tests { evaluate(f, &env()).unwrap_or_default() } + /// Huge or infinite dates never overflow (a crash in a test build, nonsense otherwise). + #[test] + fn huge_date_serials_do_not_overflow() { + for f in ["=YEAR(1E300)", "=YEAR(-1E300)", "=TEXT(1E300,\"yyyy\")", "=TODAY()+1E300", "=MONTH(1E308*10)"] { + let _ = ev(f); + } + assert_eq!(ev("=YEAR(45000)"), "2023"); + } + + /// IF works out only the branch it picks: an error in the other one is not its result + /// (#2034 review). Errors in the condition or the picked branch still show. + #[test] + fn if_uses_only_the_branch_it_picks() { + assert_eq!(ev("=IF(TRUE,1,1/0)"), "1"); + assert_eq!(ev("=IF(FALSE,1/0,2)"), "2"); + assert_eq!(ev("=IF(1<2;(1/0)+5;3)"), "#DIV/0!"); + assert_eq!(ev("=IF(1/0,1,2)"), "#DIV/0!"); + assert_eq!(ev("=IF(FALSE,SQRT(-1)*2,IF(TRUE,7,1/0))"), "7"); + assert_eq!(ev("=SUM(1,1/0)"), "#DIV/0!", "other functions still need every argument"); + assert_eq!(ev("=IF(TRUE,1 2,3)"), "#ERROR!", "a malformed branch is still an error"); + } + #[test] fn arithmetic_and_functions() { assert_eq!(ev("=2400-2*18"), "2364"); diff --git a/crates/ui-egui/src/bidi_edit.rs b/crates/ui-egui/src/bidi_edit.rs index dc400aa8ac..2c8d3739a1 100644 --- a/crates/ui-egui/src/bidi_edit.rs +++ b/crates/ui-egui/src/bidi_edit.rs @@ -382,13 +382,17 @@ pub fn show( let before_cursor = st.cursor; let mut edited = false; for ev in events { - let lay = layout(&chars, look, (!single_line).then_some(inner_w), default_size); + // Laid out only for the keys that move by what is on screen (arrows, Home, End). + let lay = || layout(&chars, look, (!single_line).then_some(inner_w), default_size); match ev { Event::Ime(egui::ImeEvent::Preedit { text, .. }) => st.preedit = text, Event::Text(s) | Event::Paste(s) | Event::Ime(egui::ImeEvent::Commit(s)) => { st.preedit.clear(); - let s: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !single_line)).collect(); + // Line breaks (Windows' \r\n too) become spaces in a one-line box, before + // other control characters are dropped. + let s = s.replace("\r\n", "\n").replace('\r', "\n"); let s = if single_line { s.replace('\n', " ") } else { s }; + let s: String = s.chars().filter(|c| !c.is_control() || *c == '\n').collect(); edited |= replace(&mut chars, st, &s, max_chars); } Event::Copy | Event::Cut => { @@ -405,6 +409,7 @@ pub fn show( let mut moved = None; match key { Key::ArrowLeft | Key::ArrowRight => { + let lay = lay(); let dir = if key == Key::ArrowLeft { -1.0 } else { 1.0 }; let (a, b) = st.range(); moved = Some(if word { @@ -422,6 +427,7 @@ pub fn show( st.preferred_x = None; } Key::ArrowUp | Key::ArrowDown => { + let lay = lay(); let (li, x) = lay.caret_x(st.cursor); let px = *st.preferred_x.get_or_insert(x); let to = if key == Key::ArrowUp { li.checked_sub(1) } else { Some(li + 1).filter(|n| *n < lay.lines.len()) }; @@ -432,10 +438,12 @@ pub fn show( }); } Key::Home => { + let lay = lay(); moved = Some(if modifiers.command { 0 } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.start) }); st.preferred_x = None; } Key::End => { + let lay = lay(); moved = Some(if modifiers.command { chars.len() } else { lay.lines.get(lay.line_of(st.cursor)).map_or(0, |l| l.end) }); st.preferred_x = None; } @@ -674,6 +682,31 @@ mod tests { assert_eq!(walk(0, 1.0), c.len(), "Right from the start reaches the end"); } + /// A paste of several lines into a one-line box keeps a space where each break was + /// (`\n` and Windows' `\r\n`), instead of running the lines together (#2034 review). + #[test] + fn a_pasted_line_break_is_a_space_in_a_one_line_box() { + let ctx = egui::Context::default(); + for (pasted, want_line, want_box) in [("one\ntwo", "one two", "one\ntwo"), ("one\r\ntwo\tthree", "one twothree", "one\ntwothree")] { + for single in [true, false] { + let mut text = String::new(); + let mut st = EditState::default(); + let id = egui::Id::unique(("paste_test", single, pasted)); + let raw = |events| egui::RawInput { events, ..Default::default() }; + let run = |text: &mut String, st: &mut EditState, events| { + let mut out = ctx.run_ui(raw(events), |ui| { + ui.memory_mut(|m| m.request_focus(id)); + show(ui, id, text, st, single, 300.0, 1, &look, 20.0, 1000); + }); + out.textures_delta.clear(); + }; + run(&mut text, &mut st, Vec::new()); + run(&mut text, &mut st, vec![Event::Paste(pasted.into())]); + assert_eq!(text, if single { want_line } else { want_box }, "single line: {single}"); + } + } + } + #[test] fn wrapping_breaks_at_spaces() { let c: Vec = "aaaa bbbb cccc".chars().collect(); diff --git a/crates/ui-egui/src/blockmgr.rs b/crates/ui-egui/src/blockmgr.rs index ee20ff0c56..35e7b28120 100644 --- a/crates/ui-egui/src/blockmgr.rs +++ b/crates/ui-egui/src/blockmgr.rs @@ -25,7 +25,7 @@ struct State { /// A block's preview, built once per block and drawing revision. #[derive(Clone)] struct Preview { - key: (String, u64), + key: (String, u64, u64), list: Arc, bounds: Bounds2, } @@ -117,8 +117,9 @@ pub fn paint_list(p: &egui::Painter, r: Rect, list: &cadcraft_render::DisplayLis /// The preview of `name`, from the cache when the drawing hasn't changed. fn preview(app: &CadApp, ctx: &egui::Context, name: &str) -> Option { - let revision = app.session.state().map(|s| s.revision).unwrap_or(0); - let key = (name.to_string(), revision); + // The drawing too: two open drawings can have a block of that name at the same revision. + let (doc, revision) = app.session.state().map(|s| (s.uid, s.revision)).unwrap_or((0, 0)); + let key = (name.to_string(), doc, revision); let id = egui::Id::unique("cc_block_manager_preview"); if let Some(p) = ctx.data(|d| d.get_temp::(id)).filter(|p| p.key == key) { return Some(p); diff --git a/crates/ui-egui/src/custom_patterns.rs b/crates/ui-egui/src/custom_patterns.rs index cb55ecb4dc..7b8b8cdb47 100644 --- a/crates/ui-egui/src/custom_patterns.rs +++ b/crates/ui-egui/src/custom_patterns.rs @@ -34,7 +34,7 @@ pub struct Found { struct Listing { folder: String, generation: u64, - patterns: Vec, + patterns: std::rc::Rc>, problem: Option, } @@ -57,13 +57,21 @@ pub fn scan(folder: &str) -> (Vec, Option) { let Ok(rd) = std::fs::read_dir(dir) else { return (Vec::new(), Some(crate::tl!("This folder does not exist").to_string())); }; - let mut files: Vec = rd - .flatten() - .map(|e| e.path()) - .filter(|p| p.is_file() && p.extension().is_some_and(|x| x.eq_ignore_ascii_case("pat"))) - .take(MAX_FILES) - .collect(); + let mut files: Vec = Vec::new(); + for entry in rd.take(MAX_FILES * 20) { + let entry = match entry { + Ok(e) => e, + Err(e) => return (Vec::new(), Some(format!("{}: {e}", crate::tl!("The folder can't be read")))), + }; + // `file_type` does not follow symbolic links: a link to a file elsewhere is not read. + let path = entry.path(); + if entry.file_type().is_ok_and(|t| t.is_file()) && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("pat")) { + files.push(path); + } + } + // The same files every time: sorted, then the first ones kept. files.sort(); + files.truncate(MAX_FILES); let mut out = Vec::new(); for path in files { if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(u64::MAX) > MAX_FILE_BYTES { @@ -84,13 +92,14 @@ pub fn scan(folder: &str) -> (Vec, Option) { } /// The folder's patterns, read again when the folder or the reload count changed. -fn listing(folder: &str) -> (Vec, Option) { +/// Shared, not copied: the tab asks for it every frame and a folder may hold thousands. +fn listing(folder: &str) -> (std::rc::Rc>, Option) { let generation = GENERATION.with(|g| *g.borrow()); LISTING.with(|cell| { let mut l = cell.borrow_mut(); if l.folder != folder || l.generation != generation { let (patterns, problem) = scan(folder); - *l = Listing { folder: folder.to_string(), generation, patterns, problem }; + *l = Listing { folder: folder.to_string(), generation, patterns: std::rc::Rc::new(patterns), problem }; } (l.patterns.clone(), l.problem.clone()) }) @@ -157,7 +166,7 @@ pub fn tab_ui(ui: &mut egui::Ui, folder: &mut String, pattern: &mut String, file .min_scrolled_height(200.0) .show(ui, |ui| { ui.set_width(182.0); - for f in &found { + for f in found.iter() { let on = selected.is_some_and(|s| s.name == f.name && s.file == f.file); let tip = if f.description.is_empty() { f.file.clone() } else { format!("{}\n{}", f.description, f.file) }; if ui.selectable_label(on, &f.name).on_hover_text(tip).clicked() { @@ -204,6 +213,16 @@ mod tests { assert_eq!(found.get(1).map(|f| f.lines.len()), Some(2)); let (none, problem) = super::scan(&dir.join("missing").to_string_lossy()); assert!(none.is_empty() && problem.is_some()); + // A symbolic link to a pattern file elsewhere is not read. + #[cfg(unix)] + { + let outside = std::env::temp_dir().join(format!("cadcraft-outside-{}.pat", std::process::id())); + std::fs::write(&outside, "*OUTSIDE, x\n0, 0,0, 0,1\n").unwrap(); + let _ = std::os::unix::fs::symlink(&outside, dir.join("link.pat")); + let (found, _) = super::scan(&dir.to_string_lossy()); + assert!(!found.iter().any(|f| f.name == "OUTSIDE"), "a link is skipped"); + let _ = std::fs::remove_file(outside); + } let _ = std::fs::remove_dir_all(dir); } } diff --git a/crates/ui-egui/src/editor_glyphs.rs b/crates/ui-egui/src/editor_glyphs.rs index 9a505b973f..b2be508f00 100644 --- a/crates/ui-egui/src/editor_glyphs.rs +++ b/crates/ui-egui/src/editor_glyphs.rs @@ -52,7 +52,18 @@ fn fonts() -> &'static Mutex> { F.get_or_init(|| Mutex::new(HashMap::new())) } +/// Forget what was worked out with fonts that changed since: the font folders were edited or +/// searched again ([`cadcraft_fonts::ttf::generation`]), so a font that was missing may be there. +fn follow_font_changes() { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = cadcraft_fonts::ttf::generation(); + if SEEN.swap(now, std::sync::atomic::Ordering::Relaxed) != now { + clear(); + } +} + fn resolve(font: &str, big: &str) -> TextFont { + follow_font_changes(); let k = (font.to_string(), big.to_string()); let mut f = fonts().lock().unwrap_or_else(PoisonError::into_inner); if let Some(t) = f.get(&k) { @@ -73,6 +84,7 @@ pub fn clear() { } fn glyph(f: &EditorFont, italic: bool, c: char) -> std::sync::Arc { + follow_font_changes(); let oblique = f.oblique + if italic { ITALIC } else { 0.0 }; let key = (f.font.clone(), f.big_font.clone(), f.wf().to_bits(), oblique.to_bits(), c); if let Some(g) = cache().lock().unwrap_or_else(PoisonError::into_inner).get(&key) { @@ -160,4 +172,16 @@ mod tests { assert!(advance(&f, false, ' ', 20.0) > 0.0); assert!(!glyph(&f, false, 'A').shaped.strokes.is_empty()); } + + /// A font missing when the editor first asked for it is looked up again once the fonts are + /// searched again (a font folder added), without restarting (#2034 review). + #[test] + fn a_rescan_forgets_resolved_fonts() { + let key = ("cadcraft_editor_cache_test.shx".to_string(), String::new()); + let _ = resolve(&key.0, ""); + assert!(fonts().lock().unwrap_or_else(PoisonError::into_inner).contains_key(&key)); + cadcraft_fonts::ttf::rescan(); + let _ = resolve("", ""); + assert!(!fonts().lock().unwrap_or_else(PoisonError::into_inner).contains_key(&key), "forgotten after the rescan"); + } } diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3386d6833b..03ef7a0211 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1062,7 +1062,7 @@ Changes apply at once and are kept for next time. Изменения применяются сразу и сохраняются до следующего запуска. Fonts Шрифты Font folders Папки шрифтов - Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Положите шрифты TrueType или OpenType (.ttf, .otf, .ttc) в папку и добавьте её сюда. Эти папки просматриваются раньше системных шрифтов; папка выше в списке имеет приоритет. + Put TrueType, OpenType or SHX fonts (.ttf, .otf, .ttc, .shx) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Положите шрифты TrueType, OpenType или SHX (.ttf, .otf, .ttc, .shx) в папку и добавьте её сюда. Эти папки просматриваются раньше системных шрифтов; папка выше в списке имеет приоритет. No font folders yet Папок шрифтов пока нет This folder does not exist Такой папки нет Add Folder... Добавить папку... @@ -1798,3 +1798,4 @@ Check for Updates… Проверить обновления… CADCraft is up to date. У вас последняя версия CADCraft. Could not check for updates. Не удалось проверить обновления. + The folder can't be read Папку не удаётся прочитать diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3b7196cb64..5e1141d567 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1390,7 +1390,7 @@ Current Layer Поточний шар Fonts Шрифти Font folders Теки шрифтів - Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Покладіть шрифти TrueType або OpenType (.ttf, .otf, .ttc) у теку й додайте її сюди. Ці теки переглядаються раніше за системні шрифти; тека вище у списку має пріоритет. + Put TrueType, OpenType or SHX fonts (.ttf, .otf, .ttc, .shx) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins. Покладіть шрифти TrueType, OpenType або SHX (.ttf, .otf, .ttc, .shx) у теку й додайте її сюди. Ці теки переглядаються раніше за системні шрифти; тека вище у списку має пріоритет. No font folders yet Тек шрифтів ще немає This folder does not exist Такої теки немає Add Folder... Додати теку... @@ -1913,3 +1913,4 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. + The folder can't be read Теку не вдається прочитати diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index de1872d824..fa2be16b7b 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -227,7 +227,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } let base_h = if mt.height > 0.0 { mt.height } else { 0.2 }; let px = ((base_h * scale) as f32).clamp(MIN_PX, MAX_PX); - let width = if mt.width > 0.0 { ((mt.width * scale) as f32).clamp(380.0, rect.width().max(380.0) * 0.9) } else { 380.0 }; + let width = editor_width(mt.width * scale, rect.width()); // The box's top-left corner on screen (rotation is ignored while editing). let code = usize::from(mt.attach.clamp(1, 9) - 1); let (col, row) = ((code % 3) as f64, (code / 3) as f64); @@ -631,6 +631,16 @@ fn toolbar(ui: &mut egui::Ui, st: &mut State, base_h: f64) { } } +/// The editor's width on screen for a text `text_w` wide (pixels; 0 or less: no width set) on a +/// canvas `canvas_w` wide: at least 380 pixels, at most nine tenths of the canvas, and never a +/// minimum above the maximum (a narrow window). +fn editor_width(text_w: f64, canvas_w: f32) -> f32 { + let max = (canvas_w * 0.9).max(120.0); + let min = 380.0_f32.min(max); + let w = text_w as f32; + if text_w > 0.0 && w.is_finite() { w.clamp(min, max) } else { min } +} + /// The symbols of the Additional symbols menu: drafting marks, comparisons, Greek letters, /// powers and fractions. const SYMBOLS: [(&str, &str); 32] = [ @@ -1086,6 +1096,24 @@ mod tests { assert!(harness.unnamed_widgets().is_empty(), "unnamed controls: {:?}", harness.unnamed_widgets()); } + /// A narrow window (400 pixels and less) never orders the bounds the wrong way round, which + /// would panic (#2034 review); the width stays within the canvas. + #[test] + fn the_editor_width_fits_narrow_canvases() { + for canvas in [0.0_f32, 50.0, 300.0, 400.0, 421.0, 800.0, 2000.0, f32::NAN] { + for text in [-1.0, 0.0, 10.0, 370.0, 390.0, 5000.0, f64::NAN, f64::INFINITY] { + let w = editor_width(text, canvas); + assert!(w.is_finite() && w > 0.0, "{canvas} {text}: {w}"); + if canvas.is_finite() && canvas >= 140.0 { + assert!(w <= canvas * 0.9 + 1e-3, "{canvas} {text}: {w}"); + } + } + } + assert_eq!(editor_width(0.0, 2000.0), 380.0); + assert_eq!(editor_width(1000.0, 2000.0), 1000.0); + assert_eq!(editor_width(500.0, 400.0), 360.0); + } + #[test] fn editor_opens_only_for_mtext_text_entry_and_finishes_with_formatted_contents() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/options/dialog.rs b/crates/ui-egui/src/options/dialog.rs index 8c23c4f9bb..d28961bb59 100644 --- a/crates/ui-egui/src/options/dialog.rs +++ b/crates/ui-egui/src/options/dialog.rs @@ -264,7 +264,7 @@ fn fonts(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { hint( ui, crate::tl!( - "Put TrueType or OpenType fonts (.ttf, .otf, .ttc) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins." + "Put TrueType, OpenType or SHX fonts (.ttf, .otf, .ttc, .shx) in a folder and add it here. These folders are searched before the system fonts; a folder higher in the list wins." ), ); ui.add_space(4.0); @@ -355,7 +355,10 @@ fn fonts(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map) { let generation = cadcraft_fonts::ttf::generation(); let mut seen: FontsSeen = ui.data(|d| d.get_temp(seen_id)).unwrap_or_default(); if seen.generation != Some(generation) { - let fonts = cadcraft_fonts::ttf::installed().into_iter().filter(|f| f.user).map(|f| (f.name, f.family)).collect(); + // Outline fonts with their family names, then the SHX fonts. + let mut fonts: Vec<(String, Option)> = + cadcraft_fonts::ttf::installed().into_iter().filter(|f| f.user).map(|f| (f.name, f.family)).collect(); + fonts.extend(cadcraft_fonts::shx::installed().into_iter().map(|stem| (format!("{stem}.shx"), None))); seen = FontsSeen { generation: Some(generation), fonts }; ui.data_mut(|d| d.insert_temp(seen_id, seen.clone())); } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index d71b3310c2..29a2d152d2 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -225,12 +225,16 @@ fn dwg_preview(sec: &[u8], at: u64) -> Option { /// The THUMBNAILIMAGE section's bitmap (hex in group 310 lines). #[cfg(not(target_arch = "wasm32"))] fn dxf_preview(text: &str) -> Option> { + /// Largest preview read (hostile files). + const MAX_BYTES: usize = 16 << 20; let at = text.find("THUMBNAILIMAGE")?; - let mut lines = text.get(at..)?.lines().map(str::trim); + // From the line after the section's name, group code and value pairs. + let mut lines = text.get(at..)?.lines().skip(1).map(str::trim); let mut out = Vec::new(); while let Some(code) = lines.next() { let value = lines.next()?; match code { + "310" if out.len() + value.len() / 2 > MAX_BYTES => return None, "310" => { let b = value.as_bytes(); for pair in b.chunks(2) { @@ -402,6 +406,18 @@ pub fn paint_missing(p: &egui::Painter, r: egui::Rect, ink: egui::Color32) { #[cfg(test)] mod tests { + /// The section is read as group code / value pairs from the line after its name: the bytes + /// come back, not a misaligned nothing (#2034 review). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_dxf_thumbnail_section_is_read_in_pairs() { + let dxf = " 0\nSECTION\n 2\nTHUMBNAILIMAGE\n 90\n2\n310\nAABB\n 0\nENDSEC\n 0\nEOF\n"; + assert_eq!(super::dxf_preview(dxf), Some(vec![0xAA, 0xBB])); + let crlf = dxf.replace('\n', "\r\n"); + assert_eq!(super::dxf_preview(&crlf), Some(vec![0xAA, 0xBB])); + assert_eq!(super::dxf_preview(" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n"), None); + } + #[test] fn a_bitmap_decodes_bottom_up_with_its_palette() { // 2×2, 8 bits, two palette colours: bottom row red/green, top row green/red. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 93b74b138d..6f24f72e5f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -449,6 +449,22 @@ pub fn sanitize(items: &[String]) -> Vec { out } +/// The bar's items as the Customize dialog edits them: known commands once each and every +/// separator where it is (side by side, first or last too), so a separator added at the end +/// stays for the command added after it. The bar itself shows them [`sanitize`]d. +pub fn editable(items: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for item in items.iter().take(MAX_ITEMS * 4) { + if out.len() >= MAX_ITEMS { + break; + } + if item == SEPARATOR || (find(item).is_some() && !out.contains(item)) { + out.push(item.clone()); + } + } + out +} + /// Move the item at `from` so it lands before the item now at `slot` (`items.len()` = the end). pub fn move_item(items: &mut Vec, from: usize, slot: usize) { if from >= items.len() || slot > items.len() { @@ -1525,7 +1541,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, which: &str, open: &mut boo let state_id = id.with(("state", bar.id())); let mut st: DialogState = ctx.data(|d| d.get_temp(state_id)).unwrap_or_default(); let bar_state = state(&app.ui, bar); - let mut items = sanitize(&bar_state.items); + let mut items = editable(&bar_state.items); let mut dock = bar_state.dock; let mut show = bar_state.show; let mut changed = false; @@ -1799,6 +1815,19 @@ mod tests { assert!(missing.is_empty(), "{missing:?}"); } + /// The Customize dialog keeps a separator added at the end (and two side by side) while + /// editing, so a command can follow it; the bar shows the cleaned list (#2034 review). + #[test] + fn editing_keeps_separators_where_they_are() { + let items = strings(&["line", "|", "|", "nosuch", "line", "|"]); + assert_eq!(editable(&items), strings(&["line", "|", "|", "|"])); + let mut list = editable(&strings(&["line"])); + list.push(SEPARATOR.to_string()); + assert_eq!(editable(&list), strings(&["line", "|"]), "the trailing separator survives the next frame"); + list.push("circle".to_string()); + assert_eq!(sanitize(&list), strings(&["line", "|", "circle"])); + } + #[test] fn sanitize_drops_unknown_repeated_and_stray_separators() { let items = strings(&["|", "line", "nonsense", "line", "|", "|", "circle", "|"]);