From fcb42c3d8e42d93f1a4557abb359eed355de1450 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Mon, 12 Oct 2026 13:50:03 +0300 Subject: [PATCH 001/201] i18n(ru): translate 547 more labels, dialog strings and tooltips The Russian catalog had 318 entries; every label, dialog string and tooltip that another catalog already translates (including the open Czech, Polish, Turkish and Spanish-dialog PRs) now has a Russian entry too: 865 in all. Terminology follows the names Excel uses in its Russian interface; the Paste Special access letters stay Latin, as in the Spanish catalog. --- crates/ui-egui/src/i18n/ru.rs | 567 ++++++++++++++++++++++++++++++++++ 1 file changed, 567 insertions(+) diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index c8f0445d8c..850ad4af64 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -393,6 +393,573 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", + " (password)" => " (пароль)", + " (password, unlocked)" => " (пароль, разблокировано)", + "$ English (United States)" => "$ английский (США)", + "'{file}' is protected." => "Файл «{file}» защищён.", + "(No suggestions)" => "(Нет вариантов)", + "(unnamed)" => "(без имени)", + "+ Add Level" => "+ Добавить уровень", + "100% Stacked Bar" => "Нормированная линейчатая", + "100% Stacked Column" => "Нормированная гистограмма", + "A clean-room, open-source, Rust-native spreadsheet. Part of ArtCraft." => { + "Электронные таблицы с открытым исходным кодом, написанные с нуля на Rust. Часть ArtCraft." + } + "A to Z" => "От А до Я", + "About" => "О программе", + "About GridCraft" => "О программе GridCraft", + "Accessibility" => "Специальные возможности", + "Action" => "Действие", + "Action Journal" => "Журнал действий", + "Add" => "Добавить", + "Add Chart Element" => "Добавить элемент диаграммы", + "Add subtotal to (columns, e.g. C,D):" => "Добавить итоги по (столбцы, например C,D):", + "Add to Dictionary" => "Добавить в словарь", + "Add-in and Automation" => "Надстройки и автоматизация", + "Agent Control" => "Управление агентами", + "Aggregate duplicates using" => "Объединять повторы с помощью", + "Align Left" => "Выровнять по левому краю", + "Align Right" => "Выровнять по правому краю", + "Alignment" => "Выравнивание", + "All" => "Все", + "All Charts" => "Все диаграммы", + "All done. We made {count} replacements." => "Готово. Выполнено замен: {count}.", + "All except borders" => "Без рамки", + "Allow" => "Разрешить", + "Allow all users of this sheet to:" => "Разрешить всем пользователям этого листа:", + "Alpha:" => "Альфа:", + "Analysis Tools" => "Инструменты анализа", + "Anova: Single Factor" => "Однофакторный дисперсионный анализ", + "Any value" => "Любое значение", + "Area" => "С областями", + "At each change in (column letter):" => "При каждом изменении в (буква столбца):", + "Automation in this workbook. GridCraft runs its own scripts; a file's VBA project is preserved but not executed." => { + "Автоматизация в этой книге. GridCraft выполняет собственные сценарии; проект VBA из файла сохраняется, но не выполняется." + } + "Average" => "Среднее", + "Background Color:" => "Цвет фона:", + "Before sheet (position, 0 = first):" => "Перед листом (позиция, 0 = первый):", + "Bin Range (blank for automatic bins):" => "Интервал карманов (пусто — автоматически):", + "Blanks" => "Пустые ячейки", + "Bold" => "Полужирный", + "Border" => "Граница", + "Bottom" => "Нижняя", + "Bottom Align" => "Выровнять по нижнему краю", + "Bottom margin (in):" => "Нижнее поле (дюймы):", + "By Changing Variable Cells:" => "Изменяя ячейки переменных:", + "By changing cell:" => "Изменяя значение ячейки:", + "Calculate Now (F9)" => "Пересчёт (F9)", + "Calculate Sheet (⇧F9)" => "Произвести вычисления на листе (⇧F9)", + "Calculation Options" => "Параметры вычислений", + "Cancel" => "Отмена", + "Category:" => "Категория:", + "Cell Color" => "Цвет ячейки", + "Cell Styles" => "Стили ячеек", + "Cell Values" => "Значения ячеек", + "Center Across Selection" => "По центру выделения", + "Change" => "Заменить", + "Change All" => "Заменить все", + "Change Chart Type" => "Изменить тип диаграммы", + "Chart" => "Диаграмма", + "Chart Title" => "Название диаграммы", + "Chart data range:" => "Диапазон данных для диаграммы:", + "Check Accessibility" => "Проверка читаемости", + "Choose a PNG or JPEG no larger than 16 MB." => "Выберите файл PNG или JPEG размером не более 16 МБ.", + "Clear Filter" => "Очистить фильтр", + "Clustered Bar" => "Линейчатая с группировкой", + "Clustered Column" => "Гистограмма с группировкой", + "Color:" => "Цвет:", + "Column Width" => "Ширина столбца", + "Column chart" => "Гистограмма", + "Column or Bar" => "Гистограмма или линейчатая", + "Column width (characters):" => "Ширина столбца (символы):", + "Column widths" => "Ширины столбцов", + "Columns" => "Столбцы", + "Columns (blank = all, e.g. A,C):" => "Столбцы (пусто = все, например A,C):", + "Combo" => "Комбинированная", + "Comma" => "Запятая", + "Comment:" => "Примечание:", + "Comments and notes (C)" => "Примечания и заметки (C)", + "Comments pane" => "Область примечаний", + "Compatibility" => "Совместимость", + "Conditional Formatting Rules Manager" => "Диспетчер правил условного форматирования", + "Conditional formats" => "Условные форматы", + "Confidence Level (%):" => "Уровень надёжности (%):", + "Confidence Level for Mean (%), blank for none:" => "Уровень надёжности для среднего (%), пусто — нет:", + "Confidence interval" => "Доверительный интервал", + "Confidence level (%):" => "Уровень надёжности (%):", + "Constant is Zero" => "Константа — ноль", + "Contributors" => "Участники", + "Convert Text to Columns" => "Распределение текста по столбцам", + "Convert the last ink stroke to a shape" => "Преобразовать последний рукописный штрих в фигуру", + "Convert to Range" => "Преобразовать в диапазон", + "Copy" => "Копировать", + "Correlation" => "Корреляция", + "Count" => "Количество", + "CountA" => "Количество значений", + "Covariance" => "Ковариация", + "Create Forecast Worksheet" => "Создание листа прогноза", + "Create Sparklines" => "Создание спарклайнов", + "Create a copy" => "Создать копию", + "Cube" => "Куб", + "Cumulative Percentage" => "Интегральный процент", + "Current region" => "Текущая область", + "Custom (%):" => "Другой (%):", + "Custom Sort" => "Настраиваемая сортировка", + "Cut" => "Вырезать", + "Damping factor:" => "Фактор затухания:", + "Data Range:" => "Диапазон данных:", + "Data validation" => "Проверка данных", + "Database" => "Работа с базой данных", + "Date & Time" => "Дата и время", + "Date unit" => "Единица даты", + "Day" => "День", + "Decimal" => "Действительное", + "Define Name…" => "Присвоить имя…", + "Delete Comment" => "Удалить примечание", + "Delete Sheet" => "Удалить лист", + "Delete chart" => "Удалить диаграмму", + "Delete rows" => "Удаление строк", + "Delete…" => "Удалить…", + "Description (optional):" => "Описание (необязательно):", + "Descriptive Statistics" => "Описательная статистика", + "Destination:" => "Поместить в:", + "Diagonal ↗" => "Диагональ ↗", + "Diagonal ↘" => "Диагональ ↘", + "Dismiss" => "Закрыть", + "Display:" => "Отображать:", + "Distributed" => "Распределённый", + "Divide" => "Разделить", + "Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?", + "Don't Save" => "Не сохранять", + "Double" => "Двойное", + "Double Accounting" => "Двойное, по ячейке", + "Doughnut" => "Кольцевая", + "Down" => "Вниз", + "Edit Name" => "Изменение имени", + "Edit chart title" => "Изменить название диаграммы", + "Edit…" => "Изменить…", + "Engineering" => "Инженерные", + "Entire column" => "Столбец", + "Entire row" => "Строку", + "Erase ink strokes" => "Стереть рукописные штрихи", + "Error message:" => "Сообщение:", + "Error style" => "Вид", + "Errors" => "Ошибки", + "Every command run in this session (replayable)" => "Все команды, выполненные в этом сеансе (можно повторить)", + "Expand formula bar" => "Развернуть строку формул", + "Exponential Smoothing" => "Экспоненциальное сглаживание", + "F-Test Two-Sample for Variances" => "Двухвыборочный F-тест для дисперсии", + "Fill missing points using" => "Заполнить отсутствующие точки с помощью", + "Filter (⌘⇧F)" => "Фильтр (⌘⇧F)", + "Filter by Selected Cell's Value" => "Фильтр по значению выделенной ячейки", + "Find" => "Найти", + "Find & Select" => "Найти и выделить", + "Find All" => "Найти все", + "Find Next" => "Найти далее", + "Find and Replace" => "Найти и заменить", + "Find what:" => "Найти:", + "Fits inside the selected cell and moves with its content." => "Помещается в выделенную ячейку и перемещается вместе с её содержимым.", + "Flash Fill (⌘E)" => "Мгновенное заполнение (⌘E)", + "Font" => "Шрифт", + "Footer (in):" => "Нижний колонтитул (дюймы):", + "Footer:" => "Нижний колонтитул:", + "Forecast Sheet" => "Лист прогноза", + "Forecast end (date or number; blank: a third of the history):" => "Завершение прогноза (дата или число; пусто — треть истории):", + "Format Cells" => "Формат ячеек", + "Format Cells|Fill" => "Заливка", + "Format Chart pane" => "Область «Формат диаграммы»", + "Format as Table" => "Форматировать как таблицу", + "Format cells" => "Форматирование ячеек", + "Format cells that are (value):" => "Форматировать ячейки, которые (значение):", + "Format cells that contain a date occurring:" => "Форматировать ячейки, содержащие дату:", + "Format cells that contain the text:" => "Форматировать ячейки, содержащие текст:", + "Format columns" => "Форматирование столбцов", + "Format rows" => "Форматирование строк", + "Format values where this formula is true:" => "Форматировать значения, для которых следующая формула является истинной:", + "Formats (T)" => "Форматы (T)", + "Formula Builder" => "Построитель формул", + "Formula:" => "Формула:", + "Formulas (F)" => "Формулы (F)", + "Formulas and number formats" => "Формулы и форматы чисел", + "Funnel" => "Воронка", + "GRG Nonlinear" => "Поиск решения нелинейных задач методом ОПГ", + "GRG Nonlinear: a local optimum of a smooth model, from the current values." => { + "Поиск решения нелинейных задач методом ОПГ: локальный оптимум гладкой модели, начиная с текущих значений." + } + "Go To" => "Перейти", + "Go To Special" => "Выделить группу ячеек", + "Goal Seek" => "Подбор параметра", + "Goal Seeking found a solution: {value}" => "Подбор параметра нашёл решение: {value}", + "Gradebook" => "Журнал оценок", + "Green Fill with Dark Green Text" => "Зелёная заливка и тёмно-зелёный текст", + "GridCraft is fully drivable by agents. Every menu item, button and gesture is a command:" => { + "GridCraft полностью управляется агентами. Каждый пункт меню, кнопка и жест — это команда:" + } + "Grouped By:" => "Группирование:", + "Growth" => "Геометрическая", + "Header (&L left, &C center, &R right; &P page, &N pages, &D date, &A sheet):" => { + "Верхний колонтитул (&L слева, &C по центру, &R справа; &P страница, &N страниц, &D дата, &A лист):" + } + "Header (in):" => "Верхний колонтитул (дюймы):", + "Hidden" => "Скрыть формулы", + "Hidden: {sheets}" => "Скрытые: {sheets}", + "Hide" => "Скрыть", + "Hide Sheet" => "Скрыть лист", + "Hierarchy & more" => "Иерархия и другие", + "Highlighter" => "Маркер", + "Histogram" => "Гистограмма распределения", + "Horizontal (Category) Axis Labels:" => "Подписи горизонтальной оси (категории):", + "Horizontal axis title:" => "Название горизонтальной оси:", + "Household Budget" => "Семейный бюджет", + "How agents drive GridCraft (MCP / control channel)" => "Как агенты управляют GridCraft (MCP / канал управления)", + "Hypothesized Mean Difference:" => "Гипотетическая средняя разность:", + "Ignore Once" => "Пропустить", + "Ignore blank" => "Игнорировать пустые ячейки", + "Import a text or CSV file" => "Импорт текстового файла или CSV", + "In the last 7 days" => "За последние 7 дней", + "In-cell dropdown" => "Список допустимых значений", + "Include forecast statistics" => "Включить статистику прогноза", + "Indent" => "Отступ", + "Information" => "Сообщение", + "Input Range:" => "Входной интервал:", + "Input X Range:" => "Входной интервал X:", + "Input Y Range:" => "Входной интервал Y:", + "Input message:" => "Сообщение для ввода:", + "Insert Calculated Field" => "Вставка вычисляемого поля", + "Insert Chart" => "Вставка диаграммы", + "Insert Function" => "Вставка функции", + "Insert Function (⇧F3)" => "Вставить функцию (⇧F3)", + "Insert Hyperlink" => "Вставка гиперссылки", + "Insert Link (⌘K)" => "Вставить ссылку (⌘K)", + "Insert Sheet" => "Вставить лист", + "Insert Slicer" => "Вставка среза", + "Insert a picture" => "Вставить рисунок", + "Insert a slicer to filter a table" => "Вставить срез для фильтрации таблицы", + "Insert an icon" => "Вставить значок", + "Insert rows" => "Вставка строк", + "Insert…" => "Вставить…", + "Interpolation" => "Интерполяция", + "Interval:" => "Интервал:", + "Italic" => "Курсив", + "Join the ArtCraft Discord" => "Присоединиться к Discord ArtCraft", + "Justify" => "По ширине", + "Keep" => "Оставить", + "Keep Solver Solution" => "Сохранить найденное решение", + "Kth Largest (blank for none):" => "K-й наибольший (пусто — нет):", + "Kth Smallest (blank for none):" => "K-й наименьший (пусто — нет):", + "Labels in first row" => "Метки в первой строке", + "Last cell" => "Последнюю ячейку", + "Last month" => "В прошлом месяце", + "Last week" => "На прошлой неделе", + "Left margin (in):" => "Левое поле (дюймы):", + "Legend Entries (Series)" => "Элементы легенды (ряды)", + "Light Red Fill" => "Светло-красная заливка", + "Light Red Fill with Dark Red Text" => "Светло-красная заливка и тёмно-красный текст", + "Line" => "График", + "Line chart" => "График", + "Line or Area" => "График или диаграмма с областями", + "Line with Markers" => "График с маркерами", + "Linear" => "Арифметическая", + "Link to (web address, e-mail or Sheet!A1):" => "Связать с (веб-адрес, электронная почта или Лист!A1):", + "Link…" => "Ссылка…", + "List" => "Список", + "Location Range:" => "Диапазон расположения:", + "Locked" => "Защищаемая ячейка", + "Locking cells or hiding formulas has no effect until you protect the worksheet (Review › Protect Sheet)." => { + "Защита ячеек и скрытие формул действуют только после защиты листа (Рецензирование › Защитить лист)." + } + "Lookup & Reference" => "Ссылки и массивы", + "Macros" => "Макросы", + "Macros and scripts in this workbook (Alt+F8)" => "Макросы и сценарии этой книги (Alt+F8)", + "Magnification" => "Масштаб", + "Make Unconstrained Variables Non-Negative" => "Сделать переменные без ограничений неотрицательными", + "Markers" => "Маркеры", + "Match case" => "Учитывать регистр", + "Match entire cell contents" => "Ячейка целиком", + "Math & Trig" => "Математические", + "Max" => "Максимум", + "Maximum:" => "Максимум:", + "Median" => "Медиана", + "Middle Align" => "Выровнять по середине", + "Min" => "Минимум", + "Minimum / Source / Formula:" => "Минимум / источник / формула:", + "Models" => "Модели", + "Modify" => "Изменить", + "Month" => "Месяц", + "More commands" => "Другие команды", + "Move or Copy" => "Переместить или скопировать", + "Move or Copy Sheet…" => "Переместить или скопировать лист…", + "Moving Average" => "Скользящее среднее", + "Multiply" => "Умножить", + "My data has headers" => "Мои данные содержат заголовки", + "My list has headers" => "Мои данные содержат заголовки", + "Name" => "Имя", + "Name Manager" => "Диспетчер имён", + "Name:" => "Имя:", + "New Comment" => "Создать примечание", + "New Name" => "Создание имени", + "New Worksheet Ply:" => "Новый рабочий лист:", + "New sheet (⇧F11)" => "Новый лист (⇧F11)", + "New title (Modify):" => "Новое название (изменить):", + "New…" => "Создать…", + "Next month" => "В следующем месяце", + "Next sheet" => "Следующий лист", + "Next week" => "На следующей неделе", + "No names defined" => "Имена не определены", + "No picture selected" => "Рисунок не выбран", + "No ranges yet." => "Диапазонов пока нет.", + "None" => "Нет", + "Normal Probability" => "График нормального распределения", + "Not in Dictionary ({cell}):" => "Нет в словаре ({cell}):", + "Note:" => "Заметка:", + "Numbers" => "Числа", + "OK" => "ОК", + "Open…" => "Открыть…", + "Operation" => "Операция", + "Orientation (degrees)" => "Ориентация (градусы)", + "Other:" => "Другой:", + "Outline" => "Внешние", + "Output Range:" => "Выходной интервал:", + "Output options" => "Параметры вывода", + "Page Breaks" => "Разрывы страниц", + "Page Setup" => "Параметры страницы", + "Paper Size" => "Размер бумаги", + "Pareto (sorted histogram)" => "Парето (отсортированная гистограмма)", + "Password" => "Пароль", + "Password (optional):" => "Пароль (необязательно):", + "Password:" => "Пароль:", + "Paste (⌘V)" => "Вставить (⌘V)", + "Paste Special" => "Специальная вставка", + "Pick From Drop-down List…" => "Выбрать из раскрывающегося списка…", + "Pick From List" => "Выбрать из списка", + "Picture file path (PNG or JPEG):" => "Путь к файлу рисунка (PNG или JPEG):", + "Pie" => "Круговая", + "Pie or Doughnut" => "Круговая или кольцевая", + "Place Picture in Cell" => "Поместить рисунок в ячейку", + "Place Picture over Cells" => "Поместить рисунок поверх ячеек", + "Previous sheet" => "Предыдущий лист", + "Print Area" => "Область печати", + "Print Titles" => "Печатать заголовки", + "Product" => "Произведение", + "Protect Sheet" => "Защитить лист", + "Protect Structure and Windows" => "Защита структуры и окон", + "Protect Workbook structure" => "Защитить структуру книги", + "Protect workbook for: Structure (sheets can't be added, moved, renamed, hidden or deleted)." => { + "Защитить книгу: структуру (листы нельзя добавлять, перемещать, переименовывать, скрывать и удалять)." + } + "Protection" => "Защита", + "Quarterly Sales Dashboard" => "Сводка продаж по кварталам", + "Radar" => "Лепестковая", + "Range password:" => "Пароль диапазона:", + "Ranges that stay editable when the sheet is protected:" => "Диапазоны, которые можно изменять на защищённом листе:", + "Rank and Percentile" => "Ранг и персентиль", + "Recommended Charts" => "Рекомендуемые диаграммы", + "Red Border" => "Красная граница", + "Red Text" => "Красный текст", + "Redo (⌘Y)" => "Повторить (⌘Y)", + "Reference:" => "Ссылка:", + "Refers To" => "Диапазон", + "Refers to cells:" => "Ссылается на ячейки:", + "Refers to:" => "Диапазон:", + "Regression" => "Регрессия", + "Remove" => "Удалить", + "Remove Duplicates" => "Удалить дубликаты", + "Remove the password (Modify)" => "Снять пароль (изменить)", + "Rename Sheet" => "Переименовать лист", + "Replace" => "Заменить", + "Replace All" => "Заменить все", + "Replace with:" => "Заменить на:", + "Residuals" => "Остатки", + "Restore Original Values" => "Восстановить исходные значения", + "Return to the original worksheet to insert this picture, or cancel and choose another cell." => { + "Вернитесь на исходный лист, чтобы вставить рисунок, или отмените и выберите другую ячейку." + } + "Right margin (in):" => "Правое поле (дюймы):", + "Row Height" => "Высота строки", + "Row height (pixels):" => "Высота строки (пиксели):", + "Rows" => "Строки", + "Sample" => "Выборка", + "Save (⌘S)" => "Сохранить (⌘S)", + "Save Changes?" => "Сохранить изменения?", + "Save a Copy" => "Сохранить копию", + "Save a copy as .{format}" => "Сохранить копию как .{format}", + "Scatter" => "Точечная", + "Scatter or Bubble" => "Точечная или пузырьковая", + "Scatter with Lines" => "Точечная с прямыми отрезками", + "Scope" => "Область", + "Scope (Workbook or sheet name):" => "Область (книга или имя листа):", + "ScreenTip:" => "Подсказка:", + "Search Commands" => "Поиск команд", + "Search and run any command" => "Найти и выполнить любую команду", + "Search commands (⌘⇧Space)" => "Поиск команд (⌘⇧Пробел)", + "Search:" => "Поиск:", + "Seasonality (auto, 0 for none, or a season length):" => "Сезонность (авто, 0 — нет, или длина сезона):", + "Select" => "Выделить", + "Select Data" => "Выбрать данные", + "Select Data Source" => "Выбор источника данных", + "Select a Solving Method:" => "Выберите метод решения:", + "Select a chart first." => "Сначала выделите диаграмму.", + "Select and move ink and shapes" => "Выделять и перемещать рукописные штрихи и фигуры", + "Semicolon" => "Точка с запятой", + "Series" => "Ряд", + "Series in" => "Ряды в", + "Series{n}" => "Ряд{n}", + "Series…" => "Прогрессия…", + "Set Objective:" => "Оптимизировать целевую функцию:", + "Set cell:" => "Установить в ячейке:", + "Share: export or save a copy" => "Поделиться: экспорт или сохранение копии", + "Sheets: {sheets}" => "Листы: {sheets}", + "Shift cells down" => "Ячейки со сдвигом вниз", + "Shift cells left" => "Ячейки со сдвигом влево", + "Shift cells right" => "Ячейки со сдвигом вправо", + "Shift cells up" => "Ячейки со сдвигом вверх", + "Show Formulas (⌃`)" => "Показать формулы (⌃`)", + "Show password" => "Показать пароль", + "Shrink to fit" => "Автоподбор ширины", + "Simplex LP: for linear models; integer and binary constraints by branch and bound." => { + "Симплекс-метод: для линейных моделей; целочисленные и двоичные ограничения — методом ветвей и границ." + } + "Single" => "Одинарное", + "Single Accounting" => "Одинарное, по ячейке", + "Skip blanks" => "Пропускать пустые ячейки", + "Slicer" => "Срез", + "Solve" => "Найти решение", + "Solver Parameters" => "Параметры поиска решения", + "Solver Results" => "Результаты поиска решения", + "Sort & Filter" => "Сортировка и фильтр", + "Sort by" => "Сортировать по", + "Space" => "Пробел", + "Special…" => "Выделить…", + "Spelling (F7)" => "Орфография (F7)", + "Stacked Area" => "С областями с накоплением", + "Stacked Bar" => "Линейчатая с накоплением", + "Stacked Column" => "Гистограмма с накоплением", + "Stacked Line" => "График с накоплением", + "Standard Errors" => "Стандартные погрешности", + "Standard Width" => "Стандартная ширина", + "Standard column width (pixels):" => "Стандартная ширина столбца (пиксели):", + "Standardized Residuals" => "Стандартизированные остатки", + "Start a conversation:" => "Начать разговор:", + "Start a new workbook" => "Создать новую книгу", + "Statistic" => "Статистика", + "Statistical" => "Статистические", + "Step value:" => "Шаг:", + "Stop" => "Останов", + "Stop value:" => "Предельное значение:", + "Subject to the Constraints:" => "В соответствии с ограничениями:", + "Subscript" => "Подстрочный", + "Subtract" => "Вычесть", + "Suggestions:" => "Варианты:", + "Sum" => "Сумма", + "Summary statistics" => "Итоговая статистика", + "Superscript" => "Надстрочный", + "Switch Row/Column" => "Строка/столбец", + "Tab" => "Знак табуляции", + "Table (⌘T)" => "Таблица (⌘T)", + "Table Styles" => "Стили таблиц", + "Text Box" => "Надпись", + "Text length" => "Длина текста", + "Text to Columns" => "Текст по столбцам", + "The output range already holds data. Replace it with the report?" => "Выходной интервал уже содержит данные. Заменить их отчётом?", + "The spelling check is complete for the entire sheet." => "Проверка орфографии на всём листе завершена.", + "Then by" => "Затем по", + "There are no conditional formatting rules on this sheet." => "На этом листе нет правил условного форматирования.", + "This month" => "В текущем месяце", + "This week" => "На текущей неделе", + "This workbook" => "Эта книга", + "This workbook has no scripts or macros." => "В этой книге нет сценариев и макросов.", + "Timeline range (blank: first column of the selection):" => "Диапазон временной шкалы (пусто — первый столбец выделения):", + "Title:" => "Заголовок:", + "To value:" => "Значение:", + "To:" => "До:", + "Today" => "Сегодня", + "Tomorrow" => "Завтра", + "Top" => "Верхняя", + "Top Align" => "Выровнять по верхнему краю", + "Top margin (in):" => "Верхнее поле (дюймы):", + "Transpose (E)" => "Транспонировать (E)", + "Treat consecutive delimiters as one" => "Считать последовательные разделители одним", + "Type" => "Тип", + "Type (custom format code):" => "Тип (код пользовательского формата):", + "Type a command, e.g. freeze, chart, bold…" => "Введите команду, например закрепить, диаграмма, полужирный…", + "Undo (⌘Z)" => "Отменить (⌘Z)", + "Undo list" => "Список отмены", + "Unhide" => "Показать", + "Unhide Sheet…" => "Показать лист…", + "Unhide sheet:" => "Показать лист:", + "Unlock with password" => "Разблокировать паролем", + "Unprotect Sheet" => "Снять защиту листа", + "Unprotect Workbook" => "Снять защиту книги", + "Up" => "Вверх", + "Use AutoFilter" => "Использование автофильтра", + "Use function" => "Операция", + "Validation" => "Проверка данных", + "Value" => "Значение", + "Value Of:" => "Значения:", + "Values (V)" => "Значения (V)", + "Values and number formats" => "Значения и форматы чисел", + "Values range (blank: second column of the selection):" => "Диапазон значений (пусто — второй столбец выделения):", + "Variable 1 Range:" => "Интервал переменной 1:", + "Variable 2 Range:" => "Интервал переменной 2:", + "Version {version}" => "Версия {version}", + "Version, contributors and the AI models that helped" => "Версия, участники и модели ИИ, которые помогали", + "Vertical" => "По вертикали", + "Vertical axis title:" => "Название вертикальной оси:", + "Visible cells only" => "Только видимые ячейки", + "Warning" => "Предупреждение", + "Waterfall" => "Каскадная", + "Web" => "Интернет", + "Weekday" => "Рабочий день", + "What-If Analysis" => "Анализ «что если»", + "Whole number" => "Целое число", + "Within workbook" => "В книге", + "Workbook" => "Книга", + "Workbook Statistics" => "Статистика книги", + "Wrap text" => "Переносить текст", + "Year" => "Год", + "Yellow Fill with Dark Yellow Text" => "Жёлтая заливка и тёмно-жёлтый текст", + "Yesterday" => "Вчера", + "Z to A" => "От Я до А", + "Zeros" => "Нули", + "Zoom In" => "Увеличить", + "Zoom Out" => "Уменьшить", + "Zoom to 100%" => "Масштаб 100%", + "Zoom to Selection" => "Масштаб по выделенному", + "Zoom…" => "Масштаб…", + "and:" => "и:", + "applies to" => "применяется к", + "between" => "между", + "dashed" => "штриховая", + "dotted" => "точечная", + "double" => "двойная", + "e.g. lookup, average, date" => "например: поиск, среднее, дата", + "equal to" => "равно", + "greater than" => "больше", + "greater than or equal to" => "больше или равно", + "less than" => "меньше", + "less than or equal to" => "меньше или равно", + "medium" => "средняя", + "none" => "нет", + "not between" => "вне", + "not equal to" => "не равно", + "t-Test: Paired Two Sample for Means" => "Парный двухвыборочный t-тест для средних", + "t-Test: Two-Sample Assuming Equal Variances" => "Двухвыборочный t-тест с одинаковыми дисперсиями", + "t-Test: Two-Sample Assuming Unequal Variances" => "Двухвыборочный t-тест с различными дисперсиями", + "thick" => "толстая", + "thin" => "тонкая", + "this workbook" => "эта книга", + "with" => "с", + "{count} cell(s) found" => "Найдено ячеек: {count}", + "{count} engine commands are available. See docs/mcp.md and docs/control-protocol.md." => { + "Доступно команд движка: {count}. См. docs/mcp.md и docs/control-protocol.md." + } + "£ English (United Kingdom)" => "£ английский (Великобритания)", + "¥ Japanese" => "¥ японский", + "— 1 step" => "— 1 шаг", + "— VBA project (preserved, not run)" => "— проект VBA (сохраняется, не выполняется)", + "— {steps} steps" => "— шагов: {steps}", + "€ Euro" => "€ евро", _ => return None, }) } From a1d97d49b363d94dcbabb03c9470ea4afbb3f2f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Mon, 12 Oct 2026 14:39:53 +0300 Subject: [PATCH 002/201] =?UTF-8?q?i18n(ru):=20name=20the=20Insert=20tab?= =?UTF-8?q?=20=C2=AB=D0=92=D1=81=D1=82=D0=B0=D0=B2=D0=BA=D0=B0=C2=BB,=20tr?= =?UTF-8?q?anslate=20AutoSave?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Russian names the Insert tab and the Insert command differently («Вставка» vs «Вставить»). Ribbon tabs now look up a `Tab|` key first and fall back to the plain label, so other languages are unchanged. Also translates the AutoSave toggle and adds the two French header/footer labels whose absence failed the catalog completeness test. --- crates/ui-egui/src/i18n.rs | 24 +++++++++++++++++++++--- crates/ui-egui/src/i18n/fr.rs | 2 ++ crates/ui-egui/src/i18n/ru.rs | 5 +++++ crates/ui-egui/src/ribbon.rs | 6 +++--- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 406cc3dd51..e68fcaab0f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -112,7 +112,19 @@ impl Language { /// A label that needs two translations (Home's text "Orientation" vs Page Layout's print /// "Orientation") is keyed `context|label`: English shows only the part after the `|`. pub fn tr(self, text: &str) -> &str { - let translated = match self { + self.lookup(text).unwrap_or_else(|| text.rsplit_once('|').map_or(text, |(_, label)| label)) + } + + /// A ribbon tab's name. Where a language names the tab differently from a command with the + /// same English label (Russian: the Insert tab is «Вставка», the Insert button «Вставить»), its + /// catalog keys the tab `Tab|name`; every other language falls back to the plain label. + pub fn tr_tab(self, tab: &str) -> &str { + self.lookup(&format!("Tab|{tab}")).unwrap_or_else(|| self.tr(tab)) + } + + /// The catalog entry for `text`, if this language has one. + fn lookup(self, text: &str) -> Option<&'static str> { + match self { Self::En => None, Self::Es => es::translate(text), Self::Ja => JAPANESE.iter().find(|(english, _)| *english == text).map(|(_, translated)| *translated), @@ -123,8 +135,7 @@ impl Language { Self::De => de::translate(text), Self::Cs => cs::translate(text), Self::Fr => fr::translate(text), - }; - translated.unwrap_or_else(|| text.rsplit_once('|').map_or(text, |(_, label)| label)) + } } } @@ -592,6 +603,13 @@ mod tests { assert_eq!(Language::Zh.tr("Data"), "数据"); assert_eq!(Language::Ko.tr("Data"), "데이터"); assert_eq!(Language::Ru.tr("Data"), "Данные"); + // The Insert tab and the Insert command have different Russian names; elsewhere the tab + // name is the plain label. + assert_eq!(Language::Ru.tr_tab("Insert"), "Вставка"); + assert_eq!(Language::Ru.tr("Insert"), "Вставить"); + assert_eq!(Language::Ru.tr_tab("Data"), "Данные"); + assert_eq!(Language::Es.tr_tab("Insert"), Language::Es.tr("Insert")); + assert_eq!(Language::En.tr_tab("Insert"), "Insert"); assert_eq!(Language::PtBr.tr("Data"), "Dados"); assert_eq!(Language::Es.tr("Data"), "Datos"); assert_eq!(Language::Es.tr("Freeze Panes"), "Inmovilizar paneles"); diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fdf1f891dd..8cd4e9b48d 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -381,6 +381,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Classeur Excel (*.xlsx)", "Calculation settings are saved with the workbook." => "Modifier le type de fichier", + "Different First Page" => "Première page différente", + "Different Odd & Even Pages" => "Pages paires et impaires différentes", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 850ad4af64..7afd626123 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -960,6 +960,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "— VBA project (preserved, not run)" => "— проект VBA (сохраняется, не выполняется)", "— {steps} steps" => "— шагов: {steps}", "€ Euro" => "€ евро", + "Tab|Insert" => "Вставка", + "AutoSave" => "Автосохранение", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Автосохранение: сохранять после каждого изменения (для книг, сохранённых в файл)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index e8291accdc..5bff246baa 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -52,14 +52,14 @@ pub fn title_bar(app: &mut SheetApp, ui: &mut Ui) { ui.horizontal_centered(|ui| { ui.add_space(TITLE_LEFT_PAD); // AutoSave toggle (saves after each change when the workbook has a file). - ui.label(egui::RichText::new("AutoSave").font(theme::ui_font(12.5)).color(t.text_dim)); + ui.label(egui::RichText::new(app.ui.language.tr("AutoSave")).font(theme::ui_font(12.5)).color(t.text_dim)); let on = app.grid.autosave(); let (r, resp) = ui.allocate_exact_size(vec2(30.0, 16.0), Sense::click()); ui.painter().rect_filled(r, 8.0, if on { t.accent } else { Color32::TRANSPARENT }); ui.painter().rect_stroke(r, 8.0, Stroke::new(1.0, if on { t.accent } else { t.text_dim }), StrokeKind::Inside); let knob = if on { pos2(r.right() - 8.0, r.center().y) } else { pos2(r.left() + 8.0, r.center().y) }; ui.painter().circle_filled(knob, 5.0, if on { Color32::WHITE } else { t.text_dim }); - if resp.on_hover_text("AutoSave: save after every change (workbooks saved to a file)").clicked() { + if resp.on_hover_text(app.ui.language.tr("AutoSave: save after every change (workbooks saved to a file)")).clicked() { app.grid.toggle_autosave(); } ui.add_space(6.0); @@ -181,7 +181,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) { let active = app.ui.ribbon_tab == tab; let contextual = ctx_tabs.contains(&tab); let font = theme::ui_font(13.5); - let label = app.ui.language.tr(tab); + let label = app.ui.language.tr_tab(tab); let tw = ui.painter().layout_no_wrap(label.to_string(), font.clone(), t.text).size().x; let (r, resp) = ui.allocate_exact_size(vec2(tw + 22.0, 30.0), Sense::click()); if resp.hovered() && !active { From 4972675b1b0e2d309dcf94442e8372a6e4741089 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:03:01 +0200 Subject: [PATCH 003/201] UI: Quick Analysis (Ctrl+Q) (#791) A corner button on multi-cell selections and Ctrl+Q open a popup of one-click analyses (formatting, charts, totals, tables, sparklines). Totals and sparklines are new engine commands, analysis.addTotal and analysis.addSparklines, each one undo step, never overwriting data unless asked. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/quick_analysis.rs | 269 +++++++++++++++++ crates/engine/src/tests.rs | 71 +++++ crates/ui-egui/examples/snapshot.rs | 20 +- crates/ui-egui/src/grid.rs | 3 + crates/ui-egui/src/i18n.rs | 24 ++ crates/ui-egui/src/i18n/cs.rs | 24 ++ crates/ui-egui/src/i18n/de.rs | 24 ++ crates/ui-egui/src/i18n/es.rs | 24 ++ crates/ui-egui/src/i18n/fr.rs | 24 ++ crates/ui-egui/src/i18n/ko.rs | 24 ++ crates/ui-egui/src/i18n/pt.rs | 24 ++ crates/ui-egui/src/i18n/ru.rs | 24 ++ crates/ui-egui/src/i18n/zh.rs | 24 ++ crates/ui-egui/src/icons.rs | 9 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/quick_analysis.rs | 364 ++++++++++++++++++++++++ crates/ui-egui/src/ribbon.rs | 5 + docs/ui-parity.md | 10 +- 20 files changed, 967 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/quick_analysis.rs create mode 100644 crates/ui-egui/src/quick_analysis.rs diff --git a/ROADMAP.md b/ROADMAP.md index e8e1c06b38..25b8d9b803 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) | | 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available | | 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found | | 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) | diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 50865a2b7d..d016fbb494 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -14,6 +14,7 @@ pub mod insert; pub mod inspect; pub mod pivot; pub mod print; +pub mod quick_analysis; pub mod review; pub mod sheet; pub mod slicer; @@ -144,6 +145,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(forecast::specs()); v.extend(analysis::specs()); v.extend(print::specs()); + v.extend(quick_analysis::specs()); v }) } diff --git a/crates/engine/src/cmd/quick_analysis.rs b/crates/engine/src/cmd/quick_analysis.rs new file mode 100644 index 0000000000..94f4197020 --- /dev/null +++ b/crates/engine/src/cmd/quick_analysis.rs @@ -0,0 +1,269 @@ +//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a +//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI +//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP +//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or +//! the column to its right), per-cell results in a block of the same shape next to it. + +use std::collections::BTreeSet; + +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; +use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind}; +use serde_json::{Value as Json, json}; + +use super::*; + +const CMD: &str = "analysis.addTotal"; +const SPARK: &str = "analysis.addSparklines"; +/// Most sparklines one call may add. +const MAX_SPARKLINES: u64 = 10_000; +/// Most cells one call may write (a per-cell block on a huge selection is refused). +const MAX_OUTPUT_CELLS: u64 = 200_000; +/// Largest block (after clipping to the used range) the command scans for numbers. +const MAX_SCAN_CELLS: u64 = 5_000_000; + +pub fn specs() -> Vec { + vec![ + cmd!( + "analysis.addTotal", + "Add Totals", + [], + None, + "{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.", + has_doc, + add_total + ), + cmd!( + "analysis.addSparklines", + "Add Sparklines", + [], + None, + "{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.", + has_doc, + add_sparklines + ), + ] +} + +#[derive(Clone, Copy, PartialEq)] +enum Func { + Aggregate(&'static str), + Percent, + Running, +} + +fn parse_func(name: &str) -> Result { + Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() { + "sum" => Func::Aggregate("SUM"), + "average" | "avg" => Func::Aggregate("AVERAGE"), + "count" => Func::Aggregate("COUNT"), + "min" => Func::Aggregate("MIN"), + "max" => Func::Aggregate("MAX"), + "percenttotal" | "percent" => Func::Percent, + "runningtotal" | "running" => Func::Running, + _ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))), + }) +} + +/// The block a Quick Analysis result is computed from. +struct Block { + sheet: usize, + /// The selection clipped to the used range. + range: RangeRef, + /// `range` without its header row (columns) or label column (rows). + data: RangeRef, + /// The columns (or, `by_rows`, the rows) of `data` that hold numbers. + lines: BTreeSet, + by_rows: bool, +} + +impl Block { + fn cell_at(&self, line: u32, i: u32) -> CellRef { + if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) } + } + /// First and last position along a line of `data`. + fn span_of_line(&self) -> (u32, u32) { + if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) } + } + fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef { + RangeRef::new(self.cell_at(line, from), self.cell_at(line, to)) + } +} + +fn block(s: &Session, p: &Json, by_rows: bool) -> Result { + let sheet = target_sheet(s, p)?; + let sel = match str_param(p, "range") { + Some(_) => target_range(s, p)?, + None => s.doc()?.selection.current(), + }; + if sel.is_single() { + return Err(bad(CMD, "select at least two cells")); + } + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + // Whole rows / columns are limited to what holds data. + let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?; + let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?; + if r.count() > MAX_SCAN_CELLS { + return Err(bad(CMD, "selection too large to analyse")); + } + let is_num = |c: CellRef| sh.value(c).is_number(); + let is_text = |c: CellRef| sh.value(c).is_text(); + // Header row (columns) / label column (rows): text only, with at least one entry. + let lead: Vec = if by_rows { + (r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect() + } else { + (r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect() + }; + let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 }; + let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c)); + let data = if by_rows { + RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end) + } else { + RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end) + }; + let mut lines: BTreeSet = BTreeSet::new(); + for (c, _) in sh.cells.iter_range(data) { + if is_num(c) { + lines.insert(if by_rows { c.row } else { c.col }); + } + } + if lines.is_empty() { + return Err(EngineError::Other("The selection holds no numbers.".into())); + } + Ok(Block { sheet, range: r, data, lines, by_rows }) +} + +fn add_total(s: &mut Session, p: &Json) -> Result { + let func = parse_func(str_param(p, "function").unwrap_or("sum"))?; + let by_rows = match str_param(p, "direction") { + None | Some("columns") => false, + Some("rows") => true, + Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))), + }; + let overwrite = bool_param(p, "overwrite").unwrap_or(false); + let b = block(s, p, by_rows)?; + let (r, sheet) = (b.range, b.sheet); + let (lo, hi) = b.span_of_line(); + let out_cells = match func { + Func::Aggregate(_) => b.lines.len() as u64, + _ => b.lines.len() as u64 * (u64::from(hi - lo) + 1), + }; + if out_cells > MAX_OUTPUT_CELLS { + return Err(bad(CMD, "selection too large for this result")); + } + // `$` pins a part of a reference like a hand-written formula would. + let abs = |c: CellRef, row: bool, col: bool| { + let a = c.a1(); + let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect(); + let digits = &a[letters.len()..]; + format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" }) + }; + // (target, formula) pairs. + let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize); + let (height, width) = (r.height(), r.width()); + for &line in &b.lines { + match func { + Func::Aggregate(name) => { + let target = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1()))); + } + Func::Percent | Func::Running => { + for i in lo..=hi { + let src = b.cell_at(line, i); + let target = if by_rows { + CellRef::new(src.row.saturating_add(height), src.col) + } else { + CellRef::new(src.row, src.col.saturating_add(width)) + }; + let formula = if func == Func::Percent { + // The summed block is locked on the axis the formula is filled along. + let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi)); + format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows)) + } else { + format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1()) + }; + writes.push((target, formula)); + } + } + } + } + // Everything has to fit on the sheet and may not overwrite data. + if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) { + return Err(EngineError::Other("There's no room next to the selection for the result.".into())); + } + let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) { + return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into())); + } + let out = writes.iter().fold(None::, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t))))); + let percent = func == Func::Percent; + let count = writes.len(); + edit(s, |cx| { + for (t, f) in &writes { + let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default(); + cx.sheet_mut(sheet)?.set_cell(*t, cell); + if percent { + let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default(); + let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%")); + cx.sheet_mut(sheet)?.set_style(*t, new); + } + cx.touch(sheet, *t); + } + Ok(()) + })?; + let name = match func { + Func::Aggregate(n) => n.to_ascii_lowercase(), + Func::Percent => "percentTotal".into(), + Func::Running => "runningTotal".into(), + }; + Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count})) +} + +fn add_sparklines(s: &mut Session, p: &Json) -> Result { + let by_rows = match str_param(p, "direction") { + None | Some("rows") => true, + Some("columns") => false, + Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))), + }; + let kind = match str_param(p, "type") { + None | Some("line") => SparklineKind::Line, + Some("column") => SparklineKind::Column, + Some("winLoss") => SparklineKind::WinLoss, + Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))), + }; + let markers = bool_param(p, "markers").unwrap_or(false); + let overwrite = bool_param(p, "overwrite").unwrap_or(false); + let b = block(s, p, by_rows)?; + if b.lines.len() as u64 > MAX_SPARKLINES { + return Err(bad(SPARK, "selection too large for this result")); + } + let (lo, hi) = b.span_of_line(); + let r = b.range; + let sparks: Vec<(CellRef, String)> = b + .lines + .iter() + .map(|&line| { + let at = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + (at, b.line_range(line, lo, hi).a1()) + }) + .collect(); + if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) { + return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into())); + } + let sheet = b.sheet; + let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) { + return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into())); + } + let out = sparks.iter().fold(None::, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t))))); + let count = sparks.len(); + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + for (cell, source) in sparks { + sh.sparklines.retain(|x| x.cell != cell); + sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers }); + } + Ok(()) + })?; + Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count})) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 33fdc113e0..c348dbaff2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2795,3 +2795,74 @@ fn a_decrypted_workbook_never_overwrites_its_encrypted_original() { assert_eq!(std::fs::read(&path).unwrap(), bytes, "the encrypted original is untouched"); std::fs::remove_dir_all(dir).unwrap(); } + +fn quick_analysis_block(s: &mut Session) { + for (a, t) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] { + s.execute("cell.set", json!({"cell": a, "input": t})).unwrap(); + } + for (r, (q1, q2)) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)].into_iter().enumerate() { + s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap(); + s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap(); + } +} + +#[test] +fn analysis_add_total_writes_formulas_in_one_undo_step() { + // Issue #791 (Quick Analysis › Totals). + let mut s = s(); + quick_analysis_block(&mut s); + let before = s.doc().unwrap().undo.len(); + // The header row and the text-only column are skipped; the selection is the default range. + s.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + let r = s.execute("analysis.addTotal", json!({"function": "sum"})).unwrap(); + assert_eq!(r["output"], "B5:C5"); + assert_eq!(v(&s, "B5"), Value::Number(6.0)); + assert_eq!(v(&s, "C5"), Value::Number(60.0)); + assert_eq!(v(&s, "A5"), Value::Empty, "text columns get no total"); + s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "average", "direction": "rows"})).unwrap(); + assert_eq!(v(&s, "D2"), Value::Number(5.5)); + s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "runningTotal", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "D4"), Value::Number(6.0), "running total down column B"); + assert_eq!(v(&s, "E4"), Value::Number(60.0)); + s.execute("analysis.addTotal", json!({"range": "B1:B4", "function": "percentTotal", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "C4"), Value::Number(0.5), "overwrite replaces the C column cell next to B"); + assert_eq!(s.doc().unwrap().undo.len(), before + 4, "one undo step per call"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(v(&s, "C4"), Value::Number(30.0)); + // A second sum into the occupied row is refused rather than overwriting. + assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4"})).is_err()); +} + +#[test] +fn analysis_add_total_refuses_bad_and_huge_input() { + let mut s = s(); + quick_analysis_block(&mut s); + // Empty params on a single cell, unknown function, no numbers, whole columns, no room. + assert!(s.execute("analysis.addTotal", json!({})).is_err()); + assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4", "function": "median"})).is_err()); + assert!(s.execute("analysis.addTotal", json!({"range": "A1:A4"})).is_err()); + let before = s.doc().unwrap().undo.len(); + let r = s.execute("analysis.addTotal", json!({"range": "B:C"})).unwrap(); + assert_eq!(r["output"], "B5:C5", "whole columns are clipped to the used range"); + assert_eq!(s.doc().unwrap().undo.len(), before + 1); + s.execute("cell.set", json!({"cell": "B1048575", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "B1048576", "input": "2"})).unwrap(); + assert!(s.execute("analysis.addTotal", json!({"range": "B1048575:C1048576"})).is_err(), "no row below the last one"); + assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap"); +} + +#[test] +fn analysis_add_sparklines_one_per_row_in_one_undo_step() { + let mut s = s(); + quick_analysis_block(&mut s); + let before = s.doc().unwrap().undo.len(); + let r = s.execute("analysis.addSparklines", json!({"range": "A1:C4", "type": "column"})).unwrap(); + assert_eq!(r["output"], "D2:D4", "header row and label column are skipped"); + let sparks = s.doc().unwrap().wb.active().unwrap().sparklines.clone(); + assert_eq!(sparks.len(), 3); + assert!(sparks.iter().any(|x| x.cell == CellRef::parse("D3").unwrap() && x.source == "B3:C3")); + assert_eq!(s.doc().unwrap().undo.len(), before + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty()); + assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err()); +} diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index a171199a1c..8b8a3bc465 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -2,7 +2,7 @@ //! //! `cargo run --release -p gridcraft-ui-egui --example snapshot -- [--sample sales] [--in file.xlsx] //! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language en|zh|ja|ko|ru|pt|cs] -//! [--dialog 'name={json}'] [--hf-edit header|footer] out.png` +//! [--dialog 'name={json}'] [--quick-analysis formatting|charts|totals|tables|sparklines] [--hf-edit header|footer] out.png` use gridcraft_engine::Session; use gridcraft_ui_egui::SheetApp; @@ -22,6 +22,7 @@ fn main() { let mut dialog: Option = None; let mut language: Option = None; let mut hf_edit: Option = None; + let mut quick: Option = None; let mut out = "snapshot.png".to_string(); let mut i = 0; while i < args.len() { @@ -67,6 +68,10 @@ fn main() { i += 1; dialog = args.get(i).cloned(); } + "--quick-analysis" => { + i += 1; + quick = args.get(i).cloned(); + } "--hf-edit" => { i += 1; hf_edit = args.get(i).cloned(); @@ -118,6 +123,19 @@ fn main() { d.split_once('=').map(|(a, b)| (a, serde_json::from_str(b).unwrap_or(json!({})))).unwrap_or((d.as_str(), json!({}))); app.open_dialog(name, p); } + if let Some(name) = &quick { + use gridcraft_ui_egui::quick_analysis::Tab; + app.grid.quick_analysis.tab = match name.as_str() { + "charts" => Tab::Charts, + "totals" => Tab::Totals, + "tables" => Tab::Tables, + "sparklines" => Tab::Sparklines, + _ => Tab::Formatting, + }; + if let Err(e) = gridcraft_ui_egui::quick_analysis::toggle(&mut app, Some(true)) { + eprintln!("quick analysis: {e}"); + } + } // Page Layout view: edit the first page's centre header (or footer) section. let active = app.session.active().and_then(|d| d.wb.active().cloned().map(|s| (d.wb.active_sheet, s))); if let (Some(part), Some((si, sh))) = (&hf_edit, active) { diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index d0eef85668..1f9efbad6a 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -96,6 +96,8 @@ pub struct GridState { /// Page ranges for Page Break Preview, cached per (doc uid, revision, sheet). pub pages: Option<((u64, u64, usize), Vec<(RangeRef, u32)>)>, pub header_menu: Option<(Pos2, bool)>, + /// Quick Analysis button and popup (Ctrl+Q). + pub quick_analysis: crate::quick_analysis::State, /// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns). pub paper: Option, /// Header or footer being edited in place (Page Layout view). @@ -624,6 +626,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) { list_picker(app, ui, &geo, previous_popups.1 == app.grid.list_picker); header_menu(app, ui, previous_popups.2 == app.grid.header_menu); context_menu(app, ui); + crate::quick_analysis::show(app, ui, &geo, sh); let track_x = if rtl { (available.left(), rect.left()) } else { (rect.right(), available.right()) }; vertical_scrollbar(app, ui, sh, &geo, track_x, max_y, &t); if app.session.clipboard.is_some() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 406cc3dd51..25b4feb01b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -565,6 +565,30 @@ const JAPANESE: &[(&str, &str)] = &[ ("Workbook calculation", "ブックの計算"), ("Enable iterative calculation", "反復計算を行う"), ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), + ("Quick Analysis (Ctrl+Q)", "クイック分析 (Ctrl+Q)"), + ("Formatting", "書式設定"), + ("Charts", "グラフ"), + ("Totals", "集計"), + ("Tables", "テーブル"), + ("Color Scale", "カラー スケール"), + ("Icon Set", "アイコン セット"), + ("Greater Than…", "指定の値より大きい…"), + ("Clear Rules", "ルールのクリア"), + ("Clustered Column", "集合縦棒"), + ("Line", "折れ線"), + ("Pie", "円"), + ("Bar", "横棒"), + ("Scatter", "散布図"), + ("Recommended Charts", "おすすめグラフ"), + ("Sum", "合計"), + ("Average", "平均"), + ("Count", "個数"), + ("% Total", "合計に対する割合"), + ("Running Total", "累計"), + ("By Column", "列ごと"), + ("By Row", "行ごと"), + ("Column", "縦棒"), + ("Win/Loss", "勝敗"), ]; #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index ca2e559428..fadf40d50a 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -391,6 +391,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "More\nFunctions" => "Další\nfunkce", "Sheet Options|View" => "Zobrazit", "Print" => "Tisknout", + "Quick Analysis (Ctrl+Q)" => "Rychlá analýza (Ctrl+Q)", + "Formatting" => "Formátování", + "Charts" => "Grafy", + "Totals" => "Součty", + "Tables" => "Tabulky", + "Color Scale" => "Barevná škála", + "Icon Set" => "Sada ikon", + "Greater Than…" => "Větší než…", + "Clear Rules" => "Vymazat pravidla", + "Clustered Column" => "Skupinový sloupcový", + "Line" => "Spojnicový", + "Pie" => "Výsečový", + "Bar" => "Pruhový", + "Scatter" => "Bodový", + "Recommended Charts" => "Doporučené grafy", + "Sum" => "Součet", + "Average" => "Průměr", + "Count" => "Počet", + "% Total" => "% z celku", + "Running Total" => "Průběžný součet", + "By Column" => "Podle sloupců", + "By Row" => "Podle řádků", + "Column" => "Sloupec", + "Win/Loss" => "Zisk/ztráta", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2ad37f675f..2fc143105b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -394,6 +394,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Dunkel", "Sheet Options|View" => "Anzeige", "Print" => "Drucken", + "Quick Analysis (Ctrl+Q)" => "Schnellanalyse (Strg+Q)", + "Formatting" => "Formatierung", + "Charts" => "Diagramme", + "Totals" => "Ergebnisse", + "Tables" => "Tabellen", + "Color Scale" => "Farbskala", + "Icon Set" => "Symbolsatz", + "Greater Than…" => "Größer als…", + "Clear Rules" => "Regeln löschen", + "Clustered Column" => "Gruppierte Säulen", + "Line" => "Linie", + "Pie" => "Kreis", + "Bar" => "Balken", + "Scatter" => "Punkt (XY)", + "Recommended Charts" => "Empfohlene Diagramme", + "Sum" => "Summe", + "Average" => "Mittelwert", + "Count" => "Anzahl", + "% Total" => "% des Gesamtergebnisses", + "Running Total" => "Laufende Summe", + "By Column" => "Nach Spalte", + "By Row" => "Nach Zeile", + "Column" => "Säule", + "Win/Loss" => "Gewinn/Verlust", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index da41bd7113..faad158341 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Oscuro", "Sheet Options|View" => "Ver", "Print" => "Imprimir", + "Quick Analysis (Ctrl+Q)" => "Análisis rápido (Ctrl+Q)", + "Formatting" => "Formato", + "Charts" => "Gráficos", + "Totals" => "Totales", + "Tables" => "Tablas", + "Color Scale" => "Escala de color", + "Icon Set" => "Conjunto de iconos", + "Greater Than…" => "Mayor que…", + "Clear Rules" => "Borrar reglas", + "Clustered Column" => "Columna agrupada", + "Line" => "Línea", + "Pie" => "Circular", + "Bar" => "Barras", + "Scatter" => "Dispersión", + "Recommended Charts" => "Gráficos recomendados", + "Sum" => "Suma", + "Average" => "Promedio", + "Count" => "Recuento", + "% Total" => "% del total", + "Running Total" => "Total acumulado", + "By Column" => "Por columna", + "By Row" => "Por fila", + "Column" => "Columna", + "Win/Loss" => "Ganancia/pérdida", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 7bf9fd100d..04dd35b973 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -383,6 +383,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Classeur Excel (*.xlsx)", "Calculation settings are saved with the workbook." => "Modifier le type de fichier", + "Quick Analysis (Ctrl+Q)" => "Analyse rapide (Ctrl+Q)", + "Formatting" => "Mise en forme", + "Charts" => "Graphiques", + "Totals" => "Totaux", + "Tables" => "Tableaux", + "Color Scale" => "Échelle de couleurs", + "Icon Set" => "Jeu d'icônes", + "Greater Than…" => "Supérieur à…", + "Clear Rules" => "Effacer les règles", + "Clustered Column" => "Histogramme groupé", + "Line" => "Courbe", + "Pie" => "Secteurs", + "Bar" => "Barres", + "Scatter" => "Nuage de points", + "Recommended Charts" => "Graphiques recommandés", + "Sum" => "Somme", + "Average" => "Moyenne", + "Count" => "Nombre", + "% Total" => "% du total", + "Running Total" => "Total cumulé", + "By Column" => "Par colonne", + "By Row" => "Par ligne", + "Column" => "Colonne", + "Win/Loss" => "Gain/perte", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index b684c78868..480e1fa417 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "통합 문서 계산", "Enable iterative calculation" => "반복 계산 사용", "Calculation settings are saved with the workbook." => "계산 설정은 통합 문서와 함께 저장됩니다.", + "Quick Analysis (Ctrl+Q)" => "빠른 분석 (Ctrl+Q)", + "Formatting" => "서식", + "Charts" => "차트", + "Totals" => "합계", + "Tables" => "표", + "Color Scale" => "색 구성표", + "Icon Set" => "아이콘 집합", + "Greater Than…" => "보다 큼…", + "Clear Rules" => "규칙 지우기", + "Clustered Column" => "묶은 세로 막대형", + "Line" => "꺾은선형", + "Pie" => "원형", + "Bar" => "가로 막대형", + "Scatter" => "분산형", + "Recommended Charts" => "추천 차트", + "Sum" => "합계", + "Average" => "평균", + "Count" => "개수", + "% Total" => "총합계 비율", + "Running Total" => "누계", + "By Column" => "열 기준", + "By Row" => "행 기준", + "Column" => "열", + "Win/Loss" => "이익/손실", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index b554ef9776..8395b82238 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -394,6 +394,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Cálculo da pasta de trabalho", "Enable iterative calculation" => "Habilitar cálculo iterativo", "Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.", + "Quick Analysis (Ctrl+Q)" => "Análise rápida (Ctrl+Q)", + "Formatting" => "Formatação", + "Charts" => "Gráficos", + "Totals" => "Totais", + "Tables" => "Tabelas", + "Color Scale" => "Escala de cor", + "Icon Set" => "Conjunto de ícones", + "Greater Than…" => "Maior que…", + "Clear Rules" => "Limpar regras", + "Clustered Column" => "Colunas agrupadas", + "Line" => "Linha", + "Pie" => "Pizza", + "Bar" => "Barras", + "Scatter" => "Dispersão", + "Recommended Charts" => "Gráficos recomendados", + "Sum" => "Soma", + "Average" => "Média", + "Count" => "Contagem", + "% Total" => "% do total", + "Running Total" => "Total acumulado", + "By Column" => "Por coluna", + "By Row" => "Por linha", + "Column" => "Coluna", + "Win/Loss" => "Ganho/perda", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index c8f0445d8c..e6273c486b 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", + "Quick Analysis (Ctrl+Q)" => "Быстрый анализ (Ctrl+Q)", + "Formatting" => "Форматирование", + "Charts" => "Диаграммы", + "Totals" => "Итоги", + "Tables" => "Таблицы", + "Color Scale" => "Цветовая шкала", + "Icon Set" => "Набор значков", + "Greater Than…" => "Больше…", + "Clear Rules" => "Удалить правила", + "Clustered Column" => "Гистограмма с группировкой", + "Line" => "График", + "Pie" => "Круговая", + "Bar" => "Линейчатая", + "Scatter" => "Точечная", + "Recommended Charts" => "Рекомендуемые диаграммы", + "Sum" => "Сумма", + "Average" => "Среднее", + "Count" => "Количество", + "% Total" => "% от итога", + "Running Total" => "Нарастающий итог", + "By Column" => "По столбцам", + "By Row" => "По строкам", + "Column" => "Столбец", + "Win/Loss" => "Выигрыш/проигрыш", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index d1cf704cba..440962086e 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -385,6 +385,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "工作簿计算", "Enable iterative calculation" => "启用迭代计算", "Calculation settings are saved with the workbook." => "计算设置随工作簿一起保存。", + "Quick Analysis (Ctrl+Q)" => "快速分析 (Ctrl+Q)", + "Formatting" => "格式化", + "Charts" => "图表", + "Totals" => "汇总", + "Tables" => "表", + "Color Scale" => "色阶", + "Icon Set" => "图标集", + "Greater Than…" => "大于…", + "Clear Rules" => "清除规则", + "Clustered Column" => "簇状柱形图", + "Line" => "折线图", + "Pie" => "饼图", + "Bar" => "条形图", + "Scatter" => "散点图", + "Recommended Charts" => "推荐的图表", + "Sum" => "求和", + "Average" => "平均值", + "Count" => "计数", + "% Total" => "占总计的百分比", + "Running Total" => "累计", + "By Column" => "按列", + "By Row" => "按行", + "Column" => "柱形", + "Win/Loss" => "盈亏", _ => return None, }) } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fe9f7bf51d..2d14cc031a 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -129,6 +129,8 @@ pub enum Icon { OpenFolder, Info, Print, + /// Quick Analysis: a small table with a spark. + QuickAnalysis, } struct G<'a> { @@ -706,6 +708,13 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, c: Color32) { g.line(&[(4.5, 9.0), (4.5, 14.5), (11.5, 14.5), (11.5, 9.0), (4.5, 9.0)], c, 1.1); g.circle(12.3, 7.6, 0.6, Some(c), None); } + Icon::QuickAnalysis => { + g.rect(2.0, 3.0, 12.0, 10.0, None, Some(c)); + g.stroke(&[(2.0, 6.5), (14.0, 6.5)], light); + g.stroke(&[(6.0, 3.0), (6.0, 13.0)], light); + g.stroke(&[(10.0, 3.0), (10.0, 13.0)], light); + g.line(&[(10.0, 1.0), (6.5, 8.0), (9.5, 8.0), (6.5, 15.0)], BLUE, 1.7); + } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b19b2551d..c154945210 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ pub mod panes; pub mod paper_view; pub mod pivot_pane; pub mod printing; +pub mod quick_analysis; pub mod ribbon; pub mod selection_glide; pub mod tabs; @@ -531,6 +532,7 @@ impl SheetApp { self.ui.language = i18n::Language::Ja; Ok(json!({"language": i18n::Language::Ja})) } + "ui.quickAnalysis" => quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)), "ui.backstage" => { // `{"page": "info"}` opens File › Info; `{"page": "close"}` returns to the sheet. match p.get("page").and_then(Json::as_str).map(str::trim) { diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs new file mode 100644 index 0000000000..7bfa454d95 --- /dev/null +++ b/crates/ui-egui/src/quick_analysis.rs @@ -0,0 +1,364 @@ +//! Quick Analysis (Ctrl+Q): a small button at the bottom-right corner of a multi-cell selection +//! that opens a popup of one-click analyses. The popup is a thin front end: every tile runs an +//! engine command through `app.run` (conditional formats, charts, `analysis.addTotal`, tables, +//! pivot tables, `analysis.addSparklines`), so nothing here is UI-only logic worth testing apart +//! from which command a tile maps to ([`tiles`]). + +use egui::{Align2, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use gridcraft_engine::core::RangeRef; +use gridcraft_engine::model::Sheet; +use serde_json::{Value as Json, json}; + +use crate::SheetApp; +use crate::grid::{Drag, Geo}; +use crate::icons::{self, Icon}; +use crate::theme::{self, Tokens}; + +/// Side of the corner button, and its gap to the selection's corner (clear of the fill handle). +const BUTTON: f32 = 22.0; +const GAP: f32 = 6.0; +const TILE: egui::Vec2 = vec2(66.0, 62.0); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Tab { + #[default] + Formatting, + Charts, + Totals, + Tables, + Sparklines, +} + +impl Tab { + const ALL: [Tab; 5] = [Tab::Formatting, Tab::Charts, Tab::Totals, Tab::Tables, Tab::Sparklines]; + fn label(self) -> &'static str { + match self { + Tab::Formatting => "Formatting", + Tab::Charts => "Charts", + Tab::Totals => "Totals", + Tab::Tables => "Tables", + Tab::Sparklines => "Sparklines", + } + } +} + +#[derive(Default)] +pub struct State { + /// The selection the popup was opened for; it closes when the selection changes. + pub open: Option, + pub tab: Tab, + /// Totals by row (results to the right) instead of by column (results below). + pub by_rows: bool, +} + +/// What a tile does. +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + Run(&'static str, Json), + Dialog(&'static str, Json), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Glyph { + Icon(Icon), + Text(&'static str), + Bars, + Scale, + Dots, + Steps, + MiniColumns, + WinLoss, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Tile { + label: &'static str, + glyph: Glyph, + pub action: Action, +} + +fn tile(label: &'static str, glyph: Glyph, action: Action) -> Tile { + Tile { label, glyph, action } +} + +/// The tiles of a tab for the selection `range` (A1 text) on the sheet called `sheet_name`. +pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec { + use Action::{Dialog, Run}; + let cf = |rule: Json| Run("home.conditionalFormat", json!({"range": range, "rule": rule})); + let chart = |kind: &str| Run("insert.chart", json!({"range": range, "type": kind})); + let total = |f: &str| Run("analysis.addTotal", json!({"range": range, "function": f, "direction": if by_rows { "rows" } else { "columns" }})); + let spark = |kind: &str| Run("analysis.addSparklines", json!({"range": range, "type": kind})); + match tab { + Tab::Formatting => vec![ + tile("Data Bars", Glyph::Bars, cf(json!({"type": "dataBar"}))), + tile("Color Scale", Glyph::Scale, cf(json!({"type": "colorScale"}))), + tile("Icon Set", Glyph::Dots, cf(json!({"type": "iconSet"}))), + tile("Greater Than…", Glyph::Text(">"), Dialog("cfQuick", json!({"type": "cellIs", "operator": "greater", "title": "Greater Than…"}))), + tile("Top 10 Items", Glyph::Text("10"), cf(json!({"type": "top10", "rank": 10}))), + tile("Clear Rules", Glyph::Icon(Icon::Eraser), Run("home.clearRules", json!({"range": range}))), + ], + Tab::Charts => vec![ + tile("Clustered Column", Glyph::Icon(Icon::ChartBar), chart("column")), + tile("Line", Glyph::Icon(Icon::ChartLine), chart("line")), + tile("Pie", Glyph::Icon(Icon::ChartPie), chart("pie")), + tile("Bar", Glyph::Icon(Icon::Chart), chart("bar")), + tile("Scatter", Glyph::Icon(Icon::ChartScatter), chart("scatter")), + tile("Recommended Charts", Glyph::Icon(Icon::Chart), Run("insert.recommendedCharts", json!({"range": range}))), + ], + Tab::Totals => vec![ + tile("Sum", Glyph::Icon(Icon::Sum), total("sum")), + tile("Average", Glyph::Text("avg"), total("average")), + tile("Count", Glyph::Text("#"), total("count")), + tile("% Total", Glyph::Icon(Icon::Percent), total("percentTotal")), + tile("Running Total", Glyph::Steps, total("runningTotal")), + ], + Tab::Tables => vec![ + tile("Table", Glyph::Icon(Icon::Table), Run("insert.table", json!({"range": range}))), + tile( + "PivotTable", + Glyph::Icon(Icon::PivotTable), + Run("insert.pivotTable", json!({"source": format!("'{}'!{range}", sheet_name.replace('\'', "''"))})), + ), + ], + Tab::Sparklines => vec![ + tile("Line", Glyph::Icon(Icon::Sparkline), spark("line")), + tile("Column", Glyph::MiniColumns, spark("column")), + tile("Win/Loss", Glyph::WinLoss, spark("winLoss")), + ], + } +} + +/// Ctrl+Q and the `ui.quickAnalysis` command: opens the popup for the selection (or closes it). +/// Errors for a single cell, where there is nothing to analyse. +pub fn toggle(app: &mut SheetApp, on: Option) -> Result { + let sel = app.session.active().map(|d| d.selection.current()).ok_or("no workbook open")?; + let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); + if !want { + app.grid.quick_analysis.open = None; + } else if sel.is_single() { + return Err("Select at least two cells to use Quick Analysis.".into()); + } else { + app.grid.quick_analysis.open = Some(sel); + } + Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) +} + +/// Paints the corner button and, when open, the popup. Called once per grid frame. +pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { + let Some(d) = app.session.active() else { return }; + let sel = d.selection.current(); + let hidden = sel.is_single() + || app.editor.is_some() + || app.dialog.is_some() + || app.text_box_editor.is_some() + || app.grid.context_menu.is_some() + || geo.paper.is_some(); + // The popup belongs to one selection; a new one (or editing) closes it. + if hidden || app.grid.quick_analysis.open.is_some_and(|r| r != sel) { + app.grid.quick_analysis.open = None; + } + if hidden { + return; + } + let sheet_name = sh.name.clone(); + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + let rect = geo.range_rect(sh, sel); + let corner = rect.right_bottom(); + let panes = geo.range_panes(RangeRef::cell(sel.end)); + let corner_visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); + // Below and right of the corner (clear of the fill handle); flipped inside when at an edge. + let area = geo.cells.shrink(2.0); + let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; + let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; + let button = geo.mirror_rect(Rect::from_min_size( + pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))), + vec2(BUTTON, BUTTON), + )); + let open = app.grid.quick_analysis.open.is_some(); + // While the mouse is down (selecting, filling) the button stays out of the way. + let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down()); + let lang = crate::i18n::current(&ctx); + if corner_visible && (open || !busy) { + let mut clicked = false; + egui::Area::new(Id::new("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { + let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click()); + let fill = if resp.is_pointer_button_down_on() || open { + t.pressed + } else if resp.hovered() { + t.hover + } else { + t.menu_bg + }; + ui.painter().rect_filled(r, 4.0, fill); + ui.painter().rect_stroke(r, 4.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); + icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), Icon::QuickAnalysis, t.accent); + clicked = resp.on_hover_text(lang.tr("Quick Analysis (Ctrl+Q)")).clicked(); + }); + if clicked { + let _ = toggle(app, None); + } + } + let Some(opened_for) = app.grid.quick_analysis.open else { return }; + let pos = pos2(button.left(), button.bottom() + 4.0); + let mut picked: Option = None; + let resp = egui::Area::new(Id::new("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + let state = &mut app.grid.quick_analysis; + ui.horizontal(|ui| { + for tab in Tab::ALL { + if ui.selectable_label(state.tab == tab, lang.tr(tab.label())).clicked() { + state.tab = tab; + } + } + }); + ui.separator(); + if state.tab == Tab::Totals { + ui.horizontal(|ui| { + ui.selectable_value(&mut state.by_rows, false, lang.tr("By Column")); + ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")); + }); + } + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for item in tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows) { + if paint_tile(ui, &t, &item, lang.tr(item.label)) { + picked = Some(item.action.clone()); + } + } + }); + }); + }); + let outside_click = ctx.input(|i| i.pointer.any_pressed()) + && ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !resp.response.rect.contains(p) && !button.contains(p)); + if let Some(action) = picked { + app.grid.quick_analysis.open = None; + match action { + Action::Run(id, params) => app.run_or_alert(id, params), + Action::Dialog(name, params) => app.open_dialog(name, params), + } + } else if outside_click || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + app.grid.quick_analysis.open = None; + } +} + +/// One option of the popup: a small picture over a wrapped label. True when clicked. +fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { + let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click()); + if resp.is_pointer_button_down_on() { + ui.painter().rect_filled(rect, 4.0, t.pressed); + } else if resp.hovered() { + ui.painter().rect_filled(rect, 4.0, t.hover); + } + let art = Rect::from_center_size(pos2(rect.center().x, rect.top() + 18.0), vec2(26.0, 26.0)); + paint_glyph(ui, t, item.glyph, art); + let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0); + let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0); + ui.painter().galley(at, galley, t.text); + resp.clicked() +} + +fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) { + let p = ui.painter(); + let (green, blue, red, yellow) = (icons::GREEN, icons::BLUE, icons::RED, icons::YELLOW); + let cell = |i: f32, j: f32| Rect::from_min_size(r.min + vec2(i * r.width() / 3.0, j * r.height() / 3.0), vec2(r.width() / 3.0, r.height() / 3.0)); + match glyph { + Glyph::Icon(icon) => icons::paint(p, r, icon, t.text), + Glyph::Text(s) => { + p.text(r.center(), Align2::CENTER_CENTER, s, theme::ui_bold(15.0), t.accent); + } + Glyph::Bars => { + for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() { + let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0)); + p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, blue); + } + } + Glyph::Scale => { + for (i, c) in [red, yellow, green].into_iter().enumerate() { + p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); + } + } + Glyph::Dots => { + for (j, c) in [green, yellow, red].into_iter().enumerate() { + p.circle_filled(cell(1.0, j as f32).center(), 3.2, c); + } + } + Glyph::Steps => { + for i in 0..3 { + let h = r.height() * (0.35 + 0.28 * i as f32); + p.rect_filled( + Rect::from_min_max( + pos2(r.left() + i as f32 * r.width() / 3.0 + 1.0, r.bottom() - h), + pos2(r.left() + (i + 1) as f32 * r.width() / 3.0 - 1.0, r.bottom()), + ), + 1.0, + green, + ); + } + } + Glyph::MiniColumns => { + for (i, h) in [0.5, 0.9, 0.65].into_iter().enumerate() { + let x = r.left() + i as f32 * r.width() / 3.0 + 2.0; + p.rect_filled(Rect::from_min_max(pos2(x, r.bottom() - r.height() * h), pos2(x + r.width() / 3.0 - 4.0, r.bottom())), 1.0, blue); + } + } + Glyph::WinLoss => { + let mid = r.center().y; + for (i, up) in [true, false, true].into_iter().enumerate() { + let x = r.left() + i as f32 * r.width() / 3.0 + 2.0; + let (a, b) = if up { (mid - 7.0, mid - 1.0) } else { (mid + 1.0, mid + 7.0) }; + p.rect_filled(Rect::from_min_max(pos2(x, a), pos2(x + r.width() / 3.0 - 4.0, b)), 1.0, if up { green } else { red }); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gridcraft_engine::Session; + + /// A header row, a label column and two numeric columns on Sheet1. + fn session() -> (Session, String) { + let mut s = Session::new(); + s.new_workbook(); + for (a, v) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] { + s.execute("cell.set", json!({"cell": a, "input": v})).unwrap(); + } + for (r, (q1, q2)) in [(1, 10), (2, 20), (3, 30)].into_iter().enumerate() { + s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap(); + s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap(); + } + let name = s.doc().unwrap().wb.active().unwrap().name.clone(); + (s, name) + } + + #[test] + fn every_engine_tile_runs_on_a_selection() { + for tab in Tab::ALL { + for by_rows in [false, true] { + let n = tiles(tab, "A1:C4", "Sheet1", by_rows).len(); + for i in 0..n { + let (mut s, name) = session(); + let item = tiles(tab, "A1:C4", &name, by_rows).remove(i); + if let Action::Run(id, params) = &item.action { + s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{} / {}: {e}", tab.label(), item.label)); + } + } + } + } + } + + #[test] + fn dialog_tile_and_single_cell_are_not_engine_runs() { + let formatting = tiles(Tab::Formatting, "A1:C4", "Sheet1", false); + assert!(formatting.iter().any(|t| matches!(&t.action, Action::Dialog("cfQuick", _)))); + // A programmatic open on a single cell is an error, not a popup. + let (s, _) = session(); + let mut app = SheetApp::new(s, Default::default()); + assert!(toggle(&mut app, Some(true)).is_err()); + app.run("selection.set", json!({"range": "A1:C4"})).unwrap(); + assert_eq!(toggle(&mut app, Some(true)).unwrap(), json!({"open": true})); + assert_eq!(app.run("ui.quickAnalysis", json!({"open": false})).unwrap(), json!({"open": false})); + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index e8291accdc..b8054f9a0f 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -2429,6 +2429,11 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T if shift => Some(("formulas.autoSum", json!({}))), Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), + Key::Q => { + // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert. + let _ = crate::quick_analysis::toggle(app, None); + None + } Key::Num1 => { app.open_dialog("formatCells", json!({})); None diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 10abcbccc2..50048c09ea 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (AutoFit reserves filter dropdown space, observed against Windows Excel) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Quick Analysis, Ctrl+Q) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -58,7 +58,7 @@ this logic, with one undo step. | Context menu on cells | 16 items (Cut, Copy, Paste, Paste Special, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup | | Move and resize charts, pictures and shapes | charts can't be resized (#190) | | Context menus on row/column headers, sheet tabs, charts, shapes | headers and tabs done; objects partial | -| Quick Analysis (Ctrl+Q) | missing | +| Quick Analysis (Ctrl+Q) | done (#791): button at the selection's bottom-right corner (hidden while editing or dragging) and Ctrl+Q open a popup with Formatting (data bars, colour scale, icon set, greater than, top 10, clear), Charts, Totals (`analysis.addTotal`: sum, average, count, % total, running total, by column or row), Tables (table, PivotTable) and Sparklines (`analysis.addSparklines`); every tile is an engine command. Missing: hover preview, Quick Analysis for non-contiguous selections, Excel's exact tile set | | Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar reported missing (#176) | | Text overflow into empty neighbours, wrap, rotation, shrink to fit | done | @@ -123,7 +123,8 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | | F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | -| Ctrl+6, Ctrl+8, Ctrl+Q, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, Quick Analysis, argument names, Function Arguments, formula bar height, tooltips | missing | +| Ctrl+Q | Ctrl+Q | Quick Analysis | **added** (#791) | +| Ctrl+6, Ctrl+8, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, argument names, Function Arguments, formula bar height, tooltips | missing | | Ctrl+Shift+Page Up / Down, Ctrl+Alt+5, Ctrl+Shift+F1, Ctrl+F5–F10, Alt+F8 / F11 / F12 | same | group sheets, shape cycling, full screen, window keys, macros, VBA, Power Query | missing | | — | Cmd+= (calculate), Cmd+T (references while editing; F4 works), Shift+F7, Cmd+Shift+L | Mac-only extras | missing (Cmd+= is egui's zoom key; no thesaurus or Modify Cell Style) | @@ -152,7 +153,7 @@ by rule and will never match Office's, by design. ## Work (50–80 h) -Key tips 3–5 · remaining shortcuts with their features 2–4 · context menus and Quick Analysis 5–8 · Page Layout view +Key tips 3–5 · remaining shortcuts with their features 2–4 · context menus 3–5 · Page Layout view 8–12 · Options dialog and ribbon/QAT customization 6–10 · accessibility 12–18 · selection and scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. @@ -160,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | Quick Analysis (Ctrl+Q): corner button and popup with formatting, charts, totals, tables and sparklines; new commands `analysis.addTotal` and `analysis.addSparklines` (#791) | | 2026-10-11 | minor | AutoFit accounts for table and ordinary filter dropdowns, including low zoom; header text excludes the button area | | 2026-10-11 | minor | Outline band for grouped rows and columns, Show / Hide Detail on the Data tab, numpad navigation keys in shortcuts (#373) | | 2026-10-11 | minor | Shift+Space / Ctrl+Space no longer start an edit; Control+Space selects the column on Mac (#338) | From a7e1a4a99bdda6698dbdff64a9876498246c355a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:05:29 +0200 Subject: [PATCH 004/201] Quick Analysis: button tests, several-areas refusal, more formatting tiles (#791) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/i18n/cs.rs | 4 + crates/ui-egui/src/i18n/de.rs | 4 + crates/ui-egui/src/i18n/es.rs | 4 + crates/ui-egui/src/i18n/fr.rs | 4 + crates/ui-egui/src/i18n/ko.rs | 4 + crates/ui-egui/src/i18n/pt.rs | 4 + crates/ui-egui/src/i18n/ru.rs | 4 + crates/ui-egui/src/i18n/zh.rs | 4 + crates/ui-egui/src/quick_analysis.rs | 99 ++++++++++++++----- crates/ui-egui/src/ribbon.rs | 9 +- crates/ui-egui/tests/quick_analysis_button.rs | 84 ++++++++++++++++ 12 files changed, 199 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/tests/quick_analysis_button.rs diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 25b4feb01b..3df27f8a75 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -589,6 +589,10 @@ const JAPANESE: &[(&str, &str)] = &[ ("By Row", "行ごと"), ("Column", "縦棒"), ("Win/Loss", "勝敗"), + ("Green Data Bars", "緑のデータ バー"), + ("Blue-White-Red Scale", "青-白-赤のスケール"), + ("White-Green Scale", "白-緑のスケール"), + ("Duplicate Values", "重複する値"), ]; #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index fadf40d50a..e93dc7f01c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -415,6 +415,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Podle řádků", "Column" => "Sloupec", "Win/Loss" => "Zisk/ztráta", + "Green Data Bars" => "Zelené datové čáry", + "Blue-White-Red Scale" => "Škála modrá-bílá-červená", + "White-Green Scale" => "Škála bílá-zelená", + "Duplicate Values" => "Duplicitní hodnoty", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2fc143105b..70ed6204ef 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -418,6 +418,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Nach Zeile", "Column" => "Säule", "Win/Loss" => "Gewinn/Verlust", + "Green Data Bars" => "Grüne Datenbalken", + "Blue-White-Red Scale" => "Blau-Weiß-Rot-Skala", + "White-Green Scale" => "Weiß-Grün-Skala", + "Duplicate Values" => "Doppelte Werte", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index faad158341..3230e48ff8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Por fila", "Column" => "Columna", "Win/Loss" => "Ganancia/pérdida", + "Green Data Bars" => "Barras de datos verdes", + "Blue-White-Red Scale" => "Escala azul-blanco-rojo", + "White-Green Scale" => "Escala blanco-verde", + "Duplicate Values" => "Valores duplicados", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 04dd35b973..fb9caa2ff4 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -407,6 +407,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Par ligne", "Column" => "Colonne", "Win/Loss" => "Gain/perte", + "Green Data Bars" => "Barres de données vertes", + "Blue-White-Red Scale" => "Échelle bleu-blanc-rouge", + "White-Green Scale" => "Échelle blanc-vert", + "Duplicate Values" => "Valeurs en double", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 480e1fa417..948b3c8333 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "행 기준", "Column" => "열", "Win/Loss" => "이익/손실", + "Green Data Bars" => "녹색 데이터 막대", + "Blue-White-Red Scale" => "파랑-흰색-빨강 눈금", + "White-Green Scale" => "흰색-녹색 눈금", + "Duplicate Values" => "중복 값", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 8395b82238..6118274fb9 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -418,6 +418,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Por linha", "Column" => "Coluna", "Win/Loss" => "Ganho/perda", + "Green Data Bars" => "Barras de dados verdes", + "Blue-White-Red Scale" => "Escala azul-branco-vermelho", + "White-Green Scale" => "Escala branco-verde", + "Duplicate Values" => "Valores duplicados", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index e6273c486b..e7930a0d6e 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "По строкам", "Column" => "Столбец", "Win/Loss" => "Выигрыш/проигрыш", + "Green Data Bars" => "Зелёные гистограммы", + "Blue-White-Red Scale" => "Шкала сине-бело-красная", + "White-Green Scale" => "Шкала бело-зелёная", + "Duplicate Values" => "Повторяющиеся значения", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 440962086e..9bbd6514d7 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -409,6 +409,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "按行", "Column" => "柱形", "Win/Loss" => "盈亏", + "Green Data Bars" => "绿色数据条", + "Blue-White-Red Scale" => "蓝-白-红色阶", + "White-Green Scale" => "白-绿色阶", + "Duplicate Values" => "重复值", _ => return None, }) } diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 7bfa454d95..94032e4d38 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -4,7 +4,7 @@ //! pivot tables, `analysis.addSparklines`), so nothing here is UI-only logic worth testing apart //! from which command a tile maps to ([`tiles`]). -use egui::{Align2, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui::{Align2, Color32, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use gridcraft_engine::core::RangeRef; use gridcraft_engine::model::Sheet; use serde_json::{Value as Json, json}; @@ -64,6 +64,9 @@ enum Glyph { Text(&'static str), Bars, Scale, + GreenBars, + BlueScale, + GreenScale, Dots, Steps, MiniColumns, @@ -96,6 +99,12 @@ pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec"), Dialog("cfQuick", json!({"type": "cellIs", "operator": "greater", "title": "Greater Than…"}))), tile("Top 10 Items", Glyph::Text("10"), cf(json!({"type": "top10", "rank": 10}))), tile("Clear Rules", Glyph::Icon(Icon::Eraser), Run("home.clearRules", json!({"range": range}))), + tile("Green Data Bars", Glyph::GreenBars, cf(json!({"type": "dataBar", "color": "#63BE7B"}))), + tile("Blue-White-Red Scale", Glyph::BlueScale, cf(json!({"type": "colorScale", "colors": ["#5A8AC6", "#FCFCFF", "#F8696B"]}))), + tile("White-Green Scale", Glyph::GreenScale, cf(json!({"type": "colorScale", "colors": ["#FCFCFF", "#63BE7B"]}))), + tile("Top 10%", Glyph::Text("10%"), cf(json!({"type": "top10", "rank": 10, "percent": true}))), + tile("Below Average", Glyph::Text(" vec![ tile("Clustered Column", Glyph::Icon(Icon::ChartBar), chart("column")), @@ -131,7 +140,11 @@ pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec) -> Result { - let sel = app.session.active().map(|d| d.selection.current()).ok_or("no workbook open")?; + let d = app.session.active().ok_or("no workbook open")?; + if d.selection.ranges.len() > 1 { + return Err("Quick Analysis works on one block of cells; select a single contiguous range.".into()); + } + let sel = d.selection.current(); let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); if !want { app.grid.quick_analysis.open = None; @@ -143,16 +156,38 @@ pub fn toggle(app: &mut SheetApp, on: Option) -> Result { Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) } -/// Paints the corner button and, when open, the popup. Called once per grid frame. -pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { - let Some(d) = app.session.active() else { return }; - let sel = d.selection.current(); - let hidden = sel.is_single() +/// Whether the button (and popup) stay out of the way: a single cell or several areas, editing, +/// an open dialog or menu, and the paged views have no corner to hang them on. +pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool { + let Some(d) = app.session.active() else { return true }; + d.selection.ranges.len() > 1 + || d.selection.current().is_single() || app.editor.is_some() || app.dialog.is_some() || app.text_box_editor.is_some() || app.grid.context_menu.is_some() - || geo.paper.is_some(); + || geo.paper.is_some() + || sh.view == gridcraft_engine::model::SheetViewMode::PageLayout +} + +/// Where the corner button sits for `sel` (on screen), and whether the selection's corner is in +/// view. Below and right of the corner, clear of the fill handle; flipped inside at the grid edge. +pub fn button_rect(geo: &Geo, sh: &Sheet, sel: RangeRef) -> (Rect, bool) { + let corner = geo.range_rect(sh, sel).right_bottom(); + let panes = geo.range_panes(RangeRef::cell(sel.end)); + let visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); + let area = geo.cells.shrink(2.0); + let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; + let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; + let at = pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))); + (geo.mirror_rect(Rect::from_min_size(at, vec2(BUTTON, BUTTON))), visible) +} + +/// Paints the corner button and, when open, the popup. Called once per grid frame. +pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { + let Some(d) = app.session.active() else { return }; + let sel = d.selection.current(); + let hidden = is_hidden(app, geo, sh); // The popup belongs to one selection; a new one (or editing) closes it. if hidden || app.grid.quick_analysis.open.is_some_and(|r| r != sel) { app.grid.quick_analysis.open = None; @@ -163,18 +198,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let sheet_name = sh.name.clone(); let ctx = ui.ctx().clone(); let t = Tokens::get(&ctx); - let rect = geo.range_rect(sh, sel); - let corner = rect.right_bottom(); - let panes = geo.range_panes(RangeRef::cell(sel.end)); - let corner_visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); - // Below and right of the corner (clear of the fill handle); flipped inside when at an edge. - let area = geo.cells.shrink(2.0); - let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; - let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; - let button = geo.mirror_rect(Rect::from_min_size( - pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))), - vec2(BUTTON, BUTTON), - )); + let (button, corner_visible) = button_rect(geo, sh, sel); let open = app.grid.quick_analysis.open.is_some(); // While the mouse is down (selecting, filling) the button stays out of the way. let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down()); @@ -219,14 +243,17 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")); }); } - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for item in tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows) { - if paint_tile(ui, &t, &item, lang.tr(item.label)) { - picked = Some(item.action.clone()); + let items = tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows); + for row in items.chunks(6) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for item in row { + if paint_tile(ui, &t, item, lang.tr(item.label)) { + picked = Some(item.action.clone()); + } } - } - }); + }); + } }); }); let outside_click = ctx.input(|i| i.pointer.any_pressed()) @@ -278,6 +305,24 @@ fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) { p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); } } + Glyph::GreenBars => { + for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() { + let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0)); + p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, green); + } + } + Glyph::BlueScale | Glyph::GreenScale => { + let cols = if glyph == Glyph::BlueScale { [blue, Color32::WHITE, red] } else { [Color32::WHITE, green.gamma_multiply(0.5), green] }; + for (i, c) in cols.into_iter().enumerate() { + p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); + } + p.rect_stroke( + Rect::from_min_size(cell(0.0, 1.0).min, vec2(r.width(), r.height() / 3.0)), + 1.0, + Stroke::new(1.0, t.separator), + StrokeKind::Inside, + ); + } Glyph::Dots => { for (j, c) in [green, yellow, red].into_iter().enumerate() { p.circle_filled(cell(1.0, j as f32).center(), 3.2, c); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index b8054f9a0f..dcc963dc3e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -2430,8 +2430,13 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), Key::Q => { - // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert. - let _ = crate::quick_analysis::toggle(app, None); + // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert, + // but several areas deserve to be told why nothing opened. + if let Err(e) = crate::quick_analysis::toggle(app, None) + && app.session.active().is_some_and(|d| d.selection.ranges.len() > 1) + { + app.alert(e); + } None } Key::Num1 => { diff --git a/crates/ui-egui/tests/quick_analysis_button.rs b/crates/ui-egui/tests/quick_analysis_button.rs new file mode 100644 index 0000000000..65fa142d91 --- /dev/null +++ b/crates/ui-egui/tests/quick_analysis_button.rs @@ -0,0 +1,84 @@ +//! Quick Analysis: where the corner button sits, and when it keeps out of the way. + +use egui::{Rect, Vec2, pos2, vec2}; +use gridcraft_engine::Session; +use gridcraft_engine::core::RangeRef; +use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::grid::Geo; +use gridcraft_ui_egui::quick_analysis::{button_rect, is_hidden, toggle}; +use serde_json::json; + +fn app() -> SheetApp { + let mut s = Session::new(); + s.new_workbook(); + SheetApp::new(s, Default::default()) +} + +fn geo(app: &SheetApp) -> Geo { + let sheet = app.session.active().unwrap().wb.active().unwrap(); + Geo::new(sheet, Rect::from_min_max(pos2(0.0, 0.0), pos2(1200.0, 800.0)), Vec2::ZERO) +} + +#[test] +fn the_button_sits_below_right_of_the_corner_clear_of_the_fill_handle() { + let app = app(); + let (g, sh) = (geo(&app), app.session.active().unwrap().wb.active().unwrap()); + let sel = RangeRef::parse("B2:D5").unwrap(); + let corner = g.range_rect(sh, sel).right_bottom(); + let (button, visible) = button_rect(&g, sh, sel); + assert!(visible); + assert!(button.left() > corner.x && button.top() > corner.y, "below and right of the corner"); + // The fill handle is a 9 x 9 square centred on the corner. + assert!(!button.intersects(Rect::from_center_size(corner, vec2(9.0, 9.0))), "clear of the fill handle"); +} + +#[test] +fn at_the_grid_edge_the_button_flips_inside_and_far_corners_are_not_visible() { + let app = app(); + let (g, sh) = (geo(&app), app.session.active().unwrap().wb.active().unwrap()); + let near_edge = RangeRef::parse("A1:ZZ1").unwrap(); + let (far, visible) = button_rect(&g, sh, near_edge); + assert!(!visible, "the corner is scrolled out of view"); + assert!(g.cells.contains_rect(far), "the popup still has an anchor inside the grid"); + let (b, _) = button_rect(&g, sh, RangeRef::parse("A1:A200").unwrap()); + assert!(g.cells.contains_rect(b)); +} + +#[test] +fn the_button_hides_for_single_cells_several_areas_editing_dialogs_and_page_layout() { + let mut app = app(); + app.run("selection.set", json!({"cell": "B2"})).unwrap(); + let hidden = |app: &SheetApp| { + let g = geo(app); + is_hidden(app, &g, app.session.active().unwrap().wb.active().unwrap()) + }; + assert!(hidden(&app), "a single cell"); + app.run("selection.set", json!({"range": "B2:D5"})).unwrap(); + assert!(!hidden(&app)); + app.begin_edit(None, false); + assert!(hidden(&app), "while editing"); + app.editor = None; + app.open_dialog("find", json!({})); + assert!(hidden(&app), "while a dialog is open"); + app.dialog = None; + assert!(!hidden(&app)); + app.run("view.pageLayout", json!({})).unwrap(); + assert!(hidden(&app), "Page Layout view"); + app.run("view.normal", json!({})).unwrap(); + assert!(!hidden(&app)); +} + +#[test] +fn several_areas_are_refused_with_a_message_rather_than_guessed() { + let mut app = app(); + app.run("selection.set", json!({"range": "B2:D5,F2:G5"})).unwrap(); + let err = toggle(&mut app, Some(true)).unwrap_err(); + assert!(err.contains("one block"), "{err}"); + assert!(app.grid.quick_analysis.open.is_none()); + assert!(hidden_for_areas(&app)); +} + +fn hidden_for_areas(app: &SheetApp) -> bool { + let g = geo(app); + is_hidden(app, &g, app.session.active().unwrap().wb.active().unwrap()) +} From 7d3516ab331924603b1ed9ba340079e2dc0b046e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:09:27 +0200 Subject: [PATCH 005/201] Calc: SUBTOTAL(10x) recalculates when Row Height, AutoFit Row Height or Ungroup reveal rows home.rowHeight, home.autofitRowHeight and data.ungroup change row hidden state without marking the edit structural, so SUBTOTAL(101-111) kept a stale value. Found by the command-sequence fuzz (seed 3). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/engine/src/cmd/data.rs | 1 + crates/engine/src/cmd/format.rs | 2 ++ crates/engine/src/tests.rs | 16 ++++++++++++++++ 4 files changed, 20 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 25b8d9b803..acacee974f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -133,6 +133,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| | 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) | +| 2026-10-12 | SUBTOTAL(109) over hidden rows recalculates after Row Height, AutoFit Row Height and Ungroup reveal rows (found by the command-sequence fuzz) | | 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available | | 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found | | 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) | diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index e4aa3baa6e..d2b3612b7d 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -1129,6 +1129,7 @@ fn group(s: &mut Session, p: &Json, on: bool) -> Result { { e.collapsed = false; } + cx.structural = true; // ungrouping reveals hidden rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index dde5fa120d..8d46010299 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -953,6 +953,7 @@ fn row_height(s: &mut Session, p: &Json) -> Result { e.custom = true; } } + cx.structural = true; // setting a height shows or hides rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } @@ -1069,6 +1070,7 @@ fn autofit_rows(s: &mut Session, p: &Json) -> Result { } cx.fit_rows.extend((a..=b).map(|r| (si, r))); } + cx.structural = true; // autofit reveals hidden rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c348dbaff2..123afa8064 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2866,3 +2866,19 @@ fn analysis_add_sparklines_one_per_row_in_one_undo_step() { assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty()); assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err()); } + +#[test] +fn subtotal_109_recalculates_when_row_height_or_autofit_reveals_rows() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [4], [8]]})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": "=SUBTOTAL(109,A1:A4)"})).unwrap(); + s.execute("home.hideRows", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(9.0)); + // A non-zero height unhides the rows (the fuzz found the stale SUBTOTAL). + s.execute("home.rowHeight", json!({"rows": "2:3", "height": 60.0})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(15.0)); + s.execute("home.hideRows", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(9.0)); + s.execute("home.autofitRowHeight", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(15.0)); +} From 28a645ca13d60d0031fe8e463cb998e29bd19d20 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Tue, 13 Oct 2026 08:00:40 -0300 Subject: [PATCH 006/201] Calc: a contested spill area stays with its array on full recalc and reopening (#964) When two dynamic arrays want the same cells, the one already spilling there keeps them and the newcomer is #SPILL!, as when the second is entered. recalc_all remembers the layout it clears (formulas that spilled, formulas that were #SPILL!) and lays arrays out in that order, then in reading order. The XLSX reader restores a dynamic array's saved `ref` as its spill range, because the file can only cache #VALUE! for a blocked array. Found by the command-sequence fuzz. --- ROADMAP.md | 1 + crates/calc/src/recalc.rs | 36 +++++++++++++++++++++++++++-------- crates/calc/src/tests.rs | 14 ++++++++++++++ crates/engine/src/tests.rs | 15 +++++++++++++++ crates/xlsx/src/sheet_read.rs | 8 ++++++++ 5 files changed, 66 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..9cd46e5fcb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-13 | Spills: when two dynamic arrays want the same cells, the one already spilling there keeps them after Calculate Now and after saving and reopening, as when the second was entered (#964, found by the command-sequence fuzz) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index b391821d72..f8dc677d53 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -781,6 +781,17 @@ impl Host for PassHost<'_> { } } +/// What a full recalculation knows about the spill layout it clears, so a contested area goes to +/// the same formula as in an incremental recalculation. +#[derive(Default)] +struct Prior { + /// Formulas that spilled (their area, from the last calculation or the file's `ref`). + spilled: HashSet, + /// Formulas that showed #SPILL!. A cell's value moves with it on a structural edit, its spill + /// area doesn't. + blocked: HashSet, +} + impl Calc { pub fn new() -> Self { Self::default() @@ -814,16 +825,19 @@ impl Calc { self.rebuild(wb); // Spills are laid out again from the formulas where they are now (a structural edit moves // or deletes the formulas, not the values they spilled). + let mut prior = Prior::default(); for i in 0..wb.sheets.len() { if wb.sheet(i).is_some_and(|s| !s.spill_ranges.is_empty() || !s.spill.is_empty()) && let Some(sh) = wb.sheet_mut(i) { + prior.spilled.extend(sh.spill_ranges.iter().filter(|(_, r)| !r.is_single()).map(|(c, _)| (i, *c))); sh.spill.clear(); sh.spill_ranges.clear(); } } let all: Vec = self.graph.nodes.keys().copied().collect(); - self.run(wb, all, true); + prior.blocked = all.iter().copied().filter(|k| wb.sheet(k.0).is_some_and(|s| s.value(k.1) == Value::Error(CellError::Spill))).collect(); + self.run(wb, all, &prior); } /// Updates the graph for cells whose content changed and recalculates what depends on them. @@ -860,7 +874,7 @@ impl Calc { if wb.calc.mode == CalcMode::Manual { // Only the edited formulas themselves are evaluated. let own: Vec = changed.iter().copied().filter(|k| self.graph.nodes.contains_key(k)).collect(); - self.run(wb, own, false); + self.run(wb, own, &Prior::default()); return; } let mut seeds: Vec = changed.to_vec(); @@ -908,7 +922,7 @@ impl Calc { let dirty = self.dirty_closure(wb, &seeds); let t1 = prof_now(); let n = dirty.len(); - self.run(wb, dirty, false); + self.run(wb, dirty, &Prior::default()); if std::env::var_os("GRIDCRAFT_PROFILE").is_some() { eprintln!("recalc: {} seeds, closure {} cells {:.1} ms, run {:.1} ms", seeds.len(), n, t1 - t0, prof_now() - t1); } @@ -947,8 +961,9 @@ impl Calc { seen.into_iter().collect() } - /// Evaluates the dirty set and writes results (and spills) back. - fn run(&mut self, wb: &mut Workbook, mut dirty: Vec, full: bool) { + /// Evaluates the dirty set and writes results (and spills) back. `prior` is the layout a full + /// recalculation cleared (empty otherwise). + fn run(&mut self, wb: &mut Workbook, mut dirty: Vec, prior: &Prior) { let mut dynamic_again = !self.graph.dynamic.is_empty(); for _round in 0..8 { if dirty.is_empty() { @@ -997,6 +1012,14 @@ impl Calc { cell.value = v; } } + // When two arrays want the same cells, the one already spilling there keeps them and + // the newcomer is #SPILL! (as when it is entered), and one that was #SPILL! stays so: + // arrays are laid out in that order, then in reading order. Without this, a full + // recalculation or reopening the file handed the area to whichever came first. + dirty.sort_by_key(|k| { + let owns = prior.spilled.contains(k) || wb.sheet(k.0).is_some_and(|s| s.spill_ranges.contains_key(&k.1)); + (prior.blocked.contains(k), !owns) + }); for k in &dirty { let new = spills.get(k); let Some(sheet) = wb.sheet_mut(k.0) else { continue }; @@ -1062,9 +1085,6 @@ impl Calc { } } } - if full { - // Everything was already evaluated once; spill dependents need another pass. - } if std::env::var_os("GRIDCRAFT_PROFILE").is_some() { eprintln!(" write-back {:.1} ms", prof_now() - tw); } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..991076d7ad 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -368,6 +368,20 @@ fn spill_into_the_old_area_of_a_blocked_neighbour() { assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]); } +#[test] +fn a_full_recalc_keeps_a_spill_with_the_formula_already_spilling_there() { + // F13's array would spill over F14:G14, which C14's array already fills: F13 is #SPILL!, and + // a full recalculation (Ctrl+Alt+F9) doesn't hand the area to F13 for coming first in + // reading order. + let mut t = T::new(); + t.set("C14", "=SEQUENCE(1,7)"); + t.set("F13", "=SEQUENCE(5,2)"); + assert_eq!(t.get("F13"), Value::Error(CellError::Spill)); + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.get("F13"), Value::Error(CellError::Spill)); + assert_eq!([t.num("C14"), t.num("G14"), t.num("I14")], [1.0, 5.0, 7.0]); +} + #[test] fn arrays_do_not_spill_in_tables() { // Excel: spilled array formulas aren't supported in tables. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae499a1895..280c1476a9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2008,6 +2008,21 @@ fn a_spill_that_goes_away_unblocks_another() { assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0))); } +#[test] +fn a_contested_spill_area_stays_with_its_array_after_reopening() { + // F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file + // can only cache #VALUE! for it; reopening (which recalculates) used to hand the area to F13 + // for coming first in reading order. + let mut s = s(); + s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap(); + s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap(); + assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill)); + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + s.execute("file.open", json!({"name": "contested.xlsx", "base64": saved["base64"]})).unwrap(); + assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill)); + assert_eq!((v(&s, "C14"), v(&s, "G14"), v(&s, "I14")), (Value::Number(1.0), Value::Number(5.0), Value::Number(7.0))); +} + #[test] fn an_array_reading_another_arrays_spill_is_updated() { // G5 is evaluated before D11 in the same pass, so it first reads D11's old spill. diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0194d22688..bd4f793806 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -452,6 +452,14 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos let dynamic = c.attr("cm").is_some(); let formula = c.child("f").and_then(|f| read_formula(cx, st, f, pos, dynamic)); let value = if formula.is_none() && st.dynamic.iter().any(|r| r.contains(pos) && r.start != pos) { Value::Empty } else { value }; + // A dynamic array keeps the area it was saved spilling over (`ref`): when two arrays want the + // same cells, recalculating gives them to this one again, as before saving. + if dynamic + && formula.as_ref().is_some_and(|f| f.array.is_none()) + && let Some(r) = st.dynamic.last().filter(|r| r.start == pos) + { + sheet.spill_ranges.insert(pos, *r); + } sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style }); } From a6d70bcafb2a9d13516b5f2a9979758dd62ff2f9 Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:55:08 -0400 Subject: [PATCH 007/201] CSV/text export: every General number as & converts it (15 significant digits) Main writes plain General with Rust's shortest round-trip (0.30000000000000004, 100000000000000000000) and still narrows coloured/sectioned General and numbers in Text cells to the 11-character cell display (1.24412E+11). Export now formats through numfmt's format_value_full, which writes General as number_to_text does, replacing io.rs's plain-General special case. Docs: merge the duplicate CSV/text rows. --- crates/engine/src/display.rs | 23 +++++++++++--- crates/engine/src/io.rs | 60 ++++++++++++++++++++++++++++-------- crates/numfmt/src/lib.rs | 36 +++++++++++++++------- crates/numfmt/src/render.rs | 9 +++--- crates/numfmt/src/tests.rs | 2 +- docs/file-format-parity.md | 9 +++--- 6 files changed, 100 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index b90e42727b..3e8d47c164 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -5,7 +5,7 @@ use std::sync::Mutex; use gridcraft_core::{CellRef, RangeRef, Value}; use gridcraft_model::{Sheet, Workbook}; -use gridcraft_numfmt::{Formatted, NumberFormat, format_value}; +use gridcraft_numfmt::{Formatted, NumberFormat, format_value, format_value_full}; /// Parsed number formats are cached by code. fn parsed(code: &str) -> NumberFormat { @@ -80,7 +80,8 @@ pub fn formula_hidden(wb: &Workbook, sheet: &Sheet, c: CellRef) -> bool { wb.styles.get(sheet.style_id(at)).protection.hidden } -/// The text a cell shows (full precision General; the grid narrows General to fit the column). +/// The text a cell shows (General up to the 11-character cell width; the grid narrows General +/// further to fit the column). pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { if sheet.show_formulas && let Some(f) = sheet.cell(c).and_then(|x| x.formula.as_ref()) @@ -88,14 +89,26 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { { return format!("={}", f.text); } - value_text(wb, sheet, c) + shown_text(wb, sheet, c) } /// A cell's value with its number format applied, independent of column width: no `#####` -/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. +/// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number +/// shown as General (also through a coloured or sectioned General, or a Text format) reads as `&` +/// turns it into text (`124412140710`, not `1.24412E+11`); Excel writes the cell display there. pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { let style = wb.styles.get(sheet.style_id(c)); - let f = format(&sheet.value(c), style.num_fmt.as_str(), wb); + with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system)) +} + +/// A cell's value through its number format, General at the 11-character cell width. +fn shown_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { + let style = wb.styles.get(sheet.style_id(c)); + with_fill_space(format(&sheet.value(c), style.num_fmt.as_str(), wb)) +} + +/// The formatted text with a single space where a `*x` repeat fill would expand. +fn with_fill_space(f: Formatted) -> String { match f.fill { Some((_, pos)) => { let mut t = f.text; diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 3e84036cbc..0cf40735fe 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -231,20 +231,10 @@ pub fn source_dir(path: &str) -> Option { /// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all /// characters in each cell" (Microsoft Support, *Excel formatting and features that are not /// transferred to other file formats*): number formats applied, never column-width `#####`. +/// One intentional difference: a number shown as General is written as `&` converts it (15 +/// significant digits), not narrowed to the cell width, so long identifiers survive. fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { - gridcraft_xlsx::write_csv(sh, delimiter, |c| { - // General's grid-width formatting rounds large identifiers to scientific notation. - // Delimited files have no column width, so preserve the whole numeric value instead. - if wb.styles.get(sh.style_id(c)).num_fmt.as_str().eq_ignore_ascii_case("General") - && let gridcraft_core::Value::Number(number) = sh.value(c) - && number.is_finite() - { - number.to_string() - } else { - crate::display::value_text(wb, sh, c) - } - }) - .map_err(|e| EngineError::Other(e.to_string())) + gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string())) } fn esc(s: &str) -> String { @@ -711,6 +701,50 @@ mod tests { } } + /// A number shown as General is written as `&` converts it (15 significant digits), whatever + /// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell + /// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive. + #[test] + fn delimited_exports_write_general_numbers_as_text_converts_them() { + use gridcraft_core::Value; + use gridcraft_model::{Cell, NumFmt, StyleId}; + let mut wb = Workbook::new(); + let mut styled = |code: &str| wb.styles.derive(StyleId::DEFAULT, |s| s.num_fmt = NumFmt::new(code)); + let (blue, signed, red, text, unit) = + (styled("[Blue]General"), styled("General;-General"), styled("General;[Red]-General"), styled("@"), styled("General\" mm\"")); + let code = 124412140710.0; + let sh = wb.sheet_mut(0).unwrap(); + let cells = [ + (Value::Number(1.0 / 3.0), StyleId::DEFAULT), + (Value::Number(0.1 + 0.2), StyleId::DEFAULT), + (Value::Number(1e20), StyleId::DEFAULT), + (Value::Number(code), blue), + (Value::Number(-1.0 / 3.0), blue), + (Value::Number(-code), signed), + (Value::Number(-code), red), + (Value::Number(code), text), + (Value::Number(code), unit), + ]; + for (col, (value, style)) in cells.into_iter().enumerate() { + sh.set_cell(CellRef::new(0, col as u32), Cell { value, formula: None, style }); + } + for (path, sep) in [("out.csv", ","), ("out.txt", "\t")] { + let output = String::from_utf8(save_bytes(&wb, path).unwrap()).unwrap(); + let expected = [ + "0.333333333333333", + "0.3", + "1E+20", + "124412140710", + "-0.333333333333333", + "-124412140710", + "-124412140710", + "124412140710", + "124412140710 mm", + ]; + assert_eq!(output, format!("{}\r\n", expected.join(sep))); + } + } + #[test] fn template_extension_saves_template_content_type() { let bytes = save_bytes(&Workbook::new(), "Budget.xltx").unwrap(); diff --git a/crates/numfmt/src/lib.rs b/crates/numfmt/src/lib.rs index 6280e1d268..22f2880660 100644 --- a/crates/numfmt/src/lib.rs +++ b/crates/numfmt/src/lib.rs @@ -256,23 +256,25 @@ impl NumberFormat { } /// Formats a number. The flag is true when the value cannot be shown (date out of range). - fn format_number(&self, n: f64, sys: DateSystem) -> (Formatted, bool) { - let general = |n: f64| Formatted { - text: format_general_fit(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), - color: None, - fill: None, - numeric: true, + /// With `full`, General is not narrowed to the cell width: it reads as `&` turns the number + /// into text (15 significant digits). + fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) { + let general_text = |n: f64, width: usize| { + if full { Some(gridcraft_core::number_to_text(n)) } else { format_general_fit(n, width) } }; + let general = + |n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true }; if self.is_general() { return (general(n), false); } let Some((sec, drop_sign)) = self.select(n) else { return (general(n), false) }; let minus = n < 0.0 && !drop_sign; let out: Option = match sec.kind { - SecKind::Text => Some(render::render_text(sec, &format_general_fit(n, GENERAL_WIDTH).unwrap_or_default())), + SecKind::Text => Some(render::render_text(sec, &general_text(n, GENERAL_WIDTH).unwrap_or_default())), SecKind::General => { let width = if minus { GENERAL_WIDTH - 1 } else { GENERAL_WIDTH }; - Some(render::render_general(sec, n.abs(), width)) + let text = general_text(n.abs(), width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11))); + Some(render::render_general(sec, &text)) } SecKind::Date => { if minus { @@ -306,16 +308,28 @@ impl NumberFormat { /// Formats a cell value for display. pub fn format_value(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted { + format_value_with(v, fmt, sys, false) +} + +/// Formats a cell value as Save As CSV/Text writes it: like [`format_value`], except that a number +/// shown as General (a General or Text section, with or without colour and literals) is not +/// narrowed to the cell width but written as `&` turns it into text: `124412140710`, not +/// `1.24412E+11`. Excel writes the cell display here; GridCraft keeps the digits. +pub fn format_value_full(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted { + format_value_with(v, fmt, sys, true) +} + +fn format_value_with(v: &Value, fmt: &NumberFormat, sys: DateSystem, full: bool) -> Formatted { match v { Value::Empty => Formatted::default(), Value::Number(n) if !n.is_finite() => Formatted { text: CellError::Num.as_str().into(), ..Formatted::default() }, - Value::Number(n) => fmt.format_number(*n, sys).0, + Value::Number(n) => fmt.format_number(*n, sys, full).0, Value::Text(t) => fmt.format_text(t), Value::Bool(b) => Formatted { text: if *b { "TRUE" } else { "FALSE" }.into(), ..Formatted::default() }, Value::Error(e) => Formatted { text: e.as_str().into(), ..Formatted::default() }, Value::Array(a) => match a.data.first() { Some(Value::Array(_)) | None => Formatted::default(), - Some(first) => format_value(first, fmt, sys), + Some(first) => format_value_with(first, fmt, sys, full), }, } } @@ -417,7 +431,7 @@ pub fn text_function(v: &Value, code: &str, sys: DateSystem) -> Result Out { out } -/// Renders a number through a General section (literals around the General keyword). -pub(crate) fn render_general(sec: &Section, v: f64, width: usize) -> Out { +/// Renders a number through a General section: `general` (the number already written as General) +/// with the section's literals around it. +pub(crate) fn render_general(sec: &Section, general: &str) -> Out { let mut out = Out::default(); for t in &sec.toks { match t { - Tok::General => out.push(&format_general_fit(v, width).unwrap_or_else(|| "#".repeat(width.clamp(1, 11)))), + Tok::General => out.push(general), Tok::Fill(c) => out.fill(*c), other => out.push(&other.literal_text()), } diff --git a/crates/numfmt/src/tests.rs b/crates/numfmt/src/tests.rs index e5687f5bd8..f45868664a 100644 --- a/crates/numfmt/src/tests.rs +++ b/crates/numfmt/src/tests.rs @@ -637,7 +637,7 @@ fn text_uncached(v: &Value, code: &str, sys: DateSystem) -> Result **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** trivial (XLSX chart sheets are kept on save (#727); previously minor: CSV save keeps the separator it was opened with) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (CSV/text export writes every General number as `&` converts it) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -41,10 +41,8 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Notes | |---|---|---|---|---| -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Excel writes the **displayed** values; we write raw values. No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | -| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes | Text Import Wizard options partly via Text to Columns | -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF) | Writes the **displayed** values like Excel (number formats applied, formula results, never column-width `#####`). No encoding choice on save. Re-import of a single-column export splits text (#127) A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | -| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes (displayed values) | Text Import Wizard options partly via Text to Columns | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it to 15 significant digits, as `&` converts it (`124412140710`, `0.333333333333333`), so part codes survive a round trip. The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes (displayed values, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.dif`, `.slk` (SYLK) | R/W | no | no | Small, legacy | | `.htm` / `.html` web page | R/W (Windows) | yes, via Get Data ▸ From HTML | yes (one sheet as a table; a used range taller than 100,001 rows fails with an error instead of being cut short) | Formatting not exported | @@ -85,6 +83,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | CSV/text export writes General numbers as `&` converts them (15 significant digits: `0.3`, not `0.30000000000000004`) also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | From 9331dbb47472b3da94c68577f9211d1fd3ab8947 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 08:23:36 -0400 Subject: [PATCH 008/201] Values: number text rounds to 15 digits before choosing decimal or scientific number_to_text picked the decimal branch for values in [999999999999999.5, 1e15) and then rounded them up to the 16-digit integer 1000000000000000. It now rounds to 15 significant digits first and chooses the notation from the rounded exponent, so those values read 1E+15 (and -1E+15). --- crates/core/src/value.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index cfef7ac57d..42f7912fb5 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -355,12 +355,14 @@ pub fn number_to_text(n: f64) -> String { if n == 0.0 || !n.is_finite() { return "0".into(); } - let a = n.abs(); - if !(1e-9..1e15).contains(&a) && a.round() != a || a >= 1e15 { + // Round to 15 significant digits first, then pick decimal or scientific from the rounded + // magnitude, so 999999999999999.5 reads `1E+15`, never a 16-digit integer. + let sci = format!("{:.14e}", n); + let mag: i32 = sci.split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0); + if !(-9..15).contains(&mag) { return sci_text(n, 15); } // 15 significant digits, trailing zeros trimmed. - let mag = a.log10().floor() as i32; let decimals = (14 - mag).clamp(0, 30) as usize; let s = format!("{:.*}", decimals, n); trim_decimal(&s) @@ -399,6 +401,12 @@ mod tests { assert_eq!(number_to_text(1234567890123456.0), "1.23456789012346E+15"); assert_eq!(number_to_text(0.0001), "0.0001"); assert_eq!(number_to_text(1e-10), "1E-10"); + assert_eq!(number_to_text(1e15 - 0.5), "1E+15"); + assert_eq!(number_to_text(1e15 - 0.1), "1E+15"); + assert_eq!(number_to_text(-(1e15 - 0.5)), "-1E+15"); + assert_eq!(number_to_text(999999999999999.0), "999999999999999"); + assert_eq!(number_to_text(9.999999999999999e-10), "0.000000001"); + assert_eq!(number_to_text(-9.999999999999999e-10), "-0.000000001"); assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333"); } From 4dd4ff9a9358e071e3109790c3fe0c69785c19a0 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 08:23:36 -0400 Subject: [PATCH 009/201] CSV/text export: integers below 2^53 keep every digit Writing every General number as & converts it rounded 16-digit integers such as card and order numbers to 1.23456789012346E+15, so opening a CSV and saving it again changed the data. Integers that f64 holds exactly (|x| < 2^53) are now written with all their digits, as before; larger integers and non-integers keep the 15-significant-digit & text. --- crates/engine/src/io.rs | 16 ++++++++++++++-- crates/numfmt/src/lib.rs | 14 +++++++++++--- docs/file-format-parity.md | 4 ++-- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 0cf40735fe..2b711f573b 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -695,15 +695,27 @@ mod tests { sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() }); sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() }); sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() }); + // Integers f64 holds exactly (below 2^53) keep every digit; larger integers and + // non-integers get the 15 significant digits `&` gives. + for (col, n) in [(3, 1234567890123456.0), (4, -9007199254740991.0), (5, 12345678901234567.0), (6, 1e15 - 0.5)] { + sheet.set_cell(CellRef::new(0, col), Cell { value: Value::Number(n), ..Default::default() }); + } for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] { let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap(); - assert_eq!(output, format!("124412140710{separator}1.23456789012345{separator}1.24E+11\r\n")); + assert_eq!( + output, + format!( + "124412140710{s}1.23456789012345{s}1.24E+11{s}1234567890123456{s}-9007199254740991{s}1.23456789012346E+16{s}1E+15\r\n", + s = separator + ) + ); } } /// A number shown as General is written as `&` converts it (15 significant digits), whatever /// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell - /// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive. + /// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive + /// (integers below 2^53 keep all their digits; see the test above). #[test] fn delimited_exports_write_general_numbers_as_text_converts_them() { use gridcraft_core::Value; diff --git a/crates/numfmt/src/lib.rs b/crates/numfmt/src/lib.rs index 22f2880660..b43b8d8881 100644 --- a/crates/numfmt/src/lib.rs +++ b/crates/numfmt/src/lib.rs @@ -256,11 +256,19 @@ impl NumberFormat { } /// Formats a number. The flag is true when the value cannot be shown (date out of range). - /// With `full`, General is not narrowed to the cell width: it reads as `&` turns the number - /// into text (15 significant digits). + /// With `full`, General is not narrowed to the cell width: an integer f64 holds exactly + /// (|n| < 2^53) is written with all its digits, so 16-digit card and order numbers survive a + /// CSV round trip; any other number reads as `&` turns it into text (15 significant digits). fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) { + const EXACT_INT: f64 = 9_007_199_254_740_992.0; // 2^53 let general_text = |n: f64, width: usize| { - if full { Some(gridcraft_core::number_to_text(n)) } else { format_general_fit(n, width) } + if !full { + format_general_fit(n, width) + } else if n != 0.0 && n.fract() == 0.0 && n.abs() < EXACT_INT { + Some(format!("{}", n as i64)) + } else { + Some(gridcraft_core::number_to_text(n)) + } }; let general = |n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true }; diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7cefaac18a..5161309152 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -41,7 +41,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Notes | |---|---|---|---|---| -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it to 15 significant digits, as `&` converts it (`124412140710`, `0.333333333333333`), so part codes survive a round trip. The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes an integer below 2^53 (which f64 holds exactly) with all its digits (`124412140710`, `1234567890123456`), so part, card and order numbers survive a round trip, and any other number to 15 significant digits, as `&` converts it (`0.333333333333333`, `1.23456789012346E+16`). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | | `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes (displayed values, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.dif`, `.slk` (SYLK) | R/W | no | no | Small, legacy | @@ -83,7 +83,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-10-13 | minor | CSV/text export writes General numbers as `&` converts them (15 significant digits: `0.3`, not `0.30000000000000004`) also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display | +| 2026-10-13 | minor | CSV/text export writes General numbers as `&` converts them (15 significant digits: `0.3`, not `0.30000000000000004`; integers below 2^53 keep every digit) also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | From 6ff543ce764a977e4e4ee6a229df4b6bf9b706b2 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 12:59:37 -0400 Subject: [PATCH 010/201] Values: number text switches to scientific past 21 characters below 1, as Excel Excel caches IMCSCH("13+5j") as 1.28233995888454E-06 and IMSECH("7+25j")'s imaginary part as 0.000241377759972715: below 1, a 15-digit decimal longer than 21 characters is written in scientific notation. 9.99999999999999E-9&"" now gives 9.99999999999999E-09, not 0.00000000999999999999999. Affects every number-to-text conversion (&, CONCAT, TEXTJOIN, IM functions, formula printing, labels). --- crates/calc/src/tests.rs | 18 ++++++++++++ crates/core/src/value.rs | 43 ++++++++++++++++++++++++++--- crates/functions/src/engineering.rs | 5 ++++ docs/function-parity.md | 3 +- 4 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..4f64e626ee 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -274,6 +274,24 @@ fn iterative_calculation_of_text_and_errors() { assert_eq!(t.get("B1"), Value::Error(CellError::Div0)); } +/// `&`, CONCAT and TEXTJOIN turn a number into at most 15 significant digits, decimal unless that +/// would need 16 integer digits or more than 21 characters below 1. +#[test] +fn text_joins_convert_numbers_to_15_significant_digits() { + let mut t = T::new(); + for (formula, text) in [ + ("=(1E15-0.5)&\"\"", "1E+15"), + ("=(999999999999999)&\"\"", "999999999999999"), + ("=1234567890123456&\"\"", "1.23456789012346E+15"), + ("=(9.99999999999999E-9)&\"\"", "9.99999999999999E-09"), + ("=CONCAT(1/3*1E-5)", "3.33333333333333E-06"), + ("=TEXTJOIN(\",\",TRUE,1/3*1E-4,0.1+0.2)", "0.0000333333333333333,0.3"), + ] { + t.set("A1", formula); + assert_eq!(t.get("A1"), Value::from(text), "{formula}"); + } +} + #[test] fn circular_references_without_iterative_calculation() { let mut t = T::new(); diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index 42f7912fb5..a84bdda614 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -349,8 +349,10 @@ pub fn sort_compare(a: &Value, b: &Value) -> Ordering { } } -/// Number → text the way Excel converts in `&` and `TEXT(x,"General")`-free contexts: up to 15 -/// significant digits, scientific for very large or very small magnitudes. +/// Number → text the way Excel converts in `&`, CONCAT and TEXTJOIN: at most 15 significant +/// digits, rounded first; scientific from 1E+15, below 1E-9, and wherever the decimal would be +/// longer than 21 characters (`0.` plus 19 decimals: `0.0000692361330972509` stays decimal, +/// `1.28233995888454E-06` does not, as Excel caches them). pub fn number_to_text(n: f64) -> String { if n == 0.0 || !n.is_finite() { return "0".into(); @@ -358,8 +360,12 @@ pub fn number_to_text(n: f64) -> String { // Round to 15 significant digits first, then pick decimal or scientific from the rounded // magnitude, so 999999999999999.5 reads `1E+15`, never a 16-digit integer. let sci = format!("{:.14e}", n); - let mag: i32 = sci.split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0); - if !(-9..15).contains(&mag) { + let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0")); + let mag: i32 = exp.parse().unwrap_or(0); + let sig = mant.bytes().filter(u8::is_ascii_digit).count() - mant.bytes().rev().take_while(|&b| b == b'0').count(); + // Characters after `0.` for |n| < 1: the leading zeros, then the significant digits. + let decimals_below_one = -mag - 1 + sig as i32; + if !(-9..15).contains(&mag) || decimals_below_one > 19 { return sci_text(n, 15); } // 15 significant digits, trailing zeros trimmed. @@ -410,6 +416,35 @@ mod tests { assert_eq!(number_to_text(1.0 / 3.0), "0.333333333333333"); } + /// Excel switches to scientific when the 15-digit decimal would be longer than 21 characters + /// (`0.` plus 19 decimals). Excel-verified: IMTAN, IMSECH, IMCSCH and IMEXP results cached by + /// Excel for Mac in the `formulas` project's test.xlsx (ENGINEERING!S53, R47, S37, V37, V39). + #[test] + fn number_text_small_magnitudes() { + assert_eq!(number_to_text(6.92361330972509e-5), "0.0000692361330972509"); + assert_eq!(number_to_text(2.41377759972715e-4), "0.000241377759972715"); + assert_eq!(number_to_text(1.28233995888454e-6), "1.28233995888454E-06"); + assert_eq!(number_to_text(-4.48088972789593e-6), "-4.48088972789593E-06"); + assert_eq!(number_to_text(5.98317105631764e-7), "5.98317105631764E-07"); + assert_eq!(number_to_text(-2.99158552811404e-7), "-2.99158552811404E-07"); + // Just below powers of ten: the 21-character limit, and the rounded magnitude. + assert_eq!(number_to_text(9.99999999999999e-5), "0.0000999999999999999"); + assert_eq!(number_to_text(9.99999999999999e-6), "9.99999999999999E-06"); + assert_eq!(number_to_text(9.9999999999999e-6), "0.0000099999999999999"); + assert_eq!(number_to_text(9.99999999999999e-9), "9.99999999999999E-09"); + assert_eq!(number_to_text(-9.99999999999999e-9), "-9.99999999999999E-09"); + assert_eq!(number_to_text(9.99999999999999e-10), "9.99999999999999E-10"); + assert_eq!(number_to_text(9.999999999999999e-6), "0.00001"); + assert_eq!(number_to_text(0.00001), "0.00001"); + assert_eq!(number_to_text(0.000001), "0.000001"); + assert_eq!(number_to_text(1.5e-9), "0.0000000015"); + // Large side: 15 significant digits, scientific from 1E+15. + assert_eq!(number_to_text(99999999999999.9), "99999999999999.9"); + assert_eq!(number_to_text(999999999999999.4), "999999999999999"); + assert_eq!(number_to_text(9999999999999998.0), "1E+16"); + assert_eq!(number_to_text(9.99999999999999e15), "9.99999999999999E+15"); + } + #[test] fn coercion() { assert_eq!(Value::from("12").to_number(), Ok(12.0)); diff --git a/crates/functions/src/engineering.rs b/crates/functions/src/engineering.rs index f34ce99f01..42e9c2f04f 100644 --- a/crates/functions/src/engineering.rs +++ b/crates/functions/src/engineering.rs @@ -1283,6 +1283,11 @@ mod tests { cx(ev("IMCSC", vec![t("4+3i")]), -0.075_489_832_915_863_7, 0.064_877_471_370_635_5); is_text(ev("IMSECH", vec![t("0")]), "1"); is_err(ev("IMCSCH", vec![t("0")]), CellError::Num); + // Excel-cached results (Excel for Mac, `formulas` project test.xlsx, ENGINEERING sheet): a + // part needing more than 21 characters as a decimal is written in scientific notation. + is_text(ev("IMCSCH", vec![t("13+5j")]), "1.28233995888454E-06+4.33496947416312E-06j"); + is_text(ev("IMEXP", vec![t("-13+25j")]), "2.24044486393732E-06-2.99158552811404E-07j"); + is_text(ev("IMSECH", vec![t("7+25j")]), "0.00180771853884451+0.000241377759972715j"); // sech z · cosh z = 1 let Value::Text(c) = ev("IMCOSH", vec![t("4+3i")]) else { panic!() }; let Value::Text(sc) = ev("IMSECH", vec![t("4+3i")]) else { panic!() }; diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..b0bd968ed9 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (number-to-text in `&`, CONCAT, TEXTJOIN and the IM functions rounds to 15 digits first and switches to scientific like Excel) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -108,6 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters, as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, `9.99999999999999E-09` (was `0.00000000999999999999999`), but `0.0000692361330972509` | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From bf9b3cb9b14be0498d8fc0b563167b6909ca5b88 Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 12:59:37 -0400 Subject: [PATCH 011/201] CSV/text export: integers below 1e16 keep every digit; no exponents The 2^53 cutoff turned exact 16-digit integers (9007199254740992, 9007199254740994) into 9.00719925474099E+15. A General number is now written with &'s 15 digits but never with an exponent: reopening a CSV gives a scientific number a 0.00E+00 format that rounds it on the next save. 1E+15 and up are written as the shortest round-trip digits (every integer below 1e16 exactly, main's output above), small numbers as their 15 digits in full. --- crates/engine/src/display.rs | 5 ++-- crates/engine/src/io.rs | 47 ++++++++++++++++++++++++------------ crates/numfmt/src/lib.rs | 36 +++++++++++++++------------ docs/file-format-parity.md | 6 ++--- 4 files changed, 59 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index 3e8d47c164..3b891caef0 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -94,8 +94,9 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { /// A cell's value with its number format applied, independent of column width: no `#####` /// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number -/// shown as General (also through a coloured or sectioned General, or a Text format) reads as `&` -/// turns it into text (`124412140710`, not `1.24412E+11`); Excel writes the cell display there. +/// shown as General (also through a coloured or sectioned General, or a Text format) is written +/// as [`format_value_full`] writes it: `&`'s 15 significant digits without an exponent, an integer +/// below 1e16 with every digit (`124412140710`, not `1.24412E+11`). Excel writes the cell display. pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { let style = wb.styles.get(sheet.style_id(c)); with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system)) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index 2b711f573b..b52c8cb903 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -231,8 +231,10 @@ pub fn source_dir(path: &str) -> Option { /// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all /// characters in each cell" (Microsoft Support, *Excel formatting and features that are not /// transferred to other file formats*): number formats applied, never column-width `#####`. -/// One intentional difference: a number shown as General is written as `&` converts it (15 -/// significant digits), not narrowed to the cell width, so long identifiers survive. +/// One intentional difference: a number shown as General is not narrowed to the cell width but +/// written as `&` converts it (15 significant digits) without an exponent, and an integer below +/// 1e16 with every digit, so long identifiers survive a reopen and save +/// (`gridcraft_numfmt::format_value_full`). fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string())) } @@ -695,27 +697,40 @@ mod tests { sheet.set_cell(CellRef::new(0, 0), Cell { value: Value::Number(124412140710.0), ..Default::default() }); sheet.set_cell(CellRef::new(0, 1), Cell { value: Value::Number(1.23456789012345), ..Default::default() }); sheet.set_cell(CellRef::new(0, 2), Cell { value: Value::Number(124412140710.0), style: scientific, ..Default::default() }); - // Integers f64 holds exactly (below 2^53) keep every digit; larger integers and - // non-integers get the 15 significant digits `&` gives. - for (col, n) in [(3, 1234567890123456.0), (4, -9007199254740991.0), (5, 12345678901234567.0), (6, 1e15 - 0.5)] { - sheet.set_cell(CellRef::new(0, col), Cell { value: Value::Number(n), ..Default::default() }); + // Every integer below 1e16 that f64 holds (also 2^53 and the even integers above it) keeps + // every digit; larger numbers keep the shortest digits that read back as the same value, + // and a number `&` would write with an exponent is written out in full, so reopening the + // file can't give it a scientific format that then rounds it on the next save. + let cells = [ + (1234567890123456.0, "1234567890123456"), + (-9007199254740991.0, "-9007199254740991"), + (9007199254740992.0, "9007199254740992"), + (9007199254740994.0, "9007199254740994"), + (9123456789012346.0, "9123456789012346"), + (-9999999999999998.0, "-9999999999999998"), + (12345678901234567.0, "12345678901234568"), + (1e20, "100000000000000000000"), + (1e15 - 0.5, "999999999999999.5"), + (1.0 / 3.0 * 1e-6, "0.000000333333333333333"), + (1.23456789012346e-10, "0.000000000123456789012346"), + ]; + for (col, (n, _)) in cells.iter().enumerate() { + sheet.set_cell(CellRef::new(0, col as u32 + 3), Cell { value: Value::Number(*n), ..Default::default() }); } for (path, separator) in [("data.csv", ","), ("data.tsv", "\t")] { let output = String::from_utf8(save_bytes(&workbook, path).unwrap()).unwrap(); - assert_eq!( - output, - format!( - "124412140710{s}1.23456789012345{s}1.24E+11{s}1234567890123456{s}-9007199254740991{s}1.23456789012346E+16{s}1E+15\r\n", - s = separator - ) - ); + let tail: Vec<&str> = cells.iter().map(|(_, text)| *text).collect(); + assert_eq!(output, format!("124412140710{s}1.23456789012345{s}1.24E+11{s}{}\r\n", tail.join(separator), s = separator)); + // Reopening the file and saving it again changes nothing. + let (reopened, _) = open_bytes(path, output.as_bytes()).unwrap(); + assert_eq!(String::from_utf8(save_bytes(&reopened, path).unwrap()).unwrap(), output); } } /// A number shown as General is written as `&` converts it (15 significant digits), whatever /// colour, sections or literals the format adds, and in a Text cell. Excel writes the cell /// display (`1.24412E+11`, `0.333333333`); GridCraft keeps the digits so part codes survive - /// (integers below 2^53 keep all their digits; see the test above). + /// (integers below 1e16 keep all their digits, and nothing gets an exponent; see the test above). #[test] fn delimited_exports_write_general_numbers_as_text_converts_them() { use gridcraft_core::Value; @@ -731,6 +746,7 @@ mod tests { (Value::Number(0.1 + 0.2), StyleId::DEFAULT), (Value::Number(1e20), StyleId::DEFAULT), (Value::Number(code), blue), + (Value::Number(9007199254740994.0), blue), (Value::Number(-1.0 / 3.0), blue), (Value::Number(-code), signed), (Value::Number(-code), red), @@ -745,8 +761,9 @@ mod tests { let expected = [ "0.333333333333333", "0.3", - "1E+20", + "100000000000000000000", "124412140710", + "9007199254740994", "-0.333333333333333", "-124412140710", "-124412140710", diff --git a/crates/numfmt/src/lib.rs b/crates/numfmt/src/lib.rs index b43b8d8881..583b5aa142 100644 --- a/crates/numfmt/src/lib.rs +++ b/crates/numfmt/src/lib.rs @@ -256,20 +256,9 @@ impl NumberFormat { } /// Formats a number. The flag is true when the value cannot be shown (date out of range). - /// With `full`, General is not narrowed to the cell width: an integer f64 holds exactly - /// (|n| < 2^53) is written with all its digits, so 16-digit card and order numbers survive a - /// CSV round trip; any other number reads as `&` turns it into text (15 significant digits). + /// With `full`, General is not narrowed to the cell width but written by [`general_full`]. fn format_number(&self, n: f64, sys: DateSystem, full: bool) -> (Formatted, bool) { - const EXACT_INT: f64 = 9_007_199_254_740_992.0; // 2^53 - let general_text = |n: f64, width: usize| { - if !full { - format_general_fit(n, width) - } else if n != 0.0 && n.fract() == 0.0 && n.abs() < EXACT_INT { - Some(format!("{}", n as i64)) - } else { - Some(gridcraft_core::number_to_text(n)) - } - }; + let general_text = |n: f64, width: usize| if full { Some(general_full(n)) } else { format_general_fit(n, width) }; let general = |n: f64| Formatted { text: general_text(n, GENERAL_WIDTH).unwrap_or_else(|| OVERFLOW.into()), color: None, fill: None, numeric: true }; if self.is_general() { @@ -321,12 +310,29 @@ pub fn format_value(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted /// Formats a cell value as Save As CSV/Text writes it: like [`format_value`], except that a number /// shown as General (a General or Text section, with or without colour and literals) is not -/// narrowed to the cell width but written as `&` turns it into text: `124412140710`, not -/// `1.24412E+11`. Excel writes the cell display here; GridCraft keeps the digits. +/// narrowed to the cell width but written by `general_full`: `124412140710`, not `1.24412E+11`. +/// Excel writes the cell display here; GridCraft keeps the digits. pub fn format_value_full(v: &Value, fmt: &NumberFormat, sys: DateSystem) -> Formatted { format_value_with(v, fmt, sys, true) } +/// General for Save As CSV/Text: the text `&` gives (15 significant digits), but never with an +/// exponent, because reopening the file would give the cell a scientific format that rounds it +/// on the next save. Where `&` writes an exponent, a number of 1 or more is written as the +/// shortest digits that read back as the same value (every integer f64 holds below 1e16 exactly, +/// so 16-digit card numbers survive), and a smaller one as its 15 significant digits in full. +fn general_full(n: f64) -> String { + let text = gridcraft_core::number_to_text(n); + if !text.contains('E') { + text + } else if n.abs() >= 1.0 { + format!("{n}") + } else { + let mag: i32 = format!("{n:.14e}").split_once('e').and_then(|(_, e)| e.parse().ok()).unwrap_or(0); + gridcraft_core::value::trim_decimal(&format!("{:.*}", (14 - mag).max(0) as usize, n)) + } +} + fn format_value_with(v: &Value, fmt: &NumberFormat, sys: DateSystem, full: bool) -> Formatted { match v { Value::Empty => Formatted::default(), diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5161309152..e8d4fde4a2 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (CSV/text export writes every General number as `&` converts it) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (CSV/text export writes every General number with `&`'s 15 digits, never an exponent; integers below 1e16 keep every digit) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -41,7 +41,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Notes | |---|---|---|---|---| -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes an integer below 2^53 (which f64 holds exactly) with all its digits (`124412140710`, `1234567890123456`), so part, card and order numbers survive a round trip, and any other number to 15 significant digits, as `&` converts it (`0.333333333333333`, `1.23456789012346E+16`). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV opened and saved again is unchanged. The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | | `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes (displayed values, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.dif`, `.slk` (SYLK) | R/W | no | no | Small, legacy | @@ -83,7 +83,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | Date | Change | Summary | |---|---|---| -| 2026-10-13 | minor | CSV/text export writes General numbers as `&` converts them (15 significant digits: `0.3`, not `0.30000000000000004`; integers below 2^53 keep every digit) also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display | +| 2026-10-14 | minor | CSV/text export writes General numbers with the 15 significant digits `&` gives (`0.3`, not `0.30000000000000004`) but never an exponent (integers below 1e16 keep every digit; 1E+15 and up as the shortest round-trip digits; small numbers written out), also through coloured or sectioned General and Text formats (`[Blue]General` still wrote `1.24412E+11`). Duplicate CSV/text rows merged. Intentional difference from Excel, which writes the cell display. The underlying `&` conversion changed too (see [function-parity.md](function-parity.md)) | | 2026-10-12 | trivial | XLSX chart sheets are kept on save (#727) | | 2026-10-12 | trivial | CSV and TSV export is capped at 512 MiB and refuses a larger used range with an error (#528) | | 2026-10-12 | minor | `.xls` import reads the calculation settings (CalcMode, CalcIter, CalcCount, CalcDelta, CalcPrecision), so circular models calculate instead of showing `#CIRC!` (#724) | From 9cbbaaeaed651824222e4a9f053cfb17e0c603dd Mon Sep 17 00:00:00 2001 From: Local contributor Date: Wed, 14 Oct 2026 13:51:54 -0400 Subject: [PATCH 012/201] Docs: CSV export wording matches the code; inferred & boundaries marked From 1E+15, CSV export writes the shortest round-trip digits, not &'s 15 digits. 'Every digit' now applies only to integers below 1e16. The open/save round-trip claim is narrowed to files GridCraft wrote. The doc now lists what a foreign CSV loses on its first save: 16-17-digit decimals are cut to 15 digits, and scientific input is rounded to its 0.00E+00 format. The 21-character switch is Excel-verified only for positive 15-digit mantissas. Shorter mantissas from 1E-6 to 1E-9 and negatives are marked as inferred, and the doc states the sign isn't counted. The function-parity 'was' value is corrected to main's 0.00000001. --- crates/core/src/value.rs | 7 +++++-- crates/engine/src/display.rs | 5 +++-- crates/engine/src/io.rs | 9 +++++---- docs/file-format-parity.md | 4 ++-- docs/function-parity.md | 2 +- 5 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index a84bdda614..ef4b910f9a 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -351,8 +351,11 @@ pub fn sort_compare(a: &Value, b: &Value) -> Ordering { /// Number → text the way Excel converts in `&`, CONCAT and TEXTJOIN: at most 15 significant /// digits, rounded first; scientific from 1E+15, below 1E-9, and wherever the decimal would be -/// longer than 21 characters (`0.` plus 19 decimals: `0.0000692361330972509` stays decimal, -/// `1.28233995888454E-06` does not, as Excel caches them). +/// longer than 21 characters, not counting the sign (`0.` plus 19 decimals). Excel-verified only +/// for positive 15-digit mantissas: `0.0000692361330972509` stays decimal and +/// `1.28233995888454E-06` does not, as Excel caches them. The limit for shorter mantissas from +/// 1E-6 to 1E-9 (e.g. `0.0000099999999999999` decimal) and for negatives (sign excluded) are +/// inferred. pub fn number_to_text(n: f64) -> String { if n == 0.0 || !n.is_finite() { return "0".into(); diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index 3b891caef0..e0af7b3004 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -95,8 +95,9 @@ pub fn cell_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { /// A cell's value with its number format applied, independent of column width: no `#####` /// and no General narrowing (Save As CSV/Text writes this). Formulas give their result. A number /// shown as General (also through a coloured or sectioned General, or a Text format) is written -/// as [`format_value_full`] writes it: `&`'s 15 significant digits without an exponent, an integer -/// below 1e16 with every digit (`124412140710`, not `1.24412E+11`). Excel writes the cell display. +/// as [`format_value_full`] writes it, never with an exponent: `&`'s 15 significant digits below +/// 1E+15 (`124412140710`, not `1.24412E+11`), the shortest round-trip digits from 1E+15 (every +/// integer below 1e16 exactly). Excel writes the cell display. pub fn value_text(wb: &Workbook, sheet: &Sheet, c: CellRef) -> String { let style = wb.styles.get(sheet.style_id(c)); with_fill_space(format_value_full(&sheet.value(c), &parsed(style.num_fmt.as_str()), wb.date_system)) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index b52c8cb903..ee2054e9a7 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -231,10 +231,11 @@ pub fn source_dir(path: &str) -> Option { /// Save As CSV/Text writes "the text and values as they are displayed in cells" with "all /// characters in each cell" (Microsoft Support, *Excel formatting and features that are not /// transferred to other file formats*): number formats applied, never column-width `#####`. -/// One intentional difference: a number shown as General is not narrowed to the cell width but -/// written as `&` converts it (15 significant digits) without an exponent, and an integer below -/// 1e16 with every digit, so long identifiers survive a reopen and save -/// (`gridcraft_numfmt::format_value_full`). +/// One intentional difference: a number shown as General is not narrowed to the cell width and +/// never gets an exponent (`gridcraft_numfmt::format_value_full`). Below 1E+15 it is written as +/// `&` converts it (15 significant digits); from 1E+15 as the shortest digits that read back as +/// the same value (every integer below 1e16 exactly, so long identifiers survive); small numbers +/// that `&` writes in scientific notation as their 15 digits in full. fn csv(wb: &Workbook, sh: &Sheet, delimiter: u8) -> Result> { gridcraft_xlsx::write_csv(sh, delimiter, |c| crate::display::value_text(wb, sh, c)).map_err(|e| EngineError::Other(e.to_string())) } diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index e8d4fde4a2..4167c02bf6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (CSV/text export writes every General number with `&`'s 15 digits, never an exponent; integers below 1e16 keep every digit) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (CSV/text export writes General numbers without an exponent: `&`'s 15 digits below 1E+15, the shortest round-trip digits from 1E+15, so integers below 1e16 keep every digit) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Every format Excel opens or saves, with GridCraft's read and write support, fidelity and tests. Part of [target-app-parity.md](target-app-parity.md). **File formats: ~50% ready, 80–120 h** @@ -41,7 +41,7 @@ and repair-free opening remain unverified. | Format | Excel | GridCraft read | GridCraft write | Notes | |---|---|---|---|---| -| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV opened and saved again is unchanged. The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | +| `.csv` UTF-8 / Windows / Mac / MS-DOS | R/W | yes (UTF-8 and UTF-16 BOMs, UTF-8, Windows-1252 fallback; delimiter detection) | yes (UTF-8 without BOM, CRLF; a file opened as CSV is saved with the separator it was read with, so a `;` file stays `;`; otherwise `,`) | Formatted numbers and formula results are written as displayed, as in Excel (never column-width `#####`). **Intentional difference:** Excel writes a General number as the cell displays it (`1.24412E+11`, `0.333333333`); GridCraft writes it with the 15 significant digits `&` gives (`0.333333333333333`, `0.3`, not `0.30000000000000004`) but never with an exponent, since reopening the file would give the cell a scientific format that rounds it on the next save: a number of 1E+15 or more is written as the shortest digits that read back as the same value (every integer below 1e16 exactly, so 16-digit card and order numbers survive: `9007199254740993` is stored and written as `9007199254740992`, `12345678901234567` as `12345678901234568`), a small one as its 15 digits in full (`0.00000128233995888454`). A CSV GridCraft wrote, opened and saved again, is unchanged. A CSV from elsewhere can change on its first save: a decimal with 16 or 17 significant digits is cut to 15, as in Excel (`3.141592653589793` → `3.14159265358979`), and a number typed in scientific notation gets the `0.00E+00` format on open and is saved rounded to it (`1.23456789012346E-10` → `1.23E-10`, unchanged from before). The same applies to a coloured or sectioned General (`[Blue]General`, `General;[Red]-General`) and to a number in a Text (`@`) cell. No encoding choice on save. Re-import of a single-column export splits text (#127). A used range that would write more than 512 MiB (two far-apart cells span the whole rectangle) is refused with an error instead of being expanded (#528). | | `.txt` tab-delimited, Unicode text | R/W | yes (`.txt`, `.tsv`, `.tab`) | yes (displayed values, with General numbers as for `.csv`) | Text Import Wizard options partly via Text to Columns | | `.prn` formatted text (space-delimited) | R/W | no | no | | | `.dif`, `.slk` (SYLK) | R/W | no | no | Small, legacy | diff --git a/docs/function-parity.md b/docs/function-parity.md index b0bd968ed9..ce3dcaffbc 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -108,7 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| -| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters, as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, `9.99999999999999E-09` (was `0.00000000999999999999999`), but `0.0000692361330972509` | +| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From 921405fa02a60ef883412a0eb630ea19ddf54d57 Mon Sep 17 00:00:00 2001 From: Harrison Booth Date: Wed, 14 Oct 2026 21:18:25 -0500 Subject: [PATCH 013/201] SORT, SORTBY and Data > Sort order numbers exactly, like Excel sort_compare compared numbers at 15 significant digits, so 0.3 and =0.1+0.2 (0.30000000000000004) tied and kept their input order. Excel 365 orders them exactly in SORT, SORTBY, Data > Sort, the AutoFilter sort and table sort: 0.3 first ascending, last descending, in either input order. Numbers now compare with partial_cmp in sort_compare (0 and -0 still tie). = and COUNTIF keep their 15-digit comparison; UNIQUE, RANK, LARGE, SMALL and MODE were already exact, as observed. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 4 ++- crates/calc/src/tests.rs | 59 +++++++++++++++++++++++++++++++++ crates/core/src/value.rs | 17 ++++++++++ crates/engine/src/tests.rs | 21 ++++++++++++ crates/functions/src/dynamic.rs | 15 +++++++++ docs/function-parity.md | 3 +- 6 files changed, 117 insertions(+), 2 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..357f1bf8d5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (rows auto-fit oversized fonts on open and whole-row/column formatting) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (SORT, SORTBY and Data > Sort order numbers exactly, like Excel) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-14 | SORT, SORTBY and Data > Sort (with the AutoFilter and table sorts) order numbers exactly like Excel, so 0.3 sorts before `=0.1+0.2` whatever the input order; `=` and COUNTIF keep their 15-digit comparison | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | @@ -193,6 +194,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | Progress log: sorts order numbers exactly | | 2026-10-12 | minor | Rows auto-fit oversized fonts on open and whole-row/column formatting (#833); progress log row | | 2026-10-12 | minor | Progress log: multi-area row/column delete (#758) | | 2026-10-12 | trivial | Progress log: XLSX chart sheets kept on save (#727) | diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..ff13374fc8 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -1266,3 +1266,62 @@ fn offset_extreme_arguments_return_ref() { assert_eq!(crate::evaluate(&wb, 0, c("D1"), formula), Value::Number(expected), "{formula}"); } } + +/// Sorting and ranking compare numbers exactly while `=` and COUNTIF compare them at 15 +/// significant digits. Every expectation was observed in Excel 365 with these fixtures +/// (`=0.1+0.2` is 0.30000000000000004): 0.3 sorts first whatever the input order. +#[test] +fn sorts_and_ranks_compare_numbers_exactly() { + let mut t = T::new(); + for (at, input) in [ + // The noisy value first, then the exact one first. + ("A1", "=0.1+0.2"), + ("B1", "e"), + ("A2", "0.3"), + ("B2", "t"), + ("D1", "0.3"), + ("E1", "t"), + ("D2", "=0.1+0.2"), + ("E2", "e"), + ("G1", "=100+1E-14"), + ("H1", "e"), + ("G2", "100"), + ("H2", "t"), + ] { + t.set(at, input); + } + let e = 0.1 + 0.2; + let n = Value::Number; + let s = |x: &str| Value::from(x); + let cases: Vec<(&str, Value)> = vec![ + ("=A1=A2", Value::Bool(true)), + ("=COUNTIF(A1:A2,0.3)", n(2.0)), + ("=INDEX(SORT(A1:B2),1,2)", s("t")), + ("=INDEX(SORT(D1:E2),1,2)", s("t")), + ("=INDEX(SORT(A1:B2,1,-1),1,2)", s("e")), + ("=INDEX(SORT(D1:E2,1,-1),1,2)", s("e")), + ("=INDEX(SORT(G1:H2),1,2)", s("t")), + ("=INDEX(SORT(G1:H2,1,-1),1,2)", s("e")), + ("=INDEX(SORTBY(B1:B2,A1:A2),1,1)", s("t")), + ("=INDEX(SORTBY(E1:E2,D1:D2),1,1)", s("t")), + ("=INDEX(SORTBY(B1:B2,A1:A2,-1),1,1)", s("e")), + ("=INDEX(SORTBY(E1:E2,D1:D2,-1),1,1)", s("e")), + // Already exact: UNIQUE, RANK, LARGE/SMALL, MODE. + ("=ROWS(UNIQUE(A1:A2))", n(2.0)), + ("=RANK.EQ(0.3,A1:A2)", n(2.0)), + ("=RANK.EQ(0.3,A1:A2,1)", n(1.0)), + ("=RANK.AVG(0.3,A1:A2)", n(2.0)), + ("=RANK.EQ(0.3,A1)", Value::Error(CellError::NA)), + ("=LARGE(A1:A2,1)", n(e)), + ("=SMALL(A1:A2,1)", n(0.3)), + ("=MODE.SNGL(A1:A2,5)", Value::Error(CellError::NA)), + ]; + let mut wrong = Vec::new(); + for (formula, expected) in cases { + let got = crate::evaluate(&t.wb, 0, c("Z1"), formula); + if got != expected { + wrong.push(format!("{formula}: got {got:?}, Excel {expected:?}")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} diff --git a/crates/core/src/value.rs b/crates/core/src/value.rs index cfef7ac57d..70c05036e2 100644 --- a/crates/core/src/value.rs +++ b/crates/core/src/value.rs @@ -339,12 +339,16 @@ pub fn compare_text(a: &str, b: &str) -> Ordering { } /// Sorting order used by Sort (ascending): numbers, text, booleans, errors, then blanks last. +/// Numbers compare exactly, not at the 15 digits of [`compare`]. Observed in Excel 365: SORT, +/// SORTBY, Data > Sort, the AutoFilter sort and table sort all put 0.3 before `=0.1+0.2` +/// (0.30000000000000004) ascending and after it descending, whatever the input order. pub fn sort_compare(a: &Value, b: &Value) -> Ordering { match (a, b) { (Value::Empty, Value::Empty) => Ordering::Equal, (Value::Empty, _) => Ordering::Greater, (_, Value::Empty) => Ordering::Less, (Value::Error(_), Value::Error(_)) => Ordering::Equal, + (Value::Number(x), Value::Number(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal), _ => compare(a, b), } } @@ -442,6 +446,19 @@ mod tests { assert_eq!(compare(&num(1.0), &num(2.0)), Ordering::Less); } + #[test] + fn sort_orders_numbers_exactly() { + let num = Value::Number; + let e = 0.1 + 0.2; + assert_eq!(sort_compare(&num(0.3), &num(e)), Ordering::Less); + assert_eq!(sort_compare(&num(e), &num(0.3)), Ordering::Greater); + assert_eq!(sort_compare(&num(100.0), &num(100.0 + 1e-14)), Ordering::Less); + assert_eq!(sort_compare(&num(0.0), &num(-0.0)), Ordering::Equal); + assert_eq!(sort_compare(&num(1.0), &Value::from("a")), Ordering::Less); + // `=` keeps its 15-digit comparison. + assert_eq!(compare(&num(0.3), &num(e)), Ordering::Equal); + } + #[test] fn arrays() { let a = Array::new(2, 2, vec![1.0.into(), 2.0.into(), 3.0.into(), 4.0.into()]).unwrap(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae499a1895..ee21430fd7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1027,6 +1027,27 @@ fn case_sensitive_sort_puts_lowercase_first() { assert_eq!(col, ["a", "A", "aB", "Ab", "b", "B"].map(Value::from)); } +/// Data > Sort orders numbers exactly, like Excel 365: 0.3 sorts before `=0.1+0.2` +/// (0.30000000000000004) ascending and after it descending, whatever the input order. +#[test] +fn sort_orders_numbers_exactly() { + for first_noisy in [true, false] { + let mut s = s(); + let (a1, a2, b1, b2) = if first_noisy { ("=0.1+0.2", "0.3", "e", "t") } else { ("0.3", "=0.1+0.2", "t", "e") }; + for (cell, input) in [("A1", a1), ("A2", a2), ("B1", b1), ("B2", b2)] { + s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + let labels = |s: &Session| [v(s, "B1"), v(s, "B2")]; + s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A"}]})).unwrap(); + assert_eq!(labels(&s), ["t", "e"].map(Value::from), "ascending, noisy first: {first_noisy}"); + s.execute("data.sort", json!({"range": "A1:B2", "header": false, "keys": [{"column": "A", "order": "desc"}]})).unwrap(); + assert_eq!(labels(&s), ["e", "t"].map(Value::from), "descending, noisy first: {first_noisy}"); + s.execute("selection.set", json!({"range": "A1:B2"})).unwrap(); + s.execute("data.sortAscending", json!({"range": "A1:B2", "column": "A"})).unwrap(); + assert_eq!(labels(&s), ["t", "e"].map(Value::from), "quick sort, noisy first: {first_noisy}"); + } +} + #[test] fn remove_duplicates_compares_shown_text() { let mut s = s(); diff --git a/crates/functions/src/dynamic.rs b/crates/functions/src/dynamic.rs index 2e29b416ca..d983bc2d33 100644 --- a/crates/functions/src/dynamic.rs +++ b/crates/functions/src/dynamic.rs @@ -1102,6 +1102,21 @@ mod tests { is_err(ev("SORTBY", vec![av(col(&[1.0, 2.0])), av(col(&[1.0, 2.0])), n(0.0)]), CellError::Value); } + /// SORT and SORTBY order numbers exactly, not at 15 digits (observed in Excel 365). + #[test] + fn sort_orders_numbers_exactly() { + for (t, e) in [(0.3, 0.1 + 0.2), (100.0, 100.0 + 1e-14), (3.3, 1.1 * 3.0)] { + for input in [[e, t], [t, e]] { + let asc = vec![vec![nv(t)], vec![nv(e)]]; + let desc = vec![vec![nv(e)], vec![nv(t)]]; + assert_eq!(rows_of(&ev("SORT", vec![av(col(&input))])), asc); + assert_eq!(rows_of(&ev("SORT", vec![av(col(&input)), n(1.0), n(-1.0)])), desc); + assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input))])), asc); + assert_eq!(rows_of(&ev("SORTBY", vec![av(col(&input)), av(col(&input)), n(-1.0)])), desc); + } + } + } + #[test] fn unique() { let v = arr(vec![vec![tv("a")], vec![tv("B")], vec![tv("A")], vec![tv("c")], vec![tv("b")]]); diff --git a/docs/function-parity.md b/docs/function-parity.md index 760ffd6ac3..e35ef547f7 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -1,6 +1,6 @@ # Function parity: worksheet functions and formulas -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (USDOLLAR added as a compatibility function; MIRR, COUNTIF and INDIRECT edge cases match Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-14 · **Change:** minor (SORT and SORTBY order numbers exactly, like Excel 365) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Excel's worksheet functions, category by category, against GridCraft's function library. Part of [target-app-parity.md](target-app-parity.md); gaps feed [gaps.md](gaps.md). @@ -108,6 +108,7 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | Date | Change | Summary | |---|---|---| +| 2026-10-14 | minor | SORT, SORTBY and Data > Sort (including the AutoFilter and table sorts) order numbers exactly, as Excel 365 does: 0.3 sorts before `=0.1+0.2` (0.30000000000000004) ascending and after it descending, in either input order. UNIQUE, RANK / RANK.EQ / RANK.AVG, LARGE, SMALL and MODE were already exact, also as observed; `=` and COUNTIF keep comparing at 15 significant digits | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | | 2026-10-11 | minor | TEXT / number formats fixed against Excel-cached results: fraction literals and zero fractions, `0` denominators zero padded, `?` pads the thousands separator, booleans use the text section (226 mismatches → 0 in 352 TEXT cells) | | 2026-10-11 | minor | Iterative calculation: circular references iterate up to Maximum Iterations / Maximum Change when enabled | From ffe73b3bd76aad33c6197d20bce98f0708545c85 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Thu, 15 Oct 2026 10:49:49 -0300 Subject: [PATCH 014/201] UI: Brazilian Portuguese function help MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Português (Brasil) translates every worksheet function description (479) and argument name (283) in i18n/pt_functions.rs, so the argument hint, autocomplete and Insert Function read in Portuguese. The translation is clean-room (not Excel's text) and still needs a native review. --- ROADMAP.md | 1 + crates/ui-egui/src/formula_locale.rs | 5 + crates/ui-egui/src/i18n.rs | 2 + crates/ui-egui/src/i18n/pt_functions.rs | 1005 +++++++++++++++++++++++ docs/localization-parity.md | 11 +- 5 files changed, 1019 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/i18n/pt_functions.rs diff --git a/ROADMAP.md b/ROADMAP.md index 426cae12fb..c233dc724c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-15 | Function help in Brazilian Portuguese: every description and argument name (479 and 283) | | 2026-10-15 | Function help follows the interface language: argument hints, autocomplete, Insert Function (search and readable categories) and the Formulas-tab menus read per-language tables of descriptions and argument names; Spanish keeps its 10 functions in the new format | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 11b551b103..944dd118f7 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -172,6 +172,11 @@ mod tests { assert_eq!(sig("IF", En, Language::Es), "IF(prueba_lógica, [valor_si_verdadero], [valor_si_falso])"); assert_eq!(sig("SUM", En, Language::Es), "SUM(número1, [número2], ...)"); assert_eq!(description("IF", En, Language::Es).as_deref(), Some("Devuelve un valor según una condición.")); + // Portuguese help, including brackets that open and close on different arguments. + assert_eq!(sig("IF", En, Language::PtBr), "IF(teste_lógico, [valor_se_verdadeiro], [valor_se_falso])"); + assert_eq!(description("IF", En, Language::PtBr).as_deref(), Some("Retorna um valor quando uma condição é TRUE e outro quando é FALSE.")); + assert_eq!(sig("SWITCH", En, Language::PtBr), "SWITCH(expressão, valor1, resultado1, [padrão_ou_valor2, resultado2], ...)"); + assert_eq!(sig("LAMBDA", En, Language::PtBr), "LAMBDA([parâmetro1, ...], cálculo)"); // Spanish names and separators, from a localized name. assert_eq!(sig("suma", Es, Language::Es), "SUMA(número1; [número2]; ...)"); assert_eq!(description("SUMA", Es, Language::Es).as_deref(), Some("Suma los números.")); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 76a98a209c..33d89a6d0c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -16,6 +16,7 @@ mod es_functions; mod fr; mod ko; mod pt; +mod pt_functions; mod ru; mod sr; mod zh; @@ -150,6 +151,7 @@ impl Language { fn function_help(self) -> Option<(HelpTable, HelpTable)> { match self { Self::Es => Some((es_functions::DESCRIPTIONS, es_functions::ARGUMENTS)), + Self::PtBr => Some((pt_functions::DESCRIPTIONS, pt_functions::ARGUMENTS)), _ => None, } } diff --git a/crates/ui-egui/src/i18n/pt_functions.rs b/crates/ui-egui/src/i18n/pt_functions.rs new file mode 100644 index 0000000000..bd6b4700ce --- /dev/null +++ b/crates/ui-egui/src/i18n/pt_functions.rs @@ -0,0 +1,1005 @@ +//! Brazilian Portuguese help for the worksheet functions: descriptions and argument names, keyed +//! by the English text of the function catalog and sorted by it (lookups binary-search). Literal +//! formula tokens in descriptions (function names, TRUE/FALSE, error values) keep their canonical +//! spelling, which is how formulas are typed in this language. + +/// Function descriptions. +pub(super) const DESCRIPTIONS: &[(&str, &str)] = &[ + ("1 for positive, -1 for negative and 0 for zero.", "1 para positivo, -1 para negativo e 0 para zero."), + ("A random integer between two bounds, inclusive.", "Um inteiro aleatório entre dois limites, inclusive."), + ("A random number between 0 and 1, recalculated every time.", "Um número aleatório entre 0 e 1, recalculado a cada vez."), + ("A range or array without its blank outer rows and columns.", "Um intervalo ou matriz sem as linhas e colunas externas em branco."), + ("A reference shifted from a starting point.", "Uma referência deslocada a partir de um ponto inicial."), + ( + "A statistic of the FORECAST.ETS model: 1 alpha, 2 beta, 3 gamma, 4 MASE, 5 SMAPE, 6 MAE, 7 RMSE, 8 step size.", + "Uma estatística do modelo FORECAST.ETS: 1 alfa, 2 beta, 3 gama, 4 MASE, 5 SMAPE, 6 MAE, 7 RMSE, 8 tamanho do passo.", + ), + ("A subtotal that can skip hidden rows.", "Um subtotal que pode ignorar linhas ocultas."), + ("Absolute value (modulus) of a complex number.", "Valor absoluto (módulo) de um número complexo."), + ("Absolute value of a number.", "Valor absoluto de um número."), + ("Accrued interest of a security paying interest at maturity.", "Juros acumulados de um título que paga juros no vencimento."), + ("Accrued interest of a security paying periodic interest.", "Juros acumulados de um título que paga juros periódicos."), + ("Accumulates an array into one value.", "Acumula uma matriz em um único valor."), + ("Adds all the numbers in the arguments.", "Soma todos os números dos argumentos."), + ("Adds the cells that meet a condition.", "Soma as células que atendem a uma condição."), + ("Adds the cells that meet every condition.", "Soma as células que atendem a todas as condições."), + ("Adds the numbers in a field of the records that meet the criteria.", "Soma os números em um campo dos registros que atendem aos critérios."), + ("Adds the squares of the numbers.", "Soma os quadrados dos números."), + ("Amount received at maturity for a fully invested security.", "Valor recebido no vencimento de um título totalmente investido."), + ("An aggregate that can skip hidden rows and errors.", "Uma agregação que pode ignorar linhas ocultas e erros."), + ("Angle of a complex number in radians.", "Ângulo de um número complexo em radianos."), + ("Angle of the point (x, y) from the x-axis in radians.", "Ângulo do ponto (x, y) em relação ao eixo x, em radianos."), + ("Annual yield of a discounted security.", "Rendimento anual de um título com desconto."), + ("Annual yield of a security paying interest at maturity.", "Rendimento anual de um título que paga juros no vencimento."), + ("Applies a LAMBDA to each column.", "Aplica uma LAMBDA a cada coluna."), + ("Applies a LAMBDA to each row.", "Aplica uma LAMBDA a cada linha."), + ("Applies a LAMBDA to each value.", "Aplica uma LAMBDA a cada valor."), + ( + "Approximate lookup in a sorted vector or the first row/column of an array.", + "Pesquisa aproximada em um vetor classificado ou na primeira linha/coluna de uma matriz.", + ), + ("Arccosine in radians.", "Arco cosseno em radianos."), + ("Arccotangent in radians (0 to pi).", "Arco cotangente em radianos (0 a pi)."), + ("Arcsine in radians.", "Arco seno em radianos."), + ("Arctangent in radians.", "Arco tangente em radianos."), + ("Arithmetic mean of the numbers.", "Média aritmética dos números."), + ("Average absolute deviation from the mean.", "Desvio absoluto médio em relação à média."), + ("Average of the cells that meet a condition.", "Média das células que atendem a uma condição."), + ("Average of the cells that meet every condition.", "Média das células que atendem a todas as condições."), + ( + "Averages the numbers in a field of the records that meet the criteria.", + "Calcula a média dos números em um campo dos registros que atendem aos critérios.", + ), + ("Base-10 logarithm of a complex number.", "Logaritmo de base 10 de um número complexo."), + ("Base-10 logarithm.", "Logaritmo na base 10."), + ("Base-2 logarithm of a complex number.", "Logaritmo de base 2 de um número complexo."), + ("Bessel function of the first kind, J_n(x).", "Função de Bessel de primeira espécie, J_n(x)."), + ("Bessel function of the second kind, Y_n(x).", "Função de Bessel de segunda espécie, Y_n(x)."), + ("Beta distribution density or probability.", "Densidade ou probabilidade da distribuição beta."), + ("Binomial probability.", "Probabilidade binomial."), + ("Bitwise AND of two non-negative integers.", "E bit a bit de dois inteiros não negativos."), + ("Bitwise OR of two non-negative integers.", "OU bit a bit de dois inteiros não negativos."), + ("Bitwise exclusive OR of two non-negative integers.", "OU exclusivo bit a bit de dois inteiros não negativos."), + ("Bond-equivalent yield of a Treasury bill.", "Rendimento equivalente ao de um título para uma letra do Tesouro."), + ("Breaks a row or column into columns of the given length.", "Divide uma linha ou coluna em colunas do comprimento especificado."), + ("Breaks a row or column into rows of the given length.", "Divide uma linha ou coluna em linhas do comprimento especificado."), + ("Builds a cell address as text from row and column numbers.", "Cria um endereço de célula como texto a partir de números de linha e coluna."), + ("Builds a complex number as text from real and imaginary parts.", "Cria um número complexo como texto a partir das partes real e imaginária."), + ("Builds a date serial number from a year, month and day.", "Cria um número de série de data a partir de um ano, mês e dia."), + ( + "Builds a summary table grouping values by row and column fields.", + "Cria uma tabela de resumo agrupando valores por campos de linha e de coluna.", + ), + ( + "Builds a time (a fraction of a day) from hours, minutes and seconds.", + "Cria um horário (uma fração de um dia) a partir de horas, minutos e segundos.", + ), + ("Builds an array from a LAMBDA.", "Cria uma matriz a partir de uma LAMBDA."), + ("Builds an array of evenly stepped numbers.", "Cria uma matriz de números com espaçamento uniforme."), + ("Builds an array of random numbers in a range.", "Cria uma matriz de números aleatórios em um intervalo."), + ("Byte version of FIND.", "Versão em bytes de FIND."), + ("Byte version of LEFT (same as LEFT for single-byte text).", "Versão em bytes de LEFT (igual a LEFT para texto de byte único)."), + ("Byte version of LEN (same as LEN for single-byte text).", "Versão em bytes de LEN (igual a LEN para texto de byte único)."), + ("Byte version of MID (same as MID for single-byte text).", "Versão em bytes de MID (igual a MID para texto de byte único)."), + ("Byte version of REPLACE.", "Versão em bytes de REPLACE."), + ("Byte version of RIGHT (same as RIGHT for single-byte text).", "Versão em bytes de RIGHT (igual a RIGHT para texto de byte único)."), + ("Byte version of SEARCH.", "Versão em bytes de SEARCH."), + ( + "Capitalises the first letter of each word and lower-cases the rest.", + "Coloca em maiúscula a primeira letra de cada palavra e as demais em minúsculas.", + ), + ("Chi-squared density or left-tailed probability.", "Densidade qui-quadrado ou probabilidade da cauda esquerda."), + ("Chi-squared test of independence.", "Teste qui-quadrado de independência."), + ("Column number of a reference.", "Número da coluna de uma referência."), + ( + "Compares an expression with a list of values and returns the result paired with the first match.", + "Compara uma expressão com uma lista de valores e retorna o resultado associado à primeira correspondência.", + ), + ("Complementary error function, 1 - ERF(x).", "Função de erro complementar, 1 - ERF(x)."), + ("Complex conjugate of a complex number.", "Conjugado complexo de um número complexo."), + ( + "Confidence interval half-width using Student's t distribution.", + "Metade da largura do intervalo de confiança usando a distribuição t de Student.", + ), + ("Confidence interval half-width using the normal distribution.", "Metade da largura do intervalo de confiança usando a distribuição normal."), + ("Converts Roman numerals to a number.", "Converte algarismos romanos em um número."), + ("Converts a binary number to decimal.", "Converte um número binário em decimal."), + ("Converts a binary number to hexadecimal.", "Converte um número binário em hexadecimal."), + ("Converts a binary number to octal.", "Converte um número binário em octal."), + ("Converts a date written as text into a date serial number.", "Converte uma data escrita como texto em um número de série de data."), + ("Converts a decimal number to binary.", "Converte um número decimal em binário."), + ("Converts a decimal number to hexadecimal.", "Converte um número decimal em hexadecimal."), + ("Converts a decimal number to octal.", "Converte um número decimal em octal."), + ("Converts a decimal price to fractional notation.", "Converte um preço decimal em notação fracionária."), + ("Converts a fractional price notation to a decimal number.", "Converte uma notação de preço fracionária em um número decimal."), + ("Converts a hexadecimal number to binary.", "Converte um número hexadecimal em binário."), + ("Converts a hexadecimal number to decimal.", "Converte um número hexadecimal em decimal."), + ("Converts a hexadecimal number to octal.", "Converte um número hexadecimal em octal."), + ("Converts a measurement from one unit to another.", "Converte uma medida de uma unidade para outra."), + ("Converts a number to Roman numerals in one of five styles.", "Converte um número em algarismos romanos em um de cinco estilos."), + ("Converts a time written as text into a fraction of a day.", "Converte uma hora escrita como texto em uma fração de dia."), + ( + "Converts a value to a number: numbers stay, TRUE is 1, everything else is 0.", + "Converte um valor em número: números ficam iguais, TRUE é 1 e todo o resto é 0.", + ), + ( + "Converts an array to text, either as a comma list or as a strict array constant.", + "Converte uma matriz em texto, como uma lista separada por vírgulas ou como uma constante de matriz estrita.", + ), + ("Converts an octal number to binary.", "Converte um número octal em binário."), + ("Converts an octal number to decimal.", "Converte um número octal em decimal."), + ("Converts an octal number to hexadecimal.", "Converte um número octal em hexadecimal."), + ( + "Converts any value to text, optionally in strict (quoted) form.", + "Converte qualquer valor em texto, opcionalmente na forma estrita (entre aspas).", + ), + ( + "Converts between the euro and the former euro member currencies at the fixed rates.", + "Converte entre o euro e as antigas moedas dos países membros do euro às taxas fixas.", + ), + ("Converts degrees to radians.", "Converte graus em radianos."), + ( + "Converts full-width characters to half-width (no change for single-byte text).", + "Converte caracteres de largura total em meia largura (sem alteração para texto de byte único).", + ), + ( + "Converts half-width characters to full-width (no change in this locale).", + "Converte caracteres de meia largura em largura total (sem alteração nesta localidade).", + ), + ("Converts radians to degrees.", "Converte radianos em graus."), + ( + "Converts text that looks like a number, date or time into a number.", + "Converte texto que parece um número, uma data ou uma hora em um número.", + ), + ( + "Converts text to a number using the given decimal and group separators.", + "Converte texto em número usando os separadores decimal e de grupo informados.", + ), + ("Converts text to lower case.", "Converte o texto em minúsculas."), + ("Converts text to upper case.", "Converte o texto em maiúsculas."), + ("Correlation coefficient of two data sets.", "Coeficiente de correlação de dois conjuntos de dados."), + ("Cosecant of a complex number.", "Cossecante de um número complexo."), + ("Cosecant of an angle in radians.", "Cossecante de um ângulo em radianos."), + ("Cosine of a complex number.", "Cosseno de um número complexo."), + ("Cosine of an angle in radians.", "Cosseno de um ângulo em radianos."), + ("Cotangent of a complex number.", "Cotangente de um número complexo."), + ("Cotangent of an angle in radians.", "Cotangente de um ângulo em radianos."), + ( + "Counts days between two dates on a 360-day year (US or European method).", + "Conta os dias entre duas datas em um ano de 360 dias (método americano ou europeu).", + ), + ("Counts empty cells and empty text in a range.", "Conta células vazias e textos vazios em um intervalo."), + ( + "Counts how many values fall into each bin, as a vertical array.", + "Conta quantos valores caem em cada intervalo de classe, como uma matriz vertical.", + ), + ( + "Counts non-blank cells in a field of the matching records (or the matching records).", + "Conta as células não vazias em um campo dos registros correspondentes (ou os registros correspondentes).", + ), + ( + "Counts numeric cells in a field of the matching records (or the matching records).", + "Conta as células numéricas em um campo dos registros correspondentes (ou os registros correspondentes).", + ), + ("Counts the cells that meet a condition.", "Conta as células que atendem a uma condição."), + ("Counts the cells that meet every condition.", "Conta as células que atendem a todas as condições."), + ("Counts the characters in a text.", "Conta os caracteres de um texto."), + ("Counts the columns in an array or range.", "Conta as colunas em uma matriz ou intervalo."), + ("Counts the items in a cube set (no cube connections; #N/A).", "Conta os itens de um conjunto de cubo (sem conexões de cubo; #N/A)."), + ("Counts the non-empty values.", "Conta os valores não vazios."), + ("Counts the numbers.", "Conta os números."), + ("Counts the rows in an array or range.", "Conta as linhas em uma matriz ou intervalo."), + ( + "Counts whole years, months or days between two dates. unit: Y, M, D, MD, YM or YD.", + "Conta anos, meses ou dias completos entre duas datas. unidade: Y, M, D, MD, YM ou YD.", + ), + ( + "Counts working days (Monday to Friday) between two dates, excluding holidays.", + "Conta os dias úteis (segunda a sexta-feira) entre duas datas, excluindo feriados.", + ), + ( + "Counts working days between two dates with a custom weekend, excluding holidays.", + "Conta os dias úteis entre duas datas com um fim de semana personalizado, excluindo feriados.", + ), + ( + "Creates a link; the cell shows the friendly name, or the link itself.", + "Cria um vínculo; a célula exibe o nome amigável ou o próprio vínculo.", + ), + ("Creates a reusable custom function.", "Cria uma função personalizada reutilizável."), + ("Cumulative beta probability.", "Probabilidade beta cumulativa."), + ("Cumulative lognormal probability.", "Probabilidade lognormal cumulativa."), + ("Cuts off the fractional part of a number at the given digits.", "Trunca a parte fracionária de um número no número de dígitos especificado."), + ("Days from settlement to the next coupon date.", "Dias da liquidação até a próxima data de cupom."), + ("Days from the start of the coupon period to settlement.", "Dias do início do período do cupom até a liquidação."), + ("Days in the coupon period that contains settlement.", "Dias no período do cupom que contém a liquidação."), + ( + "Declining-balance depreciation over any span of periods, switching to straight line.", + "Depreciação por saldo decrescente em qualquer intervalo de períodos, mudando para a depreciação linear.", + ), + ("Defines a set of cube members (no cube connections; #N/A).", "Define um conjunto de membros de cubo (sem conexões de cubo; #N/A)."), + ("Determinant of a square matrix.", "Determinante de uma matriz quadrada."), + ("Difference of two complex numbers.", "Diferença de dois números complexos."), + ("Discount rate of a security.", "Taxa de desconto de um título."), + ("Double factorial of a number.", "Fatorial duplo de um número."), + ( + "Double-declining-balance (or other factor) depreciation for a period.", + "Depreciação por saldo decrescente duplo (ou outro fator) para um período.", + ), + ( + "Effective annual rate from a nominal rate and compounding periods.", + "Taxa anual efetiva a partir de uma taxa nominal e dos períodos de capitalização.", + ), + ("Equivalent interest rate for the growth of an investment.", "Taxa de juros equivalente para o crescimento de um investimento."), + ("Error function integrated from 0 to a limit, or between two limits.", "Função de erro integrada de 0 até um limite, ou entre dois limites."), + ("Error function integrated from 0 to x.", "Função de erro integrada de 0 a x."), + ("Excess kurtosis of a sample.", "Curtose em excesso de uma amostra."), + ( + "Exponential curve coefficients and optional regression statistics.", + "Coeficientes de curva exponencial e estatísticas de regressão opcionais.", + ), + ("Exponential distribution density or probability.", "Densidade ou probabilidade da distribuição exponencial."), + ("Exponential of a complex number.", "Exponencial de um número complexo."), + ("Extracts data from XML with an XPath (not available; returns #VALUE!).", "Extrai dados de XML com um XPath (não disponível; retorna #VALUE!)."), + ( + "Extracts the first match, all matches or the capture groups of a regular expression.", + "Extrai a primeira correspondência, todas as correspondências ou os grupos de captura de uma expressão regular.", + ), + ("F distribution density or left-tailed probability.", "Densidade ou probabilidade de cauda esquerda da distribuição F."), + ("Factorial of a number.", "Fatorial de um número."), + ("Fetches data from a web service (not available; returns #VALUE!).", "Obtém dados de um serviço da web (não disponível; retorna #VALUE!)."), + ( + "Finds a value in the first column of a table and returns the value in the same row of another column.", + "Procura um valor na primeira coluna de uma tabela e retorna o valor na mesma linha de outra coluna.", + ), + ( + "Finds a value in the first row of a table and returns the value in the same column of another row.", + "Procura um valor na primeira linha de uma tabela e retorna o valor da mesma coluna de outra linha.", + ), + ( + "Finds the position of one text in another (case-sensitive).", + "Localiza a posição de um texto dentro de outro (diferencia maiúsculas e minúsculas).", + ), + ( + "Finds the position of one text in another, ignoring case and allowing wildcards.", + "Localiza a posição de um texto dentro de outro, ignorando maiúsculas e minúsculas e permitindo curingas.", + ), + ("Fisher transformation.", "Transformação de Fisher."), + ("Fixed-declining-balance depreciation for a period.", "Depreciação por saldo decrescente fixo em um período."), + ( + "Flattens an array into a single column, optionally skipping blanks or errors.", + "Converte uma matriz em uma única coluna, opcionalmente ignorando células em branco ou erros.", + ), + ( + "Flattens an array into a single row, optionally skipping blanks or errors.", + "Converte uma matriz em uma única linha, opcionalmente ignorando células em branco ou erros.", + ), + ("Forecasts a value by additive (AAA) exponential smoothing.", "Prevê um valor por suavização exponencial aditiva (AAA)."), + ("Formats a number as currency text, like DOLLAR.", "Formata um número como texto de moeda, como DOLLAR."), + ("Formats a number as currency text.", "Formata um número como texto de moeda."), + ("Formats a number as text.", "Formata um número como texto."), + ("French degressive depreciation with a life-based coefficient.", "Depreciação degressiva francesa com um coeficiente baseado na vida útil."), + ("French linear depreciation prorated for the first period.", "Depreciação linear francesa proporcional ao primeiro período."), + ("Future value of a principal after a series of compound rates.", "Valor futuro de um principal após uma série de taxas compostas."), + ("Future value of an investment with constant payments and rate.", "Valor futuro de um investimento com pagamentos e taxa constantes."), + ("Gamma distribution density or probability.", "Densidade ou probabilidade da distribuição gama."), + ("Geometric mean of positive numbers.", "Média geométrica de números positivos."), + ("Greatest common divisor of integers.", "Máximo divisor comum de inteiros."), + ("Groups rows by key fields and aggregates the values of each group.", "Agrupa linhas por campos-chave e agrega os valores de cada grupo."), + ( + "Grows an array to the given size, filling new cells with a pad value.", + "Expande uma matriz até o tamanho especificado, preenchendo as novas células com um valor de preenchimento.", + ), + ( + "Half-width of the confidence interval around a FORECAST.ETS value.", + "Metade da largura do intervalo de confiança em torno de um valor de FORECAST.ETS.", + ), + ("Harmonic mean of positive numbers.", "Média harmônica de números positivos."), + ("Hyperbolic cosecant of a complex number.", "Cossecante hiperbólica de um número complexo."), + ("Hyperbolic cosecant.", "Cossecante hiperbólica."), + ("Hyperbolic cosine of a complex number.", "Cosseno hiperbólico de um número complexo."), + ("Hyperbolic cosine.", "Cosseno hiperbólico."), + ("Hyperbolic cotangent.", "Cotangente hiperbólica."), + ("Hyperbolic secant of a complex number.", "Secante hiperbólica de um número complexo."), + ("Hyperbolic secant.", "Secante hiperbólica."), + ("Hyperbolic sine of a complex number.", "Seno hiperbólico de um número complexo."), + ("Hyperbolic sine.", "Seno hiperbólico."), + ("Hyperbolic tangent.", "Tangente hiperbólica."), + ("Hypergeometric probability of an exact count.", "Probabilidade hipergeométrica de uma contagem exata."), + ("Hypergeometric probability.", "Probabilidade hipergeométrica."), + ("Identity matrix of the given size.", "Matriz identidade do tamanho especificado."), + ("Imaginary coefficient of a complex number.", "Coeficiente imaginário de um número complexo."), + ("Information about a cell.", "Informações sobre uma célula."), + ("Integer part of a division.", "Parte inteira de uma divisão."), + ( + "Interest paid in a period of a loan with even principal payments.", + "Juros pagos em um período de um empréstimo com pagamentos de principal uniformes.", + ), + ("Interest part of a given period's payment.", "Parte de juros do pagamento de um determinado período."), + ("Interest rate of a fully invested security.", "Taxa de juros de um título totalmente investido."), + ("Interest rate per period of an annuity, found iteratively.", "Taxa de juros por período de uma anuidade, encontrada por iteração."), + ("Internal rate of return of cash flows on specific dates.", "Taxa interna de retorno de fluxos de caixa em datas específicas."), + ("Internal rate of return of periodic cash flows.", "Taxa interna de retorno de fluxos de caixa periódicos."), + ("Inverse hyperbolic cosine.", "Cosseno hiperbólico inverso."), + ("Inverse hyperbolic cotangent.", "Cotangente hiperbólica inversa."), + ("Inverse hyperbolic sine.", "Seno hiperbólico inverso."), + ("Inverse hyperbolic tangent.", "Tangente hiperbólica inversa."), + ("Inverse of a square matrix.", "Inversa de uma matriz quadrada."), + ("Inverse of the Fisher transformation.", "Inversa da transformação de Fisher."), + ("Inverse of the cumulative beta distribution.", "Inversa da distribuição beta cumulativa."), + ("Inverse of the cumulative lognormal distribution.", "Inversa da distribuição lognormal cumulativa."), + ("Inverse of the gamma cumulative distribution.", "Inversa da distribuição gama cumulativa."), + ("Inverse of the left-tailed F distribution.", "Inversa da distribuição F de cauda esquerda."), + ("Inverse of the left-tailed chi-squared distribution.", "Inversa da distribuição qui-quadrado de cauda esquerda."), + ("Inverse of the normal cumulative distribution.", "Inversa da distribuição normal cumulativa."), + ("Inverse of the right-tailed F distribution.", "Inversa da distribuição F de cauda direita."), + ("Inverse of the right-tailed chi-squared distribution.", "Inversa da distribuição qui-quadrado de cauda direita."), + ("Inverse of the standard normal cumulative distribution.", "Inversa da distribuição normal padrão cumulativa."), + ("Joins several text values into one.", "Une vários valores de texto em um só."), + ( + "Joins text from values and every cell of ranges, without a separator.", + "Une o texto de valores e de todas as células de intervalos, sem separador.", + ), + ( + "Joins text from values and ranges with a delimiter, optionally skipping empty items.", + "Une o texto de valores e intervalos com um delimitador, opcionalmente ignorando itens vazios.", + ), + ("Keeps rows or columns from the start (or end) of an array.", "Mantém linhas ou colunas do início (ou do fim) de uma matriz."), + ("Keeps the rows or columns of an array whose include flag is TRUE.", "Mantém as linhas ou colunas de uma matriz cujo argumento incluir é TRUE."), + ("Largest number (0 when there are none).", "Maior número (0 quando não há nenhum)."), + ("Largest number in a field of the matching records.", "Maior número em um campo dos registros correspondentes."), + ("Largest value among cells that meet every condition.", "Maior valor entre as células que atendem a todas as condições."), + ("Largest value counting text as 0 and logicals as 1/0.", "Maior valor, contando texto como 0 e valores lógicos como 1/0."), + ("Least common multiple of integers.", "Mínimo múltiplo comum de inteiros."), + ( + "Least-squares line coefficients and optional regression statistics.", + "Coeficientes da reta de mínimos quadrados e estatísticas de regressão opcionais.", + ), + ("Left-tailed inverse of Student's t distribution.", "Inversa de cauda esquerda da distribuição t de Student."), + ("Length of the repeating pattern detected in a time series.", "Comprimento do padrão repetitivo detectado em uma série temporal."), + ("Logarithm to the given base (10 by default).", "Logaritmo na base especificada (10 por padrão)."), + ("Lognormal density or probability.", "Densidade ou probabilidade lognormal."), + ("Macaulay duration of a security with periodic interest.", "Duração de Macaulay de um título com juros periódicos."), + ("Matrix product of two arrays.", "Produto matricial de duas matrizes."), + ("Mean after trimming a fraction of points from both ends.", "Média após descartar uma fração de pontos de ambas as extremidades."), + ("Mean counting text as 0 and logical values as 1 or 0.", "Média que conta texto como 0 e valores lógicos como 1 ou 0."), + ("Middle value of the numbers.", "Valor central dos números."), + ("Modified Bessel function of the first kind, I_n(x).", "Função de Bessel modificada de primeira espécie, I_n(x)."), + ("Modified Bessel function of the second kind, K_n(x).", "Função de Bessel modificada de segunda espécie, K_n(x)."), + ("Modified duration of a security with periodic interest.", "Duração modificada de um título com juros periódicos."), + ( + "Modified internal rate of return using separate borrow and reinvest rates.", + "Taxa interna de retorno modificada usando taxas separadas de empréstimo e de reinvestimento.", + ), + ("Most frequently occurring number.", "Número que ocorre com mais frequência."), + ("Multiplies all the numbers in the arguments.", "Multiplica todos os números dos argumentos."), + ( + "Multiplies matching elements of equally sized arrays and adds the products.", + "Multiplica elementos correspondentes de matrizes de mesmo tamanho e soma os produtos.", + ), + ("Multiplies the numbers in a field of the matching records.", "Multiplica os números em um campo dos registros correspondentes."), + ("Names intermediate results.", "Nomeia resultados intermediários."), + ("Natural log of the gamma function.", "Logaritmo natural da função gama."), + ("Natural logarithm of a complex number.", "Logaritmo natural de um número complexo."), + ("Natural logarithm.", "Logaritmo natural."), + ("Negative binomial probability.", "Probabilidade binomial negativa."), + ("Net present value of cash flows on specific dates.", "Valor presente líquido de fluxos de caixa em datas específicas."), + ("Net present value of periodic cash flows at a discount rate.", "Valor presente líquido de fluxos de caixa periódicos a uma taxa de desconto."), + ("Next coupon date after settlement.", "Data do próximo cupom após a liquidação."), + ( + "Nominal annual rate from an effective rate and compounding periods.", + "Taxa anual nominal a partir de uma taxa efetiva e do número de períodos de capitalização.", + ), + ("Normal distribution density or cumulative probability.", "Densidade ou probabilidade cumulativa da distribuição normal."), + ("Number of areas in a reference.", "Número de áreas em uma referência."), + ("Number of combinations with repetition.", "Número de combinações com repetição."), + ("Number of combinations without repetition.", "Número de combinações sem repetição."), + ("Number of coupons payable between settlement and maturity.", "Número de cupons a pagar entre a liquidação e o vencimento."), + ("Number of ordered selections with repetition.", "Número de seleções ordenadas com repetição."), + ("Number of ordered selections without repetition.", "Número de seleções ordenadas sem repetição."), + ("Number of periods needed to pay off or accumulate an amount.", "Número de períodos necessários para quitar ou acumular um valor."), + ("Number of sheets.", "Número de planilhas."), + ("One- or two-tailed Student's t probability.", "Probabilidade t de Student unicaudal ou bicaudal."), + ("One-tailed probability of a z-test.", "Probabilidade unicaudal de um teste z."), + ("Pearson product-moment correlation coefficient.", "Coeficiente de correlação do momento do produto de Pearson."), + ("Percent-encodes text for use in a URL.", "Codifica o texto com porcentagem para uso em uma URL."), + ( + "Periodic payment for a loan or annuity with constant payments and rate.", + "Pagamento periódico de um empréstimo ou anuidade com pagamentos e taxa constantes.", + ), + ("Periods needed for an investment to grow to a target value.", "Períodos necessários para que um investimento chegue a um valor desejado."), + ("Picks a value from the list by its position.", "Escolhe um valor da lista por sua posição."), + ( + "Picks columns of an array by position (negative counts from the end).", + "Seleciona colunas de uma matriz por posição (negativo conta a partir do fim).", + ), + ( + "Picks rows of an array by position (negative counts from the end).", + "Seleciona linhas de uma matriz por posição (negativo conta a partir do fim).", + ), + ("Places arrays side by side.", "Coloca matrizes lado a lado."), + ("Poisson probability.", "Probabilidade de Poisson."), + ("Population covariance of paired values.", "Covariância da população de valores pareados."), + ("Population skewness.", "Assimetria da população."), + ( + "Population standard deviation counting text as 0 and logicals as 1/0.", + "Desvio padrão da população contando texto como 0 e valores lógicos como 1/0.", + ), + ("Population standard deviation of a field over the matching records.", "Desvio padrão da população de um campo nos registros correspondentes."), + ("Population standard deviation.", "Desvio padrão da população."), + ("Population variance counting text as 0 and logicals as 1/0.", "Variância da população contando texto como 0 e valores lógicos como 1/0."), + ("Population variance of a field over the matching records.", "Variância da população de um campo nos registros correspondentes."), + ("Population variance.", "Variância da população."), + ("Positive square root.", "Raiz quadrada positiva."), + ("Predicts a value along a linear trend.", "Prevê um valor ao longo de uma tendência linear."), + ("Present value of a series of equal future payments.", "Valor presente de uma série de pagamentos futuros iguais."), + ("Previous coupon date on or before settlement.", "Data de cupom anterior, na data de liquidação ou antes dela."), + ("Price per 100 face value of a Treasury bill.", "Preço por 100 de valor nominal de uma letra do Tesouro."), + ("Price per 100 face value of a discounted security.", "Preço por 100 de valor nominal de um título com desconto."), + ( + "Price per 100 face value of a security paying interest at maturity.", + "Preço por 100 de valor nominal de um título que paga juros no vencimento.", + ), + ("Price per 100 face value of a security paying periodic interest.", "Preço por 100 de valor nominal de um título que paga juros periódicos."), + ( + "Price per 100 face value of a security with an odd first period.", + "Preço por 100 de valor nominal de um título com primeiro período irregular.", + ), + ("Price per 100 face value of a security with an odd last period.", "Preço por 100 de valor nominal de um título com último período irregular."), + ("Principal part of a given period's payment.", "Parte do principal do pagamento de um determinado período."), + ("Probability from Student's t-test.", "Probabilidade do teste t de Student."), + ("Probability of a number of successes falling in a range.", "Probabilidade de um número de sucessos estar em um intervalo."), + ("Probability that a standard normal value falls between the mean and z.", "Probabilidade de um valor normal padrão cair entre a média e z."), + ("Probability that values fall between two limits.", "Probabilidade de que os valores estejam entre dois limites."), + ("Product of complex numbers.", "Produto de números complexos."), + ("Quartile (0–4) of a data set, inclusive method.", "Quartil (0–4) de um conjunto de dados, método inclusivo."), + ("Quartile (0–4) of a data set.", "Quartil (0–4) de um conjunto de dados."), + ("Quartile (1–3) of a data set, exclusive method.", "Quartil (1–3) de um conjunto de dados, método exclusivo."), + ("Quotient of two complex numbers.", "Quociente de dois números complexos."), + ("Raises a complex number to a power.", "Eleva um número complexo a uma potência."), + ("Raises a number to a power.", "Eleva um número a uma potência."), + ("Rank of a number within a list.", "Posição de um número em uma lista."), + ("Rank of a number within a list; ties get the average rank.", "Posição de um número em uma lista; empates recebem a posição média."), + ("Rank of a number within a list; ties share the top rank.", "Posição de um número em uma lista; empates compartilham a posição mais alta."), + ("Ratio of the factorial of a sum to the product of factorials.", "Razão entre o fatorial de uma soma e o produto dos fatoriais."), + ("Reads text in a given base as a number.", "Lê um texto em uma determinada base como um número."), + ("Real coefficient of a complex number.", "Coeficiente real de um número complexo."), + ("Relative standing of a value as a fraction of the data set.", "Posição relativa de um valor como fração do conjunto de dados."), + ("Relative standing of a value from 0 to 1 inclusive.", "Posição relativa de um valor de 0 a 1, inclusive."), + ("Relative standing of a value strictly between 0 and 1.", "Posição relativa de um valor estritamente entre 0 e 1."), + ("Remainder of a division, with the sign of the divisor.", "Resto de uma divisão, com o sinal do divisor."), + ( + "Removes leading and trailing spaces and collapses runs of spaces to one.", + "Remove espaços no início e no fim e reduz sequências de espaços a um só.", + ), + ("Removes non-printable control characters from text.", "Remove do texto os caracteres de controle não imprimíveis."), + ("Removes rows or columns from the start (or end) of an array.", "Remove linhas ou colunas do início (ou do fim) de uma matriz."), + ("Repeats a text a given number of times.", "Repete um texto o número de vezes especificado."), + ( + "Replaces matches of a regular expression, all of them or a chosen occurrence.", + "Substitui correspondências de uma expressão regular, todas ou uma ocorrência escolhida.", + ), + ( + "Replaces occurrences of one text with another, optionally only a given occurrence.", + "Substitui ocorrências de um texto por outro, opcionalmente apenas uma ocorrência específica.", + ), + ("Replaces part of a text by position.", "Substitui parte de um texto pela posição."), + ("Returns 1 when a number is at least the step, otherwise 0.", "Retorna 1 quando um número é maior ou igual a passo; caso contrário, 0."), + ("Returns 1 when two numbers are equal, otherwise 0.", "Retorna 1 quando dois números são iguais; caso contrário, 0."), + ( + "Returns a code for the kind of value: 1 number, 2 text, 4 logical, 16 error, 64 array.", + "Retorna um código para o tipo de valor: 1 número, 2 texto, 4 lógico, 16 erro, 64 matriz.", + ), + ( + "Returns a fallback when the value is #N/A, otherwise the value.", + "Retorna um valor alternativo quando o valor é #N/A; caso contrário, retorna o valor.", + ), + ( + "Returns a fallback when the value is an error, otherwise the value.", + "Retorna um valor alternativo quando o valor é um erro; caso contrário, retorna o valor.", + ), + ( + "Returns a key performance indicator property from a cube (no cube connections; #N/A).", + "Retorna uma propriedade de indicador-chave de desempenho de um cubo (sem conexões de cubo; #N/A).", + ), + ("Returns a member or tuple from a cube (no cube connections; #N/A).", "Retorna um membro ou tupla de um cubo (sem conexões de cubo; #N/A)."), + ( + "Returns a property of a cube member (no cube connections; #N/A).", + "Retorna uma propriedade de um membro do cubo (sem conexões de cubo; #N/A).", + ), + ("Returns an aggregated value from a cube (no cube connections; #N/A).", "Retorna um valor agregado de um cubo (sem conexões de cubo; #N/A)."), + ("Returns characters from the middle of a text.", "Retorna caracteres do meio de um texto."), + ("Returns information about the operating environment.", "Retorna informações sobre o ambiente operacional."), + ( + "Returns one value when a condition is TRUE and another when it is FALSE.", + "Retorna um valor quando uma condição é TRUE e outro quando é FALSE.", + ), + ("Returns the #N/A error value.", "Retorna o valor de erro #N/A."), + ("Returns the 1-based position of a value in a row or column.", "Retorna a posição de um valor em uma linha ou coluna, começando em 1."), + ("Returns the ISO 8601 week number of a date.", "Retorna o número da semana ISO 8601 de uma data."), + ("Returns the Unicode code point of the first character of a text.", "Retorna o ponto de código Unicode do primeiro caractere de um texto."), + ("Returns the Windows-1252 code of the first character of a text.", "Retorna o código Windows-1252 do primeiro caractere de um texto."), + ("Returns the character for a Unicode code point.", "Retorna o caractere de um ponto de código Unicode."), + ( + "Returns the character for a code from the Windows-1252 character set.", + "Retorna o caractere de um código do conjunto de caracteres Windows-1252.", + ), + ("Returns the current date and time.", "Retorna a data e a hora atuais."), + ("Returns the current date.", "Retorna a data atual."), + ("Returns the date a number of months before or after a date.", "Retorna a data um número de meses antes ou depois de uma data."), + ( + "Returns the date a number of working days away with a custom weekend.", + "Retorna a data distante um número de dias úteis, com um fim de semana personalizado.", + ), + ( + "Returns the date a number of working days before or after a date.", + "Retorna a data que fica um número de dias úteis antes ou depois de uma data.", + ), + ("Returns the day of the month of a date.", "Retorna o dia do mês de uma data."), + ("Returns the day of the week of a date as a number.", "Retorna o dia da semana de uma data como um número."), + ("Returns the distinct rows or columns of an array.", "Retorna as linhas ou colunas distintas de uma matriz."), + ( + "Returns the element, row or column of an array at the given position.", + "Retorna o elemento, a linha ou a coluna de uma matriz na posição especificada.", + ), + ("Returns the field value of the single record that meets the criteria.", "Retorna o valor do campo do único registro que atende aos critérios."), + ("Returns the first characters of a text.", "Retorna os primeiros caracteres de um texto."), + ( + "Returns the fraction of a year between two dates under a day-count basis.", + "Retorna a fração de um ano entre duas datas sob uma base de contagem de dias.", + ), + ("Returns the hour (0-23) of a time.", "Retorna a hora (0-23) de um horário."), + ("Returns the last characters of a text.", "Retorna os últimos caracteres de um texto."), + ("Returns the last day of the month a number of months away.", "Retorna o último dia do mês a um número de meses de distância."), + ("Returns the logical value FALSE.", "Retorna o valor lógico FALSE."), + ("Returns the logical value TRUE.", "Retorna o valor lógico TRUE."), + ("Returns the minute (0-59) of a time.", "Retorna o minuto (0-59) de um horário."), + ("Returns the month (1-12) of a date.", "Retorna o mês (1-12) de uma data."), + ( + "Returns the nth member of a cube set (no cube connections; #N/A).", + "Retorna o n-ésimo membro de um conjunto de cubo (sem conexões de cubo; #N/A).", + ), + ( + "Returns the number identifying an error value, or #N/A if it is not an error.", + "Retorna o número que identifica um valor de erro, ou #N/A se não for um erro.", + ), + ("Returns the number of days between two dates.", "Retorna o número de dias entre duas datas."), + ("Returns the phonetic (furigana) text; here the text itself.", "Retorna o texto fonético (furigana); aqui, o próprio texto."), + ( + "Returns the position of a value in a row or column with flexible match and search modes.", + "Retorna a posição de um valor em uma linha ou coluna com modos de correspondência e pesquisa flexíveis.", + ), + ("Returns the second (0-59) of a time.", "Retorna o segundo (0-59) de um horário."), + ("Returns the text that comes after a delimiter.", "Retorna o texto que vem depois de um delimitador."), + ("Returns the text that comes before a delimiter.", "Retorna o texto que vem antes de um delimitador."), + ("Returns the value if it is text, otherwise empty text.", "Retorna o valor se for texto; caso contrário, texto vazio."), + ("Returns the value paired with the first condition that is TRUE.", "Retorna o valor associado à primeira condição que é TRUE."), + ("Returns the week number of a date within its year.", "Retorna o número da semana de uma data dentro do ano."), + ("Returns the year of a date.", "Retorna o ano de uma data."), + ("Reverses a logical value.", "Inverte um valor lógico."), + ("Right-tailed F probability.", "Probabilidade F de cauda direita."), + ("Right-tailed Student's t probability.", "Probabilidade t de Student de cauda direita."), + ("Right-tailed chi-squared probability.", "Probabilidade qui-quadrado de cauda direita."), + ( + "Rounds a number and formats it as text with fixed decimals and optional thousands separators.", + "Arredonda um número e o formata como texto com decimais fixos e separadores de milhar opcionais.", + ), + ("Rounds a number away from zero to a given number of digits.", "Arredonda um número para longe de zero até um determinado número de dígitos."), + ("Rounds a number down to a multiple of significance.", "Arredonda um número para baixo até um múltiplo de significância."), + ("Rounds a number down to the nearest integer or multiple.", "Arredonda um número para baixo até o inteiro ou múltiplo mais próximo."), + ("Rounds a number down to the nearest integer.", "Arredonda um número para baixo até o inteiro mais próximo."), + ( + "Rounds a number to a given number of digits, halves away from zero.", + "Arredonda um número até um determinado número de dígitos, com metades arredondadas para longe de zero.", + ), + ("Rounds a number to the nearest multiple.", "Arredonda um número para o múltiplo mais próximo."), + ("Rounds a number toward negative infinity to a multiple.", "Arredonda um número em direção ao infinito negativo até um múltiplo."), + ("Rounds a number toward positive infinity to a multiple.", "Arredonda um número em direção ao infinito positivo até um múltiplo."), + ("Rounds a number toward zero to a given number of digits.", "Arredonda um número em direção a zero até um determinado número de dígitos."), + ("Rounds a number up to a multiple of significance.", "Arredonda um número para cima até um múltiplo de significância."), + ("Rounds a number up to the nearest integer or multiple.", "Arredonda um número para cima até o inteiro ou múltiplo mais próximo."), + ("Rounds away from zero to the nearest even integer.", "Arredonda para longe de zero até o inteiro par mais próximo."), + ("Rounds away from zero to the nearest odd integer.", "Arredonda para longe de zero até o inteiro ímpar mais próximo."), + ("Row number of a reference.", "Número da linha de uma referência."), + ("Running accumulation of an array.", "Acumulação progressiva de uma matriz."), + ("Sample covariance of paired values.", "Covariância da amostra de valores pareados."), + ("Sample skewness.", "Assimetria da amostra."), + ( + "Sample standard deviation counting text as 0 and logicals as 1/0.", + "Desvio padrão da amostra contando texto como 0 e valores lógicos como 1/0.", + ), + ("Sample standard deviation of a field over the matching records.", "Desvio padrão da amostra de um campo nos registros correspondentes."), + ("Sample standard deviation.", "Desvio padrão da amostra."), + ("Sample variance counting text as 0 and logicals as 1/0.", "Variância da amostra contando texto como 0 e valores lógicos como 1/0."), + ("Sample variance of a field over the matching records.", "Variância da amostra de um campo nos registros correspondentes."), + ("Sample variance.", "Variância da amostra."), + ( + "Searches a row or column and returns the matching item, row or column from another array.", + "Pesquisa uma linha ou coluna e retorna o item correspondente, a linha ou a coluna de outra matriz.", + ), + ("Secant of a complex number.", "Secante de um número complexo."), + ("Secant of an angle in radians.", "Secante de um ângulo em radianos."), + ("Sheet number.", "Número da planilha."), + ( + "Shifts the bits of a number left (right for negative shifts).", + "Desloca os bits de um número para a esquerda (para a direita se o deslocamento for negativo).", + ), + ( + "Shifts the bits of a number right (left for negative shifts).", + "Desloca os bits de um número para a direita (para a esquerda em deslocamentos negativos).", + ), + ("Sine of a complex number.", "Seno de um número complexo."), + ("Sine of an angle in radians.", "Seno de um ângulo em radianos."), + ("Slope of the least-squares regression line.", "Inclinação da reta de regressão de mínimos quadrados."), + ("Smallest number (0 when there are none).", "Menor número (0 quando não há nenhum)."), + ("Smallest number in a field of the matching records.", "Menor número em um campo dos registros correspondentes."), + ( + "Smallest success count whose cumulative binomial probability reaches alpha.", + "Menor contagem de sucessos cuja probabilidade binomial cumulativa atinge alfa.", + ), + ("Smallest value among cells that meet every condition.", "Menor valor entre as células que atendem a todas as condições."), + ("Smallest value counting text as 0 and logicals as 1/0.", "Menor valor contando texto como 0 e valores lógicos como 1/0."), + ( + "Sorts an array by the values of other arrays of matching size.", + "Classifica uma matriz pelos valores de outras matrizes de tamanho correspondente.", + ), + ( + "Sorts the rows (or columns) of an array by one or more of its columns.", + "Classifica as linhas (ou colunas) de uma matriz por uma ou mais de suas colunas.", + ), + ("Spells out a number in Thai words with Baht.", "Escreve um número por extenso em tailandês, com Baht."), + ( + "Splits text into a grid of columns and rows at the given delimiters.", + "Divide o texto em uma grade de colunas e linhas nos delimitadores especificados.", + ), + ("Square of the correlation coefficient.", "Quadrado do coeficiente de correlação."), + ("Square root of a complex number.", "Raiz quadrada de um número complexo."), + ("Square root of the number times pi.", "Raiz quadrada do número vezes pi."), + ("Stacks arrays on top of each other.", "Empilha matrizes umas sobre as outras."), + ("Standard error of predicted y values in a regression.", "Erro padrão dos valores y previstos em uma regressão."), + ("Standard normal cumulative probability.", "Probabilidade cumulativa normal padrão."), + ("Standard normal density or cumulative probability.", "Densidade ou probabilidade cumulativa normal padrão."), + ("Standard normal density.", "Densidade normal padrão."), + ("Straight-line depreciation for one period.", "Depreciação em linha reta para um período."), + ("Student's t density or left-tailed probability.", "Densidade ou probabilidade de cauda esquerda da distribuição t de Student."), + ("Sum of a power series.", "Soma de uma série de potências."), + ("Sum of complex numbers.", "Soma de números complexos."), + ("Sum of squared deviations from the mean.", "Soma dos quadrados dos desvios da média."), + ("Sum-of-years'-digits depreciation for a period.", "Depreciação pela soma dos dígitos dos anos em um período."), + ("Sums the differences of squares of matching elements.", "Soma as diferenças dos quadrados de elementos correspondentes."), + ("Sums the squared differences of matching elements.", "Soma os quadrados das diferenças dos elementos correspondentes."), + ("Sums the sums of squares of matching elements.", "Soma as somas dos quadrados dos elementos correspondentes."), + ("Swaps the rows and columns of an array.", "Troca as linhas e as colunas de uma matriz."), + ("TRUE for references.", "TRUE para referências."), + ("TRUE when a LAMBDA argument was left out.", "TRUE quando um argumento de LAMBDA foi omitido."), + ("TRUE when a regular expression matches somewhere in the text.", "TRUE quando uma expressão regular corresponde em algum ponto do texto."), + ("TRUE when an odd number of arguments are TRUE.", "TRUE quando um número ímpar de argumentos é TRUE."), + ("TRUE when at least one argument is TRUE.", "TRUE quando pelo menos um argumento é TRUE."), + ("TRUE when every argument is TRUE.", "TRUE quando todos os argumentos são TRUE."), + ("TRUE when the cell has a formula.", "TRUE quando a célula tem uma fórmula."), + ("TRUE when the integer part of a number is even.", "TRUE quando a parte inteira de um número é par."), + ("TRUE when the integer part of a number is odd.", "TRUE quando a parte inteira de um número é ímpar."), + ("TRUE when the value is TRUE or FALSE.", "TRUE quando o valor é TRUE ou FALSE."), + ("TRUE when the value is a number.", "TRUE quando o valor é um número."), + ("TRUE when the value is any error other than #N/A.", "TRUE quando o valor é qualquer erro diferente de #N/A."), + ("TRUE when the value is any error.", "TRUE quando o valor é qualquer erro."), + ("TRUE when the value is anything other than text.", "TRUE quando o valor é qualquer coisa diferente de texto."), + ("TRUE when the value is text.", "TRUE quando o valor é texto."), + ("TRUE when the value is the #N/A error.", "TRUE quando o valor é o erro #N/A."), + ("TRUE when the value refers to an empty cell.", "TRUE quando o valor se refere a uma célula vazia."), + ("TRUE when two texts are identical, including case.", "TRUE quando dois textos são idênticos, incluindo maiúsculas e minúsculas."), + ("Tangent of a complex number.", "Tangente de um número complexo."), + ("Tangent of an angle in radians.", "Tangente de um ângulo em radianos."), + ("The constant pi to 15 digits.", "A constante pi com 15 dígitos."), + ("The formula of a cell as text.", "A fórmula de uma célula como texto."), + ("The gamma function.", "A função gama."), + ("The k-th largest number in a data set.", "O k-ésimo maior número em um conjunto de dados."), + ("The k-th smallest number in a data set.", "O k-ésimo menor número de um conjunto de dados."), + ("The reference named by a text string.", "A referência indicada por uma cadeia de texto."), + ("The sum of a subset as a fraction of the sum of all the values.", "A soma de um subconjunto como fração da soma de todos os valores."), + ("Total interest paid between two periods.", "Total de juros pagos entre dois períodos."), + ("Total principal repaid between two periods.", "Total do principal pago entre dois períodos."), + ("Two-tailed Student's t probability.", "Probabilidade t de Student bicaudal."), + ("Two-tailed inverse of Student's t distribution.", "Inversa bicaudal da distribuição t de Student."), + ("Two-tailed probability that two variances do not differ.", "Probabilidade bicaudal de que duas variâncias não sejam diferentes."), + ("Values along a fitted exponential growth curve.", "Valores ao longo de uma curva de crescimento exponencial ajustada."), + ("Values along a least-squares linear fit.", "Valores ao longo de um ajuste linear de mínimos quadrados."), + ("Vertical array of all the most frequent numbers.", "Matriz vertical de todos os números mais frequentes."), + ("Weibull density or probability.", "Densidade ou probabilidade de Weibull."), + ("Writes a number in another base, padded with zeros.", "Escreve um número em outra base, preenchido com zeros."), + ("Y-intercept of the least-squares regression line.", "Interseção com o eixo Y da reta de regressão de mínimos quadrados."), + ("Yield of a Treasury bill.", "Rendimento de uma letra do Tesouro."), + ("Yield of a security paying periodic interest.", "Rendimento de um título que paga juros periódicos."), + ("Yield of a security with an odd first period.", "Rendimento de um título com primeiro período irregular."), + ("Yield of a security with an odd last period.", "Rendimento de um título com último período irregular."), + ("Z-score of a value.", "Escore z de um valor."), + ("e raised to the given power.", "e elevado à potência especificada."), + ("k-th percentile, k from 0 to 1 inclusive.", "k-ésimo percentil, com k de 0 a 1, inclusive."), + ("k-th percentile, k strictly between 0 and 1.", "k-ésimo percentil, com k estritamente entre 0 e 1."), +]; + +/// Argument names without brackets or index (`number`, not `[number2]`). +pub(super) const ARGUMENTS: &[(&str, &str)] = &[ + ("A", "A"), + ("B", "B"), + ("a", "a"), + ("abs_num", "núm_abs"), + ("actual_range", "intervalo_real"), + ("aggregation", "agregação"), + ("alpha", "alfa"), + ("angle", "ângulo"), + ("area_num", "núm_área"), + ("argument", "argumento"), + ("array", "matriz"), + ("array_x", "matriz_x"), + ("array_y", "matriz_y"), + ("average_range", "intervalo_média"), + ("base", "base"), + ("basis", "base"), + ("beta", "beta"), + ("bins_array", "matriz_bin"), + ("bottom", "inferior"), + ("by_array", "por_matriz"), + ("by_col", "por_coluna"), + ("calc_method", "método_cálculo"), + ("calculation", "cálculo"), + ("caption", "legenda"), + ("case_sensitivity", "diferenciar_maiúsculas"), + ("coefficients", "coeficientes"), + ("col_delimiter", "delimitador_coluna"), + ("col_fields", "campos_coluna"), + ("col_index_num", "núm_índice_coluna"), + ("col_num", "núm_coluna"), + ("col_sort_order", "ordem_coluna"), + ("col_total_depth", "profundidade_total_coluna"), + ("cols", "colunas"), + ("column_num", "núm_coluna"), + ("columns", "colunas"), + ("confidence_level", "nível_confiança"), + ("connection", "conexão"), + ("const", "constante"), + ("cost", "custo"), + ("coupon", "cupom"), + ("criteria", "critérios"), + ("criteria_range", "intervalo_critérios"), + ("cumulative", "cumulativo"), + ("data_all", "dados_todos"), + ("data_array", "matriz_dados"), + ("data_completion", "preenchimento_dados"), + ("data_subset", "subconjunto_dados"), + ("database", "banco_dados"), + ("date", "data"), + ("date_purchased", "data_compra"), + ("date_text", "texto_data"), + ("dates", "datas"), + ("day", "dia"), + ("days", "dias"), + ("decimal_dollar", "moeda_decimal"), + ("decimal_separator", "separador_decimal"), + ("decimals", "decimais"), + ("default_or_value", "padrão_ou_valor"), + ("deg_freedom", "graus_liberdade"), + ("delimiter", "delimitador"), + ("denominator", "denominador"), + ("dimension", "dimensão"), + ("discount", "desconto"), + ("divisor", "divisor"), + ("effect_rate", "taxa_efetiva"), + ("end_date", "data_final"), + ("end_period", "período_final"), + ("error_val", "valor_erro"), + ("exactly_once", "exatamente_uma_vez"), + ("expected_range", "intervalo_esperado"), + ("expression", "expressão"), + ("factor", "fator"), + ("field", "campo"), + ("field_headers", "cabeçalhos_campos"), + ("field_relationship", "relação_campos"), + ("filter_array", "matriz_filtro"), + ("finance_rate", "taxa_financiamento"), + ("find_text", "texto_procurado"), + ("first_coupon", "primeiro_cupom"), + ("first_interest", "primeiro_juro"), + ("first_period", "primeiro_período"), + ("form", "forma"), + ("format", "formato"), + ("format_text", "formato_texto"), + ("fraction", "fração"), + ("fractional_dollar", "moeda_fracionária"), + ("frequency", "frequência"), + ("friendly_name", "nome_amigável"), + ("from_unit", "de_unidade"), + ("full_precision", "precisão_total"), + ("function", "função"), + ("function_num", "núm_função"), + ("fv", "vf"), + ("group_separator", "separador_grupo"), + ("guess", "estimativa"), + ("height", "altura"), + ("holidays", "feriados"), + ("hour", "hora"), + ("i_num", "núm_i"), + ("if_empty", "se_vazio"), + ("if_not_found", "se_não_encontrado"), + ("ignore", "ignorar"), + ("ignore_empty", "ignorar_vazio"), + ("include", "incluir"), + ("index_num", "núm_índice"), + ("info_type", "tipo_info"), + ("initial_value", "valor_inicial"), + ("instance_num", "núm_ocorrência"), + ("inumber", "inúm"), + ("investment", "investimento"), + ("issue", "emissão"), + ("k", "k"), + ("known_xs", "x_conhecidos"), + ("known_ys", "y_conhecidos"), + ("kpi_name", "nome_kpi"), + ("kpi_property", "propriedade_kpi"), + ("lambda", "lambda"), + ("last_interest", "último_juro"), + ("life", "vida_útil"), + ("link_location", "local_vínculo"), + ("logical", "lógico"), + ("logical_test", "teste_lógico"), + ("lookup_array", "matriz_procurada"), + ("lookup_value", "valor_procurado"), + ("lookup_vector", "vetor_procurado"), + ("lower_limit", "limite_inferior"), + ("m", "m"), + ("match_end", "corresponder_fim"), + ("match_mode", "modo_correspondência"), + ("match_type", "tipo_correspondência"), + ("maturity", "vencimento"), + ("max", "máx"), + ("max_range", "intervalo_máx"), + ("mean", "média"), + ("member_expression", "expressão_membro"), + ("method", "método"), + ("min", "mín"), + ("min_length", "comprimento_mín"), + ("min_range", "intervalo_mín"), + ("minute", "minuto"), + ("mode", "modo"), + ("month", "mês"), + ("months", "meses"), + ("multiple", "múltiplo"), + ("n", "n"), + ("name", "nome"), + ("new_text", "novo_texto"), + ("new_xs", "novos_x"), + ("no_commas", "sem_separadores"), + ("no_switch", "sem_troca"), + ("nominal_rate", "taxa_nominal"), + ("nper", "nper"), + ("npery", "nper_ano"), + ("num_bytes", "núm_bytes"), + ("num_chars", "núm_caracteres"), + ("num_digits", "núm_dígitos"), + ("number", "número"), + ("number_chosen", "número_escolhido"), + ("number_f", "número_f"), + ("number_pop", "número_pop"), + ("number_s", "número_s"), + ("number_sample", "número_amostra"), + ("number_times", "número_vezes"), + ("numerator", "numerador"), + ("occurrence", "ocorrência"), + ("old_text", "texto_antigo"), + ("options", "opções"), + ("order", "ordem"), + ("pad_with", "preencher_com"), + ("par", "valor_nominal"), + ("parameter", "parâmetro"), + ("pattern", "padrão"), + ("per", "per"), + ("percent", "percentual"), + ("period", "período"), + ("places", "casas"), + ("pmt", "pgto"), + ("population_s", "população_s"), + ("power", "potência"), + ("pr", "pr"), + ("principal", "principal"), + ("prob_range", "intervalo_prob"), + ("probability", "probabilidade"), + ("probability_s", "probabilidade_s"), + ("property", "propriedade"), + ("pv", "vp"), + ("quart", "quarto"), + ("radix", "base"), + ("range", "intervalo"), + ("range_lookup", "procurar_intervalo"), + ("rank", "posição"), + ("rate", "taxa"), + ("real_num", "núm_real"), + ("redemption", "resgate"), + ("ref", "ref"), + ("ref_text", "texto_ref"), + ("reference", "referência"), + ("reinvest_rate", "taxa_reinvestimento"), + ("relative_to", "relativo_a"), + ("replacement", "substituição"), + ("result", "resultado"), + ("result_vector", "vetor_resultado"), + ("return_array", "matriz_retorno"), + ("return_mode", "modo_retorno"), + ("return_type", "tipo_retorno"), + ("row_delimiter", "delimitador_linha"), + ("row_fields", "campos_linha"), + ("row_index_num", "núm_índice_linha"), + ("row_num", "núm_linha"), + ("row_sort_order", "ordem_linha"), + ("row_total_depth", "profundidade_total_linha"), + ("rows", "linhas"), + ("salvage", "valor_residual"), + ("sample_s", "amostra_s"), + ("scan_by_column", "examinar_por_coluna"), + ("schedule", "cronograma"), + ("search_mode", "modo_pesquisa"), + ("seasonality", "sazonalidade"), + ("second", "segundo"), + ("serial_number", "núm_série"), + ("set", "conjunto"), + ("set_expression", "expressão_conjunto"), + ("settlement", "liquidação"), + ("sheet_text", "texto_planilha"), + ("shift_amount", "quantidade_deslocamento"), + ("sigma", "sigma"), + ("significance", "significância"), + ("size", "tamanho"), + ("sort_by", "classificar_por"), + ("sort_index", "índice_classificação"), + ("sort_order", "ordem_classificação"), + ("source", "origem"), + ("standard_dev", "desvio_padrão"), + ("start", "início"), + ("start_date", "data_inicial"), + ("start_num", "núm_inicial"), + ("start_period", "período_inicial"), + ("statistic_type", "tipo_estatística"), + ("stats", "estatísticas"), + ("step", "passo"), + ("suffix", "sufixo"), + ("sum_range", "intervalo_soma"), + ("table_array", "matriz_tabela"), + ("tails", "caudas"), + ("target", "destino"), + ("target_date", "data_alvo"), + ("text", "texto"), + ("time_text", "texto_hora"), + ("timeline", "linha_tempo"), + ("to_unit", "para_unidade"), + ("top", "superior"), + ("total_depth", "profundidade_total"), + ("trials", "tentativas"), + ("triangulation_precision", "precisão_triangulação"), + ("trim_cols", "aparar_colunas"), + ("trim_rows", "aparar_linhas"), + ("type", "tipo"), + ("type_text", "tipo_texto"), + ("unit", "unidade"), + ("upper_limit", "limite_superior"), + ("url", "url"), + ("value", "valor"), + ("value_if_error", "valor_se_erro"), + ("value_if_false", "valor_se_falso"), + ("value_if_na", "valor_se_nd"), + ("value_if_true", "valor_se_verdadeiro"), + ("values", "valores"), + ("vector", "vetor"), + ("weekend", "fim_de_semana"), + ("whole_number", "número_inteiro"), + ("width", "largura"), + ("within_text", "no_texto"), + ("wrap_count", "contagem_quebra"), + ("x", "x"), + ("x_num", "núm_x"), + ("x_range", "intervalo_x"), + ("xml", "xml"), + ("xpath", "xpath"), + ("y", "y"), + ("y_num", "núm_y"), + ("year", "ano"), + ("yld", "rend"), + ("z", "z"), +]; diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 699ee1547f..9cfdff53c5 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (function help follows the interface language) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (Brazilian Portuguese function help) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Per-language status against Excel, which ships its UI in dozens of languages (Windows language packs cover 100+), with localized function names, argument separators, number and date formats, @@ -21,9 +21,9 @@ right-to-left sheets and full complex-script support. Part of - **Function help** (the argument hint, autocomplete, Insert Function and the Formulas-tab menus) follows the interface language through per-language tables keyed by the catalog's English text (`i18n/_functions.rs`): descriptions, and argument names from which the - hint is assembled with the formula syntax's function name and separator. Spanish translates - the 10 common functions it had help for (SUM, AVERAGE, IF…); other languages show the English - help. + hint is assembled with the formula syntax's function name and separator. Brazilian Portuguese + translates all 479 descriptions and 283 argument names; Spanish the 10 common functions it had + help for (SUM, AVERAGE, IF…); other languages show the English help. - **About 2,200 user-visible strings** in all (heuristic source scan: ~1,700 UI and command strings plus ~500 function descriptions), so each shipped language covers **~12%** (measured count / estimated total). @@ -55,7 +55,7 @@ separators, number/date formats, machine translation with agent review, and scri | Hindi | hi | 0 (0%) | no | Devanagari: **no shaping** | no | none | 12–18 h | | Arabic | ar | 0 (0%) | no | **no shaping, no RTL UI**; Sheet Right-to-Left mirrors the grid (#146) | no | none | 25–35 h | | French | fr | 0 (0%) | no | Latin: yes | no | none | 6–10 h | -| Portuguese | pt-BR | 923 (~42%) | dialogs and tooltips (dialogs take effect with #669) | Latin: yes | no | menus, File view, dialogs | 2–4 h | +| Portuguese | pt-BR | 923 (~42%) + function help | dialogs and tooltips (dialogs take effect with #669); function descriptions and arguments | Latin: yes | no | menus, File view, dialogs | 2–4 h | | Indonesian | id | 0 (0%) | no | Latin: yes | no | none | 5–8 h | | Japanese | ja | 268 (~12%) | no | CJK system-font fallback; IME unverified; no furigana display | no | menus only | 8–12 h | | German | de | 266 (~12%) | no | Latin: yes | no | menus only | 4–8 h | @@ -84,6 +84,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | Brazilian Portuguese function help: all 479 descriptions and 283 argument names | | 2026-10-15 | minor | Function help in the interface language: argument hints, autocomplete, Insert Function (search, categories) and the Formulas-tab menus read per-language tables of descriptions and argument names keyed by the catalog's English text; Spanish keeps its 10 functions in the new format | | 2026-10-12 | minor | Format Cells looks up its tabs, labels, options and note through `Language::tr` (Fill tab keyed `Format Cells\|Fill`); dialog titles and OK/Cancel too. Labels already in a table (Number, Currency, Fill…) show translated; the rest fall back to English until the tables add them | | 2026-10-12 | minor | Brazilian Portuguese catalog (`i18n/pt.rs`) grows from 377 to 923 entries: every key the other catalogs translate, including the dialog strings #669 starts looking up (~42%) | From d98f32a7d635e0dd04c1df0b655dd9ed19608305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Sun, 18 Oct 2026 20:40:44 +0200 Subject: [PATCH 015/201] i18n: translate AutoSave in every catalog; reword Russian entries from the English MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AutoSave and its tooltip in cs, de, es, fr, ja, ko, pt, sr and zh, using each catalog's existing word for workbook and save. Both keys are in the Japanese list, so the uniqueness test now checks every language has them. - 107 Russian entries rewritten as translations of the English label instead of Excel's own Russian strings (Calculate Sheet, Define Name, Destination, Bin Range, Input/Output Range, the t-tests, the protection permissions…). Comment is «комментарий», as in the rest of the catalog. --- crates/ui-egui/src/i18n.rs | 2 + crates/ui-egui/src/i18n/cs.rs | 2 + crates/ui-egui/src/i18n/de.rs | 4 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 4 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt.rs | 3 + crates/ui-egui/src/i18n/ru.rs | 214 +++++++++++++++++----------------- crates/ui-egui/src/i18n/sr.rs | 4 + crates/ui-egui/src/i18n/zh.rs | 2 + 10 files changed, 132 insertions(+), 107 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index efec83dbf1..e6839d5398 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -599,6 +599,8 @@ const JAPANESE: &[(&str, &str)] = &[ ("Workbook calculation", "ブックの計算"), ("Enable iterative calculation", "反復計算を行う"), ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), + ("AutoSave", "自動保存"), + ("AutoSave: save after every change (workbooks saved to a file)", "自動保存: 変更のたびに保存します (ファイルに保存されたブック)"), ]; #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 7ed8372c7d..6945fdb040 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -535,6 +535,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Zoom Out" => "Oddálit", // widgets.rs (alphabetical keys). "Dismiss" => "Zavřít", + "AutoSave" => "Automatické ukládání", + "AutoSave: save after every change (workbooks saved to a file)" => "Automatické ukládání: ukládat po každé změně (sešity uložené do souboru)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index c20c7d1b36..0161946d05 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -411,6 +411,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Dunkel", "Sheet Options|View" => "Anzeige", "Print" => "Drucken", + "AutoSave" => "Automatisch speichern", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Automatisch speichern: nach jeder Änderung speichern (Arbeitsmappen, die in einer Datei gespeichert sind)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4ce231bcad..18a2b42ee0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -440,6 +440,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Compact" => "Compacto", "Outline" => "Esquema", "Tabular" => "Tabular", + "AutoSave" => "Autoguardado", + "AutoSave: save after every change (workbooks saved to a file)" => "Autoguardado: guardar tras cada cambio (libros guardados en un archivo)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5d20ab0ca2..31ef22d631 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -410,6 +410,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Activer le calcul itératif", "Calculation settings are saved with the workbook." => "Les paramètres de calcul sont enregistrés avec le classeur.", + "AutoSave" => "Enregistrement automatique", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Enregistrement automatique : enregistrer après chaque modification (classeurs enregistrés dans un fichier)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 1902ad3015..fd87959755 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -410,6 +410,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "통합 문서 계산", "Enable iterative calculation" => "반복 계산 사용", "Calculation settings are saved with the workbook." => "계산 설정은 통합 문서와 함께 저장됩니다.", + "AutoSave" => "자동 저장", + "AutoSave: save after every change (workbooks saved to a file)" => "자동 저장: 변경할 때마다 저장(파일로 저장된 통합 문서)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index fb9236cdb6..889b57ab3e 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -956,6 +956,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Protect\nSheet" => "Proteger\nPlanilha", "Watch\nWindow" => "Janela de\nInspeção", "Workbook\nStatistics" => "Estatísticas da\nPasta de Trabalho", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Salvamento Automático: salvar após cada alteração (pastas de trabalho salvas em um arquivo)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index b134798ea8..d54f13abcf 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -425,7 +425,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "A to Z" => "От А до Я", "About" => "О программе", "About GridCraft" => "О программе GridCraft", - "Accessibility" => "Специальные возможности", + "Accessibility" => "Доступность", "Action" => "Действие", "Action Journal" => "Журнал действий", "Add" => "Добавить", @@ -441,12 +441,12 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "All" => "Все", "All Charts" => "Все диаграммы", "All done. We made {count} replacements." => "Готово. Выполнено замен: {count}.", - "All except borders" => "Без рамки", + "All except borders" => "Всё, кроме границ", "Allow" => "Разрешить", "Allow all users of this sheet to:" => "Разрешить всем пользователям этого листа:", "Alpha:" => "Альфа:", "Analysis Tools" => "Инструменты анализа", - "Anova: Single Factor" => "Однофакторный дисперсионный анализ", + "Anova: Single Factor" => "Дисперсионный анализ: один фактор", "Any value" => "Любое значение", "Area" => "С областями", "At each change in (column letter):" => "При каждом изменении в (буква столбца):", @@ -456,17 +456,17 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Average" => "Среднее", "Background Color:" => "Цвет фона:", "Before sheet (position, 0 = first):" => "Перед листом (позиция, 0 = первый):", - "Bin Range (blank for automatic bins):" => "Интервал карманов (пусто — автоматически):", + "Bin Range (blank for automatic bins):" => "Диапазон интервалов (пусто — автоматически):", "Blanks" => "Пустые ячейки", "Bold" => "Полужирный", "Border" => "Граница", "Bottom" => "Нижняя", "Bottom Align" => "Выровнять по нижнему краю", "Bottom margin (in):" => "Нижнее поле (дюймы):", - "By Changing Variable Cells:" => "Изменяя ячейки переменных:", - "By changing cell:" => "Изменяя значение ячейки:", - "Calculate Now (F9)" => "Пересчёт (F9)", - "Calculate Sheet (⇧F9)" => "Произвести вычисления на листе (⇧F9)", + "By Changing Variable Cells:" => "Изменять ячейки переменных:", + "By changing cell:" => "Изменять ячейку:", + "Calculate Now (F9)" => "Пересчитать сейчас (F9)", + "Calculate Sheet (⇧F9)" => "Пересчитать лист (⇧F9)", "Calculation Options" => "Параметры вычислений", "Cancel" => "Отмена", "Category:" => "Категория:", @@ -480,7 +480,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Chart" => "Диаграмма", "Chart Title" => "Название диаграммы", "Chart data range:" => "Диапазон данных для диаграммы:", - "Check Accessibility" => "Проверка читаемости", + "Check Accessibility" => "Проверить доступность", "Choose a PNG or JPEG no larger than 16 MB." => "Выберите файл PNG или JPEG размером не более 16 МБ.", "Clear Filter" => "Очистить фильтр", "Clustered Bar" => "Линейчатая с группировкой", @@ -495,19 +495,19 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Columns (blank = all, e.g. A,C):" => "Столбцы (пусто = все, например A,C):", "Combo" => "Комбинированная", "Comma" => "Запятая", - "Comment:" => "Примечание:", - "Comments and notes (C)" => "Примечания и заметки (C)", - "Comments pane" => "Область примечаний", + "Comment:" => "Комментарий:", + "Comments and notes (C)" => "Комментарии и заметки (C)", + "Comments pane" => "Область комментариев", "Compatibility" => "Совместимость", "Conditional Formatting Rules Manager" => "Диспетчер правил условного форматирования", "Conditional formats" => "Условные форматы", - "Confidence Level (%):" => "Уровень надёжности (%):", - "Confidence Level for Mean (%), blank for none:" => "Уровень надёжности для среднего (%), пусто — нет:", + "Confidence Level (%):" => "Уровень доверия (%):", + "Confidence Level for Mean (%), blank for none:" => "Уровень доверия для среднего (%), пусто — нет:", "Confidence interval" => "Доверительный интервал", - "Confidence level (%):" => "Уровень надёжности (%):", - "Constant is Zero" => "Константа — ноль", + "Confidence level (%):" => "Уровень доверия (%):", + "Constant is Zero" => "Константа равна нулю", "Contributors" => "Участники", - "Convert Text to Columns" => "Распределение текста по столбцам", + "Convert Text to Columns" => "Преобразовать текст в столбцы", "Convert the last ink stroke to a shape" => "Преобразовать последний рукописный штрих в фигуру", "Convert to Range" => "Преобразовать в диапазон", "Copy" => "Копировать", @@ -515,32 +515,32 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Count" => "Количество", "CountA" => "Количество значений", "Covariance" => "Ковариация", - "Create Forecast Worksheet" => "Создание листа прогноза", - "Create Sparklines" => "Создание спарклайнов", + "Create Forecast Worksheet" => "Создать лист прогноза", + "Create Sparklines" => "Создать спарклайны", "Create a copy" => "Создать копию", "Cube" => "Куб", - "Cumulative Percentage" => "Интегральный процент", + "Cumulative Percentage" => "Накопленный процент", "Current region" => "Текущая область", - "Custom (%):" => "Другой (%):", + "Custom (%):" => "Свой (%):", "Custom Sort" => "Настраиваемая сортировка", "Cut" => "Вырезать", - "Damping factor:" => "Фактор затухания:", + "Damping factor:" => "Коэффициент затухания:", "Data Range:" => "Диапазон данных:", "Data validation" => "Проверка данных", - "Database" => "Работа с базой данных", + "Database" => "Базы данных", "Date & Time" => "Дата и время", "Date unit" => "Единица даты", "Day" => "День", - "Decimal" => "Действительное", - "Define Name…" => "Присвоить имя…", - "Delete Comment" => "Удалить примечание", + "Decimal" => "Десятичное число", + "Define Name…" => "Задать имя…", + "Delete Comment" => "Удалить комментарий", "Delete Sheet" => "Удалить лист", "Delete chart" => "Удалить диаграмму", - "Delete rows" => "Удаление строк", + "Delete rows" => "Удалять строки", "Delete…" => "Удалить…", "Description (optional):" => "Описание (необязательно):", "Descriptive Statistics" => "Описательная статистика", - "Destination:" => "Поместить в:", + "Destination:" => "Место назначения:", "Diagonal ↗" => "Диагональ ↗", "Diagonal ↘" => "Диагональ ↘", "Dismiss" => "Закрыть", @@ -550,32 +550,32 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?", "Don't Save" => "Не сохранять", "Double" => "Двойное", - "Double Accounting" => "Двойное, по ячейке", + "Double Accounting" => "Двойное бухгалтерское", "Doughnut" => "Кольцевая", "Down" => "Вниз", - "Edit Name" => "Изменение имени", + "Edit Name" => "Изменить имя", "Edit chart title" => "Изменить название диаграммы", "Edit…" => "Изменить…", "Engineering" => "Инженерные", - "Entire column" => "Столбец", - "Entire row" => "Строку", + "Entire column" => "Весь столбец", + "Entire row" => "Вся строка", "Erase ink strokes" => "Стереть рукописные штрихи", - "Error message:" => "Сообщение:", - "Error style" => "Вид", + "Error message:" => "Сообщение об ошибке:", + "Error style" => "Тип сообщения", "Errors" => "Ошибки", "Every command run in this session (replayable)" => "Все команды, выполненные в этом сеансе (можно повторить)", "Expand formula bar" => "Развернуть строку формул", "Exponential Smoothing" => "Экспоненциальное сглаживание", - "F-Test Two-Sample for Variances" => "Двухвыборочный F-тест для дисперсии", + "F-Test Two-Sample for Variances" => "F-тест для дисперсий двух выборок", "Fill missing points using" => "Заполнить отсутствующие точки с помощью", "Filter (⌘⇧F)" => "Фильтр (⌘⇧F)", "Filter by Selected Cell's Value" => "Фильтр по значению выделенной ячейки", "Find" => "Найти", "Find & Select" => "Найти и выделить", "Find All" => "Найти все", - "Find Next" => "Найти далее", + "Find Next" => "Найти следующее", "Find and Replace" => "Найти и заменить", - "Find what:" => "Найти:", + "Find what:" => "Что искать:", "Fits inside the selected cell and moves with its content." => "Помещается в выделенную ячейку и перемещается вместе с её содержимым.", "Flash Fill (⌘E)" => "Мгновенное заполнение (⌘E)", "Font" => "Шрифт", @@ -587,25 +587,25 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Format Cells|Fill" => "Заливка", "Format Chart pane" => "Область «Формат диаграммы»", "Format as Table" => "Форматировать как таблицу", - "Format cells" => "Форматирование ячеек", + "Format cells" => "Форматировать ячейки", "Format cells that are (value):" => "Форматировать ячейки, которые (значение):", "Format cells that contain a date occurring:" => "Форматировать ячейки, содержащие дату:", "Format cells that contain the text:" => "Форматировать ячейки, содержащие текст:", - "Format columns" => "Форматирование столбцов", - "Format rows" => "Форматирование строк", - "Format values where this formula is true:" => "Форматировать значения, для которых следующая формула является истинной:", + "Format columns" => "Форматировать столбцы", + "Format rows" => "Форматировать строки", + "Format values where this formula is true:" => "Форматировать значения, для которых эта формула истинна:", "Formats (T)" => "Форматы (T)", "Formula Builder" => "Построитель формул", "Formula:" => "Формула:", "Formulas (F)" => "Формулы (F)", "Formulas and number formats" => "Формулы и форматы чисел", "Funnel" => "Воронка", - "GRG Nonlinear" => "Поиск решения нелинейных задач методом ОПГ", + "GRG Nonlinear" => "Нелинейный метод ОПГ", "GRG Nonlinear: a local optimum of a smooth model, from the current values." => { - "Поиск решения нелинейных задач методом ОПГ: локальный оптимум гладкой модели, начиная с текущих значений." + "Нелинейный метод ОПГ: локальный оптимум гладкой модели, начиная с текущих значений." } "Go To" => "Перейти", - "Go To Special" => "Выделить группу ячеек", + "Go To Special" => "Переход к особым ячейкам", "Goal Seek" => "Подбор параметра", "Goal Seeking found a solution: {value}" => "Подбор параметра нашёл решение: {value}", "Gradebook" => "Журнал оценок", @@ -613,13 +613,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "GridCraft is fully drivable by agents. Every menu item, button and gesture is a command:" => { "GridCraft полностью управляется агентами. Каждый пункт меню, кнопка и жест — это команда:" } - "Grouped By:" => "Группирование:", - "Growth" => "Геометрическая", + "Grouped By:" => "Группировать по:", + "Growth" => "Рост", "Header (&L left, &C center, &R right; &P page, &N pages, &D date, &A sheet):" => { "Верхний колонтитул (&L слева, &C по центру, &R справа; &P страница, &N страниц, &D дата, &A лист):" } "Header (in):" => "Верхний колонтитул (дюймы):", - "Hidden" => "Скрыть формулы", + "Hidden" => "Скрытая", "Hidden: {sheets}" => "Скрытые: {sheets}", "Hide" => "Скрыть", "Hide Sheet" => "Скрыть лист", @@ -630,31 +630,31 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Horizontal axis title:" => "Название горизонтальной оси:", "Household Budget" => "Семейный бюджет", "How agents drive GridCraft (MCP / control channel)" => "Как агенты управляют GridCraft (MCP / канал управления)", - "Hypothesized Mean Difference:" => "Гипотетическая средняя разность:", - "Ignore Once" => "Пропустить", + "Hypothesized Mean Difference:" => "Предполагаемая разность средних:", + "Ignore Once" => "Пропустить один раз", "Ignore blank" => "Игнорировать пустые ячейки", "Import a text or CSV file" => "Импорт текстового файла или CSV", "In the last 7 days" => "За последние 7 дней", - "In-cell dropdown" => "Список допустимых значений", + "In-cell dropdown" => "Раскрывающийся список в ячейке", "Include forecast statistics" => "Включить статистику прогноза", "Indent" => "Отступ", - "Information" => "Сообщение", - "Input Range:" => "Входной интервал:", - "Input X Range:" => "Входной интервал X:", - "Input Y Range:" => "Входной интервал Y:", + "Information" => "Сведения", + "Input Range:" => "Входной диапазон:", + "Input X Range:" => "Входной диапазон X:", + "Input Y Range:" => "Входной диапазон Y:", "Input message:" => "Сообщение для ввода:", - "Insert Calculated Field" => "Вставка вычисляемого поля", - "Insert Chart" => "Вставка диаграммы", - "Insert Function" => "Вставка функции", + "Insert Calculated Field" => "Вставить вычисляемое поле", + "Insert Chart" => "Вставить диаграмму", + "Insert Function" => "Вставить функцию", "Insert Function (⇧F3)" => "Вставить функцию (⇧F3)", - "Insert Hyperlink" => "Вставка гиперссылки", + "Insert Hyperlink" => "Вставить гиперссылку", "Insert Link (⌘K)" => "Вставить ссылку (⌘K)", "Insert Sheet" => "Вставить лист", - "Insert Slicer" => "Вставка среза", + "Insert Slicer" => "Вставить срез", "Insert a picture" => "Вставить рисунок", "Insert a slicer to filter a table" => "Вставить срез для фильтрации таблицы", "Insert an icon" => "Вставить значок", - "Insert rows" => "Вставка строк", + "Insert rows" => "Вставлять строки", "Insert…" => "Вставить…", "Interpolation" => "Интерполяция", "Interval:" => "Интервал:", @@ -662,11 +662,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Join the ArtCraft Discord" => "Присоединиться к Discord ArtCraft", "Justify" => "По ширине", "Keep" => "Оставить", - "Keep Solver Solution" => "Сохранить найденное решение", + "Keep Solver Solution" => "Оставить найденное решение", "Kth Largest (blank for none):" => "K-й наибольший (пусто — нет):", "Kth Smallest (blank for none):" => "K-й наименьший (пусто — нет):", "Labels in first row" => "Метки в первой строке", - "Last cell" => "Последнюю ячейку", + "Last cell" => "Последняя ячейка", "Last month" => "В прошлом месяце", "Last week" => "На прошлой неделе", "Left margin (in):" => "Левое поле (дюймы):", @@ -677,24 +677,24 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Line chart" => "График", "Line or Area" => "График или диаграмма с областями", "Line with Markers" => "График с маркерами", - "Linear" => "Арифметическая", - "Link to (web address, e-mail or Sheet!A1):" => "Связать с (веб-адрес, электронная почта или Лист!A1):", + "Linear" => "Линейная", + "Link to (web address, e-mail or Sheet!A1):" => "Ссылка на (веб-адрес, электронная почта или Лист!A1):", "Link…" => "Ссылка…", "List" => "Список", "Location Range:" => "Диапазон расположения:", - "Locked" => "Защищаемая ячейка", + "Locked" => "Заблокированная", "Locking cells or hiding formulas has no effect until you protect the worksheet (Review › Protect Sheet)." => { "Защита ячеек и скрытие формул действуют только после защиты листа (Рецензирование › Защитить лист)." } - "Lookup & Reference" => "Ссылки и массивы", + "Lookup & Reference" => "Поиск и ссылки", "Macros" => "Макросы", "Macros and scripts in this workbook (Alt+F8)" => "Макросы и сценарии этой книги (Alt+F8)", "Magnification" => "Масштаб", "Make Unconstrained Variables Non-Negative" => "Сделать переменные без ограничений неотрицательными", "Markers" => "Маркеры", "Match case" => "Учитывать регистр", - "Match entire cell contents" => "Ячейка целиком", - "Math & Trig" => "Математические", + "Match entire cell contents" => "Совпадение со всем содержимым ячейки", + "Math & Trig" => "Математика и тригонометрия", "Max" => "Максимум", "Maximum:" => "Максимум:", "Median" => "Медиана", @@ -714,9 +714,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Name" => "Имя", "Name Manager" => "Диспетчер имён", "Name:" => "Имя:", - "New Comment" => "Создать примечание", - "New Name" => "Создание имени", - "New Worksheet Ply:" => "Новый рабочий лист:", + "New Comment" => "Новый комментарий", + "New Name" => "Новое имя", + "New Worksheet Ply:" => "Новый лист:", "New sheet (⇧F11)" => "Новый лист (⇧F11)", "New title (Modify):" => "Новое название (изменить):", "New…" => "Создать…", @@ -727,7 +727,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "No picture selected" => "Рисунок не выбран", "No ranges yet." => "Диапазонов пока нет.", "None" => "Нет", - "Normal Probability" => "График нормального распределения", + "Normal Probability" => "Нормальная вероятность", "Not in Dictionary ({cell}):" => "Нет в словаре ({cell}):", "Note:" => "Заметка:", "Numbers" => "Числа", @@ -736,8 +736,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Operation" => "Операция", "Orientation (degrees)" => "Ориентация (градусы)", "Other:" => "Другой:", - "Outline" => "Внешние", - "Output Range:" => "Выходной интервал:", + "Outline" => "Контур", + "Output Range:" => "Выходной диапазон:", "Output options" => "Параметры вывода", "Page Breaks" => "Разрывы страниц", "Page Setup" => "Параметры страницы", @@ -760,7 +760,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Print Titles" => "Печатать заголовки", "Product" => "Произведение", "Protect Sheet" => "Защитить лист", - "Protect Structure and Windows" => "Защита структуры и окон", + "Protect Structure and Windows" => "Защитить структуру и окна", "Protect Workbook structure" => "Защитить структуру книги", "Protect workbook for: Structure (sheets can't be added, moved, renamed, hidden or deleted)." => { "Защитить книгу: структуру (листы нельзя добавлять, перемещать, переименовывать, скрывать и удалять)." @@ -776,9 +776,9 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Red Text" => "Красный текст", "Redo (⌘Y)" => "Повторить (⌘Y)", "Reference:" => "Ссылка:", - "Refers To" => "Диапазон", + "Refers To" => "Ссылается на", "Refers to cells:" => "Ссылается на ячейки:", - "Refers to:" => "Диапазон:", + "Refers to:" => "Ссылается на:", "Regression" => "Регрессия", "Remove" => "Удалить", "Remove Duplicates" => "Удалить дубликаты", @@ -814,7 +814,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Seasonality (auto, 0 for none, or a season length):" => "Сезонность (авто, 0 — нет, или длина сезона):", "Select" => "Выделить", "Select Data" => "Выбрать данные", - "Select Data Source" => "Выбор источника данных", + "Select Data Source" => "Выбрать источник данных", "Select a Solving Method:" => "Выберите метод решения:", "Select a chart first." => "Сначала выделите диаграмму.", "Select and move ink and shapes" => "Выделять и перемещать рукописные штрихи и фигуры", @@ -822,38 +822,38 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Series" => "Ряд", "Series in" => "Ряды в", "Series{n}" => "Ряд{n}", - "Series…" => "Прогрессия…", - "Set Objective:" => "Оптимизировать целевую функцию:", - "Set cell:" => "Установить в ячейке:", + "Series…" => "Ряд…", + "Set Objective:" => "Задать цель:", + "Set cell:" => "Ячейка:", "Share: export or save a copy" => "Поделиться: экспорт или сохранение копии", "Sheets: {sheets}" => "Листы: {sheets}", - "Shift cells down" => "Ячейки со сдвигом вниз", - "Shift cells left" => "Ячейки со сдвигом влево", - "Shift cells right" => "Ячейки со сдвигом вправо", - "Shift cells up" => "Ячейки со сдвигом вверх", + "Shift cells down" => "Сдвинуть ячейки вниз", + "Shift cells left" => "Сдвинуть ячейки влево", + "Shift cells right" => "Сдвинуть ячейки вправо", + "Shift cells up" => "Сдвинуть ячейки вверх", "Show Formulas (⌃`)" => "Показать формулы (⌃`)", "Show password" => "Показать пароль", - "Shrink to fit" => "Автоподбор ширины", + "Shrink to fit" => "Сжать по размеру", "Simplex LP: for linear models; integer and binary constraints by branch and bound." => { "Симплекс-метод: для линейных моделей; целочисленные и двоичные ограничения — методом ветвей и границ." } "Single" => "Одинарное", - "Single Accounting" => "Одинарное, по ячейке", + "Single Accounting" => "Одинарное бухгалтерское", "Skip blanks" => "Пропускать пустые ячейки", "Slicer" => "Срез", - "Solve" => "Найти решение", + "Solve" => "Решить", "Solver Parameters" => "Параметры поиска решения", "Solver Results" => "Результаты поиска решения", "Sort & Filter" => "Сортировка и фильтр", "Sort by" => "Сортировать по", "Space" => "Пробел", - "Special…" => "Выделить…", + "Special…" => "Особые…", "Spelling (F7)" => "Орфография (F7)", "Stacked Area" => "С областями с накоплением", "Stacked Bar" => "Линейчатая с накоплением", "Stacked Column" => "Гистограмма с накоплением", "Stacked Line" => "График с накоплением", - "Standard Errors" => "Стандартные погрешности", + "Standard Errors" => "Стандартные ошибки", "Standard Width" => "Стандартная ширина", "Standard column width (pixels):" => "Стандартная ширина столбца (пиксели):", "Standardized Residuals" => "Стандартизированные остатки", @@ -862,23 +862,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Statistic" => "Статистика", "Statistical" => "Статистические", "Step value:" => "Шаг:", - "Stop" => "Останов", - "Stop value:" => "Предельное значение:", - "Subject to the Constraints:" => "В соответствии с ограничениями:", + "Stop" => "Стоп", + "Stop value:" => "Конечное значение:", + "Subject to the Constraints:" => "С учётом ограничений:", "Subscript" => "Подстрочный", "Subtract" => "Вычесть", "Suggestions:" => "Варианты:", "Sum" => "Сумма", "Summary statistics" => "Итоговая статистика", "Superscript" => "Надстрочный", - "Switch Row/Column" => "Строка/столбец", - "Tab" => "Знак табуляции", + "Switch Row/Column" => "Поменять строки и столбцы", + "Tab" => "Табуляция", "Table (⌘T)" => "Таблица (⌘T)", "Table Styles" => "Стили таблиц", - "Text Box" => "Надпись", + "Text Box" => "Текстовое поле", "Text length" => "Длина текста", "Text to Columns" => "Текст по столбцам", - "The output range already holds data. Replace it with the report?" => "Выходной интервал уже содержит данные. Заменить их отчётом?", + "The output range already holds data. Replace it with the report?" => "Выходной диапазон уже содержит данные. Заменить их отчётом?", "The spelling check is complete for the entire sheet." => "Проверка орфографии на всём листе завершена.", "Then by" => "Затем по", "There are no conditional formatting rules on this sheet." => "На этом листе нет правил условного форматирования.", @@ -909,16 +909,16 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Unprotect Sheet" => "Снять защиту листа", "Unprotect Workbook" => "Снять защиту книги", "Up" => "Вверх", - "Use AutoFilter" => "Использование автофильтра", - "Use function" => "Операция", + "Use AutoFilter" => "Использовать автофильтр", + "Use function" => "Функция", "Validation" => "Проверка данных", "Value" => "Значение", - "Value Of:" => "Значения:", + "Value Of:" => "Значение:", "Values (V)" => "Значения (V)", "Values and number formats" => "Значения и форматы чисел", "Values range (blank: second column of the selection):" => "Диапазон значений (пусто — второй столбец выделения):", - "Variable 1 Range:" => "Интервал переменной 1:", - "Variable 2 Range:" => "Интервал переменной 2:", + "Variable 1 Range:" => "Диапазон переменной 1:", + "Variable 2 Range:" => "Диапазон переменной 2:", "Version {version}" => "Версия {version}", "Version, contributors and the AI models that helped" => "Версия, участники и модели ИИ, которые помогали", "Vertical" => "По вертикали", @@ -926,7 +926,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Visible cells only" => "Только видимые ячейки", "Warning" => "Предупреждение", "Waterfall" => "Каскадная", - "Web" => "Интернет", + "Web" => "Веб", "Weekday" => "Рабочий день", "What-If Analysis" => "Анализ «что если»", "Whole number" => "Целое число", @@ -957,11 +957,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "less than or equal to" => "меньше или равно", "medium" => "средняя", "none" => "нет", - "not between" => "вне", + "not between" => "не между", "not equal to" => "не равно", - "t-Test: Paired Two Sample for Means" => "Парный двухвыборочный t-тест для средних", - "t-Test: Two-Sample Assuming Equal Variances" => "Двухвыборочный t-тест с одинаковыми дисперсиями", - "t-Test: Two-Sample Assuming Unequal Variances" => "Двухвыборочный t-тест с различными дисперсиями", + "t-Test: Paired Two Sample for Means" => "t-тест: парные выборки для средних", + "t-Test: Two-Sample Assuming Equal Variances" => "t-тест: две выборки с равными дисперсиями", + "t-Test: Two-Sample Assuming Unequal Variances" => "t-тест: две выборки с неравными дисперсиями", "thick" => "толстая", "thin" => "тонкая", "this workbook" => "эта книга", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index cbf18d4c46..0bd5ffd6e9 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -408,6 +408,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Bottom Margin" => "Donja margina", "Header Margin" => "Margina zaglavlja", "Footer Margin" => "Margina podnožja", + "AutoSave" => "Automatsko čuvanje", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Automatsko čuvanje: sačuvaj posle svake izmene (radne sveske sačuvane u datoteku)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 00175925e6..fb390c218f 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -402,6 +402,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "工作簿计算", "Enable iterative calculation" => "启用迭代计算", "Calculation settings are saved with the workbook." => "计算设置随工作簿一起保存。", + "AutoSave" => "自动保存", + "AutoSave: save after every change (workbooks saved to a file)" => "自动保存:每次更改后保存(已保存到文件的工作簿)", _ => return None, }) } From 0bfded65261afcfed90a25a13dc9f9b200620f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Mon, 19 Oct 2026 22:42:05 +0300 Subject: [PATCH 016/201] i18n(ru): PivotTable field list (27 labels) --- crates/ui-egui/src/i18n/ru.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index d54f13abcf..26a2ccafa3 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -981,6 +981,34 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "AutoSave: save after every change (workbooks saved to a file)" => { "Автосохранение: сохранять после каждого изменения (для книг, сохранённых в файл)" } + // PivotTable field list. + "PivotTable Fields" => "Поля сводной таблицы", + "Choose fields to add to report:" => "Выберите поля для отчёта:", + "Use a field's menu to move it between areas:" => "Чтобы переместить поле в другую область, откройте его меню:", + "Filters" => "Фильтры", + "Values" => "Значения", + "Move to Row Labels" => "Переместить в названия строк", + "Move to Column Labels" => "Переместить в названия столбцов", + "Move to Report Filter" => "Переместить в фильтр отчёта", + "Move to Values" => "Переместить в значения", + "Summarize by Sum" => "Итоги по сумме", + "Summarize by Count" => "Итоги по количеству", + "Summarize by Average" => "Итоги по среднему", + "Summarize by Max" => "Итоги по максимуму", + "Summarize by Min" => "Итоги по минимуму", + "Show as No Calculation" => "Показать без вычислений", + "Show as % of Grand Total" => "Показать как % от общего итога", + "Show as Running Total" => "Показать как нарастающий итог", + "Show as Rank" => "Показать как ранг", + "Group by Years" => "Группировать по годам", + "Group by Quarters" => "Группировать по кварталам", + "Group by Months" => "Группировать по месяцам", + "Remove Field" => "Удалить поле", + "Refresh" => "Обновить", + "Calculated Field…" => "Вычисляемое поле…", + "Report Layout" => "Макет отчёта", + "Compact" => "Сжатый", + "Tabular" => "Табличный", _ => return None, }) } From 480b8a88b5b822000c536359f766c53ba7e56aad Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 20 Oct 2026 01:35:21 +0200 Subject: [PATCH 017/201] Quick Analysis: report calling command in block errors, clip tile labels Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/quick_analysis.rs | 10 +++++----- crates/ui-egui/src/quick_analysis.rs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/quick_analysis.rs b/crates/engine/src/cmd/quick_analysis.rs index 94f4197020..5a5158118e 100644 --- a/crates/engine/src/cmd/quick_analysis.rs +++ b/crates/engine/src/cmd/quick_analysis.rs @@ -89,14 +89,14 @@ impl Block { } } -fn block(s: &Session, p: &Json, by_rows: bool) -> Result { +fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result { let sheet = target_sheet(s, p)?; let sel = match str_param(p, "range") { Some(_) => target_range(s, p)?, None => s.doc()?.selection.current(), }; if sel.is_single() { - return Err(bad(CMD, "select at least two cells")); + return Err(bad(cmd, "select at least two cells")); } let d = s.doc()?; let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; @@ -104,7 +104,7 @@ fn block(s: &Session, p: &Json, by_rows: bool) -> Result { let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?; let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?; if r.count() > MAX_SCAN_CELLS { - return Err(bad(CMD, "selection too large to analyse")); + return Err(bad(cmd, "selection too large to analyse")); } let is_num = |c: CellRef| sh.value(c).is_number(); let is_text = |c: CellRef| sh.value(c).is_text(); @@ -141,7 +141,7 @@ fn add_total(s: &mut Session, p: &Json) -> Result { Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))), }; let overwrite = bool_param(p, "overwrite").unwrap_or(false); - let b = block(s, p, by_rows)?; + let b = block(s, p, by_rows, CMD)?; let (r, sheet) = (b.range, b.sheet); let (lo, hi) = b.span_of_line(); let out_cells = match func { @@ -233,7 +233,7 @@ fn add_sparklines(s: &mut Session, p: &Json) -> Result { }; let markers = bool_param(p, "markers").unwrap_or(false); let overwrite = bool_param(p, "overwrite").unwrap_or(false); - let b = block(s, p, by_rows)?; + let b = block(s, p, by_rows, SPARK)?; if b.lines.len() as u64 > MAX_SPARKLINES { return Err(bad(SPARK, "selection too large for this result")); } diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 94032e4d38..798f68c4f8 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -281,7 +281,7 @@ fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { paint_glyph(ui, t, item.glyph, art); let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0); let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0); - ui.painter().galley(at, galley, t.text); + ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())).galley(at, galley, t.text); resp.clicked() } From 3d19fa43f6e5fe4e1a51bebf06f02758ae730a56 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Tue, 20 Oct 2026 03:14:18 +0000 Subject: [PATCH 018/201] docs: restore the XLSX right-to-left text box row lost in the main merge --- docs/file-format-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d7d6e30b26..88edb0882e 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -85,6 +85,7 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. |---|---|---| | 2026-10-19 | minor | .xls import skips dialog sheets (WsBool `fDialog`), which share the worksheet BOF type and were read as empty worksheets | | 2026-10-19 | minor | `.xls` import reads WINDOW2: right-to-left sheets (common in older Arabic and Hebrew files) open right-to-left, and hidden gridlines, headings and zero values and Show Formulas carry over | +| 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged | | 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) | | 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other | From d0033570df58d5201096b45e8e738afbfdc5e575 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 20 Oct 2026 03:56:00 +0000 Subject: [PATCH 019/201] xtask: `parity --check` accepts a CRLF checkout of the checklist On Windows with Git's default `core.autocrlf=true` (Git for Windows, GitHub's `windows-latest` image), `docs/parity-checklist.md` is checked out with CRLF line ends. `parity --check` compared it byte for byte with the generated text (LF), so `cargo xtask ci` stopped at `parity` with "out of date" although the file was current. Line ends are no longer a difference; any other change still is. Co-authored-by: CRBBeesy --- xtask/src/parity.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/xtask/src/parity.rs b/xtask/src/parity.rs index f0efecae37..75e027f3ac 100644 --- a/xtask/src/parity.rs +++ b/xtask/src/parity.rs @@ -70,6 +70,12 @@ pub fn render(entries: &[Entry]) -> String { s } +/// Whether the checked-in checklist matches the generated text. A Windows checkout with +/// `core.autocrlf=true` (Git for Windows' default) has CRLF line ends, which aren't a change. +pub fn up_to_date(current: &str, generated: &str) -> bool { + current == generated || current.replace("\r\n", "\n") == generated +} + #[cfg(feature = "engine")] fn entries() -> Vec { use gridcraft_engine::catalog::CATALOG; @@ -106,7 +112,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let text = render(&entries()); if check { let current = std::fs::read_to_string(&out).map_err(|e| format!("{}: {e}", out.display()))?; - if current != text { + if !up_to_date(¤t, &text) { return Err(format!("{} is out of date; run `cargo xtask parity`", out.display())); } println!("{} ({} up to date)", summary_line(), out.display()); @@ -149,4 +155,14 @@ mod tests { fn empty_catalog_renders() { assert!(render(&[]).contains("0 / 0 commands implemented (0.0%)")); } + + #[test] + fn a_crlf_checkout_of_the_current_checklist_is_up_to_date() { + let text = render(&[e("file.new", "File", true), e("home.bold", "Home", false)]); + assert!(up_to_date(&text, &text)); + assert!(up_to_date(&text.replace('\n', "\r\n"), &text)); + let stale = render(&[e("file.new", "File", false), e("home.bold", "Home", false)]); + assert!(!up_to_date(&stale, &text)); + assert!(!up_to_date(&stale.replace('\n', "\r\n"), &text)); + } } From 4215f07bb34cac01e1c377ee0ef941238ea3b9f7 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:24:25 +0200 Subject: [PATCH 020/201] Formula entry: a leading + or - starts a formula, like Excel (fixes #2023) Typing `+5+4` entered the text `+5+4`: a leading sign started a formula only when a letter or `(` came next. Now any entry that starts with `+` or `-` and isn't a number on its own is a formula, as in Excel, so `+5+4` enters `=+5+4`. `+5`, `-5` and a lone sign are unchanged. The rule lives in `gridcraft_core::parse::starts_formula`, shared by the engine's entry and the Spanish formula-locale path in the UI, where a signed decimal-comma number (`-1,5`) stays a number. Text to Columns keeps a part that isn't a valid formula as text instead of emptying its cell, as paste and Replace already do. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 20 +++++++++++++ crates/engine/src/cmd/data.rs | 3 +- crates/engine/src/cmd/edit.rs | 7 +---- crates/engine/src/tests.rs | 42 ++++++++++++++++++++++++++ crates/ui-egui/src/formula_locale.rs | 44 +++++++++++++++++++++------- docs/ui-parity.md | 5 ++-- 6 files changed, 102 insertions(+), 19 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index b465beaf9e..33127c5e0a 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -49,6 +49,13 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { parse_numeric(s.trim(), sys).map(|(n, _)| n) } +/// Whether typed cell input is a formula: it starts with `=`, or, as Lotus 1-2-3 users type it, +/// with `+` or `-` and isn't a number on its own. `+5+4` is the formula `=+5+4`, `-5` the number +/// -5, and a lone `+` or `-` is text. A leading space or apostrophe makes the input text. +pub fn starts_formula(input: &str) -> bool { + input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) +} + fn parse_numeric(t: &str, sys: DateSystem) -> Option<(f64, Option<&'static str>)> { if t.is_empty() { return None; @@ -363,6 +370,19 @@ mod tests { assert_eq!(p("1.2.3.4").value, Value::text("1.2.3.4")); } + #[test] + fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() { + // #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did. + for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--"] { + assert!(starts_formula(s), "{s}"); + } + // Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or + // apostrophe and other text stay text. + for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b"] { + assert!(!starts_formula(s), "{s}"); + } + } + #[test] fn dates_and_times() { assert_eq!(p("10/7/2026").value, Value::Number(46302.0)); diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 24bd043f7d..7b77953e1b 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -839,7 +839,8 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result { } } for (c, t) in out { - let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); + // A part that isn't a valid formula (`--`) stays text, as it does when pasted. + let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(t.as_str())))); let shm = cx.sheet_mut(sheet)?; match cell { Some(x) => shm.set_cell(c, x), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fe7f1fe8bc..86b0eeeec7 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -131,12 +131,7 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri if fmt_is_text { return Ok(Some(Cell { value: Value::text(input), formula: None, style })); } - let is_formula = input.starts_with('=') - || (input.len() > 1 - && (input.starts_with('+') || input.starts_with('-')) - && gridcraft_core::parse::parse_number_text(input).is_none() - && input.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '(')); - if is_formula { + if gridcraft_core::parse::starts_formula(input) { let body = input.strip_prefix('=').unwrap_or(input); // Excel closes missing parentheses for you. let mut text = body.to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2ac2906548..506bd01915 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -202,6 +202,48 @@ fn enter_values_and_formulas() { assert_eq!(crate::display::cell_text(&d.wb, sh, CellRef::parse("B1").unwrap()), "12%"); } +#[test] +fn a_leading_plus_or_minus_starts_a_formula() { + // #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`. + let mut s = s(); + let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text()); + for (cell, typed, value) in + [("A1", "+5+4", 9.0), ("A2", "-5+4", -1.0), ("A3", "--5", 5.0), ("A4", "-3/4", -0.75), ("A5", "+A1*2", 18.0), ("A6", "-(A1)", -9.0)] + { + s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); + assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}"); + assert_eq!(v(&s, cell), Value::Number(value), "{typed}"); + } + // A signed number is a number, a lone sign is text, and an apostrophe keeps the text. + for (typed, value) in [ + ("+5", Value::Number(5.0)), + ("-5", Value::Number(-5.0)), + ("-12%", Value::Number(-0.12)), + ("-$5", Value::Number(-5.0)), + ("-", Value::text("-")), + ("+", Value::text("+")), + ("'+5+4", Value::text("+5+4")), + ] { + s.execute("cell.set", json!({"cell": "B1", "input": typed})).unwrap(); + assert_eq!(v(&s, "B1"), value, "{typed}"); + assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); + } + // Typed, a sign that doesn't start a valid formula is refused like `=--` and the cell keeps + // its value; pasted or split by Text to Columns it stays text. + s.execute("cell.set", json!({"cell": "C1", "input": "kept"})).unwrap(); + for typed in ["--", "+5+", "+49 170 1234567"] { + let e = s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_err().to_string(); + assert!(e.contains("problem with this formula"), "{typed}: {e}"); + assert_eq!(v(&s, "C1"), Value::text("kept"), "{typed}"); + } + s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); + assert_eq!(v(&s, "D1"), Value::text("--")); + assert_eq!(v(&s, "E1"), Value::Number(-1.0)); + s.execute("cell.set", json!({"cell": "F1", "input": "a,--,b"})).unwrap(); + s.execute("data.textToColumns", json!({"range": "F1", "delimiters": [","]})).unwrap(); + assert_eq!([v(&s, "F1"), v(&s, "G1"), v(&s, "H1")], [Value::text("a"), Value::text("--"), Value::text("b")]); +} + #[test] fn formulas_with_the_wrong_argument_count_are_refused_on_entry() { // #363: =DATEDIF(start, end) was stored and showed #VALUE!. Like Excel, entry refuses it and diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 6e833b95db..26b7ac007d 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -20,14 +20,16 @@ pub(crate) fn canonical( if locale == FormulaLocale::En || wb.sheet(sheet).is_some_and(|sh| wb.styles.get(sh.style_id(cell)).num_fmt.as_str() == "@") { return Ok(text.to_string()); } - // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text). - let body = text; - if body.starts_with('=') - || ((body.starts_with('+') || body.starts_with('-')) && body.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic() || c == '(')) - { + // Decimal-comma number entry follows the same preference, without rewriting text or dates. + let normalized = text.trim().replace(locale.decimal_separator(), "."); + let number = normalized.strip_suffix('%').unwrap_or(&normalized); + let is_number = number.parse::().is_ok_and(f64::is_finite); + // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except + // that a signed number in this locale (`-1,5`) is a number, not a formula. + if !is_number && gridcraft_engine::core::parse::starts_formula(text) { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. - let mut body = body.to_string(); + let mut body = text.to_string(); let mut expr = formula::parse_input(&body, locale, known); for _ in 0..8 { if expr.is_ok() { @@ -38,10 +40,7 @@ pub(crate) fn canonical( } return Ok(format!("={}", formula::print(&expr?))); } - // Decimal-comma number entry follows the same preference, without rewriting text or dates. - let normalized = body.trim().replace(locale.decimal_separator(), "."); - let number = normalized.strip_suffix('%').unwrap_or(&normalized); - if number.parse::().is_ok_and(f64::is_finite) { + if is_number { return Ok(normalized); } Ok(text.to_string()) @@ -138,3 +137,28 @@ pub(crate) fn display_template(text: &str, locale: FormulaLocale, wb: &Workbook, } display(text, locale, wb, sheet) } + +#[cfg(test)] +mod tests { + use gridcraft_engine::core::CellRef; + use gridcraft_engine::formula::FormulaLocale; + use gridcraft_engine::model::Workbook; + + use super::canonical; + + #[test] + fn a_leading_sign_starts_a_formula_in_spanish_too() { + // #2023: `+5+4` is a formula in every formula language; in Spanish `-1,5` stays the + // number -1.5 rather than becoming a formula. + let wb = Workbook::new(); + let at = CellRef::parse("A1").unwrap(); + let entry = |text: &str| canonical(text, FormulaLocale::Es, &wb, 0, at).ok(); + assert_eq!(entry("+5+4").as_deref(), Some("=+5+4")); + assert_eq!(entry("-5+4").as_deref(), Some("=-5+4")); + assert_eq!(entry("-SUMA(1;2)").as_deref(), Some("=-SUM(1,2)")); + assert_eq!(entry("-1,5").as_deref(), Some("-1.5")); + assert_eq!(entry("+2,5%").as_deref(), Some("+2.5%")); + assert_eq!(entry("-").as_deref(), Some("-")); + assert_eq!(entry("--"), None); + } +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 34cb502f54..64cf2810e1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (a leading + or - starts a formula, #2023) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -47,7 +47,7 @@ this logic, with one undo step. | Selection outline glides to a new selection (Excel: "Provide feedback with animation") | done (10-11): 0.12 s, decelerating, with the fill and fill handle; View ▸ Animations (`view.animations`) turns it off. The timing is an estimate, not yet measured against Excel; the system's reduced-motion setting isn't followed yet | | Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series); right-drag menu missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | done (M3) | -| In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done | +| In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done; a leading `+` or `-` starts a formula, as in Excel (`+5+4` enters `=+5+4`, #2023) | | Point mode (click/drag/arrow references), reference colouring, F4 | done | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | @@ -161,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, a lone `+` or `-` stays text, and an entry like `--` that isn't a valid formula is refused like `=--`; pasted or split by Text to Columns it stays text (#2023) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From 1af4d38e716f926781d36af7b09976a177964c09 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 07:45:49 +0200 Subject: [PATCH 021/201] Formula entry: keep canonical's body binding, so the diff stays small Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/formula_locale.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 26b7ac007d..132aef258a 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -20,16 +20,17 @@ pub(crate) fn canonical( if locale == FormulaLocale::En || wb.sheet(sheet).is_some_and(|sh| wb.styles.get(sh.style_id(cell)).num_fmt.as_str() == "@") { return Ok(text.to_string()); } + let body = text; // Decimal-comma number entry follows the same preference, without rewriting text or dates. - let normalized = text.trim().replace(locale.decimal_separator(), "."); + let normalized = body.trim().replace(locale.decimal_separator(), "."); let number = normalized.strip_suffix('%').unwrap_or(&normalized); let is_number = number.parse::().is_ok_and(f64::is_finite); // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except // that a signed number in this locale (`-1,5`) is a number, not a formula. - if !is_number && gridcraft_engine::core::parse::starts_formula(text) { + if !is_number && gridcraft_engine::core::parse::starts_formula(body) { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. - let mut body = text.to_string(); + let mut body = body.to_string(); let mut expr = formula::parse_input(&body, locale, known); for _ in 0..8 { if expr.is_ok() { From 0c78ddf79f5300c7e2df33da40ab567c9eaf05c4 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:04:50 +0200 Subject: [PATCH 022/201] Formula entry: a + or - entry that isn't a valid formula stays text Observed in Excel for the web: `--`, `-----`, `+5+` and `+49 170 1234567` stay text, and `- item` is #NAME?. Only `=` entries are refused. Entry now tries a `+`/`-` entry as `=` followed by the entry and, when that doesn't parse, reads it as a number or text as before; the Spanish formula path does the same with its parser. Text to Columns no longer needs its own text fallback, so that change is dropped. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 7 ++++--- crates/engine/src/cmd/data.rs | 3 +-- crates/engine/src/cmd/edit.rs | 10 +++++++++- crates/engine/src/tests.rs | 19 ++++++++++++------- crates/ui-egui/src/formula_locale.rs | 16 ++++++++++++---- docs/ui-parity.md | 2 +- 6 files changed, 39 insertions(+), 18 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index 33127c5e0a..949f9909f9 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -49,9 +49,10 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { parse_numeric(s.trim(), sys).map(|(n, _)| n) } -/// Whether typed cell input is a formula: it starts with `=`, or, as Lotus 1-2-3 users type it, -/// with `+` or `-` and isn't a number on its own. `+5+4` is the formula `=+5+4`, `-5` the number -/// -5, and a lone `+` or `-` is text. A leading space or apostrophe makes the input text. +/// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users +/// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5, +/// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse +/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. pub fn starts_formula(input: &str) -> bool { input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) } diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index 7b77953e1b..24bd043f7d 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -839,8 +839,7 @@ fn text_to_columns(s: &mut Session, p: &Json) -> Result { } } for (c, t) in out { - // A part that isn't a valid formula (`--`) stays text, as it does when pasted. - let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or_else(|_| Some(Cell::value(Value::text(t.as_str())))); + let cell = super::edit::input_to_cell(&t, sheet, c, &mut cx.wb).unwrap_or(None); let shm = cx.sheet_mut(sheet)?; match cell { Some(x) => shm.set_cell(c, x), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 86b0eeeec7..cfdd1abeba 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -131,7 +131,15 @@ pub(crate) fn input_to_cell(input: &str, sheet: usize, at: CellRef, wb: &mut gri if fmt_is_text { return Ok(Some(Cell { value: Value::text(input), formula: None, style })); } - if gridcraft_core::parse::starts_formula(input) { + // As in Excel, a `+` or `-` entry is a formula when it reads as one (`+5+4` enters `=+5+4`) + // and text when it doesn't (`--`, `+49 170 1234567`); only `=` entries are refused. + if !input.starts_with('=') + && gridcraft_core::parse::starts_formula(input) + && let Ok(cell) = input_to_cell(&format!("={input}"), sheet, at, wb) + { + return Ok(cell); + } + if input.starts_with('=') { let body = input.strip_prefix('=').unwrap_or(input); // Excel closes missing parentheses for you. let mut text = body.to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 506bd01915..7af82fbfc4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -228,14 +228,19 @@ fn a_leading_plus_or_minus_starts_a_formula() { assert_eq!(v(&s, "B1"), value, "{typed}"); assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); } - // Typed, a sign that doesn't start a valid formula is refused like `=--` and the cell keeps - // its value; pasted or split by Text to Columns it stays text. - s.execute("cell.set", json!({"cell": "C1", "input": "kept"})).unwrap(); - for typed in ["--", "+5+", "+49 170 1234567"] { - let e = s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_err().to_string(); - assert!(e.contains("problem with this formula"), "{typed}: {e}"); - assert_eq!(v(&s, "C1"), Value::text("kept"), "{typed}"); + // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and + // one that does but names nothing known is #NAME?. Only `=` entries are refused. + for typed in ["--", "-----", "+5+", "+49 170 1234567"] { + s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); + assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}"); + assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}"); } + s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap(); + assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name)); + let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string(); + assert!(e.contains("problem with this formula"), "{e}"); + assert_eq!(v(&s, "C1"), Value::text("+49 170 1234567"), "a refused entry keeps the cell"); + // Pasted or split by Text to Columns, the same rule applies. s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); assert_eq!(v(&s, "D1"), Value::text("--")); assert_eq!(v(&s, "E1"), Value::Number(-1.0)); diff --git a/crates/ui-egui/src/formula_locale.rs b/crates/ui-egui/src/formula_locale.rs index 132aef258a..dcc4d6db50 100644 --- a/crates/ui-egui/src/formula_locale.rs +++ b/crates/ui-egui/src/formula_locale.rs @@ -25,9 +25,14 @@ pub(crate) fn canonical( let normalized = body.trim().replace(locale.decimal_separator(), "."); let number = normalized.strip_suffix('%').unwrap_or(&normalized); let is_number = number.parse::().is_ok_and(f64::is_finite); - // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text), except - // that a signed number in this locale (`-1,5`) is a number, not a formula. - if !is_number && gridcraft_engine::core::parse::starts_formula(body) { + // Same formula detection as the engine's `input_to_cell` (no trimming: " =1" is text): a `+` + // or `-` entry is a formula when it reads as one and text when it doesn't, and a signed number + // in this locale (`-1,5`) is a number. The apostrophe keeps the engine from reading such text + // again in English syntax. + if !body.starts_with('=') && !is_number && gridcraft_engine::core::parse::starts_formula(body) { + return Ok(canonical(&format!("={body}"), locale, wb, sheet, cell).unwrap_or_else(|_| format!("'{body}"))); + } + if body.starts_with('=') { let known = |name: &str| wb.name(name, sheet).is_some() || wb.table(name).is_some(); // Match the engine's existing convenience for missing closing parentheses. let mut body = body.to_string(); @@ -160,6 +165,9 @@ mod tests { assert_eq!(entry("-1,5").as_deref(), Some("-1.5")); assert_eq!(entry("+2,5%").as_deref(), Some("+2.5%")); assert_eq!(entry("-").as_deref(), Some("-")); - assert_eq!(entry("--"), None); + // An entry that doesn't read as a formula stays text; only `=` entries are refused. + assert_eq!(entry("--").as_deref(), Some("'--")); + assert_eq!(entry("+34 612 345 678").as_deref(), Some("'+34 612 345 678")); + assert_eq!(entry("=--"), None); } } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 64cf2810e1..06e2039841 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -161,7 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| -| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, a lone `+` or `-` stays text, and an entry like `--` that isn't a valid formula is refused like `=--`; pasted or split by Text to Columns it stays text (#2023) | +| 2026-10-20 | minor | Typing a leading `+` or `-` starts a formula whenever the entry isn't a number on its own, as in Excel: `+5+4` enters `=+5+4` and `-5+4` enters `=-5+4` (they stayed text; only a letter or `(` after the sign started one). `+5`, `-5` and `-$5` stay numbers, and a lone `+` or `-` and an entry that doesn't read as a formula (`--`, `+49 170 1234567`) stay text, as observed in Excel for the web; only `=` entries are refused (#2023) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From fdad356fd25aa95166c5150a6e6aca5cb877f13a Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:39:07 +0200 Subject: [PATCH 023/201] AutoSum on one cell proposes its range in the editor, like Excel (fixes #1834) AutoSum from the ribbon or keyboard entered `=SUM(range)` at once, so the range could only be changed by editing the formula afterwards. On one cell it now runs with `enter: false` and leaves `=SUM(B2:B4)` in the editor with `B2:B4` pointed and selected: a click, drag, arrow key or typing replaces it, and Enter enters the formula. With nothing to sum the caret waits between the parentheses of `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` (control channel, CLI, MCP) is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/editor.rs | 43 ++++++ crates/ui-egui/src/formula_bar.rs | 6 +- crates/ui-egui/src/lib.rs | 22 +++ crates/ui-egui/tests/autosum_edit.rs | 149 +++++++++++++++++++++ crates/ui-egui/tests/keyboard_shortcuts.rs | 7 +- docs/ui-parity.md | 5 +- 6 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/tests/autosum_edit.rs diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 799109f890..64fa3627d5 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -41,6 +41,8 @@ pub struct EditState { pub completion: Option, /// Move the caret to the end on the next frame. pub caret_to_end: bool, + /// Select from this char index to `caret` when the caret is next pushed into the widget. + pub select_from: Option, } impl EditState { @@ -62,6 +64,7 @@ impl EditState { sync_caret: true, caret_to_end: true, completion: None, + select_from: None, } } @@ -107,6 +110,23 @@ impl EditState { self.sync_caret = true; } + /// Points and selects the argument of the call that ends the text, as AutoSum proposes it + /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves + /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no + /// argument (`=SUM()`) the caret goes between the parentheses. + pub fn point_last_argument(&mut self) { + let Some(open) = self.text.rfind('(') else { return }; + let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; + let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); + let (start, end) = (open + 1, close); + self.caret = chars(end); + self.point = (start < end).then_some((start, end)); + self.select_from = (start < end).then(|| chars(start)); + self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); + self.caret_to_end = false; + self.sync_caret = true; + } + /// Updates function autocomplete for the word before the caret. pub fn update_autocomplete(&mut self, names: &[String]) { self.autocomplete.clear(); @@ -316,6 +336,29 @@ mod tests { assert!(!e2.can_point()); } + #[test] + fn autosum_points_and_selects_its_proposed_range() { + // #1834: Excel leaves AutoSum's range ready to be replaced by pointing or typing. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUM(A1:A3)".into(), true, false); + e.point_last_argument(); + assert!(e.can_point()); + assert_eq!((e.caret, e.select_from, e.point), (10, Some(5), Some((5, 10)))); + assert_eq!(e.point_cell, Some(CellRef::new(0, 0)), "arrow keys move from the range's first cell"); + e.insert_ref("A2"); + assert_eq!(e.text, "=SUM(A2)"); + // No proposal: the caret waits between the parentheses. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUMA()".into(), true, false); + e.point_last_argument(); + assert!(e.can_point()); + assert_eq!((e.caret, e.select_from, e.point), (6, None, None)); + e.insert_ref("B2"); + assert_eq!(e.text, "=SUMA(B2)"); + // Text without a closing call is left alone. + let mut e = EditState::new(0, CellRef::new(3, 0), "=SUM(".into(), true, false); + e.point_last_argument(); + assert_eq!((e.caret, e.point), (5, None)); + } + #[test] fn autocomplete_and_hints() { let names: Vec = ["SUM", "SUMIF", "SUMPRODUCT", "AVERAGE"].iter().map(|s| s.to_string()).collect(); diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index 7f1ad87fc1..012a570d01 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -298,7 +298,11 @@ pub fn editor_widget(app: &mut SheetApp, ui: &mut egui::Ui, id: egui::Id, font: ed.request_focus = false; ed.sync_caret = false; let cursor = egui::text::CCursor::new(ed.caret); - output.state.cursor.set_char_range(Some(egui::text::CCursorRange::one(cursor))); + let range = match ed.select_from.take() { + Some(from) => egui::text::CCursorRange::two(egui::text::CCursor::new(from), cursor), + None => egui::text::CCursorRange::one(cursor), + }; + output.state.cursor.set_char_range(Some(range)); output.state.store(ui.ctx(), id); } else if resp.clicked() || resp.gained_focus() { // Clicking into the other editor moves editing there. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f549aec2b5..4704ef20d2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -528,11 +528,33 @@ impl SheetApp { if id == "file.exportPdf" && self.services.pick_save.is_some() && params.get("path").and_then(Json::as_str).is_none_or(str::is_empty) { return self.export_pdf_with_picker(params); } + // Menu-style AutoSum on one cell proposes its formula in the editor with the range + // pointed and selected, so a click, drag, arrow key or typing replaces it, as in Excel. + // Programmatic callers use `run` and get the total entered. + if id == "formulas.autoSum" && params.get("range").is_none() && self.session.active().is_some_and(|d| d.selection.current().is_single()) { + return self.auto_sum_in_editor(params); + } if let Err(e) = self.run(id, params) { self.alert(e); } } + fn auto_sum_in_editor(&mut self, params: Json) { + let mut params = if params.is_object() { params } else { json!({}) }; + if let Some(map) = params.as_object_mut() { + map.insert("enter".into(), Json::Bool(false)); + } + if let Err(e) = self.run("formulas.autoSum", params) { + return self.alert(e); + } + if let Some(ed) = self.editor.as_mut() { + ed.point_last_argument(); + if ed.can_point() { + self.session.mode = gridcraft_engine::Mode::Point; + } + } + } + /// Asks for a `.pdf` path with the save picker, then re-runs `file.exportPdf` with it. Other /// params (range, sheets, fitToPage) are kept. A cancelled picker does nothing. fn export_pdf_with_picker(&mut self, mut params: Json) { diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs new file mode 100644 index 0000000000..eae1da4079 --- /dev/null +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -0,0 +1,149 @@ +//! AutoSum from the ribbon or keyboard on one cell proposes its formula in the editor, with the +//! range ready to be replaced by pointing or typing, as in Excel (#1834). + +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; +use gridcraft_engine::core::{CellRef, Value}; +use gridcraft_engine::{Mode, Session}; +use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +/// 1, 2, 3 in A1:A3 and `selected` selected. +fn harness(selected: &str) -> Harness { + harness_at("A1", selected) +} + +/// 1, 2, 3 down from `first` and `selected` selected. +fn harness_at(first: &str, selected: &str) -> Harness { + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": first, "values": [[1], [2], [3]]})).unwrap(); + session.execute("selection.set", json!({"range": selected})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + app.logic(ui.ctx()); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +/// The AutoSum button: a menu-style run. +fn auto_sum(h: &mut Harness) { + h.state_mut().run_or_alert("formulas.autoSum", json!({})); + h.run_steps(2); +} + +fn editing(h: &Harness) -> Option { + h.state().editor.as_ref().map(|e| e.text.clone()) +} + +fn input(h: &Harness, cell: &str) -> String { + h.state().session.active().unwrap().wb.active().unwrap().input_text(CellRef::parse(cell).unwrap()) +} + +fn cell_center(h: &Harness, cell: &str) -> Pos2 { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll); + geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center() +} + +fn pointer(h: &mut Harness, cell: &str, pressed: bool) { + let pos = cell_center(h, cell); + h.input_mut() + .events + .extend([Event::PointerMoved(pos), Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]); + h.run_steps(2); +} + +fn enter(h: &mut Harness) { + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + } + h.run_steps(2); +} + +#[test] +fn autosum_on_one_cell_proposes_its_range_in_the_editor() { + let mut h = harness("A4"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)")); + assert_eq!(h.state().session.mode, Mode::Point); + assert_eq!(input(&h, "A4"), "", "nothing is entered before Enter"); + enter(&mut h); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); + assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); +} + +#[test] +fn a_click_or_drag_replaces_the_proposed_range() { + let mut h = harness("A4"); + auto_sum(&mut h); + pointer(&mut h, "A2", true); + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2)")); + + let mut h = harness("A4"); + auto_sum(&mut h); + pointer(&mut h, "A1", true); + let to = cell_center(&h, "A2"); + for pos in [to, to + egui::vec2(1.0, 0.0)] { + h.input_mut().events.push(Event::PointerMoved(pos)); + h.step(); + } + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A2)")); + enter(&mut h); + assert_eq!(input(&h, "A4"), "=SUM(A1:A2)"); +} + +#[test] +fn an_arrow_key_points_from_the_proposed_range() { + // Observed in Excel for the web: ↑ after AutoSum moves from the range's first cell. + let mut h = harness_at("A2", "A5"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A4)")); + for pressed in [true, false] { + h.input_mut().events.push(Event::Key { key: Key::ArrowUp, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + } + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)")); +} + +#[test] +fn typing_replaces_the_proposed_range() { + let mut h = harness("A4"); + auto_sum(&mut h); + h.input_mut().events.push(Event::Text("A2:A3".into())); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A2:A3)")); +} + +#[test] +fn with_nothing_to_sum_the_caret_waits_between_the_parentheses() { + let mut h = harness("C10"); + auto_sum(&mut h); + assert_eq!(editing(&h).as_deref(), Some("=SUM()")); + pointer(&mut h, "A1", true); + pointer(&mut h, "A1", false); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1)")); +} + +#[test] +fn a_block_and_programmatic_calls_enter_the_totals_at_once() { + let mut h = harness("A1:A4"); + auto_sum(&mut h); + assert!(h.state().editor.is_none()); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); + + // The control channel, CLI and MCP run commands with `run`: no editor. + let mut h = harness("A4"); + h.state_mut().run("formulas.autoSum", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().editor.is_none()); + assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); +} diff --git a/crates/ui-egui/tests/keyboard_shortcuts.rs b/crates/ui-egui/tests/keyboard_shortcuts.rs index 78bc966f51..5fc62f1e0f 100644 --- a/crates/ui-egui/tests/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/keyboard_shortcuts.rs @@ -235,9 +235,10 @@ fn alt_equals_autosum_does_not_also_type_the_equals_sign() { for (selected, cell, formula) in [("A4", "A4", "=SUM(A1:A3)"), ("C3", "C3", "=SUM(A3:B3)"), ("A1:B3", "B4", "=SUM(B1:B3)")] { let mut h = harness(book(selected)); alt_equals(&mut h); - assert_eq!(input(&h, cell), formula, "Alt+= on {selected}"); - assert!(h.state().editor.is_none(), "Alt+= on {selected} started an edit"); - // Enter moves on: there is no stray `=` edit to commit. + // One cell: the formula waits in the editor for Enter, as in Excel (#1834); a block gets + // its totals at once. Either way without a stray `=`. + let editing = h.state().editor.as_ref().map(|e| e.text.clone()); + assert_eq!(editing.as_deref(), (!selected.contains(':')).then_some(formula), "Alt+= on {selected}"); key(&mut h, Key::Enter, Modifiers::NONE); assert!(h.state().message.is_none(), "Alt+= on {selected}: {:?}", h.state().message); assert_eq!(input(&h, cell), formula); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 34cb502f54..2de457262c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (Ctrl+Enter fill gives each cell the automatic number format typing gives it; keytip letters typed with Alt held, #1846) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (AutoSum on one cell proposes its range in the editor, #1834) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -48,7 +48,7 @@ this logic, with one undo step. | Fill handle: drag to fill series, double-click to fill down, right-drag menu | fill done (Ctrl+drag swaps copy and series); right-drag menu missing | | Drag-move and drag-copy cells (border drag, Ctrl/Option, Shift to insert) | done (M3) | | In-cell editing, Enter/Tab movement, Alt/Option+Enter line breaks | done | -| Point mode (click/drag/arrow references), reference colouring, F4 | done | +| Point mode (click/drag/arrow references), reference colouring, F4 | done; AutoSum on one cell leaves its proposed range pointed and selected (#1834) | | AutoComplete in columns, function autocomplete and argument tips | done; cell helpers clip to the worksheet and hide when the editor scrolls out (#200) | | Header resize and double-click AutoFit | done (#42, #88 for header dividers) | | Outline symbols for grouped rows / columns (band beside the headers, brackets, − / +, level buttons 1…n+1) | done (#373): clicks run `data.hideDetail` / `data.showDetail` / `data.showLevels`, frozen panes and right-to-left sheets included; summary rows/columns are always below/right (the "Summary rows below detail" setting isn't modelled), no "Show outline symbols" option yet, and a block of cells still groups rows without the Rows / Columns dialog | @@ -161,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | AutoSum from the ribbon or keyboard on one cell proposes `=SUM(range)` in the editor instead of entering it, with the range pointed and selected: a click, drag, arrow key or typing replaces it and Enter enters it, as in Excel. With nothing to sum the caret waits inside `=SUM()`. A block still gets its totals at once, and programmatic `formulas.autoSum` is unchanged (#1834) | | 2026-10-19 | minor | Ctrl+Enter (`range.fill`) gives each cell what typing the input there gives: a General cell gets the automatic number format (`5%`, `$5`, `3/4/2026`, `=TODAY()`) even when it already held a value, and a cell with its own format, a formatted row or column, or Text keeps it. Cells that held a value used to keep General (`5%` showed 0.05), and empty cells took the active cell's format | | 2026-10-18 | minor | Keytip letters typed with left Alt held continue the sequence (Alt+H, O, A / Alt+H, O, I ran nothing before: Alt+letter cancelled keytips); other Alt combinations, AltGr and macOS Option are unchanged (#1846) | | 2026-10-12 | minor | The File view's recent list tells when each workbook was last changed, read off the UI thread | From 132bd4e9a8fa99befcae74ef8b7af1910dd6c98f Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:59:30 +0200 Subject: [PATCH 024/201] AutoSum: test the menu functions; keep the new editor method clear of #1056 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Home › AutoSum ▾ Average proposes `=AVERAGE(range)` the same way (and so will Formulas › AutoSum once it has the menu, #658). `point_last_argument` moves to the end of `impl EditState`, so this PR no longer touches the lines #1056 and #1838 change after `insert_ref`. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/editor.rs | 34 ++++++++++++++-------------- crates/ui-egui/tests/autosum_edit.rs | 12 ++++++++++ 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/editor.rs b/crates/ui-egui/src/editor.rs index 64fa3627d5..2061a0dbda 100644 --- a/crates/ui-egui/src/editor.rs +++ b/crates/ui-egui/src/editor.rs @@ -110,23 +110,6 @@ impl EditState { self.sync_caret = true; } - /// Points and selects the argument of the call that ends the text, as AutoSum proposes it - /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves - /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no - /// argument (`=SUM()`) the caret goes between the parentheses. - pub fn point_last_argument(&mut self) { - let Some(open) = self.text.rfind('(') else { return }; - let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; - let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); - let (start, end) = (open + 1, close); - self.caret = chars(end); - self.point = (start < end).then_some((start, end)); - self.select_from = (start < end).then(|| chars(start)); - self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); - self.caret_to_end = false; - self.sync_caret = true; - } - /// Updates function autocomplete for the word before the caret. pub fn update_autocomplete(&mut self, names: &[String]) { self.autocomplete.clear(); @@ -211,6 +194,23 @@ impl EditState { } None } + + /// Points and selects the argument of the call that ends the text, as AutoSum proposes it + /// (`=SUM(B1:B3)`): a click, drag, arrow key or typing replaces `B1:B3`. An arrow key moves + /// from the range's first cell, as in Excel: ↑ on `=SUM(A2:A4)` gives `=SUM(A1)`. With no + /// argument (`=SUM()`) the caret goes between the parentheses. + pub fn point_last_argument(&mut self) { + let Some(open) = self.text.rfind('(') else { return }; + let Some(close) = self.text.len().checked_sub(1).filter(|&c| c > open && self.text.ends_with(')')) else { return }; + let chars = |byte: usize| self.text.get(..byte).map_or(0, |t| t.chars().count()); + let (start, end) = (open + 1, close); + self.caret = chars(end); + self.point = (start < end).then_some((start, end)); + self.select_from = (start < end).then(|| chars(start)); + self.point_cell = self.text.get(start..end).and_then(RangeRef::parse).map(|r| r.start); + self.caret_to_end = false; + self.sync_caret = true; + } } /// References in formula text with their byte spans and colour index (same reference text ⇒ diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs index eae1da4079..a1bc0342bf 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -79,6 +79,18 @@ fn autosum_on_one_cell_proposes_its_range_in_the_editor() { assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); } +#[test] +fn the_autosum_menu_functions_propose_theirs_the_same_way() { + // Home › AutoSum ▾ Average (and Formulas › AutoSum ▾ once it has the menu, #658). + let mut h = harness("A4"); + h.state_mut().run_or_alert("formulas.autoSum", json!({"function": "AVERAGE"})); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A1:A3)")); + pointer(&mut h, "A2", true); + pointer(&mut h, "A2", false); + assert_eq!(editing(&h).as_deref(), Some("=AVERAGE(A2)")); +} + #[test] fn a_click_or_drag_replaces_the_proposed_range() { let mut h = harness("A4"); From 601cc60cfcaf15e8f3db0526cbdf26083b4fa4ac Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:17:48 +0200 Subject: [PATCH 025/201] AutoSum: a `range` that isn't text counts as no range, as in the engine `formulas.autoSum` reads `range` with `str_param`, so `{"range": null}` means the selection; the UI's check for the editor proposal now reads it the same way (CodeRabbit review). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/lib.rs | 7 ++++++- crates/ui-egui/tests/autosum_edit.rs | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4704ef20d2..1606a85473 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -531,7 +531,10 @@ impl SheetApp { // Menu-style AutoSum on one cell proposes its formula in the editor with the range // pointed and selected, so a click, drag, arrow key or typing replaces it, as in Excel. // Programmatic callers use `run` and get the total entered. - if id == "formulas.autoSum" && params.get("range").is_none() && self.session.active().is_some_and(|d| d.selection.current().is_single()) { + if id == "formulas.autoSum" + && params.get("range").and_then(Json::as_str).is_none() + && self.session.active().is_some_and(|d| d.selection.current().is_single()) + { return self.auto_sum_in_editor(params); } if let Err(e) = self.run(id, params) { @@ -539,6 +542,8 @@ impl SheetApp { } } + /// Runs AutoSum on the active cell without entering it (`enter: false`) and points the + /// proposed range in the editor that opens. fn auto_sum_in_editor(&mut self, params: Json) { let mut params = if params.is_object() { params } else { json!({}) }; if let Some(map) = params.as_object_mut() { diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/autosum_edit.rs index a1bc0342bf..9f76bf8a8d 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/autosum_edit.rs @@ -77,6 +77,12 @@ fn autosum_on_one_cell_proposes_its_range_in_the_editor() { enter(&mut h); assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::parse("A4").unwrap()), Value::Number(6.0)); + + // A `range` that isn't text is no range, for the engine and here alike. + let mut h = harness("A4"); + h.state_mut().run_or_alert("formulas.autoSum", json!({"range": null})); + h.run_steps(2); + assert_eq!(editing(&h).as_deref(), Some("=SUM(A1:A3)")); } #[test] From 77cfbda1bc0f9784e1f05b82154b7919d62b3c87 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Thu, 22 Oct 2026 05:18:54 +0000 Subject: [PATCH 026/201] docs: order parity revision history --- docs/file-format-parity.md | 2 +- docs/function-parity.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index f43c801591..fa9df6c0b7 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -117,9 +117,9 @@ refresh. Counted under features (Get & Transform, ~10% ready), not here. | 2026-10-19 | minor | .xls import skips dialog sheets (WsBool `fDialog`), which share the worksheet BOF type and were read as empty worksheets | | 2026-10-19 | minor | `.xls` import reads WINDOW2: right-to-left sheets (common in older Arabic and Hebrew files) open right-to-left, and hidden gridlines, headings and zero values and Show Formulas carry over | | 2026-10-19 | trivial | XLSX text boxes and shapes keep right-to-left paragraph direction (`a:pPr rtl`, ECMA-376 Part 1 §21.1.2.2.7): read from the first paragraph and written on every paragraph; output without it is unchanged | +| 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-18 | trivial | `file.open {csvAsText: true}` keeps every CSV/TSV/TXT field as the text the file holds, so identifiers (GTINs, SKUs, ZIP codes) keep their digits and leading zeros (#1808; a preference and a CLI flag are separate work) | | 2026-10-18 | trivial | XLSX PivotTables: `rowGrandTotals` is the Grand Total row and `colGrandTotals` the Grand Total column. Both were read and written the other way round, which a GridCraft round trip hid, so an Excel file with only one grand total opened showing the other | -| 2026-10-19 | minor | HTML (Save as Web Page and clipboard) marks right-to-left sheets and right-to-left cell text with `dir` | | 2026-10-16 | trivial | XLSX charts: `[0]!Name` (a workbook-scoped defined name) in series references is read as the name, so the series resolve instead of showing `#NAME?`. Names in chart references are written qualified (`[0]!Name`, or `Sheet!Name` for a sheet-scoped name): Excel draws a chart with a bare name blank (#1686) | | 2026-10-16 | trivial | XLSX reads and writes the workbook's show-objects setting (`workbookPr showObjects`: all, placeholders, none), which Ctrl+6 switches; a file without it is saved without it | | 2026-10-16 | trivial | XLSX: pictures in headers and footers (`&G`, the VML drawing `` names and its images) are kept on save; they are still not shown (#1257) | diff --git a/docs/function-parity.md b/docs/function-parity.md index 74916759ce..6470b9936e 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -128,8 +128,8 @@ workbooks; results checked in as data, not Excel files) and fixing what it finds | 2026-10-17 | minor | 15-significant-digit comparison moved from missing to done (#57), and the resolved caveats on the 3-D reference, dynamic-array and legacy-array rows cleared (#140, #133, #139, #156) | | 2026-10-16 | minor | FORECAST.ETS gap interpolation uses a forward-only known-point scan instead of rescanning each gap for every missing value; numerical behavior and missing-point limits are preserved (#1042) | | 2026-10-15 | minor | MEDIAN and AGGREGATE median use an overflow-safe midpoint (#1579); regressions cover finite extremes, tiny values and dependent recalculation | -| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred | | 2026-10-15 | minor | ADDRESS quotes a sheet name the way Excel does: names that read as an A1 cell (`A1`) or an R1C1 reference (`R1C1`, `RC`) and names starting with `.` get quotes; `TRUE` / `FALSE` stay bare (#1458) | +| 2026-10-14 | minor | Number-to-text (`&`, CONCAT, TEXTJOIN, VALUETOTEXT, the IM functions' complex text, and also formula printing, pivot and chart labels) rounds to 15 significant digits before choosing decimal or scientific, so `=(1E15-0.5)&""` is `1E+15`, not `1000000000000000`; and below 1 it switches to scientific when the decimal would be longer than 21 characters (sign not counted), as Excel caches IMCSCH/IMEXP/IMTAN results: `1.28233995888454E-06`, so `9.99999999999999E-09` (was `0.00000001`), but `0.0000692361330972509`. Only 15-digit positive mantissas are Excel-verified; the limit for shorter mantissas and for negatives is inferred | | 2026-10-13 | minor | Clear reports changed stored cells sparsely, including those beyond the first million coordinates; dependent formulas and removed spills update, while clearing empty merges still unblocks spills (#1032) | | 2026-10-14 | minor | Bounded references up to 1,048,576 cells (`D3:AZ400`) keep their full shape instead of stopping at the used range, so `SUMPRODUCT(D3:AZ400*B3:B400,(A3:A400=x)*(D1:AZ1=y))` broadcasts like Excel and `ROWS`, `COUNTBLANK` and `--(r="")` count the blanks; references that run to the edge of the sheet (`A:A`) still stop at the used range (#1010) | | 2026-10-12 | minor | USDOLLAR added as a Compatibility function (not on Microsoft's list, so the counts don't change); MIRR with no positive flow is -1, COUNTIF's bare `"<="` / `">="` skip empty strings, INDIRECT with `a1` = FALSE gives `#REF!` for A1-style text (#738) | From 995a4f8e2b864988c2b6e2dacc23a73666730f79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Thu, 22 Oct 2026 10:17:06 +0200 Subject: [PATCH 027/201] i18n: drop catalog keys the merge left twice (German keeps main's AutoSpeichern) --- crates/ui-egui/src/i18n/de.rs | 4 ---- crates/ui-egui/src/i18n/ru.rs | 7 ------- 2 files changed, 11 deletions(-) diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b5dbec28fe..61c2292f49 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -421,10 +421,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Dunkel", "Sheet Options|View" => "Anzeige", "Print" => "Drucken", - "AutoSave" => "Automatisch speichern", - "AutoSave: save after every change (workbooks saved to a file)" => { - "Automatisch speichern: nach jeder Änderung speichern (Arbeitsmappen, die in einer Datei gespeichert sind)" - } // grid.rs cell and row/column header context menus. "Cut" => "Ausschneiden", "Copy" => "Kopieren", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 93578a3c7c..567421355a 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -432,7 +432,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { } "A to Z" => "От А до Я", "About" => "О программе", - "About GridCraft" => "О программе GridCraft", "Accessibility" => "Доступность", "Action" => "Действие", "Action Journal" => "Журнал действий", @@ -466,7 +465,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Before sheet (position, 0 = first):" => "Перед листом (позиция, 0 = первый):", "Bin Range (blank for automatic bins):" => "Диапазон интервалов (пусто — автоматически):", "Blanks" => "Пустые ячейки", - "Bold" => "Полужирный", "Border" => "Граница", "Bottom" => "Нижняя", "Bottom Align" => "Выровнять по нижнему краю", @@ -518,7 +516,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Convert Text to Columns" => "Преобразовать текст в столбцы", "Convert the last ink stroke to a shape" => "Преобразовать последний рукописный штрих в фигуру", "Convert to Range" => "Преобразовать в диапазон", - "Copy" => "Копировать", "Correlation" => "Корреляция", "Count" => "Количество", "CountA" => "Количество значений", @@ -531,7 +528,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Current region" => "Текущая область", "Custom (%):" => "Свой (%):", "Custom Sort" => "Настраиваемая сортировка", - "Cut" => "Вырезать", "Damping factor:" => "Коэффициент затухания:", "Data Range:" => "Диапазон данных:", "Data validation" => "Проверка данных", @@ -666,7 +662,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Insert…" => "Вставить…", "Interpolation" => "Интерполяция", "Interval:" => "Интервал:", - "Italic" => "Курсив", "Join the ArtCraft Discord" => "Присоединиться к Discord ArtCraft", "Justify" => "По ширине", "Keep" => "Оставить", @@ -697,7 +692,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Lookup & Reference" => "Поиск и ссылки", "Macros" => "Макросы", "Macros and scripts in this workbook (Alt+F8)" => "Макросы и сценарии этой книги (Alt+F8)", - "Magnification" => "Масштаб", "Make Unconstrained Variables Non-Negative" => "Сделать переменные без ограничений неотрицательными", "Markers" => "Маркеры", "Match case" => "Учитывать регистр", @@ -928,7 +922,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Variable 1 Range:" => "Диапазон переменной 1:", "Variable 2 Range:" => "Диапазон переменной 2:", "Version {version}" => "Версия {version}", - "Version, contributors and the AI models that helped" => "Версия, участники и модели ИИ, которые помогали", "Vertical" => "По вертикали", "Vertical axis title:" => "Название вертикальной оси:", "Visible cells only" => "Только видимые ячейки", From ebc986fcc986e6a600f149cfb5f09fa35c71c3d8 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 22 Oct 2026 11:50:34 -0600 Subject: [PATCH 028/201] #223: test that the title bar's Save includes the cell being typed #223 made the title bar's Save button (and the Save Changes dialog's) commit the cell edit before saving, without a test for the button. The test types into A1, clicks Save, and reads the saved file back; with the commit_edit call removed it fails because the file lacks the value. --- crates/ui-egui/tests/file_menu.rs | 48 +++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/ui-egui/tests/file_menu.rs b/crates/ui-egui/tests/file_menu.rs index 047efe1b1e..50364876a3 100644 --- a/crates/ui-egui/tests/file_menu.rs +++ b/crates/ui-egui/tests/file_menu.rs @@ -108,6 +108,54 @@ fn save_actions_include_the_cell_draft_and_close_keeps_the_unsaved_prompt() { assert_eq!(h.state().session.active().unwrap().wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0)); } +/// Where the title bar's icon button for `name` is. Its icon has no text, so it is found by +/// hovering along the title bar until its tooltip ("Save (⌘S)") shows. +fn title_bar_button(h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str) -> egui::Pos2 { + let autosave = h.get_by_label("AutoSave").rect(); + let tip = format!("{name} ("); + let mut x = autosave.right(); + while x < autosave.right() + 300.0 { + let at = egui::pos2(x, autosave.center().y); + h.hover_at(at); + h.run_steps(3); + if h.query_by_label_contains(&tip).is_some() { + return at; + } + x += 6.0; + } + panic!("no title bar button shows a {tip:?} tooltip"); +} + +#[test] +fn the_title_bar_save_button_saves_the_cell_being_typed() { + // Regression test for #223: the title bar's Save button saved the file without the cell the + // user was still typing in. + let dir = std::env::temp_dir().join(format!("gridcraft-title-bar-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Book.xlsx").to_string_lossy().into_owned(); + let mut h = harness(Services::default()); + h.state_mut().run("file.save", serde_json::json!({"path": &path})).unwrap(); + h.run_steps(2); + h.input_mut().events.push(egui::Event::Text("123".into())); + h.run_steps(2); + assert!(h.state().editor.is_some()); + let save = title_bar_button(&mut h, "Save"); + for pressed in [true, false] { + h.input_mut().events.push(egui::Event::PointerButton { + pos: save, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.run_steps(2); + assert!(h.state().editor.is_none(), "Save commits the cell draft"); + let (wb, _) = gridcraft_engine::io::open_bytes("Book.xlsx", &std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(wb.active().unwrap().value(CellRef::new(0, 0)), Value::Number(123.0), "the saved file has the typed value"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn file_options_opens_the_options_page_and_pages_are_reachable_by_command() { let mut h = harness(Services::default()); From 524ce912e5960de2e39d2165a0c0fbd03c6c13ef Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 22 Oct 2026 11:50:34 -0600 Subject: [PATCH 029/201] #360: test that Watch Window stays inside the Formulas ribbon #360 (#342) moved Watch Window out of a three-row column it overflowed, without a test. The test checks Watch Window's painted label ends no lower than the ribbon's last label row; as the fourth small button it ends 15 px below. --- crates/ui-egui/tests/interaction.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/crates/ui-egui/tests/interaction.rs b/crates/ui-egui/tests/interaction.rs index 46e981d0aa..d17ccc60fc 100644 --- a/crates/ui-egui/tests/interaction.rs +++ b/crates/ui-egui/tests/interaction.rs @@ -26,6 +26,30 @@ fn blank() -> Session { s } +#[test] +fn the_formulas_ribbon_keeps_watch_window_inside_the_ribbon() { + // Regression test for #360 (#342): Watch Window was a fourth small button in a column of + // three, so it hung below the ribbon and was cut off. + fn texts(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))), + _ => {} + } + } + let mut h = harness(blank()); + h.state_mut().ui.ribbon_tab = "Formulas".into(); + h.run_steps(3); + // Ribbon button labels are painted text: find them among the frame's shapes. + let mut painted = Vec::new(); + h.output().shapes.iter().for_each(|c| texts(&c.shape, &mut painted)); + let bottom_of = |word: &str| painted.iter().filter(|(s, _)| s.contains(word)).map(|(_, r)| r.bottom()).fold(f32::NEG_INFINITY, f32::max); + // "Calculation Options" is a big button whose second line sits at the foot of the ribbon. + let (watch, foot) = (bottom_of("Window"), bottom_of("Options")); + assert!(watch.is_finite() && foot.is_finite(), "the Formulas ribbon paints Watch Window and Calculation Options"); + assert!(watch <= foot + 0.5, "Watch Window's label ends at y={watch}, below the ribbon's last label row (y={foot})"); +} + #[test] fn vertical_scrollbar_pages_and_drags_without_changing_selection() { let mut h = harness(blank()); From bc0cd892253caf48a54d40ad0a9769b445b48661 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 22 Oct 2026 11:50:34 -0600 Subject: [PATCH 030/201] #1485: test that the PivotTable field-list scrollbar sits at the pane edge #1485 let the field list take the pane's width so its scrollbar sits at the pane edge, without a test. With 14 short field names the scrollbar otherwise sits beside them, about 250 px from the edge. --- crates/ui-egui/tests/pivot_pane.rs | 44 ++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/ui-egui/tests/pivot_pane.rs b/crates/ui-egui/tests/pivot_pane.rs index d08c0e0763..d0e6dfb1f3 100644 --- a/crates/ui-egui/tests/pivot_pane.rs +++ b/crates/ui-egui/tests/pivot_pane.rs @@ -56,3 +56,47 @@ fn pivot_field_button_surfaces_follow_the_active_theme() { assert_eq!(field_button_fill(&shapes, "Region ▾"), expected, "dark mode: {dark}"); } } + +fn flatten(shape: Shape, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.into_iter().for_each(|s| flatten(s, out)), + s => out.push(s), + } +} + +#[test] +fn the_field_list_scrollbar_sits_at_the_pane_edge() { + // Regression test for #1485: with enough source fields to scroll, the field list's scrollbar + // sat just right of the longest (short) field name instead of at the pane's right edge. + use egui_kittest::kittest::Queryable as _; + let names: Vec = (1..=14).map(|i| format!("F{i}")).collect(); + let mut session = Session::new(); + session.new_workbook(); + session.execute("range.setValues", json!({"range": "A1", "values": [names.clone(), (1..=14).collect::>()]})).unwrap(); + session.execute("insert.pivotTable", json!({"source": "Sheet1!A1:N2", "destination": "Sheet1!A5", "rows": ["F1"], "values": ["F2"]})).unwrap(); + session.execute("selection.set", json!({"cell": "A5"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + let first = h.get_by_label("F1").rect(); + // A floating scrollbar is drawn while the pointer is over its area. + h.get_by_label("F1").hover(); + h.run_steps(3); + let mut shapes = Vec::new(); + h.output().shapes.iter().for_each(|c| flatten(c.shape.clone(), &mut shapes)); + let bar = shapes + .iter() + .filter_map(|s| match s { + Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 12.0 && r.rect.height() >= 20.0 && r.rect.left() > first.left() => Some(r.rect), + _ => None, + }) + .max_by(|a, b| a.right().total_cmp(&b.right())) + .expect("the field list draws a scrollbar"); + assert!(bar.right() > 1200.0 - 20.0, "the scrollbar {bar:?} sits at the pane's right edge, not beside the field names ({first:?})"); +} From 74f09bc67223b053e53a5d8bf9bda6f595d3ba82 Mon Sep 17 00:00:00 2001 From: "D. Fender" <26173007+postfen@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:44:46 -0700 Subject: [PATCH 031/201] Tables: Give each style row its own look Table styles reused three rough templates, so every row of a family in the Format as Table gallery looked alike. The neutral band was white darkened about 3%, which is invisible. Each gallery row (Light 1-7, 8-14, 15-21; Medium 1-7, 8-14, 15-21, 22-28; Dark 1-7, 8, 9-11) now has its own fills, text colours and thin lines: header rules, row lines, a vertical grid, an outer frame or white tile gaps, as observed in Excel's gallery. The colours are our own theme tints. Neutral bands are now visibly grey. One function gives each cell's look, used by the grid, print, Convert to Range and the gallery swatches, so the swatches match the tables. The outer frame follows hidden or filtered edge rows and columns. Explicit cell fills, fonts and borders still win over the table's. --- crates/engine/src/cmd/print.rs | 2 +- crates/engine/src/tables.rs | 316 +++++++++++++++++------ crates/engine/tests/table_style_looks.rs | 240 +++++++++++++++++ crates/ui-egui/src/grid.rs | 2 +- crates/ui-egui/src/ribbon.rs | 54 ++-- 5 files changed, 503 insertions(+), 111 deletions(-) create mode 100644 crates/engine/tests/table_style_looks.rs diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 4c80f2fa90..ba115e63e2 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -636,7 +636,7 @@ struct Look { fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option) -> Look { let mut style = match sh.table_at(c) { - Some(t) => crate::tables::table_cell_style(wb, si, t, c), + Some(t) => crate::tables::table_cell_shown_style(wb, si, t, c), None => wb.styles.get(sh.style_id(c)).clone(), }; let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c)); diff --git a/crates/engine/src/tables.rs b/crates/engine/src/tables.rs index 9182cd4882..b2afdd350e 100644 --- a/crates/engine/src/tables.rs +++ b/crates/engine/src/tables.rs @@ -22,113 +22,259 @@ fn accent_for(n: u32) -> Option { if k == 0 { None } else { Some(3 + k as u8) } } -/// Header/band/body colours for a table style. +/// Fills, text colours and thin lines of a table style, per part of the table (the recipes in +/// plan/excel/table-style-spec.json). Band 1 is the first data row; unbanded rows use band 2. +#[derive(Clone, Copy, Debug, PartialEq)] pub struct TableLook { pub header_fill: Option, pub header_font: Color, - pub header_bold: bool, - pub band_fill: Option, - pub body_fill: Option, - pub line: Option, - pub total_top: Option, + pub band1: Option, + pub band2: Option, + pub body_font: Color, + pub top: Option, + pub header_bottom: Option, + pub inner_h: Option, + pub inner_v: Option, + pub sides: Option, + pub bottom: Option, + /// The totals row's double top rule (the gallery doesn't show totals). + pub total_top: Color, } pub fn look(style: &str) -> TableLook { let (fam, n) = parse_style_name(style); let acc = accent_for(n); - let base = |tint: i16| match acc { - Some(a) => Color::Theme(a, tint), - None => Color::Theme(1, if tint == 0 { 0 } else { tint.clamp(-1000, 1000) }), + // An accent tint, or the neutral column's colour. + let a = |tint: i16, neutral: Color| acc.map_or(neutral, |a| Color::Theme(a, tint)); + let (black, white) = (Color::Theme(1, 0), Color::Theme(0, 0)); + let (grey, mid_grey) = (Color::Theme(0, -150), Color::Theme(0, -350)); + let main = a(0, black); + let plain = TableLook { + header_fill: None, + header_font: black, + band1: None, + band2: None, + body_font: black, + top: None, + header_bottom: None, + inner_h: None, + inner_v: None, + sides: None, + bottom: None, + total_top: main, }; - let neutral_light = |tint: i16| match acc { - Some(a) => Color::Theme(a, tint), - None => Color::Theme(0, -((1000 - tint).clamp(0, 1000) / 6)), - }; - match fam { - "Light" => { - let group = (n - 1) / 7; // 0: lines only, 1: banded header line, 2: grid + match (fam, n.saturating_sub(1) / 7) { + ("Light", 0) => { + let text = a(-250, black); + let line = Some(main); + TableLook { header_font: text, body_font: text, band1: Some(a(800, grey)), top: line, header_bottom: line, bottom: line, ..plain } + } + ("Light", 1) => { + let line = Some(main); + TableLook { header_fill: line, header_font: white, top: line, inner_h: line, sides: line, bottom: line, ..plain } + } + ("Light", _) => { + let line = Some(main); + TableLook { band1: Some(a(800, grey)), top: line, header_bottom: line, inner_v: line, sides: line, bottom: line, ..plain } + } + ("Medium", 0) => { + let line = Some(a(400, black)); + TableLook { header_fill: Some(main), header_font: white, band1: Some(a(800, grey)), top: line, sides: line, bottom: line, ..plain } + } + ("Medium", 1) => TableLook { + header_fill: Some(main), + header_font: white, + band1: Some(a(600, mid_grey)), + band2: Some(a(800, grey)), + header_bottom: Some(white), + inner_v: Some(white), + ..plain + }, + ("Medium", 2) => { + // Accent header over neutral grey bands and black rules; the neutral style adds a grid. + let line = Some(black); + let grid = if acc.is_none() { line } else { None }; + let header_fill = Some(main); TableLook { - header_fill: None, - header_font: if group == 0 { base(-250) } else { Color::Auto }, - header_bold: true, - band_fill: Some(neutral_light(800)), - body_fill: None, - line: Some(base(0)), - total_top: Some(base(0)), + header_fill, + header_font: white, + band1: Some(grey), + top: line, + header_bottom: line, + inner_v: grid, + sides: grid, + bottom: line, + total_top: black, + ..plain } } - "Dark" => TableLook { - header_fill: Some(Color::Theme(1, 0)), - header_font: Color::Theme(0, 0), - header_bold: true, - band_fill: Some(base(-250)), - body_fill: Some(base(0)), - line: None, - total_top: Some(Color::Theme(0, 0)), - }, - _ => TableLook { - header_fill: Some(base(0)), - header_font: Color::Theme(0, 0), - header_bold: true, - band_fill: Some(neutral_light(800)), - body_fill: None, - line: if (n - 1) / 7 == 0 { None } else { Some(base(400)) }, - total_top: Some(base(0)), + ("Medium", _) => { + let line = Some(a(400, black)); + let pale = Some(a(800, grey)); + TableLook { header_fill: pale, band1: Some(a(600, mid_grey)), band2: pale, top: line, inner_v: line, sides: line, bottom: line, ..plain } + } + ("Dark", 0) => TableLook { + header_fill: Some(black), + header_font: white, + band1: Some(a(-250, Color::Theme(1, 250))), + band2: Some(a(0, Color::Theme(1, 450))), + body_font: white, + header_bottom: Some(white), + total_top: white, + ..plain }, + _ if n == 8 => TableLook { header_fill: Some(black), header_font: white, band1: Some(mid_grey), band2: Some(grey), ..plain }, + _ => { + // Dark 9-11 pair accents 1+2, 3+4 and 5+6: the header takes the even one. + let k = n.clamp(9, 11) as u8 - 8; + let (head, body) = (Color::Theme(3 + 2 * k, 0), 2 + 2 * k); + let band1 = Some(Color::Theme(body, 600)); + TableLook { header_fill: Some(head), header_font: white, band1, band2: Some(Color::Theme(body, 800)), total_top: head, ..plain } + } } } -/// The style a table gives a cell (merged over the cell's own style: explicit fills/fonts win). +/// Which parts of a table are on (the Table Style Options checkboxes). +#[derive(Clone, Copy, Debug)] +pub struct TableParts { + pub header_row: bool, + pub totals_row: bool, + pub banded_rows: bool, + pub banded_cols: bool, + pub first_col: bool, + pub last_col: bool, +} + +impl TableParts { + pub fn of(t: &Table) -> TableParts { + TableParts { + header_row: t.header_row, + totals_row: t.totals_row, + banded_rows: t.banded_rows, + banded_cols: t.banded_cols, + first_col: t.first_col, + last_col: t.last_col, + } + } +} + +/// What a table style paints on one cell of a `rows` x `cols` table (`row`, `col` from its +/// top-left). Each line has one owner: a horizontal line is a cell's bottom (top only on the +/// first row and the totals row), a vertical one a cell's right (left only on the first column). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CellLook { + pub fill: Option, + pub font: Color, + pub bold: bool, + pub borders: Borders, +} + +pub fn cell_look(lk: &TableLook, p: TableParts, row: u32, col: u32, rows: u32, cols: u32) -> CellLook { + let last_row = rows.saturating_sub(1); + let last_col = cols.saturating_sub(1); + let is_header = p.header_row && row == 0; + let is_total = p.totals_row && row == last_row && !is_header; + let thin = |c: Option| c.map(|color| BorderLine { style: BorderStyle::Thin, color }).unwrap_or_default(); + let mut b = Borders::default(); + if row == 0 { + b.top = thin(lk.top); + } + b.bottom = thin(if row == last_row { + lk.bottom + } else if is_header { + lk.header_bottom + } else if p.totals_row && row.saturating_add(1) == last_row { + None // the totals row draws its own top rule + } else { + lk.inner_h + }); + if col == 0 { + b.left = thin(lk.sides); + } + b.right = thin(if col == last_col { lk.sides } else { lk.inner_v }); + let mut out = CellLook { borders: b, font: lk.body_font, ..Default::default() }; + if is_header { + out.fill = lk.header_fill; + out.font = lk.header_font; + out.bold = true; + } else if is_total { + out.fill = lk.band2; + out.bold = true; + out.borders.top = BorderLine { style: BorderStyle::Double, color: lk.total_top }; + } else { + let data_row = row.saturating_sub(p.header_row as u32); + let band1 = (p.banded_rows && data_row.is_multiple_of(2)) || (p.banded_cols && col.is_multiple_of(2)); + out.fill = if band1 { lk.band1 } else { lk.band2 }; + } + if (p.first_col && col == 0) || (p.last_col && col == last_col) { + out.bold = true; + } + out +} + +/// The style a table gives a cell (merged over the cell's own style: explicit fills, fonts and +/// borders win). pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style { let own = wb.sheet(sheet).map(|sh| wb.styles.get(sh.style_id(c)).clone()).unwrap_or_default(); + let (start, end) = (t.range.start, t.range.end); + let rows = end.row.saturating_sub(start.row).saturating_add(1); + let cols = end.col.saturating_sub(start.col).saturating_add(1); + let lk = cell_look(&look(&t.style), TableParts::of(t), c.row.saturating_sub(start.row), c.col.saturating_sub(start.col), rows, cols); let mut s = own.clone(); - let lk = look(&t.style); - let is_header = t.header_row && c.row == t.range.start.row; - let is_total = t.totals_row && c.row == t.range.end.row; - let data_row = c.row.saturating_sub(t.range.start.row + t.header_row as u32); - let data_col = c.col - t.range.start.col; - let explicit_fill = own.fill.pattern != PatternType::None; - if is_header { - if let Some(f) = lk.header_fill - && !explicit_fill - { - s.fill = Fill::solid(f); - } - if own.font.color == Color::Auto { - s.font.color = lk.header_font; - } - s.font.bold = s.font.bold || lk.header_bold; - if let Some(l) = lk.line { - s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l }; - } - } else if is_total { - s.font.bold = true; - if let Some(l) = lk.total_top { - s.borders.top = BorderLine { style: BorderStyle::Double, color: l }; - } - } else { - let band = (t.banded_rows && data_row.is_multiple_of(2)) || (t.banded_cols && data_col.is_multiple_of(2)); - if !explicit_fill { - if band { - if let Some(f) = lk.band_fill { - s.fill = Fill::solid(f); - } - } else if let Some(f) = lk.body_fill { - s.fill = Fill::solid(f); - } - } - if let Some(l) = lk.line - && t.style.contains("Light") - && c.row == t.range.end.row - { - s.borders.bottom = BorderLine { style: BorderStyle::Thin, color: l }; + if let Some(f) = lk.fill + && own.fill.pattern == PatternType::None + { + s.fill = Fill::solid(f); + } + if own.font.color == Color::Auto { + s.font.color = lk.font; + } + s.font.bold = s.font.bold || lk.bold; + for (side, line) in [ + (&mut s.borders.top, lk.borders.top), + (&mut s.borders.bottom, lk.borders.bottom), + (&mut s.borders.left, lk.borders.left), + (&mut s.borders.right, lk.borders.right), + ] { + if side.is_none() { + *side = line; } } - if (t.first_col && c.col == t.range.start.col) || (t.last_col && c.col == t.range.end.col) { - s.font.bold = true; + s +} + +/// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the +/// table's outer frame follows hidden rows and columns: the last visible row takes the table's +/// bottom line, the last visible column its right side, and the first visible row and column its +/// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while +/// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is. +pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style { + let mut s = table_cell_style(wb, sheet, t, c); + let Some(sh) = wb.sheet(sheet) else { return s }; + let (start, end) = (t.range.start, t.range.end); + let row_gone = |r: u32| sh.row_height(r) <= 0.0; + let col_gone = |k: u32| sh.col_width(k) <= 0.0; + // Each check walks outward from the cell and stops at the first visible line, so the gaps + // scanned by different cells don't overlap. + let below = c.row < end.row && (c.row + 1..=end.row).all(row_gone); + let above = c.row > start.row && (start.row..c.row).rev().all(row_gone); + let right = c.col < end.col && (c.col + 1..=end.col).all(col_gone); + let left = c.col > start.col && (start.col..c.col).rev().all(col_gone); + if !(below || above || right || left) { + return s; } - if t.style.starts_with("TableStyleDark") && !is_header && own.font.color == Color::Auto { - s.font.color = Color::Theme(0, 0); + let own = wb.styles.get(sh.style_id(c)).borders; + if below && own.bottom.is_none() { + s.borders.bottom = table_cell_style(wb, sheet, t, CellRef::new(end.row, c.col)).borders.bottom; + } + if above && own.top.is_none() { + s.borders.top = table_cell_style(wb, sheet, t, CellRef::new(start.row, c.col)).borders.top; + } + if right && own.right.is_none() { + s.borders.right = table_cell_style(wb, sheet, t, CellRef::new(c.row, end.col)).borders.right; + } + if left && own.left.is_none() { + s.borders.left = table_cell_style(wb, sheet, t, CellRef::new(c.row, start.col)).borders.left; } s } diff --git a/crates/engine/tests/table_style_looks.rs b/crates/engine/tests/table_style_looks.rs new file mode 100644 index 0000000000..366a89c679 --- /dev/null +++ b/crates/engine/tests/table_style_looks.rs @@ -0,0 +1,240 @@ +//! Table styles look like the Format as Table gallery: every row of the gallery (Light 1-7, 8-14, +//! 15-21, Medium 1-7, …) has its own fills and lines, as recorded in plan/excel/table-style-spec.json. + +use gridcraft_core::CellRef; +use gridcraft_engine::Session; +use gridcraft_engine::model::*; +use gridcraft_engine::tables::{table_cell_shown_style, table_cell_style}; +use serde_json::json; + +const ROWS: u32 = 6; // header + 5 data rows +const COLS: u32 = 5; + +fn session() -> Session { + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["a", "b", "c", "d", "e"]]})).unwrap(); + s.execute("insert.table", json!({"range": "A1:E6", "header": true})).unwrap(); + s +} + +/// The look of every cell of a 6x5 table (header on, banded rows) in `style`, row by row. +fn grid_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec> { + let wb = &s.doc().unwrap().wb; + let mut t = wb.sheet(0).unwrap().tables[0].clone(); + t.style = format!("TableStyle{style}"); + edit(&mut t); + (0..ROWS).map(|r| (0..COLS).map(|c| table_cell_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect() +} + +fn grid(style: &str) -> Vec> { + grid_with(&session(), style, |_| {}) +} + +fn thin(color: Color) -> BorderLine { + BorderLine { style: BorderStyle::Thin, color } +} + +const NONE: BorderLine = BorderLine { style: BorderStyle::None, color: Color::Auto }; +const BLACK: Color = Color::Theme(1, 0); +const WHITE: Color = Color::Theme(0, 0); + +#[test] +fn each_row_of_the_gallery_has_its_own_look() { + // Same accent (or neutral) across the gallery's rows, so only the row-group differs. + for set in [ + &["Light1", "Light8", "Light15", "Medium1", "Medium8", "Medium15", "Medium22", "Dark1", "Dark8"][..], + &["Light2", "Light9", "Light16", "Medium2", "Medium9", "Medium16", "Medium23", "Dark2", "Dark9"][..], + ] { + let looks: Vec<_> = set.iter().map(|s| grid(s)).collect(); + for (i, a) in looks.iter().enumerate() { + for (j, b) in looks.iter().enumerate().skip(i + 1) { + assert_ne!(a, b, "{} and {} look the same", set[i], set[j]); + } + } + } +} + +#[test] +fn neutral_bands_are_visibly_grey() { + let theme = Theme::default(); + let fill = |style: &str, row: usize| grid(style)[row][0].fill.fg.resolve(&theme).unwrap(); + // lt1 -150 (about #D9D9D9) and lt1 -350 (about #A6A6A6). + for ch in fill("Light1", 1) { + assert!((210..=225).contains(&ch), "Light1 band {:?}", fill("Light1", 1)); + } + for ch in fill("Medium8", 1) { + assert!((160..=172).contains(&ch), "Medium8 band1 {:?}", fill("Medium8", 1)); + } +} + +#[test] +fn light15_has_a_vertical_grid_and_no_row_lines() { + let g = grid("Light15"); + assert_eq!(g[0][0].borders.top, thin(BLACK)); + assert_eq!(g[0][2].borders.bottom, thin(BLACK), "header bottom"); + assert_eq!(g[2][1].borders.right, thin(BLACK), "inner vertical"); + assert_eq!(g[0][1].borders.right, thin(BLACK), "inner vertical in the header"); + assert_eq!(g[2][0].borders.left, thin(BLACK), "left side"); + assert_eq!(g[2][4].borders.right, thin(BLACK), "right side"); + assert_eq!(g[5][2].borders.bottom, thin(BLACK), "bottom"); + assert_eq!(g[2][1].borders.bottom, NONE, "no inner horizontal"); + assert_eq!(g[2][1].borders.top, NONE, "no inner horizontal"); + assert_eq!(g[1][0].fill.fg, Color::Theme(0, -150)); +} + +#[test] +fn medium2_has_a_pale_accent_frame_and_no_row_lines() { + let g = grid("Medium2"); + let line = thin(Color::Theme(4, 400)); + assert_eq!(g[0][0].fill.fg, Color::Theme(4, 0)); + assert_eq!(g[0][0].font.color, WHITE); + assert_eq!(g[0][2].borders.top, line); + assert_eq!(g[0][0].borders.left, line, "the sides run down the header too"); + assert_eq!(g[3][0].borders.left, line); + assert_eq!(g[3][4].borders.right, line); + assert_eq!(g[5][2].borders.bottom, line); + assert_eq!(g[0][2].borders.bottom, NONE, "no header bottom"); + assert_eq!(g[2][2].borders.bottom, NONE, "no inner horizontal"); + assert_eq!(g[2][2].borders.right, NONE, "no inner vertical"); + assert_eq!(g[1][2].fill.fg, Color::Theme(4, 800)); + assert_eq!(g[2][2].fill.pattern, PatternType::None); +} + +#[test] +fn medium9_has_white_verticals_and_header_bottom() { + let g = grid("Medium9"); + assert_eq!(g[0][1].borders.bottom, thin(WHITE)); + assert_eq!(g[0][1].borders.right, thin(WHITE)); + assert_eq!(g[3][1].borders.right, thin(WHITE)); + assert_eq!(g[3][1].borders.bottom, NONE); + assert_eq!(g[3][0].borders.left, NONE, "no frame"); + assert_eq!(g[5][4].borders.bottom, NONE, "no frame"); + assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600)); + assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800)); +} + +#[test] +fn dark2_bands_in_shaded_and_full_accent_under_a_black_header() { + let g = grid("Dark2"); + assert_eq!(g[0][0].fill.fg, BLACK); + assert_eq!(g[0][0].borders.bottom, thin(WHITE)); + assert_eq!(g[1][0].fill.fg, Color::Theme(4, -250)); + assert_eq!(g[2][0].fill.fg, Color::Theme(4, 0)); + assert_eq!(g[2][0].font.color, WHITE); + assert_eq!(g[2][0].borders, Borders::default()); +} + +#[test] +fn dark9_pairs_two_accents() { + let g = grid("Dark9"); + assert_eq!(g[0][0].fill.fg, Color::Theme(5, 0)); + assert_eq!(g[0][0].font.color, WHITE); + assert_eq!(g[1][0].fill.fg, Color::Theme(4, 600)); + assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800)); + assert_eq!(g[2][0].font.color, BLACK); + let g = grid("Dark11"); + assert_eq!(g[0][0].fill.fg, Color::Theme(9, 0)); + assert_eq!(g[1][0].fill.fg, Color::Theme(8, 600)); +} + +#[test] +fn table_options_change_the_look() { + let s = session(); + // Banded rows off: every data row looks like the second band. + let g = grid_with(&s, "Medium9", |t| t.banded_rows = false); + assert_eq!(g[1][0].fill.fg, Color::Theme(4, 800)); + assert_eq!(g[2][0].fill.fg, Color::Theme(4, 800)); + // Banded columns alternate by column. + let g = grid_with(&s, "Medium9", |t| { + t.banded_rows = false; + t.banded_cols = true; + }); + assert_eq!(g[2][0].fill.fg, Color::Theme(4, 600)); + assert_eq!(g[2][1].fill.fg, Color::Theme(4, 800)); + // Header off: the top line moves to the first data row, and nothing is drawn as a header. + let g = grid_with(&s, "Light15", |t| t.header_row = false); + assert_eq!(g[0][2].borders.top, thin(BLACK)); + assert_eq!(g[0][2].borders.bottom, NONE); + assert!(!g[0][2].font.bold); + // Totals row: bold, double top rule, no banding. + let g = grid_with(&s, "Medium2", |t| t.totals_row = true); + assert!(g[5][1].font.bold); + assert_eq!(g[5][1].borders.top, BorderLine { style: BorderStyle::Double, color: Color::Theme(4, 0) }); + assert_eq!(g[5][1].borders.bottom, thin(Color::Theme(4, 400))); + // First and last column bold. + let g = grid_with(&s, "Medium2", |t| { + t.first_col = true; + t.last_col = true; + }); + assert!(g[2][0].font.bold && g[2][4].font.bold && !g[2][2].font.bold); +} + +#[test] +fn explicit_formatting_wins() { + let mut s = session(); + s.execute("home.fillColor", json!({"range": "B3", "color": "#FF0000"})).unwrap(); + s.execute("home.fontColor", json!({"range": "B3", "color": "#00FF00"})).unwrap(); + s.execute("home.borders", json!({"range": "B3", "preset": "bottom"})).unwrap(); + let g = grid_with(&s, "Dark2", |_| {}); + assert_eq!(g[2][1].fill, Fill::solid(Color::Rgb(0xFF0000))); + assert_eq!(g[2][1].font.color, Color::Rgb(0x00FF00)); + assert_eq!(g[2][1].borders.bottom.style, BorderStyle::Thin); + assert_eq!(g[2][1].borders.bottom.color, Color::Auto); +} + +#[test] +fn every_style_name_is_safe() { + for name in ["Light0", "Light99", "Medium0", "Medium4000000000", "Dark0", "Dark12", "Dark99", "Bogus"] { + let _ = grid(name); + } +} + +/// What the grid and print draw: like `grid_with`, but through the hidden-row/column aware +/// `table_cell_shown_style`. +fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec> { + let wb = &s.doc().unwrap().wb; + let mut t = wb.sheet(0).unwrap().tables[0].clone(); + t.style = format!("TableStyle{style}"); + edit(&mut t); + (0..ROWS).map(|r| (0..COLS).map(|c| table_cell_shown_style(wb, 0, &t, CellRef::new(r, c))).collect()).collect() +} + +#[test] +fn frame_follows_the_last_visible_row_and_column() { + let frame = thin(Color::Theme(4, 400)); + // Nothing hidden: the shown look is the table look. + let s = session(); + assert_eq!(shown_with(&s, "Medium2", |_| {}), grid_with(&s, "Medium2", |_| {})); + // Last data row (and the one before it) and last column hidden: the frame moves in. + let mut s = session(); + s.execute("home.hideRows", json!({"rows": "5:6"})).unwrap(); + s.execute("home.hideColumns", json!({"cols": "E:E"})).unwrap(); + let g = shown_with(&s, "Medium2", |_| {}); + for (c, cell) in g[3].iter().take(4).enumerate() { + assert_eq!(cell.borders.bottom, frame, "bottom frame on row 4, col {c}"); + } + for (r, row) in g.iter().take(4).enumerate() { + assert_eq!(row[3].borders.right, frame, "right frame on col D, row {r}"); + } + // Rows above the last visible one keep their inner look (Medium 2 has no row lines). + assert_eq!(g[2][1].borders.bottom, NONE); + // Convert to Range and friends still see the table as it is. + assert_eq!(grid_with(&s, "Medium2", |_| {})[3][1].borders.bottom, NONE); + // Header off and the first data row filtered out: the top line moves down. + let mut s = session(); + s.execute("home.hideRows", json!({"rows": "1:1"})).unwrap(); + s.execute("home.hideColumns", json!({"cols": "A:A"})).unwrap(); + let g = shown_with(&s, "Light15", |t| t.header_row = false); + assert_eq!(g[1][2].borders.top, thin(BLACK)); + assert_eq!(g[2][1].borders.left, thin(BLACK)); + // Explicit borders still win. + let mut s = session(); + s.execute("home.borders", json!({"range": "B5", "preset": "none"})).unwrap(); + s.execute("home.fillColor", json!({"range": "B5", "color": "#FF0000"})).unwrap(); + s.execute("home.borders", json!({"range": "C5", "preset": "bottom"})).unwrap(); + s.execute("home.hideRows", json!({"rows": "6:6"})).unwrap(); + let g = shown_with(&s, "Medium2", |_| {}); + assert_eq!(g[4][1].borders.bottom, frame); + assert_eq!(g[4][2].borders.bottom.color, Color::Auto); +} diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index a0efbfae7a..b5d632a535 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -450,7 +450,7 @@ fn center_across_end(start: u32, limit: u32, continues: impl Fn(u32) -> bool) -> fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option) { let mut style = wb.styles.get(sh.style_id(c)).clone(); if let Some(t) = sh.table_at(c) { - style = gridcraft_engine::tables::table_cell_style(wb, si, t, c); + style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, c); } let cfl = cf.look(wb, si, c); if let Some(l) = &cfl diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 356381d661..faf3cac7ff 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1386,35 +1386,41 @@ fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) { } } +/// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from +/// the same look the grid uses. fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) { - let lk = gridcraft_engine::tables::look(style); - let res = |c: Option| c.and_then(|c| c.resolve(&wb.theme)).map(theme::color32); + use gridcraft_engine::tables::{TableParts, cell_look, look}; + let lk = look(style); + let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false }; + let res = |c: gridcraft_engine::model::Color| c.resolve(&wb.theme).map(theme::color32); + let line = |l: gridcraft_engine::model::BorderLine| if l.is_none() { None } else { Some(res(l.color).unwrap_or(Color32::BLACK)) }; let p = ui.painter(); p.rect_filled(r, 0.0, Color32::WHITE); - let rows = 5; - let rh = r.height() / rows as f32; - for i in 0..rows { - let rr = Rect::from_min_size(pos2(r.left(), r.top() + i as f32 * rh), vec2(r.width(), rh)); - let fill = if i == 0 { - res(lk.header_fill) - } else if i % 2 == 1 { - res(lk.band_fill) - } else { - res(lk.body_fill) - }; - if let Some(f) = fill { - p.rect_filled(rr, 0.0, f); - } - if let Some(l) = res(lk.line) { - p.line_segment([rr.left_bottom(), rr.right_bottom()], Stroke::new(1.0, l)); - } - for k in 0..3 { - let x = rr.left() + 4.0 + k as f32 * (r.width() - 8.0) / 3.0; - let col = if i == 0 { res(Some(lk.header_font)).unwrap_or(Color32::BLACK) } else { Color32::from_gray(120) }; - p.line_segment([pos2(x, rr.center().y), pos2(x + 10.0, rr.center().y)], Stroke::new(1.0, col)); + let n = 5u32; + let (cw, rh) = (r.width() / n as f32, r.height() / n as f32); + for row in 0..n { + for col in 0..n { + let cr = Rect::from_min_size(pos2(r.left() + col as f32 * cw, r.top() + row as f32 * rh), vec2(cw, rh)); + let cl = cell_look(&lk, parts, row, col, n, n); + if let Some(f) = cl.fill.and_then(res) { + p.rect_filled(cr, 0.0, f); + } + let dash = res(cl.font).unwrap_or(Color32::BLACK); + let y = cr.center().y; + p.line_segment([pos2(cr.left() + 2.0, y), pos2(cr.right() - 2.0, y)], Stroke::new(1.0, dash)); + let b = cl.borders; + for (side, edge) in [ + (b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))), + (b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())), + (b.left, Rect::from_min_max(cr.left_top(), pos2(cr.left() + 1.0, cr.bottom()))), + (b.right, Rect::from_min_max(pos2(cr.right() - 1.0, cr.top()), cr.right_bottom())), + ] { + if let Some(c) = line(side) { + p.rect_filled(edge, 0.0, c); + } + } } } - p.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_gray(210)), StrokeKind::Inside); } fn cell_style_gallery(app: &mut SheetApp, ui: &mut Ui) { From 653517466404c7d00170054c1d04dbcfab32b391 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:02:30 +0200 Subject: [PATCH 032/201] XLSX: write spilled text as cached strings, not shared strings (#2285) --- crates/xlsx/src/sheet_write.rs | 5 +++++ crates/xlsx/src/tests/array_export.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/xlsx/src/sheet_write.rs b/crates/xlsx/src/sheet_write.rs index daac03daaa..4c496e9aca 100644 --- a/crates/xlsx/src/sheet_write.rs +++ b/crates/xlsx/src/sheet_write.rs @@ -742,6 +742,11 @@ fn write_cell( Value::Number(n) => { let _ = write!(s, ">{}", num(*n)); } + // Text inside a spill or array range is a cached formula result: Excel writes it as `t="str"` + // and shows #VALUE! for a shared string there when it trusts the saved values. + Value::Text(t) if extra.is_some() => { + let _ = write!(s, " t=\"str\">{}", esc(&encode_xstring(t))); + } Value::Text(t) => { let i = out.sst.index(t); let _ = write!(s, " t=\"s\">{i}"); diff --git a/crates/xlsx/src/tests/array_export.rs b/crates/xlsx/src/tests/array_export.rs index 646bd1db3c..b8a36924aa 100644 --- a/crates/xlsx/src/tests/array_export.rs +++ b/crates/xlsx/src/tests/array_export.rs @@ -480,3 +480,24 @@ fn long_flat_chains_are_scalar_formulas() { assert_dynamic(&sheet, "B4", "B4"); assert_eq!(cell(&sheet, "B1").child("f").unwrap().text, refs); } + +#[test] +fn spilled_text_is_written_as_a_cached_string_not_a_shared_string() { + let mut wb = Workbook::new(); + let sh = wb.sheet_mut(0).unwrap(); + let mut anchor = Cell::formula(Formula::new("SORT({\"b\";\"a\";\"c\"})")); + anchor.value = Value::text("a"); + sh.cells.set(at("K4"), anchor); + sh.spill_ranges.insert(at("K4"), range("K4:K6")); + sh.spill.insert(at("K5"), Value::text("b")); + sh.spill.insert(at("K6"), Value::text("c")); + + let bytes = write_xlsx(&wb).unwrap(); + let mut pkg = Package::open(&bytes).unwrap(); + let sheet = pkg.read_xml("xl/worksheets/sheet1.xml").unwrap().unwrap(); + for (address, text) in [("K4", "a"), ("K5", "b"), ("K6", "c")] { + let c = cell(&sheet, address); + assert_eq!(c.attr("t"), Some("str"), "{address}"); + assert_eq!(c.child("v").unwrap().text, text, "{address}"); + } +} From edd64e9afc0965320868f113afa6404f5739c63d Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 00:47:02 +0200 Subject: [PATCH 033/201] View: zooming is not an undo step (fixes #2313) --- crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/cmd/view.rs | 71 +++++++++++++++++++- crates/engine/tests/command_sequence_fuzz.rs | 5 +- 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e537407127..21421902f0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -660,6 +660,7 @@ fn undo(s: &mut Session, p: &Json) -> Result { crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); + super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"undone": label})) @@ -680,6 +681,7 @@ fn redo(s: &mut Session, p: &Json) -> Result { crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); + super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"redone": label})) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index f0b2f77d39..9af8941852 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -37,13 +37,13 @@ pub fn specs() -> Vec { cmd!("view.showZeros", "Show Zeros", [], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "zeros")), cmd!("view.showObjects", "Show Objects", [], Some("Ctrl+6"), "{on?}", has_doc, show_objects), cmd!("view.rightToLeft", "Sheet Right-to-Left", ["Page Layout", "Sheet Options"], None, "{on?}", has_doc, |s, p| sheet_flag(s, p, "rtl")), - cmd!("view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom), - cmd!("view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))), + cmd!(noundo "view.zoom", "Zoom", ["View", "Zoom"], None, "{percent: 10..400}", has_doc, zoom), + cmd!(noundo "view.zoom100", "100%", ["View", "Zoom"], None, "{}", has_doc, |s, _| zoom(s, &json!({"percent": 100}))), cmd!(query "view.formulaBar", "Formula Bar", ["View", "Show"], None, "{on?: bool}", always, |s, p| { s.prefs.formula_bar = bool_param(p, "on").unwrap_or(!s.prefs.formula_bar); Ok(json!({"on": s.prefs.formula_bar})) }), - cmd!("view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection), + cmd!(noundo "view.zoomToSelection", "Zoom to Selection", ["View", "Zoom"], None, "{viewWidth?, viewHeight?}", has_doc, zoom_selection), cmd!("pageLayout.orientation", "Orientation", ["Page Layout", "Page Setup"], None, "{orientation: portrait|landscape}", has_doc, orientation), cmd!( "pageLayout.size", @@ -200,6 +200,28 @@ fn zoom(s: &mut Session, p: &Json) -> Result { Ok(json!({"zoom": z})) } +/// Zoom belongs to the window, not to the edits (Excel doesn't undo it, #2313): undo and redo keep +/// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved +/// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`. +pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) { + let current = |name: &str| now.sheets.iter().find(|sh| sh.name == name).map(|sh| sh.zoom); + let changed: Vec<(usize, u16)> = + d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(&sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); + if changed.is_empty() { + return; + } + let saved = std::sync::Arc::ptr_eq(&d.wb, &d.saved); + let wb = std::sync::Arc::make_mut(&mut d.wb); + for (i, z) in changed { + if let Some(sh) = wb.sheet_mut(i) { + sh.zoom = z; + } + } + if saved { + d.saved = d.wb.clone(); + } +} + fn zoom_selection(s: &mut Session, p: &Json) -> Result { let d = s.doc()?; let sh = d.wb.active().ok_or(EngineError::NoDocument)?; @@ -466,6 +488,49 @@ mod tests { assert_eq!(s.doc().unwrap().wb.active().unwrap().zoom, 100); } + #[test] + fn zooming_is_not_an_undo_step() { + // Excel keeps zoom on the window, not in the edit history (#2313): wheel, slider, dialog, + // 100% and Zoom to Selection leave Undo and Redo alone. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("cell.set", json!({"cell": "A2", "input": "y"})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + let (undo, redo) = s.doc().map(|d| (d.undo.len(), d.redo.len())).unwrap(); + for (id, params, zoom) in [ + ("view.zoom", json!({"percent": 150}), 150), + ("view.zoomToSelection", json!({"viewWidth": 1200, "viewHeight": 700}), 400), + ("view.zoom100", json!({}), 100), + ] { + s.execute(id, params).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.wb.active().unwrap().zoom, zoom, "{id}"); + assert_eq!((d.undo.len(), d.redo.len()), (undo, redo), "{id} touched the history"); + } + let a1 = CellRef::parse("A1").unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().value(a1).is_empty(), "Ctrl+Z after zooming undoes the last edit"); + } + + #[test] + fn undo_and_redo_keep_the_current_zoom() { + let mut s = Session::new(); + s.new_workbook(); + let zoom = |s: &Session| s.doc().unwrap().wb.active().unwrap().zoom; + s.execute("cell.set", json!({"cell": "A1", "input": "x"})).unwrap(); + s.execute("view.zoom", json!({"percent": 200})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty()); + assert_eq!(zoom(&s), 200, "undo keeps the zoom"); + // Back at the state on disk: the zoom alone doesn't make the workbook dirty, as in `zoom`. + assert!(!s.doc().unwrap().is_dirty()); + s.execute("view.zoom", json!({"percent": 50})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert!(!s.doc().unwrap().wb.active().unwrap().value(CellRef::parse("A1").unwrap()).is_empty()); + assert_eq!(zoom(&s), 50, "redo keeps the zoom"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); diff --git a/crates/engine/tests/command_sequence_fuzz.rs b/crates/engine/tests/command_sequence_fuzz.rs index f8cb603cba..4ed7dc0428 100644 --- a/crates/engine/tests/command_sequence_fuzz.rs +++ b/crates/engine/tests/command_sequence_fuzz.rs @@ -485,8 +485,8 @@ fn watch_list(wb: &Workbook) -> Option<&str> { wb.names.iter().find(|n| n.name == WATCH_NAME).map(|n| n.formula.as_str()) } -/// The workbook with view state (active sheet, scroll, active cell) and the Watch Window list -/// reset: undo restores view state as it was, but switching sheets isn't an undoable edit. +/// The workbook with view state (active sheet, scroll, active cell, zoom) and the Watch Window list +/// reset: undo restores view state as it was, but switching sheets or zooming isn't an undoable edit. fn canonical(wb: &Workbook) -> Workbook { let mut wb = wb.clone(); wb.active_sheet = 0; @@ -495,6 +495,7 @@ fn canonical(wb: &Workbook) -> Workbook { let sh = Arc::make_mut(sh); sh.view_active = CellRef::default(); sh.view_top_left = CellRef::default(); + sh.zoom = 100; } wb } From cbe10f0501bcf41f25b485e34e5f9c246de63bfb Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Thu, 22 Oct 2026 21:37:28 -0300 Subject: [PATCH 034/201] Recalc: clearing an array frees its whole spill area for a blocked array Clearing (or overwriting) a dynamic array's anchor empties its whole former spill area, but only arrays above and left of the anchor were re-evaluated, so an array blocked further right (F13 against C14's C14:I14) stayed #SPILL! until the next full recalculation. Reported by iluebbe on #964. --- ROADMAP.md | 2 +- crates/calc/src/recalc.rs | 7 +++++++ crates/engine/src/tests.rs | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index 83e83c51e5..ac6c7f2018 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -158,7 +158,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-13 | XLSX export writes a picture used on several sheets once, as one `xl/media` part every drawing points to (it wrote a copy per drawing: a 16-sheet workbook with one 112 KB logo grew from 0.4 to 1.9 MB) (#985) | | 2026-10-13 | XLSX: `[Content_Types].xml`, `_rels/.rels`, the workbook rels and `xl/workbook.xml` are the first zip entries (document properties last), so libmagic and PHP `finfo` detect the file type even with large properties (#1090) | | 2026-10-13 | Conditional formatting: a rule gathers range statistics only when it reads them (top/bottom, above average, duplicates, scales, bars, icons) and borrows them instead of copying them per cell, so the per-frame lookup of an expression or cell-value rule no longer visits its whole range (#1098, part 1) | -| 2026-10-13 | Spills: when two dynamic arrays want the same cells, the one already spilling there keeps them after Calculate Now and after saving and reopening, as when the second was entered (#964, found by the command-sequence fuzz) | +| 2026-10-13 | Spills: when two dynamic arrays want the same cells, the one already spilling there keeps them after Calculate Now and after saving and reopening, as when the second was entered; clearing it lets the other spill at once (#964, found by the command-sequence fuzz) | | 2026-10-12 | Next/previous sheet navigation stops at the first/last visible worksheet instead of activating a hidden boundary sheet; the current selection is retained | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index f2aefe6765..ff3a977506 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -1018,6 +1018,13 @@ impl Calc { } } } + // A cleared anchor empties its whole former spill area too. + for (si, r) in &cleared { + match emptied.iter_mut().find(|x| x.0 == *si) { + Some(x) => x.1 = CellRef::new(x.1.row.max(r.end.row), x.1.col.max(r.end.col)), + None => emptied.push((*si, r.end)), + } + } // An emptied cell can unblock an anchor any distance above or to the left of it. for (si, end) in emptied { for &(s, c) in self.graph.nodes.keys() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a2b95fc84a..728ed0d1c8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2472,6 +2472,20 @@ fn a_spill_that_goes_away_unblocks_another() { assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0))); } +#[test] +fn clearing_the_array_that_holds_a_contested_area_lets_the_other_spill() { + // F13's array wants F14:G14, inside C14's spill C14:I14. Clearing C14 empties the whole + // area, to the right of C14 too, so F13 spills straight away, as in Excel. + let mut s = s(); + s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap(); + s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap(); + assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill)); + s.execute("edit.clearContents", json!({"range": "C14"})).unwrap(); + assert_eq!((v(&s, "F13"), v(&s, "G17")), (Value::Number(1.0), Value::Number(10.0))); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((v(&s, "F13"), v(&s, "I14")), (Value::Error(gridcraft_core::CellError::Spill), Value::Number(7.0))); +} + #[test] fn a_contested_spill_area_stays_with_its_array_after_reopening() { // F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file From c2457bdb8c250fc9c704ac66a2a98c681965ad62 Mon Sep 17 00:00:00 2001 From: "D. Fender" <26173007+postfen@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:09:38 -0700 Subject: [PATCH 035/201] Tables: Find a table's visible edges once per paint The grid and print checked, for every painted table cell, whether all rows and columns between it and the table's edge were hidden. On a big filtered table that rescans the hidden rows for every cell. shown_edges() now finds a table's first and last visible row and column, and the per-paint CfCache keeps it for each table. Print now always keeps a CfCache. --- crates/engine/src/cf.rs | 9 +++++- crates/engine/src/cmd/print.rs | 10 +++---- crates/engine/src/tables.rs | 38 ++++++++++++++++++------ crates/engine/tests/table_style_looks.rs | 7 +++-- crates/ui-egui/src/grid.rs | 2 +- 5 files changed, 48 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index 425e5264e7..331953288e 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -20,10 +20,12 @@ pub struct CfLook { pub hide_value: bool, } -/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates). +/// Precomputed statistics per rule (min/max/percentiles/top-N thresholds/duplicates), and each +/// table's visible edges. The grid and print keep one per paint. #[derive(Default)] pub struct CfCache { stats: HashMap, + table_edges: HashMap, } #[derive(Default, Clone)] @@ -141,6 +143,11 @@ impl CfCache { Self::default() } + /// [`crate::tables::shown_edges`] of `t`, found once per cache. + pub fn table_edges(&mut self, sh: &Sheet, t: &Table) -> crate::tables::ShownEdges { + *self.table_edges.entry(t.range).or_insert_with(|| crate::tables::shown_edges(sh, t)) + } + /// Conditional look of `c`, or `None` when no rule applies. pub fn look(&mut self, wb: &Workbook, sheet: usize, c: CellRef) -> Option { let sh = wb.sheet(sheet)?; diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index ba115e63e2..3a7dc3fa8c 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -634,12 +634,12 @@ struct Look { cf: Option, } -fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut Option) -> Look { +fn cell_look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut crate::cf::CfCache) -> Look { let mut style = match sh.table_at(c) { - Some(t) => crate::tables::table_cell_shown_style(wb, si, t, c), + Some(t) => crate::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c), None => wb.styles.get(sh.style_id(c)).clone(), }; - let cfl = cf.as_mut().and_then(|cache| cache.look(wb, si, c)); + let cfl = cf.look(wb, si, c); if let Some(st) = cfl.as_ref().and_then(|l| l.style.as_ref()) { if st.fill.pattern != PatternType::None { style.fill = st.fill; @@ -882,7 +882,7 @@ fn font_for(style: &Style) -> Font { } /// Draws the cells of a block: fills, gridlines, data bars, borders and text. -fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut Option) { +fn draw_block(pg: &mut Page, b: &Block, gridlines: bool, cf: &mut crate::cf::CfCache) { let (bx, by) = (b.xs.first().copied().unwrap_or(0.0), b.ys.first().copied().unwrap_or(0.0)); let (bw, bh) = (b.xs.last().copied().unwrap_or(bx) - bx, b.ys.last().copied().unwrap_or(by) - by); if bw <= 0.0 || bh <= 0.0 { @@ -1530,7 +1530,7 @@ pub fn render_pdf(wb: &Workbook, layouts: &[SheetLayout], file: &str, path: &str let mut printed_blocks = Vec::new(); for lay in layouts { let Some(sh) = wb.sheet(lay.sheet) else { continue }; - let mut cf = if sh.cond_formats.is_empty() { None } else { Some(crate::cf::CfCache::new()) }; + let mut cf = crate::cf::CfCache::new(); let k = lay.k(); let (aw, ah) = lay.avail(); for (pi, (ri, ci)) in lay.pages.iter().enumerate() { diff --git a/crates/engine/src/tables.rs b/crates/engine/src/tables.rs index b2afdd350e..42da29e54a 100644 --- a/crates/engine/src/tables.rs +++ b/crates/engine/src/tables.rs @@ -243,23 +243,43 @@ pub fn table_cell_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> S s } +/// A table's first and last visible row and column (hidden or filtered lines skipped). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ShownEdges { + pub top: u32, + pub bottom: u32, + pub left: u32, + pub right: u32, +} + +/// Finds [`ShownEdges`]. It scans the hidden lines at each edge, so the grid and print call it +/// once per table per paint (through [`crate::cf::CfCache::table_edges`]), not once per cell. +pub fn shown_edges(sh: &Sheet, t: &Table) -> ShownEdges { + let (start, end) = (t.range.start, t.range.end); + let row_shown = |r: &u32| sh.row_height(*r) > 0.0; + let col_shown = |k: &u32| sh.col_width(*k) > 0.0; + // With every row (or column) hidden, each cell takes both edges' lines; nothing is drawn. + ShownEdges { + top: (start.row..=end.row).find(row_shown).unwrap_or(end.row), + bottom: (start.row..=end.row).rev().find(row_shown).unwrap_or(start.row), + left: (start.col..=end.col).find(col_shown).unwrap_or(end.col), + right: (start.col..=end.col).rev().find(col_shown).unwrap_or(start.col), + } +} + /// The style the grid and print draw for a table cell. Like [`table_cell_style`], but the /// table's outer frame follows hidden rows and columns: the last visible row takes the table's /// bottom line, the last visible column its right side, and the first visible row and column its /// top line and left side. (Each frame line is owned by the edge cell, which is never drawn while /// it is hidden or filtered out.) Convert to Range uses [`table_cell_style`], the table as it is. -pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, c: CellRef) -> Style { +pub fn table_cell_shown_style(wb: &Workbook, sheet: usize, t: &Table, e: ShownEdges, c: CellRef) -> Style { let mut s = table_cell_style(wb, sheet, t, c); let Some(sh) = wb.sheet(sheet) else { return s }; let (start, end) = (t.range.start, t.range.end); - let row_gone = |r: u32| sh.row_height(r) <= 0.0; - let col_gone = |k: u32| sh.col_width(k) <= 0.0; - // Each check walks outward from the cell and stops at the first visible line, so the gaps - // scanned by different cells don't overlap. - let below = c.row < end.row && (c.row + 1..=end.row).all(row_gone); - let above = c.row > start.row && (start.row..c.row).rev().all(row_gone); - let right = c.col < end.col && (c.col + 1..=end.col).all(col_gone); - let left = c.col > start.col && (start.col..c.col).rev().all(col_gone); + let below = c.row < end.row && c.row >= e.bottom; + let above = c.row > start.row && c.row <= e.top; + let right = c.col < end.col && c.col >= e.right; + let left = c.col > start.col && c.col <= e.left; if !(below || above || right || left) { return s; } diff --git a/crates/engine/tests/table_style_looks.rs b/crates/engine/tests/table_style_looks.rs index 366a89c679..64bfd2d55f 100644 --- a/crates/engine/tests/table_style_looks.rs +++ b/crates/engine/tests/table_style_looks.rs @@ -4,7 +4,7 @@ use gridcraft_core::CellRef; use gridcraft_engine::Session; use gridcraft_engine::model::*; -use gridcraft_engine::tables::{table_cell_shown_style, table_cell_style}; +use gridcraft_engine::tables::{ShownEdges, shown_edges, table_cell_shown_style, table_cell_style}; use serde_json::json; const ROWS: u32 = 6; // header + 5 data rows @@ -197,7 +197,8 @@ fn shown_with(s: &Session, style: &str, edit: impl Fn(&mut Table)) -> Vec bool) -> fn look(wb: &Workbook, si: usize, sh: &Sheet, c: CellRef, cf: &mut CfCache) -> (Look, Option) { let mut style = wb.styles.get(sh.style_id(c)).clone(); if let Some(t) = sh.table_at(c) { - style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, c); + style = gridcraft_engine::tables::table_cell_shown_style(wb, si, t, cf.table_edges(sh, t), c); } let cfl = cf.look(wb, si, c); if let Some(l) = &cfl From b9324d91796fc91b53c7e4042de021dcc2cddafc Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Fri, 23 Oct 2026 09:13:27 +0200 Subject: [PATCH 036/201] Formula entry: text that would read as a formula is edited with its apostrophe `text_needs_quote_prefix` still used the old rule (a sign followed by a letter or `(`), so text such as `+5+4` (typed as `'+5+4`, or read from a CSV or XLSX) was edited without its apostrophe and became a formula when confirmed unchanged. It now asks what `input_to_cell` asks: the entry starts a formula and parses as one. Text that stays text anyway (`--`) is still edited as it is. Found by @iluebbe in #2023. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/display.rs | 10 +++++++--- crates/engine/src/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/display.rs b/crates/engine/src/display.rs index aa8bdb22dd..ad94c808c1 100644 --- a/crates/engine/src/display.rs +++ b/crates/engine/src/display.rs @@ -41,12 +41,16 @@ fn text_needs_quote_prefix(t: &str, sys: gridcraft_core::date::DateSystem) -> bo if t.is_empty() { return false; } - let mut chars = t.chars(); - let (first, second) = (chars.next(), chars.next()); + let first = t.chars().next(); if matches!(first, Some('=' | '\'')) { return true; } - if matches!(first, Some('+' | '-')) && second.is_some_and(|c| c.is_ascii_alphabetic() || c == '(') { + // A `+` or `-` entry that reads as a formula becomes one (`+5+4`, `-abc`); one that doesn't + // stays text (`--`, `+49 170 1234567`), as `input_to_cell` decides it. + if matches!(first, Some('+' | '-')) + && gridcraft_core::parse::starts_formula(t) + && crate::cmd::edit::parse_typed_formula(t).is_ok_and(|e| crate::cmd::edit::check_arg_counts(&e).is_ok()) + { return true; } !matches!(gridcraft_core::parse::parse_input(t, sys).value, Value::Text(ref x) if x.as_ref() == t) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 285d64ce97..c10a39a9cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -267,6 +267,26 @@ fn a_leading_plus_or_minus_starts_a_formula() { assert_eq!(v(&s, "B1"), value, "{typed}"); assert!(!input(&s, "B1").is_some_and(|t| t.starts_with('=')), "{typed}"); } + // Text that would read as a formula is edited with its apostrophe, so confirming the editor + // unchanged keeps it text; text that wouldn't is edited as it is. + for (typed, shown) in [ + ("'+5+4", "'+5+4"), + ("'-5+4", "'-5+4"), + ("'+1-555-1234", "'+1-555-1234"), + ("'-abc", "'-abc"), + ("--", "--"), + ("+49 170 1234567", "+49 170 1234567"), + ] { + s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap(); + let before = v(&s, "B2"); + let edit = { + let d = s.doc().unwrap(); + crate::display::edit_text(&d.wb, d.wb.active().unwrap(), CellRef::parse("B2").unwrap()) + }; + assert_eq!(edit, shown, "{typed}"); + s.execute("cell.set", json!({"cell": "B2", "input": edit})).unwrap(); + assert_eq!(v(&s, "B2"), before, "{typed} stays text after an unchanged edit"); + } // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and // one that does but names nothing known is #NAME?. Only `=` entries are refused. for typed in ["--", "-----", "+5+", "+49 170 1234567"] { From b21dd9151f49a810e364ea1243c27fd928163a86 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 10:18:20 +0200 Subject: [PATCH 037/201] Keep the zoom when undoing or redoing a sheet rename keep_zoom matched sheets by name, so undoing a rename found no match and brought back the zoom from before the rename. A sheet missing by name now falls back to the one at the same index, when the sheet count is unchanged and that sheet's name isn't in the restored snapshot. --- crates/engine/src/cmd/view.rs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 9af8941852..d403e425a8 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -204,9 +204,15 @@ fn zoom(s: &mut Session, p: &Json) -> Result { /// each sheet's current zoom when they swap in another snapshot of the workbook. Back at the saved /// state, the zoom alone doesn't make the workbook dirty, as with `view.zoom`. pub(crate) fn keep_zoom(d: &mut crate::DocState, now: &Workbook) { - let current = |name: &str| now.sheets.iter().find(|sh| sh.name == name).map(|sh| sh.zoom); + // Sheets have no stable id. A name missing from `now` is a rename being undone or redone, which + // keeps the sheet count and position: the sheet is the one at the same index, under a name the + // restored snapshot doesn't have. + let renamed = |i: usize| { + (now.sheets.len() == d.wb.sheets.len()).then(|| now.sheets.get(i)).flatten().filter(|sh| !d.wb.sheets.iter().any(|s| s.name == sh.name)) + }; + let current = |i: usize, name: &str| now.sheets.iter().find(|sh| sh.name == name).or_else(|| renamed(i)).map(|sh| sh.zoom); let changed: Vec<(usize, u16)> = - d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(&sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); + d.wb.sheets.iter().enumerate().filter_map(|(i, sh)| current(i, &sh.name).filter(|z| *z != sh.zoom).map(|z| (i, z))).collect(); if changed.is_empty() { return; } @@ -531,6 +537,24 @@ mod tests { assert_eq!(zoom(&s), 50, "redo keeps the zoom"); } + #[test] + fn undoing_a_rename_keeps_the_current_zoom() { + let mut s = Session::new(); + s.new_workbook(); + let active = |s: &Session| { + let sh = s.doc().unwrap().wb.active().unwrap(); + (sh.name.clone(), sh.zoom) + }; + let before = active(&s).0; + s.execute("sheet.rename", json!({"name": "Data"})).unwrap(); + s.execute("view.zoom", json!({"percent": 150})).unwrap(); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(active(&s), (before, 150), "undoing the rename keeps the zoom"); + s.execute("view.zoom", json!({"percent": 75})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); From 42ad67ab13f8ae45da75dfa45b72b3b0ed5390f5 Mon Sep 17 00:00:00 2001 From: Marco Arnulfo Date: Fri, 23 Oct 2026 15:23:03 +0200 Subject: [PATCH 038/201] Keep the zoom per step when undoing or redoing several steps edit.undo and edit.redo with `steps` > 1 ran keep_zoom once, comparing the first and last snapshots. Adding C and deleting B leaves the same sheet count under other names, which keep_zoom took for a rename of B to C, so C's zoom landed on B. keep_zoom now runs after each restored snapshot, against the one it replaces. --- crates/engine/src/cmd/edit.rs | 4 ++-- crates/engine/src/cmd/view.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 21421902f0..e9c5e1768d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -657,10 +657,10 @@ fn undo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; d.selection = e.selection; + super::view::keep_zoom(d, &cur_wb); crate::push_history(&mut d.redo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); - super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"undone": label})) @@ -678,10 +678,10 @@ fn redo(s: &mut Session, p: &Json) -> Result { label = e.label.clone(); d.wb = e.wb; d.selection = e.selection; + super::view::keep_zoom(d, &cur_wb); crate::push_history(&mut d.undo, label.clone(), cur_wb, &d.wb, cur_selection); } super::extra::keep_watch_list(&now, &mut d.wb); - super::view::keep_zoom(d, &now); d.calc.rebuild(&d.wb); d.revision += 1; Ok(json!({"redone": label})) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index d403e425a8..30a843f911 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -555,6 +555,33 @@ mod tests { assert_eq!(active(&s), ("Data".to_string(), 75), "redoing the rename keeps the zoom"); } + #[test] + fn undoing_several_steps_keeps_each_sheet_its_own_zoom() { + // Adding C then deleting B leaves as many sheets as before under other names: across both + // steps at once, that looks like B renamed to C, and C's zoom used to land on B. + let mut s = Session::new(); + s.new_workbook(); + let zoom = |s: &Session, name: &str| { + let wb = &s.doc().unwrap().wb; + wb.sheet(wb.sheet_index(name).unwrap()).unwrap().zoom + }; + let names = |s: &Session| s.doc().unwrap().wb.sheets.iter().map(|sh| sh.name.clone()).collect::>(); + let first = names(&s)[0].clone(); + s.execute("home.insertSheet", json!({"name": "B", "before": 1})).unwrap(); + s.execute("home.insertSheet", json!({"name": "C", "before": 2})).unwrap(); + s.execute("home.deleteSheet", json!({"sheet": "B"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "C"})).unwrap(); + s.execute("view.zoom", json!({"percent": 150})).unwrap(); + s.execute("edit.undo", json!({"steps": 2})).unwrap(); + assert_eq!(names(&s), [first.clone(), "B".to_string()]); + assert_eq!(zoom(&s, "B"), 100, "B never had C's zoom"); + s.execute("sheet.activate", json!({"sheet": "B"})).unwrap(); + s.execute("view.zoom", json!({"percent": 80})).unwrap(); + s.execute("edit.redo", json!({"steps": 2})).unwrap(); + assert_eq!(names(&s), [first, "C".to_string()]); + assert_eq!(zoom(&s, "C"), 150, "C gets its own zoom back, not B's"); + } + #[test] fn formula_bar_toggles_without_a_workbook_and_defaults_to_shown() { let mut s = Session::new(); From ba0009a1c30a420c9ae9650240932fc75a837e23 Mon Sep 17 00:00:00 2001 From: "D. Fender" <26173007+postfen@users.noreply.github.com> Date: Fri, 23 Oct 2026 11:43:58 -0700 Subject: [PATCH 039/201] Tables: Centre the dashes in table style swatches Excel's gallery thumbnails draw each cell's dash across about half the cell, centred in the space inside the cell's lines. Ours ran nearly edge to edge and centred on the whole cell, so the dashes in the header and last row sat a pixel toward the table's frame. Cell edges are now on whole pixels, and each dash covers about half the cell, centred inside the cell's own lines. As in Excel, a spare pixel goes below the dash. --- crates/ui-egui/src/ribbon.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index faf3cac7ff..c5e3cd2352 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1389,6 +1389,7 @@ fn table_gallery(app: &mut SheetApp, ui: &mut Ui, cmd: &str) { /// A style's gallery thumbnail: a 5x5 table (header row, banded rows) painted cell by cell from /// the same look the grid uses. fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, style: &str) { + use egui::emath::GuiRounding; use gridcraft_engine::tables::{TableParts, cell_look, look}; let lk = look(style); let parts = TableParts { header_row: true, totals_row: false, banded_rows: true, banded_cols: false, first_col: false, last_col: false }; @@ -1398,17 +1399,29 @@ fn paint_table_swatch(ui: &Ui, r: Rect, wb: &gridcraft_engine::model::Workbook, p.rect_filled(r, 0.0, Color32::WHITE); let n = 5u32; let (cw, rh) = (r.width() / n as f32, r.height() / n as f32); + // Cell edges on whole pixels keep the lines crisp and the rows evenly spaced. + let ppp = ui.pixels_per_point(); + let at = |start: f32, size: f32, k: u32| (start + size * k as f32).round_to_pixels(ppp); for row in 0..n { for col in 0..n { - let cr = Rect::from_min_size(pos2(r.left() + col as f32 * cw, r.top() + row as f32 * rh), vec2(cw, rh)); + let (x0, x1) = (at(r.left(), cw, col), at(r.left(), cw, col + 1)); + let cr = Rect::from_min_max(pos2(x0, at(r.top(), rh, row)), pos2(x1, at(r.top(), rh, row + 1))); let cl = cell_look(&lk, parts, row, col, n, n); if let Some(f) = cl.fill.and_then(res) { p.rect_filled(cr, 0.0, f); } - let dash = res(cl.font).unwrap_or(Color32::BLACK); - let y = cr.center().y; - p.line_segment([pos2(cr.left() + 2.0, y), pos2(cr.right() - 2.0, y)], Stroke::new(1.0, dash)); let b = cl.borders; + // Excel centres the dash in the space inside the cell's own lines, across about half of it. + let inset = |l: gridcraft_engine::model::BorderLine| if l.is_none() { 0.0 } else { 1.0 }; + let inner = Rect::from_min_max( + pos2(cr.left() + inset(b.left), cr.top() + inset(b.top)), + pos2(cr.right() - inset(b.right), cr.bottom() - inset(b.bottom)), + ); + // When the gap can't split evenly, Excel puts the spare pixel below the dash. + let top = ((inner.center().y - 0.5) * ppp).floor() / ppp; + let (mid, half) = (inner.center().x, cw * 0.26); + let dash = Rect::from_min_max(pos2((mid - half).round_to_pixels(ppp), top), pos2((mid + half).round_to_pixels(ppp), top + 1.0)); + p.rect_filled(dash, 0.0, res(cl.font).unwrap_or(Color32::BLACK)); for (side, edge) in [ (b.top, Rect::from_min_max(cr.left_top(), pos2(cr.right(), cr.top() + 1.0))), (b.bottom, Rect::from_min_max(pos2(cr.left(), cr.bottom() - 1.0), cr.right_bottom())), From 2a59d7f15dc2179b217aca84dff36bbbe318c193 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 24 Oct 2026 20:10:10 +0200 Subject: [PATCH 040/201] Quick Analysis: keep clear of the Auto Fill Options button, tests in the shared binary After a fill-handle drag both buttons sat at the selection's corner and the Quick Analysis one, painted on top, took the click. The Quick Analysis button now waits until the fill is no longer current; Ctrl+Q still opens the popup. Drops "Bar" from the Japanese EXTRA list, now a DIALOGS key, and moves the button tests into tests/it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/quick_analysis.rs | 5 ++++- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/{ => it}/quick_analysis_button.rs | 0 4 files changed, 5 insertions(+), 2 deletions(-) rename crates/ui-egui/tests/{ => it}/quick_analysis_button.rs (100%) diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index efb2afcca1..7b4d9c89b6 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1142,7 +1142,6 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ ("Treemap", "ツリーマップ"), ("Sunburst", "サンバースト"), ("Stock", "株価"), - ("Bar", "横棒"), ( "Drag to fill cells. Drag from inside a cell to select a range.", "ドラッグしてセルをオートフィルします。セルの内側からドラッグすると範囲を選択します。", diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 798f68c4f8..5fd3f8f6a0 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -203,7 +203,10 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { // While the mouse is down (selecting, filling) the button stays out of the way. let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down()); let lang = crate::i18n::current(&ctx); - if corner_visible && (open || !busy) { + // Right after a fill-handle drag the Auto Fill Options button sits at the same corner; it wins + // until that fill is no longer current (Ctrl+Q still opens the popup). + let fill_tag = app.grid.fill_tag.is_some(); + if corner_visible && (open || (!busy && !fill_tag)) { let mut clicked = false; egui::Area::new(Id::new("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click()); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 3a9769c1c5..4b3d9be2b3 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -64,6 +64,7 @@ mod pivot_pane; mod pivot_show_details; mod popup_dismissal; mod protect_password; +mod quick_analysis_button; mod right_to_left; mod scroll_position; mod scrollbar_column_fill; diff --git a/crates/ui-egui/tests/quick_analysis_button.rs b/crates/ui-egui/tests/it/quick_analysis_button.rs similarity index 100% rename from crates/ui-egui/tests/quick_analysis_button.rs rename to crates/ui-egui/tests/it/quick_analysis_button.rs From a2caeedcd97bd84e71627afdc7f00918b2a56e14 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 10:26:14 +0100 Subject: [PATCH 041/201] Quick Analysis: use theme category colours after the theme change on main Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/icons.rs | 2 +- crates/ui-egui/src/quick_analysis.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index bdfcbbb52c..57ab9c0a79 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -754,7 +754,7 @@ fn paint_with(p: &Painter, rect: Rect, icon: Icon, c: Color32, pal: &Palette) { g.stroke(&[(2.0, 6.5), (14.0, 6.5)], light); g.stroke(&[(6.0, 3.0), (6.0, 13.0)], light); g.stroke(&[(10.0, 3.0), (10.0, 13.0)], light); - g.line(&[(10.0, 1.0), (6.5, 8.0), (9.5, 8.0), (6.5, 15.0)], BLUE, 1.7); + g.line(&[(10.0, 1.0), (6.5, 8.0), (9.5, 8.0), (6.5, 15.0)], blue, 1.7); } } } diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 5fd3f8f6a0..1035ccbd16 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -12,7 +12,7 @@ use serde_json::{Value as Json, json}; use crate::SheetApp; use crate::grid::{Drag, Geo}; use crate::icons::{self, Icon}; -use crate::theme::{self, Tokens}; +use crate::theme::{self, Cat, Tokens}; /// Side of the corner button, and its gap to the selection's corner (clear of the fill handle). const BUTTON: f32 = 22.0; @@ -290,7 +290,7 @@ fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) { let p = ui.painter(); - let (green, blue, red, yellow) = (icons::GREEN, icons::BLUE, icons::RED, icons::YELLOW); + let (green, blue, red, yellow) = (t.cat(Cat::Green), t.cat(Cat::Blue), t.cat(Cat::Red), t.cat(Cat::Amber)); let cell = |i: f32, j: f32| Rect::from_min_size(r.min + vec2(i * r.width() / 3.0, j * r.height() / 3.0), vec2(r.width() / 3.0, r.height() / 3.0)); match glyph { Glyph::Icon(icon) => icons::paint(p, r, icon, t.text), From a98f290ec02dba3a06c0eb7cdaf5650e78d43557 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 00:06:42 +0100 Subject: [PATCH 042/201] Quick Analysis: use Id::unique for the area ids (Id::new is deprecated upstream) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/quick_analysis.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 1035ccbd16..3843ea6bfa 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -208,7 +208,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let fill_tag = app.grid.fill_tag.is_some(); if corner_visible && (open || (!busy && !fill_tag)) { let mut clicked = false; - egui::Area::new(Id::new("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { + egui::Area::new(Id::unique("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click()); let fill = if resp.is_pointer_button_down_on() || open { t.pressed @@ -229,7 +229,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let Some(opened_for) = app.grid.quick_analysis.open else { return }; let pos = pos2(button.left(), button.bottom() + 4.0); let mut picked: Option = None; - let resp = egui::Area::new(Id::new("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { + let resp = egui::Area::new(Id::unique("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { let state = &mut app.grid.quick_analysis; ui.horizontal(|ui| { From dd136062f557a77213147e69e5e911cf326b6037 Mon Sep 17 00:00:00 2001 From: zyzabruh Date: Mon, 26 Oct 2026 01:27:52 +0100 Subject: [PATCH 043/201] Paste Special: a transposed paste turns formula references as Excel does (fixes #2450) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paste Special > Transpose moved the copied cells but adjusted every formula with `shift_relative`, the adjustment of an ordinary copy, so the formula kept the offset it had in the source: `=A3+1` copied from A3:A4 and pasted at C3 read the cell above instead of the cell to its left and showed 1/1/1900. Excel turns the references instead. Observed against Excel 16 on synthetic workbooks (relative, `$B$1`, `B$1`, `$B1`, ranges, another sheet, whole rows and columns, a reference off the grid, a source block not starting at A1, and a 2x2 block): the row offset of a reference becomes its column offset and the other way round around the pair of positions of the cell carrying the formula, `(r, c)` -> `dest + (c - src.col, r - src.row)`. A reference pinned with `$` is left exactly as written, a whole-row or whole-column reference comes back as a cell range whose open side runs from the transposed far edge of the sheet to its end (`1:2` -> `F$6:G$1048576`), and a result outside the grid is `#REF!`. `adjust::transpose_relative(e, src, dest)` implements that beside `shift_relative`, and `paste_special` uses it when `transpose` is set; the paste-link and cut-paste paths are untouched. Tests: `tests::copy_transpose` in gridcraft-formula covers the observed cases including the two shapes above and `#REF!`; `transposed_paste_turns_the_formula_with_the_cell_that_carries_it` replays the issue's steps and checks the value is the day after the cell to the left, `transposed_paste_turns_every_kind_of_reference_the_way_excel_does` covers a relative, a pinned, a ranged and a whole-column reference end to end. Docs: docs/ui-parity.md (header and revision history), ROADMAP.md (header and progress log). 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- ROADMAP.md | 3 +- crates/engine/src/cmd/edit.rs | 41 +++++++++++++++++++++-- crates/formula/src/adjust.rs | 62 ++++++++++++++++++++++++++++++++++- crates/formula/src/tests.rs | 23 ++++++++++++- docs/ui-parity.md | 3 +- 5 files changed, 126 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c9e746bc5a..62c9e7217c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right, and fills a selection's empty last row and column) · **Target:** Microsoft Excel (Microsoft 365) +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-26 · **Change:** minor (Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does) · **Target:** Microsoft Excel (Microsoft 365) GridCraft aims at full Microsoft Excel parity, and at being better in places: faster, open (XLSX is the native format), fully scriptable by agents (MCP, control channel, CLI), and on the web. @@ -135,6 +135,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-26 | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does: the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 reads the cell to its left (`=C3+1`) instead of keeping the offset it had in the column; a reference pinned with `$` is left standing, a whole row or column comes back as a cell range open to the sheet's edge, and one off the grid is `#REF!` (#2450) | | 2026-10-25 | AutoSum over a selection does what Excel does: a selected row gets one total to its right (in its last cell if that is empty), not a one-cell total under each cell; a block whose last column is empty gets each row's total there, one whose last row is empty each column's, and with both the corner gets the total of the block; otherwise totals go under each column as before | | 2026-10-24 | Go To lists the named ranges of every sheet (`Sheet2!Name` for a name scoped to another sheet; hidden names, constants and formulas left out) and the references entered before, a double-click goes to an entry, and the Reference box takes several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30`) | | 2026-10-24 | Status bar: a right-click opens a menu that sets which selection statistics show (Average, Count and Sum by default; Numerical Count, Minimum and Maximum are new), kept with the preferences (`view.statusBar`) | diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 102edc2d36..7009b1878d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1219,8 +1219,12 @@ fn paste_special(s: &mut Session, p: &Json) -> Result { moved.dynamic = f.dynamic; return Some(std::sync::Arc::new(moved)); } - let moved = - gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64); + let moved = if transpose { + // A transposed paste turns the references instead of shifting them (#2450). + gridcraft_formula::adjust::transpose_relative(e, sc, dest) + } else { + gridcraft_formula::adjust::shift_relative(e, dest.row as i64 - sc.row as i64, dest.col as i64 - sc.col as i64) + }; Some(std::sync::Arc::new(Formula { dynamic: f.dynamic, ..Formula::from_expr(moved) })) }; if link { @@ -2203,6 +2207,39 @@ mod tests { assert_eq!(get(&mut s, "XFD2")["value"], json!(2.0)); } + #[test] + fn transposed_paste_turns_the_formula_with_the_cell_that_carries_it() { + // #2450: the values moved but the formula kept the offset it had in the source column, + // so it read the cell above instead of the cell to its left. + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "A3", "input": "2025-10-31"})).unwrap(); + s.execute("cell.set", json!({"cell": "A4", "input": "=A3+1"})).unwrap(); + s.execute("edit.copy", json!({"range": "A3:A4"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C3"})).unwrap(); + let get = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap(); + let date = get(&mut s, "C3")["value"].as_f64().expect("the date pastes as its serial"); + assert_eq!(date, get(&mut s, "A3")["value"].as_f64().unwrap()); + assert_eq!(get(&mut s, "D3")["formula"], "=C3+1", "the formula reads the cell to its left, as Excel's does"); + assert_eq!(get(&mut s, "D3")["value"].as_f64().unwrap(), date + 1.0, "and shows the day after it"); + } + + #[test] + fn transposed_paste_turns_every_kind_of_reference_the_way_excel_does() { + // Observed from Excel 16: relative parts turn a quarter turn, a reference pinned with $ + // is left standing, and a whole column comes back as a range open to the sheet's edge. + let mut s = Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "A1", "values": [["=B1+1"], ["=$B$1"], ["=SUM(B1:C3)"], ["=SUM(B:D)"]]})).unwrap(); + s.execute("edit.copy", json!({"range": "A1:A4"})).unwrap(); + s.execute("edit.pasteSpecial", json!({"what": "all", "transpose": true, "at": "C10"})).unwrap(); + let formula = |s: &mut Session, a: &str| s.execute("cell.get", json!({"cell": a})).unwrap()["formula"].clone(); + assert_eq!(formula(&mut s, "C10"), "=C11+1"); + assert_eq!(formula(&mut s, "D10"), "=$B$1"); + assert_eq!(formula(&mut s, "E10"), "=SUM(C11:E12)"); + assert_eq!(formula(&mut s, "F10"), "=SUM($C11:$XFD13)"); + } + #[test] fn replace_case_insensitive() { assert_eq!(replace_ci("Apple apple APPLE", "apple", "pear"), "pear pear pear"); diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 319474b4ef..04e1fd1cbf 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -1,7 +1,7 @@ //! Reference adjustment: copying formulas, inserting/deleting rows and columns, moving cells, //! renaming and deleting sheets. -use gridcraft_core::{CellError, MAX_COLS, MAX_ROWS, RangeRef}; +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef}; use crate::ast::{Anchor, Expr, RefKind, Reference, SheetSel, clamp_anchor}; @@ -36,6 +36,66 @@ pub fn shift_relative_wrapping(e: Expr, dr: i64, dc: i64) -> Expr { }) } +/// Paste Special ▸ Transpose: the cell holding the formula moves from `src` to `dest`, so every +/// reference turns a quarter turn with it — its row offset becomes its column offset and the other +/// way round, `(r, c)` → `dest + (c − src.col, r − src.row)`. +/// +/// As Excel writes it out: a reference that pins a row or a column with `$` is left exactly as it +/// stands, a whole-row or whole-column reference comes back as a cell range whose open side runs +/// from the transposed far edge of the sheet, and a result that falls off the grid becomes `#REF!`. +pub fn transpose_relative(e: Expr, src: CellRef, dest: CellRef) -> Expr { + e.map(&mut |x| match x { + Expr::Ref(r) if !has_absolute(&r) => match transpose_ref(&r, src, dest) { + Some(r) => Expr::Ref(r), + None => Expr::Error(CellError::Ref), + }, + other => other, + }) +} + +/// Whether any end of the reference pins a row or a column with `$`. +fn has_absolute(r: &Reference) -> bool { + let abs = |a: &Anchor| a.row_abs || a.col_abs; + match &r.kind { + RefKind::Cell(a) => abs(a), + RefKind::Range(a, b) => abs(a) || abs(b), + RefKind::Rows(_, a0, _, a1) | RefKind::Cols(_, a0, _, a1) => *a0 || *a1, + } +} + +/// Where an end lands after the turn: its column drives the new row, its row the new column. +fn transpose_anchor(a: &Anchor, src: CellRef, dest: CellRef) -> Option<(u32, u32)> { + clamp_anchor(dest.row as i64 + a.col as i64 - src.col as i64, dest.col as i64 + a.row as i64 - src.row as i64) +} + +fn transpose_ref(r: &Reference, src: CellRef, dest: CellRef) -> Option { + let kind = match &r.kind { + RefKind::Cell(a) => { + let (row, col) = transpose_anchor(a, src, dest)?; + RefKind::Cell(Anchor { row, col, ..*a }) + } + RefKind::Range(a, b) => { + let (row, col) = transpose_anchor(a, src, dest)?; + let (row2, col2) = transpose_anchor(b, src, dest)?; + RefKind::Range(Anchor { row, col, ..*a }, Anchor { row: row2, col: col2, ..*b }) + } + // A whole row turns into a cell range: its rows become columns, while its open columns + // become rows pinned with `$` — from the transposed first column down to the last row. + RefKind::Rows(r0, _, r1, _) => { + let (row, col) = clamp_anchor(dest.row as i64 - src.col as i64, dest.col as i64 + *r0 as i64 - src.row as i64)?; + let (row2, col2) = clamp_anchor(MAX_ROWS as i64 - 1, dest.col as i64 + *r1 as i64 - src.row as i64)?; + RefKind::Range(Anchor { row, col, row_abs: true, col_abs: false }, Anchor { row: row2, col: col2, row_abs: true, col_abs: false }) + } + // A whole column likewise: its columns become rows, its open rows become columns up to XFD. + RefKind::Cols(c0, _, c1, _) => { + let (row, col) = clamp_anchor(dest.row as i64 + *c0 as i64 - src.col as i64, dest.col as i64 - src.row as i64)?; + let (row2, col2) = clamp_anchor(dest.row as i64 + *c1 as i64 - src.col as i64, MAX_COLS as i64 - 1)?; + RefKind::Range(Anchor { row, col, row_abs: false, col_abs: true }, Anchor { row: row2, col: col2, row_abs: false, col_abs: true }) + } + }; + Some(Reference { sheet: r.sheet.clone(), kind }) +} + /// Whether the formula has a relative (no `$`) row or column anywhere. pub fn has_relative_refs(e: &Expr) -> bool { e.references().iter().any(|r| match r.kind { diff --git a/crates/formula/src/tests.rs b/crates/formula/src/tests.rs index a7506aa4bc..f1fa9d5060 100644 --- a/crates/formula/src/tests.rs +++ b/crates/formula/src/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative}; +use crate::adjust::{Axis, Edit, adjust, rename_sheet, shift_relative, transpose_relative}; fn rt(src: &str) -> String { print(&parse(src).unwrap_or_else(|e| panic!("{src}: {e}"))) @@ -165,6 +165,27 @@ fn copy_shift() { assert_eq!(print(&shift_relative(e, 5, 1)), "SUM(B:B)"); } +#[test] +fn copy_transpose() { + let at = gridcraft_core::CellRef::new; + // The row of each reference drives its new column and the other way round (Excel, observed: + // A1 → F6 carrying =B1+1 comes out as =F7+1). + let e = parse("B1+SUM(B1:C3)+Sheet2!A1").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "F7+SUM(F7:H8)+Sheet2!F6"); + // The turn is around the two positions of the formula's cell, not around A1. + let e = parse("G3+SUM(1:2)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(1, 2), at(9, 5))), "G14+SUM(E$8:F$1048576)"); + // A reference pinned with `$` is left exactly as it stands. + let e = parse("$B$1+B$1+$B1+SUM($B$1:$C$3)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "$B$1+B$1+$B1+SUM($B$1:$C$3)"); + // Whole rows and columns come back as a cell range open to the sheet's edge. + let e = parse("SUM(1:2)+SUM(B:D)").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "SUM(F$6:G$1048576)+SUM($F7:$XFD9)"); + // Off the grid is #REF!, like a copy that runs past the edge. + let e = parse("A16384+B1").unwrap(); + assert_eq!(print(&transpose_relative(e, at(0, 0), at(5, 5))), "#REF!+F7"); +} + #[test] fn insert_delete() { let ins = Edit::Insert { axis: Axis::Rows, at: 2, count: 2 }; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ed875cc8ef..9cd49ba65b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (AutoSum over a selected row puts its total to the right) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel does) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -186,6 +186,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Paste Special ▸ Transpose turns a formula's references with the cell that carries it, as Excel's does (#2450): the row offset becomes the column offset and the other way round, so `=A3+1` copied from A3:A4 and pasted at C3 lands as `=C3+1` and shows the day after the cell to its left, instead of keeping the offset it had in the column and reading the cell above. A reference pinned with `$` is left exactly as Excel leaves it, a whole row or column comes back as a cell range open to the sheet's edge, and one that lands off the grid is `#REF!` | | 2026-10-25 | minor | AutoSum (Alt+=, Home › AutoSum) over a selected row puts its total to the right of the row, or in its last cell when that is empty, as in Excel; it wrote a one-cell total under each cell. A selection's empty last column takes each row's total and its empty last row each column's, with the block's total in the corner when both are empty | | 2026-10-25 | minor | Paste Name lays out only the names in view, so a workbook with thousands of names opens it at once; the arrow keys still scroll the chosen name into view. Go To matches a `Sheet2!Name` reference and hides a workbook name behind the active sheet's own name in any case and script (`Größe` = `GRÖSSE`), as formulas do. The two Page Layout view rows are one; the 0.7 in side margin used when Align with Page Margins is off is marked unverified | | 2026-10-24 | minor | Go To lists the named ranges on every sheet, as Excel's does ("The Go to popup window shows named ranges on every worksheet in your workbook"): a name scoped to another sheet appears as `Sheet2!Name`, and hidden names, constants and formulas are left out. It keeps the references entered (newest first, ten at most), and a double-click on an entry goes there. The Reference box and `edit.goTo` take several names or references separated by commas (`Price, Type`, `B14:C22,F19:G30,H21:H29`) and select them all; `edit.goTo {list: true}` returns the list | From a53483874e94e62e4272b160909d58fe1dd01759 Mon Sep 17 00:00:00 2001 From: zyzabruh Date: Mon, 26 Oct 2026 01:40:53 +0100 Subject: [PATCH 044/201] Formula: document transpose_ref's turn and its #REF! contract (review #2606) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit's only finding on the pull request was docstring coverage on the touched functions; this is the one that carried an undocumented contract — `None` means an end left the sheet and the caller turns it into `#REF!`. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- crates/formula/src/adjust.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/formula/src/adjust.rs b/crates/formula/src/adjust.rs index 04e1fd1cbf..2b3739bb2f 100644 --- a/crates/formula/src/adjust.rs +++ b/crates/formula/src/adjust.rs @@ -68,6 +68,8 @@ fn transpose_anchor(a: &Anchor, src: CellRef, dest: CellRef) -> Option<(u32, u32 clamp_anchor(dest.row as i64 + a.col as i64 - src.col as i64, dest.col as i64 + a.row as i64 - src.row as i64) } +/// Turns one reference with `src` → `dest`: `None` when an end falls outside the sheet, which +/// the caller turns into `#REF!`. fn transpose_ref(r: &Reference, src: CellRef, dest: CellRef) -> Option { let kind = match &r.kind { RefKind::Cell(a) => { From de8f36ee33060a73798a1accccc6cd0a03510d4c Mon Sep 17 00:00:00 2001 From: Zaxaerith <189452125+Zaxaerith@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:45:52 +0800 Subject: [PATCH 045/201] fix(ui): left-align font name in Home ribbon (#2454) Co-Authored-By: Codex --- crates/ui-egui/src/ribbon.rs | 3 ++- crates/ui-egui/tests/keytips.rs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 37cb2a844f..8980682d1e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1294,7 +1294,8 @@ fn autosum_menu(app: &mut SheetApp, ui: &mut Ui) { fn font_combo(app: &mut SheetApp, ui: &mut Ui, st: &Style) { let name = st.font.name.clone(); - let resp = ui.add_sized([150.0, 24.0], egui::Button::new(egui::RichText::new(&name).font(theme::ui_font(12.5)))); + // The trailing grow atom left-aligns the existing label inside the button. + let resp = ui.add_sized([150.0, 24.0], egui::Button::new(egui::RichText::new(&name).font(theme::ui_font(12.5))).right_text(())); control_keytip(app, ui, &resp, "home.fontName"); let forced = invoke(app, "home.fontName"); let items: Vec<(&str, String)> = FONTS.iter().map(|f| (*f, f.to_string())).collect(); diff --git a/crates/ui-egui/tests/keytips.rs b/crates/ui-egui/tests/keytips.rs index b4418018af..d3b0907991 100644 --- a/crates/ui-egui/tests/keytips.rs +++ b/crates/ui-egui/tests/keytips.rs @@ -522,6 +522,30 @@ fn pending_sequences_go_live_when_the_command_lands() { assert_eq!(h.state().keytips.prefix(), None); } +#[test] +fn font_name_box_left_aligns_short_and_long_names() -> Result<(), String> { + for name in ["Arial", "Calibri", "Times New Roman"] { + let mut session = blank(); + session.execute("home.fontName", json!({"name": name})).map_err(|e| e.to_string())?; + let h = harness(session); + // Querying the original name also checks that the button keeps its accessible label. + let rect = h.get_by_role_and_label(egui::accesskit::Role::Button, name).rect(); + assert!((rect.width() - 150.0).abs() < 0.1 && (rect.height() - 24.0).abs() < 0.1, "{name}: {rect:?}"); + let text_x = h + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == name && rect.contains(text.pos) => Some(text.pos.x), + _ => None, + }) + .ok_or("font name was not painted inside its button")?; + let inset = text_x - rect.left(); + assert!((0.0..=10.0).contains(&inset), "{name}: expected a small left inset, got {inset}"); + } + Ok(()) +} + #[test] fn control_keytips_open_dropdowns_and_run_handlers() { // HFF routes to the font control: its dropdown opens (popup items queryable). From 4bc91dbc6a17a23a9d103051f140bbc373eaae9e Mon Sep 17 00:00:00 2001 From: "D. Fender" <26173007+postfen@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:01:46 -0700 Subject: [PATCH 046/201] Tables: import what main's explicit imports now need; run table_style_looks in the it binary --- crates/engine/src/cf.rs | 4 +++- crates/engine/src/tables.rs | 2 +- crates/engine/tests/it/main.rs | 1 + 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index 43feba4727..ac80f9c7d5 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -4,7 +4,9 @@ use std::collections::HashMap; use gridcraft_core::{CellRef, RangeRef, Value, compare}; -use gridcraft_model::{CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Underline, Workbook, default_icon_thresholds}; +use gridcraft_model::{ + CfOperator, CfRule, CfValueKind, Color, CondFormat, PatternType, Sheet, Style, Table, Underline, Workbook, default_icon_thresholds, +}; /// The conditional look of one cell. #[derive(Clone, Debug, Default, PartialEq)] diff --git a/crates/engine/src/tables.rs b/crates/engine/src/tables.rs index 388abf529e..fd34fe2d50 100644 --- a/crates/engine/src/tables.rs +++ b/crates/engine/src/tables.rs @@ -2,7 +2,7 @@ //! `TableStyleLight1…21 / Medium1…28 / Dark1…11` names so files round-trip). use gridcraft_core::{CellRef, RangeRef}; -use gridcraft_model::{BorderLine, BorderStyle, Cell, Color, Fill, Formula, PatternType, Style, Table, Workbook}; +use gridcraft_model::{BorderLine, BorderStyle, Borders, Cell, Color, Fill, Formula, PatternType, Sheet, Style, Table, Workbook}; /// (family, number) from a style name, e.g. `TableStyleMedium2` → ("Medium", 2). pub fn parse_style_name(name: &str) -> (&'static str, u32) { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 4c91e58ac4..9696303c40 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -27,5 +27,6 @@ mod sheet_name_quoting; mod sparse_clear_invalidation; mod stored_list_shape; mod table_resize_overlap; +mod table_style_looks; mod table_total_row_last_row; mod wrap_row_height; From 09fcfb63a76f69a30c7a727c3be40d2786a10c87 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 20:18:15 +0500 Subject: [PATCH 047/201] Space on a checkbox cell toggles it and nothing else (#1951) A space on a checkbox cell toggles it, and the same key press also arrives as text -- and typing text starts editing the cell. So the cell toggled *and* opened an editor holding a space, which Enter then committed over the checkbox: the value the space had just set was replaced by a space. A space on a checkbox cell is no longer read as text to type. Rebased onto main, 352 commits on: the grid's keyboard handling moved from grid.rs to grid/keyboard.rs, which already imports `is_checkbox`, so the arm sits in front of the general text arm there. Without it the test fails on "no editor opened" -- that is, the editor still opens. --- crates/ui-egui/src/grid/keyboard.rs | 5 ++ crates/ui-egui/tests/checkbox_space.rs | 111 +++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 crates/ui-egui/tests/checkbox_space.rs diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index 8d2e698ed8..bd6c09ca77 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -60,6 +60,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res // insert text at, so a middle click on a cell is deliberately not a paste. egui::Event::MiddleClickPaste { .. } => {} egui::Event::Text(_) if shortcut_pressed || shortcut_ran => {} + // A space on a checkbox cell toggles it (the `Key::Space` arm below). The same key + // press also arrives as text, and typing text starts editing the cell -- so the cell + // toggled *and* opened an editor holding a space, which Enter then committed over the + // checkbox (#1951). + egui::Event::Text(text) if text == " " && is_checkbox(sh, app) => {} egui::Event::Text(text) if text.chars().all(|c| !c.is_control()) && !text.is_empty() => { app.begin_edit(Some(text), false); if let Some(ed) = app.editor.as_mut() { diff --git a/crates/ui-egui/tests/checkbox_space.rs b/crates/ui-egui/tests/checkbox_space.rs new file mode 100644 index 0000000000..d7ec05ed6a --- /dev/null +++ b/crates/ui-egui/tests/checkbox_space.rs @@ -0,0 +1,111 @@ +//! Space on a checkbox cell toggles it and nothing else (#1951). + +use egui::{Event, Key, Modifiers, PointerButton}; +use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_engine::core::Value; +use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +fn harness(session: Session) -> Harness { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut SheetApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + SheetApp::new(session, Default::default()), + ); + h.run_steps(4); + h +} + +/// A space, as a keyboard reports it: the key press, the text it produces, then the release. +fn space(h: &mut Harness) { + let k = |pressed| Event::Key { key: Key::Space, physical_key: Some(Key::Space), pressed, repeat: false, modifiers: Modifiers::NONE }; + h.input_mut().events.push(k(true)); + h.input_mut().events.push(Event::Text(" ".into())); + h.input_mut().events.push(k(false)); + h.run_steps(2); +} + +fn press(h: &mut Harness, key: Key) { + let k = |pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }; + h.input_mut().events.push(k(true)); + h.input_mut().events.push(k(false)); + h.run_steps(2); +} + +fn value(h: &Harness, a1: &str) -> Option { + let d = h.state().session.active().unwrap(); + d.wb.active().unwrap().cell(CellRef::parse(a1).unwrap()).map(|c| c.value.clone()) +} + +#[test] +fn space_toggles_a_checkbox_cell_without_editing_it() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("cell.set", json!({"cell": "B2", "input": "FALSE"})).unwrap(); + s.execute("insert.checkbox", json!({"range": "B2"})).unwrap(); + s.execute("selection.set", json!({"range": "B2"})).unwrap(); + let mut h = harness(s); + assert_eq!(value(&h, "B2"), Some(Value::Bool(false))); + + // The key press toggles the box; the text it also produces must not start editing, or Enter + // commits that space over the checkbox and leaves the cell blank. + space(&mut h); + assert_eq!(value(&h, "B2"), Some(Value::Bool(true))); + assert!(h.state().editor.is_none(), "no editor opened"); + press(&mut h, Key::Enter); + assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "Enter moved on and left the checkbox"); + + // And again, back to unchecked. Reached without clicking the box, since a click on the box + // toggles it in its own right (below): an ordinary cell, then across to it. + click_cell(&mut h, "D2"); + press(&mut h, Key::ArrowLeft); + press(&mut h, Key::ArrowLeft); + assert_eq!(active(&h), "B2", "the arrows walked back to the checkbox"); + space(&mut h); + assert_eq!(value(&h, "B2"), Some(Value::Bool(false))); + assert!(h.state().editor.is_none()); + + // A click on the box toggles it too, which is what the pointer path does with a checkbox + // cell and the reason the walk above avoids it. + click_cell(&mut h, "B2"); + assert_eq!(value(&h, "B2"), Some(Value::Bool(true)), "the click toggled the box"); + assert!(h.state().editor.is_none(), "no editor opened"); + + // A space still types on an ordinary cell. + click_cell(&mut h, "C3"); + space(&mut h); + assert!(h.state().editor.is_some(), "an ordinary cell starts editing"); + press(&mut h, Key::Escape); +} + +/// Click a cell, as a person selects one: the grid's own geometry gives where it is, so the +/// click goes through hit-testing and whatever the grid does with focus, rather than the +/// selection being set behind the app's back once it is running (#1960 review). +fn click_cell(h: &mut Harness, cell: &str) { + let pos = { + let app = h.state(); + let sheet = app.session.active().unwrap().wb.active().unwrap(); + let geo = Geo::new(sheet, app.grid.rect.unwrap(), app.view().scroll); + geo.cell_rect(sheet, CellRef::parse(cell).unwrap()).center() + }; + h.input_mut().events.extend([ + Event::PointerMoved(pos), + Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }, + Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }, + ]); + h.run_steps(2); + // The click has to have landed: a selection that did not move would leave each assertion + // after it testing the cell before it instead. + assert_eq!(active(h), cell, "the click selected {cell}"); +} + +/// The active cell, in A1 form. +fn active(h: &Harness) -> String { + h.state().session.active().unwrap().selection.active.to_string() +} From 921cdc974f12b22bc5001e4fd2d2f1ee08051e7d Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:59:24 +0100 Subject: [PATCH 048/201] AutoSum tests join the `it` test binary, as main's UI tests do The module uses the shared harness (`common::builder`, `common::app`), so it runs with the pinned font set like the other UI tests. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/{ => it}/autosum_edit.rs | 14 +++----------- crates/ui-egui/tests/it/main.rs | 1 + 2 files changed, 4 insertions(+), 11 deletions(-) rename crates/ui-egui/tests/{ => it}/autosum_edit.rs (93%) diff --git a/crates/ui-egui/tests/autosum_edit.rs b/crates/ui-egui/tests/it/autosum_edit.rs similarity index 93% rename from crates/ui-egui/tests/autosum_edit.rs rename to crates/ui-egui/tests/it/autosum_edit.rs index 9f76bf8a8d..5440fffe02 100644 --- a/crates/ui-egui/tests/autosum_edit.rs +++ b/crates/ui-egui/tests/it/autosum_edit.rs @@ -4,10 +4,10 @@ use egui::{Event, Key, Modifiers, PointerButton, Pos2}; use gridcraft_engine::core::{CellRef, Value}; use gridcraft_engine::{Mode, Session}; -use gridcraft_ui_egui::{SheetApp, grid::Geo}; +use gridcraft_ui_egui::grid::Geo; use serde_json::json; -type Harness = egui_kittest::Harness<'static, SheetApp>; +use crate::common::Harness; /// 1, 2, 3 in A1:A3 and `selected` selected. fn harness(selected: &str) -> Harness { @@ -20,15 +20,7 @@ fn harness_at(first: &str, selected: &str) -> Harness { session.new_workbook(); session.execute("range.setValues", json!({"range": first, "values": [[1], [2], [3]]})).unwrap(); session.execute("selection.set", json!({"range": selected})).unwrap(); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( - |ui, app: &mut SheetApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - SheetApp::new(session, Default::default()), - ); - h.run_steps(4); - h + crate::common::harness_with(crate::common::builder().with_size(egui::vec2(1200.0, 800.0)), crate::common::app(session), 4) } /// The AutoSum button: a menu-style run. diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 302bc9c49c..d37c238250 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -10,6 +10,7 @@ mod accounting_fill; mod advanced_filter; mod argument_names; mod autosave_persist; +mod autosum_edit; mod borders; mod cell_editor_caret; mod cell_pictures; From af4f17184c0f5e0891d5dd51e1716f3d0447a498 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:20:56 +0100 Subject: [PATCH 049/201] Formula entry: `+` before a time stays text, as in Excel Checked by hand in Excel for the web (English (United States) regional format): `+1:30` stays text, while `-1:30` is the formula `=-1:30` (rows 1 to 30), `+1/30` and `-1/30` are formulas and `1:30` is a time. `starts_formula` now leaves a `+` followed by a time to the usual value parsing, which keeps it as text. Raised by @iluebbe in #2023. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/parse.rs | 15 ++++++++++----- crates/engine/src/tests.rs | 21 ++++++++++++++++----- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/crates/core/src/parse.rs b/crates/core/src/parse.rs index 504a92d01f..ffad72c849 100644 --- a/crates/core/src/parse.rs +++ b/crates/core/src/parse.rs @@ -52,9 +52,14 @@ pub fn parse_number_text_in(s: &str, sys: DateSystem) -> Option { /// Whether typed cell input is meant as a formula: it starts with `=`, or, as Lotus 1-2-3 users /// type it, with `+` or `-` and isn't a number on its own (`+5+4` is `=+5+4`, `-5` the number -5, /// a lone `+` or `-` text). A leading space or apostrophe makes the input text. Callers parse -/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. +/// the formula; a `+` or `-` entry that doesn't parse (`--`) stays text, as in Excel. So does `+` +/// before a time (`+1:30`), while `-1:30` is a formula (rows 1 to 30), as Excel for the web does. pub fn starts_formula(input: &str) -> bool { - input.starts_with('=') || (input.len() > 1 && input.starts_with(['+', '-']) && parse_number_text(input).is_none()) + input.starts_with('=') + || (input.len() > 1 + && input.starts_with(['+', '-']) + && parse_number_text(input).is_none() + && !input.strip_prefix('+').is_some_and(|time| time.contains(':') && parse_number_text(time).is_some())) } /// Text that Excel's "Number Stored as Text" check flags: it would be a number if typed (signs, @@ -588,12 +593,12 @@ mod tests { #[test] fn a_leading_sign_starts_a_formula_unless_the_entry_is_a_number() { // #2023: Excel reads `+5+4` as `=+5+4`, as Lotus 1-2-3 did. - for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--"] { + for s in ["=1", "=", "+5+4", "-5+4", "--5", "+-5", "-.5*2", "-3/4", "+A1", "-SUM(1,2)", "+(5+4)", "-abc", "--", "-1:30", "+1/30", "-1/30"] { assert!(starts_formula(s), "{s}"); } // Signed numbers, percentages and currency stay numbers; a lone sign, a leading space or - // apostrophe and other text stay text. - for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b"] { + // apostrophe, `+` before a time and other text stay text. + for s in ["+5", "-5", "+5%", "-$5", "-1e3", "+.5", "-1,234.5", "+", "-", " +5+4", "'+5+4", "5+4", "", "a-b", "+1:30", "+0:30:15"] { assert!(!starts_formula(s), "{s}"); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 20c434d920..5239762d88 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -251,9 +251,16 @@ fn a_leading_plus_or_minus_starts_a_formula() { // #2023: like Excel (and Lotus 1-2-3 before it), typing `+5+4` enters the formula `=+5+4`. let mut s = s(); let input = |s: &Session, a: &str| s.doc().unwrap().wb.active().unwrap().cell(CellRef::parse(a).unwrap()).map(|c| c.input_text()); - for (cell, typed, value) in - [("A1", "+5+4", 9.0), ("A2", "-5+4", -1.0), ("A3", "--5", 5.0), ("A4", "-3/4", -0.75), ("A5", "+A1*2", 18.0), ("A6", "-(A1)", -9.0)] - { + for (cell, typed, value) in [ + ("A1", "+5+4", 9.0), + ("A2", "-5+4", -1.0), + ("A3", "--5", 5.0), + ("A4", "-3/4", -0.75), + ("A5", "+A1*2", 18.0), + ("A6", "-(A1)", -9.0), + ("A7", "+1/30", 1.0 / 30.0), + ("A8", "-1/30", -1.0 / 30.0), + ] { s.execute("cell.set", json!({"cell": cell, "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); assert_eq!(input(&s, cell), Some(format!("={typed}")), "{typed}"); assert_eq!(v(&s, cell), Value::Number(value), "{typed}"); @@ -281,6 +288,7 @@ fn a_leading_plus_or_minus_starts_a_formula() { ("'-abc", "'-abc"), ("--", "--"), ("+49 170 1234567", "+49 170 1234567"), + ("+1:30", "+1:30"), ] { s.execute("cell.set", json!({"cell": "B2", "input": typed})).unwrap(); let before = v(&s, "B2"); @@ -294,16 +302,19 @@ fn a_leading_plus_or_minus_starts_a_formula() { } // As observed in Excel for the web, an entry that doesn't read as a formula stays text, and // one that does but names nothing known is #NAME?. Only `=` entries are refused. - for typed in ["--", "-----", "+5+", "+49 170 1234567"] { + for typed in ["--", "-----", "+5+", "+49 170 1234567", "+1:30"] { s.execute("cell.set", json!({"cell": "C1", "input": typed})).unwrap_or_else(|e| panic!("{typed}: {e}")); assert_eq!(v(&s, "C1"), Value::text(typed), "{typed}"); assert_eq!(input(&s, "C1").as_deref(), Some(typed), "{typed}"); } s.execute("cell.set", json!({"cell": "C2", "input": "- item"})).unwrap(); assert_eq!(v(&s, "C2"), Value::Error(gridcraft_core::CellError::Name)); + // Excel for the web keeps `+1:30` as text (above) but reads `-1:30` as a formula (rows 1 to 30). + s.execute("cell.set", json!({"cell": "C40", "input": "-1:30"})).unwrap(); + assert_eq!(input(&s, "C40").as_deref(), Some("=-1:30")); let e = s.execute("cell.set", json!({"cell": "C1", "input": "=--"})).unwrap_err().to_string(); assert!(e.contains("problem with this formula"), "{e}"); - assert_eq!(v(&s, "C1"), Value::text("+49 170 1234567"), "a refused entry keeps the cell"); + assert_eq!(v(&s, "C1"), Value::text("+1:30"), "a refused entry keeps the cell"); // Pasted or split by Text to Columns, the same rule applies. s.execute("edit.paste", json!({"at": "D1", "text": "--\t-5+4\n"})).unwrap(); assert_eq!(v(&s, "D1"), Value::text("--")); From 6c2ba271105e6f2ac4b490b67d9409eb04ac266a Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:41:02 -0300 Subject: [PATCH 050/201] Calc: an array that grew into another's spill area is laid out after it on full recalc --- crates/calc/src/recalc.rs | 35 +++++++++++++++++++++++++++++------ crates/calc/src/tests.rs | 17 +++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index f81d543247..88c3c18ed3 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -113,13 +113,34 @@ fn components(edges: &[Vec]) -> (Vec, Vec) { /// the same formula as in an incremental recalculation. #[derive(Default)] struct Prior { - /// Formulas that spilled (their area, from the last calculation or the file's `ref`). - spilled: HashSet, + /// Formulas that spilled, with the area they filled (from the last calculation or the file's + /// `ref`). + spilled: HashMap, /// Formulas that showed #SPILL!. A cell's value moves with it on a structural edit, its spill /// area doesn't. blocked: HashSet, } +impl Prior { + /// Formulas whose new array reaches past their own former area into another formula's: they + /// are laid out after it, as in an incremental recalculation, where that area is still filled. + fn grown_into_another(&self, dirty: &[Key], spills: &HashMap>) -> HashSet { + let mut out = HashSet::default(); + for k in dirty { + let (Some(old), Some(array)) = (self.spilled.get(k), spills.get(k)) else { continue }; + let end = CellRef::new( + k.1.row.saturating_add((array.rows as u32).saturating_sub(1)), + k.1.col.saturating_add((array.cols as u32).saturating_sub(1)), + ); + let area = RangeRef::new(k.1, end); + if !old.contains_range(&area) && self.spilled.iter().any(|(o, r)| o != k && o.0 == k.0 && r.intersects(&area)) { + out.insert(*k); + } + } + out + } +} + impl Calc { pub fn new() -> Self { Self::default() @@ -205,7 +226,7 @@ impl Calc { if wb.sheet(i).is_some_and(|s| !s.spill_ranges.is_empty() || !s.spill.is_empty()) && let Some(sh) = wb.sheet_mut(i) { - prior.spilled.extend(sh.spill_ranges.iter().filter(|(_, r)| !r.is_single()).map(|(c, _)| (i, *c))); + prior.spilled.extend(sh.spill_ranges.iter().filter(|(_, r)| !r.is_single()).map(|(c, r)| ((i, *c), *r))); sh.spill.clear(); sh.spill_ranges.clear(); } @@ -391,11 +412,13 @@ impl Calc { self.circular.extend(cycles); // When two arrays want the same cells, the one already spilling there keeps them and // the newcomer is #SPILL! (as when it is entered), and one that was #SPILL! stays so: - // arrays are laid out in that order, then in reading order. Without this, a full + // arrays are laid out in that order, then in reading order. Of two that both spilled, + // one that grew into the other's former area comes second. Without this, a full // recalculation or reopening the file handed the area to whichever came first. + let grown = if prior.spilled.is_empty() { HashSet::default() } else { prior.grown_into_another(&dirty, &spills) }; dirty.sort_by_key(|k| { - let owns = prior.spilled.contains(k) || wb.sheet(k.0).is_some_and(|s| s.spill_ranges.contains_key(&k.1)); - (prior.blocked.contains(k), !owns) + let owns = prior.spilled.contains_key(k) || wb.sheet(k.0).is_some_and(|s| s.spill_ranges.contains_key(&k.1)); + (prior.blocked.contains(k), !owns, grown.contains(k)) }); let mut spill_changes = self.write_back(wb, &dirty, results, &spills); // Formulas with references only known while evaluating (INDIRECT, OFFSET) may have read diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 1913d03435..6a89615853 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -720,6 +720,23 @@ fn a_full_recalc_keeps_a_spill_with_the_formula_already_spilling_there() { assert_eq!([t.num("C14"), t.num("G14"), t.num("I14")], [1.0, 5.0, 7.0]); } +#[test] +fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() { + // Both arrays spill; in manual calculation F13 then grows over F14:G14, which C14's array + // fills. A full recalculation gives what an automatic one would: C14 keeps its cells and F13 + // is #SPILL!, although F13 comes first in reading order. + let mut t = T::new(); + t.set("J1", "1"); + t.set("C14", "=SEQUENCE(1,7)"); + t.set("F13", "=SEQUENCE(J1,2)"); + assert_eq!([t.num("F13"), t.num("G13")], [1.0, 2.0]); + t.wb.calc.mode = gridcraft_model::CalcMode::Manual; + t.set("J1", "5"); + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.get("F13"), Value::Error(CellError::Spill)); + assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]); +} + #[test] fn formulas_reading_an_array_that_loses_a_spill_conflict_read_spill_errors() { // Two arrays of one recalculation want the same empty cell: the one laid out second is From 527b884429e37ae25e60541bb36d7c4ce06c01c0 Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Sat, 31 Oct 2026 14:41:03 -0300 Subject: [PATCH 051/201] pt function help: FILTER keeps each row or column whose own include value is TRUE --- crates/ui-egui/src/i18n/pt_functions.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/pt_functions.rs b/crates/ui-egui/src/i18n/pt_functions.rs index bd6b4700ce..dfd9b3a49a 100644 --- a/crates/ui-egui/src/i18n/pt_functions.rs +++ b/crates/ui-egui/src/i18n/pt_functions.rs @@ -344,7 +344,10 @@ pub(super) const DESCRIPTIONS: &[(&str, &str)] = &[ "Une o texto de valores e intervalos com um delimitador, opcionalmente ignorando itens vazios.", ), ("Keeps rows or columns from the start (or end) of an array.", "Mantém linhas ou colunas do início (ou do fim) de uma matriz."), - ("Keeps the rows or columns of an array whose include flag is TRUE.", "Mantém as linhas ou colunas de uma matriz cujo argumento incluir é TRUE."), + ( + "Keeps the rows or columns of an array whose include flag is TRUE.", + "Mantém as linhas ou colunas de uma matriz cujo valor correspondente no argumento incluir é TRUE.", + ), ("Largest number (0 when there are none).", "Maior número (0 quando não há nenhum)."), ("Largest number in a field of the matching records.", "Maior número em um campo dos registros correspondentes."), ("Largest value among cells that meet every condition.", "Maior valor entre as células que atendem a todas as condições."), From f3546f25d9b1e94cb8bc14b72d44599394057565 Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:01:49 -0300 Subject: [PATCH 052/201] Calc: a full recalc keeps former spill areas taken until their formulas are laid out again; a structural edit doesn't --- crates/calc/src/recalc.rs | 60 +++++++++++++++++++++----------------- crates/calc/src/tests.rs | 30 +++++++++++++++++++ crates/engine/src/cmd.rs | 2 +- crates/engine/src/tests.rs | 13 +++++++++ 4 files changed, 77 insertions(+), 28 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 88c3c18ed3..1abb12631f 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -116,31 +116,14 @@ struct Prior { /// Formulas that spilled, with the area they filled (from the last calculation or the file's /// `ref`). spilled: HashMap, + /// Whether those areas are where the formulas' arrays still are. Then, until a formula is laid + /// out again, its area stays taken. A structural edit moves the formulas, not the areas. + areas_in_place: bool, /// Formulas that showed #SPILL!. A cell's value moves with it on a structural edit, its spill /// area doesn't. blocked: HashSet, } -impl Prior { - /// Formulas whose new array reaches past their own former area into another formula's: they - /// are laid out after it, as in an incremental recalculation, where that area is still filled. - fn grown_into_another(&self, dirty: &[Key], spills: &HashMap>) -> HashSet { - let mut out = HashSet::default(); - for k in dirty { - let (Some(old), Some(array)) = (self.spilled.get(k), spills.get(k)) else { continue }; - let end = CellRef::new( - k.1.row.saturating_add((array.rows as u32).saturating_sub(1)), - k.1.col.saturating_add((array.cols as u32).saturating_sub(1)), - ); - let area = RangeRef::new(k.1, end); - if !old.contains_range(&area) && self.spilled.iter().any(|(o, r)| o != k && o.0 == k.0 && r.intersects(&area)) { - out.insert(*k); - } - } - out - } -} - impl Calc { pub fn new() -> Self { Self::default() @@ -218,10 +201,20 @@ impl Calc { /// Recalculates every formula (F9 / Ctrl+Alt+F9, and after loading). pub fn recalc_all(&mut self, wb: &mut Workbook) { + self.recalc_everything(wb, true); + } + + /// Recalculates every formula after rows, columns or sheets were inserted, deleted or moved: + /// the formulas moved, the spill areas they filled are where they were. + pub fn recalc_after_structural_edit(&mut self, wb: &mut Workbook) { + self.recalc_everything(wb, false); + } + + fn recalc_everything(&mut self, wb: &mut Workbook, areas_in_place: bool) { self.rebuild(wb); // Spills are laid out again from the formulas where they are now (a structural edit moves // or deletes the formulas, not the values they spilled). - let mut prior = Prior::default(); + let mut prior = Prior { areas_in_place, ..Prior::default() }; for i in 0..wb.sheets.len() { if wb.sheet(i).is_some_and(|s| !s.spill_ranges.is_empty() || !s.spill.is_empty()) && let Some(sh) = wb.sheet_mut(i) @@ -369,6 +362,13 @@ impl Calc { fn run(&mut self, wb: &mut Workbook, mut dirty: Vec, prior: &Prior) { let mut dynamic_again = !self.graph.dynamic.is_empty(); self.last_recalc_cells = 0; + // Former areas of formulas still in the workbook (a deleted formula's area is free), when + // they are still in place. + let mut former: HashMap = if prior.areas_in_place { + prior.spilled.iter().filter(|(k, _)| self.graph.nodes.contains_key(*k)).map(|(k, r)| (*k, *r)).collect() + } else { + HashMap::default() + }; for _round in 0..8 { if dirty.is_empty() { break; @@ -412,15 +412,13 @@ impl Calc { self.circular.extend(cycles); // When two arrays want the same cells, the one already spilling there keeps them and // the newcomer is #SPILL! (as when it is entered), and one that was #SPILL! stays so: - // arrays are laid out in that order, then in reading order. Of two that both spilled, - // one that grew into the other's former area comes second. Without this, a full + // arrays are laid out in that order, then in reading order. Without this, a full // recalculation or reopening the file handed the area to whichever came first. - let grown = if prior.spilled.is_empty() { HashSet::default() } else { prior.grown_into_another(&dirty, &spills) }; dirty.sort_by_key(|k| { let owns = prior.spilled.contains_key(k) || wb.sheet(k.0).is_some_and(|s| s.spill_ranges.contains_key(&k.1)); - (prior.blocked.contains(k), !owns, grown.contains(k)) + (prior.blocked.contains(k), !owns) }); - let mut spill_changes = self.write_back(wb, &dirty, results, &spills); + let mut spill_changes = self.write_back(wb, &dirty, results, &spills, &mut former); // Formulas with references only known while evaluating (INDIRECT, OFFSET) may have read // a spill area before it was laid out: they are evaluated once more. if dynamic_again && !spills.is_empty() { @@ -446,12 +444,16 @@ impl Calc { } } + /// Writes results and lays out spills. `former` holds the areas a full recalculation cleared + /// whose formulas are not laid out yet: as in an incremental recalculation, where those cells + /// are still filled, another array can't take them. fn write_back( &mut self, wb: &mut Workbook, dirty: &[Key], results: HashMap, spills: &HashMap>, + former: &mut HashMap, ) -> Vec { let mut spill_changes = Vec::new(); let mut freed = Vec::new(); @@ -464,6 +466,7 @@ impl Calc { } } for key in dirty { + let own_former = former.remove(key); let new = spills.get(key); let Some(sheet) = wb.sheet_mut(key.0) else { continue }; let old = sheet.spill_ranges.get(&key.1).copied(); @@ -486,7 +489,10 @@ impl Calc { if let Some(array) = new { let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1)); let range = RangeRef::new(key.1, end); - let blocked = spill_is_blocked(sheet, key.1, range, end); + let blocked = spill_is_blocked(sheet, key.1, range, end) + || (!former.is_empty() + && own_former.is_none_or(|f| !f.contains_range(&range)) + && former.iter().any(|(other, area)| other.0 == key.0 && area.intersects(&range))); if blocked { if let Some(cell) = sheet.cells.get_mut(key.1) { cell.value = Value::Error(CellError::Spill); diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 6a89615853..42822f6148 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -737,6 +737,36 @@ fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() { assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]); } +#[test] +fn a_full_recalc_lays_out_arrays_as_an_automatic_one_when_one_shrinks_for_another() { + // C1 grows into C3, which A3's array fills, and A3 grows into E3, which E1's array leaves. + // Automatic recalculation lays them out in reading order with each former area still filled: + // C1 is #SPILL! and A3 takes A3:E3. A full recalculation after the same edit in manual + // calculation gives the same sheet. + let build = |manual: bool| { + let mut t = T::new(); + t.set("J1", "2"); + t.set("C1", "=SEQUENCE(J1)"); + t.set("A3", "=SEQUENCE(1,J1+1)"); + t.set("E1", "=SEQUENCE(5-J1)"); + assert_eq!([t.num("C2"), t.num("C3"), t.num("E3")], [2.0, 3.0, 3.0]); + if manual { + t.wb.calc.mode = gridcraft_model::CalcMode::Manual; + } + t.set("J1", "4"); + if manual { + t.calc.recalc_all(&mut t.wb); + } + t + }; + let (automatic, full) = (build(false), build(true)); + assert_eq!(automatic.get("C1"), Value::Error(CellError::Spill)); + assert_eq!([automatic.num("A3"), automatic.num("C3"), automatic.num("E3")], [1.0, 3.0, 5.0]); + for cell in ["A1", "C1", "C2", "C3", "C4", "E1", "E2", "A3", "B3", "C3", "D3", "E3"] { + assert_eq!(full.get(cell), automatic.get(cell), "{cell}"); + } +} + #[test] fn formulas_reading_an_array_that_loses_a_spill_conflict_read_spill_errors() { // Two arrays of one recalculation want the same empty cell: the one laid out second is diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index be1a28f4d9..7392847bd2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -397,7 +397,7 @@ pub(crate) fn commit(d: &mut DocState, f: impl FnOnce(&mut Ctx) -> Result) eprintln!("commit: edit {:?}, {} changed", since(t0), changed.len()); } if structural { - d.calc.recalc_all(&mut wb); + d.calc.recalc_after_structural_edit(&mut wb); } else if !changed.is_empty() { d.calc.cells_changed(&mut wb, &changed); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 55ad67aa4a..ac11a8919c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2892,6 +2892,19 @@ fn indirect_reads_a_spill_laid_out_in_the_same_pass() { assert_eq!(v(&s, "E5"), Value::Number(9.0)); } +#[test] +fn inserting_rows_lays_out_spills_where_the_formulas_moved() { + // D1's array grows with the inserted rows to D1:D10 and C10's array moves down to C12:E14: + // the area C10:E12 it filled before the insertion blocks neither of them. + let mut s = s(); + s.execute("cell.set", json!({"cell": "D1", "input": "=SEQUENCE(ROWS(A2:A9))"})).unwrap(); + s.execute("cell.set", json!({"cell": "C8", "input": "=1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C10", "input": "=SEQUENCE(3,3)"})).unwrap(); + s.execute("home.insertRows", json!({"rows": "3:4"})).unwrap(); + assert_eq!((v(&s, "D1"), v(&s, "D10")), (Value::Number(1.0), Value::Number(10.0))); + assert_eq!((v(&s, "C12"), v(&s, "D12"), v(&s, "E14")), (Value::Number(1.0), Value::Number(2.0), Value::Number(9.0))); +} + #[test] fn every_command_survives_empty_params() { let mut s = Session::new(); From 430f53df72dbb70882d5f98869aec869e16c03f5 Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:12:33 -0300 Subject: [PATCH 053/201] Calc: former spill areas are checked through their cells, not by scanning every area --- crates/calc/src/recalc.rs | 53 ++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index 1abb12631f..d5b54dfa54 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -364,11 +364,10 @@ impl Calc { self.last_recalc_cells = 0; // Former areas of formulas still in the workbook (a deleted formula's area is free), when // they are still in place. - let mut former: HashMap = if prior.areas_in_place { - prior.spilled.iter().filter(|(k, _)| self.graph.nodes.contains_key(*k)).map(|(k, r)| (*k, *r)).collect() - } else { - HashMap::default() - }; + let mut former = Former::default(); + if prior.areas_in_place { + former.areas = prior.spilled.iter().filter(|(k, _)| self.graph.nodes.contains_key(*k)).map(|(k, r)| (*k, *r)).collect(); + } for _round in 0..8 { if dirty.is_empty() { break; @@ -445,15 +444,14 @@ impl Calc { } /// Writes results and lays out spills. `former` holds the areas a full recalculation cleared - /// whose formulas are not laid out yet: as in an incremental recalculation, where those cells - /// are still filled, another array can't take them. + /// whose formulas are not laid out yet. fn write_back( &mut self, wb: &mut Workbook, dirty: &[Key], results: HashMap, spills: &HashMap>, - former: &mut HashMap, + former: &mut Former, ) -> Vec { let mut spill_changes = Vec::new(); let mut freed = Vec::new(); @@ -466,7 +464,7 @@ impl Calc { } } for key in dirty { - let own_former = former.remove(key); + let own_former = former.take(key); let new = spills.get(key); let Some(sheet) = wb.sheet_mut(key.0) else { continue }; let old = sheet.spill_ranges.get(&key.1).copied(); @@ -490,9 +488,7 @@ impl Calc { let end = CellRef::new(key.1.row.saturating_add(array.rows as u32 - 1), key.1.col.saturating_add(array.cols as u32 - 1)); let range = RangeRef::new(key.1, end); let blocked = spill_is_blocked(sheet, key.1, range, end) - || (!former.is_empty() - && own_former.is_none_or(|f| !f.contains_range(&range)) - && former.iter().any(|(other, area)| other.0 == key.0 && area.intersects(&range))); + || (own_former.is_none_or(|f| !f.contains_range(&range)) && former.reaches(key.0, range)); if blocked { if let Some(cell) = sheet.cells.get_mut(key.1) { cell.value = Value::Error(CellError::Spill); @@ -535,6 +531,39 @@ impl Calc { } } +/// Spill areas a full recalculation cleared, of formulas not laid out yet: as in an incremental +/// recalculation, where those cells are still filled, another array can't take them. +#[derive(Default)] +struct Former { + areas: HashMap, + /// The cells of `areas`, built when an array first needs more cells than its own former area + /// (so each check costs what checking the cells themselves does, however many areas there are). + cells: Option>, +} + +impl Former { + /// Frees `key`'s former area, as it is laid out now. + fn take(&mut self, key: &Key) -> Option { + let area = self.areas.remove(key)?; + if let Some(cells) = &mut self.cells { + for cell in area.iter() { + cells.remove(&(key.0, cell)); + } + } + Some(area) + } + + /// Whether `range` on `sheet` reaches a former area that is still taken. + fn reaches(&mut self, sheet: usize, range: RangeRef) -> bool { + if self.areas.is_empty() { + return false; + } + let areas = &self.areas; + let cells = self.cells.get_or_insert_with(|| areas.iter().flat_map(|(k, area)| area.iter().map(move |cell| (k.0, cell))).collect()); + range.iter().any(|cell| cells.contains(&(sheet, cell))) + } +} + fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: CellRef, range: RangeRef, end: CellRef) -> bool { end.row >= gridcraft_core::MAX_ROWS || end.col >= gridcraft_core::MAX_COLS From 113e312809e5adebec9bc48dfb9cf858b57ffd59 Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Mon, 2 Nov 2026 16:12:40 -0300 Subject: [PATCH 054/201] Calc: index former spill areas by 64-cell squares, not by cell, on full recalc A crafted XLSX may declare up to 16 million dynamic-range cells per sheet, and opening it runs a full recalculation: the former-area cell set grew with every cell (841 MB peak, 2.4 s for 16 one-million-cell areas). The index now lists the areas over each 64 x 64 square they cover (12 MB, 13 ms for the same sheet). --- crates/calc/src/recalc.rs | 41 ++++++++++++++++++++++++++------------- crates/calc/src/tests.rs | 17 ++++++++++++++++ 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index f0a838fe06..52de341aae 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -562,21 +562,27 @@ impl Calc { #[derive(Default)] struct Former { areas: HashMap, - /// The cells of `areas`, built when an array first needs more cells than its own former area - /// (so each check costs what checking the cells themselves does, however many areas there are). - cells: Option>, + /// The areas over each [`FORMER_TILE`]-cell square of a sheet, built when an array first needs + /// more cells than its own former area. A check looks only at the areas near the array, and the + /// index grows with the squares the areas cover, not with their cells: a file's `ref`s may + /// declare millions of them. + tiles: Option>>, +} + +/// The side of [`Former`]'s index squares, in cells. +const FORMER_TILE: u32 = 64; + +/// The index squares `range` overlaps, as (row, column) square numbers. +fn former_tiles(range: RangeRef) -> impl Iterator { + let cols = range.start.col / FORMER_TILE..=range.end.col / FORMER_TILE; + (range.start.row / FORMER_TILE..=range.end.row / FORMER_TILE).flat_map(move |r| cols.clone().map(move |c| (r, c))) } impl Former { - /// Frees `key`'s former area, as it is laid out now. + /// Frees `key`'s former area, as it is laid out now. The index keeps its key; checks skip + /// keys whose area is gone. fn take(&mut self, key: &Key) -> Option { - let area = self.areas.remove(key)?; - if let Some(cells) = &mut self.cells { - for cell in area.iter() { - cells.remove(&(key.0, cell)); - } - } - Some(area) + self.areas.remove(key) } /// Whether `range` on `sheet` reaches a former area that is still taken. @@ -585,8 +591,17 @@ impl Former { return false; } let areas = &self.areas; - let cells = self.cells.get_or_insert_with(|| areas.iter().flat_map(|(k, area)| area.iter().map(move |cell| (k.0, cell))).collect()); - range.iter().any(|cell| cells.contains(&(sheet, cell))) + let tiles = self.tiles.get_or_insert_with(|| { + let mut tiles: HashMap<(usize, u32, u32), Vec> = HashMap::default(); + for (key, area) in areas { + for (r, c) in former_tiles(*area) { + tiles.entry((key.0, r, c)).or_default().push(*key); + } + } + tiles + }); + former_tiles(range) + .any(|(r, c)| tiles.get(&(sheet, r, c)).is_some_and(|keys| keys.iter().any(|k| areas.get(k).is_some_and(|area| area.intersects(&range))))) } } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 5e84c8b4eb..35f3ab0ccd 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -737,6 +737,23 @@ fn a_full_recalc_keeps_a_spill_from_an_array_that_grew_into_it() { assert_eq!([t.num("C14"), t.num("F14"), t.num("G14"), t.num("I14")], [1.0, 4.0, 5.0, 7.0]); } +#[test] +fn a_full_recalc_keeps_a_former_area_where_it_crosses_into_far_cells() { + // As above, with one array at BI14:BO14 and the other at BN13: the former area runs past + // column BL, and the array grows into the part beyond it (former areas are indexed by squares + // of cells, so the overlap must be found away from the area's first cells too). + let mut t = T::new(); + t.set("J1", "1"); + t.set("BI14", "=SEQUENCE(1,7)"); + t.set("BN13", "=SEQUENCE(J1,2)"); + assert_eq!([t.num("BN13"), t.num("BO13")], [1.0, 2.0]); + t.wb.calc.mode = gridcraft_model::CalcMode::Manual; + t.set("J1", "5"); + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.get("BN13"), Value::Error(CellError::Spill)); + assert_eq!([t.num("BI14"), t.num("BN14"), t.num("BO14")], [1.0, 6.0, 7.0]); +} + #[test] fn a_full_recalc_lays_out_arrays_as_an_automatic_one_when_one_shrinks_for_another() { // C1 grows into C3, which A3's array fills, and A3 grows into E3, which E1's array leaves. From 4b65b85b23d81c1e1c6f3ea9d9102a8e6ee699c4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:13:51 +0100 Subject: [PATCH 055/201] Quick Analysis: keep results outside the selection, refuse multi-area, plain Ctrl+Q only - analysis.addTotal / addSparklines place results beyond the selection's own far edge, so a selection reaching past the data no longer gets its totals inside it. - Both commands refuse a multi-area selection when no range is given. - Ctrl+Shift+Q and Ctrl+Alt+Q no longer toggle the popup. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/quick_analysis.rs | 26 ++++++++--- crates/engine/src/tests.rs | 45 +++++++++++++++++++ crates/ui-egui/src/ribbon/shortcuts.rs | 3 +- crates/ui-egui/tests/it/keyboard_shortcuts.rs | 12 +++++ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/quick_analysis.rs b/crates/engine/src/cmd/quick_analysis.rs index ecfa77a056..6d0ade655c 100644 --- a/crates/engine/src/cmd/quick_analysis.rs +++ b/crates/engine/src/cmd/quick_analysis.rs @@ -74,6 +74,10 @@ struct Block { /// The columns (or, `by_rows`, the rows) of `data` that hold numbers. lines: BTreeSet, by_rows: bool, + /// Last row / column the results must stay clear of: the selection's own far edge, so a + /// selection reaching past the data still gets its results outside it. Whole rows or columns + /// (reaching the sheet limit) fall back to the clipped range. + edge: CellRef, } impl Block { @@ -93,7 +97,13 @@ fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result { let sheet = target_sheet(s, p)?; let sel = match str_param(p, "range") { Some(_) => target_range(s, p)?, - None => s.doc()?.selection.current(), + None => { + // Never guess from the current area of a multi-area selection. + if s.doc()?.selection.ranges.len() > 1 { + return Err(bad(cmd, "select a single contiguous range")); + } + s.doc()?.selection.current() + } }; if sel.is_single() { return Err(bad(cmd, "select at least two cells")); @@ -130,7 +140,11 @@ fn block(s: &Session, p: &Json, by_rows: bool, cmd: &str) -> Result { if lines.is_empty() { return Err(EngineError::Other("The selection holds no numbers.".into())); } - Ok(Block { sheet, range: r, data, lines, by_rows }) + let edge = CellRef::new( + if sel.end.row >= MAX_ROWS - 1 { r.end.row } else { sel.end.row.max(r.end.row) }, + if sel.end.col >= MAX_COLS - 1 { r.end.col } else { sel.end.col.max(r.end.col) }, + ); + Ok(Block { sheet, range: r, data, lines, by_rows, edge }) } fn add_total(s: &mut Session, p: &Json) -> Result { @@ -160,11 +174,12 @@ fn add_total(s: &mut Session, p: &Json) -> Result { }; // (target, formula) pairs. let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize); - let (height, width) = (r.height(), r.width()); + let (height, width) = (b.edge.row - r.start.row + 1, b.edge.col - r.start.col + 1); for &line in &b.lines { match func { Func::Aggregate(name) => { - let target = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + let target = + if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) }; writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1()))); } Func::Percent | Func::Running => { @@ -238,12 +253,11 @@ fn add_sparklines(s: &mut Session, p: &Json) -> Result { return Err(bad(SPARK, "selection too large for this result")); } let (lo, hi) = b.span_of_line(); - let r = b.range; let sparks: Vec<(CellRef, String)> = b .lines .iter() .map(|&line| { - let at = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + let at = if by_rows { CellRef::new(line, b.edge.col.saturating_add(1)) } else { CellRef::new(b.edge.row.saturating_add(1), line) }; (at, b.line_range(line, lo, hi).a1()) }) .collect(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2a931b09a9..a573697095 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4725,6 +4725,51 @@ fn analysis_add_total_refuses_bad_and_huge_input() { assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap"); } +#[test] +fn analysis_results_stay_outside_a_selection_that_extends_past_the_data() { + let mut s = s(); + quick_analysis_block(&mut s); + // Data ends in row 4; the selection runs to row 10, so the sum goes in row 11. + let r = s.execute("analysis.addTotal", json!({"range": "A1:C10"})).unwrap(); + assert_eq!(r["output"], "B11:C11"); + assert_eq!(v(&s, "B11"), Value::Number(6.0)); + assert_eq!(v(&s, "B5"), Value::Empty); + // Per-row blocks and sparklines move out by the selection's size too. + let r = s.execute("analysis.addTotal", json!({"range": "B1:C10", "function": "runningTotal", "direction": "rows"})).unwrap(); + assert_eq!(r["output"], "B12:C14", "per-row block lands below the selection, not inside it"); + let r = s.execute("analysis.addSparklines", json!({"range": "A1:F4"})).unwrap(); + assert_eq!(r["output"], "G2:G4"); + let r = s.execute("analysis.addSparklines", json!({"range": "A1:C8", "direction": "columns"})).unwrap(); + assert_eq!(r["output"], "B9:C9"); +} + +#[test] +fn analysis_overwrite_keeps_the_target_cell_style() { + let mut s = s(); + quick_analysis_block(&mut s); + s.execute("cell.set", json!({"cell": "B5", "input": "1"})).unwrap(); + s.execute("selection.set", json!({"cell": "B5"})).unwrap(); + s.execute("home.bold", json!({})).unwrap(); + s.execute("analysis.addTotal", json!({"range": "A1:C4", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "B5"), Value::Number(6.0)); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert!(d.wb.styles.get(sh.style_id(CellRef::parse("B5").unwrap())).font.bold, "bold survives the overwrite"); +} + +#[test] +fn analysis_commands_refuse_a_multi_area_selection_without_a_range() { + let mut s = s(); + quick_analysis_block(&mut s); + s.execute("selection.set", json!({"range": "A1:C4,E1:F4"})).unwrap(); + assert!(s.execute("analysis.addTotal", json!({})).is_err()); + assert!(s.execute("analysis.addSparklines", json!({})).is_err()); + assert_eq!(v(&s, "B5"), Value::Empty); + // An explicit range still works. + s.execute("analysis.addTotal", json!({"range": "A1:C4"})).unwrap(); + assert_eq!(v(&s, "B5"), Value::Number(6.0)); +} + #[test] fn analysis_add_sparklines_one_per_row_in_one_undo_step() { let mut s = s(); diff --git a/crates/ui-egui/src/ribbon/shortcuts.rs b/crates/ui-egui/src/ribbon/shortcuts.rs index 1af3dcc820..2eb118cd1f 100644 --- a/crates/ui-egui/src/ribbon/shortcuts.rs +++ b/crates/ui-egui/src/ribbon/shortcuts.rs @@ -42,7 +42,8 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T if shift => Some(("formulas.autoSum", json!({}))), Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), - Key::Q => { + // Plain Ctrl+Q only: Ctrl+Shift+Q and Ctrl+Alt+Q (AltGr+Q) are not Quick Analysis. + Key::Q if !shift && !m.alt => { // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert, // but several areas deserve to be told why nothing opened. if let Err(e) = crate::quick_analysis::toggle(app, None) diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index f59504dee4..56dadde3ae 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -303,3 +303,15 @@ fn ctrl_alt_letter_that_typed_text_is_not_select_all() { assert_eq!(h.state().session.active().unwrap().selection.current().a1(), "B2"); assert_eq!(h.state().editor.as_ref().unwrap().text, "\u{e4}"); } + +/// Only plain Ctrl+Q toggles Quick Analysis; Ctrl+Shift+Q and Ctrl+Alt+Q (AltGr+Q) do not. +#[test] +fn only_plain_ctrl_q_toggles_quick_analysis() { + let mut h = harness(book("A1:B3")); + key(&mut h, Key::Q, CTRL_SHIFT); + assert!(h.state().grid.quick_analysis.open.is_none(), "Ctrl+Shift+Q"); + key(&mut h, Key::Q, Modifiers { alt: true, ..CTRL }); + assert!(h.state().grid.quick_analysis.open.is_none(), "Ctrl+Alt+Q"); + key(&mut h, Key::Q, CTRL); + assert!(h.state().grid.quick_analysis.open.is_some(), "Ctrl+Q"); +} From 335109beb5ba780f3b1c90cd7b949dbfb9baabd9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:16:37 +0100 Subject: [PATCH 056/201] Quick Analysis: assert the multi-area error text Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a573697095..4461bc7994 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4762,8 +4762,10 @@ fn analysis_commands_refuse_a_multi_area_selection_without_a_range() { let mut s = s(); quick_analysis_block(&mut s); s.execute("selection.set", json!({"range": "A1:C4,E1:F4"})).unwrap(); - assert!(s.execute("analysis.addTotal", json!({})).is_err()); - assert!(s.execute("analysis.addSparklines", json!({})).is_err()); + for c in ["analysis.addTotal", "analysis.addSparklines"] { + let e = s.execute(c, json!({})).unwrap_err().to_string(); + assert!(e.contains("single contiguous range"), "{c}: {e}"); + } assert_eq!(v(&s, "B5"), Value::Empty); // An explicit range still works. s.execute("analysis.addTotal", json!({"range": "A1:C4"})).unwrap(); From def4067247e25191363eca7d2c325c8c39c5f9b6 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:22:50 +0100 Subject: [PATCH 057/201] AutoSum: main's Function Library test expects the proposal in the editor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Formulas › AutoSum and its Count Numbers item on one cell now leave `=SUM(A1:A3)` / `=COUNT(B1:B3)` in the editor until Enter, as in Excel (#1834); the test checks the proposal, presses Enter, then the cell. --- crates/ui-egui/tests/it/function_library.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/ui-egui/tests/it/function_library.rs b/crates/ui-egui/tests/it/function_library.rs index a1a7a1a37e..3cb132adc3 100644 --- a/crates/ui-egui/tests/it/function_library.rs +++ b/crates/ui-egui/tests/it/function_library.rs @@ -136,6 +136,10 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() { } h.run_steps(2); click(&mut h, "AutoSum"); + // One cell: the proposed formula waits in the editor for Enter, as in Excel (#1834). + assert_eq!(editor_text(&h).as_deref(), Some("=SUM(A1:A3)")); + h.key_press(Key::Enter); + h.run_steps(2); assert_eq!(input(&h, "A4"), "=SUM(A1:A3)"); h.state_mut().session.execute("selection.set", json!({"cell": "B4"})).unwrap(); click(&mut h, "AutoSum options"); @@ -143,6 +147,9 @@ fn autosum_runs_sum_and_its_arrow_opens_the_shared_menu() { h.get_by_label(item); } click(&mut h, "Count Numbers"); + assert_eq!(editor_text(&h).as_deref(), Some("=COUNT(B1:B3)")); + h.key_press(Key::Enter); + h.run_steps(2); assert_eq!(input(&h, "B4"), "=COUNT(B1:B3)"); click(&mut h, "AutoSum options"); click(&mut h, "More Functions…"); From 2829120d4dd7ef54db7aa5afa6c44d5e1b464b32 Mon Sep 17 00:00:00 2001 From: kezmdor <15539254+kezmdor@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:24:10 +0100 Subject: [PATCH 058/201] Recently Used: a sign before a space starts a formula too main's `functions_in_formula` test expected `- SUM(1)` not to be a formula. With #2023's rule, which `is_formula_input` now uses, it is one, as Excel for the web enters `- remember this` as `=- remember this`. --- crates/engine/src/recent.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/recent.rs b/crates/engine/src/recent.rs index 0a1bba2dc2..2bd8a375cb 100644 --- a/crates/engine/src/recent.rs +++ b/crates/engine/src/recent.rs @@ -154,7 +154,9 @@ mod tests { assert_eq!(functions_in_formula("+SUM(1)"), ["SUM"]); assert_eq!(functions_in_formula("-ABS(A1)"), ["ABS"]); assert!(functions_in_formula("-5").is_empty() && functions_in_formula("+1e3").is_empty(), "numbers"); - assert!(functions_in_formula("+").is_empty() && functions_in_formula("- SUM(1)").is_empty(), "not formulas"); + assert!(functions_in_formula("+").is_empty() && functions_in_formula("--").is_empty(), "not formulas"); + // A sign before a space still starts a formula, as Excel takes `- SUM(1)` (#2023). + assert_eq!(functions_in_formula("- SUM(1)"), ["SUM"]); } #[test] From a7a319c5c7d077f6681d6257c43b675683bcc8fb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 17:26:11 +0100 Subject: [PATCH 059/201] Quick Analysis: close the popup when the active sheet changes The popup remembered only the range, so another sheet with the same selection kept it open and the tiles ran against that sheet. It now remembers the sheet too. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/quick_analysis.rs | 14 ++++++----- .../ui-egui/tests/it/quick_analysis_button.rs | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 3843ea6bfa..ea257ccd8b 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -44,8 +44,8 @@ impl Tab { #[derive(Default)] pub struct State { - /// The selection the popup was opened for; it closes when the selection changes. - pub open: Option, + /// The sheet (by index) and selection the popup was opened for; it closes when either changes. + pub open: Option<(usize, RangeRef)>, pub tab: Tab, /// Totals by row (results to the right) instead of by column (results below). pub by_rows: bool, @@ -145,13 +145,14 @@ pub fn toggle(app: &mut SheetApp, on: Option) -> Result { return Err("Quick Analysis works on one block of cells; select a single contiguous range.".into()); } let sel = d.selection.current(); + let sheet = d.wb.active_sheet(); let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); if !want { app.grid.quick_analysis.open = None; } else if sel.is_single() { return Err("Select at least two cells to use Quick Analysis.".into()); } else { - app.grid.quick_analysis.open = Some(sel); + app.grid.quick_analysis.open = Some((sheet, sel)); } Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) } @@ -187,9 +188,10 @@ pub fn button_rect(geo: &Geo, sh: &Sheet, sel: RangeRef) -> (Rect, bool) { pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let Some(d) = app.session.active() else { return }; let sel = d.selection.current(); + let sheet = d.wb.active_sheet(); let hidden = is_hidden(app, geo, sh); - // The popup belongs to one selection; a new one (or editing) closes it. - if hidden || app.grid.quick_analysis.open.is_some_and(|r| r != sel) { + // The popup belongs to one selection on one sheet; a new one (or editing) closes it. + if hidden || app.grid.quick_analysis.open.is_some_and(|(opened_on, r)| opened_on != sheet || r != sel) { app.grid.quick_analysis.open = None; } if hidden { @@ -226,7 +228,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let _ = toggle(app, None); } } - let Some(opened_for) = app.grid.quick_analysis.open else { return }; + let Some((_, opened_for)) = app.grid.quick_analysis.open else { return }; let pos = pos2(button.left(), button.bottom() + 4.0); let mut picked: Option = None; let resp = egui::Area::new(Id::unique("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { diff --git a/crates/ui-egui/tests/it/quick_analysis_button.rs b/crates/ui-egui/tests/it/quick_analysis_button.rs index 65fa142d91..3213c8cec9 100644 --- a/crates/ui-egui/tests/it/quick_analysis_button.rs +++ b/crates/ui-egui/tests/it/quick_analysis_button.rs @@ -82,3 +82,26 @@ fn hidden_for_areas(app: &SheetApp) -> bool { let g = geo(app); is_hidden(app, &g, app.session.active().unwrap().wb.active().unwrap()) } + +/// The popup is tied to the sheet it was opened on: a sheet that remembers the same selection +/// must not inherit it, or the tiles would act on the wrong sheet. +#[test] +fn switching_sheets_closes_the_popup_even_for_the_same_selection() { + let mut app = app(); + app.run("home.insertSheet", json!({})).unwrap(); + app.run("sheet.activate", json!({"sheet": 0})).unwrap(); + app.run("selection.set", json!({"range": "B2:D5"})).unwrap(); + toggle(&mut app, Some(true)).unwrap(); + let frame = |app: &mut SheetApp| { + let sh = app.session.active().unwrap().wb.active().unwrap().clone(); + let g = Geo::new(&sh, Rect::from_min_max(pos2(0.0, 0.0), pos2(1200.0, 800.0)), Vec2::ZERO); + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |ui| gridcraft_ui_egui::quick_analysis::show(app, ui, &g, &sh)).drop_without_applying_deltas(); + }; + frame(&mut app); + assert!(app.grid.quick_analysis.open.is_some(), "the popup stays open on its own sheet"); + app.run("sheet.activate", json!({"sheet": 1})).unwrap(); + app.run("selection.set", json!({"range": "B2:D5"})).unwrap(); + frame(&mut app); + assert!(app.grid.quick_analysis.open.is_none(), "another sheet with the same selection closes it"); +} From 2240950eb650ad5016e5abebb10ce226dded5e7f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 17:39:33 +0100 Subject: [PATCH 060/201] Quick Analysis: Esc closes the popup only; bind it to the sheet's identity Esc used to clear the pending copy and Format Painter before the popup saw it. The popup also remembers the sheet by its identity rather than its position, so moving sheets cannot hand it to another sheet. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/grid/keyboard.rs | 14 ++++++--- crates/ui-egui/src/quick_analysis.rs | 10 +++---- .../ui-egui/tests/it/quick_analysis_button.rs | 29 +++++++++++++++++++ 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index a852d04c33..3fce6bedb8 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -133,10 +133,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res } } Key::Escape if app.selected_object.is_some() => app.selected_object = None, - Key::Escape => { - app.session.clipboard = None; - app.session.format_painter = None; - } + Key::Escape => cancel_pending(app), Key::Space if !cmd && !shift && is_checkbox(sh, app) => app.run_or_alert("cell.toggleCheckbox", json!({})), Key::F8 if m.alt => { app.open_dialog("macros", json!({})); @@ -187,3 +184,12 @@ fn form_control_event(app: &mut SheetApp, sh: &Sheet, ev: &egui::Event) -> bool _ => false, } } + +/// Esc with nothing else to dismiss drops the pending copy and the Format Painter. An open Quick +/// Analysis popup owns the key: it closes and the pending copy stays. +fn cancel_pending(app: &mut SheetApp) { + if app.grid.quick_analysis.open.take().is_none() { + app.session.clipboard = None; + app.session.format_painter = None; + } +} diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index ea257ccd8b..f7db7b5697 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -44,8 +44,8 @@ impl Tab { #[derive(Default)] pub struct State { - /// The sheet (by index) and selection the popup was opened for; it closes when either changes. - pub open: Option<(usize, RangeRef)>, + /// The sheet (by its identity, not its position) and selection the popup was opened for; it closes when either changes. + pub open: Option<(u64, RangeRef)>, pub tab: Tab, /// Totals by row (results to the right) instead of by column (results below). pub by_rows: bool, @@ -145,7 +145,7 @@ pub fn toggle(app: &mut SheetApp, on: Option) -> Result { return Err("Quick Analysis works on one block of cells; select a single contiguous range.".into()); } let sel = d.selection.current(); - let sheet = d.wb.active_sheet(); + let sheet = d.wb.active().map_or(0, |s| s.uid.get()); let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); if !want { app.grid.quick_analysis.open = None; @@ -188,7 +188,7 @@ pub fn button_rect(geo: &Geo, sh: &Sheet, sel: RangeRef) -> (Rect, bool) { pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let Some(d) = app.session.active() else { return }; let sel = d.selection.current(); - let sheet = d.wb.active_sheet(); + let sheet = d.wb.active().map_or(0, |s| s.uid.get()); let hidden = is_hidden(app, geo, sh); // The popup belongs to one selection on one sheet; a new one (or editing) closes it. if hidden || app.grid.quick_analysis.open.is_some_and(|(opened_on, r)| opened_on != sheet || r != sel) { @@ -269,7 +269,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { Action::Run(id, params) => app.run_or_alert(id, params), Action::Dialog(name, params) => app.open_dialog(name, params), } - } else if outside_click || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + } else if outside_click || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { app.grid.quick_analysis.open = None; } } diff --git a/crates/ui-egui/tests/it/quick_analysis_button.rs b/crates/ui-egui/tests/it/quick_analysis_button.rs index 3213c8cec9..9a5e1f2b14 100644 --- a/crates/ui-egui/tests/it/quick_analysis_button.rs +++ b/crates/ui-egui/tests/it/quick_analysis_button.rs @@ -105,3 +105,32 @@ fn switching_sheets_closes_the_popup_even_for_the_same_selection() { frame(&mut app); assert!(app.grid.quick_analysis.open.is_none(), "another sheet with the same selection closes it"); } + +/// Esc dismisses the popup and nothing else: the pending copy (and an armed Format Painter) stay. +#[test] +fn escape_closes_the_popup_without_cancelling_the_pending_copy() { + let mut session = crate::support::blank_session(); + session.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3], [4, 5, 6]]})).unwrap(); + session.execute("selection.set", json!({"range": "A1:C2"})).unwrap(); + session.execute("edit.copy", json!({})).unwrap(); + let mut h = crate::support::harness(session, 4); + assert!(h.state().session.clipboard.is_some()); + toggle(h.state_mut(), Some(true)).unwrap(); + h.run_steps(2); + assert!(h.state().grid.quick_analysis.open.is_some()); + let esc = |h: &mut crate::common::Harness| { + h.input_mut().events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(2); + }; + esc(&mut h); + assert!(h.state().grid.quick_analysis.open.is_none(), "Esc closes the popup"); + assert!(h.state().session.clipboard.is_some(), "the copy stays pending"); + esc(&mut h); + assert!(h.state().session.clipboard.is_none(), "a second Esc, with no popup, cancels the copy as before"); +} From e4e2c5292aabd8dd98d4eddeccfddcbbbe2a0e1e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 8 Nov 2026 11:24:12 +1100 Subject: [PATCH 061/201] XLSX: NETWORKDAYS.INTL and WORKDAY.INTL are saved without _xlfn. (#3517) Both are in the file format's own function list, so a file stores them unprefixed; LibreOffice gives #NAME? for the prefixed spelling. They are removed from FUTURE_FUNCTIONS. A file with the prefix still reads (the parser strips it). --- crates/xlsx/src/fmla.rs | 12 ++++++++++++ crates/xlsx/src/tables.rs | 7 +++---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/xlsx/src/fmla.rs b/crates/xlsx/src/fmla.rs index 29dd20870b..acd90f8d92 100644 --- a/crates/xlsx/src/fmla.rs +++ b/crates/xlsx/src/fmla.rs @@ -319,6 +319,18 @@ mod tests { assert!(checked > gridcraft_functions::all().len() * 10, "only {checked} formulas parsed"); } + /// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list: saved without + /// `_xlfn.` (LibreOffice gives #NAME? for the prefixed spelling), and the prefixed spelling of a + /// file written by an older version still reads (#3517, #2775). + #[test] + fn intl_day_functions_are_saved_without_the_prefix() { + let f = Formula::new("NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)"); + assert_eq!(to_file(&f), "NETWORKDAYS.INTL(DATE(2026,1,5),DATE(2026,1,9),1)+WORKDAY.INTL(DATE(2026,1,5),3,1)"); + assert_eq!(text_to_file("=WORKDAY.INTL(A1,3,1)"), "WORKDAY.INTL(A1,3,1)"); + assert_eq!(from_file("_xlfn.NETWORKDAYS.INTL(A1,B1,1)+_xlfn.WORKDAY.INTL(A1,3,1)"), "NETWORKDAYS.INTL(A1,B1,1)+WORKDAY.INTL(A1,3,1)"); + assert_eq!(from_file("NETWORKDAYS.INTL(A1,B1,1)"), "NETWORKDAYS.INTL(A1,B1,1)"); + } + #[test] fn spill_references() { assert_eq!(to_file(&Formula::new("SUM(Sheet1!$D$1#)+B2#")), "SUM(_xlfn.ANCHORARRAY(Sheet1!$D$1))+_xlfn.ANCHORARRAY(B2)"); diff --git a/crates/xlsx/src/tables.rs b/crates/xlsx/src/tables.rs index 3cfd84c2dc..06b3beb3af 100644 --- a/crates/xlsx/src/tables.rs +++ b/crates/xlsx/src/tables.rs @@ -111,6 +111,7 @@ pub fn paper_id(name: &str) -> Option { /// Functions introduced after Excel 2007 that files store with the `_xlfn.` prefix. Entries with /// `_xlws.` get `_xlfn._xlws.`. +/// NETWORKDAYS.INTL and WORKDAY.INTL are in the file format's own function list, so they're saved without `_xlfn.` (#3517). const FUTURE_FUNCTIONS: &[&str] = &[ "ACOT", "ACOTH", @@ -207,7 +208,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[ "MODE.SNGL", "MUNIT", "NEGBINOM.DIST", - "NETWORKDAYS.INTL", "NORM.DIST", "NORM.INV", "NORM.S.DIST", @@ -270,7 +270,6 @@ const FUTURE_FUNCTIONS: &[&str] = &[ "VSTACK", "WEBSERVICE", "WEIBULL.DIST", - "WORKDAY.INTL", "WRAPCOLS", "WRAPROWS", "XLOOKUP", @@ -358,8 +357,8 @@ mod tests { assert_eq!(file_function_name("stockhistory").as_deref(), Some("_xlfn.STOCKHISTORY")); assert_eq!(file_function_name("TRANSLATE").as_deref(), Some("_xlfn.TRANSLATE")); assert_eq!(file_function_name("DETECTLANGUAGE").as_deref(), Some("_xlfn.DETECTLANGUAGE")); - assert_eq!(file_function_name("NETWORKDAYS.INTL").as_deref(), Some("_xlfn.NETWORKDAYS.INTL")); - assert_eq!(file_function_name("WORKDAY.INTL").as_deref(), Some("_xlfn.WORKDAY.INTL")); + assert_eq!(file_function_name("NETWORKDAYS.INTL"), None); + assert_eq!(file_function_name("WORKDAY.INTL"), None); // Excel 16.0 build 20527 saves COPILOT as plain `COPILOT(...)` (it does not know the name yet). assert_eq!(file_function_name("COPILOT"), None); assert_eq!(file_function_name("SUM"), None); From d098a7dfc3c846f4b03387aa430de80e3c3ee8a2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 12:39:04 +0100 Subject: [PATCH 062/201] UI: Excel for Mac Control+Q opens Quick Analysis; Command+Q stays Quit ribbon::shortcut is only reached with the command modifier, so on a Mac Control+Q did nothing and Command+Q toggled Quick Analysis next to the native Quit item. The keymap now maps Mac Control+Q (without Command, Option or Shift) to Shortcut::QuickAnalysis, which shares the ribbon handler and its single-cell alert suppression, and the ribbon Q branch ignores Command on a Mac. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/keymap.rs | 5 ++++ crates/ui-egui/src/ribbon.rs | 1 + crates/ui-egui/src/ribbon/shortcuts.rs | 21 ++++++++++------ crates/ui-egui/tests/it/keyboard_shortcuts.rs | 25 +++++++++++++++++++ docs/ui-parity.md | 4 +-- 5 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 5acce9b4d7..7e04fe72d9 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -41,6 +41,8 @@ pub enum Shortcut { Zoom(i32), /// Ctrl+Alt+Shift+P: edit the active cell as Python code (Python mode). PythonMode, + /// Excel for Mac Control+Q: Quick Analysis (Windows Ctrl+Q is in `ribbon::shortcut`). + QuickAnalysis, } fn run(id: &'static str) -> Shortcut { @@ -139,6 +141,8 @@ fn lookup_control_shortcuts(ctx: LookupContext) -> Option { // Windows Ctrl+; is in `ribbon::shortcut`; Excel for Mac uses Control+; and Command+;. Semicolon if mac && ctrl => Shortcut::Date, Semicolon if mac && cmd && !s => Shortcut::Time, + // Control+Q only: Command+Q is the native Quit item. + Q if mac && ctrl && !m.command && !s => Shortcut::QuickAnalysis, _ => return None, }) } @@ -349,6 +353,7 @@ pub(crate) fn dispatch(app: &mut SheetApp, ctx: &egui::Context, key: Key, physic } Shortcut::Edit => app.begin_edit(None, false), Shortcut::PythonMode => app.toggle_python_mode(), + Shortcut::QuickAnalysis => crate::ribbon::quick_analysis(app), Shortcut::ContextMenu => app.grid.context_menu = Some(geo.cell_rect(sh, active).center()), Shortcut::DropDown => { if sh.validations.iter().any(|d| d.in_cell_dropdown && d.ranges.iter().any(|r| r.contains(active))) { diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 47f1eabd73..4e8ba9dd28 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -37,6 +37,7 @@ use home::home; use insert::{draw, insert}; use page_layout::page_layout; use review::review; +pub(crate) use shortcuts::quick_analysis; pub use shortcuts::shortcut; pub use title_bar::{MAC_CONTENT_LEFT, MAC_TITLE_BAR, TITLE_LEFT_PAD, title_bar}; use title_bar::{TITLE_BAR_H, TITLE_CONTROL_H}; diff --git a/crates/ui-egui/src/ribbon/shortcuts.rs b/crates/ui-egui/src/ribbon/shortcuts.rs index 2eb118cd1f..53d99318b7 100644 --- a/crates/ui-egui/src/ribbon/shortcuts.rs +++ b/crates/ui-egui/src/ribbon/shortcuts.rs @@ -1,5 +1,15 @@ use super::{Key, Modifiers, SheetApp, json}; +/// Ctrl+Q (Control+Q in Excel for Mac): Quick Analysis. A single cell has nothing to analyse, +/// which is not worth an alert, but several areas deserve to be told why nothing opened. +pub(crate) fn quick_analysis(app: &mut SheetApp) { + if let Err(e) = crate::quick_analysis::toggle(app, None) + && app.session.active().is_some_and(|d| d.selection.ranges.len() > 1) + { + app.alert(e); + } +} + /// Command-key shortcuts when the grid has focus. pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { let shift = m.shift; @@ -43,14 +53,9 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), // Plain Ctrl+Q only: Ctrl+Shift+Q and Ctrl+Alt+Q (AltGr+Q) are not Quick Analysis. - Key::Q if !shift && !m.alt => { - // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert, - // but several areas deserve to be told why nothing opened. - if let Err(e) = crate::quick_analysis::toggle(app, None) - && app.session.active().is_some_and(|d| d.selection.ranges.len() > 1) - { - app.alert(e); - } + // Command+Q on a Mac is the native Quit item; Control+Q there goes through the keymap. + Key::Q if !shift && !m.alt && !m.mac_cmd => { + quick_analysis(app); None } Key::Num1 => { diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index 56dadde3ae..ff0510fb23 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -315,3 +315,28 @@ fn only_plain_ctrl_q_toggles_quick_analysis() { key(&mut h, Key::Q, CTRL); assert!(h.state().grid.quick_analysis.open.is_some(), "Ctrl+Q"); } + +/// Excel for Mac: Control+Q (ctrl without command) opens Quick Analysis, Command+Q is left to the +/// native Quit item, and a single cell still opens nothing without an alert. +#[test] +fn mac_control_q_toggles_quick_analysis_and_command_q_does_not() { + const MAC_CONTROL: Modifiers = Modifiers { alt: false, ctrl: true, shift: false, mac_cmd: false, command: false }; + const MAC_COMMAND: Modifiers = Modifiers { alt: false, ctrl: false, shift: false, mac_cmd: true, command: true }; + assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_CONTROL, true), Some(Shortcut::QuickAnalysis)); + assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_COMMAND, true), None); + assert_eq!(lookup(Key::Q, Some(Key::Q), MAC_CONTROL, false), None, "Windows Ctrl+Q goes through ribbon::shortcut"); + let mac = |sel: &str| crate::common::os_harness(book(sel), egui::os::OperatingSystem::Mac); + let mut h = mac("A1:B3"); + key(&mut h, Key::Q, MAC_COMMAND); + assert!(h.state().grid.quick_analysis.open.is_none(), "Command+Q is Quit"); + key(&mut h, Key::Q, Modifiers { shift: true, ..MAC_CONTROL }); + assert!(h.state().grid.quick_analysis.open.is_none(), "Control+Shift+Q"); + key(&mut h, Key::Q, MAC_CONTROL); + assert!(h.state().grid.quick_analysis.open.is_some(), "Control+Q opens"); + key(&mut h, Key::Q, MAC_CONTROL); + assert!(h.state().grid.quick_analysis.open.is_none(), "Control+Q again closes"); + let mut h = mac("B2"); + key(&mut h, Key::Q, MAC_CONTROL); + assert!(h.state().grid.quick_analysis.open.is_none()); + assert!(h.state().message.is_none() && h.state().toast.is_none(), "no alert for a single cell"); +} diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 121c45d5a4..8c747c1528 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -145,10 +145,10 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | Ctrl+Alt+Shift+P | Cmd+Option+Shift+P | Python mode on or off | **added** | | F3 | not checked | Paste Name dialog, only when the workbook has names: OK puts the name at the caret of the formula being edited (or starts `=Name`), Paste List writes each name and what it refers to from the active cell (`formulas.pasteName`) | **added** | | F1, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | -| Ctrl+Q | Ctrl+Q | Quick Analysis | **added** (#791) | +| Ctrl+Q | Control+Q (Cmd+Q stays Quit) | Quick Analysis | **added** (#791) | | Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | Function Arguments, formula bar height, tooltips | missing | | F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | -| Ctrl+Q | Ctrl+Q | Quick Analysis | **added** (#791) | +| Ctrl+Q | Control+Q (Cmd+Q stays Quit) | Quick Analysis | **added** (#791) | | Ctrl+A after a function name, Ctrl+Alt+P | same | Function Arguments, tooltips | missing | | Ctrl+Shift+A after a function name | Control+Shift+A | argument names: `=SUMIF(` becomes `=SUMIF(range,criteria,sum_range)`, the `(` added when missing; one Undo takes them back | **added** | | Ctrl+Shift+U | Control+Shift+U | expand or collapse the formula bar (`view.expandFormulaBar`), on the grid and while editing; on Windows and Linux it no longer underlines | **added** | From c16c5865b1249ba84670e2392d0ed1fa0c012931 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 22:33:43 +0100 Subject: [PATCH 063/201] fix(i18n): translate status bar statistics, resize tips, sheet notes and macro toasts Strings that were built with format! in English now translate their template first and fill it in once (Language::tr_fill), so a value holding `{...}` is never filled again: status bar statistics and the circular reference note, the column width / row height drag tip, the formula bar text for a picture in a cell, the Move or Copy and Unhide notes, the Format Control title, the equation editor's error prefix, and the Goal Seek and macro recorder/runner toasts. New keys go into every catalog. Fixes #3600, #3602, #3603, #3605, #3607, #3608, #3609, #3610, #3611 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/control_ui.rs | 24 ++++++++- crates/ui-egui/src/dialogs.rs | 52 +++++++++++++++++- crates/ui-egui/src/dialogs/analysis.rs | 5 +- crates/ui-egui/src/equation.rs | 27 ++++++++-- crates/ui-egui/src/formula_bar.rs | 28 +++++++++- crates/ui-egui/src/grid/interact.rs | 30 +++++++++-- crates/ui-egui/src/i18n.rs | 73 ++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 23 ++++++++ crates/ui-egui/src/i18n/de.rs | 25 +++++++++ crates/ui-egui/src/i18n/el.rs | 17 ++++++ crates/ui-egui/src/i18n/es.rs | 23 ++++++++ crates/ui-egui/src/i18n/fr.rs | 23 ++++++++ crates/ui-egui/src/i18n/it.rs | 17 ++++++ crates/ui-egui/src/i18n/ja.rs | 17 ++++++ crates/ui-egui/src/i18n/ko.rs | 23 ++++++++ crates/ui-egui/src/i18n/nl.rs | 23 ++++++++ crates/ui-egui/src/i18n/pl.rs | 17 ++++++ crates/ui-egui/src/i18n/pt.rs | 17 ++++++ crates/ui-egui/src/i18n/ro.rs | 17 ++++++ crates/ui-egui/src/i18n/ru.rs | 23 ++++++++ crates/ui-egui/src/i18n/sr.rs | 23 ++++++++ crates/ui-egui/src/i18n/tr.rs | 23 ++++++++ crates/ui-egui/src/i18n/uk.rs | 29 +++++++--- crates/ui-egui/src/i18n/vi.rs | 23 ++++++++ crates/ui-egui/src/i18n/zh.rs | 23 ++++++++ crates/ui-egui/src/macro_ui.rs | 65 +++++++++++++++++++++-- crates/ui-egui/src/tabs.rs | 40 +++++++++++--- docs/localization-parity.md | 3 +- 28 files changed, 701 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/control_ui.rs b/crates/ui-egui/src/control_ui.rs index 70603ef1d3..a44442942a 100644 --- a/crates/ui-egui/src/control_ui.rs +++ b/crates/ui-egui/src/control_ui.rs @@ -455,7 +455,7 @@ pub fn open_format(app: &SheetApp, params: &Json) -> Option { "print": c.print, "locked": c.locked, }); - let title = if text_only { "Edit Text".to_string() } else { format!("Format Control: {}", c.display_name()) }; + let title = if text_only { "Edit Text".to_string() } else { app.ui.language.tr_fill("Format Control: {name}", &[("name", &c.display_name())]) }; Some(Dialog::custom("formatControl", &title, v)) } @@ -567,3 +567,25 @@ pub fn format_dialog(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, open: &mut } } } + +#[cfg(test)] +mod format_title_tests { + use super::*; + use crate::i18n::Language; + use gridcraft_engine::Session; + + #[test] + fn the_format_control_title_follows_the_interface_language() { + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + let v = app.run("insert.button", json!({"at": "B2", "text": "Go"})).unwrap(); + let id = v["control"].as_u64().unwrap(); + let name = control(&app, id as u32).unwrap().display_name(); + assert_eq!(open_format(&app, &json!({"id": id})).unwrap().title, format!("Format Control: {name}")); + app.ui.language = Language::It; + let want = Language::It.tr("Format Control: {name}").replace("{name}", &name); + assert_eq!(open_format(&app, &json!({"id": id})).unwrap().title, want); + assert!(!want.starts_with("Format Control")); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 47b215302e..e5d157e88c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -359,7 +359,7 @@ impl Dialog { vec![ Number { key: "to", label: "Before sheet (position, 0 = first):" }, Check { key: "copy", label: "Create a copy" }, - Note(format!("Sheets: {}", sheets.join(", "))), + Note(app.ui.language.tr_fill("Sheets: {sheets}", &[("sheets", &sheets.join(", "))])), ], json!({"to": 0, "copy": false}), ); @@ -476,7 +476,10 @@ impl Dialog { "unhideSheet", "Unhide", "sheet.unhide", - vec![Text { key: "sheet", label: "Unhide sheet:" }, Note(format!("Hidden: {}", opts.join(", ")))], + vec![ + Text { key: "sheet", label: "Unhide sheet:" }, + Note(app.ui.language.tr_fill("Hidden: {sheets}", &[("sheets", &opts.join(", "))])), + ], json!({"sheet": first}), ); d.values.insert("sheet".into(), json!(first)); @@ -1140,6 +1143,51 @@ impl Dialog { mod tests { use super::*; + /// The text of the dialog's note. + fn note(d: &Dialog) -> String { + d.fields.iter().find_map(|f| if let Field::Note(text) = f { Some(text.clone()) } else { None }).unwrap_or_default() + } + + #[test] + fn sheet_notes_follow_the_interface_language() { + use crate::i18n::Language; + let mut session = gridcraft_engine::Session::default(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + app.run("home.insertSheet", json!({})).unwrap(); + let unhide = json!({"sheets": ["Sheet2"]}); + assert_eq!(note(&Dialog::open(&mut app, "moveSheet", json!({})).unwrap()), "Sheets: Sheet1, Sheet2"); + assert_eq!(note(&Dialog::open(&mut app, "unhideSheet", unhide.clone()).unwrap()), "Hidden: Sheet2"); + let it = Language::It; + app.ui.language = it; + let moved = note(&Dialog::open(&mut app, "moveSheet", json!({})).unwrap()); + assert_eq!(moved, it.tr("Sheets: {sheets}").replace("{sheets}", "Sheet1, Sheet2")); + assert!(!moved.starts_with("Sheets")); + let hidden = note(&Dialog::open(&mut app, "unhideSheet", unhide).unwrap()); + assert_eq!(hidden, it.tr("Hidden: {sheets}").replace("{sheets}", "Sheet2")); + assert!(!hidden.starts_with("Hidden")); + } + + #[test] + fn goal_seek_success_toast_follows_the_interface_language() { + use crate::i18n::Language; + let mut session = gridcraft_engine::Session::default(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + app.run("cell.set", json!({"cell": "B1", "input": "=A1*2"})).unwrap(); + let it = Language::It; + app.ui.language = it; + let mut d = Dialog::custom("goalSeek", "Goal Seek", json!({"set": "B1", "to": "10", "changing": "A1"})); + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| analysis::goal_seek(&mut app, ui, &mut d, &mut true, &mut true)); + out.textures_delta.clear(); + assert_eq!(app.message, None); + // The value is shown as before (the JSON number the command returns). + let want = it.tr("Goal Seeking found a solution: {value}").replace("{value}", "5.0"); + assert_eq!(app.toast.map(|t| t.0), Some(want.clone())); + assert!(!want.starts_with("Goal Seeking")); + } + #[test] fn remove_duplicates_prefills_the_selection_and_submits_the_edited_range() { let mut session = gridcraft_engine::Session::default(); diff --git a/crates/ui-egui/src/dialogs/analysis.rs b/crates/ui-egui/src/dialogs/analysis.rs index 6a49cdaaaa..9fb510c121 100644 --- a/crates/ui-egui/src/dialogs/analysis.rs +++ b/crates/ui-egui/src/dialogs/analysis.rs @@ -34,7 +34,10 @@ pub(super) fn goal_seek(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, c } if *confirm { match app.run("data.goalSeek", json!({"set": set, "to": to.parse::().unwrap_or(0.0), "changing": changing})) { - Ok(r) => app.toast = Some((format!("Goal Seeking found a solution: {}", r["value"]), crate::now_ms())), + Ok(r) => { + let text = app.ui.language.tr_fill("Goal Seeking found a solution: {value}", &[("value", &r["value"].to_string())]); + app.toast = Some((text, crate::now_ms())); + } Err(e) => app.message = Some(("Goal Seek".into(), crate::clean_error(&e))), } } diff --git a/crates/ui-egui/src/equation.rs b/crates/ui-egui/src/equation.rs index 93afc72b38..e412be107c 100644 --- a/crates/ui-egui/src/equation.rs +++ b/crates/ui-egui/src/equation.rs @@ -129,6 +129,16 @@ fn insert_snippet(ctx: &egui::Context, id: egui::Id, text: &mut String, snippet: ctx.data_mut(|m| m.insert_temp(id.with("refocus"), true)); } +/// The line under the equation source for a parse error: where it is (the 1-based character), +/// then the message, both in the interface language. +fn parse_error_text(lang: crate::i18n::Language, position: Option, message: &str) -> String { + let message = lang.tr_error(message); + match position { + Some(p) => lang.tr_fill("Error at character {position}: {message}", &[("position", &p.to_string()), ("message", &message)]), + None => message, + } +} + /// The editor's body: quick-insert buttons, the LaTeX source with its error underlined, a live /// preview on a sheet-coloured card, and OK/Cancel. pub fn editor(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &mut bool, open: &mut bool) { @@ -164,10 +174,7 @@ pub fn editor(app: &mut SheetApp, ui: &mut egui::Ui, d: &mut Dialog, confirm: &m ui.add_space(4.0); match &pv.result { Err(e) if !text.trim().is_empty() => { - let msg = match e.char_pos(&text) { - Some(p) => format!("Error at character {p}: {}", e.message), - None => e.message.clone(), - }; + let msg = parse_error_text(app.ui.language, e.char_pos(&text), &e.message); ui.colored_label(t.danger, msg); } _ => { @@ -500,6 +507,18 @@ fn triangulate(pts: &[Pos2]) -> Vec<[usize; 3]> { mod tests { use super::*; + #[test] + fn parse_errors_follow_the_interface_language() { + use crate::i18n::Language; + assert_eq!(parse_error_text(Language::En, Some(3), "Missing }"), "Error at character 3: Missing }"); + assert_eq!(parse_error_text(Language::En, None, "Empty {group}"), "Empty {group}"); + let it = Language::It; + // The message is filled in once: its own `{message}` stays as it is. + let want = it.tr("Error at character {position}: {message}").replace("{position}", "3").replace("{message}", "Bad {message}"); + assert_eq!(parse_error_text(it, Some(3), "Bad {message}"), want); + assert!(!want.starts_with("Error at character")); + } + #[test] fn ear_clipping_covers_a_concave_polygon() { // An L shape: area 3 unit squares. diff --git a/crates/ui-egui/src/formula_bar.rs b/crates/ui-egui/src/formula_bar.rs index 091869ab8d..2877b3ce7b 100644 --- a/crates/ui-egui/src/formula_bar.rs +++ b/crates/ui-egui/src/formula_bar.rs @@ -256,7 +256,8 @@ fn active_input(app: &SheetApp) -> String { let Some(sh) = d.wb.active() else { return String::new() }; let a = sh.merge_at(d.selection.active).map(|m| m.start).unwrap_or(d.selection.active); if let Some(picture) = sh.cell_pictures.get(&a) { - return if picture.alt.is_empty() { "Picture in cell".into() } else { format!("Picture: {}", picture.alt) }; + let lang = app.ui.language; + return if picture.alt.is_empty() { lang.tr("Picture in cell").into() } else { lang.tr_fill("Picture: {alt}", &[("alt", &picture.alt)]) }; } // Python code is shown as it is: it isn't a formula to translate or a value to format. Like // a formula, it stays out of view in a Hidden cell on a protected sheet. @@ -913,6 +914,31 @@ mod spill_tests { SheetApp::new(s, Default::default()) } + #[test] + fn a_picture_in_a_cell_is_named_in_the_interface_language() { + use crate::i18n::Language; + use gridcraft_engine::core::CellRef; + use gridcraft_engine::model::CellPicture; + let mut app = app(); + let put = |app: &mut SheetApp, cell: &str, alt: &str| { + let at = CellRef::parse(cell).unwrap(); + let picture = std::sync::Arc::new(CellPicture { data: vec![], mime: "image/png".into(), alt: alt.into() }); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().wb).sheet_mut(0).unwrap().set_picture(at, picture); + }; + put(&mut app, "A1", ""); + put(&mut app, "A2", "Logo {alt}"); + select(&mut app, "A1"); + assert_eq!(active_input(&app), "Picture in cell"); + select(&mut app, "A2"); + assert_eq!(active_input(&app), "Picture: Logo {alt}"); + app.ui.language = Language::It; + select(&mut app, "A1"); + assert_eq!(active_input(&app), Language::It.tr("Picture in cell")); + assert_ne!(active_input(&app), "Picture in cell"); + select(&mut app, "A2"); + assert_eq!(active_input(&app), Language::It.tr("Picture: {alt}").replace("{alt}", "Logo {alt}")); + } + fn set(app: &mut SheetApp, cell: &str, input: &str) { app.run("cell.set", json!({"cell": cell, "input": input})).unwrap(); } diff --git a/crates/ui-egui/src/grid/interact.rs b/crates/ui-egui/src/grid/interact.rs index 2f6007c31c..967c51aba6 100644 --- a/crates/ui-egui/src/grid/interact.rs +++ b/crates/ui-egui/src/grid/interact.rs @@ -684,8 +684,7 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { } Drag::ResizeCol { col, start, orig } => { let w = (orig + (p.x - start) / geo.z).max(0.0); - app.toast = - Some((format!("Width: {:.2} ({} pixels)", gridcraft_engine::cmd::format::points_to_chars(w as f64), w.round()), crate::now_ms())); + app.toast = Some((column_width_tip(app.ui.language, w), crate::now_ms())); // Inside a selection of whole columns, every selected column takes the new width // (Ctrl-selected areas included); otherwise only the dragged one. let cols = if sel.ranges.iter().any(|r| r.is_full_cols() && col >= r.start.col && col <= r.end.col) { @@ -698,7 +697,7 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) { } Drag::ResizeRow { row, start, orig } => { let h = (orig + (p.y - start) / geo.z).max(0.0); - app.toast = Some((format!("Height: {:.2} ({} pixels)", h * 0.75, h.round()), crate::now_ms())); + app.toast = Some((row_height_tip(app.ui.language, h), crate::now_ms())); let rows = if sel.ranges.iter().any(|r| r.is_full_rows() && row >= r.start.row && row <= r.end.row) { sel.ranges .iter() @@ -956,6 +955,20 @@ fn scroll_by(app: &mut SheetApp, d: egui::Vec2) { } } +/// The tip while a column border is dragged to `width` pixels: the width in characters, then in +/// pixels (`Width: 8.43 (64 pixels)`). +pub(crate) fn column_width_tip(lang: crate::i18n::Language, width: f32) -> String { + let chars = format!("{:.2}", gridcraft_engine::cmd::format::points_to_chars(f64::from(width))); + lang.tr_fill("Width: {chars} ({pixels} pixels)", &[("chars", &chars), ("pixels", &width.round().to_string())]) +} + +/// The tip while a row border is dragged to `height` pixels: the height in points, then in pixels +/// (`Height: 15.00 (20 pixels)`). +pub(crate) fn row_height_tip(lang: crate::i18n::Language, height: f32) -> String { + let points = format!("{:.2}", height * 0.75); + lang.tr_fill("Height: {points} ({pixels} pixels)", &[("points", &points), ("pixels", &height.round().to_string())]) +} + fn fill_target(src: RangeRef, pc: CellRef) -> RangeRef { let below = pc.row as i64 - src.end.row as i64; let above = src.start.row as i64 - pc.row as i64; @@ -1165,6 +1178,17 @@ pub fn point_move(app: &mut SheetApp, ed: &mut EditState, dr: i64, dc: i64, exte mod tests { use super::*; + #[test] + fn resize_tips_follow_the_interface_language() { + use crate::i18n::Language; + assert_eq!(column_width_tip(Language::En, 64.0), "Width: 8.43 (64 pixels)"); + assert_eq!(row_height_tip(Language::En, 20.0), "Height: 15.00 (20 pixels)"); + let de = Language::De; + assert_eq!(column_width_tip(de, 64.0), de.tr("Width: {chars} ({pixels} pixels)").replace("{chars}", "8.43").replace("{pixels}", "64")); + assert_eq!(row_height_tip(de, 20.0), de.tr("Height: {points} ({pixels} pixels)").replace("{points}", "15.00").replace("{pixels}", "20")); + assert!(!column_width_tip(de, 64.0).starts_with("Width")); + } + #[test] fn the_pen_preview_is_the_ink_the_stroke_commits() { // #1786: the preview was always blue at 2 pt, whatever the pen. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 45c336f87b..8e2f5466d7 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -218,6 +218,11 @@ impl Language { translated.unwrap_or_else(|| text.rsplit_once('|').map_or(text, |(_, label)| label)) } + /// Translates `template`, then fills in its `{name}` placeholders (see [`fill`]). + pub fn tr_fill(self, template: &str, values: &[(&str, &str)]) -> String { + fill(self.tr(template), values) + } + pub(crate) fn tr_error(self, message: &str) -> String { let message = if message.starts_with("command `") { crate::clean_error(message) } else { message.to_owned() }; @@ -248,6 +253,30 @@ impl Language { } } +/// Fills in the `{name}` placeholders of a translated template in one pass, so a value that itself +/// holds `{…}` (a macro or sheet name) is shown as it is and never filled again. A placeholder +/// without a value stays as written. +pub fn fill(template: &str, values: &[(&str, &str)]) -> String { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some((before, after)) = rest.split_once('{') { + out.push_str(before); + let value = after.split_once('}').and_then(|(name, tail)| values.iter().find(|(key, _)| *key == name).map(|(_, value)| (*value, tail))); + match value { + Some((value, tail)) => { + out.push_str(value); + rest = tail; + } + None => { + out.push('{'); + rest = after; + } + } + } + out.push_str(rest); + out +} + /// English text and its translation, sorted by the English. type HelpTable = &'static [(&'static str, &'static str)]; @@ -389,6 +418,50 @@ mod tests { } } + #[test] + fn fill_puts_each_value_in_once() { + // A value holding a placeholder (a macro named `{steps}`) is shown as it is. + assert_eq!(fill("Ran macro “{name}” ({steps} steps)", &[("name", "{steps}"), ("steps", "3")]), "Ran macro “{steps}” (3 steps)"); + assert_eq!(fill("{a} and {b}, {a}", &[("a", "1")]), "1 and {b}, 1", "a placeholder without a value stays"); + assert_eq!(fill("{ unclosed", &[("unclosed", "x")]), "{ unclosed"); + assert_eq!(fill("50% {}", &[]), "50% {}"); + assert_eq!(Language::En.tr_fill("Sheets: {sheets}", &[("sheets", "Sheet1, Sheet2")]), "Sheets: Sheet1, Sheet2"); + } + + /// The templates the UI translates first and fills in after (status bar, toasts, dialog + /// notes and titles) keep their placeholders in every catalog, so no value goes missing. + #[test] + fn filled_in_templates_keep_their_placeholders() { + let placeholders = |s: &str| { + let mut names = s.split('{').skip(1).filter_map(|rest| rest.split_once('}').map(|(name, _)| name.to_string())).collect::>(); + names.sort(); + names + }; + for template in [ + "Circular References: {cell}", + "Goal Seeking found a solution: {value}", + "Width: {chars} ({pixels} pixels)", + "Height: {points} ({pixels} pixels)", + "Picture: {alt}", + "Sheets: {sheets}", + "Hidden: {sheets}", + "Format Control: {name}", + "Error at character {position}: {message}", + "Saved macro “{name}” ({steps} step)", + "Saved macro “{name}” ({steps} steps)", + "without {key}: another macro took it while recording", + "Macro “{name}” stopped: {message}", + "Ran macro “{name}” ({steps} step)", + "Ran macro “{name}” ({steps} steps)", + ] { + for language in Language::ALL { + let text = language.tr(template); + assert_eq!(placeholders(text), placeholders(template), "{}: {template:?} => {text:?}", language.code()); + assert!(!text.contains('\n'), "{}: {template:?} => {text:?}", language.code()); + } + } + } + #[test] fn translations_never_show_the_context_prefix() { // `tr` returns a found translation as it is, so a catalog that keeps `context|` in its diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 39e6337dde..0064af99f9 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -595,6 +595,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Zobrazit", "Collapse dialog" => "Sbalit dialogové okno", "Expand dialog" => "Rozbalit dialogové okno", + "Numerical Count" => "Počet čísel", + "Minimum" => "Minimum", + "Maximum" => "Maximum", + "Circular References: {cell}" => "Cyklické odkazy: {cell}", + "Width: {chars} ({pixels} pixels)" => "Šířka: {chars} (pixelů: {pixels})", + "Height: {points} ({pixels} pixels)" => "Výška: {points} (pixelů: {pixels})", + "Picture in cell" => "Obrázek v buňce", + "Picture: {alt}" => "Obrázek: {alt}", + "Format Control: {name}" => "Formát ovládacího prvku: {name}", + "Error at character {position}: {message}" => "Chyba na znaku {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ uloženo ({steps} krok)", + "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ uloženo (počet kroků: {steps})", + "without {key}: another macro took it while recording" => "bez {key}: během záznamu ji převzalo jiné makro", + "Recording stopped" => "Záznam zastaven", + "Macro “{name}” stopped: {message}" => "Makro „{name}“ se zastavilo: {message}", + "Ran macro “{name}” ({steps} step)" => "Makro „{name}“ spuštěno ({steps} krok)", + "Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ spuštěno (počet kroků: {steps})", + "Average" => "Průměr", + "Count" => "Počet", + "Sum" => "Součet", + "Goal Seeking found a solution: {value}" => "Hledání řešení našlo výsledek: {value}", + "Sheets: {sheets}" => "Listy: {sheets}", + "Hidden: {sheets}" => "Skryté: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index f136e483b6..816fb0e04d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -515,6 +515,31 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Anzeigen", "Collapse dialog" => "Dialogfeld reduzieren", "Expand dialog" => "Dialogfeld erweitern", + "Numerical Count" => "Numerische Zählung", + "Minimum" => "Minimum", + "Maximum" => "Maximum", + "Circular References: {cell}" => "Zirkelbezüge: {cell}", + "Width: {chars} ({pixels} pixels)" => "Breite: {chars} ({pixels} Pixel)", + "Height: {points} ({pixels} pixels)" => "Höhe: {points} ({pixels} Pixel)", + "Picture in cell" => "Bild in Zelle", + "Picture: {alt}" => "Bild: {alt}", + "Format Control: {name}" => "Steuerelement formatieren: {name}", + "Error at character {position}: {message}" => "Fehler bei Zeichen {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ gespeichert ({steps} Schritt)", + "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ gespeichert ({steps} Schritte)", + "without {key}: another macro took it while recording" => { + "ohne {key}: ein anderes Makro hat die Tastenkombination während der Aufzeichnung übernommen" + } + "Recording stopped" => "Aufzeichnung beendet", + "Macro “{name}” stopped: {message}" => "Makro „{name}“ angehalten: {message}", + "Ran macro “{name}” ({steps} step)" => "Makro „{name}“ ausgeführt ({steps} Schritt)", + "Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ ausgeführt ({steps} Schritte)", + "Average" => "Mittelwert", + "Count" => "Anzahl", + "Sum" => "Summe", + "Goal Seeking found a solution: {value}" => "Zielwertsuche hat eine Lösung gefunden: {value}", + "Sheets: {sheets}" => "Blätter: {sheets}", + "Hidden: {sheets}" => "Ausgeblendet: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index dc57982c7c..415aea0a80 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -1010,6 +1010,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Εμφάνιση", "Collapse dialog" => "Σύμπτυξη παραθύρου διαλόγου", "Expand dialog" => "Ανάπτυξη παραθύρου διαλόγου", + "Numerical Count" => "Αριθμητικό πλήθος", + "Minimum" => "Ελάχιστο", + "Maximum" => "Μέγιστο", + "Circular References: {cell}" => "Κυκλικές αναφορές: {cell}", + "Width: {chars} ({pixels} pixels)" => "Πλάτος: {chars} ({pixels} pixel)", + "Height: {points} ({pixels} pixels)" => "Ύψος: {points} ({pixels} pixel)", + "Picture in cell" => "Εικόνα σε κελί", + "Picture: {alt}" => "Εικόνα: {alt}", + "Format Control: {name}" => "Μορφοποίηση στοιχείου ελέγχου: {name}", + "Error at character {position}: {message}" => "Σφάλμα στον χαρακτήρα {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήμα)", + "Saved macro “{name}” ({steps} steps)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήματα)", + "without {key}: another macro took it while recording" => "χωρίς {key}: το πήρε άλλη μακροεντολή κατά την καταγραφή", + "Recording stopped" => "Η καταγραφή σταμάτησε", + "Macro “{name}” stopped: {message}" => "Η μακροεντολή «{name}» σταμάτησε: {message}", + "Ran macro “{name}” ({steps} step)" => "Η μακροεντολή «{name}» εκτελέστηκε ({steps} βήμα)", + "Ran macro “{name}” ({steps} steps)" => "Η μακροεντολή «{name}» εκτελέστηκε ({steps} βήματα)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 3c15a16b17..dd2a6a18d1 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -521,6 +521,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostrar", "Collapse dialog" => "Contraer diálogo", "Expand dialog" => "Expandir diálogo", + "Numerical Count" => "Recuento numérico", + "Minimum" => "Mínimo", + "Maximum" => "Máximo", + "Circular References: {cell}" => "Referencias circulares: {cell}", + "Width: {chars} ({pixels} pixels)" => "Ancho: {chars} ({pixels} píxeles)", + "Height: {points} ({pixels} pixels)" => "Alto: {points} ({pixels} píxeles)", + "Picture in cell" => "Imagen en celda", + "Picture: {alt}" => "Imagen: {alt}", + "Format Control: {name}" => "Formato de control: {name}", + "Error at character {position}: {message}" => "Error en el carácter {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Macro “{name}” guardada ({steps} paso)", + "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” guardada ({steps} pasos)", + "without {key}: another macro took it while recording" => "sin {key}: otra macro lo tomó durante la grabación", + "Recording stopped" => "Grabación detenida", + "Macro “{name}” stopped: {message}" => "La macro “{name}” se detuvo: {message}", + "Ran macro “{name}” ({steps} step)" => "Macro “{name}” ejecutada ({steps} paso)", + "Ran macro “{name}” ({steps} steps)" => "Macro “{name}” ejecutada ({steps} pasos)", + "Average" => "Promedio", + "Count" => "Recuento", + "Sum" => "Suma", + "Goal Seeking found a solution: {value}" => "Buscar objetivo encontró una solución: {value}", + "Sheets: {sheets}" => "Hojas: {sheets}", + "Hidden: {sheets}" => "Ocultas: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 3e95d4b726..7d881b4b4f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -481,6 +481,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Afficher", "Collapse dialog" => "Réduire la boîte de dialogue", "Expand dialog" => "Développer la boîte de dialogue", + "Numerical Count" => "Nombre de valeurs numériques", + "Minimum" => "Minimum", + "Maximum" => "Maximum", + "Circular References: {cell}" => "Références circulaires : {cell}", + "Width: {chars} ({pixels} pixels)" => "Largeur : {chars} ({pixels} pixels)", + "Height: {points} ({pixels} pixels)" => "Hauteur : {points} ({pixels} pixels)", + "Picture in cell" => "Image dans la cellule", + "Picture: {alt}" => "Image : {alt}", + "Format Control: {name}" => "Format de contrôle : {name}", + "Error at character {position}: {message}" => "Erreur au caractère {position} : {message}", + "Saved macro “{name}” ({steps} step)" => "Macro « {name} » enregistrée ({steps} étape)", + "Saved macro “{name}” ({steps} steps)" => "Macro « {name} » enregistrée ({steps} étapes)", + "without {key}: another macro took it while recording" => "sans {key} : une autre macro l’a pris pendant l’enregistrement", + "Recording stopped" => "Enregistrement arrêté", + "Macro “{name}” stopped: {message}" => "Macro « {name} » arrêtée : {message}", + "Ran macro “{name}” ({steps} step)" => "Macro « {name} » exécutée ({steps} étape)", + "Ran macro “{name}” ({steps} steps)" => "Macro « {name} » exécutée ({steps} étapes)", + "Average" => "Moyenne", + "Count" => "Nombre", + "Sum" => "Somme", + "Goal Seeking found a solution: {value}" => "Valeur cible a trouvé une solution : {value}", + "Sheets: {sheets}" => "Feuilles : {sheets}", + "Hidden: {sheets}" => "Masquées : {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3ad0ff3282..fd2ffb3a63 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1016,6 +1016,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostra", "Collapse dialog" => "Comprimi finestra di dialogo", "Expand dialog" => "Espandi finestra di dialogo", + "Numerical Count" => "Conteggio numeri", + "Minimum" => "Minimo", + "Maximum" => "Massimo", + "Circular References: {cell}" => "Riferimenti circolari: {cell}", + "Width: {chars} ({pixels} pixels)" => "Larghezza: {chars} ({pixels} pixel)", + "Height: {points} ({pixels} pixels)" => "Altezza: {points} ({pixels} pixel)", + "Picture in cell" => "Immagine nella cella", + "Picture: {alt}" => "Immagine: {alt}", + "Format Control: {name}" => "Formato controllo: {name}", + "Error at character {position}: {message}" => "Errore al carattere {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Macro “{name}” salvata ({steps} passaggio)", + "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salvata ({steps} passaggi)", + "without {key}: another macro took it while recording" => "senza {key}: un’altra macro l’ha preso durante la registrazione", + "Recording stopped" => "Registrazione interrotta", + "Macro “{name}” stopped: {message}" => "Macro “{name}” interrotta: {message}", + "Ran macro “{name}” ({steps} step)" => "Macro “{name}” eseguita ({steps} passaggio)", + "Ran macro “{name}” ({steps} steps)" => "Macro “{name}” eseguita ({steps} passaggi)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 19fc85f029..321dc62064 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1016,6 +1016,23 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Unprotect Sheet…", "シート保護の解除…"), ("Collapse dialog", "ダイアログを折りたたむ"), ("Expand dialog", "ダイアログを展開する"), + ("Numerical Count", "数値の個数"), + ("Minimum", "最小値"), + ("Maximum", "最大値"), + ("Circular References: {cell}", "循環参照: {cell}"), + ("Width: {chars} ({pixels} pixels)", "幅: {chars} ({pixels} ピクセル)"), + ("Height: {points} ({pixels} pixels)", "高さ: {points} ({pixels} ピクセル)"), + ("Picture in cell", "セル内の画像"), + ("Picture: {alt}", "画像: {alt}"), + ("Format Control: {name}", "コントロールの書式設定: {name}"), + ("Error at character {position}: {message}", "{position} 文字目でエラー: {message}"), + ("Saved macro “{name}” ({steps} step)", "マクロ「{name}」を保存しました ({steps} ステップ)"), + ("Saved macro “{name}” ({steps} steps)", "マクロ「{name}」を保存しました ({steps} ステップ)"), + ("without {key}: another macro took it while recording", "{key} なし: 記録中に別のマクロに割り当てられました"), + ("Recording stopped", "記録を終了しました"), + ("Macro “{name}” stopped: {message}", "マクロ「{name}」が停止しました: {message}"), + ("Ran macro “{name}” ({steps} step)", "マクロ「{name}」を実行しました ({steps} ステップ)"), + ("Ran macro “{name}” ({steps} steps)", "マクロ「{name}」を実行しました ({steps} ステップ)"), ]; /// Labels of the ribbon menus, pop-ups and palettes that the reference catalog does not cover (the diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8c28be26e1..299216a939 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -485,6 +485,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "표시", "Collapse dialog" => "대화 상자 축소", "Expand dialog" => "대화 상자 확장", + "Numerical Count" => "숫자 셀 수", + "Minimum" => "최소값", + "Maximum" => "최대값", + "Circular References: {cell}" => "순환 참조: {cell}", + "Width: {chars} ({pixels} pixels)" => "너비: {chars} ({pixels} 픽셀)", + "Height: {points} ({pixels} pixels)" => "높이: {points} ({pixels} 픽셀)", + "Picture in cell" => "셀 안의 그림", + "Picture: {alt}" => "그림: {alt}", + "Format Control: {name}" => "컨트롤 서식: {name}", + "Error at character {position}: {message}" => "{position}번째 문자에서 오류: {message}", + "Saved macro “{name}” ({steps} step)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)", + "Saved macro “{name}” ({steps} steps)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)", + "without {key}: another macro took it while recording" => "{key} 없음: 기록 중에 다른 매크로가 사용했습니다", + "Recording stopped" => "기록이 중지되었습니다", + "Macro “{name}” stopped: {message}" => "매크로 '{name}'이(가) 중지되었습니다: {message}", + "Ran macro “{name}” ({steps} step)" => "매크로 '{name}'을(를) 실행했습니다({steps}단계)", + "Ran macro “{name}” ({steps} steps)" => "매크로 '{name}'을(를) 실행했습니다({steps}단계)", + "Average" => "평균", + "Count" => "개수", + "Sum" => "합계", + "Goal Seeking found a solution: {value}" => "목표값 찾기에서 해를 찾았습니다: {value}", + "Sheets: {sheets}" => "시트: {sheets}", + "Hidden: {sheets}" => "숨김: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index b5cddb88d2..3786567c97 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -556,6 +556,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Weergeven", "Collapse dialog" => "Dialoogvenster samenvouwen", "Expand dialog" => "Dialoogvenster uitvouwen", + "Numerical Count" => "Numerieke telling", + "Minimum" => "Minimum", + "Maximum" => "Maximum", + "Circular References: {cell}" => "Kringverwijzingen: {cell}", + "Width: {chars} ({pixels} pixels)" => "Breedte: {chars} ({pixels} pixels)", + "Height: {points} ({pixels} pixels)" => "Hoogte: {points} ({pixels} pixels)", + "Picture in cell" => "Afbeelding in cel", + "Picture: {alt}" => "Afbeelding: {alt}", + "Format Control: {name}" => "Besturingselement opmaken: {name}", + "Error at character {position}: {message}" => "Fout bij teken {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Macro ‘{name}’ opgeslagen ({steps} stap)", + "Saved macro “{name}” ({steps} steps)" => "Macro ‘{name}’ opgeslagen ({steps} stappen)", + "without {key}: another macro took it while recording" => "zonder {key}: een andere macro heeft deze tijdens het opnemen overgenomen", + "Recording stopped" => "Opname gestopt", + "Macro “{name}” stopped: {message}" => "Macro ‘{name}’ gestopt: {message}", + "Ran macro “{name}” ({steps} step)" => "Macro ‘{name}’ uitgevoerd ({steps} stap)", + "Ran macro “{name}” ({steps} steps)" => "Macro ‘{name}’ uitgevoerd ({steps} stappen)", + "Average" => "Gemiddelde", + "Count" => "Aantal", + "Sum" => "Som", + "Goal Seeking found a solution: {value}" => "Doelzoeken heeft een oplossing gevonden: {value}", + "Sheets: {sheets}" => "Bladen: {sheets}", + "Hidden: {sheets}" => "Verborgen: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index f2bfd72c7f..dbd326f1ee 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1004,6 +1004,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Pokaż", "Collapse dialog" => "Zwiń okno dialogowe", "Expand dialog" => "Rozwiń okno dialogowe", + "Numerical Count" => "Liczba wartości liczbowych", + "Minimum" => "Minimum", + "Maximum" => "Maksimum", + "Circular References: {cell}" => "Odwołania cykliczne: {cell}", + "Width: {chars} ({pixels} pixels)" => "Szerokość: {chars} (pikseli: {pixels})", + "Height: {points} ({pixels} pixels)" => "Wysokość: {points} (pikseli: {pixels})", + "Picture in cell" => "Obraz w komórce", + "Picture: {alt}" => "Obraz: {alt}", + "Format Control: {name}" => "Formatuj formant: {name}", + "Error at character {position}: {message}" => "Błąd przy znaku {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Zapisano makro „{name}” ({steps} krok)", + "Saved macro “{name}” ({steps} steps)" => "Zapisano makro „{name}” (liczba kroków: {steps})", + "without {key}: another macro took it while recording" => "bez {key}: inne makro zajęło go podczas nagrywania", + "Recording stopped" => "Nagrywanie zatrzymane", + "Macro “{name}” stopped: {message}" => "Makro „{name}” zatrzymane: {message}", + "Ran macro “{name}” ({steps} step)" => "Uruchomiono makro „{name}” ({steps} krok)", + "Ran macro “{name}” ({steps} steps)" => "Uruchomiono makro „{name}” (liczba kroków: {steps})", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index d525f027e9..e2af5851ec 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -1022,6 +1022,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Mostrar", "Collapse dialog" => "Recolher caixa de diálogo", "Expand dialog" => "Expandir caixa de diálogo", + "Numerical Count" => "Contagem Numérica", + "Minimum" => "Mínimo", + "Maximum" => "Máximo", + "Circular References: {cell}" => "Referências Circulares: {cell}", + "Width: {chars} ({pixels} pixels)" => "Largura: {chars} ({pixels} pixels)", + "Height: {points} ({pixels} pixels)" => "Altura: {points} ({pixels} pixels)", + "Picture in cell" => "Imagem na célula", + "Picture: {alt}" => "Imagem: {alt}", + "Format Control: {name}" => "Formatar Controle: {name}", + "Error at character {position}: {message}" => "Erro no caractere {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Macro “{name}” salva ({steps} etapa)", + "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salva ({steps} etapas)", + "without {key}: another macro took it while recording" => "sem {key}: outra macro o usou durante a gravação", + "Recording stopped" => "Gravação interrompida", + "Macro “{name}” stopped: {message}" => "Macro “{name}” interrompida: {message}", + "Ran macro “{name}” ({steps} step)" => "Macro “{name}” executada ({steps} etapa)", + "Ran macro “{name}” ({steps} steps)" => "Macro “{name}” executada ({steps} etapas)", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index 66eb854b7f..e3ea8fb497 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -1066,6 +1066,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Afișare", "Collapse dialog" => "Restrângere casetă de dialog", "Expand dialog" => "Extindere casetă de dialog", + "Numerical Count" => "Numărare numerică", + "Minimum" => "Minim", + "Maximum" => "Maxim", + "Circular References: {cell}" => "Referințe circulare: {cell}", + "Width: {chars} ({pixels} pixels)" => "Lățime: {chars} ({pixels} pixeli)", + "Height: {points} ({pixels} pixels)" => "Înălțime: {points} ({pixels} pixeli)", + "Picture in cell" => "Imagine în celulă", + "Picture: {alt}" => "Imagine: {alt}", + "Format Control: {name}" => "Formatare control: {name}", + "Error at character {position}: {message}" => "Eroare la caracterul {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Macrocomanda „{name}” a fost salvată ({steps} pas)", + "Saved macro “{name}” ({steps} steps)" => "Macrocomanda „{name}” a fost salvată (pași: {steps})", + "without {key}: another macro took it while recording" => "fără {key}: altă macrocomandă l-a preluat în timpul înregistrării", + "Recording stopped" => "Înregistrare oprită", + "Macro “{name}” stopped: {message}" => "Macrocomanda „{name}” s-a oprit: {message}", + "Ran macro “{name}” ({steps} step)" => "Macrocomanda „{name}” a rulat ({steps} pas)", + "Ran macro “{name}” ({steps} steps)" => "Macrocomanda „{name}” a rulat (pași: {steps})", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 00a3062bd8..ad8cf07f8d 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -489,6 +489,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Показать", "Collapse dialog" => "Свернуть диалоговое окно", "Expand dialog" => "Развернуть диалоговое окно", + "Numerical Count" => "Количество чисел", + "Minimum" => "Минимум", + "Maximum" => "Максимум", + "Circular References: {cell}" => "Циклические ссылки: {cell}", + "Width: {chars} ({pixels} pixels)" => "Ширина: {chars} (пикселей: {pixels})", + "Height: {points} ({pixels} pixels)" => "Высота: {points} (пикселей: {pixels})", + "Picture in cell" => "Изображение в ячейке", + "Picture: {alt}" => "Изображение: {alt}", + "Format Control: {name}" => "Формат элемента управления: {name}", + "Error at character {position}: {message}" => "Ошибка в символе {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Макрос «{name}» сохранён ({steps} шаг)", + "Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» сохранён (шагов: {steps})", + "without {key}: another macro took it while recording" => "без {key}: во время записи его занял другой макрос", + "Recording stopped" => "Запись остановлена", + "Macro “{name}” stopped: {message}" => "Макрос «{name}» остановлен: {message}", + "Ran macro “{name}” ({steps} step)" => "Макрос «{name}» выполнен ({steps} шаг)", + "Ran macro “{name}” ({steps} steps)" => "Макрос «{name}» выполнен (шагов: {steps})", + "Average" => "Среднее", + "Count" => "Количество", + "Sum" => "Сумма", + "Goal Seeking found a solution: {value}" => "Подбор параметра нашёл решение: {value}", + "Sheets: {sheets}" => "Листы: {sheets}", + "Hidden: {sheets}" => "Скрытые: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 9254dc9389..152bed7227 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -476,6 +476,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Prikaži", "Collapse dialog" => "Skupi dijalog", "Expand dialog" => "Proširi dijalog", + "Numerical Count" => "Broj numeričkih vrednosti", + "Minimum" => "Minimum", + "Maximum" => "Maksimum", + "Circular References: {cell}" => "Kružne reference: {cell}", + "Width: {chars} ({pixels} pixels)" => "Širina: {chars} (piksela: {pixels})", + "Height: {points} ({pixels} pixels)" => "Visina: {points} (piksela: {pixels})", + "Picture in cell" => "Slika u ćeliji", + "Picture: {alt}" => "Slika: {alt}", + "Format Control: {name}" => "Oblikuj kontrolu: {name}", + "Error at character {position}: {message}" => "Greška kod znaka {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ je sačuvan ({steps} korak)", + "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ je sačuvan (broj koraka: {steps})", + "without {key}: another macro took it while recording" => "bez {key}: drugi makro ga je zauzeo tokom snimanja", + "Recording stopped" => "Snimanje je zaustavljeno", + "Macro “{name}” stopped: {message}" => "Makro „{name}“ je zaustavljen: {message}", + "Ran macro “{name}” ({steps} step)" => "Makro „{name}“ je pokrenut ({steps} korak)", + "Ran macro “{name}” ({steps} steps)" => "Makro „{name}“ je pokrenut (broj koraka: {steps})", + "Average" => "Prosek", + "Count" => "Broj", + "Sum" => "Zbir", + "Goal Seeking found a solution: {value}" => "Traženje cilja je pronašlo rešenje: {value}", + "Sheets: {sheets}" => "Listovi: {sheets}", + "Hidden: {sheets}" => "Skriveni: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index c8da06cb19..af2cdb0606 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -446,6 +446,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Göster", "Collapse dialog" => "İletişim kutusunu daralt", "Expand dialog" => "İletişim kutusunu genişlet", + "Numerical Count" => "Sayısal Sayım", + "Minimum" => "En Küçük", + "Maximum" => "En Büyük", + "Circular References: {cell}" => "Döngüsel Başvurular: {cell}", + "Width: {chars} ({pixels} pixels)" => "Genişlik: {chars} ({pixels} piksel)", + "Height: {points} ({pixels} pixels)" => "Yükseklik: {points} ({pixels} piksel)", + "Picture in cell" => "Hücredeki resim", + "Picture: {alt}" => "Resim: {alt}", + "Format Control: {name}" => "Denetimi Biçimlendir: {name}", + "Error at character {position}: {message}" => "{position}. karakterde hata: {message}", + "Saved macro “{name}” ({steps} step)" => "“{name}” makrosu kaydedildi ({steps} adım)", + "Saved macro “{name}” ({steps} steps)" => "“{name}” makrosu kaydedildi ({steps} adım)", + "without {key}: another macro took it while recording" => "{key} olmadan: kayıt sırasında başka bir makro aldı", + "Recording stopped" => "Kayıt durduruldu", + "Macro “{name}” stopped: {message}" => "“{name}” makrosu durdu: {message}", + "Ran macro “{name}” ({steps} step)" => "“{name}” makrosu çalıştırıldı ({steps} adım)", + "Ran macro “{name}” ({steps} steps)" => "“{name}” makrosu çalıştırıldı ({steps} adım)", + "Average" => "Ortalama", + "Count" => "Sayı", + "Sum" => "Toplam", + "Goal Seeking found a solution: {value}" => "Hedef Ara bir çözüm buldu: {value}", + "Sheets: {sheets}" => "Sayfalar: {sheets}", + "Hidden: {sheets}" => "Gizli: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 35fc9f0f77..1a70bd53c6 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -502,7 +502,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Name:" => "Name:", "Before sheet (position, 0 = first):" => "Before sheet (position, 0 = first):", "Create a copy" => "Create a copy", - "Sheets: {sheets}" => "Sheets: {sheets}", + "Sheets: {sheets}" => "Аркуші: {sheets}", "Password (optional):" => "Password (optional):", "Password:" => "Password:", "Allow all users of this sheet to:" => "Allow all users of this sheet to:", @@ -526,7 +526,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Remove the password (Modify)" => "Remove the password (Modify)", "'{file}' is protected." => "'{file}' is protected.", "Unhide sheet:" => "Unhide sheet:", - "Hidden: {sheets}" => "Hidden: {sheets}", + "Hidden: {sheets}" => "Приховані: {sheets}", "All" => "All", "Formulas (F)" => "Formulas (F)", "Values (V)" => "Values (V)", @@ -593,13 +593,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Interpolation" => "Interpolation", "Zeros" => "Zeros", "Aggregate duplicates using" => "Aggregate duplicates using", - "Average" => "Average", - "Count" => "Count", + "Average" => "Середнє", + "Count" => "Кількість", "CountA" => "CountA", "Max" => "Max", "Median" => "Median", "Min" => "Min", - "Sum" => "Sum", + "Sum" => "Сума", "Product" => "Product", "Include forecast statistics" => "Include forecast statistics", "Chart" => "Chart", @@ -803,7 +803,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Set cell:" => "Set cell:", "To value:" => "To value:", "By changing cell:" => "By changing cell:", - "Goal Seeking found a solution: {value}" => "Goal Seeking found a solution: {value}", + "Goal Seeking found a solution: {value}" => "Підбір параметра знайшов розв’язок: {value}", "Analysis Tools" => "Analysis Tools", "Anova: Single Factor" => "Anova: Single Factor", "Correlation" => "Correlation", @@ -1008,6 +1008,23 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Показати", "Collapse dialog" => "Згорнути діалогове вікно", "Expand dialog" => "Розгорнути діалогове вікно", + "Numerical Count" => "Кількість чисел", + "Minimum" => "Мінімум", + "Maximum" => "Максимум", + "Circular References: {cell}" => "Циклічні посилання: {cell}", + "Width: {chars} ({pixels} pixels)" => "Ширина: {chars} (пікселів: {pixels})", + "Height: {points} ({pixels} pixels)" => "Висота: {points} (пікселів: {pixels})", + "Picture in cell" => "Зображення в клітинці", + "Picture: {alt}" => "Зображення: {alt}", + "Format Control: {name}" => "Формат елемента керування: {name}", + "Error at character {position}: {message}" => "Помилка в символі {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Макрос «{name}» збережено ({steps} крок)", + "Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» збережено (кроків: {steps})", + "without {key}: another macro took it while recording" => "без {key}: під час запису його зайняв інший макрос", + "Recording stopped" => "Запис зупинено", + "Macro “{name}” stopped: {message}" => "Макрос «{name}» зупинено: {message}", + "Ran macro “{name}” ({steps} step)" => "Макрос «{name}» виконано ({steps} крок)", + "Ran macro “{name}” ({steps} steps)" => "Макрос «{name}» виконано (кроків: {steps})", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 8cb5a32ac6..f77b90860e 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -446,6 +446,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "Hiện", "Collapse dialog" => "Thu gọn hộp thoại", "Expand dialog" => "Mở rộng hộp thoại", + "Numerical Count" => "Số đếm số", + "Minimum" => "Tối thiểu", + "Maximum" => "Tối đa", + "Circular References: {cell}" => "Tham chiếu vòng: {cell}", + "Width: {chars} ({pixels} pixels)" => "Độ rộng: {chars} ({pixels} điểm ảnh)", + "Height: {points} ({pixels} pixels)" => "Chiều cao: {points} ({pixels} điểm ảnh)", + "Picture in cell" => "Ảnh trong ô", + "Picture: {alt}" => "Ảnh: {alt}", + "Format Control: {name}" => "Định dạng điều khiển: {name}", + "Error at character {position}: {message}" => "Lỗi tại ký tự {position}: {message}", + "Saved macro “{name}” ({steps} step)" => "Đã lưu macro “{name}” ({steps} bước)", + "Saved macro “{name}” ({steps} steps)" => "Đã lưu macro “{name}” ({steps} bước)", + "without {key}: another macro took it while recording" => "không có {key}: một macro khác đã dùng phím này khi đang ghi", + "Recording stopped" => "Đã dừng ghi", + "Macro “{name}” stopped: {message}" => "Macro “{name}” đã dừng: {message}", + "Ran macro “{name}” ({steps} step)" => "Đã chạy macro “{name}” ({steps} bước)", + "Ran macro “{name}” ({steps} steps)" => "Đã chạy macro “{name}” ({steps} bước)", + "Average" => "Trung bình", + "Count" => "Số đếm", + "Sum" => "Tổng", + "Goal Seeking found a solution: {value}" => "Tìm mục tiêu đã tìm thấy nghiệm: {value}", + "Sheets: {sheets}" => "Trang tính: {sheets}", + "Hidden: {sheets}" => "Đang ẩn: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index e71a0df3ff..8a8a010827 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -477,6 +477,29 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Show" => "显示", "Collapse dialog" => "折叠对话框", "Expand dialog" => "展开对话框", + "Numerical Count" => "数值计数", + "Minimum" => "最小值", + "Maximum" => "最大值", + "Circular References: {cell}" => "循环引用: {cell}", + "Width: {chars} ({pixels} pixels)" => "宽度: {chars} ({pixels} 像素)", + "Height: {points} ({pixels} pixels)" => "高度: {points} ({pixels} 像素)", + "Picture in cell" => "单元格中的图片", + "Picture: {alt}" => "图片: {alt}", + "Format Control: {name}" => "设置控件格式: {name}", + "Error at character {position}: {message}" => "第 {position} 个字符处出错: {message}", + "Saved macro “{name}” ({steps} step)" => "已保存宏“{name}”({steps} 步)", + "Saved macro “{name}” ({steps} steps)" => "已保存宏“{name}”({steps} 步)", + "without {key}: another macro took it while recording" => "未使用 {key}: 录制时已被另一个宏占用", + "Recording stopped" => "已停止录制", + "Macro “{name}” stopped: {message}" => "宏“{name}”已停止: {message}", + "Ran macro “{name}” ({steps} step)" => "已运行宏“{name}”({steps} 步)", + "Ran macro “{name}” ({steps} steps)" => "已运行宏“{name}”({steps} 步)", + "Average" => "平均值", + "Count" => "计数", + "Sum" => "求和", + "Goal Seeking found a solution: {value}" => "单变量求解找到一个解: {value}", + "Sheets: {sheets}" => "工作表: {sheets}", + "Hidden: {sheets}" => "隐藏: {sheets}", _ => return None, }) } diff --git a/crates/ui-egui/src/macro_ui.rs b/crates/ui-egui/src/macro_ui.rs index 9d1d74f33f..0332c32766 100644 --- a/crates/ui-egui/src/macro_ui.rs +++ b/crates/ui-egui/src/macro_ui.rs @@ -89,13 +89,16 @@ pub fn stop_recording(app: &mut SheetApp) { Some(name) => { let steps = v["steps"].as_u64().unwrap_or(0); app.macros.note_recent(name); - let mut text = format!("Saved macro “{name}” ({steps} step{})", if steps == 1 { "" } else { "s" }); + let lang = app.ui.language; + let saved = if steps == 1 { "Saved macro “{name}” ({steps} step)" } else { "Saved macro “{name}” ({steps} steps)" }; + let mut text = lang.tr_fill(saved, &[("name", name), ("steps", &steps.to_string())]); if let Some(k) = v["shortcutDropped"].as_str() { - text.push_str(&format!(" without {k}: another macro took it while recording")); + text.push(' '); + text.push_str(&lang.tr_fill("without {key}: another macro took it while recording", &[("key", k)])); } app.toast = Some((text, crate::now_ms())); } - None => app.toast = Some(("Recording stopped".into(), crate::now_ms())), + None => app.toast = Some((app.ui.language.tr("Recording stopped").into(), crate::now_ms())), }, Err(e) => app.message = Some(("Record Macro".into(), crate::clean_error(&e))), } @@ -174,9 +177,13 @@ pub fn note_result(app: &mut SheetApp, id: &str, params: &Json, v: &Json) { } app.macros.note_recent(&name); let ran = v["ran"].as_u64().unwrap_or(0); + let lang = app.ui.language; let text = match v["stopped"].as_str() { - Some(msg) => format!("Macro “{name}” stopped: {msg}"), - None => format!("Ran macro “{name}” ({ran} step{})", if ran == 1 { "" } else { "s" }), + Some(msg) => lang.tr_fill("Macro “{name}” stopped: {message}", &[("name", &name), ("message", msg)]), + None => { + let ran_text = if ran == 1 { "Ran macro “{name}” ({steps} step)" } else { "Ran macro “{name}” ({steps} steps)" }; + lang.tr_fill(ran_text, &[("name", &name), ("steps", &ran.to_string())]) + } }; app.toast = Some((text, crate::now_ms())); } @@ -673,6 +680,54 @@ pub fn record_dialog(app: &mut SheetApp, ui: &mut Ui, d: &mut Dialog, open: &mut mod tests { use super::*; + #[test] + fn macro_toasts_follow_the_interface_language() { + use crate::i18n::Language; + use gridcraft_engine::Session; + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + let ran = |app: &mut SheetApp, v: Json| { + note_result(app, "macro.run", &json!({}), &v); + app.toast.take().map(|t| t.0).unwrap_or_default() + }; + assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 1})), "Ran macro “M” (1 step)"); + assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 2})), "Ran macro “M” (2 steps)"); + assert_eq!(ran(&mut app, json!({"macro": "M", "stopped": "Oops"})), "Macro “M” stopped: Oops"); + let it = Language::It; + app.ui.language = it; + // A name holding a placeholder is shown as it is. + let want = it.tr("Ran macro “{name}” ({steps} steps)").replace("{steps}", "2").replace("{name}", "{steps}"); + assert_eq!(ran(&mut app, json!({"macro": "{steps}", "ran": 2})), want); + assert_ne!(want, "Ran macro “{steps}” (2 steps)"); + let want = it.tr("Ran macro “{name}” ({steps} step)").replace("{name}", "M").replace("{steps}", "1"); + assert_eq!(ran(&mut app, json!({"macro": "M", "ran": 1})), want); + let want = it.tr("Macro “{name}” stopped: {message}").replace("{name}", "M").replace("{message}", "Oops"); + assert_eq!(ran(&mut app, json!({"macro": "M", "stopped": "Oops"})), want); + } + + #[test] + fn recording_toasts_follow_the_interface_language() { + use crate::i18n::Language; + use gridcraft_engine::Session; + let mut session = Session::new(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + app.run("macro.record", json!({"name": "Two"})).unwrap(); + app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + app.run("cell.set", json!({"cell": "A2", "input": "2"})).unwrap(); + stop_recording(&mut app); + assert_eq!(app.toast.take().map(|t| t.0).as_deref(), Some("Saved macro “Two” (2 steps)")); + let it = Language::It; + app.ui.language = it; + app.run("macro.record", json!({"name": "Rec"})).unwrap(); + app.run("cell.set", json!({"cell": "A1", "input": "1"})).unwrap(); + stop_recording(&mut app); + let want = it.tr("Saved macro “{name}” ({steps} step)").replace("{name}", "Rec").replace("{steps}", "1"); + assert_eq!(app.toast.take().map(|t| t.0).as_deref(), Some(want.as_str())); + assert!(!want.starts_with("Saved macro")); + } + #[test] fn questions_are_read_from_the_error() { let e = "approve: Run macro 'M'? It came with a workbook you opened. (run again with `approve: true`)"; diff --git a/crates/ui-egui/src/tabs.rs b/crates/ui-egui/src/tabs.rs index 462dc2e4c1..7cd939e645 100644 --- a/crates/ui-egui/src/tabs.rs +++ b/crates/ui-egui/src/tabs.rs @@ -417,8 +417,8 @@ pub fn status_bar(app: &mut SheetApp, ui: &mut Ui) { ui.add_space(12.0); // Only a loop on the active sheet is named, so the address needs no sheet. let label = match d.calc.circular.iter().find(|(si, _)| *si == d.wb.active_sheet()) { - Some((_, c)) => format!("Circular References: {}", c.a1()), - None => "Circular References".to_owned(), + Some((_, c)) => app.ui.language.tr_fill("Circular References: {cell}", &[("cell", &c.a1())]), + None => app.ui.language.tr("Circular References").to_owned(), }; text(ui, egui::RichText::new(label).font(theme::ui_font(12.5)).color(t.danger)); } @@ -516,26 +516,30 @@ pub(crate) fn selection_statistics(app: &SheetApp) -> Vec { let code = if code == "General" { "#,##0.##########".to_string() } else { code }; gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(v), &code, &d.wb).text.trim_end_matches('.').to_string() }; + // The label the right-click menu shows, then the value: clicking a statistic copies the part + // after `": "`. + let lang = app.ui.language; + let part = |label: &str, value: String| format!("{}: {value}", lang.tr(label)); let mut parts = Vec::new(); if on.average && let Some(a) = st.average { - parts.push(format!("Average: {}", fmt(a))); + parts.push(part("Average", fmt(a))); } if on.count && st.count > 0 { - parts.push(format!("Count: {}", st.count)); + parts.push(part("Count", st.count.to_string())); } if on.numerical_count && st.count > 0 { - parts.push(format!("Numerical Count: {}", st.numeric)); + parts.push(part("Numerical Count", st.numeric.to_string())); } if on.minimum && st.numeric > 0 { - parts.push(format!("Minimum: {}", fmt(st.min))); + parts.push(part("Minimum", fmt(st.min))); } if on.maximum && st.numeric > 0 { - parts.push(format!("Maximum: {}", fmt(st.max))); + parts.push(part("Maximum", fmt(st.max))); } if on.sum && st.numeric > 0 { - parts.push(format!("Sum: {}", fmt(st.sum))); + parts.push(part("Sum", fmt(st.sum))); } parts } @@ -586,6 +590,26 @@ mod tests { app.session.active().unwrap().wb.sheets.iter().map(|s| s.name.clone()).collect() } + #[test] + fn status_bar_statistics_follow_the_interface_language() { + use crate::i18n::Language; + let mut session = gridcraft_engine::Session::default(); + session.new_workbook(); + let mut app = SheetApp::new(session, Default::default()); + for (cell, input) in [("A1", "1"), ("A2", "2"), ("A3", "3")] { + app.run("cell.set", json!({"cell": cell, "input": input})).unwrap(); + } + app.run("selection.set", json!({"range": "A1:A3"})).unwrap(); + app.run("view.statusBar", json!({"numericalCount": true, "minimum": true, "maximum": true})).unwrap(); + let parts = [("Average", "2"), ("Count", "3"), ("Numerical Count", "3"), ("Minimum", "1"), ("Maximum", "3"), ("Sum", "6")]; + let english: Vec = parts.iter().map(|(label, value)| format!("{label}: {value}")).collect(); + assert_eq!(super::selection_statistics(&app), english); + app.ui.language = Language::It; + let italian: Vec = parts.iter().map(|(label, value)| format!("{}: {value}", Language::It.tr(label))).collect(); + assert_eq!(super::selection_statistics(&app), italian, "each label as the right-click menu shows it"); + assert!(italian.iter().zip(&english).all(|(it, en)| it != en), "the Italian catalog translates every label: {italian:?}"); + } + #[test] fn status_bar_shows_the_statistics_that_are_turned_on_in_order() { let mut session = gridcraft_engine::Session::default(); diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 39a9b3f91e..ac4fd75b64 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (status bar statistics, resize tips, picture-in-cell text, sheet notes, Format Control title, equation errors, Goal Seek and macro toasts follow the interface language) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Per-language status against Excel, which ships its UI in dozens of languages (Windows language packs cover 100+), with localized function names, argument separators, number and date formats, @@ -110,6 +110,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | Strings built with `format!` in English now translate their template first and fill it in once (`Language::tr_fill`): status bar statistics and the circular-reference note, the column width / row height drag tip, the formula bar text for a picture in a cell, the Move or Copy and Unhide notes, the Format Control title, the equation editor's error prefix, and the Goal Seek and macro recorder/runner toasts (#3600, #3602, #3603, #3605, #3607–#3611). 17 new keys in every catalog; Average, Count, Sum and the three existing templates added to the 11 catalogs that lacked them, and Ukrainian's English placeholders for those six replaced. Numbers in these strings keep the `.` decimal point | | 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay | | 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review | | 2026-10-20 | minor | Japanese: furigana (`rPh` phonetic runs and `` in `xl/sharedStrings.xml`) is no longer deleted by an open + save; it is kept on the workbook and written back (a `` without runs is kept too, while duplicate texts with different readings keep only the first, reported on open). Display of the readings is still missing (`crates/xlsx/src/tests/phonetic_tests.rs`) | From a0dc48547b9a86f6bfe9496db197ff9836551eb7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 23:32:17 +0100 Subject: [PATCH 064/201] fix(i18n): translate the equation checks' own error messages The equation editor translated only its "Error at character" prefix; the checks in crates/math (macro definitions, % with a link, nesting, length, matrix-cell and size limits, layout failure) stayed English. Add the seven messages to all 18 catalogs and test them from the real checks, with the expected English built from the limits. RaTeX parser errors are open-ended text from the external crate and stay English. The localization doc now marks its counts as a snapshot and states the current status. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/equation.rs | 41 ++++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 9 ++++++++ crates/ui-egui/src/i18n/de.rs | 9 ++++++++ crates/ui-egui/src/i18n/el.rs | 9 ++++++++ crates/ui-egui/src/i18n/es.rs | 9 ++++++++ crates/ui-egui/src/i18n/fr.rs | 9 ++++++++ crates/ui-egui/src/i18n/it.rs | 9 ++++++++ crates/ui-egui/src/i18n/ja.rs | 7 ++++++ crates/ui-egui/src/i18n/ko.rs | 9 ++++++++ crates/ui-egui/src/i18n/nl.rs | 9 ++++++++ crates/ui-egui/src/i18n/pl.rs | 9 ++++++++ crates/ui-egui/src/i18n/pt.rs | 9 ++++++++ crates/ui-egui/src/i18n/ro.rs | 9 ++++++++ crates/ui-egui/src/i18n/ru.rs | 9 ++++++++ crates/ui-egui/src/i18n/sr.rs | 9 ++++++++ crates/ui-egui/src/i18n/tr.rs | 9 ++++++++ crates/ui-egui/src/i18n/uk.rs | 9 ++++++++ crates/ui-egui/src/i18n/vi.rs | 9 ++++++++ crates/ui-egui/src/i18n/zh.rs | 7 ++++++ docs/localization-parity.md | 13 +++++++++-- 20 files changed, 210 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/equation.rs b/crates/ui-egui/src/equation.rs index e412be107c..087554d1c3 100644 --- a/crates/ui-egui/src/equation.rs +++ b/crates/ui-egui/src/equation.rs @@ -519,6 +519,47 @@ mod tests { assert!(!want.starts_with("Error at character")); } + /// The equation checks' own messages (not RaTeX's syntax errors, which stay English) are + /// translated in every catalog. Each comes from the real check, and the expected English is + /// built from the limits, so a changed limit fails here instead of silently falling back to + /// English (the catalogs key the message with the number in it). + #[test] + fn equation_check_messages_are_translated_in_every_catalog() { + use crate::i18n::Language; + use gridcraft_engine::math::{MAX_CELLS, MAX_DEPTH, MAX_SOURCE_BYTES, layout}; + let cases = [ + ("\\def\\x{1} x".to_string(), "Macro definitions are not supported in equations.".to_string()), + ("50% \\href{https://example.com}{x}".to_string(), "A % can't be combined with a link in an equation.".to_string()), + (format!("{}x{}", "{".repeat(MAX_DEPTH + 1), "}".repeat(MAX_DEPTH + 1)), format!("Equations can nest at most {MAX_DEPTH} levels deep.")), + ("x".repeat(MAX_SOURCE_BYTES + 1), format!("An equation can be at most {MAX_SOURCE_BYTES} bytes long.")), + ( + "\\begin{alignedat}{99999999}a\\end{alignedat}".to_string(), + format!("An equation can have at most {MAX_CELLS} matrix cells (rows times the widest row)."), + ), + ("\\rule{99999999em}{1em}".to_string(), "This equation is too large to draw.".to_string()), + ]; + let mut messages = Vec::new(); + for (src, want) in cases { + let got = layout(&src).err().unwrap_or_else(|| panic!("{src:?} lays out")).message; + assert_eq!(got, want, "{src:?} hits another check"); + messages.push(got); + } + // Only a panic inside the layout reaches this one. + messages.push("This equation could not be laid out.".to_string()); + for message in &messages { + for language in Language::ALL { + let shown = parse_error_text(language, None, message); + assert!(!shown.contains('\n'), "{}: {message:?} => {shown:?}", language.code()); + if language != Language::En { + assert_ne!(&shown, message, "{} leaves {message:?} in English", language.code()); + } + } + } + let it = Language::It; + let want = it.tr("Error at character {position}: {message}").replace("{position}", "1").replace("{message}", it.tr(&messages[0])); + assert_eq!(parse_error_text(it, Some(1), &messages[0]), want); + } + #[test] fn ear_clipping_covers_a_concave_polygon() { // An L shape: area 3 unit squares. diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 0064af99f9..bd23a55661 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -605,6 +605,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Obrázek: {alt}", "Format Control: {name}" => "Formát ovládacího prvku: {name}", "Error at character {position}: {message}" => "Chyba na znaku {position}: {message}", + "Macro definitions are not supported in equations." => "Definice maker nejsou v rovnicích podporovány.", + "A % can't be combined with a link in an equation." => "Znak % nelze v rovnici kombinovat s odkazem.", + "Equations can nest at most 32 levels deep." => "Rovnice lze vnořit nejvýše do 32 úrovní.", + "An equation can be at most 4096 bytes long." => "Rovnice může mít nejvýše 4096 bajtů.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Rovnice může mít nejvýše 2500 buněk matice (řádky krát nejširší řádek)." + } + "This equation is too large to draw." => "Tato rovnice je příliš velká na vykreslení.", + "This equation could not be laid out." => "Tuto rovnici nelze vysázet.", "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ uloženo ({steps} krok)", "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ uloženo (počet kroků: {steps})", "without {key}: another macro took it while recording" => "bez {key}: během záznamu ji převzalo jiné makro", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 816fb0e04d..7a1602a0cc 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -525,6 +525,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Bild: {alt}", "Format Control: {name}" => "Steuerelement formatieren: {name}", "Error at character {position}: {message}" => "Fehler bei Zeichen {position}: {message}", + "Macro definitions are not supported in equations." => "Makrodefinitionen werden in Formeln nicht unterstützt.", + "A % can't be combined with a link in an equation." => "Ein % kann in einer Formel nicht mit einem Link kombiniert werden.", + "Equations can nest at most 32 levels deep." => "Formeln können höchstens 32 Ebenen tief verschachtelt werden.", + "An equation can be at most 4096 bytes long." => "Eine Formel darf höchstens 4096 Byte lang sein.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Eine Formel darf höchstens 2500 Matrixzellen haben (Zeilen mal breiteste Zeile)." + } + "This equation is too large to draw." => "Diese Formel ist zu groß zum Zeichnen.", + "This equation could not be laid out." => "Diese Formel konnte nicht gesetzt werden.", "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ gespeichert ({steps} Schritt)", "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ gespeichert ({steps} Schritte)", "without {key}: another macro took it while recording" => { diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 415aea0a80..e10889eb0b 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -1020,6 +1020,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Εικόνα: {alt}", "Format Control: {name}" => "Μορφοποίηση στοιχείου ελέγχου: {name}", "Error at character {position}: {message}" => "Σφάλμα στον χαρακτήρα {position}: {message}", + "Macro definitions are not supported in equations." => "Οι ορισμοί μακροεντολών δεν υποστηρίζονται στις εξισώσεις.", + "A % can't be combined with a link in an equation." => "Ένα % δεν μπορεί να συνδυαστεί με σύνδεσμο σε μια εξίσωση.", + "Equations can nest at most 32 levels deep." => "Οι εξισώσεις μπορούν να έχουν έως 32 επίπεδα ένθεσης.", + "An equation can be at most 4096 bytes long." => "Μια εξίσωση μπορεί να έχει έως 4096 byte.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Μια εξίσωση μπορεί να έχει έως 2500 κελιά πίνακα (γραμμές επί τη φαρδύτερη γραμμή)." + } + "This equation is too large to draw." => "Αυτή η εξίσωση είναι πολύ μεγάλη για να σχεδιαστεί.", + "This equation could not be laid out." => "Δεν ήταν δυνατή η στοιχειοθέτηση αυτής της εξίσωσης.", "Saved macro “{name}” ({steps} step)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήμα)", "Saved macro “{name}” ({steps} steps)" => "Η μακροεντολή «{name}» αποθηκεύτηκε ({steps} βήματα)", "without {key}: another macro took it while recording" => "χωρίς {key}: το πήρε άλλη μακροεντολή κατά την καταγραφή", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index dd2a6a18d1..5cb65aa12a 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -531,6 +531,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Imagen: {alt}", "Format Control: {name}" => "Formato de control: {name}", "Error at character {position}: {message}" => "Error en el carácter {position}: {message}", + "Macro definitions are not supported in equations." => "Las definiciones de macros no se admiten en las ecuaciones.", + "A % can't be combined with a link in an equation." => "Un % no se puede combinar con un vínculo en una ecuación.", + "Equations can nest at most 32 levels deep." => "Las ecuaciones pueden anidarse como máximo 32 niveles.", + "An equation can be at most 4096 bytes long." => "Una ecuación puede tener como máximo 4096 bytes.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Una ecuación puede tener como máximo 2500 celdas de matriz (filas por la fila más ancha)." + } + "This equation is too large to draw." => "Esta ecuación es demasiado grande para dibujarla.", + "This equation could not be laid out." => "No se pudo componer esta ecuación.", "Saved macro “{name}” ({steps} step)" => "Macro “{name}” guardada ({steps} paso)", "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” guardada ({steps} pasos)", "without {key}: another macro took it while recording" => "sin {key}: otra macro lo tomó durante la grabación", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 7d881b4b4f..ed84c69614 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -491,6 +491,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Image : {alt}", "Format Control: {name}" => "Format de contrôle : {name}", "Error at character {position}: {message}" => "Erreur au caractère {position} : {message}", + "Macro definitions are not supported in equations." => "Les définitions de macros ne sont pas prises en charge dans les équations.", + "A % can't be combined with a link in an equation." => "Un % ne peut pas être combiné avec un lien dans une équation.", + "Equations can nest at most 32 levels deep." => "Les équations peuvent comporter au plus 32 niveaux d’imbrication.", + "An equation can be at most 4096 bytes long." => "Une équation peut contenir au plus 4096 octets.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Une équation peut contenir au plus 2500 cellules de matrice (lignes multipliées par la ligne la plus large)." + } + "This equation is too large to draw." => "Cette équation est trop grande pour être dessinée.", + "This equation could not be laid out." => "Impossible de mettre en page cette équation.", "Saved macro “{name}” ({steps} step)" => "Macro « {name} » enregistrée ({steps} étape)", "Saved macro “{name}” ({steps} steps)" => "Macro « {name} » enregistrée ({steps} étapes)", "without {key}: another macro took it while recording" => "sans {key} : une autre macro l’a pris pendant l’enregistrement", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index fd2ffb3a63..74a9cb1549 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1026,6 +1026,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Immagine: {alt}", "Format Control: {name}" => "Formato controllo: {name}", "Error at character {position}: {message}" => "Errore al carattere {position}: {message}", + "Macro definitions are not supported in equations." => "Le definizioni di macro non sono supportate nelle equazioni.", + "A % can't be combined with a link in an equation." => "Un % non può essere combinato con un collegamento in un'equazione.", + "Equations can nest at most 32 levels deep." => "Le equazioni possono essere annidate al massimo su 32 livelli.", + "An equation can be at most 4096 bytes long." => "Un'equazione può essere lunga al massimo 4096 byte.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Un'equazione può avere al massimo 2500 celle di matrice (righe per la riga più larga)." + } + "This equation is too large to draw." => "Questa equazione è troppo grande per essere disegnata.", + "This equation could not be laid out." => "Impossibile impaginare questa equazione.", "Saved macro “{name}” ({steps} step)" => "Macro “{name}” salvata ({steps} passaggio)", "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salvata ({steps} passaggi)", "without {key}: another macro took it while recording" => "senza {key}: un’altra macro l’ha preso durante la registrazione", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 321dc62064..39309d0c30 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1026,6 +1026,13 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Picture: {alt}", "画像: {alt}"), ("Format Control: {name}", "コントロールの書式設定: {name}"), ("Error at character {position}: {message}", "{position} 文字目でエラー: {message}"), + ("Macro definitions are not supported in equations.", "数式ではマクロ定義はサポートされていません。"), + ("A % can't be combined with a link in an equation.", "数式では % とリンクを組み合わせることはできません。"), + ("Equations can nest at most 32 levels deep.", "数式の入れ子は 32 レベルまでです。"), + ("An equation can be at most 4096 bytes long.", "数式の長さは 4096 バイトまでです。"), + ("An equation can have at most 2500 matrix cells (rows times the widest row).", "数式の行列セルは 2500 個まで (行数 × 最も長い行) です。"), + ("This equation is too large to draw.", "この数式は大きすぎて描画できません。"), + ("This equation could not be laid out.", "この数式をレイアウトできませんでした。"), ("Saved macro “{name}” ({steps} step)", "マクロ「{name}」を保存しました ({steps} ステップ)"), ("Saved macro “{name}” ({steps} steps)", "マクロ「{name}」を保存しました ({steps} ステップ)"), ("without {key}: another macro took it while recording", "{key} なし: 記録中に別のマクロに割り当てられました"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 299216a939..a0a6d37892 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -495,6 +495,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "그림: {alt}", "Format Control: {name}" => "컨트롤 서식: {name}", "Error at character {position}: {message}" => "{position}번째 문자에서 오류: {message}", + "Macro definitions are not supported in equations." => "수식에서는 매크로 정의가 지원되지 않습니다.", + "A % can't be combined with a link in an equation." => "수식에서 %를 링크와 함께 사용할 수 없습니다.", + "Equations can nest at most 32 levels deep." => "수식은 최대 32단계까지 중첩할 수 있습니다.", + "An equation can be at most 4096 bytes long." => "수식은 최대 4096바이트까지 입력할 수 있습니다.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "수식에는 최대 2500개의 행렬 셀(행 수 × 가장 넓은 행)을 넣을 수 있습니다." + } + "This equation is too large to draw." => "이 수식은 너무 커서 그릴 수 없습니다.", + "This equation could not be laid out." => "이 수식을 배치할 수 없습니다.", "Saved macro “{name}” ({steps} step)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)", "Saved macro “{name}” ({steps} steps)" => "매크로 '{name}'을(를) 저장했습니다({steps}단계)", "without {key}: another macro took it while recording" => "{key} 없음: 기록 중에 다른 매크로가 사용했습니다", diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index 3786567c97..5fd1647af3 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -566,6 +566,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Afbeelding: {alt}", "Format Control: {name}" => "Besturingselement opmaken: {name}", "Error at character {position}: {message}" => "Fout bij teken {position}: {message}", + "Macro definitions are not supported in equations." => "Macrodefinities worden niet ondersteund in vergelijkingen.", + "A % can't be combined with a link in an equation." => "Een % kan niet worden gecombineerd met een koppeling in een vergelijking.", + "Equations can nest at most 32 levels deep." => "Vergelijkingen kunnen maximaal 32 niveaus diep worden genest.", + "An equation can be at most 4096 bytes long." => "Een vergelijking kan maximaal 4096 bytes lang zijn.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Een vergelijking kan maximaal 2500 matrixcellen hebben (rijen maal de breedste rij)." + } + "This equation is too large to draw." => "Deze vergelijking is te groot om te tekenen.", + "This equation could not be laid out." => "Deze vergelijking kan niet worden opgemaakt.", "Saved macro “{name}” ({steps} step)" => "Macro ‘{name}’ opgeslagen ({steps} stap)", "Saved macro “{name}” ({steps} steps)" => "Macro ‘{name}’ opgeslagen ({steps} stappen)", "without {key}: another macro took it while recording" => "zonder {key}: een andere macro heeft deze tijdens het opnemen overgenomen", diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index dbd326f1ee..56e2513a20 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1014,6 +1014,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Obraz: {alt}", "Format Control: {name}" => "Formatuj formant: {name}", "Error at character {position}: {message}" => "Błąd przy znaku {position}: {message}", + "Macro definitions are not supported in equations." => "Definicje makr nie są obsługiwane w równaniach.", + "A % can't be combined with a link in an equation." => "Znaku % nie można łączyć z linkiem w równaniu.", + "Equations can nest at most 32 levels deep." => "Równania mogą być zagnieżdżone na co najwyżej 32 poziomach.", + "An equation can be at most 4096 bytes long." => "Równanie może mieć co najwyżej 4096 bajtów.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Równanie może mieć co najwyżej 2500 komórek macierzy (wiersze razy najszerszy wiersz)." + } + "This equation is too large to draw." => "To równanie jest za duże, aby je narysować.", + "This equation could not be laid out." => "Nie można złożyć tego równania.", "Saved macro “{name}” ({steps} step)" => "Zapisano makro „{name}” ({steps} krok)", "Saved macro “{name}” ({steps} steps)" => "Zapisano makro „{name}” (liczba kroków: {steps})", "without {key}: another macro took it while recording" => "bez {key}: inne makro zajęło go podczas nagrywania", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index e2af5851ec..d1bf9c355e 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -1032,6 +1032,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Imagem: {alt}", "Format Control: {name}" => "Formatar Controle: {name}", "Error at character {position}: {message}" => "Erro no caractere {position}: {message}", + "Macro definitions are not supported in equations." => "Definições de macro não são compatíveis com equações.", + "A % can't be combined with a link in an equation." => "Um % não pode ser combinado com um link em uma equação.", + "Equations can nest at most 32 levels deep." => "As equações podem ter no máximo 32 níveis de aninhamento.", + "An equation can be at most 4096 bytes long." => "Uma equação pode ter no máximo 4096 bytes.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Uma equação pode ter no máximo 2500 células de matriz (linhas vezes a linha mais larga)." + } + "This equation is too large to draw." => "Esta equação é grande demais para ser desenhada.", + "This equation could not be laid out." => "Não foi possível diagramar esta equação.", "Saved macro “{name}” ({steps} step)" => "Macro “{name}” salva ({steps} etapa)", "Saved macro “{name}” ({steps} steps)" => "Macro “{name}” salva ({steps} etapas)", "without {key}: another macro took it while recording" => "sem {key}: outra macro o usou durante a gravação", diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index e3ea8fb497..4aea17112d 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -1076,6 +1076,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Imagine: {alt}", "Format Control: {name}" => "Formatare control: {name}", "Error at character {position}: {message}" => "Eroare la caracterul {position}: {message}", + "Macro definitions are not supported in equations." => "Definițiile de macrocomenzi nu sunt acceptate în ecuații.", + "A % can't be combined with a link in an equation." => "Un % nu poate fi combinat cu un link într-o ecuație.", + "Equations can nest at most 32 levels deep." => "Ecuațiile pot fi imbricate pe cel mult 32 de niveluri.", + "An equation can be at most 4096 bytes long." => "O ecuație poate avea cel mult 4096 de octeți.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "O ecuație poate avea cel mult 2500 de celule de matrice (rânduri înmulțite cu cel mai lat rând)." + } + "This equation is too large to draw." => "Această ecuație este prea mare pentru a fi desenată.", + "This equation could not be laid out." => "Această ecuație nu a putut fi așezată în pagină.", "Saved macro “{name}” ({steps} step)" => "Macrocomanda „{name}” a fost salvată ({steps} pas)", "Saved macro “{name}” ({steps} steps)" => "Macrocomanda „{name}” a fost salvată (pași: {steps})", "without {key}: another macro took it while recording" => "fără {key}: altă macrocomandă l-a preluat în timpul înregistrării", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index ad8cf07f8d..30754503c5 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -499,6 +499,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Изображение: {alt}", "Format Control: {name}" => "Формат элемента управления: {name}", "Error at character {position}: {message}" => "Ошибка в символе {position}: {message}", + "Macro definitions are not supported in equations." => "Определения макросов в формулах не поддерживаются.", + "A % can't be combined with a link in an equation." => "Знак % нельзя сочетать со ссылкой в формуле.", + "Equations can nest at most 32 levels deep." => "Формулы могут иметь не более 32 уровней вложенности.", + "An equation can be at most 4096 bytes long." => "Длина формулы не может превышать 4096 байт.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Формула может содержать не более 2500 ячеек матрицы (строки, умноженные на самую широкую строку)." + } + "This equation is too large to draw." => "Эта формула слишком велика для отрисовки.", + "This equation could not be laid out." => "Не удалось построить эту формулу.", "Saved macro “{name}” ({steps} step)" => "Макрос «{name}» сохранён ({steps} шаг)", "Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» сохранён (шагов: {steps})", "without {key}: another macro took it while recording" => "без {key}: во время записи его занял другой макрос", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 152bed7227..f247c4697c 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -486,6 +486,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Slika: {alt}", "Format Control: {name}" => "Oblikuj kontrolu: {name}", "Error at character {position}: {message}" => "Greška kod znaka {position}: {message}", + "Macro definitions are not supported in equations." => "Definicije makroa nisu podržane u jednačinama.", + "A % can't be combined with a link in an equation." => "Znak % ne može da se kombinuje sa vezom u jednačini.", + "Equations can nest at most 32 levels deep." => "Jednačine mogu da budu ugnežđene najviše 32 nivoa.", + "An equation can be at most 4096 bytes long." => "Jednačina može da ima najviše 4096 bajtova.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Jednačina može da ima najviše 2500 ćelija matrice (redovi puta najširi red)." + } + "This equation is too large to draw." => "Ova jednačina je prevelika za crtanje.", + "This equation could not be laid out." => "Ova jednačina nije mogla da se složi.", "Saved macro “{name}” ({steps} step)" => "Makro „{name}“ je sačuvan ({steps} korak)", "Saved macro “{name}” ({steps} steps)" => "Makro „{name}“ je sačuvan (broj koraka: {steps})", "without {key}: another macro took it while recording" => "bez {key}: drugi makro ga je zauzeo tokom snimanja", diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index af2cdb0606..2f0374e420 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -456,6 +456,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Resim: {alt}", "Format Control: {name}" => "Denetimi Biçimlendir: {name}", "Error at character {position}: {message}" => "{position}. karakterde hata: {message}", + "Macro definitions are not supported in equations." => "Denklemlerde makro tanımları desteklenmez.", + "A % can't be combined with a link in an equation." => "Bir denklemde % bir bağlantıyla birlikte kullanılamaz.", + "Equations can nest at most 32 levels deep." => "Denklemler en fazla 32 düzey iç içe olabilir.", + "An equation can be at most 4096 bytes long." => "Bir denklem en fazla 4096 bayt uzunluğunda olabilir.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Bir denklemde en fazla 2500 matris hücresi olabilir (satır sayısı çarpı en geniş satır)." + } + "This equation is too large to draw." => "Bu denklem çizilemeyecek kadar büyük.", + "This equation could not be laid out." => "Bu denklem dizilemedi.", "Saved macro “{name}” ({steps} step)" => "“{name}” makrosu kaydedildi ({steps} adım)", "Saved macro “{name}” ({steps} steps)" => "“{name}” makrosu kaydedildi ({steps} adım)", "without {key}: another macro took it while recording" => "{key} olmadan: kayıt sırasında başka bir makro aldı", diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 1a70bd53c6..2a2ad26245 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -1018,6 +1018,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Зображення: {alt}", "Format Control: {name}" => "Формат елемента керування: {name}", "Error at character {position}: {message}" => "Помилка в символі {position}: {message}", + "Macro definitions are not supported in equations." => "Визначення макросів у формулах не підтримуються.", + "A % can't be combined with a link in an equation." => "Знак % не можна поєднувати з посиланням у формулі.", + "Equations can nest at most 32 levels deep." => "Формули можуть мати не більше 32 рівнів вкладеності.", + "An equation can be at most 4096 bytes long." => "Довжина формули не може перевищувати 4096 байт.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Формула може містити не більше 2500 клітинок матриці (рядки, помножені на найширший рядок)." + } + "This equation is too large to draw." => "Ця формула завелика для відображення.", + "This equation could not be laid out." => "Не вдалося побудувати цю формулу.", "Saved macro “{name}” ({steps} step)" => "Макрос «{name}» збережено ({steps} крок)", "Saved macro “{name}” ({steps} steps)" => "Макрос «{name}» збережено (кроків: {steps})", "without {key}: another macro took it while recording" => "без {key}: під час запису його зайняв інший макрос", diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index f77b90860e..8e1e9b7047 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -456,6 +456,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "Ảnh: {alt}", "Format Control: {name}" => "Định dạng điều khiển: {name}", "Error at character {position}: {message}" => "Lỗi tại ký tự {position}: {message}", + "Macro definitions are not supported in equations." => "Định nghĩa macro không được hỗ trợ trong phương trình.", + "A % can't be combined with a link in an equation." => "Không thể kết hợp % với liên kết trong phương trình.", + "Equations can nest at most 32 levels deep." => "Phương trình chỉ có thể lồng nhau tối đa 32 cấp.", + "An equation can be at most 4096 bytes long." => "Phương trình chỉ có thể dài tối đa 4096 byte.", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => { + "Phương trình chỉ có thể có tối đa 2500 ô ma trận (số hàng nhân với hàng rộng nhất)." + } + "This equation is too large to draw." => "Phương trình này quá lớn để vẽ.", + "This equation could not be laid out." => "Không thể dàn trang phương trình này.", "Saved macro “{name}” ({steps} step)" => "Đã lưu macro “{name}” ({steps} bước)", "Saved macro “{name}” ({steps} steps)" => "Đã lưu macro “{name}” ({steps} bước)", "without {key}: another macro took it while recording" => "không có {key}: một macro khác đã dùng phím này khi đang ghi", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 8a8a010827..366e0f90f7 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -487,6 +487,13 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Picture: {alt}" => "图片: {alt}", "Format Control: {name}" => "设置控件格式: {name}", "Error at character {position}: {message}" => "第 {position} 个字符处出错: {message}", + "Macro definitions are not supported in equations." => "公式中不支持宏定义。", + "A % can't be combined with a link in an equation." => "公式中的 % 不能与链接同时使用。", + "Equations can nest at most 32 levels deep." => "公式最多只能嵌套 32 层。", + "An equation can be at most 4096 bytes long." => "公式最长为 4096 字节。", + "An equation can have at most 2500 matrix cells (rows times the widest row)." => "公式最多只能有 2500 个矩阵单元格(行数乘以最宽的行)。", + "This equation is too large to draw." => "此公式太大,无法绘制。", + "This equation could not be laid out." => "无法排版此公式。", "Saved macro “{name}” ({steps} step)" => "已保存宏“{name}”({steps} 步)", "Saved macro “{name}” ({steps} steps)" => "已保存宏“{name}”({steps} 步)", "without {key}: another macro took it while recording" => "未使用 {key}: 录制时已被另一个宏占用", diff --git a/docs/localization-parity.md b/docs/localization-parity.md index ac4fd75b64..cf6d6321ca 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -9,6 +9,13 @@ right-to-left sheets and full complex-script support. Part of ## Where we are (measured from source on `main`, after the 2026-10-10 merges) +- **Current state (2026-11-08).** The counts, labels and per-language rows in this section and in + the Languages table are a snapshot from the dates given there; every language since added a + catalog of its own (`crates/ui-egui/src/i18n/.rs`, 18 languages besides English), and + `cargo xtask i18n-report` lists what each one still lacks. The status bar statistics, resize + tips, sheet notes, Goal Seek and macro toasts and the equation editor's own error messages now + follow the interface language; error text from the RaTeX equation parser stays English. + Where an older bullet below says status messages are English literals, this one supersedes it. - **A first catalog exists, for the ribbon only.** `crates/ui-egui/src/i18n.rs` (merged 10-10 in #31, #104, #82; German added 10-11) adds an interface-language preference that defaults to the system language (closes #20) and a View-tab switcher, with English-keyed lookup tables: @@ -62,7 +69,9 @@ right-to-left sheets and full complex-script support. Part of ## Languages -UI strings translated are measured counts against the ~2,200 estimate. Estimates to `full` +UI strings translated are measured counts against the ~2,200 estimate, as a snapshot from when +each row was last measured (Spanish, French and Vietnamese have had catalogs since; see the current +state above and `cargo xtask i18n-report`). Estimates to `full` include the rest of the catalog work below (10–20 h, counted once), localized function names, separators, number/date formats, machine translation with agent review, and script work. @@ -110,7 +119,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| -| 2026-11-08 | minor | Strings built with `format!` in English now translate their template first and fill it in once (`Language::tr_fill`): status bar statistics and the circular-reference note, the column width / row height drag tip, the formula bar text for a picture in a cell, the Move or Copy and Unhide notes, the Format Control title, the equation editor's error prefix, and the Goal Seek and macro recorder/runner toasts (#3600, #3602, #3603, #3605, #3607–#3611). 17 new keys in every catalog; Average, Count, Sum and the three existing templates added to the 11 catalogs that lacked them, and Ukrainian's English placeholders for those six replaced. Numbers in these strings keep the `.` decimal point | +| 2026-11-08 | minor | Strings built with `format!` in English now translate their template first and fill it in once (`Language::tr_fill`): status bar statistics and the circular-reference note, the column width / row height drag tip, the formula bar text for a picture in a cell, the Move or Copy and Unhide notes, the Format Control title, the equation editor's error prefix and its own check messages (macro definitions, `%` with a link, nesting, length, matrix-cell and size limits; RaTeX parser errors stay English), and the Goal Seek and macro recorder/runner toasts (#3600, #3602, #3603, #3605, #3607–#3611). 24 new keys in every catalog; Average, Count, Sum and the three existing templates added to the 11 catalogs that lacked them, and Ukrainian's English placeholders for those six replaced. Numbers in these strings keep the `.` decimal point | | 2026-10-23 | minor | Missing translations are reported, never a failure: `cargo xtask i18n-report` prints, per language, the strings other catalogs translate and it lacks (plus Spanish function help rows keyed by English the function catalog no longer has) and always passes; `cargo xtask ci` runs it first. Coverage and per-language parity tests and tests of one language's exact wording are gone; UI tests take the expected text from the catalog. Duplicate-key, placeholder, context-prefix and line-shape checks stay | | 2026-10-21 | minor | Romanian interface (`ro`, Română): 970 labels covering every key of the other catalogs (`crates/ui-egui/src/i18n/ro.rs`), `ro-*` system locales, the View-tab switcher and `app.language.set`; context keys show no prefix (File › Options test). English formulas and formats; AI-assisted draft pending native-speaker review | | 2026-10-20 | minor | Japanese: furigana (`rPh` phonetic runs and `` in `xl/sharedStrings.xml`) is no longer deleted by an open + save; it is kept on the workbook and written back (a `` without runs is kept too, while duplicate texts with different readings keep only the first, reported on open). Display of the readings is still missing (`crates/xlsx/src/tests/phonetic_tests.rs`) | From c47bdffcd6c99612a11e347bd7f0f6842f59975f Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:28:58 -0300 Subject: [PATCH 065/201] Calc: preserve dynamic-array kind without discarding saved spill areas (#964) --- crates/xlsx/src/tests/roundtrip.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index ab55c84452..4b61f55b88 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1057,12 +1057,11 @@ fn legacy_and_dynamic_formulas_keep_their_kind() { let (xml, _) = sheet1_xml(&bytes); assert!(xml.contains("TANH(A1:A3)+A1:A3"), "{xml}"); assert!(xml.contains("SUM(A1:A3)"), "{xml}"); - // Uncalculated, the spill range is not known yet; the formula stays dynamic. - assert!(xml.contains("TANH(A1:A3)"), "{xml}"); - assert!(xml.contains("TANH(A1:A3)"), "{xml}"); let (back, _) = read_xlsx(&bytes).unwrap(); - for a in ["B2", "B3", "C2", "D2"] { + for (a, dynamic) in [("B2", false), ("B3", false), ("C2", true), ("D2", false)] { assert_eq!(text(&back, a), text(&wb, a), "{a}"); + let formula = back.sheet(0).unwrap().cell(at(a)).unwrap().formula.as_ref().unwrap(); + assert_eq!(formula.dynamic, dynamic, "{a}: dynamic-array metadata survives saving"); } } From 09d52cc7cd76a434431fc85d4e09ec4383e24ecf Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 11 Nov 2026 09:02:08 +0000 Subject: [PATCH 066/201] Style model: cell padding kept in Alignment `Alignment::padding: [Option; 4]` (left, right, top, bottom, in hundredths of a point; `None` where a file states none) holds an OpenDocument cell's padding, which LibreOffice lays rows out with. It is part of style equality and hashing, so styles that differ only by padding intern apart; serde default, skipped when all `None`, so older JSON reads. Excel has no cell padding: the XLSX and XLS readers set none, and the XLSX writer leaves it out (a style that differs from the default only by padding writes no ``). GridCraft does not draw padding yet. --- crates/model/src/style.rs | 33 ++++++++++++++++++++++++++ crates/xlsx/src/styles.rs | 5 +++- crates/xlsx/src/tests/roundtrip.rs | 38 +++++++++++++++++++++++++++++- crates/xlsx/src/xls/styles.rs | 1 + docs/file-format-parity.md | 3 ++- 5 files changed, 77 insertions(+), 3 deletions(-) diff --git a/crates/model/src/style.rs b/crates/model/src/style.rs index d2f10780e0..6318c557ab 100644 --- a/crates/model/src/style.rs +++ b/crates/model/src/style.rs @@ -359,6 +359,17 @@ pub struct Alignment { pub indent: u8, /// Degrees -90..=90, or 255 for vertical stacked text. pub rotation: i16, + /// Space between the cell's edges and its text, left, right, top, bottom, in hundredths + /// of a point; `None` where the file stated none (the application's own). An OpenDocument + /// cell's padding; Excel has none. Not drawn yet. + #[serde(default, skip_serializing_if = "Alignment::no_padding")] + pub padding: [Option; 4], +} + +impl Alignment { + fn no_padding(p: &[Option; 4]) -> bool { + p.iter().all(Option::is_none) + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -499,6 +510,28 @@ mod tests { assert!(!t.get(StyleId(999)).font.bold); } + #[test] + fn padding_keeps_styles_apart_and_survives_json() -> Result<(), Box> { + let mut t = StyleTable::default(); + let padded = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]); + let other = t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(1)]); + assert_ne!(padded, StyleId::DEFAULT); + assert_ne!(padded, other); + assert_eq!(t.derive(StyleId::DEFAULT, |s| s.align.padding = [Some(10), None, Some(0), Some(65535)]), padded); + assert_eq!(t.derive(padded, |s| s.align.padding = [None; 4]), StyleId::DEFAULT); + + let style = t.get(padded).clone(); + let json = serde_json::to_string(&style)?; + assert!(json.contains("padding"), "{json}"); + assert_eq!(serde_json::from_str::" + + svg_text[:start] + tag + svg_text[end:] + + "" + ) + with tempfile.TemporaryDirectory() as work: + document = Path(work) / "icon.html" + document.write_text(page) + subprocess.run( + [chrome, "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", + "--default-background-color=00000000", "--force-device-scale-factor=1", + f"--window-size={size},{size}", f"--screenshot={out}", document.as_uri()], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + + +def png_size(data): + if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR": + die("renderer wrote something that is not a PNG") + return struct.unpack(">II", data[16:24]) + + +def has_alpha(data): + # IHDR colour type 6 is RGBA; a renderer that dropped alpha would flatten the padding. + return data[25] == 6 + + +def pack_ico(pngs): + body = bytearray(struct.pack(" 256: + die(f"ico frames must be square and at most 256 px, got {width}x{height}") + body += struct.pack("I", len(data) + 8) + data + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def mac_svg(svg_text): + if 'viewBox="0 0 512 512"' not in svg_text: + die("gridcraft-nightly.svg must keep the full-bleed 0 0 512 512 viewBox") + return svg_text.replace('viewBox="0 0 512 512"', MAC_VIEWBOX) + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def render_all(kind): + renderer, program = renderer_argv(kind) + svg_text = SVG.read_text() + padded = mac_svg(svg_text) + with tempfile.TemporaryDirectory() as work: + work = Path(work) + + def draw(source, size, name): + if not source.strip(): + die(f"empty SVG for {name}") + out = work / "tile.svg" + out.write_text(source) + (render_resvg if renderer == "resvg" else render_chrome)(program, source, size, work / name) + data = (work / name).read_bytes() + if png_size(data) != (size, size): + die(f"{name}: expected {size}x{size}, got {png_size(data)}") + if not has_alpha(data): + die(f"{name}: the render has no alpha channel") + return data + + # Full-bleed tile: the Linux tar icon (256) and the Windows ICO frames. + tile = {size: draw(svg_text, size, f"tile-{size}.png") for size in sorted({256} | set(ICO_SIZES))} + (ICONS / "gridcraft-nightly.png").write_bytes(tile[256]) + (ICONS / "gridcraft-nightly.ico").write_bytes(pack_ico([tile[size] for size in ICO_SIZES])) + # Padded macOS tile: the 1024 master, the ICNS slots and the runtime Dock render. + mac = {size: draw(padded, size, f"mac-{size}.png") for size in MAC_PNG_SIZES} + (ICONS / "gridcraft-nightly-1024.png").write_bytes(mac[1024]) + (ICONS / "gridcraft-nightly.icns").write_bytes(pack_icns([(kind, mac[size]) for kind, size in ICNS_SLOTS])) + write_provenance(renderer) + + +def write_provenance(renderer): + outputs = ("gridcraft-nightly.png", "gridcraft-nightly-1024.png", "gridcraft-nightly.ico", "gridcraft-nightly.icns") + provenance = { + "title": "GridCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + {"path": "assets/app-icon/gridcraft-nightly.svg", "sha256": digest(SVG), "purpose": "vector master for every frame"}, + {"path": "assets/app-icon/gridcraft.svg", "sha256": digest(ICONS / "gridcraft.svg"), "purpose": "stable artwork this is derived from"}, + ], + "method": { + "kind": "vector render of the project-owned artwork with only its field colour deepened", + "stable_field": "#1f9d55", + "nightly_field": "#14532d", + "unchanged": "ink #0b0b0c, paper #efe9dc, every path, stroke width and the 824/1024 Mac padding", + "sizes": "each frame rendered at its own size, never upscaled", + "renderer": renderer, + "generator": "packaging/nightly-icons.py", + }, + "outputs": {name: digest(ICONS / name) for name in outputs}, + "ico_frame_sizes": list(ICO_SIZES), + "icns_png_slots": {kind: size for kind, size in ICNS_SLOTS}, + } + (ICONS / "nightly-provenance.json").write_text(json.dumps(provenance, indent=2) + "\n") + + +def check(): + provenance = json.loads((ICONS / "nightly-provenance.json").read_text()) + ok = True + for name, expected in provenance["outputs"].items(): + actual = digest(ICONS / name) + if actual != expected: + print(f"mismatch: assets/app-icon/{name} is {actual}, provenance says {expected}", file=sys.stderr) + ok = False + ico = (ICONS / "gridcraft-nightly.ico").read_bytes() + count = struct.unpack("I", icns[4:8])[0] != len(icns): + print("mismatch: the ICNS header does not cover the file", file=sys.stderr) + ok = False + return 0 if ok else 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--renderer", choices=("auto", "resvg", "chrome"), default="auto") + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + if args.check: + return check() + render_all(args.renderer) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 0000000000..ca9301cbfd --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Nightly source-contract regression tests for GridCraft; local checks, not live API/crypto evidence.""" +import base64 +import copy +import hashlib +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# Each platform's one trust field in policy v3, and the public stable identity it must name. +NIGHTLY_TRUST = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + +# The Linux leg's public release key, as the protected release checkout must carry it. +LINUX_KEY = ROOT / ".github/nightly-linux-signing-key.asc" + + +def openpgp_primary_fingerprints(armored): + """Return the v4 fingerprint of every primary public-key packet in one armored block. + + A narrow reader for the committed public key, not a general OpenPGP parser: anything other + than one well-formed public-key block, or any secret material, refuses. + """ + lines = armored.strip().splitlines() + if lines[:1] != ["-----BEGIN PGP PUBLIC KEY BLOCK-----"] or lines[-1:] != ["-----END PGP PUBLIC KEY BLOCK-----"]: + raise ValueError("exactly one armored public key block is required") + body = lines[1:-1] + if "" not in body: + raise ValueError("armor header separator missing") + body = body[body.index("") + 1:] + if not body or not body[-1].startswith("="): + raise ValueError("armor checksum missing") + data = base64.b64decode("".join(body[:-1]), validate=True) + fingerprints, offset = [], 0 + while offset < len(data): + header = data[offset] + if not header & 0x80: + raise ValueError("invalid packet header") + if header & 0x40: + tag, offset = header & 0x3F, offset + 1 + first = data[offset] + if first < 192: + length, offset = first, offset + 1 + elif first < 224: + length, offset = ((first - 192) << 8) + data[offset + 1] + 192, offset + 2 + elif first == 255: + length, offset = int.from_bytes(data[offset + 1:offset + 5], "big"), offset + 5 + else: + raise ValueError("partial packet lengths are not a public key") + else: + tag, kind, offset = (header >> 2) & 0x0F, header & 0x03, offset + 1 + if kind == 3: + raise ValueError("indeterminate packet length") + size = 1 << kind + length, offset = int.from_bytes(data[offset:offset + size], "big"), offset + size + packet = data[offset:offset + length] + if len(packet) != length: + raise ValueError("truncated packet") + if tag == 5 or tag == 7: + raise ValueError("secret key material must never be committed") + if tag == 6: + if packet[:1] != b"\x04": + raise ValueError("only v4 primary keys are expected") + fingerprints.append(hashlib.sha1(b"\x99" + length.to_bytes(2, "big") + packet).hexdigest().upper()) + offset += length + return fingerprints + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "gridcraft-nightly-release", "cancel-in-progress": "false"}: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" + lines = jobs.splitlines() + found = [] + for index, line in enumerate(lines): + head = re.fullmatch(r" if:(?: (.*))?", line) + if head is None: + continue + value = (head[1] or "").strip() + continuation = [] + for follow in lines[index + 1:]: + if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4: + break + continuation.append(follow.strip()) + indicator = value if re.fullmatch(r"[>|][+-]?", value) else None + parts = continuation if indicator else [value] + continuation + found.append((indicator, " ".join(part for part in parts if part))) + return found + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")): + source = (ROOT / ".github/workflows" / workflow).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: gridcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: gridcraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_sonar_classifies_only_the_exact_packaging_fixture_runners(self): + source = (ROOT / "sonar-project.properties").read_text() + self.assertEqual(re.findall(r"(?m)^sonar.sources=(.*)$", source), ["."]) + self.assertEqual(re.findall(r"(?m)^sonar.tests=(.*)$", source), ["packaging"]) + inclusions = re.findall(r"(?m)^sonar.test.inclusions=(.*)$", source) + self.assertEqual(len(inclusions), 1) + entries = inclusions[0].split(",") + expected = {"packaging/nightly-tests.py", "packaging/nightly-archive-tests.py", + "packaging/linux/nightly-linux-launch-tests.py", + "packaging/macos/nightly_plist_tests.py", "packaging/macos/nightly_sign_tests.py", + "packaging/windows/nightly-package-tests.ps1", + "packaging/windows/nightly-signing-tests.ps1", "packaging/nightly-release-tests.py"} + self.assertEqual(set(entries), expected, "classify exact fixtures, never production helpers or wildcard scope") + self.assertEqual(len(entries), len(expected), "duplicate fixture classification") + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actor.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/gridcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/gridcraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. + if self.policy["producer_workflow_id"] is not None: + self.assertIs(type(self.policy["producer_workflow_id"]), int) + self.assertGreater(self.policy["producer_workflow_id"], 0) + self.assertNotEqual(self.policy["producer_workflow_id"], + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_and_trust_anchors_match_producer(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(set(row), {"unsigned_artifact_name", "trust"}) + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}") + self.assertEqual(row["trust"], {field: value}) + + def test_committed_linux_key_is_exactly_the_one_the_policy_trusts(self): + self.assertFalse(LINUX_KEY.is_symlink(), "the key file must be a regular committed file") + armored = LINUX_KEY.read_text(encoding="ascii") + self.assertEqual(armored.count("-----BEGIN PGP"), 1, "exactly one armored block") + self.assertEqual(openpgp_primary_fingerprints(armored), + [self.policy["platforms"]["linux-x86_64"]["trust"]["fingerprint"]], + "exactly one primary key, and it is the release key the policy trusts") + + def test_key_reader_refuses_secret_or_extra_material(self): + armored = LINUX_KEY.read_text(encoding="ascii") + for change in (armored.replace("PUBLIC KEY BLOCK", "PRIVATE KEY BLOCK"), + armored.replace("-----END PGP PUBLIC KEY BLOCK-----\n", ""), + "Comment: extra\n" + armored): + with self.subTest(change=change[:40]), self.assertRaises(ValueError): + openpgp_primary_fingerprints(change) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/gridcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#")) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 0000000000..684239f495 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Run the synthetic nightly packaging suites together; no app build, no signing, no network.""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("gridcraft_archive_suite", "nightly-archive-tests.py"), + ("gridcraft_plist_suite", "macos/nightly_plist_tests.py"), + ("gridcraft_release_dispatch_suite", "nightly-release-tests.py"), + ("gridcraft_mac_sign_suite", "macos/nightly_sign_tests.py"), + ("gridcraft_linux_launch_suite", "linux/nightly-linux-launch-tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, here / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 0000000000..792198589e --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..15c6ac9964 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'gridcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'gridcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.gridcraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'GridCraft Nightly' 'GridCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('GridCraft', 'GridCraft 0.23.1 (nightly-v1)'), @('GridCraft Nightly', 'GridCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/gridcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'gridcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 0000000000..d45a0f83d6 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,83 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:GRIDCRAFT_VERSION = $version +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..1d2312d9c3 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,133 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "gridcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "gridcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('gridcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.gridcraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (GRIDCRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (GRIDCRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'GridCraft Nightly' -or $VersionOutput -cne "GridCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:GRIDCRAFT_VERSION -or $Version -cne $env:GRIDCRAFT_VERSION) { throw 'nightly-v1 requires explicit GRIDCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status +# build.rs reads GRIDCRAFT_BUILD_CHANNEL and GRIDCRAFT_VERSION from the environment: that pair is +# what makes this executable the nightly flavor with the prepared identity, and no other. +$oldChannel = $env:GRIDCRAFT_BUILD_CHANNEL +try { + $env:GRIDCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:GRIDCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # Into the directory the archive steps read (`$TargetDir`), not Cargo's default. + cargo build --release --locked -p gridcraft --target $Target --target-dir $TargetDir + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:GRIDCRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:GRIDCRAFT_BUILD_SHA $env:GRIDCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\gridcraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'GridCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'gridcraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('gridcraft.exe' -notin $Names -or 'gridcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 9a1303064a..386dcfebc7 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,11 +53,21 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# A nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:GRIDCRAFT_BUILD_SHA) { $env:GRIDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:GRIDCRAFT_BUILD_DATE) { $env:GRIDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "GridCraft $Version for Windows $Arch ($Target)" +# The nightly channel is its own producer: a GUI-only intermediate for the trusted signing job, never +# this MSI/portable/CLI contract. +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. @@ -83,6 +96,11 @@ foreach ($check in @(@('gridcraft.exe', 2), @('gridcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +# The nightly flavor has its own identity; shipping it as the stable app would hand a nightly window +# the stable taskbar identity, data folder and update channel (#16335). +if ((Get-Item -LiteralPath (Join-Path $Bin 'gridcraft.exe')).VersionInfo.ProductName -eq 'GridCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 222d5705b2..fe7d9e39c9 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -13,16 +13,28 @@ This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). + Nightly callers require signing with -Required and can check the signing configuration with + -Required -CheckOnly. Compilation uses the separate -CheckBuildEnvironment mode, which never + imports keys. .EXAMPLE pwsh packaging/windows/sign.ps1 dist/gridcraft.exe dist/gridcraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } @@ -44,11 +56,30 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + # Compilation must never see a key: the nightly producer calls this before cargo, and the trusted + # signing job is a separate operation with its own environment. + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -96,6 +127,10 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + # signtool verify alone can pass while the authenticode state is anything but Valid. + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index 4eed7fd86c..5b67372365 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,9 +1,17 @@ sonar.projectKey=storytold_gridcraft sonar.organization=storytold +# `sonar.tests` turns off the CLI's default scope, so `sonar.sources=.` must name the production +# tree explicitly; without it Sonar indexes the packaging fixtures and nothing else (L5). +sonar.sources=. +sonar.tests=packaging +# Only these are test runners: the helpers they exercise stay production code. +sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-archive-tests.py,packaging/linux/nightly-linux-launch-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py + # The region table is one record per locale with the same field names and many shared values # (month names, formats); that repetition is data, not copy-pasted logic. sonar.cpd.exclusions=crates/core/src/region.rs +sonar.coverage.exclusions=packaging/** # githubactions:S7637 asks for every action to be pinned to a commit SHA. A workflow covered by # .github/workflows/actions.lock runs the commit the lockfile records, so its tag refs are pinned From 73a2fd7148fb18640cb1b81f34b8aa557cee6b30 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 06:31:18 +0000 Subject: [PATCH 186/201] Repin craft-libs to storytold next 16001e7210 and egui to storytold b15ffe9bfc --- Cargo.lock | 98 +++++++++++++++++------------------ Cargo.toml | 42 +++++++-------- apps/gridcraft-web/Cargo.toml | 4 +- crates/ui-egui/Cargo.toml | 2 +- 4 files changed, 73 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0de666c072..a6f39a1f9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1034,7 +1034,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "block2 0.6.2", "objc2-app-kit 0.3.2", @@ -1044,7 +1044,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "rustix 1.1.6", ] @@ -1052,7 +1052,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1070,12 +1070,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "egui", ] @@ -1083,12 +1083,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "thiserror 2.0.21", ] @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "serde", ] @@ -1104,7 +1104,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "chrono", "craft-xml", @@ -1116,7 +1116,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "harfrust 0.13.3", "kurbo", @@ -1130,12 +1130,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" [[package]] name = "craft-gridcraft-format" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "serde", "serde_json", @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "chrono", "fixed_decimal", @@ -1186,7 +1186,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-host", "craft-i18n", @@ -1201,7 +1201,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-xml", "roxmltree", @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "serde_json", ] @@ -1219,7 +1219,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "aes", "base64 0.23.1", @@ -1237,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-odf", "craft-sheet", @@ -1248,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "aes", "base64 0.23.1", @@ -1265,7 +1265,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-xml", "craft-zip", @@ -1276,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "serde", ] @@ -1284,7 +1284,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "async-channel", "async-io", @@ -1315,7 +1315,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-host", @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "dispatch2", "objc2 0.6.5", @@ -1351,7 +1351,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-atomic", "craft-host", @@ -1368,12 +1368,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "fax", "hayro-ccitt", @@ -1384,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-xml", "flate2", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1416,12 +1416,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-i18n", @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "accesskit", "craft-behavior", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1500,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-host", @@ -1518,7 +1518,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-host", @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-host", @@ -1559,7 +1559,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-behavior", "craft-host", @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "chrono", "craft-host", @@ -1607,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "js-sys", "serde_json", @@ -1618,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-host", "craft-platform", @@ -1630,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "winsafe", ] @@ -1638,7 +1638,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-appkit", "craft-atomic", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-cfb", "craft-sheet", @@ -1683,7 +1683,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "craft-drawingml", "craft-opc", @@ -1695,7 +1695,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1705,7 +1705,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3210,7 +3210,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/aiongg/craft-libs?rev=3ad64a26ea8a72c03c416681e14f7744393790b1#3ad64a26ea8a72c03c416681e14f7744393790b1" +source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" dependencies = [ "hayro-ccitt", ] diff --git a/Cargo.toml b/Cargo.toml index e668246aa2..091b4c436c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" } # ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one # craft-libs revision. # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "=0.1.0", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "=0.1.0", features = ["ui"] } # PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers. -craft-pdf = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0", default-features = false } -craft-stream-codecs = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0", default-features = false } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). -craft-cfb = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-offcrypto = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-ods = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } # OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`. -craft-opc = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. -craft-csv = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-math = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. -craft-gridcraft-format = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. # SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx. -craft-xlsx = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-xml = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-xls = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-drawingml = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-mcp-server = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "=0.1.0" } # foundation thiserror = "2" @@ -92,15 +92,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" # One native window per workbook: the window list, Window menu titles and the immediate-viewport # driver. Same craft-libs revision as craft-update above. -craft-window = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", default-features = false, features = ["ui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", default-features = false, features = ["ui"] } # The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is # to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the # printer controls. Same craft-libs revision as above. -craft-behavior = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" } -craft-host = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" } -craft-keymap = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" } -craft-theme = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" } -craft-print = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", features = ["ui"] } +craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } +craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } +craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } +craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", features = ["ui"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index f2aa0e548f..22f879dfdc 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true } gridcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.gridcraft over the control channel. -craft-web-api = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } -craft-web-host = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 42e637df10..9bf606ecab 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the # one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml). -craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "3ad64a26ea8a72c03c416681e14f7744393790b1" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } craft-behavior = { workspace = true } craft-host = { workspace = true } craft-keymap = { workspace = true } From c2c9e2bc52af91e0d8cdc91813e93bced28e664b Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 06:32:47 +0000 Subject: [PATCH 187/201] Repin egui to storytold b15ffe9bfc (what craft-libs next pins) --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 28 ++++++++++++++-------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a6f39a1f9f..89e57014b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2033,7 +2033,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", "emath", @@ -2042,7 +2042,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -2077,7 +2077,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "accesskit", "ahash", @@ -2096,7 +2096,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -2115,7 +2115,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "accesskit_winit", "arboard", @@ -2140,7 +2140,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "egui", @@ -2153,7 +2153,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", "egui", @@ -2166,7 +2166,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "dify", "eframe", @@ -2192,7 +2192,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "bytemuck", ] @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" dependencies = [ "ahash", "bytemuck", @@ -2299,7 +2299,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[package]] name = "equivalent" @@ -8604,14 +8604,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" +source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" diff --git a/Cargo.toml b/Cargo.toml index 091b4c436c..58ee311cc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -128,18 +128,18 @@ debug = 0 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } From 4f7a511b9f00056ce8f5c104335c9547d84610c3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 07:28:30 +0000 Subject: [PATCH 188/201] Print page: widen the settings column so craft-print's Copies row does not wrap --- crates/ui-egui/src/backstage/print.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/backstage/print.rs b/crates/ui-egui/src/backstage/print.rs index de793b86ac..24178dba8a 100644 --- a/crates/ui-egui/src/backstage/print.rs +++ b/crates/ui-egui/src/backstage/print.rs @@ -22,7 +22,7 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m let pages: Vec = bs.preview.as_ref().and_then(|(_, p)| p.get("pageList")).and_then(Json::as_array).cloned().unwrap_or_default(); ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(250.0); + ui.set_width(340.0); if let Some(discover) = &app.services.printers { crate::printing::show(&mut app.printing, ui, discover, |label| lang.tr(label).to_owned()); } From 643b52cb2925a15272b0b6841dfb67770c7e59a5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 13:43:38 +0000 Subject: [PATCH 189/201] Repin craft-libs to storytold next d1bdf8e5da --- Cargo.lock | 98 +++++++++++++++++------------------ Cargo.toml | 42 +++++++-------- apps/gridcraft-web/Cargo.toml | 4 +- crates/ui-egui/Cargo.toml | 2 +- 4 files changed, 73 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 53def46152..5d6fe71ca5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1034,7 +1034,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "block2 0.6.2", "objc2-app-kit 0.3.2", @@ -1044,7 +1044,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "rustix 1.1.6", ] @@ -1052,7 +1052,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1070,12 +1070,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "egui", ] @@ -1083,12 +1083,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "thiserror 2.0.21", ] @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "serde", ] @@ -1104,7 +1104,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "chrono", "craft-xml", @@ -1116,7 +1116,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "harfrust 0.13.3", "kurbo", @@ -1130,12 +1130,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" [[package]] name = "craft-gridcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "serde", "serde_json", @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "chrono", "fixed_decimal", @@ -1186,7 +1186,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-host", "craft-i18n", @@ -1201,7 +1201,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-xml", "roxmltree", @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "serde_json", ] @@ -1219,7 +1219,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "aes", "base64 0.23.1", @@ -1237,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-odf", "craft-sheet", @@ -1248,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "aes", "base64 0.23.1", @@ -1265,7 +1265,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-xml", "craft-zip", @@ -1276,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "serde", ] @@ -1284,7 +1284,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "async-channel", "async-io", @@ -1315,7 +1315,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-host", @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "dispatch2", "objc2 0.6.5", @@ -1351,7 +1351,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-atomic", "craft-host", @@ -1368,12 +1368,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "fax", "hayro-ccitt", @@ -1384,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-xml", "flate2", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1416,12 +1416,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-i18n", @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "accesskit", "craft-behavior", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1500,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-host", @@ -1518,7 +1518,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-host", @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-host", @@ -1559,7 +1559,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-behavior", "craft-host", @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "chrono", "craft-host", @@ -1607,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "js-sys", "serde_json", @@ -1618,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-host", "craft-platform", @@ -1630,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "winsafe", ] @@ -1638,7 +1638,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-appkit", "craft-atomic", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-cfb", "craft-sheet", @@ -1683,7 +1683,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "craft-drawingml", "craft-opc", @@ -1695,7 +1695,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1705,7 +1705,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3211,7 +3211,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=16001e7210bee61db60c84fbe18c3c3e2ef4584f#16001e7210bee61db60c84fbe18c3c3e2ef4584f" +source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" dependencies = [ "hayro-ccitt", ] diff --git a/Cargo.toml b/Cargo.toml index 58ee311cc8..995d01157e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" } # ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one # craft-libs revision. # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "=0.1.0", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "=0.1.0", features = ["ui"] } # PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0", default-features = false } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0", default-features = false } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } # OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`. -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. -craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. # SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx. -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "=0.1.0" } # foundation thiserror = "2" @@ -92,15 +92,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" # One native window per workbook: the window list, Window menu titles and the immediate-viewport # driver. Same craft-libs revision as craft-update above. -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", default-features = false, features = ["ui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", default-features = false, features = ["ui"] } # The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is # to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the # printer controls. Same craft-libs revision as above. -craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } -craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } -craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } -craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", features = ["ui"] } +craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } +craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } +craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } +craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", features = ["ui"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index 22f879dfdc..03d37a8ab7 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true } gridcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.gridcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9bf606ecab..9b0ee9b6b8 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the # one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml). -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "16001e7210bee61db60c84fbe18c3c3e2ef4584f" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } craft-behavior = { workspace = true } craft-host = { workspace = true } craft-keymap = { workspace = true } From 3e43b2bce2eead65b3d30270590513925a9921f1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 15:48:35 +0000 Subject: [PATCH 190/201] Repin craft-libs to storytold next aa401985d --- Cargo.lock | 98 +++++++++++++++++------------------ Cargo.toml | 42 +++++++-------- apps/gridcraft-web/Cargo.toml | 4 +- crates/ui-egui/Cargo.toml | 2 +- 4 files changed, 73 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d6fe71ca5..890550d893 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1034,7 +1034,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "block2 0.6.2", "objc2-app-kit 0.3.2", @@ -1044,7 +1044,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "rustix 1.1.6", ] @@ -1052,7 +1052,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1070,12 +1070,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "egui", ] @@ -1083,12 +1083,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "thiserror 2.0.21", ] @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "serde", ] @@ -1104,7 +1104,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "chrono", "craft-xml", @@ -1116,7 +1116,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "harfrust 0.13.3", "kurbo", @@ -1130,12 +1130,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" [[package]] name = "craft-gridcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "serde", "serde_json", @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "chrono", "fixed_decimal", @@ -1186,7 +1186,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-host", "craft-i18n", @@ -1201,7 +1201,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-xml", "roxmltree", @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "serde_json", ] @@ -1219,7 +1219,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "aes", "base64 0.23.1", @@ -1237,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-odf", "craft-sheet", @@ -1248,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "aes", "base64 0.23.1", @@ -1265,7 +1265,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-xml", "craft-zip", @@ -1276,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "serde", ] @@ -1284,7 +1284,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "async-channel", "async-io", @@ -1315,7 +1315,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-host", @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "dispatch2", "objc2 0.6.5", @@ -1351,7 +1351,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-atomic", "craft-host", @@ -1368,12 +1368,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "fax", "hayro-ccitt", @@ -1384,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-xml", "flate2", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1416,12 +1416,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-i18n", @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "accesskit", "craft-behavior", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1500,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-host", @@ -1518,7 +1518,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-host", @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-host", @@ -1559,7 +1559,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-behavior", "craft-host", @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "chrono", "craft-host", @@ -1607,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "js-sys", "serde_json", @@ -1618,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-host", "craft-platform", @@ -1630,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "winsafe", ] @@ -1638,7 +1638,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-appkit", "craft-atomic", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-cfb", "craft-sheet", @@ -1683,7 +1683,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "craft-drawingml", "craft-opc", @@ -1695,7 +1695,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1705,7 +1705,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "flate2", "thiserror 2.0.21", @@ -3211,7 +3211,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e#d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" +source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" dependencies = [ "hayro-ccitt", ] diff --git a/Cargo.toml b/Cargo.toml index 995d01157e..5c72248170 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" } # ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one # craft-libs revision. # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "=0.1.0", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "=0.1.0", features = ["ui"] } # PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0", default-features = false } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0", default-features = false } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } # OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`. -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. -craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. # SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx. -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "=0.1.0" } # foundation thiserror = "2" @@ -92,15 +92,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" # One native window per workbook: the window list, Window menu titles and the immediate-viewport # driver. Same craft-libs revision as craft-update above. -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", default-features = false, features = ["ui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", default-features = false, features = ["ui"] } # The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is # to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the # printer controls. Same craft-libs revision as above. -craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } -craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } -craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } -craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", features = ["ui"] } +craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } +craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } +craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } +craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", features = ["ui"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index 03d37a8ab7..db990721c4 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true } gridcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.gridcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9b0ee9b6b8..d20832a04e 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the # one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml). -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d1bdf8e5dac7513e4fbc4dab16edaaeda5ebcf5e" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } craft-behavior = { workspace = true } craft-host = { workspace = true } craft-keymap = { workspace = true } From 5682daedc17c1da0a34940a1747f851418b0a41b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 18:52:35 +0100 Subject: [PATCH 191/201] Remove Quick Analysis translations from the GridCraft locale files Keep English keys only; the translations move to a craft-i18n PR (AGENTS.md rule 16). --- crates/ui-egui/src/i18n/cs.rs | 24 ------------------------ crates/ui-egui/src/i18n/de.rs | 25 ------------------------- crates/ui-egui/src/i18n/es.rs | 25 ------------------------- crates/ui-egui/src/i18n/fr.rs | 25 ------------------------- crates/ui-egui/src/i18n/ja.rs | 25 +++++-------------------- crates/ui-egui/src/i18n/ko.rs | 25 ------------------------- crates/ui-egui/src/i18n/pt.rs | 20 -------------------- crates/ui-egui/src/i18n/ru.rs | 20 -------------------- crates/ui-egui/src/i18n/sr.rs | 25 ------------------------- crates/ui-egui/src/i18n/zh.rs | 25 ------------------------- 10 files changed, 5 insertions(+), 234 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index 1f52b12bb0..a7464598a3 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -579,30 +579,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Zoom Out" => "Oddálit", // widgets.rs (alphabetical keys). "Dismiss" => "Zavřít", - "Quick Analysis (Ctrl+Q)" => "Rychlá analýza (Ctrl+Q)", - "Formatting" => "Formátování", - "Charts" => "Grafy", - "Totals" => "Součty", - "Tables" => "Tabulky", - "Color Scale" => "Barevná škála", - "Icon Set" => "Sada ikon", - "Greater Than…" => "Větší než…", - "Clear Rules" => "Vymazat pravidla", - "Clustered Column" => "Skupinový sloupcový", - "Line" => "Spojnicový", - "Pie" => "Výsečový", - "Bar" => "Pruhový", - "Scatter" => "Bodový", - "% Total" => "% z celku", - "Running Total" => "Průběžný součet", - "By Column" => "Podle sloupců", - "By Row" => "Podle řádků", - "Column" => "Sloupec", - "Win/Loss" => "Zisk/ztráta", - "Green Data Bars" => "Zelené datové čáry", - "Blue-White-Red Scale" => "Škála modrá-bílá-červená", - "White-Green Scale" => "Škála bílá-zelená", - "Duplicate Values" => "Duplicitní hodnoty", "Rename" => "Přejmenovat", "Move or Copy…" => "Přesunout nebo kopírovat…", "Duplicate" => "Duplikovat", diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 54cd5dcc0e..300cc4969a 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -478,31 +478,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Dunkel", "Sheet Options|View" => "Anzeige", "Print" => "Drucken", - "Quick Analysis (Ctrl+Q)" => "Schnellanalyse (Strg+Q)", - "Formatting" => "Formatierung", - "Charts" => "Diagramme", - "Totals" => "Ergebnisse", - "Tables" => "Tabellen", - "Color Scale" => "Farbskala", - "Icon Set" => "Symbolsatz", - "Greater Than…" => "Größer als…", - "Clear Rules" => "Regeln löschen", - "Clustered Column" => "Gruppierte Säulen", - "Line" => "Linie", - "Pie" => "Kreis", - "Bar" => "Balken", - "Scatter" => "Punkt (XY)", - "Recommended Charts" => "Empfohlene Diagramme", - "% Total" => "% des Gesamtergebnisses", - "Running Total" => "Laufende Summe", - "By Column" => "Nach Spalte", - "By Row" => "Nach Zeile", - "Column" => "Säule", - "Win/Loss" => "Gewinn/Verlust", - "Green Data Bars" => "Grüne Datenbalken", - "Blue-White-Red Scale" => "Blau-Weiß-Rot-Skala", - "White-Green Scale" => "Weiß-Grün-Skala", - "Duplicate Values" => "Doppelte Werte", "Print What" => "Was drucken", // grid.rs cell and row/column header context menus. "Cut" => "Ausschneiden", diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 0f6c924616..d0df42c8b2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -496,31 +496,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Compact" => "Compacto", "Outline" => "Esquema", "Tabular" => "Tabular", - "Quick Analysis (Ctrl+Q)" => "Análisis rápido (Ctrl+Q)", - "Formatting" => "Formato", - "Charts" => "Gráficos", - "Totals" => "Totales", - "Tables" => "Tablas", - "Color Scale" => "Escala de color", - "Icon Set" => "Conjunto de iconos", - "Greater Than…" => "Mayor que…", - "Clear Rules" => "Borrar reglas", - "Clustered Column" => "Columna agrupada", - "Line" => "Línea", - "Pie" => "Circular", - "Bar" => "Barras", - "Scatter" => "Dispersión", - "Recommended Charts" => "Gráficos recomendados", - "% Total" => "% del total", - "Running Total" => "Total acumulado", - "By Column" => "Por columna", - "By Row" => "Por fila", - "Column" => "Columna", - "Win/Loss" => "Ganancia/pérdida", - "Green Data Bars" => "Barras de datos verdes", - "Blue-White-Red Scale" => "Escala azul-blanco-rojo", - "White-Green Scale" => "Escala blanco-verde", - "Duplicate Values" => "Valores duplicados", "Insert Sheet" => "Insertar hoja", "Rename" => "Cambiar nombre", "Move or Copy…" => "Mover o copiar…", diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index c533b3ef43..104edcd161 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -456,31 +456,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { } "Maximum Change must be a number of 0 or more." => "L'écart maximal doit être un nombre supérieur ou égal à 0.", "Calculation settings are saved with the workbook." => "Les paramètres de calcul sont enregistrés avec le classeur.", - "Quick Analysis (Ctrl+Q)" => "Analyse rapide (Ctrl+Q)", - "Formatting" => "Mise en forme", - "Charts" => "Graphiques", - "Totals" => "Totaux", - "Tables" => "Tableaux", - "Color Scale" => "Échelle de couleurs", - "Icon Set" => "Jeu d'icônes", - "Greater Than…" => "Supérieur à…", - "Clear Rules" => "Effacer les règles", - "Clustered Column" => "Histogramme groupé", - "Line" => "Courbe", - "Pie" => "Secteurs", - "Bar" => "Barres", - "Scatter" => "Nuage de points", - "Recommended Charts" => "Graphiques recommandés", - "% Total" => "% du total", - "Running Total" => "Total cumulé", - "By Column" => "Par colonne", - "By Row" => "Par ligne", - "Column" => "Colonne", - "Win/Loss" => "Gain/perte", - "Green Data Bars" => "Barres de données vertes", - "Blue-White-Red Scale" => "Échelle bleu-blanc-rouge", - "White-Green Scale" => "Échelle blanc-vert", - "Duplicate Values" => "Valeurs en double", "Insert Sheet" => "Insérer une feuille", "Rename" => "Renommer", "Move or Copy…" => "Déplacer ou copier…", diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index a26845dea1..f5d9baa2ac 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1034,26 +1034,6 @@ pub(super) const DIALOGS: &[(&str, &str)] = &[ ("Tab Color", "シートの見出しの色"), ("Unhide…", "再表示…"), ("Unprotect Sheet…", "シート保護の解除…"), - ("Quick Analysis (Ctrl+Q)", "クイック分析 (Ctrl+Q)"), - ("Formatting", "書式設定"), - ("Charts", "グラフ"), - ("Totals", "集計"), - ("Tables", "テーブル"), - ("Color Scale", "カラー スケール"), - ("Icon Set", "アイコン セット"), - ("Greater Than…", "指定の値より大きい…"), - ("Clear Rules", "ルールのクリア"), - ("Bar", "横棒"), - ("% Total", "合計に対する割合"), - ("Running Total", "累計"), - ("By Column", "列ごと"), - ("By Row", "行ごと"), - ("Column", "縦棒"), - ("Win/Loss", "勝敗"), - ("Green Data Bars", "緑のデータ バー"), - ("Blue-White-Red Scale", "青-白-赤のスケール"), - ("White-Green Scale", "白-緑のスケール"), - ("Duplicate Values", "重複する値"), ("Collapse dialog", "ダイアログを折りたたむ"), ("Expand dialog", "ダイアログを展開する"), ("Numerical Count", "数値の個数"), @@ -1203,6 +1183,7 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ ("Theme Colors", "テーマの色"), ("Standard Colors", "標準の色"), ("Highlight Cells Rules", "セルの強調表示ルール"), + ("Greater Than…", "指定の値より大きい…"), ("Less Than…", "指定の値より小さい…"), ("Between…", "指定の範囲内…"), ("Equal To…", "指定の値に等しい…"), @@ -1229,6 +1210,7 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ ("5 Arrows", "5 つの矢印"), ("5 Quarters", "5 つの四分円"), ("New Rule…", "新しいルール…"), + ("Clear Rules", "ルールのクリア"), ("Manage Rules…", "ルールの管理…"), ("Good, Bad and Neutral", "良い、悪い、どちらでもない"), ("Bad", "悪い"), @@ -1261,6 +1243,8 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ ("Oval", "楕円"), ("Triangle", "三角形"), ("Arrow", "矢印"), + ("Column", "縦棒"), + ("Win/Loss", "勝敗"), ("Type to filter…", "入力して絞り込み…"), ("Sort Ascending", "昇順"), ("Sort Descending", "降順"), @@ -1299,6 +1283,7 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ ("Treemap", "ツリーマップ"), ("Sunburst", "サンバースト"), ("Stock", "株価"), + ("Bar", "横棒"), ( "Drag to fill cells. Drag from inside a cell to select a range.", "ドラッグしてセルをオートフィルします。セルの内側からドラッグすると範囲を選択します。", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index b7f1e8cc49..880f97ac84 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -462,31 +462,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Maximum Iterations must be a whole number from 1 to 32767." => "최대 반복 횟수는 1에서 32767 사이의 정수여야 합니다.", "Maximum Change must be a number of 0 or more." => "변화 한도는 0 이상의 숫자여야 합니다.", "Calculation settings are saved with the workbook." => "계산 설정은 통합 문서와 함께 저장됩니다.", - "Quick Analysis (Ctrl+Q)" => "빠른 분석 (Ctrl+Q)", - "Formatting" => "서식", - "Charts" => "차트", - "Totals" => "합계", - "Tables" => "표", - "Color Scale" => "색 구성표", - "Icon Set" => "아이콘 집합", - "Greater Than…" => "보다 큼…", - "Clear Rules" => "규칙 지우기", - "Clustered Column" => "묶은 세로 막대형", - "Line" => "꺾은선형", - "Pie" => "원형", - "Bar" => "가로 막대형", - "Scatter" => "분산형", - "Recommended Charts" => "추천 차트", - "% Total" => "총합계 비율", - "Running Total" => "누계", - "By Column" => "열 기준", - "By Row" => "행 기준", - "Column" => "열", - "Win/Loss" => "이익/손실", - "Green Data Bars" => "녹색 데이터 막대", - "Blue-White-Red Scale" => "파랑-흰색-빨강 눈금", - "White-Green Scale" => "흰색-녹색 눈금", - "Duplicate Values" => "중복 값", "Insert Sheet" => "시트 삽입", "Rename" => "이름 바꾸기", "Move or Copy…" => "이동 또는 복사…", diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 651b6fbec7..168450222f 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -1020,26 +1020,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Protect\nSheet" => "Proteger\nPlanilha", "Watch\nWindow" => "Janela de\nInspeção", "Workbook\nStatistics" => "Estatísticas da\nPasta de Trabalho", - "Quick Analysis (Ctrl+Q)" => "Análise rápida (Ctrl+Q)", - "Formatting" => "Formatação", - "Charts" => "Gráficos", - "Totals" => "Totais", - "Tables" => "Tabelas", - "Color Scale" => "Escala de cor", - "Icon Set" => "Conjunto de ícones", - "Greater Than…" => "Maior que…", - "Clear Rules" => "Limpar regras", - "Bar" => "Barras", - "% Total" => "% do total", - "Running Total" => "Total acumulado", - "By Column" => "Por coluna", - "By Row" => "Por linha", - "Column" => "Coluna", - "Win/Loss" => "Ganho/perda", - "Green Data Bars" => "Barras de dados verdes", - "Blue-White-Red Scale" => "Escala azul-branco-vermelho", - "White-Green Scale" => "Escala branco-verde", - "Duplicate Values" => "Valores duplicados", "Rename" => "Renomear", "Move or Copy…" => "Mover ou copiar…", "Duplicate" => "Duplicar", diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 7fcd028972..e2fd2ef3e9 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -461,26 +461,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Maximum Iterations must be a whole number from 1 to 32767." => "Предельное число итераций должно быть целым числом от 1 до 32767.", "Maximum Change must be a number of 0 or more." => "Максимальное изменение должно быть числом не меньше 0.", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", - "Quick Analysis (Ctrl+Q)" => "Быстрый анализ (Ctrl+Q)", - "Formatting" => "Форматирование", - "Charts" => "Диаграммы", - "Totals" => "Итоги", - "Tables" => "Таблицы", - "Color Scale" => "Цветовая шкала", - "Icon Set" => "Набор значков", - "Greater Than…" => "Больше…", - "Clear Rules" => "Удалить правила", - "Bar" => "Линейчатая", - "% Total" => "% от итога", - "Running Total" => "Нарастающий итог", - "By Column" => "По столбцам", - "By Row" => "По строкам", - "Column" => "Столбец", - "Win/Loss" => "Выигрыш/проигрыш", - "Green Data Bars" => "Зелёные гистограммы", - "Blue-White-Red Scale" => "Шкала сине-бело-красная", - "White-Green Scale" => "Шкала бело-зелёная", - "Duplicate Values" => "Повторяющиеся значения", " (password)" => " (пароль)", " (password, unlocked)" => " (пароль, разблокировано)", "$ English (United States)" => "$ английский (США)", diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index e4dc96b824..4b65ab8be3 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -451,31 +451,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Bottom Margin" => "Donja margina", "Header Margin" => "Margina zaglavlja", "Footer Margin" => "Margina podnožja", - "Quick Analysis (Ctrl+Q)" => "Brza analiza (Ctrl+Q)", - "Formatting" => "Formatiranje", - "Charts" => "Grafikoni", - "Totals" => "Ukupne vrednosti", - "Tables" => "Tabele", - "Color Scale" => "Skala boja", - "Icon Set" => "Skup ikona", - "Greater Than…" => "Veće od…", - "Clear Rules" => "Obriši pravila", - "Clustered Column" => "Grupisani stubičasti", - "Line" => "Linijski", - "Pie" => "Kružni", - "Bar" => "Trakasti", - "Scatter" => "Tačkasti", - "Recommended Charts" => "Preporučeni grafikoni", - "% Total" => "% od ukupnog", - "Running Total" => "Tekući zbir", - "By Column" => "Po kolonama", - "By Row" => "Po redovima", - "Column" => "Kolona", - "Win/Loss" => "Dobitak/gubitak", - "Green Data Bars" => "Zelene trake podataka", - "Blue-White-Red Scale" => "Skala plavo-belo-crveno", - "White-Green Scale" => "Skala belo-zeleno", - "Duplicate Values" => "Duplirane vrednosti", "Insert Sheet" => "Убаци лист", "Rename" => "Преименуј", "Move or Copy…" => "Премести или копирај…", diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index e7385cef69..b57d3292df 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -454,31 +454,6 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Maximum Iterations must be a whole number from 1 to 32767." => "最多迭代次数必须是 1 到 32767 之间的整数。", "Maximum Change must be a number of 0 or more." => "最大误差必须是大于或等于 0 的数字。", "Calculation settings are saved with the workbook." => "计算设置随工作簿一起保存。", - "Quick Analysis (Ctrl+Q)" => "快速分析 (Ctrl+Q)", - "Formatting" => "格式化", - "Charts" => "图表", - "Totals" => "汇总", - "Tables" => "表", - "Color Scale" => "色阶", - "Icon Set" => "图标集", - "Greater Than…" => "大于…", - "Clear Rules" => "清除规则", - "Clustered Column" => "簇状柱形图", - "Line" => "折线图", - "Pie" => "饼图", - "Bar" => "条形图", - "Scatter" => "散点图", - "Recommended Charts" => "推荐的图表", - "% Total" => "占总计的百分比", - "Running Total" => "累计", - "By Column" => "按列", - "By Row" => "按行", - "Column" => "柱形", - "Win/Loss" => "盈亏", - "Green Data Bars" => "绿色数据条", - "Blue-White-Red Scale" => "蓝-白-红色阶", - "White-Green Scale" => "白-绿色阶", - "Duplicate Values" => "重复值", "Insert Sheet" => "插入工作表", "Rename" => "重命名", "Move or Copy…" => "移动或复制…", From e9449b55ab3d2db562282de8312294a1b61f0814 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 19:09:50 +0100 Subject: [PATCH 192/201] Read the frame ink of equations saved before the paragraph carried it An older writer put the frame's ink on every Office Math run and wrote no fill on the paragraph end. With a colour command in the source, such an equation now reads that shared run colour instead of Automatic. --- crates/xlsx/src/drawing.rs | 32 +++++++++++++++++++++++-- crates/xlsx/src/tests/equation_tests.rs | 20 ++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index 96ccc0ad7c..474b210f47 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -337,7 +337,8 @@ fn described_source(descr: &str) -> Option<(&str, &str)> { /// stands in, as do the runs of a body without Office Math (one colour throughout: the plain-text /// box of an equation outside the subset). The runs of GridCraft's own Office Math cannot stand /// in when the source colours some of them (`{\color{green}a}+d` would read back green), so such -/// a source with no saved ink reads as Automatic. +/// a source with no saved ink reads as Automatic, unless every run carries the same colour: that +/// is how earlier versions saved an explicit ink (on each run, with no paragraph-end fill). fn equation_ink(tb: Option<&El>, source: &str, own: bool, has_math: bool) -> Color { let Some(tb) = tb else { return Color::default() }; if own && has_math { @@ -345,12 +346,39 @@ fn equation_ink(tb: Option<&El>, source: &str, own: bool, has_math: bool) -> Col return c; } if source.contains("\\color") || source.contains("\\textcolor") { - return Color::default(); + return uniform_run_color(tb).unwrap_or_default(); } } first_run_color(tb, 0).unwrap_or_default() } +/// The colour every run under `e` carries, or `None` when there is no run, a run has no fill or +/// the runs differ. +fn uniform_run_color(e: &El) -> Option { + let mut found: Option = None; + let mut mixed = false; + collect_run_colors(e, 0, &mut found, &mut mixed); + if mixed { None } else { found } +} + +fn collect_run_colors(e: &El, depth: usize, found: &mut Option, mixed: &mut bool) { + if depth > 12 || *mixed { + return; + } + if e.name == "rPr" { + match (e.child("solidFill").and_then(dml_color), *found) { + (None, _) => *mixed = true, + (Some(c), None) => *found = Some(c), + (Some(c), Some(f)) if c != f => *mixed = true, + _ => {} + } + return; + } + for c in &e.children { + collect_run_colors(c, depth + 1, found, mixed); + } +} + /// The colour of the first run (DrawingML `rPr` with a fill) under `e`. fn first_run_color(e: &El, depth: usize) -> Option { if depth > 12 { diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index a2110cac4b..800a84bd1f 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -581,6 +581,26 @@ fn nested_colours_keep_the_frame_ink_through_save_and_reopen() { } } +#[test] +fn a_workbook_saved_before_the_paragraph_carried_the_ink_keeps_its_explicit_frame_ink() { + // The earlier writer put the frame's ink on every Office Math run and wrote no fill on the + // paragraph end: strip that fill from a saved equation to get the same bytes. + let src = "{\\color{green}a+{\\color{black}b}+c}+d"; + let wb = book(vec![equation(1, "B2", src, Color::Rgb(0x1F4E79))]); + let mut parts = unzip(&write_xlsx(&wb).unwrap()); + let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); + let d = drawing(&parts); + let at = d.find("').unwrap() + at + 1; + let close = d[open_end..].find("").unwrap() + open_end; + assert!(d[open_end..close].contains("1F4E79"), "the paragraph end carries the ink: {d}"); + let legacy = format!("{}{}", &d[..open_end], &d[close..]); + assert!(legacy.matches("1F4E79").count() > 1, "every run still carries the ink"); + parts.insert(name, legacy.into_bytes()); + let s = shapes(&read_xlsx(&rezip(&parts)).unwrap().0); + assert_eq!((s.len(), s[0].kind, s[0].text.as_str(), s[0].line), (1, ShapeKind::Equation, src, Color::Rgb(0x1F4E79))); +} + #[test] fn the_plain_text_stand_in_for_an_equation_is_drawn_at_a_normal_size() { // A source Office Math cannot hold is saved as the text box alone; a source it can hold has From 966c634b1cc0ee99f55f219cf7e707bbdd262ce9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 19:15:01 +0000 Subject: [PATCH 193/201] Repin craft-libs to storytold next 8fa4db64a9 and egui to b9770908e --- Cargo.lock | 126 +++++++++++++++++----------------- Cargo.toml | 70 +++++++++---------- apps/gridcraft-web/Cargo.toml | 4 +- crates/ui-egui/Cargo.toml | 2 +- 4 files changed, 101 insertions(+), 101 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 890550d893..505d605cc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1034,7 +1034,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "block2 0.6.2", "objc2-app-kit 0.3.2", @@ -1044,7 +1044,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "rustix 1.1.6", ] @@ -1052,7 +1052,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1070,12 +1070,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "egui", ] @@ -1083,12 +1083,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "thiserror 2.0.21", ] @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde", ] @@ -1104,7 +1104,7 @@ dependencies = [ [[package]] name = "craft-drawingml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "chrono", "craft-xml", @@ -1116,7 +1116,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "harfrust 0.13.3", "kurbo", @@ -1130,12 +1130,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" [[package]] name = "craft-gridcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde", "serde_json", @@ -1145,7 +1145,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1158,7 +1158,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "chrono", "fixed_decimal", @@ -1186,7 +1186,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-host", "craft-i18n", @@ -1201,7 +1201,7 @@ dependencies = [ [[package]] name = "craft-math" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-xml", "roxmltree", @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "craft-mcp-server" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde_json", ] @@ -1219,7 +1219,7 @@ dependencies = [ [[package]] name = "craft-odf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "aes", "base64 0.23.1", @@ -1237,7 +1237,7 @@ dependencies = [ [[package]] name = "craft-ods" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-odf", "craft-sheet", @@ -1248,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "aes", "base64 0.23.1", @@ -1265,7 +1265,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-xml", "craft-zip", @@ -1276,7 +1276,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "serde", ] @@ -1284,7 +1284,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "async-channel", "async-io", @@ -1315,7 +1315,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-host", @@ -1339,7 +1339,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "dispatch2", "objc2 0.6.5", @@ -1351,7 +1351,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-atomic", "craft-host", @@ -1368,12 +1368,12 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "fax", "hayro-ccitt", @@ -1384,7 +1384,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-xml", "flate2", @@ -1401,7 +1401,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -1416,12 +1416,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-i18n", @@ -1451,7 +1451,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "accesskit", "craft-behavior", @@ -1489,7 +1489,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -1500,7 +1500,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-host", @@ -1518,7 +1518,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-host", @@ -1539,7 +1539,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-host", @@ -1559,7 +1559,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-behavior", "craft-host", @@ -1578,7 +1578,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "chrono", "craft-host", @@ -1607,7 +1607,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "js-sys", "serde_json", @@ -1618,7 +1618,7 @@ dependencies = [ [[package]] name = "craft-web-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-host", "craft-platform", @@ -1630,7 +1630,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "winsafe", ] @@ -1638,7 +1638,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-appkit", "craft-atomic", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-cfb", "craft-sheet", @@ -1683,7 +1683,7 @@ dependencies = [ [[package]] name = "craft-xlsx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "craft-drawingml", "craft-opc", @@ -1695,7 +1695,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1705,7 +1705,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2033,7 +2033,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "emath", @@ -2042,7 +2042,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -2077,7 +2077,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit", "ahash", @@ -2096,7 +2096,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -2115,7 +2115,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "accesskit_winit", "arboard", @@ -2140,7 +2140,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "egui", @@ -2153,7 +2153,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", "egui", @@ -2166,7 +2166,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "dify", "eframe", @@ -2192,7 +2192,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "bytemuck", ] @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" dependencies = [ "ahash", "bytemuck", @@ -2299,7 +2299,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[package]] name = "equivalent" @@ -3211,7 +3211,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=aa401985dd4658cdaa272fdccafdcd6e7f4dd60b#aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" +source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21" dependencies = [ "hayro-ccitt", ] @@ -8605,14 +8605,14 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec" +source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564" diff --git a/Cargo.toml b/Cargo.toml index 5c72248170..2e19c125cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,29 +30,29 @@ gridcraft-math = { path = "crates/math" } # ui-egui, craft-print in the app, craft-web-api and craft-web-host in the web app) comes from one # craft-libs revision. # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "=0.1.0", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0", features = ["ui"] } # PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers. -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0", default-features = false } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0", default-features = false } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # OPC zip packages (parts, relationships, the zip writer) under `crates/xlsx/src/package.rs`. -craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. -craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-math = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. -craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. # SpreadsheetML worksheet/drawing/string/package XML; workbook model mapping stays in gridcraft-xlsx. -craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "=0.1.0" } +craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" } # foundation thiserror = "2" @@ -92,15 +92,15 @@ skrifa = { version = "0.44", default-features = false, features = ["std"] } epaint_default_fonts = "0.37" # One native window per workbook: the window list, Window menu titles and the immediate-viewport # driver. Same craft-libs revision as craft-update above. -craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", default-features = false, features = ["ui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["ui"] } # The UI runtime GridCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`): who the app is # to the framework's dialogs, the runtime's key bindings, the theme mode, window placement and the # printer controls. Same craft-libs revision as above. -craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } -craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } -craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } -craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } -craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", features = ["ui"] } +craft-behavior = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +craft-print = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] } [workspace.lints.rust] unsafe_code = "forbid" @@ -128,18 +128,18 @@ debug = 0 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/apps/gridcraft-web/Cargo.toml b/apps/gridcraft-web/Cargo.toml index db990721c4..2b27a5d932 100644 --- a/apps/gridcraft-web/Cargo.toml +++ b/apps/gridcraft-web/Cargo.toml @@ -18,8 +18,8 @@ gridcraft-engine = { workspace = true } gridcraft-ui-egui = { workspace = true } # The host messages (storytold/craft-libs): one contract and one bridge for the web builds. # The page command API (storytold/craft-libs#413): window.gridcraft over the control channel. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } -craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } +craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" } egui = { workspace = true } log = { workspace = true } serde_json = { workspace = true } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index d20832a04e..1796a8b6d9 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the # one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml). -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "aa401985dd4658cdaa272fdccafdcd6e7f4dd60b" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } craft-behavior = { workspace = true } craft-host = { workspace = true } craft-keymap = { workspace = true } From cfc092212612de09c6d1f672908acde1ad839ee9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 20:34:24 +0100 Subject: [PATCH 194/201] Skip Office Math run styles when reading the legacy frame ink The earlier writer saved a style-only m:rPr beside the a:rPr that carries the fill on styled runs. The legacy ink check counted it as a run without a fill and read Automatic. --- crates/xlsx/src/drawing.rs | 12 ++++++++++++ crates/xlsx/src/tests/equation_tests.rs | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/xlsx/src/drawing.rs b/crates/xlsx/src/drawing.rs index 474b210f47..c0de11df20 100644 --- a/crates/xlsx/src/drawing.rs +++ b/crates/xlsx/src/drawing.rs @@ -366,6 +366,11 @@ fn collect_run_colors(e: &El, depth: usize, found: &mut Option, mixed: &m return; } if e.name == "rPr" { + // Office Math's own run style (`m:rPr`: bold, plain, script) sits beside the DrawingML one + // that carries the fill, and the parser drops the prefix that tells them apart + if is_math_run_style(e) { + return; + } match (e.child("solidFill").and_then(dml_color), *found) { (None, _) => *mixed = true, (Some(c), None) => *found = Some(c), @@ -379,6 +384,13 @@ fn collect_run_colors(e: &El, depth: usize, found: &mut Option, mixed: &m } } +/// Whether `e` is an Office Math `m:rPr` (only style children such as `m:sty`), not the DrawingML +/// `a:rPr` of the run, which holds the fill and the font. +fn is_math_run_style(e: &El) -> bool { + const MATH_STYLE: [&str; 6] = ["nor", "sty", "scr", "lit", "aln", "brk"]; + !e.children.is_empty() && e.children.iter().all(|c| MATH_STYLE.contains(&c.name.as_str())) +} + /// The colour of the first run (DrawingML `rPr` with a fill) under `e`. fn first_run_color(e: &El, depth: usize) -> Option { if depth > 12 { diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index 800a84bd1f..262b77c441 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -584,12 +584,14 @@ fn nested_colours_keep_the_frame_ink_through_save_and_reopen() { #[test] fn a_workbook_saved_before_the_paragraph_carried_the_ink_keeps_its_explicit_frame_ink() { // The earlier writer put the frame's ink on every Office Math run and wrote no fill on the - // paragraph end: strip that fill from a saved equation to get the same bytes. - let src = "{\\color{green}a+{\\color{black}b}+c}+d"; + // paragraph end: strip that fill from a saved equation to get the same bytes. The styled + // runs (`\\mathbf`, `\\text`) also carry an `m:rPr` of Office Math style beside the `a:rPr`. + let src = "{\\color{green}a+{\\color{black}\\mathbf{b}}+\\text{c}}+d"; let wb = book(vec![equation(1, "B2", src, Color::Rgb(0x1F4E79))]); let mut parts = unzip(&write_xlsx(&wb).unwrap()); let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); let d = drawing(&parts); + assert!(d.contains("').unwrap() + at + 1; let close = d[open_end..].find("").unwrap() + open_end; From 8bbc760f5dcdaebccce31d8522c25645c025c2cf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 20:38:25 +0100 Subject: [PATCH 195/201] Quick Analysis: name the launcher and tiles as buttons and show keyboard focus The launcher and every tile now expose a button role with their translated label (the launcher also its open state). The popup hands the keyboard to its first tile, arrows move the focus between tiles, Enter or Space runs one, and the focused control gets a visible ring. Ctrl+Q closes the popup while a tile has the keyboard. --- crates/ui-egui/src/quick_analysis.rs | 63 ++++++++++++++++--- .../ui-egui/tests/it/quick_analysis_button.rs | 54 ++++++++++++++++ 2 files changed, 109 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index f7db7b5697..66f5fb2e89 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -49,6 +49,8 @@ pub struct State { pub tab: Tab, /// Totals by row (results to the right) instead of by column (results below). pub by_rows: bool, + /// The popup just opened: its first tile takes the keyboard focus so arrows, Enter and Space work. + focus_first_tile: bool, } /// What a tile does. @@ -153,6 +155,7 @@ pub fn toggle(app: &mut SheetApp, on: Option) -> Result { return Err("Select at least two cells to use Quick Analysis.".into()); } else { app.grid.quick_analysis.open = Some((sheet, sel)); + app.grid.quick_analysis.focus_first_tile = true; } Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) } @@ -208,8 +211,11 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { // Right after a fill-handle drag the Auto Fill Options button sits at the same corner; it wins // until that fill is no longer current (Ctrl+Q still opens the popup). let fill_tag = app.grid.fill_tag.is_some(); + // Whether the launcher or a popup control has the keyboard, so the grid reads no keys this frame. + let mut keyboard_in_popup = false; if corner_visible && (open || (!busy && !fill_tag)) { let mut clicked = false; + let mut focused = false; egui::Area::new(Id::unique("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click()); let fill = if resp.is_pointer_button_down_on() || open { @@ -222,8 +228,13 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { ui.painter().rect_filled(r, 4.0, fill); ui.painter().rect_stroke(r, 4.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), Icon::QuickAnalysis, t.accent); - clicked = resp.on_hover_text(lang.tr("Quick Analysis (Ctrl+Q)")).clicked(); + paint_focus_ring(ui, &t, r, &resp); + let name = lang.tr("Quick Analysis (Ctrl+Q)"); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, open, name)); + focused = resp.has_focus(); + clicked = resp.on_hover_text(name).clicked(); }); + keyboard_in_popup = focused; if clicked { let _ = toggle(app, None); } @@ -231,12 +242,16 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let Some((_, opened_for)) = app.grid.quick_analysis.open else { return }; let pos = pos2(button.left(), button.bottom() + 4.0); let mut picked: Option = None; + // The frame that opened the popup (Ctrl+Q is still in the input) must not close it again. + let just_opened = app.grid.quick_analysis.focus_first_tile; let resp = egui::Area::new(Id::unique("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { egui::Frame::popup(ui.style()).show(ui, |ui| { let state = &mut app.grid.quick_analysis; ui.horizontal(|ui| { for tab in Tab::ALL { - if ui.selectable_label(state.tab == tab, lang.tr(tab.label())).clicked() { + let tab_button = ui.selectable_label(state.tab == tab, lang.tr(tab.label())); + keyboard_in_popup |= tab_button.has_focus(); + if tab_button.clicked() { state.tab = tab; } } @@ -244,16 +259,17 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { ui.separator(); if state.tab == Tab::Totals { ui.horizontal(|ui| { - ui.selectable_value(&mut state.by_rows, false, lang.tr("By Column")); - ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")); + keyboard_in_popup |= ui.selectable_value(&mut state.by_rows, false, lang.tr("By Column")).has_focus(); + keyboard_in_popup |= ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")).has_focus(); }); } let items = tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows); + let mut take_focus = std::mem::take(&mut state.focus_first_tile); for row in items.chunks(6) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 2.0; for item in row { - if paint_tile(ui, &t, item, lang.tr(item.label)) { + if paint_tile(ui, &t, item, lang.tr(item.label), std::mem::take(&mut take_focus), &mut keyboard_in_popup) { picked = Some(item.action.clone()); } } @@ -269,14 +285,43 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { Action::Run(id, params) => app.run_or_alert(id, params), Action::Dialog(name, params) => app.open_dialog(name, params), } - } else if outside_click || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + } else if outside_click + || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + || (keyboard_in_popup && !just_opened && toggle_key_pressed(&ctx)) + { app.grid.quick_analysis.open = None; } } -/// One option of the popup: a small picture over a wrapped label. True when clicked. -fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { +/// Ctrl+Q (Control+Q on a Mac, where Command+Q stays Quit) while a tile has the keyboard: the grid +/// no longer reads keys then, so the popup closes itself on the key that opened it. +fn toggle_key_pressed(ctx: &egui::Context) -> bool { + ctx.input_mut(|i| { + let pressed = |e: &egui::Event| { + matches!(e, egui::Event::Key { key: egui::Key::Q, pressed: true, modifiers: m, .. } if m.ctrl && !m.shift && !m.alt && !m.mac_cmd) + }; + let Some(at) = i.events.iter().position(pressed) else { return false }; + + i.events.remove(at); + true + }) +} + +/// A visible ring around a control that has the keyboard focus. +fn paint_focus_ring(ui: &Ui, t: &Tokens, rect: Rect, resp: &egui::Response) { + if resp.has_focus() { + ui.painter().rect_stroke(rect.expand(1.0), 5.0, Stroke::new(2.0, t.sheet_focus), StrokeKind::Outside); + } +} + +/// One option of the popup: a small picture over a wrapped label, a button named by that label. +/// `take_focus` gives it the keyboard focus. True when clicked. +fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str, take_focus: bool, has_keyboard: &mut bool) -> bool { let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click()); + if take_focus { + resp.request_focus(); + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if resp.is_pointer_button_down_on() { ui.painter().rect_filled(rect, 4.0, t.pressed); } else if resp.hovered() { @@ -287,6 +332,8 @@ fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0); let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0); ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())).galley(at, galley, t.text); + paint_focus_ring(ui, t, rect, &resp); + *has_keyboard |= resp.has_focus(); resp.clicked() } diff --git a/crates/ui-egui/tests/it/quick_analysis_button.rs b/crates/ui-egui/tests/it/quick_analysis_button.rs index 9a5e1f2b14..e8ff38782f 100644 --- a/crates/ui-egui/tests/it/quick_analysis_button.rs +++ b/crates/ui-egui/tests/it/quick_analysis_button.rs @@ -134,3 +134,57 @@ fn escape_closes_the_popup_without_cancelling_the_pending_copy() { esc(&mut h); assert!(h.state().session.clipboard.is_none(), "a second Esc, with no popup, cancels the copy as before"); } + +/// The launcher and the tiles are named buttons. The popup hands the keyboard to its first tile, +/// an arrow moves the focus to the next one and Enter runs it. +#[test] +fn launcher_and_tiles_are_named_buttons_that_work_by_keyboard() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable as _; + let mut session = crate::support::blank_session(); + session.execute("range.setValues", json!({"range": "A1", "values": [[1, 2, 3], [4, 5, 6]]})).unwrap(); + session.execute("selection.set", json!({"range": "A1:C2"})).unwrap(); + let mut h = crate::support::harness(session, 4); + h.get_by_role_and_label(Role::Button, "Quick Analysis (Ctrl+Q)"); + + toggle(h.state_mut(), Some(true)).unwrap(); + h.run_steps(3); + assert!(h.get_by_role_and_label(Role::Button, "Data Bars").is_focused(), "the first tile takes the focus"); + h.get_by_role_and_label(Role::Button, "Clear Rules"); + + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + assert!(h.get_by_role_and_label(Role::Button, "Color Scale").is_focused(), "an arrow moves the focus to the next tile"); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(h.state().grid.quick_analysis.open.is_none(), "the chosen tile closes the popup"); + let sheet = h.state().session.active().unwrap().wb.active().unwrap(); + assert_eq!(sheet.cond_formats.len(), 1, "and its color scale is applied"); +} + +/// Whether a frame of the launcher and popup draws the focus ring colour as a stroke. +fn draws_focus_ring(app: &mut SheetApp, frames: usize) -> bool { + let sh = app.session.active().unwrap().wb.active().unwrap().clone(); + let g = Geo::new(&sh, Rect::from_min_max(pos2(0.0, 0.0), pos2(1200.0, 800.0)), Vec2::ZERO); + let ctx = egui::Context::default(); + // No fade-in, so the colours are the theme's own. + ctx.global_style_mut(|style| style.animation_time = 0.0); + let ring = gridcraft_ui_egui::theme::Tokens::get(&ctx).sheet_focus; + let mut seen = false; + for _ in 0..frames { + let out = ctx.run_ui(egui::RawInput::default(), |ui| gridcraft_ui_egui::quick_analysis::show(app, ui, &g, &sh)); + seen = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == ring)); + out.drop_without_applying_deltas(); + } + seen +} + +/// The focused tile shows a ring, so a keyboard user can see where they are. +#[test] +fn the_focused_tile_shows_a_visible_focus_ring() { + let mut app = app(); + app.run("selection.set", json!({"range": "B2:D5"})).unwrap(); + assert!(!draws_focus_ring(&mut app, 3), "no ring while the popup is closed"); + toggle(&mut app, Some(true)).unwrap(); + assert!(draws_focus_ring(&mut app, 3), "the first tile has the focus and a ring"); +} From 731c90dcc13b47b81e52830686dfc5e5f87b3ef1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 20:52:50 +0100 Subject: [PATCH 196/201] Quick Analysis: use a focus ring colour that meets 3:1 on the popup in both themes The sheet's green focus colour is only 2.5:1 on the dark popup (1.9:1 on a hovered tile). Tiles now ring with the theme accent (3.9:1 or more on the popup, hover and pressed fills in light and dark); the launcher sits on the sheet and keeps the sheet's focus colour. The contrast test covers the popup pairs. --- crates/ui-egui/src/quick_analysis.rs | 11 ++++++----- crates/ui-egui/src/theme.rs | 9 +++++++++ crates/ui-egui/tests/it/quick_analysis_button.rs | 6 +++--- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 66f5fb2e89..50cd7fcb7a 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -228,7 +228,8 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { ui.painter().rect_filled(r, 4.0, fill); ui.painter().rect_stroke(r, 4.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), Icon::QuickAnalysis, t.accent); - paint_focus_ring(ui, &t, r, &resp); + // The launcher sits on the sheet, so its ring is the sheet's focus colour + paint_focus_ring(ui, t.sheet_focus, r, &resp); let name = lang.tr("Quick Analysis (Ctrl+Q)"); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, open, name)); focused = resp.has_focus(); @@ -307,10 +308,10 @@ fn toggle_key_pressed(ctx: &egui::Context) -> bool { }) } -/// A visible ring around a control that has the keyboard focus. -fn paint_focus_ring(ui: &Ui, t: &Tokens, rect: Rect, resp: &egui::Response) { +/// A visible ring in `color` around a control that has the keyboard focus. +fn paint_focus_ring(ui: &Ui, color: Color32, rect: Rect, resp: &egui::Response) { if resp.has_focus() { - ui.painter().rect_stroke(rect.expand(1.0), 5.0, Stroke::new(2.0, t.sheet_focus), StrokeKind::Outside); + ui.painter().rect_stroke(rect.expand(1.0), 5.0, Stroke::new(2.0, color), StrokeKind::Outside); } } @@ -332,7 +333,7 @@ fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str, take_focus: boo let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0); let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0); ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())).galley(at, galley, t.text); - paint_focus_ring(ui, t, rect, &resp); + paint_focus_ring(ui, t.popup_focus_ring(), rect, &resp); *has_keyboard |= resp.has_focus(); resp.clicked() } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 9ebf199440..1910a8aa93 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -300,6 +300,12 @@ impl Tokens { if ctx.global_style().visuals.dark_mode { Tokens::dark() } else { Tokens::light() } } + /// The ring around a focused control on a popup or menu surface. The sheet's own focus colour + /// is too dim on the dark popup (2.5:1), so this follows the theme's accent instead. + pub fn popup_focus_ring(&self) -> Color32 { + self.accent + } + /// One colour of the category palette. pub fn cat(&self, c: Cat) -> Color32 { self.cat.get(c as usize).copied().unwrap_or(self.text) @@ -440,6 +446,9 @@ mod contrast_tests { add("slider fill on sheet", t.sheet_fill, t.grid_bg, GLYPH); add("slider fill on track", t.sheet_fill, t.sheet_track, GLYPH); add("control focus ring on sheet", t.sheet_focus, t.grid_bg, GLYPH); + for (name, bg) in [("menu", t.menu_bg), ("hover", t.hover), ("pressed", t.pressed)] { + add(&format!("popup control focus ring on {name}"), t.popup_focus_ring(), bg, GLYPH); + } add("recording dot on ribbon", t.recording, t.ribbon, GLYPH); add("recording dot on status bar", t.recording, t.status_bar, GLYPH); for (name, c) in [ diff --git a/crates/ui-egui/tests/it/quick_analysis_button.rs b/crates/ui-egui/tests/it/quick_analysis_button.rs index e8ff38782f..5d75214f7a 100644 --- a/crates/ui-egui/tests/it/quick_analysis_button.rs +++ b/crates/ui-egui/tests/it/quick_analysis_button.rs @@ -162,18 +162,18 @@ fn launcher_and_tiles_are_named_buttons_that_work_by_keyboard() { assert_eq!(sheet.cond_formats.len(), 1, "and its color scale is applied"); } -/// Whether a frame of the launcher and popup draws the focus ring colour as a stroke. +/// Whether a frame of the launcher and popup draws the popup focus ring (a 2 px stroke). fn draws_focus_ring(app: &mut SheetApp, frames: usize) -> bool { let sh = app.session.active().unwrap().wb.active().unwrap().clone(); let g = Geo::new(&sh, Rect::from_min_max(pos2(0.0, 0.0), pos2(1200.0, 800.0)), Vec2::ZERO); let ctx = egui::Context::default(); // No fade-in, so the colours are the theme's own. ctx.global_style_mut(|style| style.animation_time = 0.0); - let ring = gridcraft_ui_egui::theme::Tokens::get(&ctx).sheet_focus; + let ring = gridcraft_ui_egui::theme::Tokens::get(&ctx).popup_focus_ring(); let mut seen = false; for _ in 0..frames { let out = ctx.run_ui(egui::RawInput::default(), |ui| gridcraft_ui_egui::quick_analysis::show(app, ui, &g, &sh)); - seen = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == ring)); + seen = out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == ring && r.stroke.width == 2.0)); out.drop_without_applying_deltas(); } seen From f96096f97ebfd72a6fd4fa771f7bf05e21274353 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 20:44:58 +0000 Subject: [PATCH 197/201] The print job takes the panel's Collate; tests load their fonts as the app does --- apps/gridcraft/src/print.rs | 1 + crates/ui-egui/tests/common/mod.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/gridcraft/src/print.rs b/apps/gridcraft/src/print.rs index e19988a119..8ea22e4a39 100644 --- a/apps/gridcraft/src/print.rs +++ b/apps/gridcraft/src/print.rs @@ -36,6 +36,7 @@ pub fn submit() -> Submit { _ => None, }, copies: settings.copies.clamp(1, 999), + collate: settings.collate, duplex: settings.duplex.and_then(|value| match value { Duplex::LongEdge => Some(craft_print::Duplex::LongEdge), Duplex::ShortEdge => Some(craft_print::Duplex::ShortEdge), diff --git a/crates/ui-egui/tests/common/mod.rs b/crates/ui-egui/tests/common/mod.rs index f5ea88666c..90fd33be43 100644 --- a/crates/ui-egui/tests/common/mod.rs +++ b/crates/ui-egui/tests/common/mod.rs @@ -19,7 +19,7 @@ pub type Harness = egui_kittest::Harness<'static, SheetApp>; pub fn builder() -> HarnessBuilder { egui_kittest::Harness::builder().with_context_setup(|ctx| { gridcraft_ui_egui::framework::install_headless(ctx); - ctx.set_fonts(gridcraft_ui_egui::theme::pinned_font_definitions()); + craft_ui::fonts::load(ctx, gridcraft_ui_egui::theme::pinned_font_definitions()); gridcraft_ui_egui::theme::apply(ctx, false); }) } From 3a37c2e88295a61e91942ddc0866a28bab02bf5d Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 25 Nov 2026 16:17:18 -0600 Subject: [PATCH 198/201] Use the shared nightly launcher template (#4758) Renders the plain nightly tar's launcher from craft-common-actions' shared template. Independent check: dylanmtaylor compared all 14 app launcher PRs byte for byte with the template rendered from the registry (https://github.com/storytold/craft-common-actions/pull/367#issuecomment-7172085284); this head was re-checked against craft-common-actions main 88148a5. --- docs/nightly-release-preparation.md | 15 ++- packaging/linux/nightly-linux-launch-tests.py | 107 +++++++++++++++--- packaging/linux/nightly-tar-launch.sh | 16 +++ packaging/linux/nightly.sh | 5 +- 4 files changed, 118 insertions(+), 25 deletions(-) create mode 100755 packaging/linux/nightly-tar-launch.sh diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 1517a514ff..1568cfc23d 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -105,21 +105,24 @@ traversing root, a root that resolves through a link into a fenced folder, an in `${XDG_DATA_HOME:-$HOME/.local/share}/gridcraft-nightly/profile`, a sibling of stable's `/gridcraft`, never an ancestor. -**Every Linux format ships a launcher, and each passes an already-supplied profile through.** +**Every Linux format ships a launcher.** The flat nightly tar's `gridcraft` is craft-common-actions' +shared launcher template (`scripts/nightly-launcher.sh.in` from #363, rendered for this app), so it always +supplies its own profile; the packaged formats pass an already-supplied profile through. | Format | Launcher | GUI | Data root | |---|---|---|---| | deb/rpm | `/usr/bin/gridcraft-nightly` | `/usr/lib/gridcraft-nightly/gridcraft` | `/gridcraft-nightly/profile` | | AppImage | `AppRun` (a script) and `usr/bin/gridcraft-nightly` | `usr/bin/gridcraft` | same | -| flat nightly tar | `gridcraft` | `gridcraft-bin` | same | -| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | same | -| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | same | +| flat nightly tar | `gridcraft` (the shared template) | `gridcraft-bin` | `/ai.storyteller.gridcraft.nightly` | +| plain tree tarball | `bin/gridcraft-nightly` | `bin/gridcraft` | `/gridcraft-nightly/profile` | +| Arch handoff | `bin/gridcraft-nightly` | `.gridcraft-nightly/gridcraft` | `/gridcraft-nightly/profile` | | Flatpak bundle | `/app/bin/gridcraft-nightly` | `/app/bin/gridcraft` | the sandbox's own `~/.local/share` | The flat nightly tar uses the kit's standard layout: `` is the launcher people run and `-bin` is the GUI ELF it starts, so the shared Unix verifier can keep requiring `gridcraft` -as the entrypoint. No launcher falls back to a relative or world-writable path for the GUI, and a -candidate that is the launcher itself is never started. +as the entrypoint. That launcher is the shared template: it resolves its own directory once and execs +`gridcraft-bin` with `--launch-profile nightly-v1 --profile-root /ai.storyteller.gridcraft.nightly --` +and the user's arguments, asking a bare `--version`/`-V` in the Launcher's own form. **macOS and Windows.** `GridCraft Nightly.app` (`CFBundleIdentifier ai.storyteller.gridcraft.nightly`, associations removed) is built and verified unsigned on main and diff --git a/packaging/linux/nightly-linux-launch-tests.py b/packaging/linux/nightly-linux-launch-tests.py index dff5ad53f1..06482c808c 100644 --- a/packaging/linux/nightly-linux-launch-tests.py +++ b/packaging/linux/nightly-linux-launch-tests.py @@ -2,10 +2,13 @@ """The Linux launch profile, staged the way each format ships it; no cargo build, no GUI, no network. What is checked, all synthetic: - * `nightly-launch.sh` (the AppImage and tar launcher) passes the flavor's own tokens and nothing else; + * `nightly-tar-launch.sh` (craft-common-actions' rendered template, the plain tar's entrypoint) starts + `-bin` with the template's exact tokens and the channel's own profile root; + * `nightly-launch.sh` (the AppImage and plain-tree launcher) passes the flavor's own tokens; * `package.sh` stages the deb/rpm, AppImage and tar launchers and a nightly desktop entry, and leaves a stable tree exactly as it was. `nfpm`, `appimagetool` and `strip` are stubs on PATH. """ +import hashlib import os from pathlib import Path import shutil @@ -16,9 +19,13 @@ import unittest ROOT = Path(__file__).resolve().parents[2] LAUNCHER = ROOT / "packaging/linux/nightly-launch.sh" +TAR_LAUNCHER = ROOT / "packaging/linux/nightly-tar-launch.sh" PACKAGE = ROOT / "packaging/linux/package.sh" NIGHTLY_VERSION = "0.19.1-nightly.20261124.7.1.gabcdef012345" PROFILE = "gridcraft-nightly/profile" +# The tar launcher is the shared template rendered for this app; these are its bytes. +TAR_PROFILE = "ai.storyteller.gridcraft.nightly" +TAR_LAUNCHER_SHA256 = "da4d5c6187527b57bb3d6b9f2b8791dff71c2f3421a4116cbda3cd3314b54af7" RECORDER = """#!/bin/sh printf '<%s>\\n' "$@" @@ -30,7 +37,7 @@ def run(argv, cwd, env, check=True): class MovedTreeLauncher(unittest.TestCase): - """nightly-launch.sh as AppRun and as an unpacked tar's launcher.""" + """nightly-launch.sh as AppRun and as a plain tree tarball's launcher.""" def setUp(self): self.scratch = tempfile.TemporaryDirectory() @@ -43,13 +50,11 @@ class MovedTreeLauncher(unittest.TestCase): """Each placement puts the GUI and this launcher where its format does. appdir: AppRun at the root, GUI in usr/bin (also usr/bin/gridcraft-nightly). - tar: the kit's flat tar, `gridcraft` launcher beside the `gridcraft-bin` GUI. tree: a plain tree tarball, bin/gridcraft-nightly beside bin/gridcraft. """ tree = self.root / layout binary, launcher_name = { "appdir": (tree / "usr/bin/gridcraft", tree / "AppRun"), - "tar": (tree / "gridcraft-bin", tree / "gridcraft"), "tree": (tree / "bin/gridcraft", tree / "bin/gridcraft-nightly"), }[layout] binary.parent.mkdir(parents=True) @@ -66,7 +71,7 @@ class MovedTreeLauncher(unittest.TestCase): return ["<--launch-profile>", "", "<--profile-root>", f"<{self.data / PROFILE}>", "<-->"] def test_every_layout_starts_the_gui_through_the_launch_profile(self): - for layout in ("appdir", "tar", "tree"): + for layout in ("appdir", "tree"): with self.subTest(layout=layout): launcher = self.install(layout) self.assertEqual(self.query(launcher).stdout.splitlines(), self.tokens()) @@ -92,16 +97,84 @@ class MovedTreeLauncher(unittest.TestCase): self.assertIn("no GridCraft binary", missing.stderr) self.assertFalse(self.data.exists(), "a refused launch creates no data folder") - def test_a_flat_tar_launcher_never_starts_itself(self): - launcher = self.install("tar") - (self.root / "tar/gridcraft-bin").unlink() - refused = run([str(launcher)], cwd=self.root, env=self.env, check=False) - self.assertEqual(refused.returncode, 2) - self.assertIn("no GridCraft binary", refused.stderr) - def test_the_launcher_is_portable_shell(self): - run(["sh", "-n", str(LAUNCHER)], cwd=self.root, env=self.env) - self.assertTrue(LAUNCHER.read_text().startswith("#!/bin/sh\n")) + for launcher in (LAUNCHER, TAR_LAUNCHER): + with self.subTest(launcher=launcher.name): + run(["sh", "-n", str(launcher)], cwd=self.root, env=self.env) + self.assertTrue(launcher.read_text().startswith("#!/bin/sh\n")) + + +class CanonicalTarLauncher(unittest.TestCase): + """The plain nightly tar's entrypoint: the shared template, rendered for GridCraft.""" + + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.data = self.root / "data" + self.home = self.root / "home with space" + self.env = {"PATH": os.environ["PATH"], "XDG_DATA_HOME": str(self.data)} + + def install(self): + """The kit's flat tar: the `gridcraft` launcher beside the `gridcraft-bin` GUI.""" + tree = self.root / "tar" + tree.mkdir() + (tree / "gridcraft-bin").write_text(RECORDER) + (tree / "gridcraft-bin").chmod(0o755) + shutil.copy2(TAR_LAUNCHER, tree / "gridcraft") + (tree / "gridcraft").chmod(0o755) + return tree / "gridcraft" + + def prefix(self, profile_root): + return ["<--launch-profile>", "", "<--profile-root>", f"<{profile_root}>"] + + def tokens(self, profile_root): + return self.prefix(profile_root) + ["<-->"] + + def test_every_argument_follows_the_profile_tokens(self): + launcher = self.install() + self.assertEqual(run([str(launcher)], cwd=self.root, env=self.env).stdout.splitlines(), + self.tokens(self.data / TAR_PROFILE)) + self.assertEqual( + run([str(launcher), "workbook with spaces.xlsx", "--other-name.xlsx"], cwd=self.root, env=self.env).stdout.splitlines(), + self.tokens(self.data / TAR_PROFILE) + ["", "<--other-name.xlsx>"], + ) + + def test_the_profile_root_falls_back_to_the_data_home_under_home(self): + launcher = self.install() + env = {"PATH": os.environ["PATH"], "HOME": str(self.home)} + self.assertEqual(run([str(launcher), "book.xlsx"], cwd=self.root, env=env).stdout.splitlines(), + self.tokens(self.home / ".local/share" / TAR_PROFILE) + [""]) + self.assertFalse(self.home.exists(), "the launcher creates no folder of its own") + + def test_a_version_query_asks_the_gui_in_the_launcher_form(self): + launcher = self.install() + for flag in ("--version", "-V"): + with self.subTest(flag=flag): + self.assertEqual(run([str(launcher), flag], cwd=self.root, env=self.env).stdout.splitlines(), + self.prefix(self.data / TAR_PROFILE) + ["<--version>"]) + + def test_a_launcher_profile_argv_passes_through_unchanged(self): + # The ArtCraft Launcher names its own profile and per-install root; the app validates the pair. + launcher = self.install() + argv = ["--launch-profile", "nightly-v1", "--profile-root", str(self.root / "launcher root"), "--", "book.xlsx"] + self.assertEqual(run([str(launcher), *argv], cwd=self.root, env=self.env).stdout.splitlines(), + [f"<{arg}>" for arg in argv]) + + def test_a_missing_gui_fails_before_anything_runs(self): + launcher = self.install() + (self.root / "tar/gridcraft-bin").unlink() + missing = run([str(launcher), "book.xlsx"], cwd=self.root, env=self.env, check=False) + self.assertNotEqual(missing.returncode, 0) + self.assertEqual(missing.stdout, "") + + def test_the_bytes_are_the_shared_template_rendered_for_gridcraft(self): + data = TAR_LAUNCHER.read_bytes() + self.assertEqual(hashlib.sha256(data).hexdigest(), TAR_LAUNCHER_SHA256, + "the tar launcher must stay byte for byte scripts/nightly-launcher.sh.in rendered for gridcraft") + self.assertIn(b'target="$dir/gridcraft-bin"', data) + self.assertIn(b'/ai.storyteller.gridcraft.nightly"', data) + self.assertNotIn(b"gridcraft-nightly/profile", data, "the profile root is the package identity") class FlatNightlyTar(unittest.TestCase): @@ -110,13 +183,13 @@ class FlatNightlyTar(unittest.TestCase): def test_the_flat_tar_stages_the_kit_layout(self): source = (ROOT / "packaging/linux/nightly.sh").read_text() self.assertIn('cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin"', source, "the GUI is -bin") - self.assertIn('"$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft"', source, "the launcher is ") + self.assertIn('"$ROOT/packaging/linux/nightly-tar-launch.sh" "$STAGE/gridcraft"', source, "the launcher is ") self.assertNotIn('"$STAGE/gridcraft-nightly"', source, "the flat tar's launcher is gridcraft") policy = (ROOT / "packaging/nightly-archive.py").read_text() self.assertIn('{"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"}', policy) self.assertIn('required = {"gridcraft", "gridcraft-bin", "gridcraft-nightly.png"', policy) - launcher = LAUNCHER.read_text() - self.assertIn('"$here/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships") + launcher = TAR_LAUNCHER.read_text() + self.assertIn('target="$dir/gridcraft-bin"', launcher, "the launcher starts the GUI the tar ships") class StagedFormats(unittest.TestCase): diff --git a/packaging/linux/nightly-tar-launch.sh b/packaging/linux/nightly-tar-launch.sh new file mode 100755 index 0000000000..a8465b760a --- /dev/null +++ b/packaging/linux/nightly-tar-launch.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Nightly launcher generated by craft-common-actions scripts/nightly-launcher.sh.in. Do not edit: +# the shared nightly producer accepts this file only byte for byte as rendered for the app. +set -eu +dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd -P) +readonly dir +target="$dir/gridcraft-bin" +readonly target +profile_root="${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller.gridcraft.nightly" +readonly profile_root +case "${1-}" in + # The ArtCraft Launcher passes its own profile and per-install root; the app validates the pair. + --launch-profile) exec "$target" "$@" ;; + --version | -V) exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" --version ;; +esac +exec "$target" --launch-profile nightly-v1 --profile-root "$profile_root" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh index 9839623801..93d49a98fb 100755 --- a/packaging/linux/nightly.sh +++ b/packaging/linux/nightly.sh @@ -20,10 +20,11 @@ STAGE="$NIGHTLY_WORK/stage" mkdir -p "$STAGE" # The kit's tar layout: `gridcraft` is the launcher people run and `gridcraft-bin` is the GUI it # starts. An unpacked archive is isolated too, because the GUI refuses to start without a launch -# profile and the launcher is the only thing that supplies one. +# profile and the launcher is the only thing that supplies one. The launcher is craft-common-actions' +# canonical template rendered for this app (scripts/nightly_app.py launcher), not a local script. cp "$NIGHTLY_GUI" "$STAGE/gridcraft-bin" chmod 755 "$STAGE/gridcraft-bin" -cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/gridcraft" +cp "$ROOT/packaging/linux/nightly-tar-launch.sh" "$STAGE/gridcraft" chmod 755 "$STAGE/gridcraft" # The nightly channel's own icon (deeper field); the archive member name stays as the helper requires. cp "$ROOT/assets/app-icon/gridcraft-nightly.png" "$STAGE/gridcraft-nightly.png" From b1216a17e8f13ba6fab276bcb6dcfec79ba86601 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Wed, 25 Nov 2026 20:44:49 -0600 Subject: [PATCH 199/201] Switch on supervised nightlies on the nightly-signer branch (#4767) Supervised nightly switch-on, merged under Skylar's explicit Nightly 758 override after green CI, CodeRabbit on this head with no open threads, Sonar passing, and an independent adversarial review with no blockers. --- .github/nightly-signing-policy.json | 10 +- .github/workflows/nightly-sign.yml | 17 +- .github/workflows/nightly.yml | 8 +- docs/nightly-release-preparation.md | 55 +++-- packaging/nightly-release-tests.py | 326 +++++++++++++++++++++++++++- 5 files changed, 383 insertions(+), 33 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 02d5129b1c..111e18eb97 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -2,13 +2,13 @@ "schema": "craft-nightly-release-policy/v3", "repository": "storytold/gridcraft", "repository_id": 1408285582, - "producer_workflow_id": null, + "producer_workflow_id": 429713469, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", - "release_branch": "release", + "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", "dylanmtaylor", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 4430db0945..4f7f25a9f8 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -1,7 +1,8 @@ name: GridCraft release-ref nightly signer -# Enabled for supervised manual dispatch on release. Main/release contents must match. -# A reusable callee does not change context; this must be a real top-level release dispatch. +# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever +# fast-forwards to reviewed main commits (never the stable release branch). +# A reusable callee does not change context; this must be a real top-level signer-branch dispatch. on: workflow_dispatch: inputs: @@ -22,21 +23,23 @@ concurrency: jobs: release: - # Actual context guards: official repository, manual dispatch, real release branch. + # Actual context guards: official repository, manual dispatch, real nightly-signer branch. if: >- github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && - github.ref == 'refs/heads/release' && github.ref_type == 'branch' + github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch' permissions: contents: write actions: read checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + app-name: gridcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} # No secrets: inherit or raw platform values in this caller. Only the isolated native - # callee job may bind the existing release environment and export keys in its signing step. + # callee job may bind the release environment and export its keys; that environment must + # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index a201ce8588..0c9439d1fa 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,13 +22,13 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba with: - tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba app-name: gridcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 # One producer run builds every listed platform for one all-or-nothing release. The pin is the - # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the - # Linux/macOS signer (#342). + # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, + # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 1568cfc23d..8a002d820f 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -1,11 +1,11 @@ # Windows, Linux and macOS release-ref nightly: supervised manual go-live **Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the -signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact context guards and run when one of the reviewed manual actors dispatches them. There is no schedule yet. The installed policy [`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy -adapted from `storytold/photocraft#16594`. Once `nightly.yml` lands on `main`, populate -`producer_workflow_id` before promoting the policy to `release`, read with: +adapted from `storytold/photocraft#16594`. `producer_workflow_id` is the registered +`nightly.yml` workflow id, read with: ```bash gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id @@ -14,16 +14,38 @@ gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions -main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded -lineage compares and an issue reread at the end of candidate admission) on top of -[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input -and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed -source availability, not provider, queue, native signing or crypto qualification. +Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions +main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +candidate is admitted on the built commit's own Sonar analysis, not main's latest) after +[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly +registry rows for the 14 apps) and +[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out +of the app's clean-source check, and macOS on `macos-15`), following +[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the +policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the +multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed +registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`) +earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source +availability, not provider, queue, native signing or crypto qualification. +**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` +branch, so nightly signer files never need a stable release sync. The policy's `release_branch` +names it, the signer's guard requires it and its caller passes `app-name`. The branch only +fast-forwards to reviewed main commits, through the nightly-signer settings script's `advance` (no +queued signer run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the +existing `release` environment must admit `nightly-signer` alongside `release` before the first +dispatch (a repository settings change, not a workflow one). Its trust closure is all of `.github/` +and `packaging/`, including `packaging/env.sh`, which `import-cert.sh` sources with the Apple keys. +On that branch only the pinned `nightly-sign.yml` caller may reach an environment: no app workflow +binds one, nothing else calls `nightly-release.yml`, and the only caller of the shared stable +`release.yml` is `release.yml`, whose callee must carry the stable-only environment guard. The +contract tests check the in-repo part on every main PR; the settings scan also resolves the callee. +Stable releases still come only from `refs/heads/release`. History does not carry over a switch +between `release` and `nightly-signer`, so the switch happens before the first publication. + Existing stable workflows are unchanged. **First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a -listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` with that producer run ID and attempt, by a listed manual actor. **Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the @@ -44,13 +66,13 @@ so there is no separate Linux or macOS caller job and the signer caller has no p ## Installed policy values and their sources Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` and -any Sonar debt snapshot) before the policy is promoted to `release`. +any Sonar debt snapshot) before `nightly-signer` is advanced to it. | Field | Value | Source | |---|---|---| | `repository_id` | `1408285582` | `gh api repos/storytold/gridcraft --jq .id` | -| `producer_workflow_id` | `null` (pending `main` registration) | Read with `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id` after `nightly.yml` lands on `main` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `producer_workflow_id` | `429713469` | `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml` (path `.github/workflows/nightly.yml`, state `active`) | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions exact-analysis admission, #371 after #370 and #369, following #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows | Suite stable identities (Windows Authenticode publisher subject, Linux OpenPGP release key fingerprint, macOS Apple Developer ID team `DJ6XS33FX8`) | @@ -63,8 +85,8 @@ any Sonar debt snapshot) before the policy is promoted to `release`. - `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named `GridCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets may be passed or inherited. -- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, - and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, +- `.github/workflows/nightly-sign.yml`: top-level signer registration, enabled for manual dispatch + on `nightly-signer`, which carries a reviewed main commit. It rejects wrong repository/event/actual branch, including same-name tags. Its constant whole-run concurrency (`gridcraft-nightly-release`) is distinct from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no credentials; only the shared callee's sign jobs bind the `release` environment. @@ -82,6 +104,9 @@ any Sonar debt snapshot) before the policy is promoted to `release`. - Manual actors are exactly the reviewed release managers in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty. - Root serialization in `nightly-sign.yml` remains literal (`group: gridcraft-nightly-release`, `cancel-in-progress: false`); it carries no `queue:` key while actionlint 1.7.12 rejects that key, and the value is re-added when the hosted queue is qualified. - Installed policy v3 fields, bounds, platforms, candidate workflows, and Sonar identity match `sonar-project.properties` and the callers. +- The `nightly-signer` trust-closure scan: no app workflow binds `environment:`, only + `nightly-sign.yml` calls `nightly-release.yml` at a 40-hex SHA, and the only caller of the + shared stable `release.yml` is `release.yml`. ## GridCraft's nightly-v1 flavor (the same branch) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index ca9301cbfd..72191664ff 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -6,11 +6,21 @@ import hashlib import json from pathlib import Path import re +import textwrap import unittest ROOT = Path(__file__).resolve().parents[1] INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" +DISPATCHER = ROOT / ".github/workflows/nightly-dispatch.yml" +SIGNER_BRANCH = "nightly-signer" + + +def inline_scripts(path): + """Read literal run blocks, not a substitute for YAML/actionlint validation.""" + return [textwrap.dedent(block) for block in re.findall( + r"^ run: \|\n((?: .*\n|\n)+)", path.read_text(), re.MULTILINE)] + NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") # Each platform's one trust field in policy v3, and the public stable identity it must name. NIGHTLY_TRUST = { @@ -275,7 +285,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.ref_type == 'branch' && (github.event_name == 'schedule' || " "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && " - "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + "github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'", } def test_enabled_jobs_keep_exact_context_guards(self): @@ -347,7 +357,7 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertEqual(set(self.policy), expected) self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") self.assertEqual(self.policy["repository"], "storytold/gridcraft") - self.assertEqual(self.policy["release_branch"], "release") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, "the signer runs on its dedicated branch") self.assertIs(type(self.policy["repository_id"]), int) self.assertGreater(self.policy["repository_id"], 0) # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. @@ -459,6 +469,318 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertIn(item["type"], sonar["issue_types"]) self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + def test_sonar_policy_keeps_the_shared_candidate_contract(self): + """The Sonar shape craft-common-actions' candidate contract() admits, refused here first. + An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both + lists, a missing live gate condition or a widened security bound is refused at admission, so + this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved + vulnerability on main is still refused; accepting the new-code rating only records the + reviewed A threshold instead of demanding a clean rating the live gate does not. + """ + sonar = self.policy["candidate_policy"]["sonar"] + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating", + "new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"} + self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed") + self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"]))) + metrics = {} + for field in ("accepted_conditions", "required_conditions"): + for condition in sonar[field]: + with self.subTest(field=field, metric=condition.get("metric")): + expected = {"metric", "comparator", "error_threshold"} + if field == "accepted_conditions": + expected.add("maximum") + self.assertEqual(set(condition), expected) + self.assertNotIn(condition["metric"], metrics, "one condition per gate metric") + metrics[condition["metric"]] = condition + self.assertIn(condition["comparator"], ("GT", "LT")) + self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + if field != "accepted_conditions": + continue + self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map") + self.assertIn(accepted[condition["metric"]], sonar["issue_types"], + "an accepted failure must lie inside the reviewed issue scope") + self.assertEqual(condition["comparator"], "GT") + self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + maximum = float(condition["maximum"]) + if condition["metric"] in ("security_rating", "new_security_rating"): + self.assertEqual(int(maximum), maximum, "the A..E bound is a whole rating") + self.assertTrue(1 <= maximum <= 5, "the security bound stays A..E") + self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays") + else: + self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt") + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]), + "accepted conditions and reviewed issue types must cover the same scope") + self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once") + + +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif masked is None or flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + # The masked text only proves the shape: a quoted key ("uses", 'environment') keeps + # its identity, so the entries are read from the original mapping text, never ''. + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'}, + "a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"}, + "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self): + entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n') + self.assertEqual(refused, []) + self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity") + self.assertIn((2, "runs-on", "ubuntu-latest", False), entries) + _, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n") + self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"]) + + def test_signer_dispatch_guard_and_policy_name_the_same_branch(self): + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["gridcraft"], "the shared signer needs the reviewed registry app") + # This app ships no completion dispatcher yet: that workflow forwards scheduled producers + # only, and no schedule is approved. Adding it is part of a reviewed cadence change. + self.assertFalse(DISPATCHER.exists(), "a completion dispatcher needs its own reviewed activation") + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + self.assertFalse((ROOT / "docs/nightly-signing-policy.example.json").exists(), + "a policy example must then name the signer branch") if __name__ == "__main__": unittest.main(verbosity=2) From de4e878aa8b558346bce308e5694493d7adb8f81 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 26 Nov 2026 00:41:08 -0600 Subject: [PATCH 200/201] Re-pin nightly callers to craft-common-actions 8389cad8 (signer Windows fix) (#4777) Round-5 re-pin under Skylar's Nightly 891 signer-only roll (route A keeps the one-shared-pin invariant). Moves every nightly pin from craft-common-actions be00e5cc to 8389cad8, which carries the Windows ctime rule that stops the signer refusing a just-written JSON (#375). Only the pins and their docs move; no build or packaging code changes. --- .github/nightly-signing-policy.json | 6 +++--- .github/workflows/nightly-sign.yml | 4 ++-- .github/workflows/nightly.yml | 7 +++---- docs/nightly-release-preparation.md | 17 ++++------------- 4 files changed, 12 insertions(+), 22 deletions(-) diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 111e18eb97..6c59485ccf 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1408285582, "producer_workflow_id": 429713469, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "producer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba", + "signer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 4f7f25a9f8..f263a8ffc3 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a app-name: gridcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 0c9439d1fa..94c3a2f7a1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,13 +22,12 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a with: - tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba + tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a app-name: gridcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 # One producer run builds every listed platform for one all-or-nothing release. The pin is the - # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, - # #369 and #364). + # craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 8a002d820f..94f87ef365 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -14,18 +14,9 @@ gh api repos/storytold/gridcraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions -main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the -candidate is admitted on the built commit's own Sonar analysis, not main's latest) after -[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly -registry rows for the 14 apps) and -[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out -of the app's clean-source check, and macOS on `macos-15`), following -[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the -policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the -multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed -registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`) -earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source +Shared tooling is pinned to `8389cad8b849ea6bdb5e15fbce16772c3457565a`, the craft-common-actions +main commit that merged the signer Windows fix (#375), following the shared work already +reviewed here. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source availability, not provider, queue, native signing or crypto qualification. **Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` branch, so nightly signer files never need a stable release sync. The policy's `release_branch` @@ -72,7 +63,7 @@ any Sonar debt snapshot) before `nightly-signer` is advanced to it. |---|---|---| | `repository_id` | `1408285582` | `gh api repos/storytold/gridcraft --jq .id` | | `producer_workflow_id` | `429713469` | `gh api repos/storytold/gridcraft/actions/workflows/nightly.yml` (path `.github/workflows/nightly.yml`, state `active`) | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions exact-analysis admission, #371 after #370 and #369, following #364) | The callers' pin | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `8389cad8…` (the signer Windows fix (#375)) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows | Suite stable identities (Windows Authenticode publisher subject, Linux OpenPGP release key fingerprint, macOS Apple Developer ID team `DJ6XS33FX8`) | From aab0a9c385ba5ee7e9817680218f2d28b03db046 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 26 Nov 2026 05:30:10 -0600 Subject: [PATCH 201/201] Nightly: open the Launcher's files rather than its `--`, and stop blocking a refused launch on macOS (#4775) Nightly launch fix under Skylar's Exec 454: the Launcher's trailing `--` no longer reaches the file list, and a refused launch no longer blocks on macOS (the reason goes to stderr and the app exits 2). Folds in the review rounds: only options before `--` name the control channel (`-- --control` opens a document), documents keep command-line order across the separator, the launcher fixture takes the platform's absolute profile root, and the fixture is rustfmt-clean. --- apps/gridcraft/src/main.rs | 167 ++++++++++++++++++++++++++++++------- 1 file changed, 138 insertions(+), 29 deletions(-) diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 9da2a92121..049f6b901d 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -268,14 +268,23 @@ fn initialize_nightly_process_identity() -> Result<(), process_identity::Identit ) } -/// Tell a desktop user why a nightly launch was refused. A headless form (`--version` on a runner) -/// never gets here: the version query is answered before this and before any profile work. +/// Whether a refusal may also open a native message box. Standard error always carries the reason; +/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert +/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hung in +/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26). +fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool { + build_flavor::needs_native_error(flavor, desktop_session) && !macos +} + +/// Tell a desktop user why a nightly launch was refused, in a native box where one renders without the +/// app's event loop (Windows, X11/Wayland), and on standard error always. A headless form (`--version` +/// on a runner) never gets here: the version query is answered before this and before any profile work. fn report_launch_profile_error(error: &str) { eprintln!("GridCraft launch profile: {error}"); let desktop_session = cfg!(windows) || cfg!(target_os = "macos") || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); - if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) { if let Err(error) = initialize_nightly_process_identity() { eprintln!("GridCraft launch profile: {error}"); return; @@ -330,6 +339,55 @@ fn prepare_launch() -> Option> { Some(early.args) } +/// The app's own command line, once the launch profile's tokens are gone: `--control`, +/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after +/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its +/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never +/// opened as a file. +#[derive(Debug, Default, PartialEq)] +struct DesktopArgs { + control_port: Option, + control_token: Option, + sample: Option, + files: Vec, +} + +fn desktop_args(args: &[String], control_port: Option, control_token: Option) -> DesktopArgs { + let mut parsed = DesktopArgs { control_port, control_token, ..DesktopArgs::default() }; + let mut i = 0; + while i < args.len() { + match args[i].as_str() { + "--" => { + parsed.files.extend(args[i + 1..].iter().cloned()); + break; + } + "--control" => { + i += 1; + parsed.control_port = args.get(i).and_then(|p| p.parse().ok()); + } + "--control-token" => { + i += 1; + parsed.control_token = args.get(i).cloned(); + } + "--sample" => { + i += 1; + parsed.sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into())); + } + a if a.starts_with("-psn_") => {} + a => parsed.files.push(a.to_string()), + } + i += 1; + } + parsed +} + +/// A nightly owns no control channel, and only options count: everything after `--` is a file, so a +/// document named `--control` is opened rather than read as a flag. +fn nightly_control_refused(nightly: bool, args: &[String]) -> bool { + let options_end = args.iter().position(|a| a == "--").unwrap_or(args.len()); + nightly && args[..options_end].iter().any(|a| a == "--control" || a == "--control-token") +} + fn main() -> eframe::Result<()> { // A confined launcher run (`gridcraft_sandbox::launch_command`, which a Python cell starts from // this same executable) comes before everything else: it opens no window, writes no log, and @@ -392,34 +450,14 @@ fn main() -> eframe::Result<()> { } // The control channel is a stable-only service: a nightly window owns no port, writes no // token and never inherits the stable app's `GRIDCRAFT_CONTROL_PORT`/`GRIDCRAFT_CONTROL_TOKEN`. - if nightly && args.iter().any(|a| a == "--control" || a == "--control-token") { + if nightly_control_refused(nightly, &args) { eprintln!("GridCraft Nightly: the control channel is not part of the nightly channel"); std::process::exit(2); } - let mut control_port: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten(); - let mut control_token: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten(); - let mut sample: Option = None; - let mut files: Vec = Vec::new(); - let mut i = 0; - while i < args.len() { - match args[i].as_str() { - "--control" => { - i += 1; - control_port = args.get(i).and_then(|p| p.parse().ok()); - } - "--control-token" => { - i += 1; - control_token = args.get(i).cloned(); - } - "--sample" => { - i += 1; - sample = Some(args.get(i).cloned().unwrap_or_else(|| "sales".into())); - } - a if a.starts_with("-psn_") => {} - a => files.push(a.to_string()), - } - i += 1; - } + let control_port: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok())).flatten(); + let control_token: Option = (!nightly).then(|| std::env::var("GRIDCRAFT_CONTROL_TOKEN").ok()).flatten(); + let parsed = desktop_args(&args, control_port, control_token); + let (control_port, control_token, sample, files) = (parsed.control_port, parsed.control_token, parsed.sample, parsed.files); // The log file lives in the settings folder, next to the preferences; opened after the // arguments, so `--version` leaves no file behind. Records logged until now are written to it // first. Runs without preferences (agents' test runs) log to standard error only, so they @@ -449,7 +487,6 @@ fn main() -> eframe::Result<()> { if !nightly { app.start_update_check(); } - let control_port = control_port; load_prefs(&mut app); // Stamp the startup workbook's author from the persisted user name. if app.session.documents().is_empty() { @@ -616,3 +653,75 @@ mod packaging_tests { } } } + +#[cfg(test)] +mod launch_separator_tests { + use super::*; + use crate::build_flavor::BuildFlavor; + + /// The profile root a Launcher run is started with: absolute for the platform the test runs on. + /// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive + /// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too. + fn launcher_root() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" } + } + + /// The argv the Launcher starts a nightly with, extended by `tail`, as the start then reads it. + fn launcher_argv(tail: &[&str]) -> Vec { + let mut argv: Vec = + ["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect(); + argv.extend(tail.iter().map(std::ffi::OsString::from)); + launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect() + } + + #[test] + fn the_other_platforms_root_spelling_is_refused_as_relative() { + let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" }; + let argv: Vec = + ["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect(); + assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused"); + } + + #[test] + fn the_launchers_separator_is_never_a_file() { + let parsed = desktop_args(&launcher_argv(&[]), None, None); + assert_eq!(parsed, DesktopArgs::default(), "the separator must not reach the file list"); + } + + #[test] + fn files_after_the_separator_are_opened_in_order() { + assert_eq!(desktop_args(&launcher_argv(&["a.file"]), None, None).files, ["a.file"]); + let parsed = desktop_args(&launcher_argv(&["a.file", "--version", "--sample"]), None, None); + assert_eq!(parsed.files, ["a.file", "--version", "--sample"], "after -- every word is a file"); + assert_eq!((parsed.sample, parsed.control_port), (None, None)); + } + + #[test] + fn a_control_flag_after_the_separator_is_a_file_not_a_refusal() { + let argv = launcher_argv(&["--control"]); + assert!(!nightly_control_refused(true, &argv), "a document named --control must open, not refuse"); + let parsed = desktop_args(&argv, None, None); + assert_eq!((parsed.control_port, parsed.files), (None, vec!["--control".to_string()])); + } + + #[test] + fn a_control_flag_before_the_separator_still_names_the_port() { + let with_file = vec!["--control".to_string(), "7979".to_string(), "--".to_string(), "a.file".to_string()]; + assert!(nightly_control_refused(true, &with_file)); + let parsed = desktop_args(&with_file, None, None); + assert_eq!((parsed.control_port, parsed.files), (Some(7979), vec!["a.file".to_string()])); + let plain = vec!["--control".to_string(), "7979".to_string()]; + assert!(nightly_control_refused(true, &plain)); + let parsed = desktop_args(&plain, None, None); + assert_eq!((parsed.control_port, parsed.files), (Some(7979), Vec::::new())); + assert!(!nightly_control_refused(false, &plain), "the stable app keeps its control channel"); + } + + #[test] + fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() { + assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang"); + assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box"); + assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box"); + } +}