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 01/81] 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 02/81] =?UTF-8?q?i18n(ru):=20name=20the=20Insert=20tab=20?= =?UTF-8?q?=C2=AB=D0=92=D1=81=D1=82=D0=B0=D0=B2=D0=BA=D0=B0=C2=BB,=20trans?= =?UTF-8?q?late=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 28a645ca13d60d0031fe8e463cb998e29bd19d20 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Tue, 13 Oct 2026 08:00:40 -0300 Subject: [PATCH 03/81] 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 04/81] 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 05/81] 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 06/81] 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 07/81] 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 08/81] 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 09/81] 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 ffe73b3bd76aad33c6197d20bce98f0708545c85 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Thu, 15 Oct 2026 10:49:49 -0300 Subject: [PATCH 10/81] 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 11/81] 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 12/81] 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 3d19fa43f6e5fe4e1a51bebf06f02758ae730a56 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Tue, 20 Oct 2026 03:14:18 +0000 Subject: [PATCH 13/81] 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 14/81] 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 77cfbda1bc0f9784e1f05b82154b7919d62b3c87 Mon Sep 17 00:00:00 2001 From: Neil Cawse Date: Thu, 22 Oct 2026 05:18:54 +0000 Subject: [PATCH 15/81] 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 16/81] 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 17/81] #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 18/81] #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 19/81] #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 20/81] 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 21/81] 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 cbe10f0501bcf41f25b485e34e5f9c246de63bfb Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Thu, 22 Oct 2026 21:37:28 -0300 Subject: [PATCH 22/81] 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 23/81] 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 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 24/81] 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 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 25/81] 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 26/81] 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 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 27/81] 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 28/81] 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 29/81] 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 30/81] 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 31/81] 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 e4e2c5292aabd8dd98d4eddeccfddcbbbe2a0e1e Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 8 Nov 2026 11:24:12 +1100 Subject: [PATCH 32/81] 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 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 33/81] 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 71ba34f061665f43389deabd005c77b705ea0838 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 09:01:44 -0800 Subject: [PATCH 34/81] Updates: take craft-update from craft-libs main at 6e03f65bf --- Cargo.lock | 16 +++++++++------- Cargo.toml | 4 ++-- apps/gridcraft/Cargo.toml | 2 +- crates/ui-egui/Cargo.toml | 2 +- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a07b445d88..3986edf0fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -910,12 +910,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "fixed_decimal", "icu_decimal", @@ -938,7 +938,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-winprint-gdi", "log", @@ -952,7 +952,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -972,7 +972,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -982,6 +982,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", @@ -1018,7 +1019,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "egui", "objc2 0.6.5", @@ -6519,7 +6520,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4" +source = "git+https://github.com/storytold/winprint.rs?rev=bc06a7c48b768eb27a828c7986f6d2868b245ee0#bc06a7c48b768eb27a828c7986f6d2868b245ee0" dependencies = [ "flate2", "fmt-derive", @@ -6534,6 +6535,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] diff --git a/Cargo.toml b/Cargo.toml index 2e460354f3..e0038ca6df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ gridcraft-math = { path = "crates/math" } # Every craft-libs crate (craft-update and craft-window here, craft-ui in ui-egui, craft-print in # the 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 = "1b34eba41e62138fc2438d2734523b302840b45d", version = "=0.1.0", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", version = "=0.1.0", features = ["egui"] } # foundation thiserror = "2" @@ -72,7 +72,7 @@ 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 = "1b34eba41e62138fc2438d2734523b302840b45d", default-features = false, features = ["egui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", default-features = false, features = ["egui"] } [workspace.lints.rust] unsafe_code = "forbid" diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index 9365f3e15f..8704a6e396 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -35,7 +35,7 @@ winit = { version = "0.30", default-features = false, features = ["x11", "waylan [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # Same craft-libs revision as the workspace's craft-update and craft-window (see the root # Cargo.toml). -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-update = { workspace = true } rfd = { workspace = true } arboard = { workspace = true, features = ["image-data"] } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 3ecbbbbf99..1a1c2a9ab3 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -11,7 +11,7 @@ workspace = true [dependencies] # The shared capture slot (`craft_ui::capture`) comes 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 = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } gridcraft-engine = { workspace = true } gridcraft-chart = { workspace = true } # `monochrome_emoji_fonts` restores the Noto Emoji and emoji-icon faces that 0.37 moved behind From f6a75ef153a4e2a42b6118c4188296aa1b022989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 09:42:40 -0800 Subject: [PATCH 35/81] Updates: take craft-update from craft-libs main at e98299546 craft-update, craft-window and the file-format crates (craft-cfb, craft-offcrypto, craft-opc, craft-csv, craft-xls) move from bb57d422d to craft-libs main at e98299546, which includes #923: the check of whether the copy can install itself now runs on the update-check thread instead of in Updater::tick on the UI thread. --- Cargo.lock | 20 ++++++++++---------- Cargo.toml | 14 +++++++------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 395518b46c..fddaefe799 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -922,12 +922,12 @@ dependencies = [ [[package]] name = "craft-cfb" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" [[package]] name = "craft-csv" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "thiserror 2.0.21", ] @@ -963,7 +963,7 @@ dependencies = [ [[package]] name = "craft-offcrypto" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "aes", "base64 0.23.1", @@ -980,7 +980,7 @@ dependencies = [ [[package]] name = "craft-opc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "craft-xml", "craft-zip", @@ -1005,7 +1005,7 @@ dependencies = [ [[package]] name = "craft-sheet" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" [[package]] name = "craft-ui" @@ -1030,7 +1030,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "chrono", "dunce", @@ -1077,7 +1077,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "egui", "objc2 0.6.5", @@ -1096,7 +1096,7 @@ dependencies = [ [[package]] name = "craft-xls" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "craft-cfb", "craft-sheet", @@ -1109,7 +1109,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "quick-xml 0.41.0", "thiserror 2.0.21", @@ -1118,7 +1118,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4" +source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index debe801190..c2bac0fc8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,17 +30,17 @@ 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "=0.1.0", features = ["egui"] } # Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]). -craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" } -craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" } +craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" } +craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" } +craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. -craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" } +craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } # foundation thiserror = "2" @@ -80,7 +80,7 @@ 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 = "bb57d422d0bc842cbde430955825553ab7b976f4", default-features = false, features = ["egui"] } +craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", default-features = false, features = ["egui"] } [workspace.lints.rust] unsafe_code = "forbid" From 87d2264d927e4238177fcc1573c1520c00466634 Mon Sep 17 00:00:00 2001 From: alphazw Date: Fri, 13 Nov 2026 16:45:13 +0800 Subject: [PATCH 36/81] Route the first keystroke of an IME composition through the input method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a cell wasn't in edit mode, `grid/keyboard.rs` consumed `Event::Text` and seeded the in-cell editor with that keystroke. egui only delivers composition events to a widget that publishes `PlatformOutput::ime` in that frame, and only a focused `TextEdit` did so — which opens after the grid has already handled the first key. A CJK IME therefore lost its first key: with Wubi, typing `xta` wrote `x` into the cell and the input method only ever saw `ta`. The grid now publishes `IMEOutput` (egui 0.37's `IMEOutput::new`, anchored to the active cell) on every frame it owns keyboard input, so the first key reaches the input method. The editor is seeded from `ImeEvent::Commit`, never from a `Preedit`; `Event::Text` still handles ASCII exactly as before. The `context_generation` is kept in `Context` data and advances when the grid gains IME focus. `PlatformOutput` is rebuilt each frame, so the editor's own `TextEdit` keeps owning composition without any explicit disable. A locked cell on a protected sheet gets no IME request: `begin_edit` refuses those edits, so the grid applies the same merged-cell anchor and protection check before publishing, avoiding a composition that would be discarded. `IMEOutput` wants screen coordinates, so the cell and merged-range rectangles are mirrored for right-to-left sheets and the caret follows the drawn cell. Adds `tests/it/ime_composition.rs` (registered in `tests/it/main.rs`) with eight kittest cases: the grid publishes `PlatformOutput::ime` before the first keystroke, IME is withheld for a dialog and for locked cells but kept for unlocked cells on a protected sheet, the right-to-left rect is mirrored, a commit opens the editor with the committed text, a preedit alone does not, and ASCII typing still seeds the editor. The harness allows tofu because the suite's pinned font set has no Han face; the tests are about input routing. --- crates/ui-egui/src/grid/keyboard.rs | 83 +++++++++++- crates/ui-egui/tests/it/ime_composition.rs | 143 +++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 3 files changed, 223 insertions(+), 4 deletions(-) create mode 100644 crates/ui-egui/tests/it/ime_composition.rs diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index a852d04c33..a8454afb1e 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -32,6 +32,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res ctx.memory_mut(|m| { m.set_focus_lock_filter(resp.id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }) }); + request_grid_ime(app, ctx, resp, geo, sh); let events = grid_events(app, ctx, sh); // A shortcut key that also types a character (Shift+Space sends Text(" ")) must not start an edit. let shortcut_pressed = events.iter().any(|e| { @@ -43,6 +44,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res // a shortcut ran, that text must not start an edit over what it just did. let mut shortcut_ran = false; for ev in events { + // IME events are handled outside the match to keep this loop's complexity down. Any + // non-commit IME event (preedit, delete-surrounding) falls through to `_ => {}` below. + if handle_ime_commit(app, &ev, shortcut_pressed, shortcut_ran) { + return; + } match ev { egui::Event::Copy => { app.copy_to_clipboard(ctx, "edit.copy"); @@ -59,10 +65,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res egui::Event::MiddleClickPaste { .. } => {} egui::Event::Text(_) if shortcut_pressed || shortcut_ran => {} 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() { - ed.caret = ed.text.chars().count(); - } + seed_editor(app, text); return; } egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => { @@ -156,6 +159,78 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res } } +/// Open the in-cell editor with typed or committed text and put the caret after it. +fn seed_editor(app: &mut SheetApp, text: String) { + app.begin_edit(Some(text), false); + if let Some(ed) = app.editor.as_mut() { + ed.caret = ed.text.chars().count(); + } +} + +/// Seed the editor from a finished composition, if `ev` is one. +/// +/// Only `ImeEvent::Commit` is finished text; a preedit is the input method's in-progress +/// spelling and must not seed the editor. `Event::Ime` and `Event::Text` are mutually +/// exclusive for one keystroke, so accepting a commit cannot double-insert a character. +/// Returns whether the caller should stop handling this frame's events. +fn handle_ime_commit(app: &mut SheetApp, ev: &egui::Event, shortcut_pressed: bool, shortcut_ran: bool) -> bool { + let egui::Event::Ime(egui::ImeEvent::Commit(text)) = ev else { return false }; + if shortcut_pressed || shortcut_ran || text.is_empty() { + return false; + } + seed_editor(app, text.clone()); + true +} + +/// Ask the OS to route keystrokes through the input method while the grid owns keyboard input. +/// +/// egui enables IME only for a widget that publishes `PlatformOutput::ime` in that frame. The +/// in-cell `TextEdit` opens *after* the grid has consumed the first keystroke, so without this +/// the first key of a CJK composition is delivered as raw `Event::Text` and lands in the cell +/// (Wubi `xta` writes `x` and the input method only ever sees `ta`). The request must be +/// published on every focused frame, not in response to a key: winit applies it at the end of +/// the frame, so a key arriving while IME is still off cannot be recovered. +/// +/// `PlatformOutput` is rebuilt every frame, so returning early (an editor, a dialog or another +/// widget taking focus) simply leaves `ime` as `None` and the input method turns off. +fn request_grid_ime(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) { + if !ctx.memory(|m| m.owns_ime_events(resp.id)) { + return; + } + let Some(d) = app.session.active() else { return }; + let active = d.selection.active; + let merged = sh.merge_at(active); + // `begin_edit` refuses a locked cell on a protected sheet. Publishing an IME request for + // one would let the user compose text that is then discarded, so skip it up front, using + // the same merged-cell anchor and protection check as `SheetApp::begin_edit`. + let anchor = merged.map(|m| m.start).unwrap_or(active); + if app.session.locked_cell_message(d.wb.active_sheet(), anchor).is_some() { + return; + } + // `cell_rect`/`range_rect` are logical coordinates, but `IMEOutput` needs screen ones. + // On a right-to-left sheet the grid is mirrored, so publishing the logical rect puts the + // candidate window on the opposite side. After mirroring, `rect.min` is the screen-side + // start of the cell in both layouts, which is where the caret belongs. + let rect = match merged { + Some(m) => geo.mirror_rect(geo.range_rect(sh, m)), + None => geo.mirror_rect(geo.cell_rect(sh, active)), + }; + let cursor_rect = egui::Rect::from_min_size(rect.min, egui::vec2(1.0, rect.height())); + // egui 0.37 identifies an IME context by (owner, generation). The generation must change + // when this owner gains focus and stay stable for ordinary text and selection updates. + let gained_focus = resp.gained_focus(); + let generation = ctx.data_mut(|data| { + let g: &mut u64 = data.get_temp_mut_or_default(egui::Id::unique("gridcraft.grid_ime_generation")); + if gained_focus || *g == 0 { + *g = g.wrapping_add(1); + } + *g + }); + ctx.output_mut(|o| { + o.ime = Some(egui::output::IMEOutput::new(resp.id, generation, egui::IMEPurpose::Normal, rect, cursor_rect)); + }); +} + /// This frame's input events, without those the focused form control took. fn grid_events(app: &mut SheetApp, ctx: &egui::Context, sh: &Sheet) -> Vec { let events = ctx.input(|i| i.events.clone()); diff --git a/crates/ui-egui/tests/it/ime_composition.rs b/crates/ui-egui/tests/it/ime_composition.rs new file mode 100644 index 0000000000..8d0d4c2ffe --- /dev/null +++ b/crates/ui-egui/tests/it/ime_composition.rs @@ -0,0 +1,143 @@ +//! IME composition at the grid level. +//! +//! With a CJK input method, the first keystroke of a composition must reach the input method, +//! not be written straight into the cell as raw text. The grid publishes `PlatformOutput::ime` +//! on every frame it owns keyboard input, so the OS delivers `ImeEvent`s; a `Commit` opens the +//! in-cell editor with the finished text. Plain ASCII keeps using `Event::Text` (no regression). + +use egui::{Event, ImeEvent}; +use gridcraft_engine::Session; +use gridcraft_engine::core::CellRef; +use gridcraft_ui_egui::SheetApp; +use serde_json::json; + +type Harness = egui_kittest::Harness<'static, SheetApp>; + +/// A warmed harness over `session`, with the grid holding keyboard input on the active cell. +/// +/// The suite pins a font set with no Han face, so the harness draws tofu for the CJK commit +/// text: these tests check input routing, not glyph coverage. +fn fixture_with(session: Session) -> Harness { + let builder = crate::common::builder().allow_missing_glyphs().with_size(egui::vec2(1200.0, 800.0)); + crate::common::harness_with(builder, crate::common::app(session), 4) +} + +/// A warmed harness over a blank workbook, with the grid holding keyboard input on `A1`. +fn fixture() -> Harness { + fixture_with(crate::support::blank_session()) +} + +/// A protected sheet with `active` selected, optionally unlocking one cell first. +fn protected_session(active: &str, unlock: Option<&str>) -> Session { + let mut s = Session::new(); + s.new_workbook(); + if let Some(cell) = unlock { + s.execute("home.formatCells", json!({"range": cell, "style": {"protection": {"locked": false}}})).unwrap(); + } + s.execute("review.protectSheet", json!({})).unwrap(); + s.execute("selection.set", json!({"cell": active})).unwrap(); + s +} + +/// The text the in-cell editor currently holds, or `None` when no editor is open. +fn editor_text(h: &Harness) -> Option { + h.state().editor.as_ref().map(|ed| ed.text.clone()) +} + +/// The grid must request IME on every frame it owns keyboard input: winit applies +/// `set_ime_allowed` at the end of the frame, so requesting it in response to the first key is +/// already too late. The commit tests below only exercise the event handler and would still +/// pass with `request_grid_ime` removed, so this asserts the actual fix. +#[test] +fn grid_publishes_ime_request_before_the_first_keystroke() { + let mut h = fixture(); + h.run_steps(1); + let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME"); + assert!(matches!(ime.purpose, egui::IMEPurpose::Normal), "cell text is ordinary input"); + assert!(ime.rect.width() > 0.0 && ime.rect.height() > 0.0, "the IME rect must cover the active cell"); + assert_eq!(ime.cursor_rect.min, ime.rect.min, "the caret sits at the cell's start"); + assert!(ime.context_generation > 0, "egui 0.37 needs a non-zero IME context generation"); +} + +/// When a dialog takes the keyboard, `PlatformOutput` must stop advertising a grid IME owner. +/// The output is rebuilt each frame, so an early return is what turns IME off. +#[test] +fn grid_withholds_ime_request_when_it_does_not_own_keyboard_input() { + let mut h = fixture(); + h.state_mut().message = Some(("GridCraft".into(), "busy".into())); + h.run_steps(1); + assert!(h.output().platform_output.ime.is_none(), "a message dialog must take IME ownership away from the grid"); +} + +/// A locked cell on a protected sheet cannot be edited, so inviting a composition there would +/// only produce text that `SheetApp::begin_edit` discards. +#[test] +fn locked_cell_on_a_protected_sheet_does_not_request_ime() { + let mut h = fixture_with(protected_session("A1", None)); + h.run_steps(1); + assert!(h.output().platform_output.ime.is_none(), "a composition on a locked cell is always refused"); +} + +/// The protection guard must not disable IME for cells that are still editable. +#[test] +fn unlocked_cell_on_a_protected_sheet_still_requests_ime() { + let mut h = fixture_with(protected_session("C2", Some("C2"))); + h.run_steps(1); + assert!(h.output().platform_output.ime.is_some(), "unlocked cells stay editable on a protected sheet"); +} + +/// `IMEOutput::rect` is in screen coordinates, while `Geo::cell_rect` is in logical ones; on a +/// right-to-left sheet the two differ, and the candidate window must follow the drawn cell. +#[test] +fn right_to_left_sheet_publishes_mirrored_ime_rects() { + let mut s = Session::new(); + s.new_workbook(); + s.execute("view.rightToLeft", json!({"on": true})).unwrap(); + s.execute("selection.set", json!({"cell": "B2"})).unwrap(); + let mut h = fixture_with(s); + h.run_steps(1); + + let geo = h.state().grid.geo.clone().expect("the grid has been drawn"); + let sheet = h.state().session.active().unwrap().wb.active().unwrap(); + let logical = geo.cell_rect(sheet, CellRef::parse("B2").unwrap()); + let expected = geo.mirror_rect(logical); + assert!(geo.rtl, "the fixture must be right-to-left"); + assert!((expected.min.x - logical.min.x).abs() > 1.0, "the fixture must distinguish mirrored from logical x"); + + let ime = h.output().platform_output.ime.as_ref().expect("the focused grid must request IME"); + assert!((ime.rect.min.x - expected.min.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected); + assert!((ime.rect.max.x - expected.max.x).abs() < 0.01, "IME rect must use screen coordinates: got {:?}, expected {:?}", ime.rect, expected); + assert!((ime.cursor_rect.min.x - ime.rect.min.x).abs() < 0.01, "the caret must sit at the mirrored cell's start"); +} + +/// A committed composition opens the editor with its text and leaves the caret after it. +#[test] +fn ime_commit_opens_editor_with_committed_text() { + let mut h = fixture(); + h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into()))); + h.run_steps(2); + let ed = h.state().editor.as_ref().expect("an IME commit must open the in-cell editor"); + assert_eq!(ed.text, "张", "the committed text should seed the editor"); + assert_eq!(ed.caret, ed.text.chars().count(), "the caret should sit after the committed text"); +} + +/// A preedit is not text yet: it must not open the editor on its own, only the commit does. +#[test] +fn ime_preedit_does_not_seed_editor() { + let mut h = fixture(); + h.input_mut().events.push(Event::Ime(ImeEvent::Preedit { text: "zh".into(), active_range_chars: Some(0..2) })); + h.run_steps(2); + assert!(h.state().editor.is_none(), "a preedit must not seed the editor on its own"); + h.input_mut().events.push(Event::Ime(ImeEvent::Commit("张".into()))); + h.run_steps(2); + assert_eq!(editor_text(&h).as_deref(), Some("张"), "the commit after a preedit opens the editor"); +} + +/// Plain ASCII never composes, so `Event::Text` still seeds the editor exactly as before. +#[test] +fn ascii_text_still_seeds_editor_no_regression() { + let mut h = fixture(); + h.input_mut().events.push(Event::Text("abc".into())); + h.run_steps(2); + assert_eq!(editor_text(&h).as_deref(), Some("abc"), "ASCII typing must still seed the editor"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a6d27142d6..ad4d67c4ca 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -59,6 +59,7 @@ mod header_column_drag; mod host_chrome; mod hyperlink_ctrl_click; mod hyperlink_dialog; +mod ime_composition; mod in_cell_editor_size; mod in_cell_editor_wrap; mod ink_render; From 8a04139ef2e9b565fbb22e180d0afc298991bd81 Mon Sep 17 00:00:00 2001 From: quantforge-br <218010578+quantforge-br@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:33:15 -0300 Subject: [PATCH 37/81] Calc: a spill keeps the cells it held when another array grows into them (#964) #2483 lets a spill that already exists keep its cells, but when both anchors held a spill, reading order decided: an array growing into a neighbour's spill took its cells, in automatic calculation and after a full recalculation. Excel keeps the cells the neighbour owns. Standing now also remembers the area each anchor that held a spill filled before the calculation. For each contested cell the anchor whose spill held it keeps it; otherwise #2483's rules apply as before. With the xlsx reader restoring each dynamic array's saved area, a reopened workbook keeps its layout too, so both known limits documented on Standing are gone. Tests now covered by #2483 are dropped, and its grow-and-back test asserts the blocked grower. --- ROADMAP.md | 2 +- crates/calc/src/recalc.rs | 98 +++++++++++++++++++++-------- crates/calc/src/recalc/pass_host.rs | 8 +-- crates/calc/src/tests.rs | 31 --------- crates/engine/src/tests.rs | 33 +++------- crates/xlsx/src/tests/roundtrip.rs | 3 + 6 files changed, 91 insertions(+), 84 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index ea22822d01..e8f197036a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -200,7 +200,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; clearing it lets the other spill at once (#964, found by the command-sequence fuzz) | +| 2026-10-13 | Spills: an array that grows into cells another array's spill already holds is `#SPILL!`, in automatic calculation and after Calculate Now, as in Excel; a workbook reopened from XLSX keeps the spill layout it was saved with (#964, found by the command-sequence fuzz) | | 2026-10-13 | Grid: resizing several selected columns or rows previews on the dragged one and applies the size to all on release; Esc cancels (#1082) | | 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 | PDF writer: objects are written straight to the output, identical pictures are stored once, style operators are emitted only when they change, `q` nesting is limited to 28 and polyline joins no longer leak into later strokes (#816) | diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index ab1b5bd039..f38ed8d91c 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -59,26 +59,29 @@ pub struct Calc { /// Who gets the cells when two arrays want the same ones. Excel (measured by a reviewer on /// PR #2483) lets the spill that already exists keep its cells, whichever anchor comes first; -/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here: +/// the other formula shows `#SPILL!`, and clearing the winner lets it spill. The rule here, for +/// each cell both want: /// -/// 1. an anchor that held a spill before this calculation outranks one that did not; -/// 2. otherwise the anchor first in reading order (row, then column) wins. +/// 1. the anchor whose spill held that cell before this calculation keeps it, so an array that +/// grows into another's area is `#SPILL!` even when it held a spill of its own; +/// 2. otherwise an anchor that held a spill before this calculation outranks one that did not; +/// 3. otherwise the anchor first in reading order (row, then column) wins. /// -/// Rule 2 alone decides when nothing is remembered, so the result never depends on hash order +/// Rule 3 alone decides when nothing is remembered, so the result never depends on hash order /// or evaluation order. A full recalculation remembers the layout the sheet held before it -/// started (rule 1), so it agrees with the incremental one; a workbook that is calculated for -/// the first time has no such layout (rule 2 only). -/// -/// Known limits: (a) the xlsx reader does not restore spill layouts, so a workbook opened from a -/// file is laid out by rule 2 alone, although Excel keeps the layout the file records; (b) when -/// both anchors held a spill and one grows into the other, rule 2 decides, where Excel keeps -/// the cells the other already owns. +/// started, so it agrees with the incremental one; a workbook that is calculated for the first +/// time has no such layout (rule 3 only). The xlsx reader restores the area each dynamic array +/// was saved spilling over, so a workbook opened from a file keeps the layout it was saved with. #[derive(Clone, Debug, Default)] struct Standing { /// `true`: `keys` are the anchors that held a spill (full recalculation, which lays every /// spill out afresh). `false`: `keys` are the formulas that held none (incremental). held: bool, keys: HashSet, + /// The area each anchor that held a spill filled before this calculation, for the anchors the + /// calculation lays out again (full: all of them; incremental: the formulas it recalculates). + /// Any other anchor still fills the area the sheet shows. + areas: HashMap, } impl Standing { @@ -86,7 +89,7 @@ impl Standing { self.keys.contains(&k) == self.held } - /// Whether `a` takes cells from `b` when both want them. + /// Whether `a` takes cells from `b` when both want them and neither held them (rules 2, 3). fn outranks(&self, a: Key, b: Key) -> bool { match (self.had_spill(a), self.had_spill(b)) { (true, false) => true, @@ -94,6 +97,22 @@ impl Standing { _ => (a.1.row, a.1.col) < (b.1.row, b.1.col), } } + + /// Whether `k`'s spill held `cell` before this calculation; `now` is the area the sheet + /// shows for `k`. + fn held_cell(&self, k: Key, now: Option, cell: CellRef) -> bool { + self.had_spill(k) && self.areas.get(&k).copied().or(now).is_some_and(|r| r.contains(cell)) + } + + /// Whether `a` takes `cell` from `b` when both want it (rule 1, then [`Self::outranks`]). Each + /// anchor comes with the area the sheet shows for it. + fn outranks_at(&self, (a, a_now): (Key, Option), (b, b_now): (Key, Option), cell: CellRef) -> bool { + match (self.held_cell(a, a_now, cell), self.held_cell(b, b_now, cell)) { + (true, false) => true, + (false, true) => false, + _ => self.outranks(a, b), + } + } } /// A set of cells by row, each row's columns in their own set: a window of rows and columns is @@ -313,12 +332,18 @@ impl Calc { self.rebuild(wb); // The layout the sheets hold now decides who keeps cells two arrays both want. // (A Python cell that holds a spill counts too, as it does in the incremental pass.) - let mut held = HashSet::default(); + let mut areas: HashMap = HashMap::default(); for i in 0..wb.sheets.len() { if let Some(sh) = wb.sheet(i) { - held.extend(sh.spill_ranges.keys().filter(|a| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some())).map(|a| (i, *a))); + areas.extend( + sh.spill_ranges + .iter() + .filter(|(a, _)| sh.cell(**a).is_some_and(|c| c.formula.is_some() || c.py.is_some())) + .map(|(a, r)| ((i, *a), *r)), + ); } } + let held = areas.keys().copied().collect(); // 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). for i in 0..wb.sheets.len() { @@ -330,7 +355,7 @@ impl Calc { } } let all: Vec = self.graph.nodes.keys().copied().collect(); - self.standing = Standing { held: true, keys: held }; + self.standing = Standing { held: true, keys: held, areas }; self.run(wb, all, true); self.standing = Standing::default(); } @@ -542,8 +567,15 @@ impl Calc { if !full { // What each formula held before this calculation touched it. for &k in &dirty { - if seen.insert(k) && wb.sheet(k.0).is_some_and(|s| !s.spill_ranges.contains_key(&k.1)) { - self.standing.keys.insert(k); + if seen.insert(k) { + match wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) { + Some(r) => { + self.standing.areas.insert(k, *r); + } + None => { + self.standing.keys.insert(k); + } + } } } } @@ -664,7 +696,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); // Two arrays that want the same cells (see [`Standing`]): a spill already laid out - // that this anchor outranks is taken over, and recalculated. + // that this anchor outranks on every cell they share is taken over, and recalculated. let standing = &self.standing; // A spill can only be in the way where it has cells besides its anchor, and an // anchor itself blocks the array. When no spilled cell lies in the range, the owners @@ -675,13 +707,18 @@ impl Calc { sheet .spill_ranges .iter() - .filter(|(o, r)| **o != key.1 && r.intersects(&range) && standing.outranks(*key, (key.0, **o))) + .filter(|(o, r)| { + **o != key.1 + && r.intersection(&range).is_some_and(|shared| { + shared.iter().all(|cell| standing.outranks_at((*key, old), ((key.0, **o), Some(**r)), cell)) + }) + }) .map(|(o, r)| (*o, *r)) .collect() } else { Vec::new() }; - let blocked = spill_is_blocked(sheet, *key, range, end, standing); + let blocked = spill_is_blocked(sheet, (*key, old), range, end, standing); if !blocked { for (o, r) in outranked { for c in r.iter() { @@ -739,11 +776,22 @@ thread_local! { pub(crate) static OWNER_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// Whether the array at `anchor` can't be laid out over `range`. A spill already laid out that -/// `anchor` outranks does not block it: it is taken over when written back. -fn spill_is_blocked(sheet: &gridcraft_model::Sheet, anchor: Key, range: RangeRef, end: CellRef, standing: &Standing) -> bool { - let outranked = - |cell: CellRef| sheet.spill_ranges.iter().any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks(anchor, (anchor.0, *o))); +/// Whether the array at `anchor` (with the area the sheet showed for it) can't be laid out over +/// `range`. A spill already laid out that `anchor` outranks does not block it: it is taken over +/// when written back. +fn spill_is_blocked( + sheet: &gridcraft_model::Sheet, + (anchor, now): (Key, Option), + range: RangeRef, + end: CellRef, + standing: &Standing, +) -> bool { + let outranked = |cell: CellRef| { + sheet + .spill_ranges + .iter() + .any(|(o, r)| *o != anchor.1 && r.contains(cell) && standing.outranks_at((anchor, now), ((anchor.0, *o), Some(*r)), cell)) + }; end.row >= gridcraft_core::MAX_ROWS || end.col >= gridcraft_core::MAX_COLS || range.iter().any(|cell| cell != anchor.1 && (sheet.cells.has(cell) || (sheet.spill.contains_key(&cell) && !outranked(cell)))) diff --git a/crates/calc/src/recalc/pass_host.rs b/crates/calc/src/recalc/pass_host.rs index 78bd5d9efa..7f42c3644d 100644 --- a/crates/calc/src/recalc/pass_host.rs +++ b/crates/calc/src/recalc/pass_host.rs @@ -163,9 +163,9 @@ fn spill_hits_overlap(index: &SpillIndex, sheet: usize, hits: &[CellRef], range: } /// Whether an array result at `k` can't spill: it is in a table, or its area runs off the sheet, -/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it -/// (see `Standing`; unless that formula is recalculated in this pass, and so may spill elsewhere -/// now). A spill it outranks gives way to it when written back. +/// overlaps merged cells, holds other cells, or the spill of another formula that outranks it on +/// a cell they share (see `Standing`; unless that formula is recalculated in this pass, and so +/// may spill elsewhere now). A spill it outranks gives way to it when written back. fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool { let Some(sh) = host.wb.sheet(sheet) else { return false }; let end = @@ -182,7 +182,7 @@ fn spill_blocked(host: &PassHost<'_>, (sheet, anchor): Key, a: &Array) -> bool { && r.contains(c) && !host.exprs.contains_key(&(sheet, *o)) && !host.python.contains_key(&(sheet, *o)) - && standing.outranks((sheet, *o), (sheet, anchor)) + && standing.outranks_at(((sheet, *o), Some(*r)), ((sheet, anchor), own.copied()), c) }) }; end.row >= gridcraft_core::MAX_ROWS diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index d8c424c773..b1a06db35b 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -706,20 +706,6 @@ 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 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 @@ -737,23 +723,6 @@ 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. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a9410c232e..5a3f813866 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2993,9 +2993,10 @@ fn overlapping_spills_keep_the_one_that_exists_whichever_anchor_is_first() { #[test] fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() { use gridcraft_core::CellError::Spill; - // Both arrays already spill; F8 (first in reading order) grows down over E10's spill, takes - // its cells, shrinks back and lets it spill again, then the steps are undone, redone, edited - // inside the contested area and cleared. Every state must match a full recalc. + // Both arrays already spill; F8 (first in reading order) grows down over E10's spill, is + // #SPILL! because E10 holds those cells (as in Excel), shrinks back and spills again, then the + // steps are undone, redone, edited inside the contested area and cleared. Every state must + // match a full recalc. let mut s = s(); s.execute("cell.set", json!({"cell": "H1", "input": "1"})).unwrap(); s.execute("cell.set", json!({"cell": "F8", "input": "=SEQUENCE(H1)"})).unwrap(); @@ -3017,18 +3018,18 @@ fn a_spill_growing_into_another_and_back_matches_a_full_recalc_at_every_step() { s.execute(id, params.clone()).unwrap(); assert_matches_full_recalc(&s); if i == 0 { - // Both held a spill: reading order gives F8 the cells. - assert_eq!(v(&s, "F12"), Value::Number(5.0)); - assert_eq!(v(&s, "E10"), Value::Error(Spill)); + // Both held a spill: E10 holds F10, so it keeps it and F8 is blocked. + assert_eq!(v(&s, "F8"), Value::Error(Spill)); + assert_eq!(v(&s, "F10"), Value::Number(20.0)); } if i == 2 { assert_eq!(v(&s, "E10"), Value::Number(10.0)); assert_eq!(v(&s, "F10"), Value::Number(20.0)); } if i == 3 { - // Undone back to the grown F8. - assert_eq!(v(&s, "F12"), Value::Number(5.0)); - assert_eq!(v(&s, "E10"), Value::Error(Spill)); + // Undone back to the grown F8, blocked again. + assert_eq!(v(&s, "F8"), Value::Error(Spill)); + assert_eq!(v(&s, "F10"), Value::Number(20.0)); } if i == 8 { assert_eq!((v(&s, "F8"), v(&s, "E10"), v(&s, "F9")), (Value::Empty, Value::Empty, Value::Empty)); @@ -3270,20 +3271,6 @@ 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 diff --git a/crates/xlsx/src/tests/roundtrip.rs b/crates/xlsx/src/tests/roundtrip.rs index 2751c82247..7669f999ee 100644 --- a/crates/xlsx/src/tests/roundtrip.rs +++ b/crates/xlsx/src/tests/roundtrip.rs @@ -1058,6 +1058,9 @@ 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 dynamic array keeps the area the file says it spilled over. + assert!(xml.contains("TANH(A1:A3)"), "{xml}"); + assert!(xml.contains("TANH(A1:A3)"), "{xml}"); let (back, _) = read_xlsx(&bytes).unwrap(); for (a, dynamic) in [("B2", false), ("B3", false), ("C2", true), ("D2", false)] { assert_eq!(text(&back, a), text(&wb, a), "{a}"); From 60e9ae022278865134d75a2c6df24c1dfc403bd3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:07:44 +0700 Subject: [PATCH 38/81] =?UTF-8?q?i18n:=20fill-handle=20and=20Home=20?= =?UTF-8?q?=E2=80=BA=20Fill=20menu=20labels=20in=20every=20catalog=20(#445?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The right-drag fill menu and the Auto Fill Options button (Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Fill Days, Fill Weekdays, Fill Months, Fill Years and the button's own name) had no row in any catalog, so every language showed them in English. Add them to all 18 non-English catalogs, add Series…, Down and Up from the Home › Fill menu to the nine catalogs that lacked them, and translate the Ukrainian rows that held English. fill_menu_labels_are_translated_in_every_catalog fails when one of these rows goes missing or stays English. Fixes #4458 Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/i18n.rs | 29 +++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.rs | 9 +++++++++ crates/ui-egui/src/i18n/de.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/el.rs | 9 +++++++++ crates/ui-egui/src/i18n/es.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/fr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/it.rs | 9 +++++++++ crates/ui-egui/src/i18n/ja.rs | 9 +++++++++ crates/ui-egui/src/i18n/ko.rs | 12 ++++++++++++ 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 | 12 ++++++++++++ crates/ui-egui/src/i18n/sr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/tr.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/uk.rs | 15 ++++++++++++--- crates/ui-egui/src/i18n/vi.rs | 12 ++++++++++++ crates/ui-egui/src/i18n/zh.rs | 12 ++++++++++++ docs/localization-parity.md | 3 ++- 20 files changed, 223 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 6f5036c80f..0b25ccecf6 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -532,6 +532,35 @@ mod tests { } } + /// The fill-handle menus (the right-drag menu and the Auto Fill Options button) and the + /// Home › Fill menu have a row in every catalog, with no silent English fallback (#4458). + #[test] + fn fill_menu_labels_are_translated_in_every_catalog() { + let keys = [ + "Copy Cells", + "Fill Series", + "Fill Formatting Only", + "Fill Without Formatting", + "Fill Days", + "Fill Weekdays", + "Fill Months", + "Fill Years", + "Auto Fill Options", + "Series…", + "Down", + "Up", + ]; + for key in keys { + assert_eq!(Language::En.tr(key), key); + for language in Language::ALL.into_iter().filter(|l| *l != Language::En) { + let code = language.code(); + let shown = language.translated(key).unwrap_or_else(|| panic!("{code}: no row for {key:?}")); + assert!(!shown.trim().is_empty() && !shown.contains('\n'), "{code}: bad translation of {key:?}: {shown:?}"); + assert_ne!(shown, key, "{code}: the row for {key:?} is still English"); + } + } + } + #[test] fn fill_puts_each_value_in_once() { // A value holding a placeholder (a macro named `{steps}`) is shown as it is. diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index a7464598a3..7fbf474c57 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -728,6 +728,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char má nečíselný argument {argument}", "\\@char with invalid code point {code}" => "\\@char s neplatným kódovým bodem {code}", "Invalid environment name character: {character}" => "Neplatný znak v názvu prostředí: {character}", + "Copy Cells" => "Kopírovat buňky", + "Fill Series" => "Vyplnit řady", + "Fill Formatting Only" => "Vyplnit pouze formáty", + "Fill Without Formatting" => "Vyplnit bez formátování", + "Fill Days" => "Vyplnit dny", + "Fill Weekdays" => "Vyplnit pracovní dny", + "Fill Months" => "Vyplnit měsíce", + "Fill Years" => "Vyplnit roky", + "Auto Fill Options" => "Možnosti automatického vyplnění", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 300cc4969a..e1490bb96e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -650,6 +650,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char hat ein nicht numerisches Argument {argument}", "\\@char with invalid code point {code}" => "\\@char mit ungültigem Codepunkt {code}", "Invalid environment name character: {character}" => "Ungültiges Zeichen im Umgebungsnamen: {character}", + "Copy Cells" => "Zellen kopieren", + "Fill Series" => "Datenreihe ausfüllen", + "Fill Formatting Only" => "Nur Formate ausfüllen", + "Fill Without Formatting" => "Ohne Formatierung ausfüllen", + "Fill Days" => "Tage ausfüllen", + "Fill Weekdays" => "Wochentage ausfüllen", + "Fill Months" => "Monate ausfüllen", + "Fill Years" => "Jahre ausfüllen", + "Auto Fill Options" => "Optionen für automatisches Ausfüllen", + "Series…" => "Reihe…", + "Down" => "Nach unten", + "Up" => "Nach oben", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/el.rs b/crates/ui-egui/src/i18n/el.rs index 1287ad6a02..b5cab06d06 100644 --- a/crates/ui-egui/src/i18n/el.rs +++ b/crates/ui-egui/src/i18n/el.rs @@ -1135,6 +1135,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "Το \\@char έχει μη αριθμητικό όρισμα {argument}", "\\@char with invalid code point {code}" => "\\@char με μη έγκυρο σημείο κώδικα {code}", "Invalid environment name character: {character}" => "Μη έγκυρος χαρακτήρας στο όνομα περιβάλλοντος: {character}", + "Copy Cells" => "Αντιγραφή κελιών", + "Fill Series" => "Συμπλήρωση σειράς", + "Fill Formatting Only" => "Συμπλήρωση μόνο μορφοποίησης", + "Fill Without Formatting" => "Συμπλήρωση χωρίς μορφοποίηση", + "Fill Days" => "Συμπλήρωση ημερών", + "Fill Weekdays" => "Συμπλήρωση εργάσιμων ημερών", + "Fill Months" => "Συμπλήρωση μηνών", + "Fill Years" => "Συμπλήρωση ετών", + "Auto Fill Options" => "Επιλογές αυτόματης συμπλήρωσης", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d0df42c8b2..d318e998fc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -656,6 +656,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char tiene un argumento no numérico {argument}", "\\@char with invalid code point {code}" => "\\@char con un punto de código no válido {code}", "Invalid environment name character: {character}" => "Carácter no válido en el nombre del entorno: {character}", + "Copy Cells" => "Copiar celdas", + "Fill Series" => "Rellenar serie", + "Fill Formatting Only" => "Rellenar solo formatos", + "Fill Without Formatting" => "Rellenar sin formato", + "Fill Days" => "Rellenar días", + "Fill Weekdays" => "Rellenar días laborables", + "Fill Months" => "Rellenar meses", + "Fill Years" => "Rellenar años", + "Auto Fill Options" => "Opciones de autorrelleno", + "Series…" => "Serie…", + "Down" => "Hacia abajo", + "Up" => "Hacia arriba", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 104edcd161..1fdcb1279c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -618,6 +618,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char a un argument non numérique {argument}", "\\@char with invalid code point {code}" => "\\@char avec un point de code non valide {code}", "Invalid environment name character: {character}" => "Caractère non valide dans le nom d'environnement : {character}", + "Copy Cells" => "Copier les cellules", + "Fill Series" => "Remplir la série", + "Fill Formatting Only" => "Remplir les formats uniquement", + "Fill Without Formatting" => "Remplir sans la mise en forme", + "Fill Days" => "Remplir les jours", + "Fill Weekdays" => "Remplir les jours ouvrés", + "Fill Months" => "Remplir les mois", + "Fill Years" => "Remplir les années", + "Auto Fill Options" => "Options de remplissage automatique", + "Series…" => "Série…", + "Down" => "Vers le bas", + "Up" => "Vers le haut", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1ca07d34b0..1154e17385 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1139,6 +1139,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ha un argomento non numerico {argument}", "\\@char with invalid code point {code}" => "\\@char con punto di codice non valido {code}", "Invalid environment name character: {character}" => "Carattere non valido nel nome dell'ambiente: {character}", + "Copy Cells" => "Copia celle", + "Fill Series" => "Riempi serie", + "Fill Formatting Only" => "Riempi solo formattazione", + "Fill Without Formatting" => "Riempi senza formattazione", + "Fill Days" => "Riempi giorni", + "Fill Weekdays" => "Riempi giorni feriali", + "Fill Months" => "Riempi mesi", + "Fill Years" => "Riempi anni", + "Auto Fill Options" => "Opzioni di riempimento automatico", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f5d9baa2ac..3033b55e56 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1288,6 +1288,15 @@ pub(super) const EXTRA: &[(&str, &str)] = &[ "Drag to fill cells. Drag from inside a cell to select a range.", "ドラッグしてセルをオートフィルします。セルの内側からドラッグすると範囲を選択します。", ), + ("Copy Cells", "セルのコピー"), + ("Fill Series", "連続データを入力"), + ("Fill Formatting Only", "書式のみを入力"), + ("Fill Without Formatting", "書式なしで入力"), + ("Fill Days", "日単位で入力"), + ("Fill Weekdays", "平日単位で入力"), + ("Fill Months", "月単位で入力"), + ("Fill Years", "年単位で入力"), + ("Auto Fill Options", "オートフィル オプション"), ]; /// Translates an interface label; `None` for a label the catalog does not know, so `i18n.rs` can diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 880f97ac84..2e5b7660f0 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -616,6 +616,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char 의 인수 {argument} 이(가) 숫자가 아닙니다", "\\@char with invalid code point {code}" => "\\@char 의 코드 포인트 {code} 이(가) 잘못되었습니다", "Invalid environment name character: {character}" => "환경 이름에 잘못된 문자가 있습니다: {character}", + "Copy Cells" => "셀 복사", + "Fill Series" => "연속 데이터 채우기", + "Fill Formatting Only" => "서식만 채우기", + "Fill Without Formatting" => "서식 없이 채우기", + "Fill Days" => "일 단위 채우기", + "Fill Weekdays" => "평일 단위 채우기", + "Fill Months" => "월 단위 채우기", + "Fill Years" => "연 단위 채우기", + "Auto Fill Options" => "자동 채우기 옵션", + "Series…" => "연속 데이터…", + "Down" => "아래쪽", + "Up" => "위쪽", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/nl.rs b/crates/ui-egui/src/i18n/nl.rs index ea0352af32..8267b65efe 100644 --- a/crates/ui-egui/src/i18n/nl.rs +++ b/crates/ui-egui/src/i18n/nl.rs @@ -691,6 +691,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char heeft een niet-numeriek argument {argument}", "\\@char with invalid code point {code}" => "\\@char met ongeldig codepunt {code}", "Invalid environment name character: {character}" => "Ongeldig teken in de omgevingsnaam: {character}", + "Copy Cells" => "Cellen kopiëren", + "Fill Series" => "Reeks vullen", + "Fill Formatting Only" => "Alleen opmaak vullen", + "Fill Without Formatting" => "Vullen zonder opmaak", + "Fill Days" => "Dagen vullen", + "Fill Weekdays" => "Werkdagen vullen", + "Fill Months" => "Maanden vullen", + "Fill Years" => "Jaren vullen", + "Auto Fill Options" => "Opties voor automatisch vullen", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index b7b5882055..0b774cbf11 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -1127,6 +1127,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ma nienumeryczny argument {argument}", "\\@char with invalid code point {code}" => "\\@char z nieprawidłowym punktem kodowym {code}", "Invalid environment name character: {character}" => "Nieprawidłowy znak w nazwie środowiska: {character}", + "Copy Cells" => "Kopiuj komórki", + "Fill Series" => "Wypełnij serią", + "Fill Formatting Only" => "Wypełnij tylko formatami", + "Fill Without Formatting" => "Wypełnij bez formatowania", + "Fill Days" => "Wypełnij dniami", + "Fill Weekdays" => "Wypełnij dniami roboczymi", + "Fill Months" => "Wypełnij miesiącami", + "Fill Years" => "Wypełnij latami", + "Auto Fill Options" => "Opcje autowypełniania", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 168450222f..a26216f1ba 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -1143,6 +1143,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char tem um argumento não numérico {argument}", "\\@char with invalid code point {code}" => "\\@char com ponto de código inválido {code}", "Invalid environment name character: {character}" => "Caractere inválido no nome do ambiente: {character}", + "Copy Cells" => "Copiar Células", + "Fill Series" => "Preencher Série", + "Fill Formatting Only" => "Preencher Somente Formatos", + "Fill Without Formatting" => "Preencher Sem Formatação", + "Fill Days" => "Preencher Dias", + "Fill Weekdays" => "Preencher Dias Úteis", + "Fill Months" => "Preencher Meses", + "Fill Years" => "Preencher Anos", + "Auto Fill Options" => "Opções de Autopreenchimento", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ro.rs b/crates/ui-egui/src/i18n/ro.rs index ad47d70115..e4b1ab3c76 100644 --- a/crates/ui-egui/src/i18n/ro.rs +++ b/crates/ui-egui/src/i18n/ro.rs @@ -1189,6 +1189,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char are un argument nenumeric {argument}", "\\@char with invalid code point {code}" => "\\@char cu punct de cod nevalid {code}", "Invalid environment name character: {character}" => "Caracter nevalid în numele mediului: {character}", + "Copy Cells" => "Copiere celule", + "Fill Series" => "Umplere serie", + "Fill Formatting Only" => "Umplere doar formate", + "Fill Without Formatting" => "Umplere fără formatare", + "Fill Days" => "Umplere zile", + "Fill Weekdays" => "Umplere zile lucrătoare", + "Fill Months" => "Umplere luni", + "Fill Years" => "Umplere ani", + "Auto Fill Options" => "Opțiuni de umplere automată", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 77a3874429..3f861bb2fd 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -626,6 +626,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "У \\@char нечисловой аргумент {argument}", "\\@char with invalid code point {code}" => "\\@char с недопустимой кодовой точкой {code}", "Invalid environment name character: {character}" => "Недопустимый символ в имени окружения: {character}", + "Copy Cells" => "Копировать ячейки", + "Fill Series" => "Заполнить ряд", + "Fill Formatting Only" => "Заполнить только форматы", + "Fill Without Formatting" => "Заполнить без форматирования", + "Fill Days" => "Заполнить по дням", + "Fill Weekdays" => "Заполнить по рабочим дням", + "Fill Months" => "Заполнить по месяцам", + "Fill Years" => "Заполнить по годам", + "Auto Fill Options" => "Параметры автозаполнения", + "Series…" => "Ряд…", + "Down" => "Вниз", + "Up" => "Вверх", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/sr.rs b/crates/ui-egui/src/i18n/sr.rs index 4b65ab8be3..5aabbf7b1a 100644 --- a/crates/ui-egui/src/i18n/sr.rs +++ b/crates/ui-egui/src/i18n/sr.rs @@ -609,6 +609,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char ima nenumerički argument {argument}", "\\@char with invalid code point {code}" => "\\@char sa nevažećom kodnom tačkom {code}", "Invalid environment name character: {character}" => "Nevažeći znak u nazivu okruženja: {character}", + "Copy Cells" => "Kopiraj ćelije", + "Fill Series" => "Popuni niz", + "Fill Formatting Only" => "Popuni samo oblikovanja", + "Fill Without Formatting" => "Popuni bez oblikovanja", + "Fill Days" => "Popuni dane", + "Fill Weekdays" => "Popuni radne dane", + "Fill Months" => "Popuni mesece", + "Fill Years" => "Popuni godine", + "Auto Fill Options" => "Opcije automatskog popunjavanja", + "Series…" => "Niz…", + "Down" => "Nadole", + "Up" => "Nagore", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/tr.rs b/crates/ui-egui/src/i18n/tr.rs index e2d27fbf06..ca59a0dd98 100644 --- a/crates/ui-egui/src/i18n/tr.rs +++ b/crates/ui-egui/src/i18n/tr.rs @@ -581,6 +581,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char sayısal olmayan bir bağımsız değişkene sahip: {argument}", "\\@char with invalid code point {code}" => "\\@char geçersiz bir kod noktası içeriyor: {code}", "Invalid environment name character: {character}" => "Ortam adında geçersiz karakter: {character}", + "Copy Cells" => "Hücreleri Kopyala", + "Fill Series" => "Seriyi Doldur", + "Fill Formatting Only" => "Yalnızca Biçimleri Doldur", + "Fill Without Formatting" => "Biçimlendirmeden Doldur", + "Fill Days" => "Günleri Doldur", + "Fill Weekdays" => "İş Günlerini Doldur", + "Fill Months" => "Ayları Doldur", + "Fill Years" => "Yılları Doldur", + "Auto Fill Options" => "Otomatik Doldurma Seçenekleri", + "Series…" => "Seri…", + "Down" => "Aşağı", + "Up" => "Yukarı", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 185a21c1d1..33141bdfff 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -907,7 +907,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Delete chart" => "Видалити діаграму", "Delete…" => "Delete…", "Dismiss" => "Dismiss", - "Down" => "Down", + "Down" => "Вниз", "Edit chart title" => "Редагувати назву діаграми", "Erase ink strokes" => "Erase ink strokes", "Every command run in this session (replayable)" => "Every command run in this session (replayable)", @@ -954,7 +954,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Search and run any command" => "Search and run any command", "Search commands" => "Search commands", "Select and move ink and shapes" => "Select and move ink and shapes", - "Series…" => "Series…", + "Series…" => "Ряд…", "Share: export or save a copy" => "Share: export or save a copy", "Show Formulas (⌃`)" => "Show Formulas (⌃`)", "Slicer" => "Slicer", @@ -969,7 +969,7 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Undo" => "Undo", "Undo list" => "Undo list", "Unhide Sheet…" => "Unhide Sheet…", - "Up" => "Up", + "Up" => "Угору", "Version, contributors and the AI models that helped" => "Version, contributors and the AI models that helped", "What-If Analysis" => "What-If Analysis", "Zoom In" => "Zoom In", @@ -1131,6 +1131,15 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char має нечисловий аргумент {argument}", "\\@char with invalid code point {code}" => "\\@char з неприпустимою кодовою точкою {code}", "Invalid environment name character: {character}" => "Неприпустимий символ у назві середовища: {character}", + "Copy Cells" => "Копіювати комірки", + "Fill Series" => "Заповнити ряд", + "Fill Formatting Only" => "Заповнити лише формати", + "Fill Without Formatting" => "Заповнити без форматування", + "Fill Days" => "Заповнити дні", + "Fill Weekdays" => "Заповнити робочі дні", + "Fill Months" => "Заповнити місяці", + "Fill Years" => "Заповнити роки", + "Auto Fill Options" => "Параметри автозаповнення", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/vi.rs b/crates/ui-egui/src/i18n/vi.rs index 93dd959379..100230d026 100644 --- a/crates/ui-egui/src/i18n/vi.rs +++ b/crates/ui-egui/src/i18n/vi.rs @@ -577,6 +577,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char có đối số không phải số {argument}", "\\@char with invalid code point {code}" => "\\@char có điểm mã không hợp lệ {code}", "Invalid environment name character: {character}" => "Ký tự không hợp lệ trong tên môi trường: {character}", + "Copy Cells" => "Sao chép ô", + "Fill Series" => "Điền chuỗi", + "Fill Formatting Only" => "Chỉ điền định dạng", + "Fill Without Formatting" => "Điền không kèm định dạng", + "Fill Days" => "Điền theo ngày", + "Fill Weekdays" => "Điền theo ngày làm việc", + "Fill Months" => "Điền theo tháng", + "Fill Years" => "Điền theo năm", + "Auto Fill Options" => "Tùy chọn tự động điền", + "Series…" => "Chuỗi…", + "Down" => "Xuống", + "Up" => "Lên", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index b57d3292df..36e1d4ccad 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -600,6 +600,18 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "\\@char has non-numeric argument {argument}" => "\\@char 的参数 {argument} 不是数字", "\\@char with invalid code point {code}" => "\\@char 的码位 {code} 无效", "Invalid environment name character: {character}" => "环境名称中有无效字符: {character}", + "Copy Cells" => "复制单元格", + "Fill Series" => "填充序列", + "Fill Formatting Only" => "仅填充格式", + "Fill Without Formatting" => "不带格式填充", + "Fill Days" => "以天数填充", + "Fill Weekdays" => "以工作日填充", + "Fill Months" => "以月填充", + "Fill Years" => "以年填充", + "Auto Fill Options" => "自动填充选项", + "Series…" => "序列…", + "Down" => "向下", + "Up" => "向上", _ => return None, }) } diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d3f94425ce..c32c2c3be0 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-11-15 · **Change:** minor (RaTeX equation parser messages follow the interface language); previously 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); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (fill-handle and Home › Fill menu labels in every catalog); previously minor (RaTeX equation parser messages follow the interface language); previously 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); previously minor (Arabic PDF export no longer fails when a character or the Arabic font is missing; Arabic PDF cells keep their reading direction and RTL pages mirror); previously minor (Ukrainian Chart is Діаграма); previously minor (Diagram and Decorative Text labels, Diagram distinct from Chart); previously minor (CJK fallback baseline alignment); previously minor (Arabic bidi display, editing and cell reading direction; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (Arabic font fallback; missing translations are listed by `cargo xtask i18n-report` and never fail a check); previously minor (number formats honour the `B1`/`B2` calendar prefixes, checked against Excel; earlier: missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks); previously minor (AutoFit estimates Arabic text width from measured glyph widths); previously minor (missing translations are listed by `cargo xtask i18n-report` and never fail a check; Arabic text sorts by its letters, not its vowel marks) · **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, @@ -146,6 +146,7 @@ language (none so far) and of localized function names. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | The fill-handle menus (right-drag menu and Auto Fill Options: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Fill Days, Fill Weekdays, Fill Months, Fill Years, and the button's own name) have a row in all 18 non-English catalogs, and Series…, Down and Up from the Home › Fill menu in the nine catalogs that lacked them; the Ukrainian rows that held English are translated. A test fails when one goes missing (#4458). The translations are AI-assisted and not yet reviewed by native speakers | | 2026-11-15 | minor | The RaTeX equation parser's messages follow the interface language: its 33 fixed messages are catalog keys, and its 33 messages that carry a piece of the source (a command, token, environment name or count) are read back into templates (`i18n::unfill`) whose translation is filled with the same pieces. A message of another shape, such as RaTeX's internal ones or the chemistry parser's, stays English. 66 new keys in every catalog (#4261) | | 2026-11-10 | minor | Ukrainian Chart is `Діаграма`, matching [craft-i18n#211](https://github.com/storytold/craft-i18n/pull/211) and distinct from Diagram (`Схема`) | | 2026-11-10 | minor | Diagram and Decorative Text labels in all 18 non-English catalogs; Diagram never repeats the catalog's chart word (German `Schema`, Ukrainian `Схема`, Romanian `Schemă`), see [feature-names.md](feature-names.md) | From 12e1b5379b47be10ade677a5eb83a8efb6fd12ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Dobo=C5=A1?= Date: Wed, 18 Nov 2026 10:20:40 +0100 Subject: [PATCH 39/81] Keyboard: punctuation shortcuts follow the character the layout types (#1384) (#1385) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Keyboard: punctuation shortcuts follow the character the layout types (#1384) On a Croatian or German keyboard Shift+, types `;`, so Excel inserts the date with Ctrl+Shift+,. GridCraft matched the key's US position and ran Decrease Font Size. Punctuation keys now go by the character typed (translated to the US key and Shift that type it), digits keep their position, and a character egui has no key for (č, ö) still falls back to the position. ribbon::shortcut reads the same key, so Ctrl+Shift+0 typing `=` unhides columns instead of opening Insert, and Ctrl++ opens it. * Keyboard: Cmd+Shift+; on a Mac doesn't insert today's date (review) ribbon::shortcut's Semicolon arm took Shift too, so the US-key mapping turned Cmd+Shift+; (and Cmd+Shift+. on a Croatian or German layout) into the date. Ctrl+Shift+; stays the time. * Keyboard: tests for AZERTY and Czech, and for typing while a cell is edited (#1384) French AZERTY (`;` and `:` unshifted on the US `,` and `.` keys) and Czech (`;` on the US backtick key, `:` Shift+.) give the date and the time with Ctrl. The layout mapping runs only in the grid, which reads no shortcuts while a cell is edited; a test pins that: `;` and `:` typed as Shift+, and Shift+. on a Croatian or German keyboard go into the cell, and the font size stays. --- crates/ui-egui/src/grid/keyboard.rs | 4 +- crates/ui-egui/src/keymap.rs | 56 ++++++- crates/ui-egui/src/ribbon/shortcuts.rs | 3 +- crates/ui-egui/tests/it/keyboard_shortcuts.rs | 138 ++++++++++++++++++ docs/ui-parity.md | 6 +- 5 files changed, 196 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index a852d04c33..92dc9034a3 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -146,7 +146,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res // Ctrl+Shift+letter (⌘⇧letter) runs the macro with that shortcut, unless GridCraft uses it. _ if cmd && shift && !m.alt && crate::macro_ui::run_shortcut(app, key) => {} _ if cmd && !crate::keymap::altgr_text(ctx, m, ctx.os() == egui::os::OperatingSystem::Mac) => { - crate::ribbon::shortcut(app, key, m) + // The same key the English table reads: Ctrl+Shift+, typing `;` is Ctrl+;. + let (key, shift) = crate::keymap::us_key(key, physical_key, shift).unwrap_or((key, shift)); + crate::ribbon::shortcut(app, key, egui::Modifiers { shift, ..m }); } _ => {} } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 5acce9b4d7..462d4cf4d9 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -55,14 +55,54 @@ fn borders(preset: &str) -> Shortcut { Shortcut::Run("home.borders", json!({"preset": preset})) } -/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US -/// layout (as Excel matches Ctrl+Shift+4 rather than the `$` character); `mac` selects the Excel -/// for Mac variants where they differ. Navigation keys go by the logical key: with Num Lock off -/// the numpad's arrows and Page Down report the digit keys (Num6, Num3) as their physical keys. -pub fn lookup(key: Key, physical: Option, m: Modifiers, mac: bool) -> Option { +/// Navigation keys go by the logical key: with Num Lock off the numpad's arrows and Page Down +/// report the digit keys (Num6, Num3) as their physical keys. +fn is_navigation(key: Key) -> bool { use Key::*; - let navigation = matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete); - let key = if navigation { key } else { physical.unwrap_or(key) }; + matches!(key, ArrowLeft | ArrowRight | ArrowUp | ArrowDown | PageUp | PageDown | Home | End | Insert | Delete) +} + +/// The US key and Shift state a symbol or digit key press stands for in the English shortcuts. +/// Digits go by position (Ctrl+Shift+4 is the currency format wherever `$` is). Punctuation keys +/// go by the character the layout types, as Excel does: Shift+, types `;` on a Croatian or German +/// keyboard, so Ctrl+Shift+, is Ctrl+; (today's date) there, and a lone `+` is the US Shift+=. +/// A character egui has no key for (`č`, `ö`, `<`) arrives as the key's position, which stands +/// in. `None` for every other key (letters, navigation, function keys). +pub fn us_key(key: Key, physical: Option, shift: bool) -> Option<(Key, bool)> { + use Key::*; + if is_navigation(key) { + return None; + } + let at = physical?; + let symbol = + |k: Key| matches!(k, Backtick | Minus | Equals | OpenBracket | CloseBracket | Backslash | Semicolon | Quote | Comma | Period | Slash); + match at { + Num0 | Num1 | Num2 | Num3 | Num4 | Num5 | Num6 | Num7 | Num8 | Num9 => Some((at, shift)), + _ if symbol(at) => Some(match key { + // Characters a US keyboard types with Shift. + Colon => (Semicolon, true), + Plus => (Equals, true), + Questionmark => (Slash, true), + Pipe => (Backslash, true), + OpenCurlyBracket => (OpenBracket, true), + CloseCurlyBracket => (CloseBracket, true), + // An unshifted US character, typed here with or without Shift. + _ if key != at && symbol(key) => (key, false), + _ => (key, shift), + }), + _ => None, + } +} + +/// The shortcut for a key press in the grid, if any. `physical` is the key's position on a US +/// layout: digits and letters go by it, punctuation by the character typed ([`us_key`]). `mac` +/// selects the Excel for Mac variants where they differ. Navigation keys go by the logical key. +pub fn lookup(key: Key, physical: Option, m: Modifiers, mac: bool) -> Option { + let (key, shift) = match us_key(key, physical, m.shift) { + Some(us) => us, + None if is_navigation(key) => (key, m.shift), + None => (physical.unwrap_or(key), m.shift), + }; let ctx = LookupContext { key, modifiers: m, @@ -71,7 +111,7 @@ pub fn lookup(key: Key, physical: Option, m: Modifiers, mac: bool) -> Optio alt: m.alt && !m.ctrl && !m.command, ctrl_alt: m.alt && (m.ctrl || m.command), plain: !m.ctrl && !m.command && !m.alt, - shift: m.shift, + shift, mac, }; lookup_number_formats(ctx) diff --git a/crates/ui-egui/src/ribbon/shortcuts.rs b/crates/ui-egui/src/ribbon/shortcuts.rs index cd862cbd9c..2a2d3caecf 100644 --- a/crates/ui-egui/src/ribbon/shortcuts.rs +++ b/crates/ui-egui/src/ribbon/shortcuts.rs @@ -70,7 +70,8 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { None } }, - Key::Semicolon => { + // Ctrl+Shift+; (the time) is in `keymap::lookup`; Cmd+Shift+; on a Mac does nothing. + Key::Semicolon if !shift => { // Insert today's date. let text = app .session diff --git a/crates/ui-egui/tests/it/keyboard_shortcuts.rs b/crates/ui-egui/tests/it/keyboard_shortcuts.rs index f59504dee4..4f45bcb032 100644 --- a/crates/ui-egui/tests/it/keyboard_shortcuts.rs +++ b/crates/ui-egui/tests/it/keyboard_shortcuts.rs @@ -212,6 +212,144 @@ fn alt_down_only_opens_enabled_table_filter_buttons() { } } +/// A key press as a non-US layout reports it: `typed` is the character the layout types (egui's +/// logical key), `at` the key's position named after a US keyboard. +fn key_on_layout(h: &mut Harness, typed: Key, at: Key, m: Modifiers) { + h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m }); + h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m }); + h.run_steps(2); +} + +fn editor_text(h: &Harness) -> Option { + h.state().editor.as_ref().map(|e| e.text.clone()) +} + +fn today(h: &Harness) -> String { + let d = h.state().session.active().unwrap(); + let now = gridcraft_engine::core::date::serial_in_system(d.wb.date_system, gridcraft_engine::calc::now_serial()); + gridcraft_engine::display::format(&gridcraft_engine::core::Value::Number(now.floor()), "m/d/yyyy", &d.wb).text +} + +#[test] +fn symbol_shortcuts_follow_the_character_the_layout_types() { + // Croatian and German keyboards type `;` with Shift+, and `:` with Shift+. (US positions). + // `+` is unshifted, on the US `=` key (Croatian) or `]` key (German); `'` is the US `-` key + // (Croatian) or Shift+# on the US `\` key (German); Shift+0 types `=` on both. + for (layout, plus_at, quote_at, quote_shift) in [("hr", Key::Equals, Key::Minus, false), ("de", Key::CloseBracket, Key::Backslash, true)] { + let mut h = harness(book("C2")); + let size = style(&h, "C2").font.size; + // Ctrl+; (Ctrl+Shift+,): today's date, not Decrease Font Size. + key_on_layout(&mut h, Key::Semicolon, Key::Comma, CTRL_SHIFT); + assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;"); + assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+; changed the font size"); + key(&mut h, Key::Escape, Modifiers::NONE); + // Ctrl+: (Ctrl+Shift+.): the time, not Increase Font Size. + key_on_layout(&mut h, Key::Colon, Key::Period, CTRL_SHIFT); + let time = editor_text(&h).unwrap_or_default(); + assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}"); + assert_eq!(style(&h, "C2").font.size, size, "{layout}: Ctrl+: changed the font size"); + key(&mut h, Key::Escape, Modifiers::NONE); + // Ctrl+': the formula of the cell above. + key_on_layout(&mut h, Key::Quote, quote_at, if quote_shift { CTRL_SHIFT } else { CTRL }); + assert_eq!(editor_text(&h).as_deref(), Some("=A1*2"), "{layout}: Ctrl+'"); + key(&mut h, Key::Escape, Modifiers::NONE); + // Ctrl++: Insert, as Ctrl+Shift+= on a US keyboard. + key_on_layout(&mut h, Key::Plus, plus_at, CTRL); + assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells"), "{layout}: Ctrl++"); + h.state_mut().dialog = None; + // Digits go by position: Ctrl+Shift+0 unhides columns although it types `=`. + h.state_mut().session.run("selection.set", json!({"range": "B:B"})).unwrap(); + h.state_mut().session.run("home.hideColumns", json!({})).unwrap(); + h.state_mut().session.run("selection.set", json!({"range": "A1:C1"})).unwrap(); + key_on_layout(&mut h, Key::Equals, Key::Num0, CTRL_SHIFT); + assert!(h.state().dialog.is_none(), "{layout}: Ctrl+Shift+0 opened {:?}", h.state().dialog.as_ref().map(|d| d.name())); + let d = h.state().session.active().unwrap(); + assert!(!d.wb.active().unwrap().is_col_hidden(1), "{layout}: Ctrl+Shift+0 didn't unhide column B"); + } +} + +#[test] +fn date_and_time_shortcuts_on_azerty_and_czech_keyboards() { + // French AZERTY types `;` and `:` unshifted on the US `,` and `.` keys; Czech QWERTZ types `;` + // unshifted on the US backtick key and `:` with Shift+. (US positions). + for (layout, semi_at, semi_m, colon_m) in [("fr", Key::Comma, CTRL, CTRL), ("cs", Key::Backtick, CTRL, CTRL_SHIFT)] { + let mut h = harness(book("C2")); + let size = style(&h, "C2").font.size; + key_on_layout(&mut h, Key::Semicolon, semi_at, semi_m); + assert_eq!(editor_text(&h), Some(today(&h)), "{layout}: Ctrl+;"); + key(&mut h, Key::Escape, Modifiers::NONE); + key_on_layout(&mut h, Key::Colon, Key::Period, colon_m); + let time = editor_text(&h).unwrap_or_default(); + assert!(time.contains(':') && (time.ends_with("AM") || time.ends_with("PM")), "{layout}: Ctrl+: gave {time:?}"); + assert_eq!(style(&h, "C2").font.size, size, "{layout}: the font size changed"); + } +} + +#[test] +fn layout_keys_type_their_character_in_a_cell_being_edited() { + // While a cell is edited the grid reads no shortcuts, so `;` and `:` (Shift+, and Shift+. on + // Croatian and German keyboards) are typed, and nothing changes the font size. + let mut h = harness(book("C2")); + let size = style(&h, "C2").font.size; + h.input_mut().events.push(Event::Text("x".into())); + h.run_steps(2); + for (typed, at, text) in [(Key::Semicolon, Key::Comma, ";"), (Key::Colon, Key::Period, ":")] { + let m = Modifiers::SHIFT; + h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: true, repeat: false, modifiers: m }); + h.input_mut().events.push(Event::Text(text.into())); + h.input_mut().events.push(Event::Key { key: typed, physical_key: Some(at), pressed: false, repeat: false, modifiers: m }); + h.run_steps(2); + } + assert_eq!(editor_text(&h).as_deref(), Some("x;:")); + assert_eq!(style(&h, "C2").font.size, size); +} + +#[test] +fn us_symbol_shortcuts_keep_their_keys() { + let mut h = harness(book("C2")); + // Ctrl+;: the date. Ctrl+Shift+; arrives as `:` on Windows and as `;` with Shift elsewhere. + key(&mut h, Key::Semicolon, CTRL); + assert_eq!(editor_text(&h), Some(today(&h))); + key(&mut h, Key::Escape, Modifiers::NONE); + for typed in [Key::Colon, Key::Semicolon] { + key_on_layout(&mut h, typed, Key::Semicolon, CTRL_SHIFT); + assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Ctrl+Shift+; as {typed:?}"); + key(&mut h, Key::Escape, Modifiers::NONE); + } + // Ctrl+Shift+, and Ctrl+Shift+. (`<` and `>` have no egui key) change the font size. + let size = style(&h, "C2").font.size; + key(&mut h, Key::Period, CTRL_SHIFT); + assert!(style(&h, "C2").font.size > size); + key(&mut h, Key::Comma, CTRL_SHIFT); + assert_eq!(style(&h, "C2").font.size, size); + // Ctrl+Shift+= arrives as `+`: Insert. + key_on_layout(&mut h, Key::Plus, Key::Equals, CTRL_SHIFT); + assert_eq!(h.state().dialog.as_ref().map(|d| d.name()), Some("insertCells")); + let run = |id: &'static str| Some(Shortcut::Run(id, json!({}))); + // The lookup itself: `;` typed with Shift is Ctrl+; (handled with the Ctrl letters), not the + // key's position (Decrease Font Size). + assert_eq!(lookup(Key::Semicolon, Some(Key::Comma), CTRL_SHIFT, false), None); + assert_eq!(lookup(Key::Colon, Some(Key::Period), CTRL_SHIFT, false), Some(Shortcut::Time)); + assert_eq!(lookup(Key::Comma, Some(Key::Comma), CTRL_SHIFT, false), run("home.decreaseFontSize")); + // A character egui has no key for (`č` on the US `;` key) leaves the position. + assert_eq!(lookup(Key::Semicolon, Some(Key::Semicolon), CTRL_SHIFT, false), Some(Shortcut::Time)); +} + +#[test] +fn cmd_shift_semicolon_on_a_mac_does_not_insert_the_date() { + // The Mac table has Cmd+; (the time) and Control+; (the date), and nothing for Cmd+Shift+;. It + // arrives as `:` on the US `;` key, or on the US `.` key of a Croatian or German keyboard. + let mut h = harness(book("C2")); + h.ctx.set_os(egui::os::OperatingSystem::Mac); + let cmd_shift = Modifiers { shift: true, mac_cmd: true, command: true, ..Modifiers::NONE }; + for at in [Key::Semicolon, Key::Period] { + key_on_layout(&mut h, Key::Colon, at, cmd_shift); + assert_eq!(editor_text(&h), None, "Cmd+Shift+; at {at:?}"); + } + key(&mut h, Key::Semicolon, Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }); + assert!(editor_text(&h).is_some_and(|t| t.ends_with("AM") || t.ends_with("PM")), "Cmd+; is still the time"); +} + /// #1443: Ctrl+Q (also with Shift or Alt, which is what AltGr+Q reports on Windows) must not /// close the window and lose unsaved input; macOS keeps Cmd+Q as the app's Quit. #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2c1e24a0c8..a1debf5fb4 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-11-05 · **Change:** minor (preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-05 · **Change:** minor (punctuation shortcuts follow the keyboard layout's characters; earlier: preserve centered emoji and symbol fallback placement; earlier: preserve leading and trailing blank cell lines; earlier: align wrapped and unwrapped cells; earlier: CJK title baseline regression and mixed-script rendering validation; earlier: form controls: buttons, sliders and spin buttons on the sheet; earlier: Highlight the active cell's row, a global preference in File › Options › General; earlier: a linked cell's menu edits, opens or removes the link; earlier: Display options for this workbook: sheet tabs and scroll bars; earlier: dragging over row or column headers in point mode extends the reference; earlier: a picture on the system clipboard pastes as a floating picture at the active cell with Cmd/Ctrl+V or Paste (#699); earlier: frozen columns keep their text, gridlines and merged borders whole while the sheet scrolls (#2544); earlier: every Paste Special option has its access key; earlier: the Draw tab's live stroke preview uses the pen's colour and thickness; earlier: copy quotes only cells with a tab or line break, as Excel does; earlier: Ctrl+. Next Corner of Selection; earlier: dragging the selection's border onto data asks before replacing it; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis use them, the arrow keys select while a dialog is collapsed and F4 cycles a reference's anchors; earlier: Python cells: Python mode in the formula bar; earlier: Insert › Equation and the equation editor; earlier: every floating object selects, resizes from eight handles and deletes with the keyboard; earlier: Formulas › Error Checking › Trace Error; trace arrows stay through a zoom (#3097); earlier: Page Setup sets the page order, Down, then over or Over, then down, which printing, the print preview, Page Break Preview and Page Layout view follow; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and the Insert Function categories; Esc leaves a File-page text field before closing the view; earlier: checkbox cells print as boxes; Ctrl+arrow and Ctrl+Shift+arrow while pointing a formula reference; editing a hyperlink loads its existing fields; AutoSum over a selected row puts its total to the right; ribbon catalog count 276 / 292) · **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 @@ -105,6 +105,9 @@ Checked against Microsoft's published "Keyboard shortcuts in Excel" (Windows and `keymap.rs` (everything added in #110, with a `lookup` table that tests cover) and `formula_bar.rs` (keys while editing). "Ctrl" means Cmd on a Mac unless the Mac column says otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, wherever `$` is). +Punctuation keys go by the character the keyboard layout types, as in Excel: on a Croatian or German +keyboard Ctrl+Shift+, types `;` and inserts the date, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert. +A character egui has no key for (`č`, `ö`, `<`) falls back to the key's position. | Shortcut (Windows) | Mac | Action | Status | |---|---|---|---| @@ -332,6 +335,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | 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-19 | trivial | While a mouse button is held (a click or a drag selecting cells) the selection outline is drawn on its cells at once instead of gliding after the pointer, which read as lag; keyboard moves still glide | | 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-14 | minor | Punctuation shortcuts follow the character the keyboard layout types, digits keep their position: on a Croatian or German keyboard Ctrl+Shift+, (`;`) inserts the date instead of decreasing the font size, Ctrl+Shift+. (`:`) the time, Ctrl++ opens Insert, Ctrl+' copies the formula above, and Ctrl+Shift+0 (`=`) unhides columns instead of opening Insert | | 2026-10-17 | minor | A Ctrl+Alt+letter key that types a character (a user-defined Windows hotkey such as Ctrl+Alt+A for `ä`) types it instead of running the Ctrl+letter shortcut, e.g. Select All (#1530) | | 2026-10-16 | minor | Right-drag on the fill handle opens the fill menu on release: Copy Cells, Fill Series, Fill Formatting Only, Fill Without Formatting, Series…; Esc cancels the drag or closes the menu without filling | | 2026-10-16 | minor | With the active cell in a Table whose header row is scrolled out of view, the column headings show the header names and their filter buttons in place of the letters (#1423) | From 12dd9aea9ba971381b288479aa645d9cc04e17f4 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Wed, 18 Nov 2026 10:22:30 +0100 Subject: [PATCH 40/81] test: header AutoFit check measures the text as AutoFit did (#2273) * test: header AutoFit check measures the text as AutoFit did table_filter_autofit_works_through_command_and_header_double_click compared the autofitted column with the engine's text-width estimate, but in the app AutoFit measures with the installed fonts (Session::text_width). Where those are narrower than the estimate (a Mac with Carlito, metric-compatible with Calibri), the estimate "overlapped" the filter button and the test failed on main. It now measures with the same function AutoFit used. * test: the header AutoFit UI check measures with the app's fonts, which the app always installs The fallback to the engine's estimate never ran: SheetApp::logic installs the measure before AutoFit. AutoFit on the estimate is covered by the engine's autofit_filter_buttons tests. --- crates/ui-egui/tests/it/header_autofit.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/header_autofit.rs b/crates/ui-egui/tests/it/header_autofit.rs index e8fb393056..a6bce5bf17 100644 --- a/crates/ui-egui/tests/it/header_autofit.rs +++ b/crates/ui-egui/tests/it/header_autofit.rs @@ -287,7 +287,12 @@ fn table_filter_autofit_works_through_command_and_header_double_click() { let rect = geo.cell_rect(sheet, cell); let button = gridcraft_ui_egui::grid::filter_button_rect(&geo, sheet, cell); let style = app.session.active().unwrap().wb.styles.get(sheet.style_id(cell)); - let text_width = gridcraft_engine::cmd::format::approx_text_width("Quarterly Revenue", style.font.size, style.font.bold) * geo.z; + // Measured as AutoFit measured it, with the app's fonts (they differ from machine to + // machine). The app installs them before AutoFit runs; AutoFit without them, on the + // engine's estimate, is `autofit_filter_buttons` in the engine's tests. + let measure = app.session.text_width.as_ref().expect("the app measures text with its fonts"); + let measured = measure("Quarterly Revenue", &style.font, true); + let text_width = measured * geo.z; assert!(rect.left() + text_width + 2.5 * geo.z < button.left(), "heading overlaps filter: zoom={zoom}, double_click={double_click}"); assert_eq!(app.session.active().unwrap().undo.len(), 1); h.state_mut().session.execute("edit.undo", json!({})).unwrap(); From 20c5742f7991dbfc208da1fd3b543f292f030da4 Mon Sep 17 00:00:00 2001 From: Zaxaerith Date: Wed, 18 Nov 2026 17:26:01 +0800 Subject: [PATCH 41/81] fix(web): mark PDF exports in gridcraft:save (#2452) (#2535) * fix(web): distinguish PDF exports in host save messages (#2452) --- apps/gridcraft-web/src/host.rs | 82 +++++++++++++++------- apps/gridcraft-web/src/host_save.rs | 104 ++++++++++++++++++++++++++++ apps/gridcraft-web/src/main.rs | 2 + 3 files changed, 162 insertions(+), 26 deletions(-) create mode 100644 apps/gridcraft-web/src/host_save.rs diff --git a/apps/gridcraft-web/src/host.rs b/apps/gridcraft-web/src/host.rs index 4a7193b739..a59e39a466 100644 --- a/apps/gridcraft-web/src/host.rs +++ b/apps/gridcraft-web/src/host.rs @@ -12,10 +12,10 @@ //! - `gridcraft:open` (from the host): `{ name, bytes }`. It opens like a workbook picked with //! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is //! copied. -//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes }` for every file GridCraft would -//! otherwise download: Save and Save As (an .xlsx workbook) and Export as PDF. The host stores -//! it and reports failures itself. GridCraft doesn't tell the host which saves make a file the -//! document, so `saveAs` is always `false`. +//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes, export }` for every file GridCraft +//! would otherwise download. With `export: false`, the host stores the XLSX workbook; with +//! `export: true`, it stores a separate file (such as a PDF) without replacing the workbook. +//! `saveAs` remains `false`; it does not distinguish Save from Save As here. //! - `gridcraft:dirty` whenever unsaved changes appear or go away, `gridcraft:failed` when the //! app couldn't start. //! @@ -27,16 +27,16 @@ use std::cell::RefCell; use std::rc::Rc; use craft_web_host::web::{FileData, Host, Message}; +use craft_web_host::{Mode, Outgoing, file_name, message_type}; use gridcraft_ui_egui::{Inbox, Services, SheetApp}; +use wasm_bindgen::JsValue; +use crate::host_save::{SaveMessage, sync_saved}; use crate::hostmode::open_name; /// The app id in the host messages (`gridcraft:ready`). const APP: &str = "gridcraft"; -/// Saved files that count as a workbook: the document is then clean under the name it was saved as. -const WORKBOOK_EXTS: &[&str] = &["xlsx"]; - /// The largest workbook taken from the host page, refused before it is copied. const MAX_OPEN_BYTES: u64 = 512 << 20; @@ -46,6 +46,7 @@ const MAX_AUTHOR_CHARS: usize = 200; #[derive(Clone)] pub struct Bridge { host: Rc, + save_target: Rc, /// Names of the files handed to the host since the last frame. saved: Rc>>, } @@ -55,7 +56,19 @@ impl Bridge { /// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app /// with downloads), or a parent on another origin. pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option { - Some(Self { host: Rc::new(Host::connect(APP, canvas)?), saved: Rc::default() }) + let host = Host::connect(APP, canvas)?; + let save_target = match host.mode() { + Mode::Parent => { + // Host::connect already admitted only a same-origin parent. Keep that origin + // as the postMessage target so later navigation can't receive workbook bytes. + let window = web_sys::window()?; + let parent = window.parent().ok().flatten()?; + let origin = window.location().origin().ok()?; + SaveTarget::Parent { parent, origin } + } + Mode::Page => SaveTarget::Page(canvas.clone()), + }; + Some(Self { host: Rc::new(host), save_target: Rc::new(save_target), saved: Rc::default() }) } /// Send saved and exported files to the host instead of downloading them, and hear files @@ -91,20 +104,13 @@ impl Bridge { /// crate does not repeat a state it already reported). pub fn sync(&self, app: &mut SheetApp) { let saved = std::mem::take(&mut *self.saved.borrow_mut()); - if let Some(name) = saved.iter().rev().find(|name| is_workbook(name)) - && let Some(doc) = app.session.active_mut() - { - doc.saved = doc.wb.clone(); - if doc.path.is_none() { - doc.title = name.clone(); - } - } + sync_saved(&saved, app); self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty())); } fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> { - let name = file_name(path); - self.host.post_save(&name, bytes, None, false)?; + let name = file_name(Some(path), "document"); + self.save_target.post(SaveMessage::new(&name, bytes)).map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))?; self.saved.borrow_mut().push(name); Ok(()) } @@ -118,6 +124,38 @@ impl Bridge { } } +/// A save-only adapter: the pinned host crate's `post_save` cannot add app-specific fields. +/// All other messages and transport detection still go through `Host`. +enum SaveTarget { + Parent { parent: web_sys::Window, origin: String }, + Page(web_sys::HtmlCanvasElement), +} + +impl SaveTarget { + fn post(&self, save: SaveMessage<'_>) -> Result<(), JsValue> { + let buffer = js_sys::Uint8Array::from(save.bytes).buffer(); + let kind = message_type(APP, Outgoing::Save.kind()); + let payload = js_sys::Object::new(); + let set = |key, value: JsValue| js_sys::Reflect::set(&payload, &JsValue::from_str(key), &value); + set("name", save.name.into())?; + set("bytes", buffer.clone().into())?; + set("saveAs", JsValue::FALSE)?; + set("export", JsValue::from_bool(save.export))?; + match self { + Self::Parent { parent, origin } => { + set("type", kind.as_str().into())?; + parent.post_message_with_transfer(&payload, origin, &js_sys::Array::of1(&buffer)) + } + Self::Page(canvas) => { + let init = web_sys::CustomEventInit::new(); + init.set_detail(&payload.into()); + let event = web_sys::CustomEvent::new_with_event_init_dict(&kind, &init)?; + canvas.dispatch_event(&event).map(|_| ()) + } + } + } +} + /// The file an open message carries, pushed onto the inbox for the next frame, like a dropped /// file. A host's file is untrusted input: an oversized one is refused before it is copied into /// the app's memory (the data's own length, not the host's claim). @@ -133,11 +171,3 @@ fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData) inbox.lock().unwrap_or_else(|e| e.into_inner()).push((open_name(name), array.to_vec())); ctx.request_repaint(); } - -fn is_workbook(name: &str) -> bool { - name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e))) -} - -fn file_name(path: &str) -> String { - std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()) -} diff --git a/apps/gridcraft-web/src/host_save.rs b/apps/gridcraft-web/src/host_save.rs new file mode 100644 index 0000000000..d8f14c7dca --- /dev/null +++ b/apps/gridcraft-web/src/host_save.rs @@ -0,0 +1,104 @@ +//! Host save payloads and workbook receipts, shared with native regression tests. + +use gridcraft_ui_egui::SheetApp; + +/// Only these outputs replace the editable workbook in the host. +const WORKBOOK_EXTS: &[&str] = &["xlsx"]; + +pub struct SaveMessage<'a> { + pub name: &'a str, + pub bytes: &'a [u8], + pub export: bool, +} + +impl<'a> SaveMessage<'a> { + pub fn new(name: &'a str, bytes: &'a [u8]) -> Self { + // All other outputs are exports, not necessarily PDFs. + Self { name, bytes, export: !is_workbook(name) } + } +} + +fn is_workbook(name: &str) -> bool { + name.rsplit_once('.').is_some_and(|(_, ext)| WORKBOOK_EXTS.iter().any(|e| ext.eq_ignore_ascii_case(e))) +} + +/// Preserve the bridge's existing rule: only a workbook receipt marks the document saved. +pub fn sync_saved(saved: &[String], app: &mut SheetApp) { + if let Some(name) = saved.iter().rev().find(|name| is_workbook(name)) + && let Some(doc) = app.session.active_mut() + { + doc.saved = doc.wb.clone(); + if doc.path.is_none() { + doc.title = name.clone(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gridcraft_engine::Session; + use serde_json::json; + use std::sync::Arc; + + #[test] + fn save_payload_marks_exports_and_preserves_name_and_bytes() { + let bytes = [0, 1, 127, 128, 255]; + for (name, export) in [("finance.xlsx", false), ("finance.XLSX", false), ("finance.pdf", true), ("finance.PDF", true)] { + let message = SaveMessage::new(name, &bytes); + assert_eq!(message.export, export, "{name}"); + assert_eq!(message.name, name); + assert_eq!(message.bytes, bytes.as_slice()); + assert_eq!(message.bytes.as_ptr(), bytes.as_ptr(), "the payload borrows the original bytes"); + } + } + + #[test] + fn other_outputs_are_exports_not_workbook_saves() { + for name in ["finance.csv", "finance.bin", "finance", "finance.xlsx.pdf", "finance.xlsx.bak"] { + assert!(SaveMessage::new(name, &[]).export, "{name}"); + } + assert!(!SaveMessage::new("finance.pdf.xlsx", &[]).export); + } + + fn edited_app() -> Result { + let mut session = Session::new(); + session.new_workbook(); + session.execute("cell.set", json!({"cell": "A1", "input": "42"})).map_err(|e| e.to_string())?; + Ok(SheetApp::new(session, Default::default())) + } + + #[test] + fn pdf_receipts_leave_the_workbook_dirty_and_its_title_unchanged() -> Result<(), String> { + for name in ["finance.pdf", "finance.PDF"] { + let mut app = edited_app()?; + let doc = app.session.active().ok_or("no active document")?; + assert!(doc.is_dirty()); + let title = doc.title.clone(); + let saved = doc.saved.clone(); + sync_saved(&[name.to_string()], &mut app); + let doc = app.session.active().ok_or("no active document")?; + assert!(doc.is_dirty(), "{name}"); + assert!(Arc::ptr_eq(&saved, &doc.saved), "an export must not replace the saved snapshot"); + assert_eq!(doc.title, title); + } + Ok(()) + } + + #[test] + fn workbook_receipts_mark_saved_and_later_exports_do_not_replace_them() -> Result<(), String> { + for name in ["finance.xlsx", "finance.XLSX"] { + let mut app = edited_app()?; + assert!(app.session.active().ok_or("no active document")?.is_dirty()); + sync_saved(&[name.to_string(), "finance.pdf".to_string()], &mut app); + let doc = app.session.active().ok_or("no active document")?; + assert!(!doc.is_dirty()); + assert!(Arc::ptr_eq(&doc.saved, &doc.wb)); + assert_eq!(doc.title, name); + app.session.execute("cell.set", json!({"cell": "A1", "input": "43"})).map_err(|e| e.to_string())?; + sync_saved(&["finance.PDF".to_string()], &mut app); + assert!(app.session.active().ok_or("no active document")?.is_dirty(), "a subsequent export leaves new edits unsaved"); + } + Ok(()) + } +} diff --git a/apps/gridcraft-web/src/main.rs b/apps/gridcraft-web/src/main.rs index 823a68e9b4..a321bb937c 100644 --- a/apps/gridcraft-web/src/main.rs +++ b/apps/gridcraft-web/src/main.rs @@ -26,6 +26,8 @@ mod api; #[cfg(target_arch = "wasm32")] mod host; #[cfg(any(target_arch = "wasm32", test))] +mod host_save; +#[cfg(any(target_arch = "wasm32", test))] mod hostmode; #[cfg(any(target_arch = "wasm32", test))] mod prefs; From 82c97858dff3865209fdf72131af48e9cf47f62d Mon Sep 17 00:00:00 2001 From: bmh129 Date: Wed, 18 Nov 2026 03:26:39 -0600 Subject: [PATCH 42/81] Linux: run on native Wayland again by default (revert #165) (#2789) * Linux: run on native Wayland again by default (revert #165) winit 0.30.13 reported dropped files only on X11. The egui 0.37 migration (#2543) pins storytold/winit, whose patch W15 reports file drops through a per-seat Wayland data device (rust-windowing/winit#4729), so files dragged from the file manager open on native Wayland too. The XWayland default is no longer needed. It also costs a startup crash: winit's X11 backend loads libxkbcommon-x11, which the Linux packages don't depend on. Where it's missing (a Fedora toolbox, minimal installs), GridCraft panics before the window opens: "Library libxkbcommon-x11.so could not be loaded." Checked on GNOME (Wayland, Fedora 44) with a build of main plus other proposed changes, run with GRIDCRAFT_WAYLAND=1 (the path this revert makes the default): an .xlsx and a .csv dragged from Files each open as a workbook, and the app starts without libxkbcommon-x11 installed. This reverts commit 6f0e43c21c5fd71b8ac6c30ac86d447f7671240f. Claude-Session: https://claude.ai/code/session_01Rvu8dWh26U2fsLQMSBQfH8 --- apps/gridcraft/Cargo.toml | 3 --- apps/gridcraft/src/main.rs | 12 +----------- 2 files changed, 1 insertion(+), 14 deletions(-) diff --git a/apps/gridcraft/Cargo.toml b/apps/gridcraft/Cargo.toml index 72f5d08554..572e89fa06 100644 --- a/apps/gridcraft/Cargo.toml +++ b/apps/gridcraft/Cargo.toml @@ -25,9 +25,6 @@ chrono = { workspace = true } # Icon + VERSIONINFO for gridcraft.exe; build.rs only uses it when the target is Windows. winresource = "0.1" -[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "linux"))))'.dependencies] -winit = { version = "0.30", default-features = false, features = ["x11"] } - [target.'cfg(target_os = "linux")'.dependencies] # Retain X11 fallback; draw Wayland client-side controls without bundled title fonts. winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] } diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index f5232b17c6..753c868d76 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -358,21 +358,11 @@ fn main() -> eframe::Result<()> { } let window_builder = viewport.clone(); let options = eframe::NativeOptions { viewport, ..Default::default() }; - #[cfg(unix)] + #[cfg(target_os = "macos")] let mut options = options; // Intel Macs: Metal's compiler aborts on wgpu's indirect-validation shaders (see graphics.rs). #[cfg(target_os = "macos")] graphics::configure_indirect_validation(&mut options, graphics::skips_indirect_validation(true, cfg!(target_arch = "x86_64"))); - // winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file - // manager showed a "no" cursor. Run through XWayland when it's there; GRIDCRAFT_WAYLAND=1 - // keeps the native Wayland backend. - #[cfg(all(unix, not(target_os = "macos")))] - if std::env::var_os("DISPLAY").is_some_and(|d| !d.is_empty()) && std::env::var_os("GRIDCRAFT_WAYLAND").is_none() { - options.event_loop_builder = Some(Box::new(|b| { - use winit::platform::x11::EventLoopBuilderExtX11; - b.with_x11(); - })); - } // Before eframe creates the wgpu instance: Windows starts on DirectX 12, or OpenGL when // DirectX 12 has no GPU driver, and never touches Vulkan unless asked (see graphics.rs). #[cfg(target_os = "windows")] From dbf674ef484e8e15e340f8086b4966e65daa06ed Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:34:32 -0500 Subject: [PATCH 43/81] links: spawn the Windows opener by absolute path (#2176) (#2204) * links: spawn the Windows opener by absolute path (#2176) Explorer is now spawned as %SystemRoot%\explorer.exe (falling back to windir, then C:\Windows; only local drive paths are accepted), so an explorer.exe planted next to the app or in the CWD can't run. Space, ", comma and ^ are percent-encoded before Explorer parses its command line. macOS uses /usr/bin/open; a target starting with - or / is refused on every platform so it can never become an opener option. * links: rename opener enum variant (clippy) `Os::MacOs` -> `Os::Mac` (clippy::enum_variant_names). Also give the desktop-theme watcher's non-Linux `Link` a non-unit type so clippy::let_unit_value stops firing on Windows/macOS. * ui: leave desktop_theme Link alone (covered by #2141) * #2176: say why the Explorer escape still encodes commas --- apps/gridcraft/src/main.rs | 19 ++--- apps/gridcraft/src/opener.rs | 151 +++++++++++++++++++++++++++++++++++ 2 files changed, 161 insertions(+), 9 deletions(-) create mode 100644 apps/gridcraft/src/opener.rs diff --git a/apps/gridcraft/src/main.rs b/apps/gridcraft/src/main.rs index 753c868d76..858c7f9d1d 100644 --- a/apps/gridcraft/src/main.rs +++ b/apps/gridcraft/src/main.rs @@ -17,6 +17,7 @@ mod graphics; mod logging; #[cfg(target_os = "macos")] mod native_menu; +mod opener; mod print; use std::cell::RefCell; @@ -218,16 +219,16 @@ fn open_with_system(target: &str) { log::warn!("refused to open {target:?}: only http, https and mailto links are opened"); return; }; - let target = target.as_str(); - let cmd = if cfg!(target_os = "macos") { - "open" - } else if cfg!(windows) { - "explorer" - } else { - "xdg-open" + // By absolute path where the platform has one (#2176): a bare `explorer` would be looked up + // in the application's directory first. + let env = |key: &str| std::env::var(key).ok(); + let (system_root, windir) = (env("SystemRoot"), env("windir")); + let Some((program, arg)) = opener::opener_command(opener::Os::current(), &target, system_root.as_deref(), windir.as_deref()) else { + log::warn!("refused to open {target:?}: it could be read as an option"); + return; }; - if let Err(e) = std::process::Command::new(cmd).arg(target).spawn() { - log::warn!("{cmd} {target}: {e}"); + if let Err(e) = std::process::Command::new(&program).arg(&arg).spawn() { + log::warn!("{} {arg}: {e}", program.display()); } } diff --git a/apps/gridcraft/src/opener.rs b/apps/gridcraft/src/opener.rs new file mode 100644 index 0000000000..dbe0498e5d --- /dev/null +++ b/apps/gridcraft/src/opener.rs @@ -0,0 +1,151 @@ +//! How a link is handed to the operating system's opener (#2176). +//! +//! The opener is spawned by absolute path where the platform has a fixed one: a bare program name +//! on Windows is searched for in the application's own directory (and the current directory) +//! before System32 and the Windows directory, so an `explorer.exe` planted next to a portable +//! GridCraft would run with the user's session. The target never becomes an option of the opener, +//! and on Windows the characters Explorer's own command-line parser treats specially are +//! percent-encoded. Pure functions, so the tests run on every OS. + +use std::path::PathBuf; + +/// Whose opener to use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Os { + Mac, + Windows, + /// Linux, the BSDs and other freedesktop systems: `xdg-open`. + Other, +} + +impl Os { + pub fn current() -> Os { + if cfg!(target_os = "macos") { + Os::Mac + } else if cfg!(windows) { + Os::Windows + } else { + Os::Other + } + } +} + +/// Used when neither `SystemRoot` nor `windir` holds a usable path. +const DEFAULT_WINDOWS_DIR: &str = "C:\\Windows"; + +/// The Windows directory: `SystemRoot`, else `windir`, else `C:\Windows`. A value is used only +/// when it is a local drive path (`X:\…`) without `..` segments; relative or network values +/// would bring back the search this exists to avoid. +pub fn windows_dir(system_root: Option<&str>, windir: Option<&str>) -> String { + [system_root, windir] + .into_iter() + .flatten() + .map(str::trim) + .find(|d| is_local_drive_path(d)) + .map_or(DEFAULT_WINDOWS_DIR, |d| d.trim_end_matches(['\\', '/'])) + .to_string() +} + +/// `X:\…` or `X:/…` (not the drive-relative `X:` or `X:dir`), with no `..` segment and no quote. +fn is_local_drive_path(d: &str) -> bool { + let mut chars = d.chars(); + let drive = chars.next().is_some_and(|c| c.is_ascii_alphabetic()) && chars.next() == Some(':'); + let rest = chars.as_str(); + let rooted = rest.starts_with(['\\', '/']); + drive && rooted && !d.contains('"') && !rest.split(['\\', '/']).any(|seg| seg == "..") +} + +/// Percent-encodes the characters Explorer's command-line parser (comma-separated switches such +/// as `/select,`), the C runtime's quoting rules and `cmd` treat specially: space, `"`, `,` and +/// `^`. Space, `"` and `^` may not appear unencoded in a URL, so encoding them leaves the address +/// unchanged. A comma may, and RFC 3986 does not treat `%2C` as equivalent to it (a `mailto:` +/// recipient list is comma-separated); it is encoded anyway because Explorer's parser separates +/// switches at commas, and a handler that percent-decodes the address sees the comma again. +pub fn escape_for_explorer(target: &str) -> String { + let mut out = String::with_capacity(target.len()); + for c in target.chars() { + match c { + ' ' => out.push_str("%20"), + '"' => out.push_str("%22"), + ',' => out.push_str("%2C"), + '^' => out.push_str("%5E"), + _ => out.push(c), + } + } + out +} + +/// The program and its single argument that open `target` (already accepted by +/// `links::classify`) on `os`. `None` when the target could be read as an option: it starts with +/// `-` or `/`, or is empty. `xdg-open` takes no `--`, so refusing is the only safe answer. +pub fn opener_command(os: Os, target: &str, system_root: Option<&str>, windir: Option<&str>) -> Option<(PathBuf, String)> { + if target.is_empty() || target.starts_with(['-', '/']) { + return None; + } + Some(match os { + Os::Mac => (PathBuf::from("/usr/bin/open"), target.to_string()), + Os::Windows => { + let exe = format!("{}\\explorer.exe", windows_dir(system_root, windir)); + (PathBuf::from(exe), escape_for_explorer(target)) + } + // Found on PATH: its location differs between distributions and the BSDs. + Os::Other => (PathBuf::from("xdg-open"), target.to_string()), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn windows_opener_is_explorer_in_the_windows_directory() { + let (exe, arg) = opener_command(Os::Windows, "https://a.example/x", Some("C:\\Windows"), None).unwrap_or_default(); + assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe")); + assert_eq!(arg, "https://a.example/x"); + // Never a bare name, whatever the environment says. + for (root, windir) in [(None, None), (Some(""), Some("")), (Some("Windows"), None), (Some(".\\"), Some("explorer"))] { + let (exe, _) = opener_command(Os::Windows, "https://a.example", root, windir).unwrap_or_default(); + assert_eq!(exe, PathBuf::from("C:\\Windows\\explorer.exe"), "{root:?} {windir:?}"); + } + } + + #[test] + fn windows_dir_prefers_system_root_then_windir_then_default() { + assert_eq!(windows_dir(Some("D:\\WINNT\\"), Some("E:\\Win")), "D:\\WINNT"); + assert_eq!(windows_dir(None, Some("E:\\Win")), "E:\\Win"); + assert_eq!(windows_dir(Some("relative\\dir"), Some("e:/win/")), "e:/win"); + assert_eq!(windows_dir(None, None), "C:\\Windows"); + assert_eq!(windows_dir(Some("D:\\"), None), "D:"); + for bad in ["\\\\host\\share", "//host/share", "C:", "C:Windows", "C:\\Windows\\..\\Users\\x", "C:\\\"x", "", " ", "1:\\x"] { + assert_eq!(windows_dir(Some(bad), None), "C:\\Windows", "{bad:?}"); + } + } + + #[test] + fn explorer_switch_characters_are_percent_encoded() { + let (_, arg) = opener_command(Os::Windows, "https://x/,/select,C:\\Windows\\a b\"^", None, None).unwrap_or_default(); + assert_eq!(arg, "https://x/%2C/select%2CC:\\Windows\\a%20b%22%5E"); + assert!(!arg.contains([' ', '"', ',', '^'])); + assert_eq!(escape_for_explorer("mailto:a@b.example?subject=Hi there"), "mailto:a@b.example?subject=Hi%20there"); + // Other platforms get the address as it is. + let (_, arg) = opener_command(Os::Other, "https://x/a,b", None, None).unwrap_or_default(); + assert_eq!(arg, "https://x/a,b"); + } + + #[test] + fn mac_and_freedesktop_openers() { + let (exe, arg) = opener_command(Os::Mac, "https://a.example", None, None).unwrap_or_default(); + assert_eq!((exe, arg.as_str()), (PathBuf::from("/usr/bin/open"), "https://a.example")); + let (exe, _) = opener_command(Os::Other, "mailto:a@b.example", None, None).unwrap_or_default(); + assert_eq!(exe, PathBuf::from("xdg-open")); + } + + #[test] + fn a_target_never_becomes_an_option() { + for os in [Os::Mac, Os::Windows, Os::Other] { + for bad in ["-a", "--help", "-e calc", "/select,C:\\x", "/root,C:\\", ""] { + assert_eq!(opener_command(os, bad, None, None), None, "{os:?} {bad:?}"); + } + } + } +} From bf48def687bf46a4e2529d7e66c4e3c5b427124d Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:35:20 +0100 Subject: [PATCH 44/81] Create new saved files without group/other write permission (#2567) * Create new saved files without group/other write permission Fixes #2519 --- crates/engine/src/io.rs | 6 ++++++ crates/engine/src/io/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/crates/engine/src/io.rs b/crates/engine/src/io.rs index a4c4f63d85..e60efe7f9b 100644 --- a/crates/engine/src/io.rs +++ b/crates/engine/src/io.rs @@ -1055,6 +1055,12 @@ pub fn write_file(path: &str, bytes: &[u8]) -> Result<()> { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } + // A brand-new file gets the restrictive default: no group/other write, whatever the umask. + #[cfg(unix)] + if prior.is_none() { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o644); + } let mut f = opts.open(&tmp).map_err(|e| { let _ = std::fs::remove_file(&tmp); EngineError::Other(format!("{path}: {e}")) diff --git a/crates/engine/src/io/tests.rs b/crates/engine/src/io/tests.rs index d2a4c0888a..9c4127f1da 100644 --- a/crates/engine/src/io/tests.rs +++ b/crates/engine/src/io/tests.rs @@ -78,6 +78,34 @@ fn restored_mode_drops_the_group_and_special_bits_when_the_group_is_lost() { assert_eq!(super::restored_mode(0o104_755, false), 0o705, "setuid is dropped"); } +#[cfg(not(target_arch = "wasm32"))] +#[cfg(unix)] +#[test] +fn fresh_save_drops_group_and_other_write_under_a_permissive_umask() { + use std::os::unix::fs::PermissionsExt; + if std::env::var_os("GRIDCRAFT_UMASK_CHILD").is_none() { + // Re-run this test in a child shell whose umask is 0002. + let exe = std::env::current_exe().unwrap(); + let status = std::process::Command::new("sh") + .arg("-c") + .arg("umask 0002 && exec \"$0\" --exact io::tests::fresh_save_drops_group_and_other_write_under_a_permissive_umask") + .arg(exe) + .env("GRIDCRAFT_UMASK_CHILD", "1") + .status() + .unwrap(); + assert!(status.success()); + return; + } + let dir = std::env::temp_dir().join(format!("gridcraft-fs-safety-umask-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let fresh = dir.join("new.xlsx"); + write_file(fresh.to_str().unwrap(), b"v").unwrap(); + let mode = std::fs::metadata(&fresh).unwrap().permissions().mode() & 0o777; + let _ = std::fs::remove_dir_all(&dir); + assert!(mode & 0o022 == 0, "mode {mode:o}"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn open_refuses_directories_and_unknowable_lengths() { From 272ae54101f87510a1e836b43cf1ee98e68fb8f2 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:35:49 +0100 Subject: [PATCH 45/81] Delete separate rows or columns in one pass (#2385) * Delete separate rows or columns in one pass Fixes #2287 --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/edit/paste_special.rs | 40 ++++++++++---- crates/engine/src/cmd/sheet.rs | 39 +++++++------- crates/engine/src/tests.rs | 59 +++++++++++++++++++++ crates/model/src/store.rs | 38 +++++++++++++ 5 files changed, 148 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 8c7072f520..2ec1cb64f2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -35,7 +35,7 @@ use go_to::go_to_special; #[cfg(test)] use go_to::{GO_TO_MAX_AREAS, GO_TO_RECENT, reference_parts}; use paste_special::paste_special; -pub(crate) use paste_special::{rewrite_all_formulas, rewrite_cell_links, rewrite_python_refs}; +pub(crate) use paste_special::{rewrite_all_formulas_many, rewrite_cell_links, rewrite_python_refs}; use selection::{select_all, select_col, select_region, select_row, selection_move, selection_next, selection_next_corner, selection_set}; pub fn specs() -> Vec { diff --git a/crates/engine/src/cmd/edit/paste_special.rs b/crates/engine/src/cmd/edit/paste_special.rs index 96fed75bc4..ac1a073ecc 100644 --- a/crates/engine/src/cmd/edit/paste_special.rs +++ b/crates/engine/src/cmd/edit/paste_special.rs @@ -566,10 +566,15 @@ fn paste_validations( /// Applies a reference adjustment to every cell formula and defined name in the workbook. pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: &str, e: &gridcraft_formula::adjust::Edit) -> Result<()> { + rewrite_all_formulas_many(wb, target, std::slice::from_ref(e)) +} + +/// [`rewrite_all_formulas`] for several edits applied in order, visiting each formula once. +pub(crate) fn rewrite_all_formulas_many(wb: &mut gridcraft_model::Workbook, target: &str, edits: &[gridcraft_formula::adjust::Edit]) -> Result<()> { use gridcraft_formula::adjust::Edit; // Rows and columns inserted or deleted on the target sheet move its legacy array ranges too // (a cut moves its arrays itself). - let moves_arrays = matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); + let moves_arrays = |e: &Edit| matches!(e, Edit::Insert { .. } | Edit::Delete { .. } | Edit::InsertCells { .. } | Edit::DeleteCells { .. }); for si in 0..wb.sheets.len() { let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); let keys: Vec<(CellRef, std::sync::Arc)> = @@ -577,16 +582,29 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: & if keys.is_empty() { continue; } - let on_target = moves_arrays && host.eq_ignore_ascii_case(target); + let on_target = host.eq_ignore_ascii_case(target); let Some(sheet) = wb.sheet_mut(si) else { continue }; for (c, f) in keys { - // Borrows the tree and copies and prints only the formulas the edit changes. A formula - // the edit leaves alone keeps its stored text, even if that text is not canonical. - let Some(new) = f.with_expr(|x| gridcraft_formula::adjust::adjust_if_changed(x, &host, target, e)) else { continue }; - let array = match f.array { - Some(a) if on_target => crate::cmd::sheet::map_range(a, e), - a => a, + // Borrows the tree and copies and prints only the formulas the edits change. A formula + // the edits leave alone keeps its stored text, even if that text is not canonical. + let Some(new) = f.with_expr(|x| { + let mut cur: Option = None; + for e in edits { + if let Some(n) = gridcraft_formula::adjust::adjust_if_changed(cur.as_ref().unwrap_or(x), &host, target, e) { + cur = Some(n); + } + } + cur + }) else { + continue; }; + let mut array = f.array; + for e in edits { + array = match array { + Some(a) if on_target && moves_arrays(e) => crate::cmd::sheet::map_range(a, e), + a => a, + }; + } let nf = match new { Some(new) => Formula { array, dynamic: f.dynamic, ..Formula::from_expr(new) }, None if array != f.array => Formula { array, ..(*f).clone() }, @@ -600,12 +618,12 @@ pub(crate) fn rewrite_all_formulas(wb: &mut gridcraft_model::Workbook, target: & for n in wb.names.iter_mut() { if let Ok(expr) = gridcraft_formula::parse_name(&n.formula) { // Names are workbook-level: unqualified refs don't occur; qualified ones adjust. - let new = gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e); + let new = edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, "\u{0}", target, e)); n.formula = gridcraft_formula::print(&new); } } - rewrite_cell_links(wb, |host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)); - rewrite_python_refs(wb, &|host, expr| gridcraft_formula::adjust::adjust(expr, host, target, e)) + rewrite_cell_links(wb, |host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e))); + rewrite_python_refs(wb, &|host, expr| edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, host, target, e))) } /// Runs `f` over every reference a floating object holds (a chart's series values, categories, diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 7fda979835..bde0c50590 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -242,15 +242,20 @@ fn shift_sheet_features(sh: &mut Sheet, axis: Axis, at: u32, count: u32, insert: /// Rewrites every formula reference (chart series included), sparkline source and PivotTable /// source for a structural edit on `target`. pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { - cx.edits.push((target.to_string(), e.clone())); + rewrite_many(cx, target, std::slice::from_ref(e)) +} + +/// [`rewrite`] for several edits applied in order, parsing each reference once. +fn rewrite_many(cx: &mut Ctx, target: &str, edits: &[Edit]) -> Result<()> { + cx.edits.extend(edits.iter().map(|e| (target.to_string(), e.clone()))); let wb = &mut cx.wb; - super::edit::rewrite_all_formulas(wb, target, e)?; + super::edit::rewrite_all_formulas_many(wb, target, edits)?; for si in 0..wb.sheets.len() { let host = wb.sheets.get(si).map(|s| s.name.clone()).unwrap_or_default(); let Some(sh) = wb.sheet_mut(si) else { continue }; let fix = |text: &str| -> String { match gridcraft_formula::parse(text) { - Ok(expr) => gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)), + Ok(expr) => gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))), Err(_) => text.to_string(), } }; @@ -263,7 +268,7 @@ pub(super) fn rewrite(cx: &mut Ctx, target: &str, e: &Edit) -> Result<()> { let body = pt.source.trim().trim_start_matches('='); if let Ok(expr) = gridcraft_formula::parse(body) { let before = gridcraft_formula::print(&expr); - let after = gridcraft_formula::print(&gridcraft_formula::adjust::adjust(expr, &host, target, e)); + let after = gridcraft_formula::print(&edits.iter().fold(expr, |expr, e| gridcraft_formula::adjust::adjust(expr, &host, target, e))); if after != before { pt.source = after; } @@ -378,23 +383,21 @@ fn delete_lines(s: &mut Session, p: &Json, axis: Axis) -> Result { let out = edit(s, |cx| { let name = cx.wb.sheet(sheet).map(|s| s.name.clone()).unwrap_or_default(); cx.protection_checked = true; - // Last area first, so the earlier ones keep their positions. - for (at, count) in areas { - { - let sh = cx.sheet_mut(sheet)?; - let block = match axis { - Axis::Rows => RangeRef::rows(at, (at + count - 1).min(MAX_ROWS - 1)), - Axis::Cols => RangeRef::cols(at, (at + count - 1).min(MAX_COLS - 1)), - }; - sh.take_cells(block); - match axis { - Axis::Rows => sh.cells.shift_rows(at + count, -(count as i64)), - Axis::Cols => sh.cells.shift_cols(at + count, -(count as i64)), - } + { + let sh = cx.sheet_mut(sheet)?; + // Cells move once, past every deleted area above or left of them. + let ascending: Vec<(u32, u32)> = areas.iter().rev().copied().collect(); + match axis { + Axis::Rows => sh.cells.delete_rows(&ascending), + Axis::Cols => sh.cells.delete_cols(&ascending), + } + // Last area first, so the earlier ones keep their positions. + for &(at, count) in &areas { shift_sheet_features(sh, axis, at, count, false); } - rewrite(cx, &name, &Edit::Delete { axis, at, count })?; } + let edits: Vec = areas.iter().map(|&(at, count)| Edit::Delete { axis, at, count }).collect(); + rewrite_many(cx, &name, &edits)?; cx.structural = true; Ok(Json::Null) })?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0a64e87a68..cd699bf1c6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -869,6 +869,65 @@ fn deleting_a_multi_area_row_selection_removes_every_area_and_undoes_once() { assert_eq!((v(&s, "A1"), v(&s, "B1"), v(&s, "C1")), (Value::Number(2.0), Value::Number(4.0), Value::Empty)); } +#[test] +#[allow(clippy::disallowed_methods)] // native-only test: timing the two deletes +fn deleting_many_separate_rows_takes_about_as_long_as_one_block() { + // #2287: every 10th row of a 12,000-row sheet, as 1,200 single-row areas. + let (rows, step) = (12_000u32, 10u32); + let values: Vec = (0..rows).map(|r| json!([r, r + 100_000, r + 200_000])).collect(); + let deleted = |r: u32| r >= 1 && (r - 1).is_multiple_of(step); + let list = (0..rows).filter(|&r| deleted(r)).map(|r| format!("{0}:{0}", r + 1)).collect::>().join(","); + let build = || { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("cell.set", json!({"cell": "E1", "input": format!("=SUM(A1:A{rows})")})).unwrap(); + s.execute("cell.set", json!({"cell": "E3", "input": "=B25"})).unwrap(); + s + }; + let mut block = build(); + let t = std::time::Instant::now(); + block.execute("home.deleteRows", json!({"rows": format!("2:{}", rows / step + 1)})).unwrap(); + let block_time = t.elapsed(); + + let mut s = build(); + let t = std::time::Instant::now(); + s.execute("home.deleteRows", json!({"rows": list})).unwrap(); + let separate_time = t.elapsed(); + + let kept: Vec = (0..rows).filter(|&r| !deleted(r)).collect(); + let d = s.doc().unwrap(); + let sh = d.wb.active().unwrap(); + assert_eq!(sh.used_range().unwrap().end.row as usize, kept.len() - 1); + for (i, r) in kept.iter().enumerate() { + assert_eq!(sh.value(CellRef::new(i as u32, 0)), Value::Number(*r as f64)); + assert_eq!(sh.value(CellRef::new(i as u32, 2)), Value::Number((*r + 200_000) as f64)); + } + assert_eq!(s.execute("cell.get", json!({"cell": "E1"})).unwrap()["formula"], format!("=SUM(A1:A{})", kept.len())); + // B25 loses rows 2, 12 and 22 above it; the formula itself moves from E3 to E2. + assert_eq!(s.execute("cell.get", json!({"cell": "E2"})).unwrap()["formula"], "=B22"); + assert!( + separate_time < block_time * 20 + std::time::Duration::from_millis(500), + "separate rows took {separate_time:?}, one block took {block_time:?}" + ); +} + +#[test] +fn deleting_many_separate_columns_matches_per_area_result() { + let mut s = s(); + let values: Vec = (0..50).map(|r| json!((0..40).map(|c| r * 100 + c).collect::>())).collect(); + s.execute("range.setValues", json!({"range": "A1", "values": values})).unwrap(); + s.execute("cell.set", json!({"cell": "A60", "input": "=SUM(A1:AN1)+H2"})).unwrap(); + // Columns B, E, H (refs) and F:G. + s.execute("home.deleteColumns", json!({"cols": "B:B,E:E,H:H,F:G"})).unwrap(); + let kept: Vec = (0..40).filter(|c| ![1, 4, 5, 6, 7].contains(c)).collect(); + for r in 0..50u32 { + for (i, c) in kept.iter().enumerate() { + assert_eq!(s.doc().unwrap().wb.active().unwrap().value(CellRef::new(r, i as u32)), Value::Number((r * 100 + c) as f64)); + } + } + assert_eq!(s.execute("cell.get", json!({"cell": "A60"})).unwrap()["formula"], "=SUM(A1:AI1)+#REF!"); +} + #[test] fn move_columns_reorders_without_overwriting_and_undoes_once() { let mut s = s(); diff --git a/crates/model/src/store.rs b/crates/model/src/store.rs index 21406efa7e..1de9003fef 100644 --- a/crates/model/src/store.rs +++ b/crates/model/src/store.rs @@ -290,6 +290,44 @@ impl CellStore { let moved = self.take_rows(0..=u32::MAX, from..=u32::MAX); self.put_rows(moved.into_iter().map(|(row, cols)| (row, shift_keys(cols, delta)))); } + /// Deletes the rows in `spans` (`(first, count)`, ascending and disjoint) and closes the gaps + /// in one pass: each later cell moves up once by the number of deleted rows above it. + pub fn delete_rows(&mut self, spans: &[(u32, u32)]) { + self.delete_lines(spans, true); + } + /// Column form of [`CellStore::delete_rows`]. + pub fn delete_cols(&mut self, spans: &[(u32, u32)]) { + self.delete_lines(spans, false); + } + fn delete_lines(&mut self, spans: &[(u32, u32)], rows: bool) { + let Some(&(first, _)) = spans.first() else { return }; + // Lines deleted before the end of each span, for mapping a kept line to its new place. + let mut before = Vec::with_capacity(spans.len()); + let mut total = 0u32; + for &(_, count) in spans { + total = total.saturating_add(count); + before.push(total); + } + let map = |v: u32| -> Option { + let i = spans.partition_point(|&(at, _)| at <= v); + let Some(i) = i.checked_sub(1) else { return Some(v) }; + let (at, count) = spans.get(i).copied().unwrap_or_default(); + if v - at < count { None } else { Some(v - before.get(i).copied().unwrap_or_default()) } + }; + let keys: Vec = if rows { + let r = RangeRef::new(CellRef::new(first, 0), CellRef::new(gridcraft_core::MAX_ROWS - 1, gridcraft_core::MAX_COLS - 1)); + self.iter_range(r).map(|(c, _)| c).collect() + } else { + self.iter().filter(|(c, _)| c.col >= first).map(|(c, _)| c).collect() + }; + let moved: Vec<(CellRef, Cell)> = keys.into_iter().filter_map(|c| self.remove(c).map(|cell| (c, cell))).collect(); + for (c, cell) in moved { + let to = if rows { map(c.row).map(|r| CellRef::new(r, c.col)) } else { map(c.col).map(|x| CellRef::new(c.row, x)) }; + if let Some(to) = to { + self.set(to, cell); + } + } + } /// Shifts cells within rows `r0..=r1` and columns `>= from` horizontally (Insert/Delete Cells /// with shift right/left). pub fn shift_cols_in_rows(&mut self, r0: u32, r1: u32, from: u32, delta: i64) { From a3119f57c2e3e1ba23fe11b042444842ddbc4636 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:36:37 -0500 Subject: [PATCH 46/81] xlsx/csv: cap secondary reader allocations (#2159) (#2199) * xlsx/csv: cap secondary reader allocations (#2159) - XML: at most 1M children per element, 16,384 per worksheet row (TooLarge). - Workbook-wide cap of 16M cell elements. - Array-formula ranges indexed by row (budgeted), not scanned per cell. - writes share a 4M budget. - At most 4096 sheets; duplicate names deduplicated with a HashSet. - Pivot: field lists capped, repeated fields used once, labels borrowed. - CSV: fields past MAX_COLS dropped while reading the record. - At most 4M shared strings. - Relationships looked up by id through a HashMap. * xlsx: close the remaining secondary-reader cap gaps (#2159) - CSV: characters of a field past column 16,384 are not stored; quotes, delimiters and line ends in it are still followed. - Pivot: a field list cut at MAX_FIELDS is reported with a warning. - Sheet names: the prefix shortens once the (n) suffix passes (999), so deduplicated names stay within 31 characters. - Rows dropped for a bad row number still charge their elements against MAX_CELLS. - Test Ctx helper gains the fields upstream added. * #2159: describe MAX_CELLS as the reader's own cap calc::eval::MAX_CELLS has the same value but limits one array result, not a workbook. * #2159: warn on capped pivot cache fields, dedupe pivot names through sets A cache cut at 16,384 fields is now reported, as the table field lists are. Axis filters and calculated fields are deduplicated through a set of lower-cased names instead of a scan per field, which was quadratic in the 16,384 fields allowed; the first of names equal but for case still wins. --- crates/xlsx/src/ods.rs | 19 ++++- crates/xlsx/src/pivot/read.rs | 64 +++++++++++---- crates/xlsx/src/read.rs | 113 ++++++++++++++++----------- crates/xlsx/src/sheet_read.rs | 91 ++++++++++++++++++--- crates/xlsx/src/sheet_read/parts.rs | 8 +- crates/xlsx/src/tests/csv_tests.rs | 37 +++++++++ crates/xlsx/src/tests/malformed.rs | 113 +++++++++++++++++++++++++++ crates/xlsx/src/tests/pivot_tests.rs | 62 +++++++++++++++ 8 files changed, 431 insertions(+), 76 deletions(-) diff --git a/crates/xlsx/src/ods.rs b/crates/xlsx/src/ods.rs index 8e3fd40872..1ef65b6beb 100644 --- a/crates/xlsx/src/ods.rs +++ b/crates/xlsx/src/ods.rs @@ -233,6 +233,7 @@ struct Import { text: u64, formats: Vec<(&'static str, StyleId)>, spreadsheet_seen: bool, + names: crate::read::SheetNames, } impl Import { @@ -241,7 +242,20 @@ impl Import { wb.sheets.clear(); let mut report = ReadReport::default(); report.warn("ODS data-only import: formulas become their saved results and will not recalculate. Source formatting, charts, images and other features are not imported. Save a new .xlsx file; ODS saving is not supported."); - Self { wb, report, stack: vec![], sheet: None, row: None, cell: None, cells: 0, merges: 0, text: 0, formats: vec![], spreadsheet_seen: false } + Self { + wb, + report, + stack: vec![], + sheet: None, + row: None, + cell: None, + cells: 0, + merges: 0, + text: 0, + formats: vec![], + spreadsheet_seen: false, + names: Default::default(), + } } fn parse(&mut self, bytes: &[u8]) -> Result<(), IoError> { @@ -317,9 +331,10 @@ impl Import { return Err(IoError::TooLarge("ODS contains more than 1024 sheets".into())); } let original = attr(reader, e, TABLE, b"name")?.unwrap_or_default(); - let mut name = crate::read::SheetNames::of(&self.wb).unique(original.trim_matches('\''), self.wb.sheets.len()); + let mut name = self.names.unique(original.trim_matches('\''), self.wb.sheets.len()); if self.wb.check_sheet_name(&name, None).is_err() { name = self.wb.next_sheet_name(); + self.names.insert(&name); } if name != original { self.report.warn("Some ODS sheet names were shortened or renamed to valid, unique XLSX sheet names."); diff --git a/crates/xlsx/src/pivot/read.rs b/crates/xlsx/src/pivot/read.rs index bce6457a9e..5fd1efbcad 100644 --- a/crates/xlsx/src/pivot/read.rs +++ b/crates/xlsx/src/pivot/read.rs @@ -1,6 +1,6 @@ use super::{ CellRef, Ctx, DateSystem, El, HashMap, IoError, MAX_FIELDS, PivotCalcField, PivotDateGroup, PivotField, PivotFilter, PivotFunc, PivotLayout, - PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet, same, + PivotShowAs, PivotSort, PivotTable, PivotValue, RangeRef, abs_range, func_caption, func_from, number_to_text, quote_sheet, }; // ================================================================ reading @@ -118,8 +118,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option }; let sys = cx.date_system; let mut fields = Vec::new(); + let mut truncated = false; if let Some(cf) = x.child("cacheFields") { - for f in cf.kids("cacheField").take(MAX_FIELDS) { + for f in capped(cf.kids("cacheField"), &mut truncated) { let items = f.child("sharedItems").map(|si| si.children.iter().map(|e| item_label_el(e, sys)).collect()).unwrap_or_default(); let group = f.child("fieldGroup").map(|g| { let base = g.attr_u32("base").map(|b| b as usize); @@ -142,6 +143,9 @@ fn read_cache(cx: &mut Ctx<'_>, part: &str, sheet_name: &str) -> Option }); } } + if truncated { + cx.warn(format!("{part}: cache fields past {MAX_FIELDS} were dropped; its PivotTables may be incomplete")); + } if fields.is_empty() { cx.warn("a PivotTable's cache has no fields; kept as plain cells"); return None; @@ -231,14 +235,25 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option = x.child("pivotFields").map(|p| p.kids("pivotField").collect()).unwrap_or_default(); + // Field lists are capped, and a field is used once (Excel puts a field on one axis, once): + // each use walks the field's items. + // A list cut at the cap is reported, so an incomplete PivotTable can be told apart. + let mut truncated = false; + let pfs: Vec<&El> = x.child("pivotFields").map(|p| capped(p.kids("pivotField"), &mut truncated)).unwrap_or_default(); let pf = |i: usize| pfs.get(i).copied(); - let idx_list = |name: &str, attr: &str| -> Vec { - x.child(name).map(|e| e.children.iter().filter_map(|f| f.attr_i64(attr)).collect()).unwrap_or_default() + let mut used_fields = std::collections::HashSet::new(); + let mut idx_list = |name: &str, attr: &str| -> Vec { + x.child(name) + .map(|e| capped(e.children.iter().filter_map(|f| f.attr_i64(attr)).filter(|&i| i < 0 || used_fields.insert(i)), &mut truncated)) + .unwrap_or_default() }; let row_x = idx_list("rowFields", "x"); let col_x = idx_list("colFields", "x"); - let pages: Vec<&El> = x.child("pageFields").map(|p| p.kids("pageField").collect()).unwrap_or_default(); + let mut page_fields = std::collections::HashSet::new(); + let pages: Vec<&El> = x + .child("pageFields") + .map(|p| capped(p.kids("pageField").filter(|f| f.attr_i64("fld").is_none_or(|i| page_fields.insert(i))), &mut truncated)) + .unwrap_or_default(); // Layout from the first axis field (pivotField defaults: compact and outline on). let first_axis = row_x.iter().chain(col_x.iter()).find(|i| **i >= 0).and_then(|i| pf(*i as usize)); @@ -268,8 +283,11 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option = Vec::new(); + // Lower-cased names of the fields already filtered on an axis, the first of which wins (as + // `same` compares them): scanning the filters for each field would be quadratic. + let mut axis_filtered: std::collections::HashSet = std::collections::HashSet::new(); // (fields, position of Σ Values (`-2`) among them) - let axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec| -> (Vec, Option) { + let mut axis = |cx: &mut Ctx<'_>, list: &[i64], filters: &mut Vec| -> (Vec, Option) { let mut v = Vec::new(); let mut values_at = None; for &i in list { @@ -282,7 +300,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option, x: &El, cache: &CacheIn, id: u32) -> Option = items.iter().filter(|it| !it.flag("h", false)).filter_map(|it| lab(it)).collect(); - if !filters.iter().any(|ff| same(&ff.source_col, &name)) { - filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) }); - } + filters.push(PivotFilter { source_col: name.clone(), selected: Some(shown) }); } } v.push(f); @@ -308,7 +324,7 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option= 0).map(|i| i as usize) else { continue }; let Some((name, _)) = field_ref(cx, cache, i) else { continue }; - let labels = cache.fields.get(i).map(|f| f.labels().to_vec()).unwrap_or_default(); + let labels: &[String] = cache.fields.get(i).map(|f| f.labels()).unwrap_or(&[]); let selected = if let Some(k) = p.attr_u32("item") { labels.get(k as usize).map(|l| vec![l.clone()]) } else { @@ -341,7 +357,8 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option, x: &El, cache: &CacheIn, id: u32) -> Option = pt.calculated_fields.iter().map(|c| c.name.to_lowercase()).collect(); for f in &cache.fields { if let Some(formula) = &f.formula && !f.name.trim().is_empty() - && !pt.calculated_fields.iter().any(|c| same(&c.name, &f.name)) + && calc_names.insert(f.name.to_lowercase()) { let formula = formula.trim(); let formula = if formula.starts_with('=') { formula.to_string() } else { format!("={formula}") }; @@ -394,8 +413,21 @@ fn read_table(cx: &mut Ctx<'_>, x: &El, cache: &CacheIn, id: u32) -> Option(items: impl Iterator, truncated: &mut bool) -> Vec { + let mut v: Vec = items.take(MAX_FIELDS.saturating_add(1)).collect(); + if v.len() > MAX_FIELDS { + v.truncate(MAX_FIELDS); + *truncated = true; + } + v +} diff --git a/crates/xlsx/src/read.rs b/crates/xlsx/src/read.rs index 5ae2a782b3..7c01cb4210 100644 --- a/crates/xlsx/src/read.rs +++ b/crates/xlsx/src/read.rs @@ -46,6 +46,57 @@ pub struct Ctx<'a> { pub known_function: Option<&'a dyn Fn(&str) -> bool>, /// The code of the workbook's Python cells, from its Python part. pub python: crate::python_part::ScriptsIn, + /// Cell elements read so far, across every sheet (capped by `sheet_read::MAX_CELLS`). + pub cells: u64, +} + +/// The most worksheets read from one workbook (as the XLS reader allows). +const MAX_SHEETS: usize = 4096; +/// The most shared strings read from one workbook (as the XLS reader allows): each is an +/// `Arc` of its own, so a hundred million tiny `` would ask for gigabytes. +const MAX_STRINGS: usize = 4_000_000; + +/// Sheet names taken while reading, compared as `Workbook::sheet_index` compares them (ASCII case +/// folded), with the next `(n)` suffix to try for each base, so renaming duplicates stays linear. +#[derive(Default)] +pub(crate) struct SheetNames { + taken: HashSet, + next_suffix: HashMap, +} + +impl SheetNames { + /// Records `name` as taken. + pub(crate) fn insert(&mut self, name: &str) { + self.taken.insert(name.to_ascii_lowercase()); + } + + /// A valid name for the `i`-th sheet based on `name`, not yet taken; it is recorded as taken. + pub(crate) fn unique(&mut self, name: &str, i: usize) -> String { + let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect(); + if base.trim().is_empty() { + base = format!("Sheet{}", i + 1); + } + if self.taken.insert(base.to_ascii_lowercase()) { + return base; + } + let key: String = base.chars().take(25).collect::().to_ascii_lowercase(); + let mut n = self.next_suffix.get(&key).copied().unwrap_or(2); + loop { + // 25 characters of the base, fewer once the suffix grows past ` (999)`, so the name + // stays within 31 characters however many duplicates there are. + let suffix = format!(" ({n})"); + let short: String = base.chars().take(31usize.saturating_sub(suffix.len()).min(25)).collect(); + let candidate = format!("{short}{suffix}"); + n = n.saturating_add(1); + if self.taken.insert(candidate.to_ascii_lowercase()) { + self.next_suffix.insert(key, n); + return candidate; + } + if n == usize::MAX { + return base; + } + } + } } impl Ctx<'_> { @@ -120,6 +171,9 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError> let mut phonetics = Vec::new(); let mut dropped = 0usize; let res = xml::parse_streaming(&b, &["si"], &mut |si| { + if sst.len() >= MAX_STRINGS { + return Err(IoError::TooLarge(format!("the workbook has more than {MAX_STRINGS} shared strings"))); + } let text = xml::rich_text(&si); let raw = si.kids("rPh").count(); let (runs, props) = xml::phonetic_data(&si, &text); @@ -130,8 +184,10 @@ fn read_shared_strings(cx: &mut Ctx<'_>, wb_rels: &[Rel]) -> Result<(), IoError> sst.push(Arc::from(text)); Ok(()) }); - if let Err(e) = res { - cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len())); + match res { + Ok(_) => {} + Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), + Err(e) => cx.warn(format!("shared strings are damaged ({e}); kept {} strings", sst.len())), } if dropped > 0 { cx.warn(format!("shared strings: {dropped} phonetic runs were dropped (bad sb/eb or no reading)")); @@ -267,6 +323,7 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W shared_formula_bytes: 0, known_function, python: Default::default(), + cells: 0, }; let root_rels = cx.pkg.rels("")?; let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into()); @@ -318,11 +375,19 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W // Legacy formula cells per model sheet, rewritten once names and tables are known. let mut legacy_formulas: Vec<(usize, Vec)> = vec![]; let mut pivot_caches = crate::pivot::CachesIn::new(&wb_xml, &wb_rels); - let sheet_els: Vec = wb_xml.child("sheets").map(|s| s.kids("sheet").cloned().collect()).unwrap_or_default(); + let sheet_els: Vec<&El> = wb_xml.child("sheets").map(|s| s.kids("sheet").collect()).unwrap_or_default(); + if sheet_els.len() > MAX_SHEETS { + return Err(IoError::TooLarge(format!("the workbook has more than {MAX_SHEETS} sheets"))); + } + let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(wb_rels.len()); + for r in &wb_rels { + // The first of duplicate ids wins, as a linear search would find it. + rel_by_id.entry(r.id.as_str()).or_insert(r); + } let mut names = SheetNames::default(); for (i, se) in sheet_els.iter().enumerate() { let name = se.attr("name").unwrap_or("").to_string(); - let rel = se.attr("id").and_then(|id| wb_rels.iter().find(|r| r.id == id)).cloned(); + let rel = se.attr("id").and_then(|id| rel_by_id.get(id).copied()).cloned(); let Some(rel) = rel else { cx.warn(format!("sheet \"{name}\" has no part; skipped")); file_to_model.push(None); @@ -476,46 +541,6 @@ pub fn read_xlsx<'a>(bytes: &'a [u8], opts: crate::ReadOptions<'a>) -> Result<(W Ok((wb, cx.report)) } -/// The sheet names an import has assigned so far, for repairing repeated ones. -#[derive(Default)] -pub(crate) struct SheetNames { - /// Assigned names, ASCII-lowercased. - taken: HashSet, - /// For each lowercased stem, the next suffix to try: a file full of repeated names would - /// otherwise retry every occupied suffix for every sheet. - next: HashMap, -} - -impl SheetNames { - pub(crate) fn of(wb: &Workbook) -> Self { - SheetNames { taken: wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect(), next: HashMap::new() } - } - - /// A valid name for the i-th sheet, unique among the names assigned so far, which it joins. - pub(crate) fn unique(&mut self, name: &str, i: usize) -> String { - let mut base: String = name.chars().filter(|c| !matches!(c, ':' | '\\' | '/' | '?' | '*' | '[' | ']')).take(31).collect(); - if base.trim().is_empty() { - base = format!("Sheet{}", i + 1); - } - let name = if self.taken.contains(&base.to_ascii_lowercase()) { - let stem: String = base.chars().take(25).collect(); - let next = self.next.entry(stem.to_ascii_lowercase()).or_insert(2); - let found = (*next..).find(|n| !self.taken.contains(&format!("{stem} ({n})").to_ascii_lowercase())); - match found { - Some(n) => { - *next = n + 1; - format!("{stem} ({n})") - } - None => base, - } - } else { - base - }; - self.taken.insert(name.to_ascii_lowercase()); - name - } -} - /// Strips a sheet qualifier (`'My Sheet'!$A$1` → `$A$1`). fn strip_sheet(s: &str) -> &str { match s.rfind('!') { diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index a3089cab8b..d406c01346 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -134,6 +134,9 @@ fn settle_python_spills_past_budget(st: &RowState, sheet: &mut Sheet) { } } +/// The most cell elements read from one workbook, across its sheets: the reader's own cap. +/// (`calc::eval::MAX_CELLS` has the same value but limits one array result, not a workbook.) +pub(crate) const MAX_CELLS: u64 = 16_000_000; /// Target and tooltip bytes kept for hyperlinks of one sheet, over all cells: the same URL is /// copied for every cell of its range, so length × cells must stay bounded whatever the file. const MAX_HYPERLINK_BYTES: u64 = 8 * 1024 * 1024; @@ -191,12 +194,10 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr let rels = cx.pkg.rels(part)?; let mut sheet = Sheet::new(name); let mut st = RowState::default(); - let res = xml::parse_streaming(&bytes, &["row"], &mut |row| { - read_row(cx, &mut sheet, &mut st, &row); - Ok(()) - }); + let res = xml::parse_streaming(&bytes, &["row"], &mut |row| read_row(cx, &mut sheet, &mut st, &row)); let root = match res { Ok(r) => r, + Err(IoError::TooLarge(m)) => return Err(IoError::TooLarge(m)), Err(e) => { cx.warn(format!("sheet \"{name}\" is damaged ({e}); kept {} rows", st.rows)); El::default() @@ -208,6 +209,12 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr settle_python_spills_past_budget(&st, &mut sheet); drop(bytes); + // Relationships by id: hyperlinks, drawings and tables each look one up. + let mut rel_by_id: HashMap<&str, &Rel> = HashMap::with_capacity(rels.len()); + for r in &rels { + // The first of duplicate ids wins, as a linear search would find it. + rel_by_id.entry(r.id.as_str()).or_insert(r); + } let mut fit_to_page = false; let mut link_budget = LinkBudget::default(); let mut cf_kept_cells = 0u64; @@ -245,7 +252,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_budget), + "hyperlinks" => read_hyperlinks(cx, name, e, &rel_by_id, &mut sheet, &mut link_budget), "autoFilter" => sheet.autofilter = read_autofilter(cx, e), "printOptions" => { sheet.print.gridlines = e.flag("gridLines", false); @@ -319,14 +326,14 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr }); } "drawing" => { - if let Some(rel) = e.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) { + if let Some(rel) = e.attr("id").and_then(|id| rel_by_id.get(id).copied()) { let target = rel.target.clone(); crate::drawing::read_drawing(cx, &target, &mut sheet)?; } } "tableParts" => { for tp in e.kids("tablePart") { - if let Some(rel) = tp.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)) { + if let Some(rel) = tp.attr("id").and_then(|id| rel_by_id.get(id).copied()) { let target = rel.target.clone(); if let Some(x) = cx.optional_xml(&target)? && let Some(mut t) = read_table(cx, &x) @@ -496,19 +503,30 @@ fn read_cols(cx: &Ctx<'_>, e: &El, sheet: &mut Sheet, remaining: &mut u64) -> Re Ok(()) } -fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) { +/// Charges `n` cell elements against the workbook's [`MAX_CELLS`]. +fn charge_cells(cx: &mut Ctx<'_>, n: u64) -> Result<(), IoError> { + cx.cells = cx.cells.saturating_add(n); + if cx.cells > MAX_CELLS { + return Err(IoError::TooLarge(format!("the workbook has more than {MAX_CELLS} cells"))); + } + Ok(()) +} + +/// One ``. Every `` in it counts against [`MAX_CELLS`], also in a row that is dropped +/// for a bad row number: one worksheet part read for many sheets can't parse cells uncounted. +fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) -> Result<(), IoError> { st.rows += 1; let r = match row.attr_u32("r") { Some(r) if r >= 1 => r - 1, Some(_) => { st.dropped += 1; - return; + return charge_cells(cx, row.kids("c").count() as u64); } None => st.next_row, }; if r >= MAX_ROWS { st.dropped += 1; - return; + return charge_cells(cx, row.kids("c").count() as u64); } st.next_row = r + 1; let mut info = LineInfo::default(); @@ -532,6 +550,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) { } let mut next_col = 0u32; for c in row.kids("c") { + charge_cells(cx, 1)?; let pos = match c.attr("r") { Some(a) => match CellRef::parse(a.trim()) { Some(p) => p, @@ -549,6 +568,7 @@ fn read_row(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, row: &El) { next_col = pos.col + 1; read_cell(cx, sheet, st, c, pos); } + Ok(()) } fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos: CellRef) { @@ -929,6 +949,57 @@ mod tests { assert_eq!(parse_iso_datetime("2024-13-01", DateSystem::D1900), None); } + fn ctx(pkg: crate::package::Package<'_>) -> Ctx<'_> { + Ctx { + pkg, + report: Default::default(), + sst: vec![], + phonetics: vec![], + xf_map: vec![], + dxfs: vec![], + palette: vec![], + date_system: DateSystem::D1900, + styles: Default::default(), + persons: Default::default(), + next_id: 1, + num_fmts: Default::default(), + cell_pictures: vec![], + cf_ext_ids: vec![], + known_function: None, + python: Default::default(), + cells: 0, + shared_formula_bytes: 0, + legacy_formulas: vec![], + } + } + + /// #2159: the workbook-wide cell cap refuses the open once passed, across sheets. + #[test] + fn cells_past_the_workbook_cap_are_refused() { + let bytes = crate::tests::minimal(r#"12"#, &[], "", ""); + let pkg = crate::package::Package::open(&bytes).unwrap(); + let mut cx = ctx(pkg); + cx.cells = MAX_CELLS - 2; + let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap(); + assert_eq!(sheet.cells.len(), 2); + assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_)))); + } + + /// #2159: the cells of a row dropped for its row number still count against the cap, so a + /// part read for many sheets can't parse cells uncounted. + #[test] + fn cells_of_dropped_rows_count_against_the_cap() { + let rows = r#"123"#; + let bytes = crate::tests::minimal(rows, &[], "", ""); + let pkg = crate::package::Package::open(&bytes).unwrap(); + let mut cx = ctx(pkg); + let (sheet, _) = read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data").unwrap(); + assert!(sheet.cells.is_empty(), "both rows are dropped"); + assert_eq!(cx.cells, 3); + cx.cells = MAX_CELLS - 2; + assert!(matches!(read_sheet(&mut cx, "xl/worksheets/sheet1.xml", "Data"), Err(IoError::TooLarge(_)))); + } + #[test] fn sqref_keeps_more_than_ten_thousand_ranges() { let sq = (1..=12_000).map(|r| format!("A{r}")).collect::>().join(" "); diff --git a/crates/xlsx/src/sheet_read/parts.rs b/crates/xlsx/src/sheet_read/parts.rs index 309ab4a025..a01bb5481b 100644 --- a/crates/xlsx/src/sheet_read/parts.rs +++ b/crates/xlsx/src/sheet_read/parts.rs @@ -4,12 +4,12 @@ use super::{ from_file, truncate_chars, xml, }; -/// `budget` counts the cells and bytes this sheet's hyperlinks have copied so far, across -/// `` blocks. -pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, budget: &mut LinkBudget) { +/// `rels` maps relationship ids to relationships (the first of duplicate ids). `budget` counts the +/// cells and bytes this sheet's hyperlinks have copied so far, across `` blocks. +pub(super) fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &HashMap<&str, &Rel>, sheet: &mut Sheet, budget: &mut LinkBudget) { for h in e.kids("hyperlink") { let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue }; - let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or(""); + let rel_target = h.attr("id").and_then(|id| rels.get(id)).map(|r| r.target.as_str()).unwrap_or(""); let location = h.attr("location").filter(|l| !l.is_empty()); // Each covered cell gets its own copy of the link: refuse oversized targets before copying. if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET { diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index adf083a978..b4fd000b41 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -360,6 +360,43 @@ fn the_cap_counts_the_bytes_the_cells_hold_and_accepted_exports_keep_every_posit assert_eq!(tabs.len(), 14); } +/// #2159: a record keeps at most one field per sheet column while it is read, not after; the rest +/// of the line is still read through, so the next line starts the next record. +#[test] +fn fields_past_the_last_column_are_not_collected() { + let src = format!("{}last\nnext,row\n", "x,".repeat(100_000)); + let mut records = vec![]; + parse_records(&src, ',', '"', MAX_COLS as usize, |rec| { + records.push(rec); + true + }); + assert_eq!(records.len(), 2); + assert_eq!(records[0].len(), 16_384); + assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]); + // The same through the reader, and a quoted delimiter past the cap doesn't split the line. + let src = format!("{}\"a,\nb\",z\nnext\n", "x,".repeat(20_000)); + let wb = read_csv(src.as_bytes(), &CsvOptions { delimiter: b',', ..CsvOptions::default() }).unwrap(); + assert_eq!(v(&wb, 0, 16_383), Value::text("x")); + assert_eq!(v(&wb, 1, 0), Value::text("next")); + assert_eq!(wb.sheet(0).unwrap().cells.len(), 16_385); +} + +/// #2159: a long field past the last column is skipped character by character, not collected +/// and then thrown away; a quote inside it is a plain character, as in a kept field. +#[test] +fn a_long_field_past_the_last_column_is_not_stored() { + let src = format!("{}{}a\"b,{}\nnext,row\n", "x,".repeat(16_384), "y".repeat(1_000_000), "z".repeat(1_000)); + let mut records = vec![]; + parse_records(&src, ',', '"', MAX_COLS as usize, |rec| { + records.push(rec); + true + }); + assert_eq!(records.len(), 2, "the quote didn't open a quoted field across the line end"); + assert_eq!(records[0].len(), 16_384); + assert!(records[0].iter().all(|f| f == "x")); + assert_eq!(records[1], vec!["next".to_string(), "row".to_string()]); +} + #[test] fn parser_stops_collecting_fields_at_max_cols() { let extra = 50; diff --git a/crates/xlsx/src/tests/malformed.rs b/crates/xlsx/src/tests/malformed.rs index 870ce316d0..71a4709921 100644 --- a/crates/xlsx/src/tests/malformed.rs +++ b/crates/xlsx/src/tests/malformed.rs @@ -280,6 +280,119 @@ fn hostile_formula_text_does_not_overflow_the_stack() { assert_eq!(a_value, gridcraft_core::Value::Number(3.0)); } +/// A one-sheet-per-entry workbook: `names` are the sheet names, every sheet sharing one part. +fn many_sheets(names: &[String]) -> Vec { + let sheets: String = names.iter().enumerate().map(|(i, n)| format!(r#""#, i + 1)).collect(); + let wb = format!( + r#"{sheets}"# + ); + let rels = r#""#; + let sheet = r#""#; + make_zip(&[ + ("[Content_Types].xml", super::CT.as_bytes()), + ("_rels/.rels", super::ROOT_RELS.as_bytes()), + ("xl/workbook.xml", wb.as_bytes()), + ("xl/_rels/workbook.xml.rels", rels.as_bytes()), + ("xl/worksheets/sheet1.xml", sheet.as_bytes()), + ]) +} + +/// #2159: a row of endless `` is not built in memory: the part's kept-element cap +/// ([`crate::xml::MAX_XML_NODES`]) stops it, and the sheet is reported as damaged. +#[test] +fn a_row_wider_than_the_grid_is_refused() { + let row = |n: usize| format!(r#"{}"#, "".repeat(n)); + let (wb, rep) = read_xlsx(&minimal(&row(crate::xml::MAX_XML_NODES + 1), &[], "", "")).unwrap(); + assert!(wb.sheet(0).unwrap().cells.is_empty()); + assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings); + assert!(read_xlsx(&minimal(&row(16_384), &[], "", "")).is_ok()); + // Every other part has the cap too (a merge list of more than a million entries). + let merges = format!("{}", r#""#.repeat(crate::xml::MAX_XML_NODES + 1)); + let (wb, rep) = read_xlsx(&minimal(&merges, &[], "", "")).unwrap(); + assert!(wb.sheet(0).unwrap().merges.is_empty()); + assert!(rep.warnings.iter().any(|w| w.contains("damaged")), "{:?}", rep.warnings); +} + +/// #2159: overlapping `` entries share one budget of column writes. +#[test] +fn overlapping_column_entries_have_a_budget() { + let parts = [("xl/styles.xml", r#""#)]; + let rels = r#""#; + let cols = format!("{}", r#""#.repeat(300)); + assert!(matches!(read_xlsx(&minimal(&cols, &parts, rels, "")), Err(IoError::TooLarge(_)))); + // A normal list reads with no warning. + let (wb, rep) = read_xlsx(&minimal(r#""#, &parts, rels, "")).unwrap(); + assert_eq!(wb.sheet(0).unwrap().cols.len(), 3); + assert!(rep.warnings.is_empty(), "{:?}", rep.warnings); +} + +/// #2159: the sheet count is capped, and renaming duplicate sheet names stays linear. +#[test] +fn sheet_count_is_capped_and_duplicate_names_are_renamed() { + let names: Vec = (0..4097).map(|i| format!("S{i}")).collect(); + assert!(matches!(read_xlsx(&many_sheets(&names)), Err(IoError::TooLarge(_)))); + let dups: Vec = (0..300).map(|i| if i % 2 == 0 { "a".to_string() } else { "A".to_string() }).collect(); + let (wb, _) = read_xlsx(&many_sheets(&dups)).unwrap(); + assert_eq!(wb.sheets.len(), 300); + assert_eq!(wb.sheets[0].name, "a"); + assert_eq!(wb.sheets[1].name, "A (2)"); + assert_eq!(wb.sheets[299].name, "A (300)"); + let distinct: std::collections::HashSet = wb.sheets.iter().map(|s| s.name.to_ascii_lowercase()).collect(); + assert_eq!(distinct.len(), 300); + // The name set alone: thousands of duplicates, with a suffixed name already taken. + let mut taken = crate::read::SheetNames::default(); + assert_eq!(taken.unique("x (3)", 0), "x (3)"); + let got: Vec = (0..4096).map(|i| taken.unique("X", i)).collect(); + assert_eq!(got[0], "X"); + assert_eq!(got[1], "X (2)"); + assert_eq!(got[2], "X (4)"); + assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::>().len(), 4096); + assert_eq!(taken.unique("", 9), "Sheet10"); + // A 25-character name repeated past ` (999)` shortens its prefix so every name fits 31. + let mut taken = crate::read::SheetNames::default(); + let base = "N".repeat(25); + let got: Vec = (0..4096).map(|i| taken.unique(&base, i)).collect(); + assert!(got.iter().all(|n| n.chars().count() <= 31), "{:?}", got.iter().find(|n| n.chars().count() > 31)); + assert_eq!(got[998], format!("{base} (999)")); + assert_eq!(got[999], format!("{} (1000)", "N".repeat(24))); + assert_eq!(got.iter().map(|n| n.to_ascii_lowercase()).collect::>().len(), 4096); +} + +/// #2159: the shared-string count is capped (each string is an allocation of its own). +#[test] +fn too_many_shared_strings_are_refused() { + let sst = |n: usize| format!(r#"{}"#, "".repeat(n)); + let rels = r#""#; + let big = sst(4_000_001); + assert!(matches!(read_xlsx(&minimal("", &[("xl/sharedStrings.xml", &big)], rels, "")), Err(IoError::TooLarge(_)))); + let small = sst(3); + assert!(read_xlsx(&minimal("", &[("xl/sharedStrings.xml", &small)], rels, "")).is_ok()); +} + +/// #2159: hyperlinks find their relationship by id (a map, not a scan per hyperlink); the first +/// of duplicate ids wins, as before. +#[test] +fn hyperlinks_resolve_relationships_by_id() { + let n = 5_000; + let mut rels = String::from(r#""#); + for i in 0..n { + rels.push_str(&format!( + r#""# + )); + } + rels.push_str(r#""#); + rels.push_str(""); + let links: String = (0..n).map(|i| format!(r#""#, i + 1)).collect(); + let body = format!(r#"{links}"#); + let (wb, _) = read_xlsx(&minimal(&body, &[("xl/worksheets/_rels/sheet1.xml.rels", &rels)], "", "")).unwrap(); + let s = wb.sheet(0).unwrap(); + assert_eq!(s.hyperlinks.len(), n); + let link = |a: &str| s.hyperlinks.get(&gridcraft_core::CellRef::parse(a).unwrap()).map(|h| h.target.clone()); + assert_eq!(link("A1").as_deref(), Some("https://example.com/0")); + assert_eq!(link("A5000").as_deref(), Some("https://example.com/4999")); + assert_eq!(link("B1"), None); +} + /// #2173: a hyperlink is copied into every cell it covers, so oversized targets are dropped, /// ScreenTips are cut to 255 characters and the cell cap holds across `` blocks. #[test] diff --git a/crates/xlsx/src/tests/pivot_tests.rs b/crates/xlsx/src/tests/pivot_tests.rs index 155e279405..4489cb441f 100644 --- a/crates/xlsx/src/tests/pivot_tests.rs +++ b/crates/xlsx/src/tests/pivot_tests.rs @@ -545,6 +545,68 @@ fn hostile_pivot_parts_warn_not_panic() { assert!(report.warnings.iter().any(|w| w.contains("index")), "{:?}", report.warnings); } +/// #2159: a field repeated on the axes or as a page field is used once (each use walks the +/// field's items and copied its labels), and the lists are capped. +#[test] +fn repeated_pivot_fields_are_used_once() { + let items: String = (0..2_000).map(|_| r#""#).collect(); + let rows = r#""#.repeat(20_000); + let pages = r#""#.repeat(20_000); + let table = format!( + r#"{items}{rows}{rows}{pages}"# + ); + let (wb, report) = read_xlsx(&with_pivot(&table, Some(GOOD_CACHE))).unwrap(); + let pt = &wb.sheet(0).unwrap().pivots[0]; + assert_eq!(pt.rows.len(), 1, "{:?}", report.warnings); + assert!(pt.columns.is_empty()); + assert_eq!(pt.rows[0].collapsed_items.len(), 2_000); + assert_eq!(pt.filters.iter().filter(|f| f.source_col == "K").count(), 1); + // One page field: the table's range starts two rows above its location. + assert_eq!(pt.last_range, Some(rr("D3:F9"))); +} + +/// #2159: a field list cut at the 16,384-entry cap is reported, so an incomplete PivotTable can be +/// told apart from a complete one. +#[test] +fn capped_pivot_field_lists_warn() { + let fields = r#""#.repeat(16_385); + let table = format!( + r#"{fields}"# + ); + let (_, report) = read_xlsx(&with_pivot(&table, Some(GOOD_CACHE))).unwrap(); + assert!(report.warnings.iter().any(|w| w.contains("field lists past 16384 entries")), "{:?}", report.warnings); + let table = r#""#; + let (_, report) = read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap(); + assert!(!report.warnings.iter().any(|w| w.contains("field lists past")), "{:?}", report.warnings); +} + +/// #2159: a cache cut at 16,384 fields is reported too, as the table field lists are. +#[test] +fn capped_cache_fields_warn() { + let fields = r#""#.repeat(16_385); + let cache = format!( + r#"{fields}"# + ); + let table = r#""#; + let (_, report) = read_xlsx(&with_pivot(table, Some(&cache))).unwrap(); + assert!(report.warnings.iter().any(|w| w.contains("cache fields past 16384")), "{:?}", report.warnings); + let (_, report) = read_xlsx(&with_pivot(table, Some(GOOD_CACHE))).unwrap(); + assert!(!report.warnings.iter().any(|w| w.contains("cache fields past")), "{:?}", report.warnings); +} + +/// #2159: axis filters and calculated fields are deduplicated through a set of lower-cased names; +/// the first of names equal but for case still wins, as with the scan it replaced. +#[test] +fn axis_filters_and_calculated_fields_dedupe_ignoring_case() { + let cache = r#""#; + let table = r#""#; + let (wb, report) = read_xlsx(&with_pivot(table, Some(cache))).unwrap(); + let pt = &wb.sheet(0).unwrap().pivots[0]; + assert_eq!((pt.rows.len(), pt.columns.len()), (1, 1), "{:?}", report.warnings); + assert_eq!(pt.filters, vec![PivotFilter { source_col: "K".into(), selected: Some(vec!["a".into()]) }]); + assert_eq!(pt.calculated_fields, vec![PivotCalcField { name: "Price".into(), formula: "=1".into() }]); +} + #[test] fn cache_found_by_workbook_cache_id() { let rels_extra = r#""#; From 8f8078c134c4f964e9b54d14480794ea2aae9a6a Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:50:37 +0700 Subject: [PATCH 47/81] Fix main's build and tests after the recent merges (#4474) - Import SheetApp in the pivot pane tests. - Move the keyboard owner check out of keyboard() to stay within the complexity limit. - Aim the title bar button helper at the button's own node. Fixes #4473. Signed-off-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/grid/keyboard.rs | 14 ++++++++++---- crates/ui-egui/tests/it/file_menu.rs | 6 ++++-- crates/ui-egui/tests/it/pivot_pane.rs | 2 +- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/grid/keyboard.rs b/crates/ui-egui/src/grid/keyboard.rs index afecce5029..89259ca86f 100644 --- a/crates/ui-egui/src/grid/keyboard.rs +++ b/crates/ui-egui/src/grid/keyboard.rs @@ -2,8 +2,10 @@ use super::geo::Geo; use super::menus::is_checkbox; use super::{CellRef, Drag, Sheet, SheetApp, json}; -/// Grid keyboard handling when no text field has focus. -pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) { +/// Whether something other than the grid owns the keyboard this frame: an editor, a dialog, a +/// message, a menu or another focused widget. Kept out of [`keyboard`] to hold its complexity +/// within the workspace limit. +fn keyboard_elsewhere(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response) -> bool { // Focus left on an editor that no longer exists goes back to the grid. let stale = [egui::Id::unique("gridcraft.cell_editor"), egui::Id::unique("gridcraft.formula_bar"), crate::text_box::editor_id()]; let editing = app.editor.is_some() || app.text_box_editor.is_some(); @@ -14,7 +16,7 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res // An open filter menu owns the keyboard even when a click inside it left focus on nothing (#1516). // So do the fill menu (its Esc closes it, not the copy) and the right-drag that opens it (an // arrow key would move the selection the menu fills from), and a macro's question. - if editing + editing || app.dialog.is_some() || other_focus || app.message.is_some() @@ -22,7 +24,11 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res || app.grid.fill_menu.is_some() || matches!(app.grid.drag, Drag::Fill { menu: true, .. }) || app.macros.question.is_some() - { +} + +/// Grid keyboard handling when no text field has focus. +pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Response, geo: &Geo, sh: &Sheet) { + if keyboard_elsewhere(app, ctx, resp) { return; } if ctx.memory(|m| m.focused()).is_none() { diff --git a/crates/ui-egui/tests/it/file_menu.rs b/crates/ui-egui/tests/it/file_menu.rs index 0bde339447..4ec8aab602 100644 --- a/crates/ui-egui/tests/it/file_menu.rs +++ b/crates/ui-egui/tests/it/file_menu.rs @@ -176,8 +176,10 @@ fn title_bar_button(h: &mut egui_kittest::Harness<'static, SheetApp>, name: &str 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; + // The button's accessible label carries its tooltip, so the node found may be the button + // itself rather than a tooltip at the pointer: aim at the node. + if let Some(node) = h.query_by_label_contains(&tip) { + return node.rect().center(); } x += 6.0; } diff --git a/crates/ui-egui/tests/it/pivot_pane.rs b/crates/ui-egui/tests/it/pivot_pane.rs index 0ac619d3a6..1076e3e143 100644 --- a/crates/ui-egui/tests/it/pivot_pane.rs +++ b/crates/ui-egui/tests/it/pivot_pane.rs @@ -2,7 +2,7 @@ use egui::{Color32, RawInput, Rect, Shape, pos2, vec2}; use gridcraft_engine::Session; -use gridcraft_ui_egui::theme; +use gridcraft_ui_egui::{SheetApp, theme}; use serde_json::json; /// Builds a pivot report at D3 and returns the painted shapes after six frames in the caller's light or dark mode. From aef4ceb10dd62dcd0f06e611485ab32635ba7c58 Mon Sep 17 00:00:00 2001 From: Harrison Booth <73434116+Harrison-Booth@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:39:57 -0600 Subject: [PATCH 48/81] RATE follows Excel's iteration (#2502) fix(functions): RATE follows Excel's iteration RATE used Newton with fallbacks and a bracketing search, so it found roots Excel doesn't and missed the last iterate Excel returns. It now follows Excel's solver as observed with synthetic inputs: a secant iteration from the guess and the guess moved 0.001 toward a larger equation value, at most 200 steps, stopping when a step is under 1e-7 and the equation is within 1e-7 of zero (or as close as its terms allow), with the result more than 1e-7 above -100%. After 200 steps the last iterate is kept if it is within a looser 1e-4. Subnormal steps flush to zero as in Excel. RATE(5,0,-100,0) is now -0.999999409145182 like Excel (was #NUM!), and RATE(4,0,-0.0001,100) is #NUM! like Excel (was 30.62). A guess at or below -1 is #VALUE!. IRR and XIRR keep their solver. RATE test: compare with a relative tolerance, not exact equality ROADMAP: keep the progress log in descending date order RATE: pin Excel's #NUM! for a fractional nper with a guess near -1 --- ROADMAP.md | 2 + crates/functions/src/financial/tests.rs | 76 +++++++++++++++++++++++ crates/functions/src/financial/tvm.rs | 82 ++++++++++++++++++++++--- docs/function-parity.md | 6 +- 4 files changed, 156 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c4ac8517ec..9ba40b023c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -187,6 +187,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-15 | Row auto-fit counts a cell's line breaks only when the cell wraps, as Excel does: a file whose unwrapped cells hold multi-line text no longer opens with tall rows (typing a break still turns wrap on and grows the row) | | 2026-10-14 | Set precision as displayed is applied: with the option on, formula results, spills and numbers typed or reformatted are stored as their number format shows them and formulas calculate from those values; `formulas.calculationOptions` gains `precisionAsDisplayed` (turning it on rounds existing constants; locked constants on a protected sheet keep their value; numbers written to a new sheet are rounded too) (#1343) | | 2026-10-14 | Lookups (MATCH, XMATCH, VLOOKUP, HLOOKUP, XLOOKUP, LOOKUP) compare numbers exactly like Excel, so a computed key such as `=0.1+0.2` no longer finds 0.3; `=` and COUNTIF/SUMIF keep their 15-digit comparison | +| 2026-10-14 | RATE matches Excel's solver: the same last iterate for slowly converging cases (about -100% when the future value is 0, instead of `#NUM!`) and `#NUM!` where Excel's iteration can't reach a very large rate | | 2026-10-14 | Functions: EOMONTH, EDATE, WORKDAY, NETWORKDAYS, YEARFRAC, WEEKNUM, the bond and coupon functions, DISC, BIN2DEC, IM* and the other Analysis ToolPak functions give `#VALUE!` for a reference to more than one cell in a value argument, as Excel 365 does, instead of spilling; array constants and computed arrays still lift | | 2026-10-14 | Protect Sheet on a protected sheet: Home › Format, its keytips (HOP, RPS) and the tab menu now read Unprotect Sheet… and unprotect (straight away without a password); a protected sheet that forbids selecting locked (or unlocked) cells is enforced for clicks, arrows and Go To, and the Protect Sheet dialog has the select options (#1346) | | 2026-10-14 | `.xls` (Excel 97-2003) files open with their formatting: fonts, solid and pattern fills, borders (with diagonals), alignment (rotation, indent, wrap, shrink), locked and hidden cells, the workbook's custom colour palette, its Normal font and its user-defined cell styles | @@ -321,6 +322,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | 2026-10-14 | minor | XLSX dynamic-array `cm` metadata kept on save; progress log row | | 2026-10-14 | minor | Progress log: spill anchor reading its old spill area | | 2026-10-14 | minor | Progress log: formulas reading an array that loses a spill conflict | +| 2026-10-14 | trivial | Progress log: RATE follows Excel's iteration | | 2026-10-13 | trivial | Progress log: More Colors… and Recent Colors in the colour menus (#928) | | 2026-10-13 | minor | Multi-level category axes (read, drawn, written); progress log row | | 2026-10-13 | trivial | Progress log: shared pictures written once on XLSX export (#985) | diff --git a/crates/functions/src/financial/tests.rs b/crates/functions/src/financial/tests.rs index a12e31022e..011d8f3da0 100644 --- a/crates/functions/src/financial/tests.rs +++ b/crates/functions/src/financial/tests.rs @@ -33,6 +33,82 @@ fn tvm() { is_err(ev("CUMIPMT", vec![n(0.01), n(360.0), n(125000.0), n(1.0), n(1.0), n(2.0)]), CellError::Num); } +/// RATE with the given arguments, as a number or an error. +fn rate_of(args: &[f64]) -> Value { + ev("RATE", args.iter().map(|x| n(*x)).collect()) +} + +#[track_caller] +fn rate_is(args: &[f64], expected: f64) { + close_tol(rate_of(args), expected, 1e-15); +} + +/// Expected values observed in Excel 365 with these synthetic inputs. +#[test] +fn rate_follows_excel_iteration() { + // No payments and a zero future value: the answer is -100%, which the iteration + // approaches without reaching. Excel returns the last iterate, bit for bit. + rate_is(&[5.0, 0.0, -100.0, 0.0], -0.999_999_409_145_182_5); + rate_is(&[3.0, 0.0, -50.0, 0.0], -0.999_999_744_782_979_9); + rate_is(&[10.0, 0.0, -1.0, 0.0], -0.999_998_741_101_371_3); + rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, 0.5], -0.999_999_408_783_809_4); + rate_is(&[5.0, 0.0, -100.0, 0.0, 0.0, -0.99], -0.999_999_411_730_630_3); + // Second starting point goes the other way when the equation is positive at the guess. + rate_is(&[5.0, 0.0, 100.0, 0.0], -0.999_999_409_810_240_3); + rate_is(&[5.0, 0.0, -100.0, 1e-29], -0.999_999_260_333_075_4); + rate_is(&[5.0, 0.0, -100.0, 1e4], 1.511_886_431_510_563_3); + rate_is(&[4.0, 0.0, -1.0, 100.0], 2.162_277_660_168_009); + // Within 1e-7 by step but not by value: Excel keeps going. + rate_is(&[5.0, 0.0, -1e25, 0.0], -0.999_999_628_525_605_1); + // 200 steps without converging: the last iterate when it is within 1e-4, else #NUM!. + rate_is(&[20.0, 0.0, -1.0, 0.0], -0.999_112_071_912_539_3); + rate_is(&[36.0, 0.0, -1.0, 0.0, 0.0, -0.994], -0.999_875_315_309_626_9); + is_err(rate_of(&[12.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[25.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[20.0, 0.0, -1e60, 0.0]), CellError::Num); + // Large rates the iteration can't reach are #NUM! in Excel. + is_err(rate_of(&[4.0, 0.0, -0.0001, 100.0]), CellError::Num); + is_err(rate_of(&[5.0, 0.0, -100.0, 1e5]), CellError::Num); + is_err(rate_of(&[10.0, -300.0, 1000.0]), CellError::Num); + // ...but are found from a closer guess. + rate_is(&[4.0, 0.0, -0.1, 100.0, 0.0, 4.0], 4.623_413_251_903_489); + close_tol(rate_of(&[10.0, -300.0, 1000.0, 0.0, 0.0, 0.3]), 0.273_198_424_105_560_4, 1e-12); + // Converging on a rate at or below -100% (or within 1e-7 of it) is #NUM!. + is_err(rate_of(&[1.0, 0.0, -1.0, 0.0]), CellError::Num); + is_err(rate_of(&[10.0, -1000.0, 1000.0]), CellError::Num); + is_err(rate_of(&[1.0, 0.0, -100.0, 1e-5]), CellError::Num); + rate_is(&[1.0, 0.0, -100.0, 2e-5], -0.999_999_8); + is_err(rate_of(&[5.0, 0.0, -1e30, 0.0]), CellError::Num); + is_err(rate_of(&[0.5, 0.0, -1.0, 0.0]), CellError::Num); + // A value that never gets near zero is #NUM!, however small the step. + is_err(rate_of(&[4.0, 0.0, 100.0, 100.0]), CellError::Num); + is_err(rate_of(&[4.0, 0.0, -1e-12, 1e-6]), CellError::Num); + rate_is(&[4.0, 0.0, -1e-14, 1e-8], 0.099_000_000_283_235_72); + // Subnormal steps are flushed to zero. + rate_is(&[3.0, 0.0, -1e-305, 0.0], 0.101); + is_err(rate_of(&[4.0, 0.0, 0.0, 100.0]), CellError::Num); + // Guess at or below -1 is #VALUE!; type is 0 or anything else (1). + is_err(rate_of(&[10.0, -100.0, 1000.0, 0.0, 0.0, -1.0]), CellError::Value); + is_err(rate_of(&[0.0, -100.0, 1000.0]), CellError::Num); + // Excel does not step the second point back to -1: a fractional nper with a guess near -1 is #NUM! + // even though a root exists at -0.99, and the same case from a guess of -0.99 finds it. + is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.9995]), CellError::Num); + is_err(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.5]), CellError::Num); + close_tol(rate_of(&[0.5, 0.0, -1.0, 0.1, 0.0, -0.99]), -0.99, 1e-7); + assert_eq!(rate_of(&[10.0, -100.0, 1000.0, 0.0, 2.0]), rate_of(&[10.0, -100.0, 1000.0, 0.0, 1.0])); + // Ordinary loans, and large amounts that can't get within 1e-7 of zero. + close_tol(rate_of(&[360.0, -1000.0, 150000.0]), 0.005_850_253_376_759_637, 1e-11); + close_tol(rate_of(&[360.0, -1000.0, 150000.0, 0.0, 1.0]), 0.005_898_953_457_098_463, 1e-11); + close_tol(rate_of(&[1000.0, -1e6, 1e8]), 0.009_999_522_655_994_865, 1e-12); + close_tol(rate_of(&[360.0, -1e9, 1.5e11]), 0.005_850_253_376_759_668, 1e-12); + close_tol(rate_of(&[10.0, -50.0, 1000.0]), -0.109_560_293_684_682_5, 1e-14); + // Roots at 0% come out as rounding noise in both, so only the absolute size matters. + match rate_of(&[10.0, -100.0, 1000.0]) { + Value::Number(x) => assert!(x.abs() < 1e-8, "{x}"), + other => panic!("{other:?}"), + } +} + /// PMT within about 4 ULPs of Excel's (Value2 of synthetic probes; libm differs by an ULP across /// platforms). The old `(1 + rate)^nper` form was 25 to 91 ULPs off on these, enough to flip a loan schedule's final `IF(p - SUM(r) > 0, ...)`. #[test] diff --git a/crates/functions/src/financial/tvm.rs b/crates/functions/src/financial/tvm.rs index 872e7cbeb1..d8aa2f9977 100644 --- a/crates/functions/src/financial/tvm.rs +++ b/crates/functions/src/financial/tvm.rs @@ -218,21 +218,85 @@ fn solve_rate(f: impl Fn(f64) -> f64, guess: f64) -> R { Err(CellError::Num) } +/// RATE's equation at rate `r`: the loan and the payments grown to the end of the term, plus +/// `fv`. RATE returns the rate where it is zero. The second value is the size of its terms, to +/// judge how close to zero the first can get in floating point. +fn rate_equation(r: f64, np: f64, pmt: f64, pv: f64, fv: f64, typ: f64) -> (f64, f64) { + if r == 0.0 { + return (pv + pmt * np + fv, pv.abs() + (pmt * np).abs() + fv.abs()); + } + let p = (1.0 + r).powf(np); + let (a, b) = (pv * p, pmt * (1.0 / r + typ) * (p - 1.0)); + (a + b + fv, a.abs() + b.abs() + fv.abs()) +} + +/// Excel works with subnormal numbers flushed to zero: a secant step that underflows doesn't +/// move. Observed with RATE(3,0,-1E-305,0), which is 0.101 (the second starting point). +fn flush_subnormal(x: f64) -> f64 { + if x.abs() < f64::MIN_POSITIVE { 0.0 } else { x } +} + +/// Excel's RATE solver, reconstructed by observing Excel with synthetic inputs (not from its +/// code; its documentation says only "iteration", 20 steps and 0.0000001): +/// +/// - A secant iteration starting at the guess and at the guess moved 0.001 toward a larger +/// value of the equation, for at most 200 steps. +/// - It stops at the first iterate that moved less than 1e-7 and where the equation is within +/// 1e-7 of zero (or as close as its terms allow, for very large amounts). Excel returns that +/// iterate, not the exact root, so a slowly converging case such as no payments and a zero +/// future value (exact answer -100%) gives a rate just above -1. +/// - The result must be above -1 by more than the tolerance; otherwise it is #NUM!. +/// - After 200 steps without that, Excel still returns the last iterate if it is within a +/// looser 1e-4 (step, equation value and distance above -1); otherwise #NUM!. So a root the +/// iteration can't reach (a very large rate) is #NUM! even though it exists. +fn rate_solve(f: impl Fn(f64) -> (f64, f64), guess: f64) -> R { + const STEPS: usize = 200; + const TOL: f64 = 1e-7; + const LOOSE: f64 = 1e-4; + let eval = |x: f64| { + let (y, size) = f(x); + if y.is_finite() { Ok((y, size)) } else { Err(CellError::Num) } + }; + let near_zero = |y: f64, size: f64| y.abs() < TOL || y.abs() <= 1e-12 * size; + let (mut x0, (mut f0, _)) = (guess, eval(guess)?); + let mut x1 = if f0 < 0.0 { guess + 0.001 } else { guess - 0.001 }; + let (mut f1, mut size1) = eval(x1)?; + for _ in 0..STEPS { + let den = flush_subnormal(f1 - f0); + if den == 0.0 { + // The secant is flat: done if the iteration had already settled. + if (x1 - x0).abs() < TOL && near_zero(f1, size1) && x1 - TOL > -1.0 { + return Ok(x1); + } + return Err(CellError::Num); + } + let x2 = x1 - flush_subnormal(f1 * (x1 - x0)) / den; + if !x2.is_finite() { + return Err(CellError::Num); + } + let (f2, size2) = eval(x2)?; + if (x2 - x1).abs() < TOL && near_zero(f2, size2) { + return if x2 - TOL > -1.0 { Ok(x2) } else { Err(CellError::Num) }; + } + (x0, f0, x1, f1, size1) = (x1, f1, x2, f2, size2); + } + if (x1 - x0).abs() < LOOSE && f1.abs() < LOOSE && x1 - LOOSE > -1.0 { + return Ok(x1); + } + Err(CellError::Num) +} + pub(super) fn rate(a: &[Arg], _c: &mut dyn Ctx) -> R { let (np, pmt, pv) = (num(a, 0)?, num(a, 1)?, num(a, 2)?); let (fv, typ, guess) = (opt_num(a, 3, 0.0)?, type_arg(a, 4)?, opt_num(a, 5, 0.1)?); if np <= 0.0 { return Err(CellError::Num); } - let f = |r: f64| { - if r.abs() < 1e-12 { - pv + pmt * np + fv - } else { - let p = (1.0 + r).powf(np); - pv * p + pmt * (1.0 + r * typ) * (p - 1.0) / r + fv - } - }; - num_val(solve_rate(f, guess)?) + // Excel: a guess at or below -100% is #VALUE!, not #NUM!. + if guess <= -1.0 { + return Err(CellError::Value); + } + num_val(rate_solve(|r| rate_equation(r, np, pmt, pv, fv, typ), guess)?) } pub(super) fn npv(a: &[Arg], _c: &mut dyn Ctx) -> R { diff --git a/docs/function-parity.md b/docs/function-parity.md index 608e045e7f..55d4ce49f8 100644 --- a/docs/function-parity.md +++ b/docs/function-parity.md @@ -111,7 +111,10 @@ assertions each, but there is no conformance suite against Excel-computed result reports keep finding edge cases: MIN() with no arguments (#138), COUNTBLANK past the used range (#137, and past 16,384 cells #1010, fixed 10-14 for bounded references), ROUND at 15 digits and DATE(1900,2,29) (fixed 10-09), SUMIF sum-range sizing (fixed 10-09). Statistical distributions and financial functions with iterative solvers (RATE, IRR, -XIRR, YIELD) are the highest-risk for last-digit differences. +XIRR, YIELD) are the highest-risk for last-digit differences. RATE follows Excel's own iteration, reconstructed from observation (secant from the guess and the guess ± 0.001, at most 200 steps, +stop within 1e-7 by step and value, a looser 1e-4 check after 200 steps), so it returns the same +iterate as Excel where convergence is slow (about -100% for `RATE(n,0,-pv,0)`) and `#NUM!` where +Excel's solver gives up (very large rates); roots at 0% differ only by rounding noise (under 1e-7). TEXT() and cell display share `crates/numfmt`; checked against Excel-cached results in number- and text-format test workbooks (352 TEXT cells), all match: @@ -178,6 +181,7 @@ Positive fractional inputs still truncate, and signed zero remains valid. Covere | 2026-10-14 | minor | Set precision as displayed: results, spills and typed or reformatted numbers are stored as their format shows them when the option is on (#1343) | | 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-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-14 | minor | RATE follows Excel's iteration (secant, 200 steps, 1e-7 by step and value): `RATE(5,0,-100,0)` is -0.999999409145182 like Excel instead of `#NUM!`, `RATE(4,0,-0.0001,100)` is `#NUM!` like Excel instead of 30.62 | | 2026-10-13 | minor | Legacy formulas from files (no dynamic-array metadata) evaluate with implicit intersection: cells differing from Excel's cached values 68,964 → 49,866 across 4,224 test-corpus workbooks (none gets more) | | 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-12 | minor | GETPIVOTDATA added: 514 / 523 by name, 505 working | From f8af138f285249a5c9b84732f535bb9cad8feab1 Mon Sep 17 00:00:00 2001 From: neilcawse Date: Wed, 18 Nov 2026 09:13:46 -0500 Subject: [PATCH 49/81] XLSX: read, evaluate and write Excel 2010 conditional formats (#717) XLSX: read, evaluate and write Excel 2010 conditional formats Excel 2010+ keeps conditional format rules whose formulas refer to other sheets only in the worksheet's x14:conditionalFormattings extension, with xm:f formulas and an inline x14:dxf in place of a dxfId. GridCraft skipped the whole extension with a warning. Read: x14 cellIs (every operator, one or two formulas), expression, blanks, errors, duplicate/unique, top 10, above average and time period rules become ordinary rules, with the inline differential format (font, fill, border, number format) and priorities that interleave with the main section's. A data bar's linked extension (the x14:id of a main-section rule) adds no second rule. Other x14 kinds (data bar settings, x14 icon sets) are skipped with a warning naming the kind. Evaluate: cross-sheet references in rule formulas already resolve; an engine test pins cellIs and expression rules against cells on another sheet. Write: a cell-value or formula rule referring to another sheet is written in the x14 extension ({78C0D931-6437-407d-A8EE-F0AAD7539E65}) with an inline x14:dxf and a unique id; other rules stay in the main section. The extension shares one extLst with the sparklines (CF first). Inline number formats get ids styles.xml declares. XLSX: say which x14 conditional format rules stay in the main section Colour scale, data bar and icon set rules are always written in the main section, even when their cfvo formulas refer to other sheets; the parity docs now say so. (This commit first dropped the reader's own x14:id linking; after the rebase onto main, main's data bar linking from #550 is the one path, so only the docs part remains.) XLSX: correct the x14 conditional format provenance and list skipped kinds The file that motivated the x14 conditional format work (watchdog-report.xlsx) was saved by LibreOffice 25.2, not Excel, so nothing observed in Excel backs the earlier commit's statement that Excel 2010+ keeps cross-sheet rules only in the extension. MS-XLSX 2.6.27 (CT_CfRule) allows single-sheet references in xm:f but says nothing about where Excel places such rules; the comments and docs now say the placement follows the LibreOffice-saved file and Excel's own is unverified. MS-XLSX 2.6.27 forbids sheet-range-reference (3-D spans) in xm:f, so a rule with a 3-D span now stays in the main section. The parity docs and gaps list name the x14 kinds read (cellIs, expression, blanks, errors, duplicate/unique, top10, aboveAverage, timePeriod) and those skipped with a warning and lost on save (data bars, icon sets, colour scales, containsText, notContainsText, beginsWith, endsWith). Styles: differential formats keep their cell protection on save dxf_xml, which writes both styles.xml dxfs and inline x14:dxf elements, wrote font, number format, fill, alignment and border but never protection, although read_dxf reads it. A rule whose format unlocked or hid cells lost that on save. It now writes protection after border, the order CT_Dxf requires. XLSX: solid data bars are saved with negatives in the bar colour and no axis, as GridCraft draws them docs: order parity revision history docs: record verified x14 conditional format placement docs: fold the Excel check into the PR's own changelog row instead of a new dated row docs: the Excel check covered cross-sheet expression rules, not cell-value rules Fix differential format serialization Preserve default dxf protection --- crates/engine/src/cf.rs | 37 +++++ crates/xlsx/src/sheet_read.rs | 26 +--- crates/xlsx/src/sheet_read/rules.rs | 215 +++++++++++++++++++-------- crates/xlsx/src/sheet_write.rs | 76 +++++----- crates/xlsx/src/sheet_write/rules.rs | 54 +++++++ crates/xlsx/src/styles.rs | 107 +++++++------ crates/xlsx/src/tests/roundtrip.rs | 138 +++++++++++++++++ crates/xlsx/src/write.rs | 14 +- docs/file-format-parity.md | 4 +- docs/gaps.md | 13 +- 10 files changed, 511 insertions(+), 173 deletions(-) diff --git a/crates/engine/src/cf.rs b/crates/engine/src/cf.rs index c49dffccdd..8129c52f84 100644 --- a/crates/engine/src/cf.rs +++ b/crates/engine/src/cf.rs @@ -737,6 +737,43 @@ mod tests { assert_eq!([look("A1"), look("A2")], [true, false]); } + #[test] + fn rules_compare_with_cells_on_other_sheets() { + let mut s = crate::Session::new(); + s.new_workbook(); + s.execute("range.setValues", json!({"range": "E1", "values": [["Suspended"], ["OK"], ["Terminated"], [7], [3]]})).unwrap(); + let rule = |r: serde_json::Value| json!({"range": "E1:E5", "rule": r}); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$8", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "cellIs", "operator": "equal", "value": "='Vehicle Range'!$A$9", "preset": "redText"})), + ) + .unwrap(); + s.execute( + "home.conditionalFormat", + rule(json!({"type": "expression", "formula": "=AND(ISNUMBER(E1),E1>'Vehicle Range'!$B$1)", "preset": "yellowFill"})), + ) + .unwrap(); + s.execute("home.insertSheet", json!({"name": "Vehicle Range"})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!A8", "values": [["Suspended"], ["Terminated"]]})).unwrap(); + s.execute("range.setValues", json!({"range": "'Vehicle Range'!B1", "values": [[5]]})).unwrap(); + let d = s.doc().unwrap(); + let report = d.wb.sheets.iter().position(|sh| sh.name != "Vehicle Range").unwrap(); + let mut cache = CfCache::new(); + let mut look = |a: &str| cache.look(&d.wb, report, CellRef::parse(a).unwrap()).and_then(|l| l.style).unwrap_or_default(); + let looks = ["E1", "E2", "E3", "E4", "E5"].map(&mut look); + // The cells equal to 'Vehicle Range'!A8 or A9 get the red text. + let red_text = looks[0].font.color; + assert_ne!(red_text, Color::Auto); + let red = |st: &Style| st.font.color == red_text; + let filled = |st: &Style| st.fill.pattern == PatternType::Solid; + assert_eq!(looks.each_ref().map(red), [true, false, true, false, false]); + assert_eq!(looks.each_ref().map(filled), [false, false, false, true, false]); + } #[test] fn text_rules_skip_error_values() { let mut s = crate::Session::new(); diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index d406c01346..35fd4c8818 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -8,7 +8,7 @@ use gridcraft_core::{CellError, CellRef, DateSystem, MAX_COLS, MAX_ROWS, RangeRe use gridcraft_formula::Expr; use gridcraft_model::{ AutoFilter, Cell, CfOperator, CfRule, CfValueKind, Comment, CondFormat, EditRange, ErrorStyle, FilterCriterion, Formula, Hyperlink, LineInfo, - NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Table, TableColumn, TotalsFn, + NoteBox, NoteCorner, Orientation, PageOrder, PasswordHash, Sheet, SheetProtection, Sparkline, SparklineKind, Style, Table, TableColumn, TotalsFn, Validation, ValidationKind, XmlColumnPr, }; @@ -25,7 +25,7 @@ mod rules; pub use parts::{read_autofilter, read_table}; use parts::{read_comments, read_hyperlinks, read_note_shapes, read_threaded}; -use rules::{read_cf, read_validation}; +use rules::{read_cf, read_validation, read_x14_cf}; struct Shared { anchor: CellRef, @@ -344,7 +344,7 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<(Sheet, cr } } } - "extLst" => read_ext(cx, e, &mut sheet), + "extLst" => read_ext(cx, e, &mut sheet, &mut cf_kept_cells), "protectedRanges" => read_protected_ranges(e, &mut sheet), _ => {} } @@ -850,7 +850,7 @@ pub fn parse_sqref(s: Option<&str>) -> Vec { } /// Worksheet extensions: x14 data validations and sparklines. -fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { +fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, cf_kept_cells: &mut u64) { for ext in e.kids("ext") { for c in &ext.children { match c.name.as_str() { @@ -878,23 +878,7 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) { } } } - "conditionalFormattings" => { - let mut skipped = false; - for r in c.kids("conditionalFormatting").flat_map(|f| f.kids("cfRule")) { - let idx = r.attr("id").and_then(|id| cx.cf_ext_ids.iter().find(|(i, _)| i == id)).map(|(_, n)| *n); - match (idx.and_then(|n| sheet.cond_formats.get_mut(n)), r.child("dataBar")) { - (Some(CondFormat { rule: CfRule::DataBar { gradient, .. }, .. }), Some(db)) => { - *gradient = db.flag("gradient", true); - // Only the fill style is modelled; borders, lengths, axis or negative colours are lost. - skipped |= db.attrs.iter().any(|(k, _)| k != "gradient") || db.children.iter().any(|k| k.name != "cfvo"); - } - _ => skipped = true, - } - } - if skipped { - cx.warn("some Excel 2010 conditional format extensions were skipped"); - } - } + "conditionalFormattings" => read_x14_cf(cx, c, sheet, cf_kept_cells), _ => {} } } diff --git a/crates/xlsx/src/sheet_read/rules.rs b/crates/xlsx/src/sheet_read/rules.rs index c3a3f04f65..b985953c9c 100644 --- a/crates/xlsx/src/sheet_read/rules.rs +++ b/crates/xlsx/src/sheet_read/rules.rs @@ -1,5 +1,5 @@ use super::{ - CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Validation, ValidationKind, from_file, + CfOperator, CfRule, CfValueKind, CondFormat, Ctx, El, ErrorStyle, MAX_COND_CELLS, RangeRef, Sheet, Style, Validation, ValidationKind, from_file, parse_sqref, read_color, }; @@ -57,79 +57,164 @@ pub(super) fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, kept_cells: & for r in e.kids("cfRule") { let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default()); let formulas: Vec = r.kids("formula").map(|f| from_file(f.text.trim())).collect(); - let f0 = formulas.first().cloned().unwrap_or_default(); - let text = r.attr("text").unwrap_or("").to_string(); // The x14 id that links a data bar to its Excel 2010 extension (solid fill lives there). let ext_id = r.child("extLst").and_then(|l| l.kids("ext").find_map(|x| x.child("id"))).map(|i| i.text.trim().to_string()).filter(|i| !i.is_empty()); - let rule = match r.attr("type").unwrap_or("") { - "cellIs" => CfRule::CellIs { op: cf_op(r.attr("operator")), a: f0, b: formulas.get(1).cloned(), style }, - "expression" => CfRule::Expression { formula: f0, style }, - "containsText" => CfRule::ContainsText { text, style }, - "notContainsText" => CfRule::NotContainsText { text, style }, - "beginsWith" => CfRule::BeginsWith { text, style }, - "endsWith" => CfRule::EndsWith { text, style }, - "containsBlanks" => CfRule::Blanks { style }, - "notContainsBlanks" => CfRule::NoBlanks { style }, - "containsErrors" => CfRule::Errors { style }, - "notContainsErrors" => CfRule::NoErrors { style }, - "duplicateValues" => CfRule::Duplicate { style }, - "uniqueValues" => CfRule::Unique { style }, - "top10" => { - CfRule::Top10 { bottom: r.flag("bottom", false), percent: r.flag("percent", false), rank: r.attr_u32("rank").unwrap_or(10), style } - } - "aboveAverage" => CfRule::AboveAverage { - below: !r.flag("aboveAverage", true), - equal: r.flag("equalAverage", false), - std_dev: r.attr_u32("stdDev").unwrap_or(0).min(3) as u8, - style, - }, - "timePeriod" => CfRule::TimePeriod { period: r.attr("timePeriod").unwrap_or("today").to_string(), style }, - "colorScale" => { - let Some(cs) = r.child("colorScale") else { continue }; - let colors = cs.kids("color").map(|c| read_color(c, &cx.palette)); - CfRule::ColorScale { stops: cfvos(cs).into_iter().zip(colors).collect() } - } - "dataBar" => { - let Some(db) = r.child("dataBar") else { continue }; - let v = cfvos(db); - CfRule::DataBar { - min: v.first().cloned().unwrap_or(CfValueKind::Min), - max: v.get(1).cloned().unwrap_or(CfValueKind::Max), - color: db.child("color").map(|c| read_color(c, &cx.palette)).unwrap_or_default(), - gradient: true, - show_value: db.flag("showValue", true), + let ty = r.attr("type").unwrap_or(""); + match cf_rule(cx, r, ty, formulas, style) { + Some(rule) => { + if !push_cf(cx, sheet, &ranges, block_cells, r, rule, kept_cells) { + break; + } + if let Some(id) = ext_id { + cx.cf_ext_ids.push((id, sheet.cond_formats.len() - 1)); } } - "iconSet" => { - let Some(is) = r.child("iconSet") else { continue }; - CfRule::IconSet { - set: is.attr("iconSet").unwrap_or("3TrafficLights1").to_string(), - thresholds: cfvos(is), - reverse: is.flag("reverse", false), - show_value: is.flag("showValue", true), - } + None if matches!(ty, "colorScale" | "dataBar" | "iconSet") => {} + None => cx.warn(format!("conditional format type \"{ty}\" is not supported")), + } + } +} + +fn push_cf(cx: &mut Ctx<'_>, sheet: &mut Sheet, ranges: &[RangeRef], block_cells: u64, r: &El, rule: CfRule, kept_cells: &mut u64) -> bool { + let total = kept_cells.saturating_add(block_cells); + if total > MAX_COND_CELLS { + cx.warn(format!("conditional formats past {MAX_COND_CELLS} kept range cells were dropped")); + return false; + } + *kept_cells = total; + sheet.cond_formats.push(CondFormat { + ranges: ranges.to_vec(), + rule, + priority: r.attr_u32("priority").unwrap_or(0), + stop_if_true: r.flag("stopIfTrue", false), + }); + true +} + +/// The rule of a `cfRule` (main namespace or x14) of type `ty`, given its formulas and +/// differential style; `None` for an unknown type or a scale, bar or icon set without its body. +fn cf_rule(cx: &Ctx<'_>, r: &El, ty: &str, formulas: Vec, style: Box