From fcb42c3d8e42d93f1a4557abb359eed355de1450 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Mon, 12 Oct 2026 13:50:03 +0300 Subject: [PATCH 001/425] i18n(ru): translate 547 more labels, dialog strings and tooltips The Russian catalog had 318 entries; every label, dialog string and tooltip that another catalog already translates (including the open Czech, Polish, Turkish and Spanish-dialog PRs) now has a Russian entry too: 865 in all. Terminology follows the names Excel uses in its Russian interface; the Paste Special access letters stay Latin, as in the Spanish catalog. --- crates/ui-egui/src/i18n/ru.rs | 567 ++++++++++++++++++++++++++++++++++ 1 file changed, 567 insertions(+) diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index c8f0445d8c..850ad4af64 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -393,6 +393,573 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", + " (password)" => " (пароль)", + " (password, unlocked)" => " (пароль, разблокировано)", + "$ English (United States)" => "$ английский (США)", + "'{file}' is protected." => "Файл «{file}» защищён.", + "(No suggestions)" => "(Нет вариантов)", + "(unnamed)" => "(без имени)", + "+ Add Level" => "+ Добавить уровень", + "100% Stacked Bar" => "Нормированная линейчатая", + "100% Stacked Column" => "Нормированная гистограмма", + "A clean-room, open-source, Rust-native spreadsheet. Part of ArtCraft." => { + "Электронные таблицы с открытым исходным кодом, написанные с нуля на Rust. Часть ArtCraft." + } + "A to Z" => "От А до Я", + "About" => "О программе", + "About GridCraft" => "О программе GridCraft", + "Accessibility" => "Специальные возможности", + "Action" => "Действие", + "Action Journal" => "Журнал действий", + "Add" => "Добавить", + "Add Chart Element" => "Добавить элемент диаграммы", + "Add subtotal to (columns, e.g. C,D):" => "Добавить итоги по (столбцы, например C,D):", + "Add to Dictionary" => "Добавить в словарь", + "Add-in and Automation" => "Надстройки и автоматизация", + "Agent Control" => "Управление агентами", + "Aggregate duplicates using" => "Объединять повторы с помощью", + "Align Left" => "Выровнять по левому краю", + "Align Right" => "Выровнять по правому краю", + "Alignment" => "Выравнивание", + "All" => "Все", + "All Charts" => "Все диаграммы", + "All done. We made {count} replacements." => "Готово. Выполнено замен: {count}.", + "All except borders" => "Без рамки", + "Allow" => "Разрешить", + "Allow all users of this sheet to:" => "Разрешить всем пользователям этого листа:", + "Alpha:" => "Альфа:", + "Analysis Tools" => "Инструменты анализа", + "Anova: Single Factor" => "Однофакторный дисперсионный анализ", + "Any value" => "Любое значение", + "Area" => "С областями", + "At each change in (column letter):" => "При каждом изменении в (буква столбца):", + "Automation in this workbook. GridCraft runs its own scripts; a file's VBA project is preserved but not executed." => { + "Автоматизация в этой книге. GridCraft выполняет собственные сценарии; проект VBA из файла сохраняется, но не выполняется." + } + "Average" => "Среднее", + "Background Color:" => "Цвет фона:", + "Before sheet (position, 0 = first):" => "Перед листом (позиция, 0 = первый):", + "Bin Range (blank for automatic bins):" => "Интервал карманов (пусто — автоматически):", + "Blanks" => "Пустые ячейки", + "Bold" => "Полужирный", + "Border" => "Граница", + "Bottom" => "Нижняя", + "Bottom Align" => "Выровнять по нижнему краю", + "Bottom margin (in):" => "Нижнее поле (дюймы):", + "By Changing Variable Cells:" => "Изменяя ячейки переменных:", + "By changing cell:" => "Изменяя значение ячейки:", + "Calculate Now (F9)" => "Пересчёт (F9)", + "Calculate Sheet (⇧F9)" => "Произвести вычисления на листе (⇧F9)", + "Calculation Options" => "Параметры вычислений", + "Cancel" => "Отмена", + "Category:" => "Категория:", + "Cell Color" => "Цвет ячейки", + "Cell Styles" => "Стили ячеек", + "Cell Values" => "Значения ячеек", + "Center Across Selection" => "По центру выделения", + "Change" => "Заменить", + "Change All" => "Заменить все", + "Change Chart Type" => "Изменить тип диаграммы", + "Chart" => "Диаграмма", + "Chart Title" => "Название диаграммы", + "Chart data range:" => "Диапазон данных для диаграммы:", + "Check Accessibility" => "Проверка читаемости", + "Choose a PNG or JPEG no larger than 16 MB." => "Выберите файл PNG или JPEG размером не более 16 МБ.", + "Clear Filter" => "Очистить фильтр", + "Clustered Bar" => "Линейчатая с группировкой", + "Clustered Column" => "Гистограмма с группировкой", + "Color:" => "Цвет:", + "Column Width" => "Ширина столбца", + "Column chart" => "Гистограмма", + "Column or Bar" => "Гистограмма или линейчатая", + "Column width (characters):" => "Ширина столбца (символы):", + "Column widths" => "Ширины столбцов", + "Columns" => "Столбцы", + "Columns (blank = all, e.g. A,C):" => "Столбцы (пусто = все, например A,C):", + "Combo" => "Комбинированная", + "Comma" => "Запятая", + "Comment:" => "Примечание:", + "Comments and notes (C)" => "Примечания и заметки (C)", + "Comments pane" => "Область примечаний", + "Compatibility" => "Совместимость", + "Conditional Formatting Rules Manager" => "Диспетчер правил условного форматирования", + "Conditional formats" => "Условные форматы", + "Confidence Level (%):" => "Уровень надёжности (%):", + "Confidence Level for Mean (%), blank for none:" => "Уровень надёжности для среднего (%), пусто — нет:", + "Confidence interval" => "Доверительный интервал", + "Confidence level (%):" => "Уровень надёжности (%):", + "Constant is Zero" => "Константа — ноль", + "Contributors" => "Участники", + "Convert Text to Columns" => "Распределение текста по столбцам", + "Convert the last ink stroke to a shape" => "Преобразовать последний рукописный штрих в фигуру", + "Convert to Range" => "Преобразовать в диапазон", + "Copy" => "Копировать", + "Correlation" => "Корреляция", + "Count" => "Количество", + "CountA" => "Количество значений", + "Covariance" => "Ковариация", + "Create Forecast Worksheet" => "Создание листа прогноза", + "Create Sparklines" => "Создание спарклайнов", + "Create a copy" => "Создать копию", + "Cube" => "Куб", + "Cumulative Percentage" => "Интегральный процент", + "Current region" => "Текущая область", + "Custom (%):" => "Другой (%):", + "Custom Sort" => "Настраиваемая сортировка", + "Cut" => "Вырезать", + "Damping factor:" => "Фактор затухания:", + "Data Range:" => "Диапазон данных:", + "Data validation" => "Проверка данных", + "Database" => "Работа с базой данных", + "Date & Time" => "Дата и время", + "Date unit" => "Единица даты", + "Day" => "День", + "Decimal" => "Действительное", + "Define Name…" => "Присвоить имя…", + "Delete Comment" => "Удалить примечание", + "Delete Sheet" => "Удалить лист", + "Delete chart" => "Удалить диаграмму", + "Delete rows" => "Удаление строк", + "Delete…" => "Удалить…", + "Description (optional):" => "Описание (необязательно):", + "Descriptive Statistics" => "Описательная статистика", + "Destination:" => "Поместить в:", + "Diagonal ↗" => "Диагональ ↗", + "Diagonal ↘" => "Диагональ ↘", + "Dismiss" => "Закрыть", + "Display:" => "Отображать:", + "Distributed" => "Распределённый", + "Divide" => "Разделить", + "Do you want to save the changes you made to {title}?" => "Сохранить изменения в «{title}»?", + "Don't Save" => "Не сохранять", + "Double" => "Двойное", + "Double Accounting" => "Двойное, по ячейке", + "Doughnut" => "Кольцевая", + "Down" => "Вниз", + "Edit Name" => "Изменение имени", + "Edit chart title" => "Изменить название диаграммы", + "Edit…" => "Изменить…", + "Engineering" => "Инженерные", + "Entire column" => "Столбец", + "Entire row" => "Строку", + "Erase ink strokes" => "Стереть рукописные штрихи", + "Error message:" => "Сообщение:", + "Error style" => "Вид", + "Errors" => "Ошибки", + "Every command run in this session (replayable)" => "Все команды, выполненные в этом сеансе (можно повторить)", + "Expand formula bar" => "Развернуть строку формул", + "Exponential Smoothing" => "Экспоненциальное сглаживание", + "F-Test Two-Sample for Variances" => "Двухвыборочный F-тест для дисперсии", + "Fill missing points using" => "Заполнить отсутствующие точки с помощью", + "Filter (⌘⇧F)" => "Фильтр (⌘⇧F)", + "Filter by Selected Cell's Value" => "Фильтр по значению выделенной ячейки", + "Find" => "Найти", + "Find & Select" => "Найти и выделить", + "Find All" => "Найти все", + "Find Next" => "Найти далее", + "Find and Replace" => "Найти и заменить", + "Find what:" => "Найти:", + "Fits inside the selected cell and moves with its content." => "Помещается в выделенную ячейку и перемещается вместе с её содержимым.", + "Flash Fill (⌘E)" => "Мгновенное заполнение (⌘E)", + "Font" => "Шрифт", + "Footer (in):" => "Нижний колонтитул (дюймы):", + "Footer:" => "Нижний колонтитул:", + "Forecast Sheet" => "Лист прогноза", + "Forecast end (date or number; blank: a third of the history):" => "Завершение прогноза (дата или число; пусто — треть истории):", + "Format Cells" => "Формат ячеек", + "Format Cells|Fill" => "Заливка", + "Format Chart pane" => "Область «Формат диаграммы»", + "Format as Table" => "Форматировать как таблицу", + "Format cells" => "Форматирование ячеек", + "Format cells that are (value):" => "Форматировать ячейки, которые (значение):", + "Format cells that contain a date occurring:" => "Форматировать ячейки, содержащие дату:", + "Format cells that contain the text:" => "Форматировать ячейки, содержащие текст:", + "Format columns" => "Форматирование столбцов", + "Format rows" => "Форматирование строк", + "Format values where this formula is true:" => "Форматировать значения, для которых следующая формула является истинной:", + "Formats (T)" => "Форматы (T)", + "Formula Builder" => "Построитель формул", + "Formula:" => "Формула:", + "Formulas (F)" => "Формулы (F)", + "Formulas and number formats" => "Формулы и форматы чисел", + "Funnel" => "Воронка", + "GRG Nonlinear" => "Поиск решения нелинейных задач методом ОПГ", + "GRG Nonlinear: a local optimum of a smooth model, from the current values." => { + "Поиск решения нелинейных задач методом ОПГ: локальный оптимум гладкой модели, начиная с текущих значений." + } + "Go To" => "Перейти", + "Go To Special" => "Выделить группу ячеек", + "Goal Seek" => "Подбор параметра", + "Goal Seeking found a solution: {value}" => "Подбор параметра нашёл решение: {value}", + "Gradebook" => "Журнал оценок", + "Green Fill with Dark Green Text" => "Зелёная заливка и тёмно-зелёный текст", + "GridCraft is fully drivable by agents. Every menu item, button and gesture is a command:" => { + "GridCraft полностью управляется агентами. Каждый пункт меню, кнопка и жест — это команда:" + } + "Grouped By:" => "Группирование:", + "Growth" => "Геометрическая", + "Header (&L left, &C center, &R right; &P page, &N pages, &D date, &A sheet):" => { + "Верхний колонтитул (&L слева, &C по центру, &R справа; &P страница, &N страниц, &D дата, &A лист):" + } + "Header (in):" => "Верхний колонтитул (дюймы):", + "Hidden" => "Скрыть формулы", + "Hidden: {sheets}" => "Скрытые: {sheets}", + "Hide" => "Скрыть", + "Hide Sheet" => "Скрыть лист", + "Hierarchy & more" => "Иерархия и другие", + "Highlighter" => "Маркер", + "Histogram" => "Гистограмма распределения", + "Horizontal (Category) Axis Labels:" => "Подписи горизонтальной оси (категории):", + "Horizontal axis title:" => "Название горизонтальной оси:", + "Household Budget" => "Семейный бюджет", + "How agents drive GridCraft (MCP / control channel)" => "Как агенты управляют GridCraft (MCP / канал управления)", + "Hypothesized Mean Difference:" => "Гипотетическая средняя разность:", + "Ignore Once" => "Пропустить", + "Ignore blank" => "Игнорировать пустые ячейки", + "Import a text or CSV file" => "Импорт текстового файла или CSV", + "In the last 7 days" => "За последние 7 дней", + "In-cell dropdown" => "Список допустимых значений", + "Include forecast statistics" => "Включить статистику прогноза", + "Indent" => "Отступ", + "Information" => "Сообщение", + "Input Range:" => "Входной интервал:", + "Input X Range:" => "Входной интервал X:", + "Input Y Range:" => "Входной интервал Y:", + "Input message:" => "Сообщение для ввода:", + "Insert Calculated Field" => "Вставка вычисляемого поля", + "Insert Chart" => "Вставка диаграммы", + "Insert Function" => "Вставка функции", + "Insert Function (⇧F3)" => "Вставить функцию (⇧F3)", + "Insert Hyperlink" => "Вставка гиперссылки", + "Insert Link (⌘K)" => "Вставить ссылку (⌘K)", + "Insert Sheet" => "Вставить лист", + "Insert Slicer" => "Вставка среза", + "Insert a picture" => "Вставить рисунок", + "Insert a slicer to filter a table" => "Вставить срез для фильтрации таблицы", + "Insert an icon" => "Вставить значок", + "Insert rows" => "Вставка строк", + "Insert…" => "Вставить…", + "Interpolation" => "Интерполяция", + "Interval:" => "Интервал:", + "Italic" => "Курсив", + "Join the ArtCraft Discord" => "Присоединиться к Discord ArtCraft", + "Justify" => "По ширине", + "Keep" => "Оставить", + "Keep Solver Solution" => "Сохранить найденное решение", + "Kth Largest (blank for none):" => "K-й наибольший (пусто — нет):", + "Kth Smallest (blank for none):" => "K-й наименьший (пусто — нет):", + "Labels in first row" => "Метки в первой строке", + "Last cell" => "Последнюю ячейку", + "Last month" => "В прошлом месяце", + "Last week" => "На прошлой неделе", + "Left margin (in):" => "Левое поле (дюймы):", + "Legend Entries (Series)" => "Элементы легенды (ряды)", + "Light Red Fill" => "Светло-красная заливка", + "Light Red Fill with Dark Red Text" => "Светло-красная заливка и тёмно-красный текст", + "Line" => "График", + "Line chart" => "График", + "Line or Area" => "График или диаграмма с областями", + "Line with Markers" => "График с маркерами", + "Linear" => "Арифметическая", + "Link to (web address, e-mail or Sheet!A1):" => "Связать с (веб-адрес, электронная почта или Лист!A1):", + "Link…" => "Ссылка…", + "List" => "Список", + "Location Range:" => "Диапазон расположения:", + "Locked" => "Защищаемая ячейка", + "Locking cells or hiding formulas has no effect until you protect the worksheet (Review › Protect Sheet)." => { + "Защита ячеек и скрытие формул действуют только после защиты листа (Рецензирование › Защитить лист)." + } + "Lookup & Reference" => "Ссылки и массивы", + "Macros" => "Макросы", + "Macros and scripts in this workbook (Alt+F8)" => "Макросы и сценарии этой книги (Alt+F8)", + "Magnification" => "Масштаб", + "Make Unconstrained Variables Non-Negative" => "Сделать переменные без ограничений неотрицательными", + "Markers" => "Маркеры", + "Match case" => "Учитывать регистр", + "Match entire cell contents" => "Ячейка целиком", + "Math & Trig" => "Математические", + "Max" => "Максимум", + "Maximum:" => "Максимум:", + "Median" => "Медиана", + "Middle Align" => "Выровнять по середине", + "Min" => "Минимум", + "Minimum / Source / Formula:" => "Минимум / источник / формула:", + "Models" => "Модели", + "Modify" => "Изменить", + "Month" => "Месяц", + "More commands" => "Другие команды", + "Move or Copy" => "Переместить или скопировать", + "Move or Copy Sheet…" => "Переместить или скопировать лист…", + "Moving Average" => "Скользящее среднее", + "Multiply" => "Умножить", + "My data has headers" => "Мои данные содержат заголовки", + "My list has headers" => "Мои данные содержат заголовки", + "Name" => "Имя", + "Name Manager" => "Диспетчер имён", + "Name:" => "Имя:", + "New Comment" => "Создать примечание", + "New Name" => "Создание имени", + "New Worksheet Ply:" => "Новый рабочий лист:", + "New sheet (⇧F11)" => "Новый лист (⇧F11)", + "New title (Modify):" => "Новое название (изменить):", + "New…" => "Создать…", + "Next month" => "В следующем месяце", + "Next sheet" => "Следующий лист", + "Next week" => "На следующей неделе", + "No names defined" => "Имена не определены", + "No picture selected" => "Рисунок не выбран", + "No ranges yet." => "Диапазонов пока нет.", + "None" => "Нет", + "Normal Probability" => "График нормального распределения", + "Not in Dictionary ({cell}):" => "Нет в словаре ({cell}):", + "Note:" => "Заметка:", + "Numbers" => "Числа", + "OK" => "ОК", + "Open…" => "Открыть…", + "Operation" => "Операция", + "Orientation (degrees)" => "Ориентация (градусы)", + "Other:" => "Другой:", + "Outline" => "Внешние", + "Output Range:" => "Выходной интервал:", + "Output options" => "Параметры вывода", + "Page Breaks" => "Разрывы страниц", + "Page Setup" => "Параметры страницы", + "Paper Size" => "Размер бумаги", + "Pareto (sorted histogram)" => "Парето (отсортированная гистограмма)", + "Password" => "Пароль", + "Password (optional):" => "Пароль (необязательно):", + "Password:" => "Пароль:", + "Paste (⌘V)" => "Вставить (⌘V)", + "Paste Special" => "Специальная вставка", + "Pick From Drop-down List…" => "Выбрать из раскрывающегося списка…", + "Pick From List" => "Выбрать из списка", + "Picture file path (PNG or JPEG):" => "Путь к файлу рисунка (PNG или JPEG):", + "Pie" => "Круговая", + "Pie or Doughnut" => "Круговая или кольцевая", + "Place Picture in Cell" => "Поместить рисунок в ячейку", + "Place Picture over Cells" => "Поместить рисунок поверх ячеек", + "Previous sheet" => "Предыдущий лист", + "Print Area" => "Область печати", + "Print Titles" => "Печатать заголовки", + "Product" => "Произведение", + "Protect Sheet" => "Защитить лист", + "Protect Structure and Windows" => "Защита структуры и окон", + "Protect Workbook structure" => "Защитить структуру книги", + "Protect workbook for: Structure (sheets can't be added, moved, renamed, hidden or deleted)." => { + "Защитить книгу: структуру (листы нельзя добавлять, перемещать, переименовывать, скрывать и удалять)." + } + "Protection" => "Защита", + "Quarterly Sales Dashboard" => "Сводка продаж по кварталам", + "Radar" => "Лепестковая", + "Range password:" => "Пароль диапазона:", + "Ranges that stay editable when the sheet is protected:" => "Диапазоны, которые можно изменять на защищённом листе:", + "Rank and Percentile" => "Ранг и персентиль", + "Recommended Charts" => "Рекомендуемые диаграммы", + "Red Border" => "Красная граница", + "Red Text" => "Красный текст", + "Redo (⌘Y)" => "Повторить (⌘Y)", + "Reference:" => "Ссылка:", + "Refers To" => "Диапазон", + "Refers to cells:" => "Ссылается на ячейки:", + "Refers to:" => "Диапазон:", + "Regression" => "Регрессия", + "Remove" => "Удалить", + "Remove Duplicates" => "Удалить дубликаты", + "Remove the password (Modify)" => "Снять пароль (изменить)", + "Rename Sheet" => "Переименовать лист", + "Replace" => "Заменить", + "Replace All" => "Заменить все", + "Replace with:" => "Заменить на:", + "Residuals" => "Остатки", + "Restore Original Values" => "Восстановить исходные значения", + "Return to the original worksheet to insert this picture, or cancel and choose another cell." => { + "Вернитесь на исходный лист, чтобы вставить рисунок, или отмените и выберите другую ячейку." + } + "Right margin (in):" => "Правое поле (дюймы):", + "Row Height" => "Высота строки", + "Row height (pixels):" => "Высота строки (пиксели):", + "Rows" => "Строки", + "Sample" => "Выборка", + "Save (⌘S)" => "Сохранить (⌘S)", + "Save Changes?" => "Сохранить изменения?", + "Save a Copy" => "Сохранить копию", + "Save a copy as .{format}" => "Сохранить копию как .{format}", + "Scatter" => "Точечная", + "Scatter or Bubble" => "Точечная или пузырьковая", + "Scatter with Lines" => "Точечная с прямыми отрезками", + "Scope" => "Область", + "Scope (Workbook or sheet name):" => "Область (книга или имя листа):", + "ScreenTip:" => "Подсказка:", + "Search Commands" => "Поиск команд", + "Search and run any command" => "Найти и выполнить любую команду", + "Search commands (⌘⇧Space)" => "Поиск команд (⌘⇧Пробел)", + "Search:" => "Поиск:", + "Seasonality (auto, 0 for none, or a season length):" => "Сезонность (авто, 0 — нет, или длина сезона):", + "Select" => "Выделить", + "Select Data" => "Выбрать данные", + "Select Data Source" => "Выбор источника данных", + "Select a Solving Method:" => "Выберите метод решения:", + "Select a chart first." => "Сначала выделите диаграмму.", + "Select and move ink and shapes" => "Выделять и перемещать рукописные штрихи и фигуры", + "Semicolon" => "Точка с запятой", + "Series" => "Ряд", + "Series in" => "Ряды в", + "Series{n}" => "Ряд{n}", + "Series…" => "Прогрессия…", + "Set Objective:" => "Оптимизировать целевую функцию:", + "Set cell:" => "Установить в ячейке:", + "Share: export or save a copy" => "Поделиться: экспорт или сохранение копии", + "Sheets: {sheets}" => "Листы: {sheets}", + "Shift cells down" => "Ячейки со сдвигом вниз", + "Shift cells left" => "Ячейки со сдвигом влево", + "Shift cells right" => "Ячейки со сдвигом вправо", + "Shift cells up" => "Ячейки со сдвигом вверх", + "Show Formulas (⌃`)" => "Показать формулы (⌃`)", + "Show password" => "Показать пароль", + "Shrink to fit" => "Автоподбор ширины", + "Simplex LP: for linear models; integer and binary constraints by branch and bound." => { + "Симплекс-метод: для линейных моделей; целочисленные и двоичные ограничения — методом ветвей и границ." + } + "Single" => "Одинарное", + "Single Accounting" => "Одинарное, по ячейке", + "Skip blanks" => "Пропускать пустые ячейки", + "Slicer" => "Срез", + "Solve" => "Найти решение", + "Solver Parameters" => "Параметры поиска решения", + "Solver Results" => "Результаты поиска решения", + "Sort & Filter" => "Сортировка и фильтр", + "Sort by" => "Сортировать по", + "Space" => "Пробел", + "Special…" => "Выделить…", + "Spelling (F7)" => "Орфография (F7)", + "Stacked Area" => "С областями с накоплением", + "Stacked Bar" => "Линейчатая с накоплением", + "Stacked Column" => "Гистограмма с накоплением", + "Stacked Line" => "График с накоплением", + "Standard Errors" => "Стандартные погрешности", + "Standard Width" => "Стандартная ширина", + "Standard column width (pixels):" => "Стандартная ширина столбца (пиксели):", + "Standardized Residuals" => "Стандартизированные остатки", + "Start a conversation:" => "Начать разговор:", + "Start a new workbook" => "Создать новую книгу", + "Statistic" => "Статистика", + "Statistical" => "Статистические", + "Step value:" => "Шаг:", + "Stop" => "Останов", + "Stop value:" => "Предельное значение:", + "Subject to the Constraints:" => "В соответствии с ограничениями:", + "Subscript" => "Подстрочный", + "Subtract" => "Вычесть", + "Suggestions:" => "Варианты:", + "Sum" => "Сумма", + "Summary statistics" => "Итоговая статистика", + "Superscript" => "Надстрочный", + "Switch Row/Column" => "Строка/столбец", + "Tab" => "Знак табуляции", + "Table (⌘T)" => "Таблица (⌘T)", + "Table Styles" => "Стили таблиц", + "Text Box" => "Надпись", + "Text length" => "Длина текста", + "Text to Columns" => "Текст по столбцам", + "The output range already holds data. Replace it with the report?" => "Выходной интервал уже содержит данные. Заменить их отчётом?", + "The spelling check is complete for the entire sheet." => "Проверка орфографии на всём листе завершена.", + "Then by" => "Затем по", + "There are no conditional formatting rules on this sheet." => "На этом листе нет правил условного форматирования.", + "This month" => "В текущем месяце", + "This week" => "На текущей неделе", + "This workbook" => "Эта книга", + "This workbook has no scripts or macros." => "В этой книге нет сценариев и макросов.", + "Timeline range (blank: first column of the selection):" => "Диапазон временной шкалы (пусто — первый столбец выделения):", + "Title:" => "Заголовок:", + "To value:" => "Значение:", + "To:" => "До:", + "Today" => "Сегодня", + "Tomorrow" => "Завтра", + "Top" => "Верхняя", + "Top Align" => "Выровнять по верхнему краю", + "Top margin (in):" => "Верхнее поле (дюймы):", + "Transpose (E)" => "Транспонировать (E)", + "Treat consecutive delimiters as one" => "Считать последовательные разделители одним", + "Type" => "Тип", + "Type (custom format code):" => "Тип (код пользовательского формата):", + "Type a command, e.g. freeze, chart, bold…" => "Введите команду, например закрепить, диаграмма, полужирный…", + "Undo (⌘Z)" => "Отменить (⌘Z)", + "Undo list" => "Список отмены", + "Unhide" => "Показать", + "Unhide Sheet…" => "Показать лист…", + "Unhide sheet:" => "Показать лист:", + "Unlock with password" => "Разблокировать паролем", + "Unprotect Sheet" => "Снять защиту листа", + "Unprotect Workbook" => "Снять защиту книги", + "Up" => "Вверх", + "Use AutoFilter" => "Использование автофильтра", + "Use function" => "Операция", + "Validation" => "Проверка данных", + "Value" => "Значение", + "Value Of:" => "Значения:", + "Values (V)" => "Значения (V)", + "Values and number formats" => "Значения и форматы чисел", + "Values range (blank: second column of the selection):" => "Диапазон значений (пусто — второй столбец выделения):", + "Variable 1 Range:" => "Интервал переменной 1:", + "Variable 2 Range:" => "Интервал переменной 2:", + "Version {version}" => "Версия {version}", + "Version, contributors and the AI models that helped" => "Версия, участники и модели ИИ, которые помогали", + "Vertical" => "По вертикали", + "Vertical axis title:" => "Название вертикальной оси:", + "Visible cells only" => "Только видимые ячейки", + "Warning" => "Предупреждение", + "Waterfall" => "Каскадная", + "Web" => "Интернет", + "Weekday" => "Рабочий день", + "What-If Analysis" => "Анализ «что если»", + "Whole number" => "Целое число", + "Within workbook" => "В книге", + "Workbook" => "Книга", + "Workbook Statistics" => "Статистика книги", + "Wrap text" => "Переносить текст", + "Year" => "Год", + "Yellow Fill with Dark Yellow Text" => "Жёлтая заливка и тёмно-жёлтый текст", + "Yesterday" => "Вчера", + "Z to A" => "От Я до А", + "Zeros" => "Нули", + "Zoom In" => "Увеличить", + "Zoom Out" => "Уменьшить", + "Zoom to 100%" => "Масштаб 100%", + "Zoom to Selection" => "Масштаб по выделенному", + "Zoom…" => "Масштаб…", + "and:" => "и:", + "applies to" => "применяется к", + "between" => "между", + "dashed" => "штриховая", + "dotted" => "точечная", + "double" => "двойная", + "e.g. lookup, average, date" => "например: поиск, среднее, дата", + "equal to" => "равно", + "greater than" => "больше", + "greater than or equal to" => "больше или равно", + "less than" => "меньше", + "less than or equal to" => "меньше или равно", + "medium" => "средняя", + "none" => "нет", + "not between" => "вне", + "not equal to" => "не равно", + "t-Test: Paired Two Sample for Means" => "Парный двухвыборочный t-тест для средних", + "t-Test: Two-Sample Assuming Equal Variances" => "Двухвыборочный t-тест с одинаковыми дисперсиями", + "t-Test: Two-Sample Assuming Unequal Variances" => "Двухвыборочный t-тест с различными дисперсиями", + "thick" => "толстая", + "thin" => "тонкая", + "this workbook" => "эта книга", + "with" => "с", + "{count} cell(s) found" => "Найдено ячеек: {count}", + "{count} engine commands are available. See docs/mcp.md and docs/control-protocol.md." => { + "Доступно команд движка: {count}. См. docs/mcp.md и docs/control-protocol.md." + } + "£ English (United Kingdom)" => "£ английский (Великобритания)", + "¥ Japanese" => "¥ японский", + "— 1 step" => "— 1 шаг", + "— VBA project (preserved, not run)" => "— проект VBA (сохраняется, не выполняется)", + "— {steps} steps" => "— шагов: {steps}", + "€ Euro" => "€ евро", _ => return None, }) } From a1d97d49b363d94dcbabb03c9470ea4afbb3f2f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=B3=D0=B4=D0=B0=20=D0=9C=2E=D0=93=2E?= Date: Mon, 12 Oct 2026 14:39:53 +0300 Subject: [PATCH 002/425] =?UTF-8?q?i18n(ru):=20name=20the=20Insert=20tab?= =?UTF-8?q?=20=C2=AB=D0=92=D1=81=D1=82=D0=B0=D0=B2=D0=BA=D0=B0=C2=BB,=20tr?= =?UTF-8?q?anslate=20AutoSave?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Russian names the Insert tab and the Insert command differently («Вставка» vs «Вставить»). Ribbon tabs now look up a `Tab|` key first and fall back to the plain label, so other languages are unchanged. Also translates the AutoSave toggle and adds the two French header/footer labels whose absence failed the catalog completeness test. --- crates/ui-egui/src/i18n.rs | 24 +++++++++++++++++++++--- crates/ui-egui/src/i18n/fr.rs | 2 ++ crates/ui-egui/src/i18n/ru.rs | 5 +++++ crates/ui-egui/src/ribbon.rs | 6 +++--- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 406cc3dd51..e68fcaab0f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -112,7 +112,19 @@ impl Language { /// A label that needs two translations (Home's text "Orientation" vs Page Layout's print /// "Orientation") is keyed `context|label`: English shows only the part after the `|`. pub fn tr(self, text: &str) -> &str { - let translated = match self { + self.lookup(text).unwrap_or_else(|| text.rsplit_once('|').map_or(text, |(_, label)| label)) + } + + /// A ribbon tab's name. Where a language names the tab differently from a command with the + /// same English label (Russian: the Insert tab is «Вставка», the Insert button «Вставить»), its + /// catalog keys the tab `Tab|name`; every other language falls back to the plain label. + pub fn tr_tab(self, tab: &str) -> &str { + self.lookup(&format!("Tab|{tab}")).unwrap_or_else(|| self.tr(tab)) + } + + /// The catalog entry for `text`, if this language has one. + fn lookup(self, text: &str) -> Option<&'static str> { + match self { Self::En => None, Self::Es => es::translate(text), Self::Ja => JAPANESE.iter().find(|(english, _)| *english == text).map(|(_, translated)| *translated), @@ -123,8 +135,7 @@ impl Language { Self::De => de::translate(text), Self::Cs => cs::translate(text), Self::Fr => fr::translate(text), - }; - translated.unwrap_or_else(|| text.rsplit_once('|').map_or(text, |(_, label)| label)) + } } } @@ -592,6 +603,13 @@ mod tests { assert_eq!(Language::Zh.tr("Data"), "数据"); assert_eq!(Language::Ko.tr("Data"), "데이터"); assert_eq!(Language::Ru.tr("Data"), "Данные"); + // The Insert tab and the Insert command have different Russian names; elsewhere the tab + // name is the plain label. + assert_eq!(Language::Ru.tr_tab("Insert"), "Вставка"); + assert_eq!(Language::Ru.tr("Insert"), "Вставить"); + assert_eq!(Language::Ru.tr_tab("Data"), "Данные"); + assert_eq!(Language::Es.tr_tab("Insert"), Language::Es.tr("Insert")); + assert_eq!(Language::En.tr_tab("Insert"), "Insert"); assert_eq!(Language::PtBr.tr("Data"), "Dados"); assert_eq!(Language::Es.tr("Data"), "Datos"); assert_eq!(Language::Es.tr("Freeze Panes"), "Inmovilizar paneles"); diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fdf1f891dd..8cd4e9b48d 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -381,6 +381,8 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Classeur Excel (*.xlsx)", "Calculation settings are saved with the workbook." => "Modifier le type de fichier", + "Different First Page" => "Première page différente", + "Different Odd & Even Pages" => "Pages paires et impaires différentes", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 850ad4af64..7afd626123 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -960,6 +960,11 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "— VBA project (preserved, not run)" => "— проект VBA (сохраняется, не выполняется)", "— {steps} steps" => "— шагов: {steps}", "€ Euro" => "€ евро", + "Tab|Insert" => "Вставка", + "AutoSave" => "Автосохранение", + "AutoSave: save after every change (workbooks saved to a file)" => { + "Автосохранение: сохранять после каждого изменения (для книг, сохранённых в файл)" + } _ => return None, }) } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index e8291accdc..5bff246baa 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -52,14 +52,14 @@ pub fn title_bar(app: &mut SheetApp, ui: &mut Ui) { ui.horizontal_centered(|ui| { ui.add_space(TITLE_LEFT_PAD); // AutoSave toggle (saves after each change when the workbook has a file). - ui.label(egui::RichText::new("AutoSave").font(theme::ui_font(12.5)).color(t.text_dim)); + ui.label(egui::RichText::new(app.ui.language.tr("AutoSave")).font(theme::ui_font(12.5)).color(t.text_dim)); let on = app.grid.autosave(); let (r, resp) = ui.allocate_exact_size(vec2(30.0, 16.0), Sense::click()); ui.painter().rect_filled(r, 8.0, if on { t.accent } else { Color32::TRANSPARENT }); ui.painter().rect_stroke(r, 8.0, Stroke::new(1.0, if on { t.accent } else { t.text_dim }), StrokeKind::Inside); let knob = if on { pos2(r.right() - 8.0, r.center().y) } else { pos2(r.left() + 8.0, r.center().y) }; ui.painter().circle_filled(knob, 5.0, if on { Color32::WHITE } else { t.text_dim }); - if resp.on_hover_text("AutoSave: save after every change (workbooks saved to a file)").clicked() { + if resp.on_hover_text(app.ui.language.tr("AutoSave: save after every change (workbooks saved to a file)")).clicked() { app.grid.toggle_autosave(); } ui.add_space(6.0); @@ -181,7 +181,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui) { let active = app.ui.ribbon_tab == tab; let contextual = ctx_tabs.contains(&tab); let font = theme::ui_font(13.5); - let label = app.ui.language.tr(tab); + let label = app.ui.language.tr_tab(tab); let tw = ui.painter().layout_no_wrap(label.to_string(), font.clone(), t.text).size().x; let (r, resp) = ui.allocate_exact_size(vec2(tw + 22.0, 30.0), Sense::click()); if resp.hovered() && !active { From 4972675b1b0e2d309dcf94442e8372a6e4741089 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:03:01 +0200 Subject: [PATCH 003/425] UI: Quick Analysis (Ctrl+Q) (#791) A corner button on multi-cell selections and Ctrl+Q open a popup of one-click analyses (formatting, charts, totals, tables, sparklines). Totals and sparklines are new engine commands, analysis.addTotal and analysis.addSparklines, each one undo step, never overwriting data unless asked. Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/quick_analysis.rs | 269 +++++++++++++++++ crates/engine/src/tests.rs | 71 +++++ crates/ui-egui/examples/snapshot.rs | 20 +- crates/ui-egui/src/grid.rs | 3 + crates/ui-egui/src/i18n.rs | 24 ++ crates/ui-egui/src/i18n/cs.rs | 24 ++ crates/ui-egui/src/i18n/de.rs | 24 ++ crates/ui-egui/src/i18n/es.rs | 24 ++ crates/ui-egui/src/i18n/fr.rs | 24 ++ crates/ui-egui/src/i18n/ko.rs | 24 ++ crates/ui-egui/src/i18n/pt.rs | 24 ++ crates/ui-egui/src/i18n/ru.rs | 24 ++ crates/ui-egui/src/i18n/zh.rs | 24 ++ crates/ui-egui/src/icons.rs | 9 + crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/quick_analysis.rs | 364 ++++++++++++++++++++++++ crates/ui-egui/src/ribbon.rs | 5 + docs/ui-parity.md | 10 +- 20 files changed, 967 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/quick_analysis.rs create mode 100644 crates/ui-egui/src/quick_analysis.rs diff --git a/ROADMAP.md b/ROADMAP.md index e8e1c06b38..25b8d9b803 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) | | 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available | | 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found | | 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) | diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 50865a2b7d..d016fbb494 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -14,6 +14,7 @@ pub mod insert; pub mod inspect; pub mod pivot; pub mod print; +pub mod quick_analysis; pub mod review; pub mod sheet; pub mod slicer; @@ -144,6 +145,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(forecast::specs()); v.extend(analysis::specs()); v.extend(print::specs()); + v.extend(quick_analysis::specs()); v }) } diff --git a/crates/engine/src/cmd/quick_analysis.rs b/crates/engine/src/cmd/quick_analysis.rs new file mode 100644 index 0000000000..94f4197020 --- /dev/null +++ b/crates/engine/src/cmd/quick_analysis.rs @@ -0,0 +1,269 @@ +//! Quick Analysis › Totals: appends totals (or per-cell percentages / running totals) next to a +//! block of numbers as ordinary formulas, in one undoable edit. The popup in the UI +//! (`ui.quickAnalysis`) is a thin front end for this command; the control channel, CLI and MCP +//! call it directly. The layout is GridCraft's own: aggregates go in the row below the block (or +//! the column to its right), per-cell results in a block of the same shape next to it. + +use std::collections::BTreeSet; + +use gridcraft_core::{CellRef, MAX_COLS, MAX_ROWS, RangeRef}; +use gridcraft_model::{Color, NumFmt, Sparkline, SparklineKind}; +use serde_json::{Value as Json, json}; + +use super::*; + +const CMD: &str = "analysis.addTotal"; +const SPARK: &str = "analysis.addSparklines"; +/// Most sparklines one call may add. +const MAX_SPARKLINES: u64 = 10_000; +/// Most cells one call may write (a per-cell block on a huge selection is refused). +const MAX_OUTPUT_CELLS: u64 = 200_000; +/// Largest block (after clipping to the used range) the command scans for numbers. +const MAX_SCAN_CELLS: u64 = 5_000_000; + +pub fn specs() -> Vec { + vec![ + cmd!( + "analysis.addTotal", + "Add Totals", + [], + None, + "{function?: sum|average|count|min|max|percentTotal|runningTotal (default sum), direction?: columns|rows (default columns: one result per column, below the block; rows: one per row, right of it; percentTotal and runningTotal write a block of the same shape to the right (columns) or below (rows)), range?: \"A1:C9\" (default: the selection; limited to the used range), overwrite?: bool (else non-empty output cells are refused)} → {function, direction, output, cells}. Quick Analysis › Totals. A header row (columns) or label column (rows) is skipped; columns without numbers get no total. One undo step.", + has_doc, + add_total + ), + cmd!( + "analysis.addSparklines", + "Add Sparklines", + [], + None, + "{type?: line|column|winLoss (default line), direction?: rows|columns (default rows: one sparkline per row, in the column right of the block; columns: one per column, in the row below), markers?: bool, range?: \"A1:F9\" (default: the selection; limited to the used range), overwrite?: bool} → {output, sparklines}. Quick Analysis › Sparklines. A header row (columns) or label column (rows) is skipped; lines without numbers get none. One undo step.", + has_doc, + add_sparklines + ), + ] +} + +#[derive(Clone, Copy, PartialEq)] +enum Func { + Aggregate(&'static str), + Percent, + Running, +} + +fn parse_func(name: &str) -> Result { + Ok(match name.to_ascii_lowercase().replace(['_', '-', ' ', '%'], "").as_str() { + "sum" => Func::Aggregate("SUM"), + "average" | "avg" => Func::Aggregate("AVERAGE"), + "count" => Func::Aggregate("COUNT"), + "min" => Func::Aggregate("MIN"), + "max" => Func::Aggregate("MAX"), + "percenttotal" | "percent" => Func::Percent, + "runningtotal" | "running" => Func::Running, + _ => return Err(bad(CMD, format!("unknown function `{name}` (use sum, average, count, min, max, percentTotal or runningTotal)"))), + }) +} + +/// The block a Quick Analysis result is computed from. +struct Block { + sheet: usize, + /// The selection clipped to the used range. + range: RangeRef, + /// `range` without its header row (columns) or label column (rows). + data: RangeRef, + /// The columns (or, `by_rows`, the rows) of `data` that hold numbers. + lines: BTreeSet, + by_rows: bool, +} + +impl Block { + fn cell_at(&self, line: u32, i: u32) -> CellRef { + if self.by_rows { CellRef::new(line, i) } else { CellRef::new(i, line) } + } + /// First and last position along a line of `data`. + fn span_of_line(&self) -> (u32, u32) { + if self.by_rows { (self.data.start.col, self.data.end.col) } else { (self.data.start.row, self.data.end.row) } + } + fn line_range(&self, line: u32, from: u32, to: u32) -> RangeRef { + RangeRef::new(self.cell_at(line, from), self.cell_at(line, to)) + } +} + +fn block(s: &Session, p: &Json, by_rows: bool) -> Result { + let sheet = target_sheet(s, p)?; + let sel = match str_param(p, "range") { + Some(_) => target_range(s, p)?, + None => s.doc()?.selection.current(), + }; + if sel.is_single() { + return Err(bad(CMD, "select at least two cells")); + } + let d = s.doc()?; + let sh = d.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + // Whole rows / columns are limited to what holds data. + let used = sh.cells.used_range().ok_or_else(|| EngineError::Other("There is no data to analyse.".into()))?; + let r = sel.intersection(&used).ok_or_else(|| EngineError::Other("There is no data to analyse in the selection.".into()))?; + if r.count() > MAX_SCAN_CELLS { + return Err(bad(CMD, "selection too large to analyse")); + } + let is_num = |c: CellRef| sh.value(c).is_number(); + let is_text = |c: CellRef| sh.value(c).is_text(); + // Header row (columns) / label column (rows): text only, with at least one entry. + let lead: Vec = if by_rows { + (r.start.row..=r.end.row).map(|row| CellRef::new(row, r.start.col)).collect() + } else { + (r.start.col..=r.end.col).map(|c| CellRef::new(r.start.row, c)).collect() + }; + let longer_than_one = if by_rows { r.width() > 1 } else { r.height() > 1 }; + let has_label = longer_than_one && lead.iter().any(|c| is_text(*c)) && !lead.iter().any(|c| is_num(*c)); + let data = if by_rows { + RangeRef::new(CellRef::new(r.start.row, r.start.col + u32::from(has_label)), r.end) + } else { + RangeRef::new(CellRef::new(r.start.row + u32::from(has_label), r.start.col), r.end) + }; + let mut lines: BTreeSet = BTreeSet::new(); + for (c, _) in sh.cells.iter_range(data) { + if is_num(c) { + lines.insert(if by_rows { c.row } else { c.col }); + } + } + if lines.is_empty() { + return Err(EngineError::Other("The selection holds no numbers.".into())); + } + Ok(Block { sheet, range: r, data, lines, by_rows }) +} + +fn add_total(s: &mut Session, p: &Json) -> Result { + let func = parse_func(str_param(p, "function").unwrap_or("sum"))?; + let by_rows = match str_param(p, "direction") { + None | Some("columns") => false, + Some("rows") => true, + Some(other) => return Err(bad(CMD, format!("direction must be columns or rows, not `{other}`"))), + }; + let overwrite = bool_param(p, "overwrite").unwrap_or(false); + let b = block(s, p, by_rows)?; + let (r, sheet) = (b.range, b.sheet); + let (lo, hi) = b.span_of_line(); + let out_cells = match func { + Func::Aggregate(_) => b.lines.len() as u64, + _ => b.lines.len() as u64 * (u64::from(hi - lo) + 1), + }; + if out_cells > MAX_OUTPUT_CELLS { + return Err(bad(CMD, "selection too large for this result")); + } + // `$` pins a part of a reference like a hand-written formula would. + let abs = |c: CellRef, row: bool, col: bool| { + let a = c.a1(); + let letters: String = a.chars().take_while(|ch| ch.is_ascii_alphabetic()).collect(); + let digits = &a[letters.len()..]; + format!("{}{letters}{}{digits}", if col { "$" } else { "" }, if row { "$" } else { "" }) + }; + // (target, formula) pairs. + let mut writes: Vec<(CellRef, String)> = Vec::with_capacity(out_cells as usize); + let (height, width) = (r.height(), r.width()); + for &line in &b.lines { + match func { + Func::Aggregate(name) => { + let target = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + writes.push((target, format!("={name}({})", b.line_range(line, lo, hi).a1()))); + } + Func::Percent | Func::Running => { + for i in lo..=hi { + let src = b.cell_at(line, i); + let target = if by_rows { + CellRef::new(src.row.saturating_add(height), src.col) + } else { + CellRef::new(src.row, src.col.saturating_add(width)) + }; + let formula = if func == Func::Percent { + // The summed block is locked on the axis the formula is filled along. + let (a, z) = (b.cell_at(line, lo), b.cell_at(line, hi)); + format!("={}/SUM({}:{})", src.a1(), abs(a, !by_rows, by_rows), abs(z, !by_rows, by_rows)) + } else { + format!("=SUM({}:{})", abs(b.cell_at(line, lo), !by_rows, by_rows), src.a1()) + }; + writes.push((target, formula)); + } + } + } + } + // Everything has to fit on the sheet and may not overwrite data. + if writes.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) { + return Err(EngineError::Other("There's no room next to the selection for the result.".into())); + } + let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + if !overwrite && writes.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.cells.get(*t).is_some_and(|c| c.formula.is_some())) { + return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into())); + } + let out = writes.iter().fold(None::, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t))))); + let percent = func == Func::Percent; + let count = writes.len(); + edit(s, |cx| { + for (t, f) in &writes { + let cell = super::edit::input_to_cell(f, sheet, *t, &mut cx.wb)?.unwrap_or_default(); + cx.sheet_mut(sheet)?.set_cell(*t, cell); + if percent { + let cur = cx.wb.sheet(sheet).map(|sh| sh.style_id(*t)).unwrap_or_default(); + let new = cx.wb.styles.derive(cur, |st| st.num_fmt = NumFmt::new("0.0%")); + cx.sheet_mut(sheet)?.set_style(*t, new); + } + cx.touch(sheet, *t); + } + Ok(()) + })?; + let name = match func { + Func::Aggregate(n) => n.to_ascii_lowercase(), + Func::Percent => "percentTotal".into(), + Func::Running => "runningTotal".into(), + }; + Ok(json!({"function": name, "direction": if by_rows { "rows" } else { "columns" }, "output": out.map(|o| o.a1()), "cells": count})) +} + +fn add_sparklines(s: &mut Session, p: &Json) -> Result { + let by_rows = match str_param(p, "direction") { + None | Some("rows") => true, + Some("columns") => false, + Some(other) => return Err(bad(SPARK, format!("direction must be rows or columns, not `{other}`"))), + }; + let kind = match str_param(p, "type") { + None | Some("line") => SparklineKind::Line, + Some("column") => SparklineKind::Column, + Some("winLoss") => SparklineKind::WinLoss, + Some(other) => return Err(bad(SPARK, format!("type must be line, column or winLoss, not `{other}`"))), + }; + let markers = bool_param(p, "markers").unwrap_or(false); + let overwrite = bool_param(p, "overwrite").unwrap_or(false); + let b = block(s, p, by_rows)?; + if b.lines.len() as u64 > MAX_SPARKLINES { + return Err(bad(SPARK, "selection too large for this result")); + } + let (lo, hi) = b.span_of_line(); + let r = b.range; + let sparks: Vec<(CellRef, String)> = b + .lines + .iter() + .map(|&line| { + let at = if by_rows { CellRef::new(line, r.end.col.saturating_add(1)) } else { CellRef::new(r.end.row.saturating_add(1), line) }; + (at, b.line_range(line, lo, hi).a1()) + }) + .collect(); + if sparks.iter().any(|(t, _)| t.row >= MAX_ROWS || t.col >= MAX_COLS) { + return Err(EngineError::Other("There's no room next to the selection for the sparklines.".into())); + } + let sheet = b.sheet; + let sh = s.doc()?.wb.sheet(sheet).ok_or(EngineError::NoDocument)?; + if !overwrite && sparks.iter().any(|(t, _)| !sh.value(*t).is_empty() || sh.sparklines.iter().any(|x| x.cell == *t)) { + return Err(EngineError::Other("The cells next to the selection already hold data; clear them first.".into())); + } + let out = sparks.iter().fold(None::, |acc, (t, _)| Some(acc.map_or(RangeRef::cell(*t), |a| a.union(&RangeRef::cell(*t))))); + let count = sparks.len(); + edit(s, |cx| { + let sh = cx.sheet_mut(sheet)?; + for (cell, source) in sparks { + sh.sparklines.retain(|x| x.cell != cell); + sh.sparklines.push(Sparkline { cell, source, kind, color: Color::Theme(4, 0), markers }); + } + Ok(()) + })?; + Ok(json!({"output": out.map(|o| o.a1()), "sparklines": count})) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 33fdc113e0..c348dbaff2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2795,3 +2795,74 @@ fn a_decrypted_workbook_never_overwrites_its_encrypted_original() { assert_eq!(std::fs::read(&path).unwrap(), bytes, "the encrypted original is untouched"); std::fs::remove_dir_all(dir).unwrap(); } + +fn quick_analysis_block(s: &mut Session) { + for (a, t) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] { + s.execute("cell.set", json!({"cell": a, "input": t})).unwrap(); + } + for (r, (q1, q2)) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)].into_iter().enumerate() { + s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap(); + s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap(); + } +} + +#[test] +fn analysis_add_total_writes_formulas_in_one_undo_step() { + // Issue #791 (Quick Analysis › Totals). + let mut s = s(); + quick_analysis_block(&mut s); + let before = s.doc().unwrap().undo.len(); + // The header row and the text-only column are skipped; the selection is the default range. + s.execute("selection.set", json!({"range": "A1:C4"})).unwrap(); + let r = s.execute("analysis.addTotal", json!({"function": "sum"})).unwrap(); + assert_eq!(r["output"], "B5:C5"); + assert_eq!(v(&s, "B5"), Value::Number(6.0)); + assert_eq!(v(&s, "C5"), Value::Number(60.0)); + assert_eq!(v(&s, "A5"), Value::Empty, "text columns get no total"); + s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "average", "direction": "rows"})).unwrap(); + assert_eq!(v(&s, "D2"), Value::Number(5.5)); + s.execute("analysis.addTotal", json!({"range": "B1:C4", "function": "runningTotal", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "D4"), Value::Number(6.0), "running total down column B"); + assert_eq!(v(&s, "E4"), Value::Number(60.0)); + s.execute("analysis.addTotal", json!({"range": "B1:B4", "function": "percentTotal", "overwrite": true})).unwrap(); + assert_eq!(v(&s, "C4"), Value::Number(0.5), "overwrite replaces the C column cell next to B"); + assert_eq!(s.doc().unwrap().undo.len(), before + 4, "one undo step per call"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(v(&s, "C4"), Value::Number(30.0)); + // A second sum into the occupied row is refused rather than overwriting. + assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4"})).is_err()); +} + +#[test] +fn analysis_add_total_refuses_bad_and_huge_input() { + let mut s = s(); + quick_analysis_block(&mut s); + // Empty params on a single cell, unknown function, no numbers, whole columns, no room. + assert!(s.execute("analysis.addTotal", json!({})).is_err()); + assert!(s.execute("analysis.addTotal", json!({"range": "A1:C4", "function": "median"})).is_err()); + assert!(s.execute("analysis.addTotal", json!({"range": "A1:A4"})).is_err()); + let before = s.doc().unwrap().undo.len(); + let r = s.execute("analysis.addTotal", json!({"range": "B:C"})).unwrap(); + assert_eq!(r["output"], "B5:C5", "whole columns are clipped to the used range"); + assert_eq!(s.doc().unwrap().undo.len(), before + 1); + s.execute("cell.set", json!({"cell": "B1048575", "input": "1"})).unwrap(); + s.execute("cell.set", json!({"cell": "B1048576", "input": "2"})).unwrap(); + assert!(s.execute("analysis.addTotal", json!({"range": "B1048575:C1048576"})).is_err(), "no row below the last one"); + assert!(s.execute("analysis.addTotal", json!({"range": "B1:C1048576", "function": "runningTotal"})).is_err(), "per-cell block over the cap"); +} + +#[test] +fn analysis_add_sparklines_one_per_row_in_one_undo_step() { + let mut s = s(); + quick_analysis_block(&mut s); + let before = s.doc().unwrap().undo.len(); + let r = s.execute("analysis.addSparklines", json!({"range": "A1:C4", "type": "column"})).unwrap(); + assert_eq!(r["output"], "D2:D4", "header row and label column are skipped"); + let sparks = s.doc().unwrap().wb.active().unwrap().sparklines.clone(); + assert_eq!(sparks.len(), 3); + assert!(sparks.iter().any(|x| x.cell == CellRef::parse("D3").unwrap() && x.source == "B3:C3")); + assert_eq!(s.doc().unwrap().undo.len(), before + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty()); + assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err()); +} diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index a171199a1c..8b8a3bc465 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -2,7 +2,7 @@ //! //! `cargo run --release -p gridcraft-ui-egui --example snapshot -- [--sample sales] [--in file.xlsx] //! [--size 1440x900] [--scale 2] [--cmd 'id={json}']... [--tab Insert] [--dark] [--language en|zh|ja|ko|ru|pt|cs] -//! [--dialog 'name={json}'] [--hf-edit header|footer] out.png` +//! [--dialog 'name={json}'] [--quick-analysis formatting|charts|totals|tables|sparklines] [--hf-edit header|footer] out.png` use gridcraft_engine::Session; use gridcraft_ui_egui::SheetApp; @@ -22,6 +22,7 @@ fn main() { let mut dialog: Option = None; let mut language: Option = None; let mut hf_edit: Option = None; + let mut quick: Option = None; let mut out = "snapshot.png".to_string(); let mut i = 0; while i < args.len() { @@ -67,6 +68,10 @@ fn main() { i += 1; dialog = args.get(i).cloned(); } + "--quick-analysis" => { + i += 1; + quick = args.get(i).cloned(); + } "--hf-edit" => { i += 1; hf_edit = args.get(i).cloned(); @@ -118,6 +123,19 @@ fn main() { d.split_once('=').map(|(a, b)| (a, serde_json::from_str(b).unwrap_or(json!({})))).unwrap_or((d.as_str(), json!({}))); app.open_dialog(name, p); } + if let Some(name) = &quick { + use gridcraft_ui_egui::quick_analysis::Tab; + app.grid.quick_analysis.tab = match name.as_str() { + "charts" => Tab::Charts, + "totals" => Tab::Totals, + "tables" => Tab::Tables, + "sparklines" => Tab::Sparklines, + _ => Tab::Formatting, + }; + if let Err(e) = gridcraft_ui_egui::quick_analysis::toggle(&mut app, Some(true)) { + eprintln!("quick analysis: {e}"); + } + } // Page Layout view: edit the first page's centre header (or footer) section. let active = app.session.active().and_then(|d| d.wb.active().cloned().map(|s| (d.wb.active_sheet, s))); if let (Some(part), Some((si, sh))) = (&hf_edit, active) { diff --git a/crates/ui-egui/src/grid.rs b/crates/ui-egui/src/grid.rs index d0eef85668..1f9efbad6a 100644 --- a/crates/ui-egui/src/grid.rs +++ b/crates/ui-egui/src/grid.rs @@ -96,6 +96,8 @@ pub struct GridState { /// Page ranges for Page Break Preview, cached per (doc uid, revision, sheet). pub pages: Option<((u64, u64, usize), Vec<(RangeRef, u32)>)>, pub header_menu: Option<(Pos2, bool)>, + /// Quick Analysis button and popup (Ctrl+Q). + pub quick_analysis: crate::quick_analysis::State, /// Page Layout view pagination, cached per (doc uid, revision, sheet, rows, columns). pub paper: Option, /// Header or footer being edited in place (Page Layout view). @@ -624,6 +626,7 @@ pub fn show(app: &mut SheetApp, ui: &mut egui::Ui) { list_picker(app, ui, &geo, previous_popups.1 == app.grid.list_picker); header_menu(app, ui, previous_popups.2 == app.grid.header_menu); context_menu(app, ui); + crate::quick_analysis::show(app, ui, &geo, sh); let track_x = if rtl { (available.left(), rect.left()) } else { (rect.right(), available.right()) }; vertical_scrollbar(app, ui, sh, &geo, track_x, max_y, &t); if app.session.clipboard.is_some() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 406cc3dd51..25b4feb01b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -565,6 +565,30 @@ const JAPANESE: &[(&str, &str)] = &[ ("Workbook calculation", "ブックの計算"), ("Enable iterative calculation", "反復計算を行う"), ("Calculation settings are saved with the workbook.", "計算の設定はブックと共に保存されます。"), + ("Quick Analysis (Ctrl+Q)", "クイック分析 (Ctrl+Q)"), + ("Formatting", "書式設定"), + ("Charts", "グラフ"), + ("Totals", "集計"), + ("Tables", "テーブル"), + ("Color Scale", "カラー スケール"), + ("Icon Set", "アイコン セット"), + ("Greater Than…", "指定の値より大きい…"), + ("Clear Rules", "ルールのクリア"), + ("Clustered Column", "集合縦棒"), + ("Line", "折れ線"), + ("Pie", "円"), + ("Bar", "横棒"), + ("Scatter", "散布図"), + ("Recommended Charts", "おすすめグラフ"), + ("Sum", "合計"), + ("Average", "平均"), + ("Count", "個数"), + ("% Total", "合計に対する割合"), + ("Running Total", "累計"), + ("By Column", "列ごと"), + ("By Row", "行ごと"), + ("Column", "縦棒"), + ("Win/Loss", "勝敗"), ]; #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index ca2e559428..fadf40d50a 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -391,6 +391,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "More\nFunctions" => "Další\nfunkce", "Sheet Options|View" => "Zobrazit", "Print" => "Tisknout", + "Quick Analysis (Ctrl+Q)" => "Rychlá analýza (Ctrl+Q)", + "Formatting" => "Formátování", + "Charts" => "Grafy", + "Totals" => "Součty", + "Tables" => "Tabulky", + "Color Scale" => "Barevná škála", + "Icon Set" => "Sada ikon", + "Greater Than…" => "Větší než…", + "Clear Rules" => "Vymazat pravidla", + "Clustered Column" => "Skupinový sloupcový", + "Line" => "Spojnicový", + "Pie" => "Výsečový", + "Bar" => "Pruhový", + "Scatter" => "Bodový", + "Recommended Charts" => "Doporučené grafy", + "Sum" => "Součet", + "Average" => "Průměr", + "Count" => "Počet", + "% Total" => "% z celku", + "Running Total" => "Průběžný součet", + "By Column" => "Podle sloupců", + "By Row" => "Podle řádků", + "Column" => "Sloupec", + "Win/Loss" => "Zisk/ztráta", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2ad37f675f..2fc143105b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -394,6 +394,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Dunkel", "Sheet Options|View" => "Anzeige", "Print" => "Drucken", + "Quick Analysis (Ctrl+Q)" => "Schnellanalyse (Strg+Q)", + "Formatting" => "Formatierung", + "Charts" => "Diagramme", + "Totals" => "Ergebnisse", + "Tables" => "Tabellen", + "Color Scale" => "Farbskala", + "Icon Set" => "Symbolsatz", + "Greater Than…" => "Größer als…", + "Clear Rules" => "Regeln löschen", + "Clustered Column" => "Gruppierte Säulen", + "Line" => "Linie", + "Pie" => "Kreis", + "Bar" => "Balken", + "Scatter" => "Punkt (XY)", + "Recommended Charts" => "Empfohlene Diagramme", + "Sum" => "Summe", + "Average" => "Mittelwert", + "Count" => "Anzahl", + "% Total" => "% des Gesamtergebnisses", + "Running Total" => "Laufende Summe", + "By Column" => "Nach Spalte", + "By Row" => "Nach Zeile", + "Column" => "Säule", + "Win/Loss" => "Gewinn/Verlust", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index da41bd7113..faad158341 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Dark" => "Oscuro", "Sheet Options|View" => "Ver", "Print" => "Imprimir", + "Quick Analysis (Ctrl+Q)" => "Análisis rápido (Ctrl+Q)", + "Formatting" => "Formato", + "Charts" => "Gráficos", + "Totals" => "Totales", + "Tables" => "Tablas", + "Color Scale" => "Escala de color", + "Icon Set" => "Conjunto de iconos", + "Greater Than…" => "Mayor que…", + "Clear Rules" => "Borrar reglas", + "Clustered Column" => "Columna agrupada", + "Line" => "Línea", + "Pie" => "Circular", + "Bar" => "Barras", + "Scatter" => "Dispersión", + "Recommended Charts" => "Gráficos recomendados", + "Sum" => "Suma", + "Average" => "Promedio", + "Count" => "Recuento", + "% Total" => "% del total", + "Running Total" => "Total acumulado", + "By Column" => "Por columna", + "By Row" => "Por fila", + "Column" => "Columna", + "Win/Loss" => "Ganancia/pérdida", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 7bf9fd100d..04dd35b973 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -383,6 +383,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Calcul du classeur", "Enable iterative calculation" => "Classeur Excel (*.xlsx)", "Calculation settings are saved with the workbook." => "Modifier le type de fichier", + "Quick Analysis (Ctrl+Q)" => "Analyse rapide (Ctrl+Q)", + "Formatting" => "Mise en forme", + "Charts" => "Graphiques", + "Totals" => "Totaux", + "Tables" => "Tableaux", + "Color Scale" => "Échelle de couleurs", + "Icon Set" => "Jeu d'icônes", + "Greater Than…" => "Supérieur à…", + "Clear Rules" => "Effacer les règles", + "Clustered Column" => "Histogramme groupé", + "Line" => "Courbe", + "Pie" => "Secteurs", + "Bar" => "Barres", + "Scatter" => "Nuage de points", + "Recommended Charts" => "Graphiques recommandés", + "Sum" => "Somme", + "Average" => "Moyenne", + "Count" => "Nombre", + "% Total" => "% du total", + "Running Total" => "Total cumulé", + "By Column" => "Par colonne", + "By Row" => "Par ligne", + "Column" => "Colonne", + "Win/Loss" => "Gain/perte", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index b684c78868..480e1fa417 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "통합 문서 계산", "Enable iterative calculation" => "반복 계산 사용", "Calculation settings are saved with the workbook." => "계산 설정은 통합 문서와 함께 저장됩니다.", + "Quick Analysis (Ctrl+Q)" => "빠른 분석 (Ctrl+Q)", + "Formatting" => "서식", + "Charts" => "차트", + "Totals" => "합계", + "Tables" => "표", + "Color Scale" => "색 구성표", + "Icon Set" => "아이콘 집합", + "Greater Than…" => "보다 큼…", + "Clear Rules" => "규칙 지우기", + "Clustered Column" => "묶은 세로 막대형", + "Line" => "꺾은선형", + "Pie" => "원형", + "Bar" => "가로 막대형", + "Scatter" => "분산형", + "Recommended Charts" => "추천 차트", + "Sum" => "합계", + "Average" => "평균", + "Count" => "개수", + "% Total" => "총합계 비율", + "Running Total" => "누계", + "By Column" => "열 기준", + "By Row" => "행 기준", + "Column" => "열", + "Win/Loss" => "이익/손실", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index b554ef9776..8395b82238 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -394,6 +394,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Cálculo da pasta de trabalho", "Enable iterative calculation" => "Habilitar cálculo iterativo", "Calculation settings are saved with the workbook." => "As configurações de cálculo são salvas com a pasta de trabalho.", + "Quick Analysis (Ctrl+Q)" => "Análise rápida (Ctrl+Q)", + "Formatting" => "Formatação", + "Charts" => "Gráficos", + "Totals" => "Totais", + "Tables" => "Tabelas", + "Color Scale" => "Escala de cor", + "Icon Set" => "Conjunto de ícones", + "Greater Than…" => "Maior que…", + "Clear Rules" => "Limpar regras", + "Clustered Column" => "Colunas agrupadas", + "Line" => "Linha", + "Pie" => "Pizza", + "Bar" => "Barras", + "Scatter" => "Dispersão", + "Recommended Charts" => "Gráficos recomendados", + "Sum" => "Soma", + "Average" => "Média", + "Count" => "Contagem", + "% Total" => "% do total", + "Running Total" => "Total acumulado", + "By Column" => "Por coluna", + "By Row" => "Por linha", + "Column" => "Coluna", + "Win/Loss" => "Ganho/perda", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index c8f0445d8c..e6273c486b 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -393,6 +393,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "Вычисления в книге", "Enable iterative calculation" => "Включить итеративные вычисления", "Calculation settings are saved with the workbook." => "Параметры вычислений сохраняются вместе с книгой.", + "Quick Analysis (Ctrl+Q)" => "Быстрый анализ (Ctrl+Q)", + "Formatting" => "Форматирование", + "Charts" => "Диаграммы", + "Totals" => "Итоги", + "Tables" => "Таблицы", + "Color Scale" => "Цветовая шкала", + "Icon Set" => "Набор значков", + "Greater Than…" => "Больше…", + "Clear Rules" => "Удалить правила", + "Clustered Column" => "Гистограмма с группировкой", + "Line" => "График", + "Pie" => "Круговая", + "Bar" => "Линейчатая", + "Scatter" => "Точечная", + "Recommended Charts" => "Рекомендуемые диаграммы", + "Sum" => "Сумма", + "Average" => "Среднее", + "Count" => "Количество", + "% Total" => "% от итога", + "Running Total" => "Нарастающий итог", + "By Column" => "По столбцам", + "By Row" => "По строкам", + "Column" => "Столбец", + "Win/Loss" => "Выигрыш/проигрыш", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index d1cf704cba..440962086e 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -385,6 +385,30 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "Workbook calculation" => "工作簿计算", "Enable iterative calculation" => "启用迭代计算", "Calculation settings are saved with the workbook." => "计算设置随工作簿一起保存。", + "Quick Analysis (Ctrl+Q)" => "快速分析 (Ctrl+Q)", + "Formatting" => "格式化", + "Charts" => "图表", + "Totals" => "汇总", + "Tables" => "表", + "Color Scale" => "色阶", + "Icon Set" => "图标集", + "Greater Than…" => "大于…", + "Clear Rules" => "清除规则", + "Clustered Column" => "簇状柱形图", + "Line" => "折线图", + "Pie" => "饼图", + "Bar" => "条形图", + "Scatter" => "散点图", + "Recommended Charts" => "推荐的图表", + "Sum" => "求和", + "Average" => "平均值", + "Count" => "计数", + "% Total" => "占总计的百分比", + "Running Total" => "累计", + "By Column" => "按列", + "By Row" => "按行", + "Column" => "柱形", + "Win/Loss" => "盈亏", _ => return None, }) } diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fe9f7bf51d..2d14cc031a 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -129,6 +129,8 @@ pub enum Icon { OpenFolder, Info, Print, + /// Quick Analysis: a small table with a spark. + QuickAnalysis, } struct G<'a> { @@ -706,6 +708,13 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, c: Color32) { g.line(&[(4.5, 9.0), (4.5, 14.5), (11.5, 14.5), (11.5, 9.0), (4.5, 9.0)], c, 1.1); g.circle(12.3, 7.6, 0.6, Some(c), None); } + Icon::QuickAnalysis => { + g.rect(2.0, 3.0, 12.0, 10.0, None, Some(c)); + g.stroke(&[(2.0, 6.5), (14.0, 6.5)], light); + g.stroke(&[(6.0, 3.0), (6.0, 13.0)], light); + g.stroke(&[(10.0, 3.0), (10.0, 13.0)], light); + g.line(&[(10.0, 1.0), (6.5, 8.0), (9.5, 8.0), (6.5, 15.0)], BLUE, 1.7); + } } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0b19b2551d..c154945210 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ pub mod panes; pub mod paper_view; pub mod pivot_pane; pub mod printing; +pub mod quick_analysis; pub mod ribbon; pub mod selection_glide; pub mod tabs; @@ -531,6 +532,7 @@ impl SheetApp { self.ui.language = i18n::Language::Ja; Ok(json!({"language": i18n::Language::Ja})) } + "ui.quickAnalysis" => quick_analysis::toggle(self, p.get("open").and_then(Json::as_bool)), "ui.backstage" => { // `{"page": "info"}` opens File › Info; `{"page": "close"}` returns to the sheet. match p.get("page").and_then(Json::as_str).map(str::trim) { diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs new file mode 100644 index 0000000000..7bfa454d95 --- /dev/null +++ b/crates/ui-egui/src/quick_analysis.rs @@ -0,0 +1,364 @@ +//! Quick Analysis (Ctrl+Q): a small button at the bottom-right corner of a multi-cell selection +//! that opens a popup of one-click analyses. The popup is a thin front end: every tile runs an +//! engine command through `app.run` (conditional formats, charts, `analysis.addTotal`, tables, +//! pivot tables, `analysis.addSparklines`), so nothing here is UI-only logic worth testing apart +//! from which command a tile maps to ([`tiles`]). + +use egui::{Align2, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use gridcraft_engine::core::RangeRef; +use gridcraft_engine::model::Sheet; +use serde_json::{Value as Json, json}; + +use crate::SheetApp; +use crate::grid::{Drag, Geo}; +use crate::icons::{self, Icon}; +use crate::theme::{self, Tokens}; + +/// Side of the corner button, and its gap to the selection's corner (clear of the fill handle). +const BUTTON: f32 = 22.0; +const GAP: f32 = 6.0; +const TILE: egui::Vec2 = vec2(66.0, 62.0); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Tab { + #[default] + Formatting, + Charts, + Totals, + Tables, + Sparklines, +} + +impl Tab { + const ALL: [Tab; 5] = [Tab::Formatting, Tab::Charts, Tab::Totals, Tab::Tables, Tab::Sparklines]; + fn label(self) -> &'static str { + match self { + Tab::Formatting => "Formatting", + Tab::Charts => "Charts", + Tab::Totals => "Totals", + Tab::Tables => "Tables", + Tab::Sparklines => "Sparklines", + } + } +} + +#[derive(Default)] +pub struct State { + /// The selection the popup was opened for; it closes when the selection changes. + pub open: Option, + pub tab: Tab, + /// Totals by row (results to the right) instead of by column (results below). + pub by_rows: bool, +} + +/// What a tile does. +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + Run(&'static str, Json), + Dialog(&'static str, Json), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Glyph { + Icon(Icon), + Text(&'static str), + Bars, + Scale, + Dots, + Steps, + MiniColumns, + WinLoss, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Tile { + label: &'static str, + glyph: Glyph, + pub action: Action, +} + +fn tile(label: &'static str, glyph: Glyph, action: Action) -> Tile { + Tile { label, glyph, action } +} + +/// The tiles of a tab for the selection `range` (A1 text) on the sheet called `sheet_name`. +pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec { + use Action::{Dialog, Run}; + let cf = |rule: Json| Run("home.conditionalFormat", json!({"range": range, "rule": rule})); + let chart = |kind: &str| Run("insert.chart", json!({"range": range, "type": kind})); + let total = |f: &str| Run("analysis.addTotal", json!({"range": range, "function": f, "direction": if by_rows { "rows" } else { "columns" }})); + let spark = |kind: &str| Run("analysis.addSparklines", json!({"range": range, "type": kind})); + match tab { + Tab::Formatting => vec![ + tile("Data Bars", Glyph::Bars, cf(json!({"type": "dataBar"}))), + tile("Color Scale", Glyph::Scale, cf(json!({"type": "colorScale"}))), + tile("Icon Set", Glyph::Dots, cf(json!({"type": "iconSet"}))), + tile("Greater Than…", Glyph::Text(">"), Dialog("cfQuick", json!({"type": "cellIs", "operator": "greater", "title": "Greater Than…"}))), + tile("Top 10 Items", Glyph::Text("10"), cf(json!({"type": "top10", "rank": 10}))), + tile("Clear Rules", Glyph::Icon(Icon::Eraser), Run("home.clearRules", json!({"range": range}))), + ], + Tab::Charts => vec![ + tile("Clustered Column", Glyph::Icon(Icon::ChartBar), chart("column")), + tile("Line", Glyph::Icon(Icon::ChartLine), chart("line")), + tile("Pie", Glyph::Icon(Icon::ChartPie), chart("pie")), + tile("Bar", Glyph::Icon(Icon::Chart), chart("bar")), + tile("Scatter", Glyph::Icon(Icon::ChartScatter), chart("scatter")), + tile("Recommended Charts", Glyph::Icon(Icon::Chart), Run("insert.recommendedCharts", json!({"range": range}))), + ], + Tab::Totals => vec![ + tile("Sum", Glyph::Icon(Icon::Sum), total("sum")), + tile("Average", Glyph::Text("avg"), total("average")), + tile("Count", Glyph::Text("#"), total("count")), + tile("% Total", Glyph::Icon(Icon::Percent), total("percentTotal")), + tile("Running Total", Glyph::Steps, total("runningTotal")), + ], + Tab::Tables => vec![ + tile("Table", Glyph::Icon(Icon::Table), Run("insert.table", json!({"range": range}))), + tile( + "PivotTable", + Glyph::Icon(Icon::PivotTable), + Run("insert.pivotTable", json!({"source": format!("'{}'!{range}", sheet_name.replace('\'', "''"))})), + ), + ], + Tab::Sparklines => vec![ + tile("Line", Glyph::Icon(Icon::Sparkline), spark("line")), + tile("Column", Glyph::MiniColumns, spark("column")), + tile("Win/Loss", Glyph::WinLoss, spark("winLoss")), + ], + } +} + +/// Ctrl+Q and the `ui.quickAnalysis` command: opens the popup for the selection (or closes it). +/// Errors for a single cell, where there is nothing to analyse. +pub fn toggle(app: &mut SheetApp, on: Option) -> Result { + let sel = app.session.active().map(|d| d.selection.current()).ok_or("no workbook open")?; + let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); + if !want { + app.grid.quick_analysis.open = None; + } else if sel.is_single() { + return Err("Select at least two cells to use Quick Analysis.".into()); + } else { + app.grid.quick_analysis.open = Some(sel); + } + Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) +} + +/// Paints the corner button and, when open, the popup. Called once per grid frame. +pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { + let Some(d) = app.session.active() else { return }; + let sel = d.selection.current(); + let hidden = sel.is_single() + || app.editor.is_some() + || app.dialog.is_some() + || app.text_box_editor.is_some() + || app.grid.context_menu.is_some() + || geo.paper.is_some(); + // The popup belongs to one selection; a new one (or editing) closes it. + if hidden || app.grid.quick_analysis.open.is_some_and(|r| r != sel) { + app.grid.quick_analysis.open = None; + } + if hidden { + return; + } + let sheet_name = sh.name.clone(); + let ctx = ui.ctx().clone(); + let t = Tokens::get(&ctx); + let rect = geo.range_rect(sh, sel); + let corner = rect.right_bottom(); + let panes = geo.range_panes(RangeRef::cell(sel.end)); + let corner_visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); + // Below and right of the corner (clear of the fill handle); flipped inside when at an edge. + let area = geo.cells.shrink(2.0); + let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; + let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; + let button = geo.mirror_rect(Rect::from_min_size( + pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))), + vec2(BUTTON, BUTTON), + )); + let open = app.grid.quick_analysis.open.is_some(); + // While the mouse is down (selecting, filling) the button stays out of the way. + let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down()); + let lang = crate::i18n::current(&ctx); + if corner_visible && (open || !busy) { + let mut clicked = false; + egui::Area::new(Id::new("quick_analysis_button")).fixed_pos(button.min).order(Order::Foreground).show(&ctx, |ui| { + let (r, resp) = ui.allocate_exact_size(button.size(), Sense::click()); + let fill = if resp.is_pointer_button_down_on() || open { + t.pressed + } else if resp.hovered() { + t.hover + } else { + t.menu_bg + }; + ui.painter().rect_filled(r, 4.0, fill); + ui.painter().rect_stroke(r, 4.0, Stroke::new(1.0, t.separator), StrokeKind::Inside); + icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), Icon::QuickAnalysis, t.accent); + clicked = resp.on_hover_text(lang.tr("Quick Analysis (Ctrl+Q)")).clicked(); + }); + if clicked { + let _ = toggle(app, None); + } + } + let Some(opened_for) = app.grid.quick_analysis.open else { return }; + let pos = pos2(button.left(), button.bottom() + 4.0); + let mut picked: Option = None; + let resp = egui::Area::new(Id::new("quick_analysis_popup")).fixed_pos(pos).order(Order::Foreground).constrain(true).show(&ctx, |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + let state = &mut app.grid.quick_analysis; + ui.horizontal(|ui| { + for tab in Tab::ALL { + if ui.selectable_label(state.tab == tab, lang.tr(tab.label())).clicked() { + state.tab = tab; + } + } + }); + ui.separator(); + if state.tab == Tab::Totals { + ui.horizontal(|ui| { + ui.selectable_value(&mut state.by_rows, false, lang.tr("By Column")); + ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")); + }); + } + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for item in tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows) { + if paint_tile(ui, &t, &item, lang.tr(item.label)) { + picked = Some(item.action.clone()); + } + } + }); + }); + }); + let outside_click = ctx.input(|i| i.pointer.any_pressed()) + && ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !resp.response.rect.contains(p) && !button.contains(p)); + if let Some(action) = picked { + app.grid.quick_analysis.open = None; + match action { + Action::Run(id, params) => app.run_or_alert(id, params), + Action::Dialog(name, params) => app.open_dialog(name, params), + } + } else if outside_click || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + app.grid.quick_analysis.open = None; + } +} + +/// One option of the popup: a small picture over a wrapped label. True when clicked. +fn paint_tile(ui: &mut Ui, t: &Tokens, item: &Tile, label: &str) -> bool { + let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click()); + if resp.is_pointer_button_down_on() { + ui.painter().rect_filled(rect, 4.0, t.pressed); + } else if resp.hovered() { + ui.painter().rect_filled(rect, 4.0, t.hover); + } + let art = Rect::from_center_size(pos2(rect.center().x, rect.top() + 18.0), vec2(26.0, 26.0)); + paint_glyph(ui, t, item.glyph, art); + let galley = ui.painter().layout(label.to_string(), theme::ui_font(11.0), t.text, TILE.x - 4.0); + let at = pos2(rect.center().x - galley.size().x / 2.0, rect.top() + 34.0); + ui.painter().galley(at, galley, t.text); + resp.clicked() +} + +fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) { + let p = ui.painter(); + let (green, blue, red, yellow) = (icons::GREEN, icons::BLUE, icons::RED, icons::YELLOW); + let cell = |i: f32, j: f32| Rect::from_min_size(r.min + vec2(i * r.width() / 3.0, j * r.height() / 3.0), vec2(r.width() / 3.0, r.height() / 3.0)); + match glyph { + Glyph::Icon(icon) => icons::paint(p, r, icon, t.text), + Glyph::Text(s) => { + p.text(r.center(), Align2::CENTER_CENTER, s, theme::ui_bold(15.0), t.accent); + } + Glyph::Bars => { + for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() { + let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0)); + p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, blue); + } + } + Glyph::Scale => { + for (i, c) in [red, yellow, green].into_iter().enumerate() { + p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); + } + } + Glyph::Dots => { + for (j, c) in [green, yellow, red].into_iter().enumerate() { + p.circle_filled(cell(1.0, j as f32).center(), 3.2, c); + } + } + Glyph::Steps => { + for i in 0..3 { + let h = r.height() * (0.35 + 0.28 * i as f32); + p.rect_filled( + Rect::from_min_max( + pos2(r.left() + i as f32 * r.width() / 3.0 + 1.0, r.bottom() - h), + pos2(r.left() + (i + 1) as f32 * r.width() / 3.0 - 1.0, r.bottom()), + ), + 1.0, + green, + ); + } + } + Glyph::MiniColumns => { + for (i, h) in [0.5, 0.9, 0.65].into_iter().enumerate() { + let x = r.left() + i as f32 * r.width() / 3.0 + 2.0; + p.rect_filled(Rect::from_min_max(pos2(x, r.bottom() - r.height() * h), pos2(x + r.width() / 3.0 - 4.0, r.bottom())), 1.0, blue); + } + } + Glyph::WinLoss => { + let mid = r.center().y; + for (i, up) in [true, false, true].into_iter().enumerate() { + let x = r.left() + i as f32 * r.width() / 3.0 + 2.0; + let (a, b) = if up { (mid - 7.0, mid - 1.0) } else { (mid + 1.0, mid + 7.0) }; + p.rect_filled(Rect::from_min_max(pos2(x, a), pos2(x + r.width() / 3.0 - 4.0, b)), 1.0, if up { green } else { red }); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gridcraft_engine::Session; + + /// A header row, a label column and two numeric columns on Sheet1. + fn session() -> (Session, String) { + let mut s = Session::new(); + s.new_workbook(); + for (a, v) in [("A1", "Item"), ("B1", "Q1"), ("C1", "Q2"), ("A2", "x"), ("A3", "y"), ("A4", "z")] { + s.execute("cell.set", json!({"cell": a, "input": v})).unwrap(); + } + for (r, (q1, q2)) in [(1, 10), (2, 20), (3, 30)].into_iter().enumerate() { + s.execute("cell.set", json!({"cell": format!("B{}", r + 2), "input": q1.to_string()})).unwrap(); + s.execute("cell.set", json!({"cell": format!("C{}", r + 2), "input": q2.to_string()})).unwrap(); + } + let name = s.doc().unwrap().wb.active().unwrap().name.clone(); + (s, name) + } + + #[test] + fn every_engine_tile_runs_on_a_selection() { + for tab in Tab::ALL { + for by_rows in [false, true] { + let n = tiles(tab, "A1:C4", "Sheet1", by_rows).len(); + for i in 0..n { + let (mut s, name) = session(); + let item = tiles(tab, "A1:C4", &name, by_rows).remove(i); + if let Action::Run(id, params) = &item.action { + s.execute(id, params.clone()).unwrap_or_else(|e| panic!("{} / {}: {e}", tab.label(), item.label)); + } + } + } + } + } + + #[test] + fn dialog_tile_and_single_cell_are_not_engine_runs() { + let formatting = tiles(Tab::Formatting, "A1:C4", "Sheet1", false); + assert!(formatting.iter().any(|t| matches!(&t.action, Action::Dialog("cfQuick", _)))); + // A programmatic open on a single cell is an error, not a popup. + let (s, _) = session(); + let mut app = SheetApp::new(s, Default::default()); + assert!(toggle(&mut app, Some(true)).is_err()); + app.run("selection.set", json!({"range": "A1:C4"})).unwrap(); + assert_eq!(toggle(&mut app, Some(true)).unwrap(), json!({"open": true})); + assert_eq!(app.run("ui.quickAnalysis", json!({"open": false})).unwrap(), json!({"open": false})); + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index e8291accdc..b8054f9a0f 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -2429,6 +2429,11 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T if shift => Some(("formulas.autoSum", json!({}))), Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), + Key::Q => { + // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert. + let _ = crate::quick_analysis::toggle(app, None); + None + } Key::Num1 => { app.open_dialog("formatCells", json!({})); None diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 10abcbccc2..50048c09ea 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (AutoFit reserves filter dropdown space, observed against Windows Excel) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (Quick Analysis, Ctrl+Q) · **Target:** Microsoft Excel (Microsoft 365), Excel for Mac 16.113.4 Interaction, controls and feel, against Excel. Part of [target-app-parity.md](target-app-parity.md). **UI/UX fidelity: ~55% ready, 50–80 h** (estimated). Ribbon command coverage is measured @@ -58,7 +58,7 @@ this logic, with one undo step. | Context menu on cells | 16 items (Cut, Copy, Paste, Paste Special, Insert, Delete, Clear Contents, Filter by value, Sort, New Comment, New Note, Format Cells, Pick From Drop-down List, Define Name, Link). Insert Copied Cells (Insert Cut Cells for whole rows/columns) while the clipboard holds a copy (#21). Missing: Insert Cut Cells for a cell block, paste-option icons, Quick Analysis, Get Data from Table, Show Changes, Smart Lookup | | Move and resize charts, pictures and shapes | charts can't be resized (#190) | | Context menus on row/column headers, sheet tabs, charts, shapes | headers and tabs done; objects partial | -| Quick Analysis (Ctrl+Q) | missing | +| Quick Analysis (Ctrl+Q) | done (#791): button at the selection's bottom-right corner (hidden while editing or dragging) and Ctrl+Q open a popup with Formatting (data bars, colour scale, icon set, greater than, top 10, clear), Charts, Totals (`analysis.addTotal`: sum, average, count, % total, running total, by column or row), Tables (table, PivotTable) and Sparklines (`analysis.addSparklines`); every tile is an engine command. Missing: hover preview, Quick Analysis for non-contiguous selections, Excel's exact tile set | | Smooth scrolling, scrollbars | done; vertical scrollbar added 10-09 (#73); horizontal scrollbar reported missing (#176) | | Text overflow into empty neighbours, wrap, rotation, shrink to fit | done | @@ -123,7 +123,8 @@ otherwise. Number-format and border keys match the physical key (Ctrl+Shift+4, w | F5, Shift+F5 (Mac), F7, Shift+F9, Ctrl+Alt+F9, F12, Ctrl+F4 | same | Go To, Find, Spelling, calculate sheet / all, Save As, close | **added** | | Shift+F10, Alt+Shift+F10, Ctrl+F1 | Shift+F10, Cmd+Option+R | context menu, Error Checking, ribbon | **added** | | F1, F3, F4 (repeat), F6 / Shift+F6, F8 / Shift+F8, F11, End mode | same | help, Paste Name, Repeat, pane cycling, extend/add mode, chart sheet | missing (no such feature yet) | -| Ctrl+6, Ctrl+8, Ctrl+Q, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, Quick Analysis, argument names, Function Arguments, formula bar height, tooltips | missing | +| Ctrl+Q | Ctrl+Q | Quick Analysis | **added** (#791) | +| Ctrl+6, Ctrl+8, Ctrl+Shift+A, Ctrl+A after a function name, Ctrl+Shift+U, Ctrl+Alt+P | same | objects, outline symbols, argument names, Function Arguments, formula bar height, tooltips | missing | | Ctrl+Shift+Page Up / Down, Ctrl+Alt+5, Ctrl+Shift+F1, Ctrl+F5–F10, Alt+F8 / F11 / F12 | same | group sheets, shape cycling, full screen, window keys, macros, VBA, Power Query | missing | | — | Cmd+= (calculate), Cmd+T (references while editing; F4 works), Shift+F7, Cmd+Shift+L | Mac-only extras | missing (Cmd+= is egui's zoom key; no thesaurus or Modify Cell Style) | @@ -152,7 +153,7 @@ by rule and will never match Office's, by design. ## Work (50–80 h) -Key tips 3–5 · remaining shortcuts with their features 2–4 · context menus and Quick Analysis 5–8 · Page Layout view +Key tips 3–5 · remaining shortcuts with their features 2–4 · context menus 3–5 · Page Layout view 8–12 · Options dialog and ribbon/QAT customization 6–10 · accessibility 12–18 · selection and scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. @@ -160,6 +161,7 @@ scrollbar bugs 2–4 · pixel/feel pass against observed Excel 7–12. | Date | Change | Summary | |---|---|---| +| 2026-10-12 | minor | Quick Analysis (Ctrl+Q): corner button and popup with formatting, charts, totals, tables and sparklines; new commands `analysis.addTotal` and `analysis.addSparklines` (#791) | | 2026-10-11 | minor | AutoFit accounts for table and ordinary filter dropdowns, including low zoom; header text excludes the button area | | 2026-10-11 | minor | Outline band for grouped rows and columns, Show / Hide Detail on the Data tab, numpad navigation keys in shortcuts (#373) | | 2026-10-11 | minor | Shift+Space / Ctrl+Space no longer start an edit; Control+Space selects the column on Mac (#338) | From a7e1a4a99bdda6698dbdff64a9876498246c355a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:05:29 +0200 Subject: [PATCH 004/425] Quick Analysis: button tests, several-areas refusal, more formatting tiles (#791) Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/i18n.rs | 4 + crates/ui-egui/src/i18n/cs.rs | 4 + crates/ui-egui/src/i18n/de.rs | 4 + crates/ui-egui/src/i18n/es.rs | 4 + crates/ui-egui/src/i18n/fr.rs | 4 + crates/ui-egui/src/i18n/ko.rs | 4 + crates/ui-egui/src/i18n/pt.rs | 4 + crates/ui-egui/src/i18n/ru.rs | 4 + crates/ui-egui/src/i18n/zh.rs | 4 + crates/ui-egui/src/quick_analysis.rs | 99 ++++++++++++++----- crates/ui-egui/src/ribbon.rs | 9 +- crates/ui-egui/tests/quick_analysis_button.rs | 84 ++++++++++++++++ 12 files changed, 199 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/tests/quick_analysis_button.rs diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 25b4feb01b..3df27f8a75 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -589,6 +589,10 @@ const JAPANESE: &[(&str, &str)] = &[ ("By Row", "行ごと"), ("Column", "縦棒"), ("Win/Loss", "勝敗"), + ("Green Data Bars", "緑のデータ バー"), + ("Blue-White-Red Scale", "青-白-赤のスケール"), + ("White-Green Scale", "白-緑のスケール"), + ("Duplicate Values", "重複する値"), ]; #[cfg(test)] diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index fadf40d50a..e93dc7f01c 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -415,6 +415,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Podle řádků", "Column" => "Sloupec", "Win/Loss" => "Zisk/ztráta", + "Green Data Bars" => "Zelené datové čáry", + "Blue-White-Red Scale" => "Škála modrá-bílá-červená", + "White-Green Scale" => "Škála bílá-zelená", + "Duplicate Values" => "Duplicitní hodnoty", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 2fc143105b..70ed6204ef 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -418,6 +418,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Nach Zeile", "Column" => "Säule", "Win/Loss" => "Gewinn/Verlust", + "Green Data Bars" => "Grüne Datenbalken", + "Blue-White-Red Scale" => "Blau-Weiß-Rot-Skala", + "White-Green Scale" => "Weiß-Grün-Skala", + "Duplicate Values" => "Doppelte Werte", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index faad158341..3230e48ff8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Por fila", "Column" => "Columna", "Win/Loss" => "Ganancia/pérdida", + "Green Data Bars" => "Barras de datos verdes", + "Blue-White-Red Scale" => "Escala azul-blanco-rojo", + "White-Green Scale" => "Escala blanco-verde", + "Duplicate Values" => "Valores duplicados", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 04dd35b973..fb9caa2ff4 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -407,6 +407,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Par ligne", "Column" => "Colonne", "Win/Loss" => "Gain/perte", + "Green Data Bars" => "Barres de données vertes", + "Blue-White-Red Scale" => "Échelle bleu-blanc-rouge", + "White-Green Scale" => "Échelle blanc-vert", + "Duplicate Values" => "Valeurs en double", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 480e1fa417..948b3c8333 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "행 기준", "Column" => "열", "Win/Loss" => "이익/손실", + "Green Data Bars" => "녹색 데이터 막대", + "Blue-White-Red Scale" => "파랑-흰색-빨강 눈금", + "White-Green Scale" => "흰색-녹색 눈금", + "Duplicate Values" => "중복 값", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/pt.rs b/crates/ui-egui/src/i18n/pt.rs index 8395b82238..6118274fb9 100644 --- a/crates/ui-egui/src/i18n/pt.rs +++ b/crates/ui-egui/src/i18n/pt.rs @@ -418,6 +418,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "Por linha", "Column" => "Coluna", "Win/Loss" => "Ganho/perda", + "Green Data Bars" => "Barras de dados verdes", + "Blue-White-Red Scale" => "Escala azul-branco-vermelho", + "White-Green Scale" => "Escala branco-verde", + "Duplicate Values" => "Valores duplicados", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index e6273c486b..e7930a0d6e 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -417,6 +417,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "По строкам", "Column" => "Столбец", "Win/Loss" => "Выигрыш/проигрыш", + "Green Data Bars" => "Зелёные гистограммы", + "Blue-White-Red Scale" => "Шкала сине-бело-красная", + "White-Green Scale" => "Шкала бело-зелёная", + "Duplicate Values" => "Повторяющиеся значения", _ => return None, }) } diff --git a/crates/ui-egui/src/i18n/zh.rs b/crates/ui-egui/src/i18n/zh.rs index 440962086e..9bbd6514d7 100644 --- a/crates/ui-egui/src/i18n/zh.rs +++ b/crates/ui-egui/src/i18n/zh.rs @@ -409,6 +409,10 @@ pub(super) fn translate(text: &str) -> Option<&'static str> { "By Row" => "按行", "Column" => "柱形", "Win/Loss" => "盈亏", + "Green Data Bars" => "绿色数据条", + "Blue-White-Red Scale" => "蓝-白-红色阶", + "White-Green Scale" => "白-绿色阶", + "Duplicate Values" => "重复值", _ => return None, }) } diff --git a/crates/ui-egui/src/quick_analysis.rs b/crates/ui-egui/src/quick_analysis.rs index 7bfa454d95..94032e4d38 100644 --- a/crates/ui-egui/src/quick_analysis.rs +++ b/crates/ui-egui/src/quick_analysis.rs @@ -4,7 +4,7 @@ //! pivot tables, `analysis.addSparklines`), so nothing here is UI-only logic worth testing apart //! from which command a tile maps to ([`tiles`]). -use egui::{Align2, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui::{Align2, Color32, Id, Order, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; use gridcraft_engine::core::RangeRef; use gridcraft_engine::model::Sheet; use serde_json::{Value as Json, json}; @@ -64,6 +64,9 @@ enum Glyph { Text(&'static str), Bars, Scale, + GreenBars, + BlueScale, + GreenScale, Dots, Steps, MiniColumns, @@ -96,6 +99,12 @@ pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec"), Dialog("cfQuick", json!({"type": "cellIs", "operator": "greater", "title": "Greater Than…"}))), tile("Top 10 Items", Glyph::Text("10"), cf(json!({"type": "top10", "rank": 10}))), tile("Clear Rules", Glyph::Icon(Icon::Eraser), Run("home.clearRules", json!({"range": range}))), + tile("Green Data Bars", Glyph::GreenBars, cf(json!({"type": "dataBar", "color": "#63BE7B"}))), + tile("Blue-White-Red Scale", Glyph::BlueScale, cf(json!({"type": "colorScale", "colors": ["#5A8AC6", "#FCFCFF", "#F8696B"]}))), + tile("White-Green Scale", Glyph::GreenScale, cf(json!({"type": "colorScale", "colors": ["#FCFCFF", "#63BE7B"]}))), + tile("Top 10%", Glyph::Text("10%"), cf(json!({"type": "top10", "rank": 10, "percent": true}))), + tile("Below Average", Glyph::Text(" vec![ tile("Clustered Column", Glyph::Icon(Icon::ChartBar), chart("column")), @@ -131,7 +140,11 @@ pub fn tiles(tab: Tab, range: &str, sheet_name: &str, by_rows: bool) -> Vec) -> Result { - let sel = app.session.active().map(|d| d.selection.current()).ok_or("no workbook open")?; + let d = app.session.active().ok_or("no workbook open")?; + if d.selection.ranges.len() > 1 { + return Err("Quick Analysis works on one block of cells; select a single contiguous range.".into()); + } + let sel = d.selection.current(); let want = on.unwrap_or(app.grid.quick_analysis.open.is_none()); if !want { app.grid.quick_analysis.open = None; @@ -143,16 +156,38 @@ pub fn toggle(app: &mut SheetApp, on: Option) -> Result { Ok(json!({"open": app.grid.quick_analysis.open.is_some()})) } -/// Paints the corner button and, when open, the popup. Called once per grid frame. -pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { - let Some(d) = app.session.active() else { return }; - let sel = d.selection.current(); - let hidden = sel.is_single() +/// Whether the button (and popup) stay out of the way: a single cell or several areas, editing, +/// an open dialog or menu, and the paged views have no corner to hang them on. +pub fn is_hidden(app: &SheetApp, geo: &Geo, sh: &Sheet) -> bool { + let Some(d) = app.session.active() else { return true }; + d.selection.ranges.len() > 1 + || d.selection.current().is_single() || app.editor.is_some() || app.dialog.is_some() || app.text_box_editor.is_some() || app.grid.context_menu.is_some() - || geo.paper.is_some(); + || geo.paper.is_some() + || sh.view == gridcraft_engine::model::SheetViewMode::PageLayout +} + +/// Where the corner button sits for `sel` (on screen), and whether the selection's corner is in +/// view. Below and right of the corner, clear of the fill handle; flipped inside at the grid edge. +pub fn button_rect(geo: &Geo, sh: &Sheet, sel: RangeRef) -> (Rect, bool) { + let corner = geo.range_rect(sh, sel).right_bottom(); + let panes = geo.range_panes(RangeRef::cell(sel.end)); + let visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); + let area = geo.cells.shrink(2.0); + let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; + let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; + let at = pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))); + (geo.mirror_rect(Rect::from_min_size(at, vec2(BUTTON, BUTTON))), visible) +} + +/// Paints the corner button and, when open, the popup. Called once per grid frame. +pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { + let Some(d) = app.session.active() else { return }; + let sel = d.selection.current(); + let hidden = is_hidden(app, geo, sh); // The popup belongs to one selection; a new one (or editing) closes it. if hidden || app.grid.quick_analysis.open.is_some_and(|r| r != sel) { app.grid.quick_analysis.open = None; @@ -163,18 +198,7 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { let sheet_name = sh.name.clone(); let ctx = ui.ctx().clone(); let t = Tokens::get(&ctx); - let rect = geo.range_rect(sh, sel); - let corner = rect.right_bottom(); - let panes = geo.range_panes(RangeRef::cell(sel.end)); - let corner_visible = panes.iter().any(|p| p.contains(pos2(corner.x - 1.0, corner.y - 1.0))); - // Below and right of the corner (clear of the fill handle); flipped inside when at an edge. - let area = geo.cells.shrink(2.0); - let x = if corner.x + GAP + BUTTON > area.right() { corner.x - GAP - BUTTON } else { corner.x + GAP }; - let y = if corner.y + GAP + BUTTON > area.bottom() { corner.y - GAP - BUTTON } else { corner.y + GAP }; - let button = geo.mirror_rect(Rect::from_min_size( - pos2(x.clamp(area.left(), (area.right() - BUTTON).max(area.left())), y.clamp(area.top(), (area.bottom() - BUTTON).max(area.top()))), - vec2(BUTTON, BUTTON), - )); + let (button, corner_visible) = button_rect(geo, sh, sel); let open = app.grid.quick_analysis.open.is_some(); // While the mouse is down (selecting, filling) the button stays out of the way. let busy = app.grid.drag != Drag::None || ctx.input(|i| i.pointer.any_down()); @@ -219,14 +243,17 @@ pub fn show(app: &mut SheetApp, ui: &mut Ui, geo: &Geo, sh: &Sheet) { ui.selectable_value(&mut state.by_rows, true, lang.tr("By Row")); }); } - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 2.0; - for item in tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows) { - if paint_tile(ui, &t, &item, lang.tr(item.label)) { - picked = Some(item.action.clone()); + let items = tiles(state.tab, &opened_for.a1(), &sheet_name, state.by_rows); + for row in items.chunks(6) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for item in row { + if paint_tile(ui, &t, item, lang.tr(item.label)) { + picked = Some(item.action.clone()); + } } - } - }); + }); + } }); }); let outside_click = ctx.input(|i| i.pointer.any_pressed()) @@ -278,6 +305,24 @@ fn paint_glyph(ui: &Ui, t: &Tokens, glyph: Glyph, r: Rect) { p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); } } + Glyph::GreenBars => { + for (j, w) in [0.9, 0.55, 0.3].into_iter().enumerate() { + let row = cell(0.0, j as f32).shrink2(vec2(0.0, 1.0)); + p.rect_filled(Rect::from_min_size(row.min, vec2(r.width() * w, row.height())), 1.0, green); + } + } + Glyph::BlueScale | Glyph::GreenScale => { + let cols = if glyph == Glyph::BlueScale { [blue, Color32::WHITE, red] } else { [Color32::WHITE, green.gamma_multiply(0.5), green] }; + for (i, c) in cols.into_iter().enumerate() { + p.rect_filled(cell(i as f32, 1.0).shrink(0.5), 1.0, c); + } + p.rect_stroke( + Rect::from_min_size(cell(0.0, 1.0).min, vec2(r.width(), r.height() / 3.0)), + 1.0, + Stroke::new(1.0, t.separator), + StrokeKind::Inside, + ); + } Glyph::Dots => { for (j, c) in [green, yellow, red].into_iter().enumerate() { p.circle_filled(cell(1.0, j as f32).center(), 3.2, c); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index b8054f9a0f..dcc963dc3e 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -2430,8 +2430,13 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) { Key::T => Some(("insert.table", json!({}))), Key::E => Some(("edit.flashFill", json!({}))), Key::Q => { - // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert. - let _ = crate::quick_analysis::toggle(app, None); + // Quick Analysis; a single cell has nothing to analyse, which is not worth an alert, + // but several areas deserve to be told why nothing opened. + if let Err(e) = crate::quick_analysis::toggle(app, None) + && app.session.active().is_some_and(|d| d.selection.ranges.len() > 1) + { + app.alert(e); + } None } Key::Num1 => { diff --git a/crates/ui-egui/tests/quick_analysis_button.rs b/crates/ui-egui/tests/quick_analysis_button.rs new file mode 100644 index 0000000000..65fa142d91 --- /dev/null +++ b/crates/ui-egui/tests/quick_analysis_button.rs @@ -0,0 +1,84 @@ +//! Quick Analysis: where the corner button sits, and when it keeps out of the way. + +use egui::{Rect, Vec2, pos2, vec2}; +use gridcraft_engine::Session; +use gridcraft_engine::core::RangeRef; +use gridcraft_ui_egui::SheetApp; +use gridcraft_ui_egui::grid::Geo; +use gridcraft_ui_egui::quick_analysis::{button_rect, is_hidden, toggle}; +use serde_json::json; + +fn app() -> SheetApp { + let mut s = Session::new(); + s.new_workbook(); + SheetApp::new(s, Default::default()) +} + +fn geo(app: &SheetApp) -> Geo { + let sheet = app.session.active().unwrap().wb.active().unwrap(); + Geo::new(sheet, Rect::from_min_max(pos2(0.0, 0.0), pos2(1200.0, 800.0)), Vec2::ZERO) +} + +#[test] +fn the_button_sits_below_right_of_the_corner_clear_of_the_fill_handle() { + let app = app(); + let (g, sh) = (geo(&app), app.session.active().unwrap().wb.active().unwrap()); + let sel = RangeRef::parse("B2:D5").unwrap(); + let corner = g.range_rect(sh, sel).right_bottom(); + let (button, visible) = button_rect(&g, sh, sel); + assert!(visible); + assert!(button.left() > corner.x && button.top() > corner.y, "below and right of the corner"); + // The fill handle is a 9 x 9 square centred on the corner. + assert!(!button.intersects(Rect::from_center_size(corner, vec2(9.0, 9.0))), "clear of the fill handle"); +} + +#[test] +fn at_the_grid_edge_the_button_flips_inside_and_far_corners_are_not_visible() { + let app = app(); + let (g, sh) = (geo(&app), app.session.active().unwrap().wb.active().unwrap()); + let near_edge = RangeRef::parse("A1:ZZ1").unwrap(); + let (far, visible) = button_rect(&g, sh, near_edge); + assert!(!visible, "the corner is scrolled out of view"); + assert!(g.cells.contains_rect(far), "the popup still has an anchor inside the grid"); + let (b, _) = button_rect(&g, sh, RangeRef::parse("A1:A200").unwrap()); + assert!(g.cells.contains_rect(b)); +} + +#[test] +fn the_button_hides_for_single_cells_several_areas_editing_dialogs_and_page_layout() { + let mut app = app(); + app.run("selection.set", json!({"cell": "B2"})).unwrap(); + let hidden = |app: &SheetApp| { + let g = geo(app); + is_hidden(app, &g, app.session.active().unwrap().wb.active().unwrap()) + }; + assert!(hidden(&app), "a single cell"); + app.run("selection.set", json!({"range": "B2:D5"})).unwrap(); + assert!(!hidden(&app)); + app.begin_edit(None, false); + assert!(hidden(&app), "while editing"); + app.editor = None; + app.open_dialog("find", json!({})); + assert!(hidden(&app), "while a dialog is open"); + app.dialog = None; + assert!(!hidden(&app)); + app.run("view.pageLayout", json!({})).unwrap(); + assert!(hidden(&app), "Page Layout view"); + app.run("view.normal", json!({})).unwrap(); + assert!(!hidden(&app)); +} + +#[test] +fn several_areas_are_refused_with_a_message_rather_than_guessed() { + let mut app = app(); + app.run("selection.set", json!({"range": "B2:D5,F2:G5"})).unwrap(); + let err = toggle(&mut app, Some(true)).unwrap_err(); + assert!(err.contains("one block"), "{err}"); + assert!(app.grid.quick_analysis.open.is_none()); + assert!(hidden_for_areas(&app)); +} + +fn hidden_for_areas(app: &SheetApp) -> bool { + let g = geo(app); + is_hidden(app, &g, app.session.active().unwrap().wb.active().unwrap()) +} From 7d3516ab331924603b1ed9ba340079e2dc0b046e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 21:09:27 +0200 Subject: [PATCH 005/425] Calc: SUBTOTAL(10x) recalculates when Row Height, AutoFit Row Height or Ungroup reveal rows home.rowHeight, home.autofitRowHeight and data.ungroup change row hidden state without marking the edit structural, so SUBTOTAL(101-111) kept a stale value. Found by the command-sequence fuzz (seed 3). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + crates/engine/src/cmd/data.rs | 1 + crates/engine/src/cmd/format.rs | 2 ++ crates/engine/src/tests.rs | 16 ++++++++++++++++ 4 files changed, 20 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 25b8d9b803..acacee974f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -133,6 +133,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| | 2026-10-12 | Quick Analysis (Ctrl+Q): a corner button and popup on multi-cell selections run conditional formats, charts, totals (`analysis.addTotal`), tables, PivotTables and sparklines (`analysis.addSparklines`) in one click (#791) | +| 2026-10-12 | SUBTOTAL(109) over hidden rows recalculates after Row Height, AutoFit Row Height and Ungroup reveal rows (found by the command-sequence fuzz) | | 2026-10-12 | File › Print selects a system printer, copies, duplex and grayscale, submits PDF jobs through craft-print on a worker and shows spooler errors; browser printing and PDF export remain available | | 2026-10-11 | Command-sequence fuzzing: random command sequences checked against undo/redo, XLSX round-trip and full recalculation; fixes for the table, legacy-array, spill, AutoSum, Watch Window and sheet-copy bugs it found | | 2026-10-11 | Password-protected workbooks open: GridCraft asks for the password and decrypts Agile and Standard encryption (#11) | diff --git a/crates/engine/src/cmd/data.rs b/crates/engine/src/cmd/data.rs index e4aa3baa6e..d2b3612b7d 100644 --- a/crates/engine/src/cmd/data.rs +++ b/crates/engine/src/cmd/data.rs @@ -1129,6 +1129,7 @@ fn group(s: &mut Session, p: &Json, on: bool) -> Result { { e.collapsed = false; } + cx.structural = true; // ungrouping reveals hidden rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } diff --git a/crates/engine/src/cmd/format.rs b/crates/engine/src/cmd/format.rs index dde5fa120d..8d46010299 100644 --- a/crates/engine/src/cmd/format.rs +++ b/crates/engine/src/cmd/format.rs @@ -953,6 +953,7 @@ fn row_height(s: &mut Session, p: &Json) -> Result { e.custom = true; } } + cx.structural = true; // setting a height shows or hides rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } @@ -1069,6 +1070,7 @@ fn autofit_rows(s: &mut Session, p: &Json) -> Result { } cx.fit_rows.extend((a..=b).map(|r| (si, r))); } + cx.structural = true; // autofit reveals hidden rows: SUBTOTAL(10x) depends on it Ok(Json::Null) }) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c348dbaff2..123afa8064 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2866,3 +2866,19 @@ fn analysis_add_sparklines_one_per_row_in_one_undo_step() { assert!(s.doc().unwrap().wb.active().unwrap().sparklines.is_empty()); assert!(s.execute("analysis.addSparklines", json!({"range": "A1:A4"})).is_err()); } + +#[test] +fn subtotal_109_recalculates_when_row_height_or_autofit_reveals_rows() { + let mut s = s(); + s.execute("range.setValues", json!({"range": "A1", "values": [[1], [2], [4], [8]]})).unwrap(); + s.execute("cell.set", json!({"cell": "C1", "input": "=SUBTOTAL(109,A1:A4)"})).unwrap(); + s.execute("home.hideRows", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(9.0)); + // A non-zero height unhides the rows (the fuzz found the stale SUBTOTAL). + s.execute("home.rowHeight", json!({"rows": "2:3", "height": 60.0})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(15.0)); + s.execute("home.hideRows", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(9.0)); + s.execute("home.autofitRowHeight", json!({"rows": "2:3"})).unwrap(); + assert_eq!(v(&s, "C1"), Value::Number(15.0)); +} From 28a645ca13d60d0031fe8e463cb998e29bd19d20 Mon Sep 17 00:00:00 2001 From: quantmind-br Date: Tue, 13 Oct 2026 08:00:40 -0300 Subject: [PATCH 006/425] Calc: a contested spill area stays with its array on full recalc and reopening (#964) When two dynamic arrays want the same cells, the one already spilling there keeps them and the newcomer is #SPILL!, as when the second is entered. recalc_all remembers the layout it clears (formulas that spilled, formulas that were #SPILL!) and lays arrays out in that order, then in reading order. The XLSX reader restores a dynamic array's saved `ref` as its spill range, because the file can only cache #VALUE! for a blocked array. Found by the command-sequence fuzz. --- ROADMAP.md | 1 + crates/calc/src/recalc.rs | 36 +++++++++++++++++++++++++++-------- crates/calc/src/tests.rs | 14 ++++++++++++++ crates/engine/src/tests.rs | 15 +++++++++++++++ crates/xlsx/src/sheet_read.rs | 8 ++++++++ 5 files changed, 66 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 070552d07e..9cd46e5fcb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -132,6 +132,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in | Date | What landed | |---|---| +| 2026-10-13 | Spills: when two dynamic arrays want the same cells, the one already spilling there keeps them after Calculate Now and after saving and reopening, as when the second was entered (#964, found by the command-sequence fuzz) | | 2026-10-12 | Rows auto-fit oversized fonts: opening a file and whole-row/column formatting grow non-custom rows to their tallest font (#833) | | 2026-10-12 | Number formats: parsing a format code is linear in its length (long runs of `[`, `,` or `/` no longer take quadratic time), and an unclosed `[` is a literal when splitting sections as well as when tokenizing (#810) | | 2026-10-12 | Number formats: a fraction denominator with 65,536 zeros no longer crashes; format codes are capped at 255 characters like Excel (longer codes display as General, `TEXT` gives `#VALUE!`) (#807) | diff --git a/crates/calc/src/recalc.rs b/crates/calc/src/recalc.rs index b391821d72..f8dc677d53 100644 --- a/crates/calc/src/recalc.rs +++ b/crates/calc/src/recalc.rs @@ -781,6 +781,17 @@ impl Host for PassHost<'_> { } } +/// What a full recalculation knows about the spill layout it clears, so a contested area goes to +/// the same formula as in an incremental recalculation. +#[derive(Default)] +struct Prior { + /// Formulas that spilled (their area, from the last calculation or the file's `ref`). + spilled: HashSet, + /// Formulas that showed #SPILL!. A cell's value moves with it on a structural edit, its spill + /// area doesn't. + blocked: HashSet, +} + impl Calc { pub fn new() -> Self { Self::default() @@ -814,16 +825,19 @@ impl Calc { self.rebuild(wb); // Spills are laid out again from the formulas where they are now (a structural edit moves // or deletes the formulas, not the values they spilled). + let mut prior = Prior::default(); for i in 0..wb.sheets.len() { if wb.sheet(i).is_some_and(|s| !s.spill_ranges.is_empty() || !s.spill.is_empty()) && let Some(sh) = wb.sheet_mut(i) { + prior.spilled.extend(sh.spill_ranges.iter().filter(|(_, r)| !r.is_single()).map(|(c, _)| (i, *c))); sh.spill.clear(); sh.spill_ranges.clear(); } } let all: Vec = self.graph.nodes.keys().copied().collect(); - self.run(wb, all, true); + prior.blocked = all.iter().copied().filter(|k| wb.sheet(k.0).is_some_and(|s| s.value(k.1) == Value::Error(CellError::Spill))).collect(); + self.run(wb, all, &prior); } /// Updates the graph for cells whose content changed and recalculates what depends on them. @@ -860,7 +874,7 @@ impl Calc { if wb.calc.mode == CalcMode::Manual { // Only the edited formulas themselves are evaluated. let own: Vec = changed.iter().copied().filter(|k| self.graph.nodes.contains_key(k)).collect(); - self.run(wb, own, false); + self.run(wb, own, &Prior::default()); return; } let mut seeds: Vec = changed.to_vec(); @@ -908,7 +922,7 @@ impl Calc { let dirty = self.dirty_closure(wb, &seeds); let t1 = prof_now(); let n = dirty.len(); - self.run(wb, dirty, false); + self.run(wb, dirty, &Prior::default()); if std::env::var_os("GRIDCRAFT_PROFILE").is_some() { eprintln!("recalc: {} seeds, closure {} cells {:.1} ms, run {:.1} ms", seeds.len(), n, t1 - t0, prof_now() - t1); } @@ -947,8 +961,9 @@ impl Calc { seen.into_iter().collect() } - /// Evaluates the dirty set and writes results (and spills) back. - fn run(&mut self, wb: &mut Workbook, mut dirty: Vec, full: bool) { + /// Evaluates the dirty set and writes results (and spills) back. `prior` is the layout a full + /// recalculation cleared (empty otherwise). + fn run(&mut self, wb: &mut Workbook, mut dirty: Vec, prior: &Prior) { let mut dynamic_again = !self.graph.dynamic.is_empty(); for _round in 0..8 { if dirty.is_empty() { @@ -997,6 +1012,14 @@ impl Calc { cell.value = v; } } + // When two arrays want the same cells, the one already spilling there keeps them and + // the newcomer is #SPILL! (as when it is entered), and one that was #SPILL! stays so: + // arrays are laid out in that order, then in reading order. Without this, a full + // recalculation or reopening the file handed the area to whichever came first. + dirty.sort_by_key(|k| { + let owns = prior.spilled.contains(k) || wb.sheet(k.0).is_some_and(|s| s.spill_ranges.contains_key(&k.1)); + (prior.blocked.contains(k), !owns) + }); for k in &dirty { let new = spills.get(k); let Some(sheet) = wb.sheet_mut(k.0) else { continue }; @@ -1062,9 +1085,6 @@ impl Calc { } } } - if full { - // Everything was already evaluated once; spill dependents need another pass. - } if std::env::var_os("GRIDCRAFT_PROFILE").is_some() { eprintln!(" write-back {:.1} ms", prof_now() - tw); } diff --git a/crates/calc/src/tests.rs b/crates/calc/src/tests.rs index 196c57de78..991076d7ad 100644 --- a/crates/calc/src/tests.rs +++ b/crates/calc/src/tests.rs @@ -368,6 +368,20 @@ fn spill_into_the_old_area_of_a_blocked_neighbour() { assert_eq!([t.num("C8"), t.num("D8"), t.num("C9"), t.num("D9")], [1.0, 2.0, 3.0, 4.0]); } +#[test] +fn a_full_recalc_keeps_a_spill_with_the_formula_already_spilling_there() { + // F13's array would spill over F14:G14, which C14's array already fills: F13 is #SPILL!, and + // a full recalculation (Ctrl+Alt+F9) doesn't hand the area to F13 for coming first in + // reading order. + let mut t = T::new(); + t.set("C14", "=SEQUENCE(1,7)"); + t.set("F13", "=SEQUENCE(5,2)"); + assert_eq!(t.get("F13"), Value::Error(CellError::Spill)); + t.calc.recalc_all(&mut t.wb); + assert_eq!(t.get("F13"), Value::Error(CellError::Spill)); + assert_eq!([t.num("C14"), t.num("G14"), t.num("I14")], [1.0, 5.0, 7.0]); +} + #[test] fn arrays_do_not_spill_in_tables() { // Excel: spilled array formulas aren't supported in tables. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae499a1895..280c1476a9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2008,6 +2008,21 @@ fn a_spill_that_goes_away_unblocks_another() { assert_eq!((v(&s, "E10"), v(&s, "G10")), (Value::Number(1.0), Value::Number(3.0))); } +#[test] +fn a_contested_spill_area_stays_with_its_array_after_reopening() { + // F13's array wants F14:G14, which C14's array already fills, so F13 is #SPILL!. The file + // can only cache #VALUE! for it; reopening (which recalculates) used to hand the area to F13 + // for coming first in reading order. + let mut s = s(); + s.execute("cell.set", json!({"cell": "C14", "input": "=SEQUENCE(1,7)"})).unwrap(); + s.execute("cell.set", json!({"cell": "F13", "input": "=SEQUENCE(5,2)"})).unwrap(); + assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill)); + let saved = s.execute("file.saveBytes", json!({"format": "xlsx"})).unwrap(); + s.execute("file.open", json!({"name": "contested.xlsx", "base64": saved["base64"]})).unwrap(); + assert_eq!(v(&s, "F13"), Value::Error(gridcraft_core::CellError::Spill)); + assert_eq!((v(&s, "C14"), v(&s, "G14"), v(&s, "I14")), (Value::Number(1.0), Value::Number(5.0), Value::Number(7.0))); +} + #[test] fn an_array_reading_another_arrays_spill_is_updated() { // G5 is evaluated before D11 in the same pass, so it first reads D11's old spill. diff --git a/crates/xlsx/src/sheet_read.rs b/crates/xlsx/src/sheet_read.rs index 0194d22688..bd4f793806 100644 --- a/crates/xlsx/src/sheet_read.rs +++ b/crates/xlsx/src/sheet_read.rs @@ -452,6 +452,14 @@ fn read_cell(cx: &mut Ctx<'_>, sheet: &mut Sheet, st: &mut RowState, c: &El, pos let dynamic = c.attr("cm").is_some(); let formula = c.child("f").and_then(|f| read_formula(cx, st, f, pos, dynamic)); let value = if formula.is_none() && st.dynamic.iter().any(|r| r.contains(pos) && r.start != pos) { Value::Empty } else { value }; + // A dynamic array keeps the area it was saved spilling over (`ref`): when two arrays want the + // same cells, recalculating gives them to this one again, as before saving. + if dynamic + && formula.as_ref().is_some_and(|f| f.array.is_none()) + && let Some(r) = st.dynamic.last().filter(|r| r.start == pos) + { + sheet.spill_ranges.insert(pos, *r); + } sheet.cells.set(pos, Cell { value, formula: formula.map(Arc::new), style }); } From a6d70bcafb2a9d13516b5f2a9979758dd62ff2f9 Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:55:08 -0400 Subject: [PATCH 007/425] 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 bf15f965aea77593876e210114841409a980ca8d Mon Sep 17 00:00:00 2001 From: neilcawse <8085959+neilcawse@users.noreply.github.com> Date: Mon, 12 Oct 2026 11:54:09 -0400 Subject: [PATCH 008/425] PivotTables: refresh keeps sort by value, captions, item order and layout settings A refreshed PivotTable read from an Excel file now lays out like Excel's: - Sort by a value field (autoSortScope on data field n): PivotField.sort_by, applied within each parent; pivot.sort takes `by: "Sum of X"`. - Captions: rowHeaderCaption, colHeaderCaption, dataCaption, grandTotalCaption and missingCaption (For empty cells show), field custom names and renamed items (item n). - Manual item order of fields that aren't auto-sorted. - Per-field subtotals (defaultSubtotal, with the table default in pivotTableDefinition16), Repeat Item Labels (fillDownLabels), field number formats, the Values row (hideValuesRow) and the classic layout (gridDropZones). - rowGrandTotals/colGrandTotals were read and written the wrong way round. - Date items sort after text, as in Excel. All settings are written back to XLSX. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/pivot.rs | 190 +++++++++++++- crates/engine/src/pivot.rs | 356 ++++++++++++++++++--------- crates/model/src/features.rs | 48 ++++ crates/xlsx/src/pivot.rs | 186 ++++++++++++-- crates/xlsx/src/tests/pivot_tests.rs | 34 ++- docs/gaps.md | 5 +- docs/target-app-parity.md | 5 +- 7 files changed, 668 insertions(+), 156 deletions(-) diff --git a/crates/engine/src/cmd/pivot.rs b/crates/engine/src/cmd/pivot.rs index 8a441fa1b4..804eacea64 100644 --- a/crates/engine/src/cmd/pivot.rs +++ b/crates/engine/src/cmd/pivot.rs @@ -101,7 +101,15 @@ pub fn specs() -> Vec { value_settings ), cmd!("pivot.filter", "Filter Items", [], None, "{pivot?, field, selected: [\"East\", ..] | null (all), replace?}", has_doc, filter), - cmd!("pivot.sort", "Sort Field", [], None, "{pivot?, field, order: asc|desc|none, replace?}", has_doc, sort), + cmd!( + "pivot.sort", + "Sort Field", + [], + None, + "{pivot?, field, order: asc|desc|none, by?: \"Sum of Sales\" (sort by a value field), replace?}", + has_doc, + sort + ), cmd!( "pivot.group", "Group Field", @@ -736,6 +744,18 @@ fn summarize_table(s: &mut Session, p: &Json) -> Result { // ---------------------------------------------------------------- queries +fn field_json(f: &PivotField) -> Json { + json!({ + "field": f.source_col, + "caption": f.caption, + "sort": sort_name(f.sort), + "sortBy": f.sort_by, + "group": group_name(f.date_group), + "numberFormat": f.number_format, + "collapsed": f.collapsed_items, + }) +} + fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { json!({ "id": pt.id, @@ -744,8 +764,8 @@ fn pivot_json(wb: &Workbook, si: usize, pt: &PivotTable) -> Json { "anchor": pt.anchor.a1(), "range": pt.last_range.map(|r| r.a1()), "source": pt.source, - "rows": pt.rows.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), - "columns": pt.columns.iter().map(|f| json!({"field": f.source_col, "sort": sort_name(f.sort), "group": group_name(f.date_group), "collapsed": f.collapsed_items})).collect::>(), + "rows": pt.rows.iter().map(field_json).collect::>(), + "columns": pt.columns.iter().map(field_json).collect::>(), "values": pt.values.iter().map(|v| json!({"field": v.source_col, "func": func_name(v.func), "name": v.name, "showAs": show_as_name(v.show_as), "numberFormat": v.number_format})).collect::>(), "filters": pt.filters.iter().map(|f| json!({"field": f.source_col, "selected": f.selected, "report": !in_axes(pt, &f.source_col)})).collect::>(), "layout": layout_name(pt.layout), @@ -1074,6 +1094,12 @@ fn value_settings(s: &mut Session, p: &Json) -> Result { None => {} } let name = v.name.clone(); + // Fields sorted by this value field follow its new caption. + for f in pt.rows.iter_mut().chain(pt.columns.iter_mut()) { + if f.sort_by.as_deref().is_some_and(|b| b.eq_ignore_ascii_case(&cur.name)) { + f.sort_by = Some(name.clone()); + } + } if let Some(slot) = pt.values.get_mut(i) { *slot = v; } @@ -1146,8 +1172,23 @@ fn sort(s: &mut Session, p: &Json) -> Result { "none" | "manual" | "source" => PivotSort::None, o => return Err(bad(C, format!("unknown order `{o}` (asc|desc|none)"))), }; + // Sort by a value field (its caption or source field) instead of by the item labels. + let by = str_param(p, "by").map(str::to_string); update(s, p, |pt, _, _| { - axis_field(C, pt, &field)?.sort = order; + let by = match by { + Some(b) => Some( + pt.values + .iter() + .find(|v| v.name.eq_ignore_ascii_case(&b)) + .or_else(|| pt.values.iter().find(|v| v.source_col.eq_ignore_ascii_case(&b))) + .map(|v| v.name.clone()) + .ok_or_else(|| bad(C, format!("`{b}` isn't in the values area")))?, + ), + None => None, + }; + let f = axis_field(C, pt, &field)?; + f.sort = order; + f.sort_by = by; Ok(json!({})) }) } @@ -1552,6 +1593,7 @@ fn recommended(s: &mut Session, p: &Json) -> Result { #[cfg(test)] mod tests { use gridcraft_core::{CellError, CellRef, Value}; + use gridcraft_model::{PivotLayout, PivotSort}; use serde_json::{Value as Json, json}; use crate::Session; @@ -1982,6 +2024,146 @@ mod tests { s.execute("pivot.refresh", json!({"pivot": "PivotTable1"})).unwrap(); } + /// Edits the active sheet's last PivotTable in the model (settings only a file sets) and + /// refreshes it. + fn edit_pt(s: &mut Session, f: impl FnOnce(&mut gridcraft_model::PivotTable)) { + let d = s.doc_mut().unwrap(); + let wb = std::sync::Arc::make_mut(&mut d.wb); + let si = wb.active_sheet; + f(wb.sheet_mut(si).unwrap().pivots.last_mut().unwrap()); + s.execute("pivot.refresh", json!({})).unwrap(); + } + + #[test] + fn sort_by_value_within_each_parent() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "values": ["Sales"]})).unwrap(); + // East 415, West 285, North 135. + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Sum of Sales"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Sum of Sales")); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["East", "West", "North"]); + s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Sales"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6")], ["North", "West", "East"]); + assert!(s.execute("pivot.sort", json!({"field": "Region", "order": "asc", "by": "Nope"})).is_err()); + // The sort follows a renamed value field; sorting without `by` sorts by label again. + s.execute("pivot.valueSettings", json!({"field": "Sum of Sales", "name": "Revenue"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by.as_deref(), Some("Revenue")); + assert_eq!(text(&s, "A4"), "North"); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc"})).unwrap(); + assert_eq!(pt(&s).rows[0].sort_by, None); + assert_eq!(text(&s, "A4"), "West"); + // Inner items sort within their parent; subtotals stay with their group. + s.execute("pivot.addField", json!({"field": "Product", "area": "rows"})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Region", "order": "desc", "by": "Revenue"})).unwrap(); + s.execute("pivot.sort", json!({"field": "Product", "order": "desc", "by": "Revenue"})).unwrap(); + // East: Pears 195, Apples 160, Plums 60. + assert_eq!( + [text(&s, "A4"), text(&s, "B4"), text(&s, "B5"), text(&s, "B6"), text(&s, "A7")], + ["East", "Pears", "Apples", "Plums", "East Total"] + ); + assert_eq!(val(&s, "C4"), Value::Number(195.0)); + // West: Apples 170, Plums 70, Pears 45. + assert_eq!([text(&s, "A8"), text(&s, "B8"), text(&s, "B9"), text(&s, "B10")], ["West", "Apples", "Plums", "Pears"]); + // Columns sort by their row totals. + s.execute("pivot.moveField", json!({"field": "Region", "from": "rows", "to": "columns"})).unwrap(); + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4")], ["East", "West", "North"]); + } + + #[test] + fn captions_renamed_items_and_manual_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Product"], "values": ["Sales"]})).unwrap(); + edit_pt(&mut s, |p| { + p.row_header_caption = Some("Area".into()); + p.col_header_caption = Some("Fruit".into()); + p.grand_total_caption = Some("Everything".into()); + p.rows[0].item_captions = vec![("East".into(), "Eastern".into())]; + p.columns[0].sort = PivotSort::None; + p.columns[0].item_order = vec!["Plums".into(), "Pears".into()]; + }); + assert_eq!(text(&s, "A4"), "Area"); + assert_eq!(text(&s, "B3"), "Fruit"); + // Listed items first, the rest after. + assert_eq!([text(&s, "B4"), text(&s, "C4"), text(&s, "D4"), text(&s, "E4")], ["Plums", "Pears", "Apples", "Everything"]); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(text(&s, "A8"), "Everything"); + // A renamed item sorts by its label still, and a filter still names it by its label. + s.execute("pivot.filter", json!({"field": "Region", "selected": ["East"]})).unwrap(); + assert_eq!(text(&s, "A5"), "Eastern"); + assert_eq!(val(&s, "E5"), Value::Number(415.0)); + // Outline layout: the field's custom name heads its column. + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Outline; + p.rows[0].caption = Some("Sales area".into()); + p.columns[0].caption = Some("Kind".into()); + }); + assert_eq!(text(&s, "A4"), "Sales area"); + assert_eq!(text(&s, "B3"), "Kind"); + } + + #[test] + fn field_subtotals_repeat_labels_and_values_row() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region", "Product"], "values": ["Sales"]})).unwrap(); + s.execute("pivot.layout", json!({"layout": "tabular"})).unwrap(); + assert_eq!(text(&s, "A7"), "East Total"); + // Region without subtotals although the table has them; labels repeated on every row. + edit_pt(&mut s, |p| { + p.rows[0].subtotal = Some(false); + p.rows[0].repeat_labels = true; + }); + assert_eq!(pt(&s).last_range.unwrap().height(), 1 + 9 + 1); + assert_eq!([text(&s, "A4"), text(&s, "A5"), text(&s, "A6"), text(&s, "A7")], ["East", "East", "East", "North"]); + assert_eq!(text(&s, "B7"), "Apples"); + // Outline repeats the labels too. + s.execute("pivot.layout", json!({"layout": "outline"})).unwrap(); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "A5"), text(&s, "B5")], ["East", "", "East", "Apples"]); + // Two values without a column field: the Values row (Outline/Tabular) holds the caption. + s.execute("pivot.removeField", json!({"field": "Product"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Units", "area": "values"})).unwrap(); + assert_eq!(text(&s, "B3"), "Values"); + assert_eq!([text(&s, "A4"), text(&s, "B4"), text(&s, "C4")], ["Region", "Sum of Sales", "Sum of Units"]); + edit_pt(&mut s, |p| p.data_caption = Some("Data".into())); + assert_eq!(text(&s, "B3"), "Data"); + edit_pt(&mut s, |p| p.show_values_row = false); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Region", "Sum of Sales"]); + // Compact layout never shows it. + edit_pt(&mut s, |p| { + p.show_values_row = true; + p.layout = PivotLayout::Compact; + }); + assert_eq!([text(&s, "A3"), text(&s, "B3")], ["Row Labels", "Sum of Sales"]); + } + + #[test] + fn empty_cell_caption_classic_layout_and_date_order() { + let mut s = sales(); + s.execute("insert.pivotTable", json!({"rows": ["Region"], "columns": ["Units"], "values": ["Sales"]})).unwrap(); + // East has no record with 1 unit: blank, or the "For empty cells show" caption. + assert_eq!([text(&s, "A5"), text(&s, "B4"), text(&s, "B5")], ["East", "1", ""]); + edit_pt(&mut s, |p| p.empty_caption = Some("0".into())); + assert_eq!(text(&s, "B5"), "0"); + // Classic layout, one value and no column field: the value caption above the row + // headers and a "Total" column. + s.execute("pivot.removeField", json!({"field": "Units"})).unwrap(); + edit_pt(&mut s, |p| { + p.layout = PivotLayout::Tabular; + p.classic_layout = true; + }); + assert_eq!([text(&s, "A3"), text(&s, "A4"), text(&s, "B4"), text(&s, "A5")], ["Sum of Sales", "Region", "Total", "East"]); + assert_eq!(pt(&s).last_range.unwrap().height(), 2 + 3 + 1); + // A field number format applies to the item labels; date items sort after text, as in + // Excel. + s.execute("sheet.activate", json!({"sheet": "Sheet1"})).unwrap(); + s.execute("cell.set", json!({"cell": "C13", "input": "NA"})).unwrap(); + s.execute("sheet.activate", json!({"sheet": "Sheet2"})).unwrap(); + s.execute("pivot.removeField", json!({"field": "Region"})).unwrap(); + s.execute("pivot.addField", json!({"field": "Date", "area": "rows"})).unwrap(); + edit_pt(&mut s, |p| p.rows[0].number_format = Some("m/d/yyyy".into())); + assert_eq!(text(&s, "A5"), "NA"); + } + fn pivot_chart(s: &Session) -> gridcraft_model::Chart { s.doc().unwrap().wb.active().unwrap().charts.last().unwrap().clone() } diff --git a/crates/engine/src/pivot.rs b/crates/engine/src/pivot.rs index 6146bd4f91..29dbb3f6f0 100644 --- a/crates/engine/src/pivot.rs +++ b/crates/engine/src/pivot.rs @@ -9,7 +9,7 @@ use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use gridcraft_core::date::datetime_from_serial; -use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value}; +use gridcraft_core::{CellError, CellRef, MAX_COLS, MAX_ROWS, RangeRef, Value, number_to_text}; use gridcraft_model::*; use crate::pivot_calc::CalcSet; @@ -199,6 +199,20 @@ struct Item { first: usize, /// The value is a number shown with the source format. formatted: bool, + /// The item's custom name (a renamed item). + caption: Option, + /// Position in the field's manual item order. + rank: Option, +} + +impl Item { + /// The value shown: the custom name, else the item's value. + fn shown_value(&self) -> Value { + self.caption.as_deref().map(Value::text).unwrap_or_else(|| self.value.clone()) + } + fn shown_label(&self) -> &str { + self.caption.as_deref().unwrap_or(&self.label) + } } #[derive(Default)] @@ -207,6 +221,8 @@ struct FieldItems { index: HashMap, } +/// Sort classes: numbers, text, dates (a number shown with a date format; Excel sorts these +/// after text), logicals, errors, blanks. fn cmp_items(a: &Item, b: &Item) -> Ordering { a.class.cmp(&b.class).then(a.num.total_cmp(&b.num)).then_with(|| a.text.cmp(&b.text)) } @@ -221,9 +237,11 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: num, first, formatted, + caption: None, + rank: None, }; match v { - Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 4, 0.0, false)), + Value::Empty => ("b".into(), it(Value::text("(blank)"), "(blank)".into(), 5, 0.0, false)), Value::Number(n) => { if group != PivotDateGroup::None && let Some(dt) = datetime_from_serial(wb.date_system, *n) @@ -240,15 +258,16 @@ fn make_item(wb: &Workbook, v: &Value, group: PivotDateGroup, fmt: &str, first: }; return (format!("g{key}"), it(Value::text(label.as_str()), label, 0, key, false)); } - let label = crate::display::format(v, fmt, wb).text; - (format!("n{}", n.to_bits()), it(v.clone(), label, 0, *n, true)) + let shown = crate::display::format(v, fmt, wb); + let class = if crate::display::number_format(fmt).is_date() { 2 } else { 0 }; + (format!("n{}", n.to_bits()), it(v.clone(), shown.text, class, *n, true)) } Value::Text(t) => (format!("t{}", t.to_lowercase()), it(v.clone(), t.to_string(), 1, 0.0, false)), Value::Bool(b) => { let l = if *b { "TRUE" } else { "FALSE" }; - (format!("l{l}"), it(Value::Bool(*b), l.into(), 2, *b as u8 as f64, false)) + (format!("l{l}"), it(Value::Bool(*b), l.into(), 3, *b as u8 as f64, false)) } - Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 3, 0.0, false)), + Value::Error(e) => (format!("e{}", e.as_str()), it(v.clone(), e.as_str().into(), 4, 0.0, false)), Value::Array(_) => make_item(wb, &v.scalar(), group, fmt, first), } } @@ -270,6 +289,29 @@ impl FieldItems { fn label(&self, i: u32) -> String { self.get(i).map(|x| x.label.clone()).unwrap_or_default() } + fn shown_label(&self, i: u32) -> String { + self.get(i).map(|x| x.shown_label().to_string()).unwrap_or_default() + } + /// Applies a field's renamed items and manual item order. Settings name items by label; a + /// number item also matches its unformatted number text (how a file's cache names it). + fn apply(&mut self, f: &PivotField) { + if f.item_captions.is_empty() && f.item_order.is_empty() { + return; + } + let mut order: HashMap = HashMap::new(); + for (i, l) in f.item_order.iter().enumerate() { + order.entry(l.to_lowercase()).or_insert(i); + } + let mut captions: HashMap = HashMap::new(); + for (l, c) in &f.item_captions { + captions.entry(l.to_lowercase()).or_insert(c.as_str()); + } + for it in &mut self.items { + let raw = if it.formatted { Some(number_to_text(it.num).to_lowercase()) } else { None }; + it.rank = order.get(&it.text).or_else(|| raw.as_ref().and_then(|r| order.get(r))).copied(); + it.caption = captions.get(&it.text).or_else(|| raw.as_ref().and_then(|r| captions.get(r))).map(|c| c.to_string()); + } + } } /// The label of a source value under a date grouping (for filters and field lists). @@ -409,7 +451,14 @@ struct Node { children: Vec, } -fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems]) -> Vec { +/// Sorting of an axis by value fields: the value field each axis field sorts by, and the value +/// of an axis path (a row path with the column total, or a column path with the row total). +struct ByValue<'a> { + fields: Vec>, + value: &'a dyn Fn(&[u32], usize) -> Option, +} + +fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[FieldItems], by_value: &ByValue) -> Vec { let (Some(field), Some(fi)) = (fields.get(depth), items.get(depth)) else { return vec![] }; let mut order: Vec = Vec::new(); let mut groups: HashMap> = HashMap::new(); @@ -422,23 +471,33 @@ fn build_tree(paths: &[&[u32]], depth: usize, fields: &[&PivotField], items: &[F g.push(p); } } - let mut nodes: Vec = order + let vi = by_value.fields.get(depth).copied().flatten().filter(|_| field.sort != PivotSort::None); + let mut nodes: Vec<(Option, Node)> = order .into_iter() .map(|it| { let ps = groups.remove(&it).unwrap_or_default(); - Node { item: it, children: build_tree(&ps, depth + 1, fields, items) } + let key = vi.and_then(|vi| ps.first().and_then(|p| p.get(..=depth)).and_then(|p| (by_value.value)(p, vi))); + (key, Node { item: it, children: build_tree(&ps, depth + 1, fields, items, by_value) }) }) .collect(); - let by = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { + let by_label = |a: &Node, b: &Node| match (fi.get(a.item), fi.get(b.item)) { (Some(x), Some(y)) => match field.sort { PivotSort::Asc => cmp_items(x, y), PivotSort::Desc => cmp_items(y, x), - PivotSort::None => x.first.cmp(&y.first), + PivotSort::None => x.rank.unwrap_or(usize::MAX).cmp(&y.rank.unwrap_or(usize::MAX)).then(x.first.cmp(&y.first)), }, _ => Ordering::Equal, }; - nodes.sort_by(by); - nodes + // By value: numbers in the sort direction, then items without a number; ties by label. + let by_key = |a: &Option, b: &Option| match (a, b) { + (Some(x), Some(y)) if field.sort == PivotSort::Desc => y.total_cmp(x), + (Some(x), Some(y)) => x.total_cmp(y), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + }; + nodes.sort_by(|(ka, a), (kb, b)| by_key(ka, kb).then_with(|| by_label(a, b))); + nodes.into_iter().map(|(_, n)| n).collect() } fn is_collapsed(field: &PivotField, label: &str) -> bool { @@ -587,11 +646,22 @@ struct Ctx<'a> { val_names: Vec, } +/// A label cell of a report line: (column, value, indent, number format). +type Label = (usize, Value, u8, Option); + +/// Whether an axis field shows subtotals (its own setting, else the table's). +fn shows_subtotals(pt: &PivotTable, f: Option<&&PivotField>) -> bool { + f.and_then(|f| f.subtotal).unwrap_or(pt.subtotals) +} + impl Ctx<'_> { - fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String) { - let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { return (Value::Empty, None, String::new()) }; - let fmt = if it.formatted { self.row_fmts.get(depth).cloned() } else { None }; - (it.value.clone(), fmt, it.label.clone()) + /// (shown value, number format, item label, shown label) of a row item. + fn label_cell(&self, depth: usize, item: u32) -> (Value, Option, String, String) { + let Some(it) = self.row_items.get(depth).and_then(|fi| fi.get(item)) else { + return (Value::Empty, None, String::new(), String::new()); + }; + let fmt = if it.formatted && it.caption.is_none() { self.row_fmts.get(depth).cloned() } else { None }; + (it.shown_value(), fmt, it.label.clone(), it.shown_label().to_string()) } /// (column, indent) of a row level (Σ Values counts as a level) in Compact/Outline form. @@ -620,86 +690,79 @@ impl Ctx<'_> { /// The Σ Values level at row field depth `depth`: one item per value field, each followed by /// the row fields below it (`nodes`) or, innermost, holding that value. - fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, out: &mut Vec) { + fn flatten_values(&self, nodes: &[Node], depth: usize, prefix: &mut Vec, repeat: &mut Vec