From 74def9b39cd5a496feebfbc6b19b78227ec1a8a1 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 20 Nov 2026 18:41:35 +0700 Subject: [PATCH 1/2] feat(datagrid): wrap long values onto several lines in the data grid --- .claude/rules/data-grid.md | 7 +- .../SpecialCharacterText.swift | 40 +++ .../SpecialCharacterTextTests.swift | 55 +++ .../Core/DataGrid/DataGridDisplayState.swift | 11 +- .../Core/DataGrid/DataGridModel.swift | 16 + .../DataGrid/DataGridOwnerProtocols.swift | 3 + .../Core/DataGrid/DataGridPrewarmWindow.swift | 52 ++- .../Core/DataGrid/RowDisplayBox.swift | 33 +- .../TablePro/Core/Menu/ViewMenuBuilder.swift | 2 + .../Formatting/CellDisplayFormatter.swift | 33 +- ...inSplitViewController+MenuValidation.swift | 6 + ...nSplitViewController+ViewMenuActions.swift | 4 + .../RecentlyClosedTabReopener.swift | 4 +- .../TabPersistenceCoordinator.swift | 6 +- apple/TablePro/Models/Query/QueryTab.swift | 6 +- .../Models/Query/QueryTabManager.swift | 2 + .../TablePro/Models/Query/QueryTabState.swift | 7 +- .../Models/Settings/AppSettings.swift | 6 + .../TablePro/Resources/Localizable.xcstrings | 9 + .../Cells/DataGridCellAppearance.swift | 5 +- .../Cells/DataGridCellPresenter.swift | 128 ++++++- .../DataGrid/Cells/DataGridCellRenderer.swift | 111 +++++- .../DataGrid/Cells/DataGridCellText.swift | 40 +++ .../DataGrid/Cells/DataGridMetrics.swift | 20 ++ .../DataGrid/Cells/DataGridWrapLayout.swift | 167 +++++++++ .../DataGridViewController+HeaderMenu.swift | 7 + .../DataGrid/DataGridContainerView.swift | 36 +- .../DataGridViewController+Changes.swift | 20 +- .../DataGridViewController+Columns.swift | 3 + .../DataGridViewController+Drawing.swift | 8 +- .../DataGridViewController+Menus.swift | 7 + .../DataGridViewController+Selection.swift | 8 +- ...DataGridViewController+TableDelegate.swift | 5 + .../DataGridViewController+Wrap.swift | 335 +++++++++++++++++ .../DataGrid/DataGridViewController.swift | 17 + .../Editing/DataGridEditingCellView.swift | 12 +- .../DataGridViewController+FieldEditing.swift | 3 + .../Main/Child/QueryTabGridStateStore.swift | 11 + .../MainContentCoordinator+GridModels.swift | 24 +- .../Main/MainContentCommandActions.swift | 13 + .../Settings/Sections/DataGridSection.swift | 2 + .../Structure/StructureGridStateStore.swift | 1 + .../Core/Menu/MainMenuBuilderTests.swift | 14 + .../Services/CellDisplayFormatterTests.swift | 26 ++ .../Services/PersistedTabRoundTripTests.swift | 18 + .../Settings/SettingsFieldDecodingTests.swift | 14 + .../DataGrid/DataGridCellTextTests.swift | 12 + .../DataGrid/DataGridWordWrapTests.swift | 301 ++++++++++++++++ .../DataGrid/DataGridWrapLayoutTests.swift | 143 ++++++++ .../Views/DataGrid/DataTabWrapTextTests.swift | 61 ++++ core/crates/ffi/src/results/cell_text.rs | 136 ++++++- core/crates/ffi/src/results/cursor.rs | 81 ++++- core/crates/ffi/src/window_abi.rs | 39 +- .../0003-result-windows-for-native-grids.md | 2 +- ...-result-window-can-keep-its-line-breaks.md | 43 +++ core/docs/decisions/README.md | 3 +- .../app/src/services/grid/display_text.rs | 132 ++++++- .../src/services/grid/special_characters.rs | 31 +- linux/crates/app/src/ui/browse_tab/layout.rs | 22 ++ linux/crates/app/src/ui/data_grid/columns.rs | 47 ++- .../app/src/ui/data_grid/grid_actions.rs | 43 +++ .../crates/app/src/ui/data_grid/grid_cell.rs | 291 ++++++++++++++- .../app/src/ui/data_grid/grid_config.rs | 2 + .../crates/app/src/ui/data_grid/grid_menu.rs | 30 +- linux/crates/app/src/ui/data_grid/imp.rs | 2 + linux/crates/app/src/ui/data_grid/mod.rs | 3 + linux/crates/app/src/ui/data_grid/pointer.rs | 44 ++- .../app/src/ui/data_grid/row_number_column.rs | 10 +- .../app/src/ui/data_grid/special_marks.rs | 16 +- .../crates/app/src/ui/data_grid/test_grid.rs | 3 + .../app/src/ui/data_grid/tests/cells.rs | 2 + .../app/src/ui/data_grid/tests/gutter.rs | 32 +- .../app/src/ui/data_grid/tests/menus.rs | 9 +- .../crates/app/src/ui/data_grid/tests/mod.rs | 1 + .../crates/app/src/ui/data_grid/tests/view.rs | 9 +- .../crates/app/src/ui/data_grid/tests/wrap.rs | 336 ++++++++++++++++++ .../crates/app/src/ui/editor/results_pane.rs | 82 +++++ linux/crates/app/src/ui/key_tab/mod.rs | 1 + .../preferences_dialog/data_browser_group.rs | 21 ++ linux/crates/app/src/ui/result_pane/mod.rs | 1 + .../platform/src/settings/grid_preferences.rs | 5 + linux/crates/platform/src/settings/keys.rs | 1 + linux/crates/platform/src/settings/mod.rs | 8 + linux/crates/platform/tests/settings.rs | 25 ++ .../data/app.tablepro.TablePro.gschema.xml.in | 6 + .../ui/preferences-data-browser-group.ui | 6 + linux/data/resources/ui/results-pane.ui | 22 ++ linux/docs/decisions/0027-one-data-grid.md | 2 +- .../0047-wrapped-text-in-the-data-grid.md | 47 +++ linux/docs/decisions/README.md | 3 +- linux/docs/features.md | 4 +- linux/docs/storage.md | 1 + linux/po/POTFILES.in | 1 + .../docs/decisions/0003-data-grid-control.md | 2 +- .../0023-wrapped-cells-and-uneven-rows.md | 82 +++++ windows/docs/decisions/README.md | 3 +- windows/src/TablePro.App.Model/AppSettings.cs | 3 + windows/src/TablePro.App.Model/QueryTab.cs | 20 +- .../src/TablePro.App.Model/SessionState.cs | 4 + windows/src/TablePro.App.Model/TableTab.cs | 17 + windows/src/TablePro.App/MainWindow.xaml | 2 + windows/src/TablePro.App/MainWindow.xaml.cs | 12 + .../TablePro.App/Strings/en-US/Resources.resw | 18 + .../Views/DefinitionTabView.xaml.cs | 6 + windows/src/TablePro.App/Views/GridMenus.cs | 16 + windows/src/TablePro.App/Views/ITabContent.cs | 5 + .../src/TablePro.App/Views/KeyTabView.xaml.cs | 7 + .../TablePro.App/Views/QueryTabView.xaml.cs | 24 +- .../TablePro.App/Views/ResultsPane.xaml.cs | 7 + .../src/TablePro.App/Views/SettingsView.xaml | 4 + .../TablePro.App/Views/SettingsView.xaml.cs | 10 + .../TablePro.App/Views/TableTabView.xaml.cs | 12 + .../TablePro.App/Views/WorkspaceView.xaml.cs | 3 +- .../src/TablePro.DataGrid.Model/CellBlock.cs | 44 ++- .../src/TablePro.DataGrid.Model/CellCache.cs | 15 + .../TablePro.DataGrid.Model/EditedGridData.cs | 8 +- .../src/TablePro.DataGrid.Model/GridData.cs | 7 + .../TablePro.DataGrid.Model/GridNavigation.cs | 18 + .../TablePro.DataGrid.Model/ResultSetData.cs | 19 +- .../src/TablePro.DataGrid.Model/RowHeights.cs | 155 ++++++++ .../TablePro.DataGrid.Model/TextGridData.cs | 6 +- windows/src/TablePro.DataGrid/CellPainter.cs | 238 +++++++++++++ .../DataGridView.Accessibility.cs | 2 +- .../TablePro.DataGrid/DataGridView.Editing.cs | 26 +- .../DataGridView.Interaction.cs | 44 ++- .../TablePro.DataGrid/DataGridView.Tips.cs | 22 +- .../TablePro.DataGrid/DataGridView.Wrap.cs | 269 ++++++++++++++ windows/src/TablePro.DataGrid/DataGridView.cs | 91 +++-- windows/src/TablePro.DataGrid/DrawnRow.cs | 46 ++- windows/src/TablePro.DataGrid/Layouts.cs | 15 +- .../Generated/WindowMethods.g.cs | 22 +- windows/src/TablePro.Interop/ResultCursor.cs | 18 +- .../TablePro.App.Model.Tests/QueryTabTests.cs | 41 ++- .../TablePro.App.Model.Tests/StoreTests.cs | 48 +++ .../TablePro.App.Model.Tests/TableTabTests.cs | 46 +++ .../TablePro.App.UITests/WrapTextTests.cs | 60 ++++ windows/tests/TablePro.DataGrid.Gate/Gate.cs | 26 ++ .../TablePro.DataGrid.Gate/ci/run-gate.ps1 | 5 +- .../CoreDataTests.cs | 29 ++ .../FakeGridData.cs | 9 +- .../RowHeightsTests.cs | 190 ++++++++++ .../WrapTextTests.cs | 197 ++++++++++ .../TablePro.DataGrid.Tests/CellTipTests.cs | 43 +++ .../TablePro.DataGrid.Tests/DrawingTests.cs | 94 +++++ .../TablePro.DataGrid.Tests/EditingTests.cs | 56 +++ .../InteractionTests.cs | 131 +++++++ .../ItemsRepeaterTrapTests.cs | 94 +++++ .../tests/TablePro.DataGrid.Tests/WrapData.cs | 112 ++++++ .../VerticalPathTests.cs | 22 ++ 149 files changed, 5791 insertions(+), 213 deletions(-) create mode 100644 apple/Packages/TableProEditor/Sources/TableProTextEngine/SpecialCharacters/SpecialCharacterText.swift create mode 100644 apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SpecialCharacterTextTests.swift create mode 100644 apple/TablePro/Views/DataGrid/Cells/DataGridWrapLayout.swift create mode 100644 apple/TablePro/Views/DataGrid/DataGridViewController+Wrap.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataGridWordWrapTests.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataGridWrapLayoutTests.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataTabWrapTextTests.swift create mode 100644 core/docs/decisions/0041-a-result-window-can-keep-its-line-breaks.md create mode 100644 linux/crates/app/src/ui/data_grid/tests/wrap.rs create mode 100644 linux/docs/decisions/0047-wrapped-text-in-the-data-grid.md create mode 100644 windows/docs/decisions/0023-wrapped-cells-and-uneven-rows.md create mode 100644 windows/src/TablePro.DataGrid.Model/RowHeights.cs create mode 100644 windows/src/TablePro.DataGrid/DataGridView.Wrap.cs create mode 100644 windows/tests/TablePro.App.UITests/WrapTextTests.cs create mode 100644 windows/tests/TablePro.DataGrid.Model.Tests/RowHeightsTests.cs create mode 100644 windows/tests/TablePro.DataGrid.Model.Tests/WrapTextTests.cs create mode 100644 windows/tests/TablePro.DataGrid.Tests/WrapData.cs diff --git a/.claude/rules/data-grid.md b/.claude/rules/data-grid.md index 9c445b0a16..17072747ce 100644 --- a/.claude/rules/data-grid.md +++ b/.claude/rules/data-grid.md @@ -27,8 +27,8 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode - **Two tables, one grid.** The main pane's `DataGridTableView` holds every column, the row numbers first. The frozen pane is a second table laid over the main pane's leading edge, showing the row numbers and the frozen columns. Keys, find, copy and VoiceOver work on the main table. - **The main table is the only first responder.** The frozen table refuses it and hands its presses to the controller. `DataGridContainerView.gridHasFocus` is the one focus flag: both panes' row views take `isEmphasized` from it, and so does the active-cell border. -- **Row height, row count, reloads, inserts and removes reach both panes in one call**, so their document heights never differ. -- **Vertical scroll stays in step through bounds-change notifications**: each pane's clip moves the other with `clipView.scroll(to:)` and `reflectScrolledClipView`, only when its y differs. Anywhere else scroll with `NSView.scroll(_:)`: moving a clip's x that way leaves the header behind. +- **Row height, row count, reloads, inserts, removes and height notes reach both panes in one call**, so their document heights never differ while rows are one pitch. A grid that wraps is the exception: AppKit estimates the height of rows it has not asked about, each table by its own sample, so the two documents differ. +- **Vertical scroll stays in step through bounds-change notifications**: each pane's clip moves the other with `clipView.scroll(to:)` and `reflectScrolledClipView`, only when its y differs. A grid that wraps matches the first visible row and its offset instead of y, in both directions, in `DataGridContainerView.syncVertical`, the one place the panes are aligned. Anywhere else scroll with `NSView.scroll(_:)`: moving a clip's x that way leaves the header behind. - **The frozen pane forwards every wheel event to the main scroll view**, so one momentum engine moves both. - **A `fitsRows` grid is as tall as its rows and scrolls only sideways.** It publishes `model.fittingHeight` for its host to size it, hands a vertical gesture to the enclosing scroll view (the axis is decided once per gesture), and reveals a row by scrolling that page. The Structure tab's sections use it. - **Frozen columns take at most two thirds of the grid** (`DataGridMetrics.maximumFrozenShare`). Columns past that scroll, and Freeze Up to This Column is refused in the menu. @@ -39,6 +39,9 @@ Three layers, knowledge pointing one way: an owner's adapter, then `DataGridMode - **Cells are drawn, not mounted.** `DataGridRowView` draws its pane's cells through `DataGridCellRenderer`. `tableView(_:viewFor:row:)` returns nil except for the cell being edited and the accessibility stand-ins: a view per cell costs 45 ms a frame at 1,000 rows by 200 columns against 1.5 ms drawn. - **A change repaints, it never reloads.** It reaches pixels as `needsDisplay` on the row views it names. `reloadData(forRowIndexes:columnIndexes:)` only mounts or unmounts a cell view, since reloading an edited row ends the edit. A full `reloadData()` drops the table selection without telling anyone, so the controller writes it back. +- **Wrap Text is per grid, and off is the fixed-pitch table.** `model.wrapsText` is the store's flag on a grid that offers `.wrapText`. The controller answers `tableView(_:heightOfRow:)` only while it is on (`responds(to:)`, then the delegates are assigned again and the tables reloaded), so a grid that never wraps runs none of this. `tableView.rowHeight` stays the one-line height in both modes. +- **A wrapped row's height comes from `display.lineCounts`**, a line count per `RowID` over every column, capped at `DataGridWrapLayout.maximumLines`. It clears with the display cache and whenever `DataGridWrapGeometry` moves (a width, the column set, a font, the Row height, Show Invisible Characters). A row with no count is one line. Rows AppKit shows or holds ready are measured on the main actor as the viewport moves, the prewarm fills the rest, and every count that changes an answer is followed by `noteHeightOfRows` on both panes inside a kept place, never by a reload. +- **In a tall row everything but the value sits on the first line**: the row number, the accessory, the checkbox, a placeholder and the edit field. `DataGridWrapLayout` breaks the value and the renderer draws it, from the text the formatter left with every line break as one LF. - **Every column stays attached.** Never hide an off-screen column with `NSTableColumn.isHidden`: each write costs O(attached columns). Columns come from each pane's pool, keyed by `DataGridColumnID`, so a re-run of the same result does not flicker (#951). - **Resolve a table column through `DataGridPane.slot(atTableIndex:columns:)` and `tableIndex(forDisplayPosition:columns:)`**, never a fixed index into `tableColumns`: the row-number column sits first and the frozen pane holds a subset. - **`gridStyleMask` stays empty.** AppKit's vertical grid lines keep a subview per column (518 ms a layout at 500 columns). `DataGridBodyChrome` draws the separators in each row, and the stripes and separators past the last row. diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/SpecialCharacters/SpecialCharacterText.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/SpecialCharacters/SpecialCharacterText.swift new file mode 100644 index 0000000000..c091f34738 --- /dev/null +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/SpecialCharacters/SpecialCharacterText.swift @@ -0,0 +1,40 @@ +// +// SpecialCharacterText.swift +// TableProTextEngine +// + +import AppKit + +// The editor's marks for a view that breaks a value into lines itself, such as a grid cell that wraps. +public struct SpecialCharacterText { + // As long as the source, unit for unit, so an offset into one is an offset into the other. + public let string: NSAttributedString + public let marks: [SpecialCharacterMark] + + public init(_ string: NSAttributedString, style: SpecialCharacterStyle) { + let display = SpecialCharacterDisplay.make(from: string, style: style) + self.string = display.string + marks = display.marks + } + + // `line` shows `string` from `start`: typeset from it there, or laid out from that part alone. + // `drawn` is `line` or an end truncation of it, which drops the marks the ellipsis replaced. + public func marks(from start: Int, in line: CTLine, drawnAs drawn: CTLine) -> [SpecialCharacterMark] { + guard !marks.isEmpty else { return [] } + let range = CTLineGetStringRange(line) + let lineEnd = range.location + range.length + var shownEnd = lineEnd + if drawn !== line { + let runs = CTLineGetGlyphRuns(drawn) as? [CTRun] ?? [] + shownEnd = runs.map(CTRunGetStringRange) + .filter { $0.location + $0.length == lineEnd } + .map(\.location) + .min() ?? lineEnd + } + let end = start + shownEnd - range.location + let shown = marks + .filter { $0.offset >= start && $0.offset + $0.length <= end } + .map { $0.offset(by: -start) } + return SpecialCharacterGeometry.positioned(shown, in: drawn) + } +} diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SpecialCharacterTextTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SpecialCharacterTextTests.swift new file mode 100644 index 0000000000..1db2076f96 --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/SpecialCharacterTextTests.swift @@ -0,0 +1,55 @@ +import AppKit +@testable import TableProTextEngine +import Testing + +@MainActor +struct SpecialCharacterTextTests { + private let font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) + + private func attributed(_ text: String) -> NSAttributedString { + NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: NSColor.black]) + } + + @Test("The laid out text is as long as its source and leaves a line break unmarked") + func keepsLengthAndLineBreaks() { + let source = "a\u{200B}\nb\u{202E}c" + let text = SpecialCharacterText(attributed(source), style: SpecialCharacterStyle()) + + #expect(text.string.length == (source as NSString).length) + #expect(text.marks.map(\.offset) == [1, 4]) + #expect((text.string.string as NSString).character(at: 2) == 0x0A) + } + + @Test("A typeset line takes only its own marks, placed from the line's start") + func marksFollowTheirLine() throws { + let text = SpecialCharacterText(attributed("ab\u{200B}\ncd\u{200B}"), style: SpecialCharacterStyle()) + let typesetter = CTTypesetterCreateWithAttributedString(text.string) + let first = CTTypesetterCreateLine(typesetter, CFRange(location: 0, length: 4)) + let second = CTTypesetterCreateLine(typesetter, CFRange(location: 4, length: 3)) + + let firstMarks = text.marks(from: 0, in: first, drawnAs: first) + let secondMarks = text.marks(from: 4, in: second, drawnAs: second) + let prefix = CGFloat(CTLineGetTypographicBounds(CTLineCreateWithAttributedString(attributed("cd")), nil, nil, nil)) + + #expect(firstMarks.count == 1) + #expect(secondMarks.count == 1) + let mark = try #require(secondMarks.first) + #expect(abs(mark.minX - prefix) < 0.5) + #expect(mark.maxX - mark.minX > 10) + } + + @Test("A line laid out from part of the text, then cut at its end, drops the marks the ellipsis replaced") + func truncatedPartDropsHiddenMarks() throws { + let source = "x\n\u{200B}" + String(repeating: "y", count: 40) + "\u{200B}" + let text = SpecialCharacterText(attributed(source), style: SpecialCharacterStyle()) + let part = text.string.attributedSubstring(from: NSRange(location: 2, length: text.string.length - 2)) + let line = CTLineCreateWithAttributedString(part) + let ellipsis = CTLineCreateWithAttributedString(attributed("\u{2026}")) + let cut = try #require(CTLineCreateTruncatedLine(line, 120, .end, ellipsis)) + + #expect(text.marks(from: 2, in: line, drawnAs: line).count == 2) + let shown = text.marks(from: 2, in: line, drawnAs: cut) + #expect(shown.count == 1) + #expect(shown.first?.minX == 0) + } +} diff --git a/apple/TablePro/Core/DataGrid/DataGridDisplayState.swift b/apple/TablePro/Core/DataGrid/DataGridDisplayState.swift index 53e13177b9..7fc130bfef 100644 --- a/apple/TablePro/Core/DataGrid/DataGridDisplayState.swift +++ b/apple/TablePro/Core/DataGrid/DataGridDisplayState.swift @@ -8,6 +8,15 @@ import Foundation // Formatted text kept by the model, so a remount of the grid draws from it instead of formatting every row again (#2424). @MainActor final class DataGridDisplayState { - let cache = RowDisplayCache() + let lineCounts: RowLineCountStore + let cache: RowDisplayCache var highlightRuleSetKey: HighlightRuleSet.Key? + // Whether the cached text kept its line breaks, which only a grid that wraps asks for. + var keepsLineBreaks = false + + init() { + let lineCounts = RowLineCountStore() + self.lineCounts = lineCounts + cache = RowDisplayCache(lineCounts: lineCounts) + } } diff --git a/apple/TablePro/Core/DataGrid/DataGridModel.swift b/apple/TablePro/Core/DataGrid/DataGridModel.swift index 190a318c46..8c84b27ebb 100644 --- a/apple/TablePro/Core/DataGrid/DataGridModel.swift +++ b/apple/TablePro/Core/DataGrid/DataGridModel.swift @@ -373,6 +373,22 @@ final class DataGridModel: ObservableObject { refreshFind() } + // MARK: - Wrap + + // Only a grid that offers the command wraps, whatever its store holds. + var wrapsText: Bool { + configuration.commands.contains(.wrapText) && store.wrapsText + } + + // The cached text is flattened or keeps its breaks by this flag, so it goes with the change, mounted or not. + func setWrapsText(_ wraps: Bool) { + guard configuration.commands.contains(.wrapText), wraps != store.wrapsText, commitEditing() else { return } + store.wrapsText = wraps + display.keepsLineBreaks = wraps + display.cache.removeAll() + mountedView?.configurationDidChange() + } + // MARK: - Schemas private func observeSchemas() { diff --git a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift index 0cecfd6ad8..c7d6433288 100644 --- a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift +++ b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift @@ -22,6 +22,7 @@ enum DataGridCommand: Hashable, CaseIterable { case valueFilter case copyAsSQL case loadUnloadedValues + case wrapText } enum DataGridLayoutScope: Equatable { @@ -161,6 +162,7 @@ protocol DataGridStateStore: AnyObject { var displayFormats: [ValueDisplayFormat?] { get set } var selectionSnapshot: GridSelectionSnapshot { get set } var viewportAnchor: GridViewportPlacement? { get set } + var wrapsText: Bool { get set } var layoutScope: DataGridLayoutScope { get } } @@ -172,6 +174,7 @@ final class InMemoryDataGridStateStore: DataGridStateStore { var displayFormats: [ValueDisplayFormat?] = [] var selectionSnapshot = GridSelectionSnapshot.empty var viewportAnchor: GridViewportPlacement? + var wrapsText = false let layoutScope: DataGridLayoutScope = .ephemeral init(columnLayout: ColumnLayoutState = ColumnLayoutState(), sortState: SortState = SortState()) { diff --git a/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift b/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift index 9013bc41c0..552135903c 100644 --- a/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift +++ b/apple/TablePro/Core/DataGrid/DataGridPrewarmWindow.swift @@ -5,7 +5,7 @@ // The slice of a result the data grid formats ahead of the viewport. // -import Foundation +import AppKit import TableProPluginKit /// The rows the background prewarm may format, as a function of the rows on screen. @@ -23,6 +23,45 @@ enum DataGridPrewarmWindow { } } +// What a wrapping grid's rows are measured against, copied out so a batch counts their lines where it formats them. +struct DataGridPrewarmWrap: Sendable { + struct Column: Sendable { + let dataIndex: Int + let width: CGFloat + let kind: DataGridCellKind + } + + let columns: [Column] + let face: DataGridWrapLayout.Face + let isEditable: Bool + let marksEmptyText: Bool + let marksInvisibles: Bool + // Rows with a pending change or a value left on the server draw text the batch cannot see. + let measurableRows: Set + let generation: Int + + // Nil leaves the row to the main actor: a marked character is as wide as its marker, which is laid out there. + func lineCount(of row: Row, texts: ContiguousArray) -> Int? { + guard measurableRows.contains(row.id) else { return nil } + var lines = 1 + for column in columns where column.dataIndex < row.values.count && column.dataIndex < texts.count { + let rawValue = row.values[column.dataIndex] + guard column.kind != .checkbox, + DataGridCellContent.placeholder(for: rawValue, marksEmptyText: marksEmptyText) == nil, + let text = texts[column.dataIndex] else { continue } + let accessory = DataGridCellAccessory.visible(for: column.kind, isEditable: isEditable, rawValue: rawValue.asText) + let width = accessory.availableTextWidth(in: NSRect(x: 0, y: 0, width: column.width, height: 0)) + if marksInvisibles { + let shown = DataGridWrapLayout.bounded(text, width: width, pointSize: face.font.pointSize).text + guard !DataGridWrapLayout.holdsMarkableCharacter(shown) else { return nil } + } + lines = max(lines, DataGridWrapLayout.lineCount(of: text, width: width, face: face)) + if lines >= DataGridWrapLayout.maximumLines { break } + } + return lines + } +} + // A few rows of the window, copied out so the formatting never holds the result's whole buffer: an edit made // meanwhile would then copy every row. struct DataGridPrewarmBatch: Sendable { @@ -36,12 +75,14 @@ struct DataGridPrewarmBatch: Sendable { let dateFormat: DateFormatOption // What the display cache had dropped when the rows were copied; text formatted before a later drop is stale. let invalidations: Int + var keepsLineBreaks = false + var wrap: DataGridPrewarmWrap? // A renderer serves one thread, so each batch builds its own from the format. @concurrent - nonisolated func formatted() async -> sending [(id: RowID, box: RowDisplayBox)] { + nonisolated func formatted() async -> sending [(id: RowID, box: RowDisplayBox, lineCount: Int?)] { let dates = DateDisplayRenderer(format: dateFormat) - var formatted: [(id: RowID, box: RowDisplayBox)] = [] + var formatted: [(id: RowID, box: RowDisplayBox, lineCount: Int?)] = [] formatted.reserveCapacity(rows.count) for row in rows where !Task.isCancelled { let box = RowDisplayBox(ContiguousArray(repeating: nil, count: columnCount)) @@ -51,11 +92,12 @@ struct DataGridPrewarmBatch: Sendable { columnType: dataIndex < columnTypes.count ? columnTypes[dataIndex] : nil, displayFormat: dataIndex < formats.count ? formats[dataIndex] : nil, databaseType: databaseType, - dates: dates + dates: dates, + keepsLineBreaks: keepsLineBreaks ) box.setText(display.text ?? row.values[dataIndex].asText ?? "", at: dataIndex, isFormatted: display.isFormatted) } - formatted.append((row.id, box)) + formatted.append((row.id, box, wrap?.lineCount(of: row, texts: box.values))) } return formatted } diff --git a/apple/TablePro/Core/DataGrid/RowDisplayBox.swift b/apple/TablePro/Core/DataGrid/RowDisplayBox.swift index 2ad564c4c1..cb3f6a9be1 100644 --- a/apple/TablePro/Core/DataGrid/RowDisplayBox.swift +++ b/apple/TablePro/Core/DataGrid/RowDisplayBox.swift @@ -46,6 +46,31 @@ final class RowDisplayBox { } } +// The lines each measured row needs while its grid wraps. A row with no entry has not been measured and stands one line tall. +@MainActor +final class RowLineCountStore { + private var counts: [RowID: Int] = [:] + // Rises whenever a count is dropped, so one measured off the main actor can tell it went stale on the way back. + private(set) var generation = 0 + + subscript(id: RowID) -> Int? { + get { counts[id] } + set { counts[id] = newValue } + } + + var isEmpty: Bool { counts.isEmpty } + + func remove(_ id: RowID) { + generation &+= 1 + counts.removeValue(forKey: id) + } + + func removeAll() { + generation &+= 1 + counts.removeAll(keepingCapacity: true) + } +} + @MainActor final class RowDisplayCache { // Callers mutate a box in place, so only the cost recorded at insertion matches what was added to `totalCost`. @@ -63,10 +88,13 @@ final class RowDisplayCache { private(set) var invalidations = 0 private let countLimit: Int private let costLimit: Int + // A row's line count follows from its text, so every call that drops text drops the count with it. + private let lineCounts: RowLineCountStore? - init(countLimit: Int = 50_000, costLimit: Int = 64 * 1_024 * 1_024) { + init(countLimit: Int = 50_000, costLimit: Int = 64 * 1_024 * 1_024, lineCounts: RowLineCountStore? = nil) { self.countLimit = countLimit self.costLimit = costLimit + self.lineCounts = lineCounts } func box(forID id: RowID) -> RowDisplayBox? { @@ -106,6 +134,7 @@ final class RowDisplayCache { func removeAll() { invalidations &+= 1 + lineCounts?.removeAll() storage.removeAll(keepingCapacity: true) highlights.removeAll(keepingCapacity: true) insertionOrder.removeAll(keepingCapacity: true) @@ -116,6 +145,7 @@ final class RowDisplayCache { // Row ids are positional: a row edited in place keeps its id and would otherwise be served its pre-edit text. func clearValues(forID id: RowID) { invalidations &+= 1 + lineCounts?.remove(id) highlights.removeValue(forKey: id) guard let existing = storage[id] else { return } totalCost -= existing.cost @@ -127,6 +157,7 @@ final class RowDisplayCache { func clearValues(forDataIndexes dataIndexes: Set) { guard !dataIndexes.isEmpty else { return } invalidations &+= 1 + lineCounts?.removeAll() highlights.removeAll(keepingCapacity: true) storage = storage.mapValues { entry in for index in dataIndexes { diff --git a/apple/TablePro/Core/Menu/ViewMenuBuilder.swift b/apple/TablePro/Core/Menu/ViewMenuBuilder.swift index 4c44aaee83..7c84105edb 100644 --- a/apple/TablePro/Core/Menu/ViewMenuBuilder.swift +++ b/apple/TablePro/Core/Menu/ViewMenuBuilder.swift @@ -98,6 +98,8 @@ enum ViewMenuBuilder { String(localized: "Highlight Rules…"), action: #selector(MainSplitViewController.showHighlightRules(_:)) ), + // A focused data grid answers this itself; the window answers for the selected tab's grid otherwise. + MenuItemFactory.item(String(localized: "Wrap Text"), action: #selector(MainSplitViewController.toggleWrapText(_:))), MenuItemFactory.item( String(localized: "Show Query History"), action: #selector(MainSplitViewController.toggleQueryHistory(_:)), diff --git a/apple/TablePro/Core/Services/Formatting/CellDisplayFormatter.swift b/apple/TablePro/Core/Services/Formatting/CellDisplayFormatter.swift index ff342b04ba..f4b0224640 100644 --- a/apple/TablePro/Core/Services/Formatting/CellDisplayFormatter.swift +++ b/apple/TablePro/Core/Services/Formatting/CellDisplayFormatter.swift @@ -48,7 +48,8 @@ enum CellDisplayFormatter { _ rawValue: PluginCellValue, columnType: ColumnType?, displayFormat: ValueDisplayFormat?, - databaseType: DatabaseType? + databaseType: DatabaseType?, + keepsLineBreaks: Bool = false ) -> (text: String?, isFormatted: Bool) { resolve( rawValue, @@ -56,7 +57,8 @@ enum CellDisplayFormatter { displayFormat: displayFormat, databaseType: databaseType, dates: DateFormattingService.shared.renderer, - checksRendering: true + checksRendering: true, + keepsLineBreaks: keepsLineBreaks ) } @@ -66,7 +68,8 @@ enum CellDisplayFormatter { columnType: ColumnType?, displayFormat: ValueDisplayFormat?, databaseType: DatabaseType?, - dates: DateDisplayRenderer + dates: DateDisplayRenderer, + keepsLineBreaks: Bool = false ) -> (text: String?, isFormatted: Bool) { resolve( rawValue, @@ -74,7 +77,8 @@ enum CellDisplayFormatter { displayFormat: displayFormat, databaseType: databaseType, dates: dates, - checksRendering: true + checksRendering: true, + keepsLineBreaks: keepsLineBreaks ) } @@ -85,7 +89,8 @@ enum CellDisplayFormatter { displayFormat: ValueDisplayFormat?, databaseType: DatabaseType?, dates: DateDisplayRenderer, - checksRendering: Bool + checksRendering: Bool, + keepsLineBreaks: Bool = false ) -> (text: String?, isFormatted: Bool) { switch rawValue { case .null: @@ -94,7 +99,7 @@ enum CellDisplayFormatter { if let displayFormat, displayFormat.isApplicable(to: columnType, databaseType: databaseType), let formatted = ValueDisplayFormatter.apply(data, format: displayFormat, columnType: columnType) { - return (fitToCell(formatted), true) + return (fitToCell(formatted, keepsLineBreaks: keepsLineBreaks), true) } return (BlobFormattingService.shared.format(data, for: .grid), false) case .text(let value): @@ -102,7 +107,10 @@ enum CellDisplayFormatter { if let displayFormat, displayFormat != .raw, displayFormat.isApplicable(to: columnType, databaseType: databaseType), let formatted = ValueDisplayFormatter.apply(value, format: displayFormat, columnType: columnType, dates: dates) { - return (fitToCell(formatted), checksRendering && rendered(formatted, from: value, by: displayFormat)) + return ( + fitToCell(formatted, keepsLineBreaks: keepsLineBreaks), + checksRendering && rendered(formatted, from: value, by: displayFormat) + ) } var displayValue = value if let columnType { @@ -118,7 +126,7 @@ enum CellDisplayFormatter { ) } } - return (fitToCell(displayValue), false) + return (fitToCell(displayValue, keepsLineBreaks: keepsLineBreaks), false) } } @@ -139,14 +147,17 @@ enum CellDisplayFormatter { } // Binary read as text carries newlines and runs to megabytes, so all output is capped and flattened. A lone CR stays for the cell to mark. - private static func fitToCell(_ value: String) -> String { + // A grid that wraps keeps the breaks instead, each as one LF. + private static func fitToCell(_ value: String, keepsLineBreaks: Bool) -> String { // A value within the cap in UTF-8 is within it in UTF-16, and asking for that length walks the whole value. - guard value.utf8.count > maxDisplayLength else { return value.flattenedForCell } + guard value.utf8.count > maxDisplayLength else { + return keepsLineBreaks ? value.keepingLineBreaksForCell : value.flattenedForCell + } var displayValue = value let nsDisplay = displayValue as NSString if nsDisplay.length > maxDisplayLength { displayValue = nsDisplay.substring(to: maxDisplayLength) + "…" } - return displayValue.flattenedForCell + return keepsLineBreaks ? displayValue.keepingLineBreaksForCell : displayValue.flattenedForCell } } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift index 7048c13b90..19eb0bd74a 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift @@ -41,6 +41,7 @@ struct MenuValidationContext: Equatable { var canFocusInspector = false var canFocusAssistant = false var canPresentHighlightRules = false + var canToggleWrapText = false var isQueryTab = false var hasResultRows = false // Export Results reaches a Table Health tab's findings, which no result set holds. @@ -330,6 +331,8 @@ extension MainSplitViewController: NSMenuItemValidation { return context.isConnected && context.canUseTableResultCommands case #selector(showHighlightRules(_:)): return context.isConnected && context.canPresentHighlightRules + case #selector(toggleWrapText(_:)): + return context.isConnected && context.canToggleWrapText case #selector(pinResult(_:)): return context.canPinResultTab case #selector(compareResult(_:)): @@ -730,6 +733,7 @@ extension MainSplitViewController: NSMenuItemValidation { canFocusInspector: canFocusInspector, canFocusAssistant: canFocusAssistant, canPresentHighlightRules: actions.canPresentHighlightRules, + canToggleWrapText: actions.canToggleWrapText, isQueryTab: actions.isQueryTab, hasResultRows: actions.hasResultRows, hasTableHealthFindings: actions.hasTableHealthFindings, @@ -928,6 +932,8 @@ extension MainSplitViewController: NSMenuItemValidation { ?? String(localized: "Release File Lock"), on: menuItem ) + case #selector(toggleWrapText(_:)): + setState(commandActions?.wrapsGridText == true ? .on : .off, on: menuItem) case #selector(setResultView(_:)): setState(isCurrentResultView(menuItem) ? .on : .off, on: menuItem) case #selector(setContentModeFromMenu(_:)): diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+ViewMenuActions.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+ViewMenuActions.swift index dfd8dd6a96..6839f3d212 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+ViewMenuActions.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+ViewMenuActions.swift @@ -107,6 +107,10 @@ extension MainSplitViewController { commandActions?.showHighlightRules() } + @objc func toggleWrapText(_ sender: Any?) { + commandActions?.toggleWrapText() + } + @objc func toggleQueryHistory(_ sender: Any?) { commandActions?.toggleHistoryPanel() } diff --git a/apple/TablePro/Core/Services/Infrastructure/RecentlyClosedTabReopener.swift b/apple/TablePro/Core/Services/Infrastructure/RecentlyClosedTabReopener.swift index 59c1f0805c..95accd8c4f 100644 --- a/apple/TablePro/Core/Services/Infrastructure/RecentlyClosedTabReopener.swift +++ b/apple/TablePro/Core/Services/Infrastructure/RecentlyClosedTabReopener.swift @@ -52,9 +52,11 @@ internal enum RecentlyClosedTabReopener { } private static func makeTab(for entry: RecentlyClosedTabEntry) -> QueryTab { + let dataGrid = AppSettingsManager.shared.dataGrid var tab = QueryTab( from: entry.tab, - defaultPageSize: AppSettingsManager.shared.dataGrid.defaultPageSize + defaultPageSize: dataGrid.defaultPageSize, + defaultWrapsText: dataGrid.wrapText ) FileTabBaseline.hydrate(&tab) return tab diff --git a/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift b/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift index f667112ce4..956616d0ae 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift @@ -215,8 +215,10 @@ internal final class TabPersistenceCoordinator: ObservableObject { return RestoreResult(tabs: [], selectedTabId: nil, source: .none) } - let defaultPageSize = AppSettingsManager.shared.dataGrid.defaultPageSize - var restoredTabs = state.tabs.map { QueryTab(from: $0, defaultPageSize: defaultPageSize) } + let dataGrid = AppSettingsManager.shared.dataGrid + var restoredTabs = state.tabs.map { + QueryTab(from: $0, defaultPageSize: dataGrid.defaultPageSize, defaultWrapsText: dataGrid.wrapText) + } FileTabBaseline.hydrate(&restoredTabs) RestoredHiddenColumns.hydrate( &restoredTabs, diff --git a/apple/TablePro/Models/Query/QueryTab.swift b/apple/TablePro/Models/Query/QueryTab.swift index 7409e6b1e1..02c968882a 100644 --- a/apple/TablePro/Models/Query/QueryTab.swift +++ b/apple/TablePro/Models/Query/QueryTab.swift @@ -64,6 +64,8 @@ struct QueryTab: Identifiable, Equatable { var columnLayout: ColumnLayoutState // On the tab, not the grid: JSON mode, the inspector and the Edit menu's row commands read the order unmounted (#2251). var valueFilter: GridValueFilterState + // Seeded from the Data Grid setting when the tab is made; a later change of the setting leaves it alone. + var wrapsText = false var sessionHighlightRules: [HighlightRule] = [] // Set only by Reveal, after the user authenticated; never saved, so a reopened tab masks again. var revealsMaskedValues = false @@ -169,7 +171,7 @@ struct QueryTab: Identifiable, Equatable { self.restoredCursorLength = nil } - init(from persisted: PersistedTab, defaultPageSize: Int) { + init(from persisted: PersistedTab, defaultPageSize: Int, defaultWrapsText: Bool = false) { self.id = persisted.id self.title = persisted.tabType.fixedTitle ?? persisted.title // A file names its tab, and a blank fallback would leave an emptied name with no title. @@ -212,6 +214,7 @@ struct QueryTab: Identifiable, Equatable { columnContentWidths: persisted.columnContentWidths ) self.valueFilter = GridValueFilterState() + self.wrapsText = persisted.wrapsText ?? defaultWrapsText self.pagination = PaginationState(pageSize: defaultPageSize) self.chartConfiguration = ResultChartConfiguration() self.mapConfiguration = ResultMapConfiguration() @@ -370,6 +373,7 @@ struct QueryTab: Identifiable, Equatable { collapsedFoldRanges: Self.foldBounds(collapsedFoldRanges, in: persistedQuery), columnWidths: widths, columnContentWidths: contentWidths, + wrapsText: wrapsText, isPinned: isPinned, isTemporary: tableContext.isTemporary ) diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index b7b6874e35..7c915c4ccf 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -375,6 +375,7 @@ final class QueryTabManager: ObservableObject { tabTitle = nextTitle() } var newTab = QueryTab(title: tabTitle, tabType: .query) + newTab.wrapsText = AppSettingsManager.shared.dataGrid.wrapText // Held as a name, so a move or a restore never renumbers it; clearing it comes back to the same title. if keepsTitle, title != nil, sourceFileURL == nil { newTab.automaticTitle = tabTitle @@ -505,6 +506,7 @@ final class QueryTabManager: ObservableObject { tableName: tableName ) newTab.pagination = PaginationState(pageSize: pageSize) + newTab.wrapsText = AppSettingsManager.shared.dataGrid.wrapText newTab.tableContext.databaseName = databaseName newTab.tableContext.objectType = objectType newTab.tableContext.isTemporary = isTemporary diff --git a/apple/TablePro/Models/Query/QueryTabState.swift b/apple/TablePro/Models/Query/QueryTabState.swift index 51734b8916..206f2cd763 100644 --- a/apple/TablePro/Models/Query/QueryTabState.swift +++ b/apple/TablePro/Models/Query/QueryTabState.swift @@ -74,6 +74,8 @@ struct PersistedTab: Codable { var collapsedFoldRanges: [Int]? var columnWidths: [String: CGFloat]? var columnContentWidths: [String: CGFloat]? + // Nil in files written before this existed: the tab then takes the Data Grid setting. + var wrapsText: Bool? var windowGroupIndex: Int? var isPinned: Bool = false var isTemporary: Bool = false @@ -107,6 +109,7 @@ struct PersistedTab: Codable { collapsedFoldRanges: [Int]? = nil, columnWidths: [String: CGFloat]? = nil, columnContentWidths: [String: CGFloat]? = nil, + wrapsText: Bool? = nil, windowGroupIndex: Int? = nil, isPinned: Bool = false, isTemporary: Bool = false @@ -136,6 +139,7 @@ struct PersistedTab: Codable { self.collapsedFoldRanges = collapsedFoldRanges self.columnWidths = columnWidths self.columnContentWidths = columnContentWidths + self.wrapsText = wrapsText self.windowGroupIndex = windowGroupIndex self.isPinned = isPinned self.isTemporary = isTemporary @@ -146,7 +150,7 @@ struct PersistedTab: Codable { case sourceFileURL, sourceFileEncoding, erDiagramSchemaKey, objectRef, versionHistorySubject, queryParameters case sortColumns, sortSource, restoredPage, restoredPageSize, cursorOffset, cursorLength case collapsedFoldRanges - case columnWidths, columnContentWidths, windowGroupIndex + case columnWidths, columnContentWidths, wrapsText, windowGroupIndex case isPinned case isTemporary case overflowFileName @@ -179,6 +183,7 @@ struct PersistedTab: Codable { collapsedFoldRanges = try container.decodeIfPresent([Int].self, forKey: .collapsedFoldRanges) columnWidths = try container.decodeIfPresent([String: CGFloat].self, forKey: .columnWidths) columnContentWidths = try container.decodeIfPresent([String: CGFloat].self, forKey: .columnContentWidths) + wrapsText = try container.decodeIfPresent(Bool.self, forKey: .wrapsText) windowGroupIndex = try container.decodeIfPresent(Int.self, forKey: .windowGroupIndex) isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) ?? false isTemporary = try container.decodeIfPresent(Bool.self, forKey: .isTemporary) ?? false diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 09cbe8bcb7..eda5295543 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -124,6 +124,8 @@ struct DataGridSettings: Codable, Equatable { var defaultSortDirection: SortDirection var rowCopyFormat: RowCopyFormat var showInvisibleCharacters: Bool + // What a new tab's grid starts with; an open tab keeps its own choice. + var wrapText: Bool // 0 keeps every result a run returns. var resultSetsKeptPerRun: Int @@ -143,6 +145,7 @@ struct DataGridSettings: Codable, Equatable { defaultSortDirection: .ascending, rowCopyFormat: .rows, showInvisibleCharacters: true, + wrapText: false, resultSetsKeptPerRun: 0 ) @@ -162,6 +165,7 @@ struct DataGridSettings: Codable, Equatable { defaultSortDirection: SortDirection = .ascending, rowCopyFormat: RowCopyFormat = .rows, showInvisibleCharacters: Bool = true, + wrapText: Bool = false, resultSetsKeptPerRun: Int = 0 ) { self.rowHeight = rowHeight @@ -179,6 +183,7 @@ struct DataGridSettings: Codable, Equatable { self.defaultSortDirection = defaultSortDirection self.rowCopyFormat = rowCopyFormat self.showInvisibleCharacters = showInvisibleCharacters + self.wrapText = wrapText self.resultSetsKeptPerRun = resultSetsKeptPerRun } @@ -207,6 +212,7 @@ struct DataGridSettings: Codable, Equatable { showInvisibleCharacters = container.decodeSetting( .showInvisibleCharacters, default: fallback.showInvisibleCharacters ) + wrapText = container.decodeSetting(.wrapText, default: fallback.wrapText) resultSetsKeptPerRun = container.decodeSetting(.resultSetsKeptPerRun, default: fallback.resultSetsKeptPerRun) } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index ad74bb60f8..57b2b87f85 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -108563,6 +108563,9 @@ } } } + }, + "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid." : { + }, "Longest" : { @@ -223327,6 +223330,12 @@ } } } + }, + "Wrap Text" : { + + }, + "Wrap text in cells" : { + }, "Wrench" : { "extractionState" : "manual", diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellAppearance.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellAppearance.swift index ec6b958728..b96257f5f3 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellAppearance.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellAppearance.swift @@ -18,6 +18,8 @@ struct DataGridCellAppearance: Equatable { let accessoryColor: NSColor? let checkboxMark: DataGridCheckboxMark? let specialCharacterColor: NSColor? + // NULL, Empty and the other stand-ins stay one line in a grid that wraps. + let isPlaceholder: Bool static func resolve( kind: DataGridCellKind, @@ -102,7 +104,8 @@ struct DataGridCellAppearance: Equatable { accessoryRole: accessoryRole, accessoryColor: accessoryRole?.color(selectionText: palette.selectionText), checkboxMark: kind == .checkbox ? checkboxMark : nil, - specialCharacterColor: specialCharacterColor + specialCharacterColor: specialCharacterColor, + isPlaceholder: content.placeholder != nil ) } diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift index fd27a1042a..71c141c7d8 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellPresenter.swift @@ -33,6 +33,8 @@ final class DataGridCellPresenter { private var highlightRuleSet = HighlightRuleSet.empty // Indexed by data index: the draw path reads it once per cell. private var presentations: [DataGridColumnPresentation] = [] + // Set by the grid while it wraps, so the text it caches keeps its line breaks. + var keepsLineBreaks = false init(model: DataGridModel, valueColors: ValueColorSettings = AppSettingsManager.shared.valueColors) { self.model = model @@ -209,7 +211,8 @@ final class DataGridCellPresenter { rawValue, columnType: type, displayFormat: format, - databaseType: databaseType + databaseType: databaseType, + keepsLineBreaks: keepsLineBreaks ) let text = formatted.text ?? rawValue.asText ?? "" @@ -228,8 +231,93 @@ final class DataGridCellPresenter { return (text, formatted.isFormatted) } + // MARK: - Wrap + + struct WrapMeasure { + let geometry: DataGridWrapGeometry + let rows: TableRows + let formats: [ValueDisplayFormat?] + let databaseType: DatabaseType? + let checkboxColumns: Set + } + + func makeWrapMeasure(_ geometry: DataGridWrapGeometry) -> WrapMeasure? { + guard let model else { return nil } + let rows = model.rows + prepareRowState(rows: rows) + return WrapMeasure( + geometry: geometry, + rows: rows, + formats: model.store.displayFormats, + databaseType: model.configuration.traits.databaseType, + checkboxColumns: model.configuration.checkboxColumns + ) + } + + // The lines of the row's tallest cell over every column the grid shows, by the rules the draw follows. + func wrapLineCount(of row: Row, measure: WrapMeasure) -> Int { + let geometry = measure.geometry + let state = visualState(of: row) + let absent = measure.rows.absentColumns(of: row.id) + let unloaded = measure.rows.unloadedColumns(of: row.id) + let columnCount = measure.rows.columns.count + var lines = 1 + for column in geometry.columns where column.dataIndex >= 0 && column.dataIndex < row.values.count { + let dataIndex = column.dataIndex + let rawValue = row.values[dataIndex] + let isExpression = state.isExpression(columnIndex: dataIndex) + guard !measure.checkboxColumns.contains(dataIndex), + DataGridCellContent.placeholder( + for: rawValue, + isAbsent: absent.contains(dataIndex), + isExpression: isExpression, + unloadedByteCount: unloaded[dataIndex], + marksEmptyText: geometry.marksEmptyText + ) == nil else { continue } + let text = displayText( + of: row, + dataIndex: dataIndex, + type: column.type, + formats: measure.formats, + databaseType: measure.databaseType, + columnCount: columnCount + ) + let accessory = DataGridCellAccessory.visible(for: column.kind, isEditable: geometry.isEditable, rawValue: rawValue.asText) + lines = max(lines, DataGridWrapLayout.lineCount( + of: text, + width: accessory.availableTextWidth(in: NSRect(x: 0, y: 0, width: column.width, height: 0)), + face: isExpression ? geometry.medium : geometry.regular, + marksInvisibles: geometry.marksInvisibles + )) + if lines >= DataGridWrapLayout.maximumLines { break } + } + return lines + } + + private func prewarmWrap(for rows: [Row], in tableRows: TableRows, geometry: DataGridWrapGeometry, generation: Int) -> DataGridPrewarmWrap { + prepareRowState(rows: tableRows) + let measurable = rows.filter { row in + visualState(of: row).expressionColumns.isEmpty + && tableRows.absentColumns(of: row.id).isEmpty + && !tableRows.hasUnloadedValues(row.id) + } + return DataGridPrewarmWrap( + columns: geometry.columns.map { DataGridPrewarmWrap.Column(dataIndex: $0.dataIndex, width: $0.width, kind: $0.kind) }, + face: geometry.regular, + isEditable: geometry.isEditable, + marksEmptyText: geometry.marksEmptyText, + marksInvisibles: geometry.marksInvisibles, + measurableRows: Set(measurable.map(\.id)), + generation: generation + ) + } + // Copies the next rows of the window that have no text yet, and where the walk stopped. - func prewarmBatch(in window: Range, from start: Int) -> (batch: DataGridPrewarmBatch?, next: Int)? { + func prewarmBatch( + in window: Range, + from start: Int, + wrap geometry: DataGridWrapGeometry? = nil + ) -> (batch: DataGridPrewarmBatch?, next: Int)? { guard let model, start < window.upperBound else { return nil } let rows = model.rows let order = model.order @@ -250,16 +338,42 @@ final class DataGridCellPresenter { formats: model.store.displayFormats, databaseType: model.configuration.traits.databaseType, dateFormat: DateFormattingService.shared.currentFormat, - invalidations: cache.invalidations + invalidations: cache.invalidations, + keepsLineBreaks: keepsLineBreaks, + wrap: geometry.map { + prewarmWrap(for: copied, in: rows, geometry: $0, generation: model.display.lineCounts.generation) + } ) return (batch, index) } // False when cached text was dropped while the batch formatted, so what came back may describe old values. - func installPrewarmed(_ formatted: sending [(id: RowID, box: RowDisplayBox)], of batch: DataGridPrewarmBatch) -> Bool { - guard let cache = model?.display.cache, cache.invalidations == batch.invalidations else { return false } - for (id, box) in formatted where cache.box(forID: id) == nil { - cache.setBox(box, forID: id) + func installPrewarmed( + _ formatted: sending [(id: RowID, box: RowDisplayBox, lineCount: Int?)], + of batch: DataGridPrewarmBatch + ) -> Bool { + var grown: [RowID] = [] + return installPrewarmed(formatted, of: batch, grownRows: &grown) + } + + // `grownRows` takes the rows measured taller than the one line the table was told, for the grid to note. + func installPrewarmed( + _ formatted: sending [(id: RowID, box: RowDisplayBox, lineCount: Int?)], + of batch: DataGridPrewarmBatch, + grownRows: inout [RowID] + ) -> Bool { + guard let display = model?.display, display.cache.invalidations == batch.invalidations, + batch.keepsLineBreaks == keepsLineBreaks else { return false } + let cache = display.cache + let lineCounts = display.lineCounts + let takesLineCounts = batch.wrap?.generation == lineCounts.generation + for entry in formatted where cache.box(forID: entry.id) == nil { + cache.setBox(entry.box, forID: entry.id) + guard takesLineCounts, let lineCount = entry.lineCount, lineCounts[entry.id] == nil else { continue } + lineCounts[entry.id] = lineCount + if lineCount > 1 { + grownRows.append(entry.id) + } } return true } diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellRenderer.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellRenderer.swift index 36dbc226ff..0776daaea3 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellRenderer.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellRenderer.swift @@ -43,6 +43,22 @@ final class DataGridCellRenderer { } } + // A wrapped value breaks by its column's width, so the width joins the key. + private struct WrapKey: Hashable { + let line: LineKey + let width: CGFloat + } + + private final class WrappedText { + let lines: [DataGridWrapLayout.Line] + let marks: [[SpecialCharacterMark]] + + init(lines: [DataGridWrapLayout.Line], marks: [[SpecialCharacterMark]]) { + self.lines = lines + self.marks = marks + } + } + private struct RowNumberKey: Hashable { let number: Int let font: NSFont @@ -55,6 +71,7 @@ final class DataGridCellRenderer { private static let maximumLaidOutCharacters = 300 private var lineCache: [LineKey: LaidOutLine] = [:] + private var wrapCache: [WrapKey: WrappedText] = [:] private var rowNumberLines: [RowNumberKey: CTLine] = [:] private var rowNumberMetrics: (font: NSFont, lineHeight: CGFloat, baselineOffset: CGFloat)? @@ -69,10 +86,17 @@ final class DataGridCellRenderer { func invalidateCachedLines() { lineCache.removeAll(keepingCapacity: true) + wrapCache.removeAll(keepingCapacity: true) rowNumberLines.removeAll(keepingCapacity: true) } - func draw(_ appearance: DataGridCellAppearance, in rect: NSRect, controlView: NSView? = nil) { + // `wrap` is set by a grid that wraps: a value breaks over the row's lines, and all else sits on the first. + func draw( + _ appearance: DataGridCellAppearance, + in rect: NSRect, + controlView: NSView? = nil, + wrap: DataGridWrapMetrics? = nil + ) { guard rect.width > 0, rect.height > 0, let context = NSGraphicsContext.current?.cgContext else { return } if let tint = appearance.backgroundTint { @@ -80,14 +104,19 @@ final class DataGridCellRenderer { rect.fill() } - let accessoryRect = appearance.accessory.frame(in: rect) + let firstLine = wrap?.firstLine(of: rect) ?? rect + let accessoryRect = appearance.accessory.frame(in: firstLine) context.saveGState() context.clip(to: rect) - drawText(appearance, in: rect, context: context) + if let wrap, !appearance.isPlaceholder { + drawWrappedText(appearance, in: rect, metrics: wrap, context: context) + } else { + drawText(appearance, in: firstLine, context: context) + } drawAccessory(appearance.accessoryRole, color: appearance.accessoryColor, in: accessoryRect) if let mark = appearance.checkboxMark, let controlView { - drawCheckbox(mark, in: rect, controlView: controlView) + drawCheckbox(mark, in: firstLine, controlView: controlView) } context.restoreGState() } @@ -162,6 +191,80 @@ final class DataGridCellRenderer { context.restoreGState() } + private func drawWrappedText( + _ appearance: DataGridCellAppearance, + in rect: NSRect, + metrics: DataGridWrapMetrics, + context: CGContext + ) { + guard !appearance.text.isEmpty else { return } + let font = appearance.font + let width = appearance.accessory.availableTextWidth(in: rect) + guard DataGridWrapLayout.canWrap(width: width, font: font) else { return } + + let wrapped = wrappedText(for: appearance, width: width) + let textX = rect.minX + DataGridMetrics.cellHorizontalInset + let firstBaseline = rect.minY + (metrics.rowHeight - font.ascender + font.descender - font.leading) / 2 + font.ascender + context.saveGState() + for (index, line) in wrapped.lines.enumerated() { + let baseline = firstBaseline + CGFloat(index) * metrics.lineHeight + guard baseline - font.ascender < rect.maxY else { break } + context.textMatrix = CGAffineTransform(scaleX: 1, y: -1) + context.textPosition = CGPoint(x: textX, y: baseline) + CTLineDraw(line.line, context) + let marks = wrapped.marks[index] + guard !marks.isEmpty else { continue } + SpecialCharacterLine.draw( + marks, + fromX: textX, + top: baseline - font.ascender, + height: font.ascender - font.descender, + in: context + ) + } + context.restoreGState() + } + + // A line break is a break here, so only the other invisible characters take a mark. + private func wrappedText(for appearance: DataGridCellAppearance, width: CGFloat) -> WrappedText { + let font = appearance.font + let cut = DataGridWrapLayout.bounded(appearance.text, width: width, pointSize: font.pointSize) + let key = WrapKey( + line: LineKey( + shownText: cut.text, + isClipped: cut.isCut, + font: font, + color: appearance.textColor, + mark: appearance.textMark, + specialCharacterColor: appearance.specialCharacterColor + ), + width: width + ) + if let cached = wrapCache[key] { return cached } + + var attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: appearance.textColor] + appearance.textMark?.attributes.forEach { attributes[$0.key] = $0.value } + let string = NSAttributedString(string: cut.text, attributes: attributes) + let marked = appearance.specialCharacterColor.map { + SpecialCharacterText(string, style: SpecialCharacterStyle(color: $0)) + } + let lines = DataGridWrapLayout.lines( + of: marked?.string ?? string, + width: width, + endsCut: cut.isCut, + ellipsisAttributes: attributes + ) + let created = WrappedText( + lines: lines, + marks: lines.map { marked?.marks(from: $0.start, in: $0.source, drawnAs: $0.line) ?? [] } + ) + if wrapCache.count >= Self.lineCacheLimit { + wrapCache.removeAll(keepingCapacity: true) + } + wrapCache[key] = created + return created + } + // The mark is part of the key: the same value struck through is a different drawing. private func line(for text: String, appearance: DataGridCellAppearance) -> LaidOutLine { let font = appearance.font diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridCellText.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridCellText.swift index 017a437888..768ddd6c27 100644 --- a/apple/TablePro/Views/DataGrid/Cells/DataGridCellText.swift +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridCellText.swift @@ -32,6 +32,46 @@ internal extension String { flattenedOntoOneLine(keepingLoneCarriageReturns: true) } + // What a wrapping cell lays out: every break form is one LF, CRLF counts once, and a break that ends the value goes. + var keepingLineBreaksForCell: String { + var text = self + let normalized: String? = text.withUTF8 { bytes in + var output: [UInt8] = [] + var copiedUpTo = 0 + var index = 0 + var changed = false + while index < bytes.count { + var length = Self.lineBreakLength(in: bytes, at: index) + guard length > 0 else { + index += 1 + continue + } + if bytes[index] == 0x0D, index + 1 < bytes.count, bytes[index + 1] == 0x0A { + length = 2 + } + let endsText = index + length == bytes.count + if length == 1, bytes[index] == 0x0A, !endsText { + index += 1 + continue + } + if !changed { + output.reserveCapacity(bytes.count) + changed = true + } + output.append(contentsOf: bytes[copiedUpTo.. CGFloat { + (font.ascender - font.descender + font.leading).rounded(.up) + } + + // The padding of a one-line row stays around the lines, so one line is exactly the row height. + static func wrappedRowHeight(lines: Int, rowHeight: CGFloat, lineHeight: CGFloat) -> CGFloat { + rowHeight + CGFloat(max(lines, 1) - 1) * lineHeight + } + // An overlay scroller floats over the last row, so only a legacy one adds height. static func fittingHeight( headerHeight: CGFloat, @@ -32,3 +41,14 @@ enum DataGridMetrics { headerHeight + CGFloat(max(rowCount, 0)) * rowPitch + horizontalScrollerHeight } } + +// What a wrapping grid lays a tall row out by: the one-line row height, and the pitch of the lines after the first. +struct DataGridWrapMetrics: Equatable { + let rowHeight: CGFloat + let lineHeight: CGFloat + + // Where a one-line row would put what it draws: the row number, the accessory, the checkbox and the edit field stay there. + func firstLine(of rect: NSRect) -> NSRect { + NSRect(x: rect.minX, y: rect.minY, width: rect.width, height: min(rowHeight, rect.height)) + } +} diff --git a/apple/TablePro/Views/DataGrid/Cells/DataGridWrapLayout.swift b/apple/TablePro/Views/DataGrid/Cells/DataGridWrapLayout.swift new file mode 100644 index 0000000000..50782a66d0 --- /dev/null +++ b/apple/TablePro/Views/DataGrid/Cells/DataGridWrapLayout.swift @@ -0,0 +1,167 @@ +// +// DataGridWrapLayout.swift +// TablePro +// + +import AppKit +import CoreText +import TableProTextEngine + +// Where a value breaks when a cell wraps it. The count sizes the row and the lines draw it, from the same breaks. +enum DataGridWrapLayout { + static let maximumLines = 10 + + // Fonts are immutable and Core Text reads one from any thread, so a row is measured off the main actor with it. + struct Face: Equatable, @unchecked Sendable { + let font: NSFont + // Infinite when the font lacks an ASCII glyph, which leaves every value to the typesetter. + let widestASCIIAdvance: CGFloat + + init(_ font: NSFont) { + self.font = font + let characters = Array(UInt16(0x20)...UInt16(0x7E)) + var glyphs = [CGGlyph](repeating: 0, count: characters.count) + guard CTFontGetGlyphsForCharacters(font as CTFont, characters, &glyphs, characters.count) else { + widestASCIIAdvance = .infinity + return + } + var advances = [CGSize](repeating: .zero, count: glyphs.count) + CTFontGetAdvancesForGlyphs(font as CTFont, .horizontal, glyphs, &advances, glyphs.count) + widestASCIIAdvance = advances.map(\.width).max() ?? .infinity + } + } + + struct Line { + let line: CTLine + // `line`, or the line an end truncation was cut from. + let source: CTLine + // The UTF-16 offset of the line's first character in the laid out text. + let start: Int + } + + // A column too narrow for one character draws no text and stays one line. + static func canWrap(width: CGFloat, font: NSFont) -> Bool { + width >= font.pointSize + } + + // Typesetting costs the whole string even when ten lines are read, so the text is cut to what ten lines can hold. + static func bounded(_ text: String, width: CGFloat, pointSize: CGFloat) -> (text: String, isCut: Bool) { + let unitsPerLine = pointSize > 0 ? max(32, Int((width / (pointSize * 0.2)).rounded(.up))) : 32 + let limit = maximumLines * unitsPerLine + var text = text + let kept: String? = text.withUTF8 { bytes in + var units = 0 + var breaks = 0 + for index in bytes.indices { + let byte = bytes[index] + if byte == 0x0A { + breaks += 1 + if breaks == maximumLines { + return String(bytes: bytes[..= 0xF0 ? 2 : 1 + if units > limit { + return String(bytes: bytes[.. Bool { + text.utf16.contains { SpecialCharacter.mayBeSpecial($0) } + } + + // The lines a value takes with no invisible character marked. Safe off the main actor. + static func lineCount(of text: String, width: CGFloat, face: Face) -> Int { + guard !text.isEmpty, canWrap(width: width, font: face.font) else { return 1 } + if fitsOneLine(text, width: width, face: face) { return 1 } + let cut = bounded(text, width: width, pointSize: face.font.pointSize) + return lineCount(of: NSAttributedString(string: cut.text, attributes: [.font: face.font]), width: width) + } + + // The marks keep their caches on the main actor, and a marker is wider than the character it stands for. + @MainActor + static func lineCount(of text: String, width: CGFloat, face: Face, marksInvisibles: Bool) -> Int { + guard marksInvisibles else { return lineCount(of: text, width: width, face: face) } + guard !text.isEmpty, canWrap(width: width, font: face.font) else { return 1 } + if fitsOneLine(text, width: width, face: face) { return 1 } + let cut = bounded(text, width: width, pointSize: face.font.pointSize) + let string = NSAttributedString(string: cut.text, attributes: [.font: face.font]) + guard holdsMarkableCharacter(cut.text) else { return lineCount(of: string, width: width) } + return lineCount(of: SpecialCharacterText(string, style: SpecialCharacterStyle()).string, width: width) + } + + static func lineCount(of string: NSAttributedString, width: CGFloat) -> Int { + let length = string.length + guard length > 0 else { return 1 } + let typesetter = CTTypesetterCreateWithAttributedString(string) + var start = 0 + var count = 0 + while start < length, count < maximumLines { + start += max(1, CTTypesetterSuggestLineBreak(typesetter, start, Double(width))) + count += 1 + } + // Core Text opens no line after a closing break; the row still shows the empty line the value ends with. + if start >= length, count < maximumLines, (string.string as NSString).character(at: length - 1) == 0x0A { + count += 1 + } + return max(1, count) + } + + // `endsCut` says text was dropped after `string`, so its last line ends in an ellipsis as the tenth line does. + static func lines( + of string: NSAttributedString, + width: CGFloat, + endsCut: Bool, + ellipsisAttributes: [NSAttributedString.Key: Any] + ) -> [Line] { + let length = string.length + guard length > 0 else { return [] } + let typesetter = CTTypesetterCreateWithAttributedString(string) + var lines: [Line] = [] + var start = 0 + while start < length { + let count = min(length - start, max(1, CTTypesetterSuggestLineBreak(typesetter, start, Double(width)))) + let end = start + count + let dropsRest = lines.count == maximumLines - 1 && end < length + if dropsRest || (end == length && endsCut) { + lines.append(closingLine(of: string, from: start, width: width, ellipsisAttributes: ellipsisAttributes)) + return lines + } + let line = CTTypesetterCreateLine(typesetter, CFRange(location: start, length: count)) + lines.append(Line(line: line, source: line, start: start)) + start = end + } + return lines + } + + // The rest of the paragraph with an ellipsis after it, cut to the width when the two do not fit. + private static func closingLine( + of string: NSAttributedString, + from start: Int, + width: CGFloat, + ellipsisAttributes: [NSAttributedString.Key: Any] + ) -> Line { + let text = string.string as NSString + let nextBreak = text.range(of: "\n", options: .literal, range: NSRange(location: start, length: text.length - start)) + let end = nextBreak.location == NSNotFound ? text.length : nextBreak.location + let ellipsis = NSAttributedString(string: "\u{2026}", attributes: ellipsisAttributes) + let shown = NSMutableAttributedString(attributedString: string.attributedSubstring(from: NSRange(location: start, length: end - start))) + shown.append(ellipsis) + let full = CTLineCreateWithAttributedString(shown) + guard CTLineGetTypographicBounds(full, nil, nil, nil) > Double(width) else { + return Line(line: full, source: full, start: start) + } + let token = CTLineCreateWithAttributedString(ellipsis) + return Line(line: CTLineCreateTruncatedLine(full, Double(width), .end, token) ?? token, source: full, start: start) + } + + private static func fitsOneLine(_ text: String, width: CGFloat, face: Face) -> Bool { + guard CGFloat(text.utf8.count) * face.widestASCIIAdvance <= width else { return false } + return text.utf8.allSatisfy { $0 >= 0x20 && $0 < 0x7F } + } +} diff --git a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+HeaderMenu.swift b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+HeaderMenu.swift index 84d08cd831..750cd083af 100644 --- a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+HeaderMenu.swift +++ b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+HeaderMenu.swift @@ -66,6 +66,12 @@ extension DataGridViewController { menuItem(String(localized: "Size All Columns to Fit"), #selector(sizeAllColumnsToFitFromMenu(_:)), nil), ]) + if commands.offers(.wrapText) { + let wrap = menuItem(String(localized: "Wrap Text"), #selector(toggleWrapText(_:)), nil) + wrap.state = model.wrapsText ? .on : .off + groups.append([wrap]) + } + if commands.offers(.hideColumns) { var visibility = [menuItem(String(localized: "Hide Column"), #selector(hideColumnFromMenu(_:)), columnID)] if !model.store.columnLayout.hiddenColumns.isEmpty { @@ -188,6 +194,7 @@ extension DataGridViewController { #selector(DataGridViewController.chooseProtobufSchemaFromMenu(_:)), #selector(DataGridViewController.sizeColumnToFitFromMenu(_:)), #selector(DataGridViewController.sizeAllColumnsToFitFromMenu(_:)), + #selector(DataGridViewController.toggleWrapText(_:)), #selector(DataGridViewController.hideColumnFromMenu(_:)), #selector(DataGridViewController.showAllColumnsFromMenu(_:)), #selector(DataGridViewController.freezeColumnsFromMenu(_:)), diff --git a/apple/TablePro/Views/DataGrid/DataGridContainerView.swift b/apple/TablePro/Views/DataGrid/DataGridContainerView.swift index a7aa4aa40f..29f0e5199d 100644 --- a/apple/TablePro/Views/DataGrid/DataGridContainerView.swift +++ b/apple/TablePro/Views/DataGrid/DataGridContainerView.swift @@ -13,6 +13,8 @@ final class DataGridContainerView: NSView { weak var controller: DataGridViewController? private(set) var gridHasFocus = false + // Set while the grid wraps: AppKit estimates the rows it has not asked about, so the two documents differ in height. + var anchorsRowsWhenSyncing = false private var isSyncingScroll = false private var firstResponderObservation: NSKeyValueObservation? private var windowObservers: [NSObjectProtocol] = [] @@ -127,18 +129,48 @@ final class DataGridContainerView: NSView { ] } + func resyncVertical() { + syncVertical(from: main.scrollView, to: frozen.scrollView) + } + // clipView.scroll(to:) is right here: only y moves, so the header clip, which follows x, never drifts. private func syncVertical(from source: NSScrollView, to target: NSScrollView) { guard !isSyncingScroll, !target.isHidden || target === main.scrollView else { return } - let y = source.contentView.bounds.origin.y let clip = target.contentView - guard clip.bounds.origin.y != y else { return } + let y: CGFloat + if anchorsRowsWhenSyncing { + y = rowAnchoredY(from: source, to: target) + guard abs(clip.bounds.origin.y - y) > 0.01 else { return } + } else { + y = source.contentView.bounds.origin.y + guard clip.bounds.origin.y != y else { return } + } isSyncingScroll = true clip.scroll(to: NSPoint(x: clip.bounds.origin.x, y: y)) target.reflectScrolledClipView(clip) isSyncingScroll = false } + // The same row at the same offset under each header, whatever height each table gives the rows above it. + private func rowAnchoredY(from source: NSScrollView, to target: NSScrollView) -> CGFloat { + let sourceClip = source.contentView + let y = sourceClip.bounds.origin.y + guard let sourceTable = source.documentView as? NSTableView, + let targetTable = target.documentView as? NSTableView else { return y } + let rowCount = min(sourceTable.numberOfRows, targetTable.numberOfRows) + let top = y + sourceClip.contentInsets.top + guard rowCount > 0, top >= 0 else { return y } + let targetInset = target.contentView.contentInsets.top + let shown = sourceTable.rows(in: NSRect(x: sourceClip.bounds.minX, y: top, width: max(sourceClip.bounds.width, 1), height: 1)) + guard shown.length > 0, shown.location >= 0, shown.location < rowCount else { + // Past the last row, as an elastic scroll goes: the distance below it is the same in both. + let last = rowCount - 1 + return targetTable.rect(ofRow: last).maxY + top - sourceTable.rect(ofRow: last).maxY - targetInset + } + let row = shown.location + return targetTable.rect(ofRow: row).minY + top - sourceTable.rect(ofRow: row).minY - targetInset + } + private func observePageScroll() { if let pageScrollObserver { NotificationCenter.default.removeObserver(pageScrollObserver) diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift index dec75b2e01..6e491b0802 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Changes.swift @@ -37,9 +37,14 @@ extension DataGridViewController { editingDidApply(change) selectionDidMove() selectionSummaryTracker.dataDidChange() + wrapDidApply(change) } func configurationDidChange() { + guard model.wrapsText == wrapsText else { + wrapModeDidChange() + return + } applyTableSettings() let changed = presenter.refreshColumnPresentations() reconcileColumns(widening: changed) @@ -47,6 +52,7 @@ extension DataGridViewController { syncSortIndicators() redrawVisibleRows() updateFittingHeight() + syncWrapGeometry() } // MARK: - Structural changes @@ -56,6 +62,9 @@ extension DataGridViewController { let changed = presenter.refreshColumnPresentations() reconcileColumns(widening: changed) applyRowNumberWidth() + // The reload asks every height again, so new widths only drop the counts here. + syncWrapGeometry(retiles: false) + wrapState.measured = nil for pane in panes { pane.tableView.reloadData() } @@ -185,6 +194,10 @@ extension DataGridViewController { font: ThemeEngine.shared.dataGridFonts.regular ) guard panes.contains(where: { $0.tableView.rowHeight != height }) else { return } + guard !wrapsText else { + applyWrappedRowHeight(height) + return + } keepingFirstVisibleRow { for pane in panes { pane.tableView.rowHeight = height @@ -325,7 +338,7 @@ extension DataGridViewController { displayCount: model.rowCount ) let start = max(nextIndex ?? window.lowerBound, window.lowerBound) - guard let (batch, next) = presenter.prewarmBatch(in: window, from: start) else { return } + guard let (batch, next) = presenter.prewarmBatch(in: window, from: start, wrap: wrapState.geometry) else { return } guard let batch else { nextIndex = next continue @@ -333,13 +346,16 @@ extension DataGridViewController { let formatted = await batch.formatted() guard !Task.isCancelled else { return } // Text dropped meanwhile leaves these rows to read again. - if presenter.installPrewarmed(formatted, of: batch) { + var grown: [RowID] = [] + if presenter.installPrewarmed(formatted, of: batch, grownRows: &grown) { nextIndex = next } + noteRowHeights(ofRowIDs: grown) } } func mainViewportDidMove() { + measureViewportRows() remountAccessibilityCells() schedulePrewarmResume() } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift index 98e4f8fda3..9bcc0883e8 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Columns.swift @@ -276,6 +276,7 @@ extension DataGridViewController { } isRebuildingColumns = false geometryDidChange() + syncWrapGeometry() model.columnGeometryDidChange(widths: named, order: nil) } @@ -294,6 +295,8 @@ extension DataGridViewController { updateFrozenPane() } geometryDidChange() + // AppKit posts the resize once the drag ends, so the rows are measured again once, not on every step. + syncWrapGeometry() model.columnGeometryDidChange(widths: [id.name: tableColumn.width], order: nil) } diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Drawing.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Drawing.swift index 46d9a5b9c3..c22c3e3950 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+Drawing.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Drawing.swift @@ -37,7 +37,8 @@ extension DataGridViewController { selected: selected, isWholeRow: !columns.isEmpty && selected.contains(integersIn: 0..= 0, row < table.numberOfRows else { return } revealingInGrid { table.scrollRowToVisible(row) + if wrapsText { + // The row was placed by an estimate until it was measured, which the scroll just did. + measureViewportRows() + table.scrollRowToVisible(row) + } if let displayColumn { revealColumn(displayColumn) } @@ -411,7 +416,8 @@ extension DataGridViewController { guard let rowModel = model.row(at: row), let column = model.columns.column(at: cell.displayColumn) else { return false } let columnRect = table.rect(ofColumn: tableColumn) let rowRect = table.rect(ofRow: row) - let cellRect = NSRect(x: columnRect.minX, y: rowRect.minY, width: columnRect.width, height: rowRect.height) + let wholeCell = NSRect(x: columnRect.minX, y: rowRect.minY, width: columnRect.width, height: rowRect.height) + let cellRect = wrapMetrics?.firstLine(of: wholeCell) ?? wholeCell if model.configuration.checkboxColumns.contains(column.dataIndex) { guard DataGridCheckboxMark.frame(in: cellRect).contains(point) else { return false } return toggleCheckbox(rowID: rowModel.id, column: column, displayRow: row) diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+TableDelegate.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+TableDelegate.swift index a878694d7a..e4f0c3dcf3 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController+TableDelegate.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+TableDelegate.swift @@ -38,6 +38,11 @@ extension DataGridViewController: NSTableViewDataSource, NSTableViewDelegate { static let rowViewIdentifier = NSUserInterfaceItemIdentifier("DataGridRowView") + // Asked only while the grid wraps (see responds(to:)). A row not measured yet stands one line tall. + func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { + rowHeight(forRow: row, in: tableView) + } + // Answers from the active column only, so type-select matches what the reader is looking at. func tableView(_ tableView: NSTableView, typeSelectStringFor tableColumn: NSTableColumn?, row: Int) -> String? { guard tableView === main.tableView, diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController+Wrap.swift b/apple/TablePro/Views/DataGrid/DataGridViewController+Wrap.swift new file mode 100644 index 0000000000..28281bb064 --- /dev/null +++ b/apple/TablePro/Views/DataGrid/DataGridViewController+Wrap.swift @@ -0,0 +1,335 @@ +// +// DataGridViewController+Wrap.swift +// TablePro +// + +import AppKit +import TableProPluginKit + +// What the measured rows were measured against. A change in any of it voids every count. +struct DataGridWrapGeometry: Equatable { + struct Column: Equatable { + let dataIndex: Int + let type: ColumnType? + // The column's rect in the main table, which holds every column at the width both panes draw it. + let width: CGFloat + let kind: DataGridCellKind + } + + let columns: [Column] + let regular: DataGridWrapLayout.Face + let medium: DataGridWrapLayout.Face + let marksInvisibles: Bool + let isEditable: Bool + let marksEmptyText: Bool + let rowHeight: CGFloat + let lineHeight: CGFloat +} + +@MainActor +final class DataGridWrapState { + var isOn = false + var geometry: DataGridWrapGeometry? + // The display rows already measured, and the line-count generation that holds for. + var measured: (rows: Range, generation: Int)? + var isMeasuring = false + // Rows whose height waits for the field edit in them to end. + var deferredRows: Set = [] +} + +extension DataGridViewController { + var wrapsText: Bool { wrapState.isOn } + + var wrapMetrics: DataGridWrapMetrics? { + guard wrapState.isOn else { return nil } + return DataGridWrapMetrics(rowHeight: main.tableView.rowHeight, lineHeight: wrapLineHeight) + } + + private var wrapLineHeight: CGFloat { + wrapState.geometry?.lineHeight ?? DataGridMetrics.lineHeight(of: ThemeEngine.shared.dataGridFonts.regular) + } + + // MARK: - Mode + + // AppKit reads which delegate methods exist when the delegate is assigned, so the tables take it again. + // Returns true when the mode moved, which a full reload has to follow. + @discardableResult + func applyWrapMode() -> Bool { + let wraps = model.wrapsText + let display = model.display + if display.keepsLineBreaks != wraps { + display.keepsLineBreaks = wraps + display.cache.removeAll() + } + presenter.keepsLineBreaks = wraps + guard wraps != wrapState.isOn else { return false } + wrapState.isOn = wraps + wrapState.geometry = nil + wrapState.measured = nil + wrapState.deferredRows = [] + display.lineCounts.removeAll() + answersRowHeights = wraps + container.anchorsRowsWhenSyncing = wraps + for pane in panes { + pane.tableView.delegate = nil + pane.tableView.delegate = self + } + return true + } + + // The toggle: a reload is the only way the tables take or drop their row heights, so the place is kept by row. + func wrapModeDidChange() { + _ = commitCellEditing() + let table = main.tableView + var anchor: (rowID: RowID, fraction: CGFloat)? + if let sample = viewportSample(), let rowID = model.rowID(at: sample.row) { + anchor = (rowID, sample.offset / max(table.rect(ofRow: sample.row).height, 1)) + } + applyTableSettings() + applyWrapMode() + reloadAll() + guard let anchor, let row = model.displayIndex(of: anchor.rowID), row < table.numberOfRows else { + measureViewportRows() + return + } + measureRows(row..<(row + 1), noting: true) + let rect = table.rect(ofRow: row) + scrollViewportTop(to: rect.minY + anchor.fraction * rect.height) + measureViewportRows() + } + + @objc func toggleWrapText(_ sender: Any?) { + model.setWrapsText(!model.wrapsText) + } + + // MARK: - Geometry + + private func makeWrapGeometry() -> DataGridWrapGeometry { + let table = main.tableView + let fonts = ThemeEngine.shared.dataGridFonts + let configuration = model.configuration + let columns = model.columns + var measured: [DataGridWrapGeometry.Column] = [] + measured.reserveCapacity(columns.count) + for (position, column) in columns.columns.enumerated() { + guard let index = main.tableIndex(forDisplayPosition: position, columns: columns), + index < table.numberOfColumns else { continue } + measured.append(DataGridWrapGeometry.Column( + dataIndex: column.dataIndex, + type: column.type, + width: table.rect(ofColumn: index).width, + kind: presenter.presentation(forDataIndex: column.dataIndex).kind + )) + } + return DataGridWrapGeometry( + columns: measured, + regular: DataGridWrapLayout.Face(fonts.regular), + medium: DataGridWrapLayout.Face(fonts.medium), + marksInvisibles: presenter.registry.showsInvisibleCharacters, + isEditable: configuration.isEditable, + marksEmptyText: configuration.marksEmptyText, + rowHeight: table.rowHeight, + lineHeight: DataGridMetrics.lineHeight(of: fonts.regular) + ) + } + + // Cheap to ask after anything that can move a width, a font or what a cell draws: nothing happens unless one did. + @discardableResult + func syncWrapGeometry(retiles: Bool = true) -> Bool { + guard wrapState.isOn else { return false } + let geometry = makeWrapGeometry() + guard geometry != wrapState.geometry else { return false } + wrapState.geometry = geometry + model.display.lineCounts.removeAll() + if retiles { + noteAllRowHeights() + } + return true + } + + // MARK: - Measuring + + // The rows AppKit shows or holds ready take their real height before they draw. A row first measured as it + // enters is measured here, on the main actor: the prewarm is paused for the whole of a live scroll. + func measureViewportRows() { + guard wrapState.isOn, !wrapState.isMeasuring else { return } + wrapState.isMeasuring = true + defer { wrapState.isMeasuring = false } + // A row that grows pushes others out and one that was estimated tall lets others in, so the range is read again. + for _ in 0..<4 { + let rows = viewportRows() + let generation = model.display.lineCounts.generation + if let measured = wrapState.measured, measured.generation == generation, + measured.rows.lowerBound <= rows.lowerBound, measured.rows.upperBound >= rows.upperBound { + return + } + let grown = measureRows(rows, noting: false) + wrapState.measured = (rows, model.display.lineCounts.generation) + guard !grown.isEmpty else { return } + noteRowHeights(grown) + } + } + + private func viewportRows() -> Range { + let table = main.tableView + let count = table.numberOfRows + guard count > 0 else { return 0..<0 } + let rows = table.rows(in: table.visibleRect.union(table.preparedContentRect)) + let lower = min(max(rows.location, 0), count) + return lower.., noting: Bool) -> IndexSet { + var grown = IndexSet() + guard wrapState.isOn, !range.isEmpty else { return grown } + if wrapState.geometry == nil { + syncWrapGeometry(retiles: false) + } + guard let geometry = wrapState.geometry, let measure = presenter.makeWrapMeasure(geometry) else { return grown } + let lineCounts = model.display.lineCounts + let order = model.order + for index in range { + guard let row = order.row(at: index, in: measure.rows), lineCounts[row.id] == nil else { continue } + let lines = presenter.wrapLineCount(of: row, measure: measure) + lineCounts[row.id] = lines + if lines > 1 { + grown.insert(index) + } + } + if noting, !grown.isEmpty { + noteRowHeights(grown) + } + return grown + } + + func rowHeight(forRow row: Int, in tableView: NSTableView) -> CGFloat { + let lines = model.rowID(at: row).flatMap { model.display.lineCounts[$0] } ?? 1 + return DataGridMetrics.wrappedRowHeight(lines: lines, rowHeight: tableView.rowHeight, lineHeight: wrapLineHeight) + } + + // MARK: - Noting heights + + func noteAllRowHeights() { + let count = main.tableView.numberOfRows + guard wrapState.isOn, count > 0 else { return } + noteRowHeights(IndexSet(integersIn: 0.. Void) { + let table = main.tableView + guard table.numberOfRows > 0 else { + change() + return + } + var visible = table.visibleRect + visible.origin.y += headerInset + visible.size.height = max(0, visible.height - headerInset) + let shown = table.rows(in: visible) + guard shown.length > 0, shown.location >= 0, shown.location < table.numberOfRows else { + change() + return + } + let anchor = shown.location + let before = table.rect(ofRow: anchor) + let offset = visible.minY - before.minY + change() + guard anchor < table.numberOfRows else { return } + let after = table.rect(ofRow: anchor) + let kept = offset * after.height / max(before.height, 1) + let top = after.minY + kept + guard abs(top - visible.minY) > 0.01 else { return } + scrollViewportTop(to: top) + } + + // Past a few hundred rows AppKit places rows on fractions of a point and the clip view snaps to a pixel, so the + // top is rounded into the row it belongs to: rounded down, the row above would be the first one shown. + private func scrollViewportTop(to top: CGFloat) { + let scale = main.tableView.window?.backingScaleFactor ?? 1 + let snapped = (top * scale).rounded(.up) / scale + let x = main.scrollView.contentView.bounds.origin.x + main.tableView.scroll(NSPoint(x: x, y: snapped - headerInset)) + } + + // MARK: - Changes + + func wrapDidApply(_ change: DataGridChange) { + guard wrapState.isOn else { return } + wrapState.measured = nil + switch change { + case .reload, .rowsInserted, .rowsRemoved: + measureViewportRows() + case .columnsChanged, .columnMetadataChanged: + if !syncWrapGeometry() { + measureViewportRows() + } + case .rowsUpdated(let rows, _): + // The model dropped these rows' text and counts, so the tables hold heights nothing answers any more. + noteRowHeights(rows) + case .allRowsRepainted: + break + } + } +} diff --git a/apple/TablePro/Views/DataGrid/DataGridViewController.swift b/apple/TablePro/Views/DataGrid/DataGridViewController.swift index ca5e3adf27..1a7f3ac4d9 100644 --- a/apple/TablePro/Views/DataGrid/DataGridViewController.swift +++ b/apple/TablePro/Views/DataGrid/DataGridViewController.swift @@ -14,6 +14,9 @@ final class DataGridViewController: NSViewController, DataGridMountedView { let container = DataGridContainerView() let editingState = DataGridEditingState() let menuState = DataGridMenuState() + let wrapState = DataGridWrapState() + // Read by responds(to:), which AppKit may ask from outside the main actor's checking; written on the main actor only. + nonisolated(unsafe) var answersRowHeights = false private(set) lazy var selectionSummaryTracker = SelectionSummaryTracker( inputProvider: { [weak self] in self?.selectionSummaryInput() } @@ -65,6 +68,14 @@ final class DataGridViewController: NSViewController, DataGridMountedView { var panes: [DataGridPane] { container.panes } var gridHasFocus: Bool { container.gridHasFocus } + // A table that is not wrapping never sees heightOfRow, so it stays the fixed-pitch table it has always been. + override func responds(to aSelector: Selector!) -> Bool { + if aSelector == #selector(NSTableViewDelegate.tableView(_:heightOfRow:)) { + return answersRowHeights + } + return super.responds(to: aSelector) + } + // MARK: - Lifecycle override func loadView() { @@ -94,6 +105,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { observeTheme() observeFind() applyTableSettings() + applyWrapMode() reloadAll() needsViewportRestore = model.store.viewportAnchor != nil // Attaching publishes the summary state, which SwiftUI refuses inside the update that made this view. @@ -117,6 +129,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { knownWidthsSawRows = false savedWidthIDs = [] pendingPageReveal = nil + wrapState.geometry = nil mount() } @@ -163,6 +176,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { applyStagedViewport() } updateFittingHeight() + measureViewportRows() scheduleAccessibilityRemount() if pendingPageReveal != nil { // The page scrolls once its own layout is done, so its document already holds the grid's new height. @@ -285,6 +299,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { applyRowNumberWidth() refreshHeaders() redrawVisibleRows() + syncWrapGeometry() } private func dataGridSettingsDidChange() { @@ -308,6 +323,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { } else if previous.showInvisibleCharacters != settings.showInvisibleCharacters { redrawVisibleRows() } + syncWrapGeometry() } private func valueColorSettingsDidChange() { @@ -321,6 +337,7 @@ final class DataGridViewController: NSViewController, DataGridMountedView { func reformatText() { model.display.cache.removeAll() redrawVisibleRows() + noteAllRowHeights() startBackgroundPrewarm() } diff --git a/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift b/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift index 62f30a5670..42f71de486 100644 --- a/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift +++ b/apple/TablePro/Views/DataGrid/Editing/DataGridEditingCellView.swift @@ -15,6 +15,13 @@ final class DataGridEditingCellView: NSTableCellView { let field = DataGridEditingTextField(frame: .zero) private var scope: ThemeScope = .live + // Set while the grid wraps: the field then sits on the row's first line, where the value's text starts. + var firstLineHeight: CGFloat? { + didSet { + guard firstLineHeight != oldValue else { return } + needsLayout = true + } + } override init(frame frameRect: NSRect) { super.init(frame: frameRect) @@ -50,10 +57,11 @@ final class DataGridEditingCellView: NSTableCellView { func layoutField() { let inset = Self.borderWidth let lineHeight = field.font.map { ($0.ascender - $0.descender + $0.leading).rounded(.up) } ?? bounds.height - let height = min(lineHeight + 2, max(0, bounds.height - 2 * inset)) + let band = firstLineHeight.map { min($0, bounds.height) } ?? bounds.height + let height = min(lineHeight + 2, max(0, band - 2 * inset)) let frame = NSRect( x: inset, - y: ((bounds.height - height) / 2).rounded(), + y: ((band - height) / 2).rounded(), width: max(0, bounds.width - 2 * inset), height: height ) diff --git a/apple/TablePro/Views/DataGrid/Editing/DataGridViewController+FieldEditing.swift b/apple/TablePro/Views/DataGrid/Editing/DataGridViewController+FieldEditing.swift index b5363f8f42..2ed8134b15 100644 --- a/apple/TablePro/Views/DataGrid/Editing/DataGridViewController+FieldEditing.swift +++ b/apple/TablePro/Views/DataGrid/Editing/DataGridViewController+FieldEditing.swift @@ -35,6 +35,7 @@ extension DataGridViewController { cell: cell.coord ) let cellView = state.editingCellView + cellView.firstLineHeight = wrapsText ? table.rowHeight : nil cellView.prepare( text: text, font: ThemeEngine.shared.dataGridFonts.regular, @@ -77,6 +78,7 @@ extension DataGridViewController { unmountEditingCell() restoreGridFocus() let committed = commit ? commitText(text, for: session) : true + noteDeferredRowHeights() model.editingDidEnd() if let movement, committed { continueEditing(from: session.target, movement) @@ -175,6 +177,7 @@ extension DataGridViewController { DispatchQueue.main.async { [weak self] in guard let self, self.editingState.session?.editor != .field else { return } self.unmountEditingCell() + self.noteDeferredRowHeights() } if state.isApplyingChange { state.deferredCommit = (session, text) diff --git a/apple/TablePro/Views/Main/Child/QueryTabGridStateStore.swift b/apple/TablePro/Views/Main/Child/QueryTabGridStateStore.swift index 7bedc57c19..02bd556c04 100644 --- a/apple/TablePro/Views/Main/Child/QueryTabGridStateStore.swift +++ b/apple/TablePro/Views/Main/Child/QueryTabGridStateStore.swift @@ -170,6 +170,17 @@ final class QueryTabGridStateStore: DataGridStateStore { } } + // MARK: - Wrap + + var wrapsText: Bool { + get { tab?.wrapsText ?? false } + set { + guard let coordinator, tab?.wrapsText != newValue else { return } + coordinator.tabManager.mutate(tabId: tabId) { $0.wrapsText = newValue } + coordinator.persistence.saveAggregated() + } + } + // MARK: - Viewport var viewportAnchor: GridViewportPlacement? { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index 80fd994766..fc2e9bfb07 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -190,7 +190,7 @@ extension MainContentCoordinator { private func gridCommands(for tab: QueryTab, isSelected: Bool, isEditable: Bool) -> Set { var commands: Set = [ .hideColumns, .showRowsAsJSON, .exportResults, .shareResult, .navigateForeignKey, - .highlightValues, .displayAs, .freezeColumns, .valueFilter + .highlightValues, .displayAs, .freezeColumns, .valueFilter, .wrapText ] let operations = isEditable ? (activeViewWriteTarget?.operations ?? .all) : [] if operations.contains(.insert) { @@ -210,6 +210,28 @@ extension MainContentCoordinator { return commands } + // MARK: - Wrap + + private var wrappableGridModel: DataGridModel? { + guard hasMountedDataGrid, let tab = tabManager.selectedTab, tab.display.resultsViewMode == .data, + let model = existingGridModel(forTab: tab.id), + model.configuration.commands.contains(.wrapText) else { return nil } + return model + } + + var canToggleWrapText: Bool { + wrappableGridModel != nil + } + + var wrapsGridText: Bool { + wrappableGridModel?.wrapsText ?? false + } + + func toggleWrapText() { + guard let model = wrappableGridModel else { return } + model.setWrapsText(!model.wrapsText) + } + // MARK: - Display caches var currentDisplayInputs: DataTabDisplayInputs { diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index 32748ff92b..a603cb4978 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -802,6 +802,19 @@ final class MainContentCommandActions: ObservableObject { coordinator.presentHighlightRules() } + var canToggleWrapText: Bool { + coordinator?.canToggleWrapText ?? false + } + + var wrapsGridText: Bool { + coordinator?.wrapsGridText ?? false + } + + func toggleWrapText() { + guard canToggleWrapText, let coordinator else { return } + coordinator.toggleWrapText() + } + func showFindBar(replace: Bool = false) { guard canUseGridFindCommands else { return } coordinator?.findCoordinator.showFind(replace: replace) diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 9b3c11ec12..d350bb320b 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -39,6 +39,8 @@ struct DataGridSection: View { Toggle("Smart value detection", isOn: $settings.enableSmartValueDetection) Toggle("Show invisible characters", isOn: $settings.showInvisibleCharacters) .help(String(localized: "Mark zero-width, control and special space characters in cells and value fields")) + Toggle("Wrap text in cells", isOn: $settings.wrapText) + .help(String(localized: "Long values wrap onto up to 10 lines. Applies to new tabs; View > Wrap Text changes the open grid.")) Toggle("Color values by type", isOn: $valueColors.colorsValuesByType) .help(String(localized: "Draw strings, numbers, dates and other typed values in the colors of the theme's Values section")) .accessibilityIdentifier("color-values-by-type-toggle") diff --git a/apple/TablePro/Views/Structure/StructureGridStateStore.swift b/apple/TablePro/Views/Structure/StructureGridStateStore.swift index 2a07bf9734..7f1cd49766 100644 --- a/apple/TablePro/Views/Structure/StructureGridStateStore.swift +++ b/apple/TablePro/Views/Structure/StructureGridStateStore.swift @@ -18,6 +18,7 @@ final class StructureGridStateStore: DataGridStateStore { var displayFormats: [ValueDisplayFormat?] = [] var selectionSnapshot = GridSelectionSnapshot.empty var viewportAnchor: GridViewportPlacement? + var wrapsText = false let layoutScope: DataGridLayoutScope = .ephemeral var columnLayout: ColumnLayoutState { diff --git a/apple/TableProTests/Core/Menu/MainMenuBuilderTests.swift b/apple/TableProTests/Core/Menu/MainMenuBuilderTests.swift index f1f26bdb2c..80af032d03 100644 --- a/apple/TableProTests/Core/Menu/MainMenuBuilderTests.swift +++ b/apple/TableProTests/Core/Menu/MainMenuBuilderTests.swift @@ -754,6 +754,20 @@ struct MainMenuValidationTests { #expect(!enabled(#selector(MainSplitViewController.showHighlightRules(_:)), context)) } + @Test("Wrap Text needs a connected data grid that offers it") + func wrapTextNeedsDataGrid() { + var context = MenuValidationContext() + context.canToggleWrapText = true + #expect(!enabled(#selector(MainSplitViewController.toggleWrapText(_:)), context)) + context.isConnected = true + #expect(enabled(#selector(MainSplitViewController.toggleWrapText(_:)), context)) + context.isAgentMode = true + #expect(!enabled(#selector(MainSplitViewController.toggleWrapText(_:)), context)) + context.isAgentMode = false + context.canToggleWrapText = false + #expect(!enabled(#selector(MainSplitViewController.toggleWrapText(_:)), context)) + } + @Test("Capability flags gate driver-specific commands") func capabilitiesGateCommands() { var context = MenuValidationContext() diff --git a/apple/TableProTests/Core/Services/CellDisplayFormatterTests.swift b/apple/TableProTests/Core/Services/CellDisplayFormatterTests.swift index 6ed90efebf..d99e86837f 100644 --- a/apple/TableProTests/Core/Services/CellDisplayFormatterTests.swift +++ b/apple/TableProTests/Core/Services/CellDisplayFormatterTests.swift @@ -165,6 +165,32 @@ struct CellDisplayFormatterTests { #expect(result == "line1 line2\rline3 line4") } + @Test("a grid that wraps asks for the line breaks, each as one LF, and still caps the value") + func keepsLineBreaksOnRequest() throws { + let kept = CellDisplayFormatter.display( + .text("line1\nline2\rline3\r\nline4\n"), + columnType: nil, + displayFormat: nil, + databaseType: nil, + keepsLineBreaks: true + ) + #expect(kept.text == "line1\nline2\nline3\nline4") + + let flattened = CellDisplayFormatter.display(.text("a\nb"), columnType: nil, displayFormat: nil, databaseType: nil) + #expect(flattened.text == "a b") + + let long = String(repeating: "a\n", count: CellDisplayFormatter.maxDisplayLength) + let capped = try #require(CellDisplayFormatter.display( + .text(long), + columnType: nil, + displayFormat: nil, + databaseType: nil, + keepsLineBreaks: true + ).text) + #expect((capped as NSString).length == CellDisplayFormatter.maxDisplayLength + 1) + #expect(capped.hasSuffix("…")) + } + @Test("text over max length is truncated") func longTextTruncated() { let longString = String(repeating: "a", count: CellDisplayFormatter.maxDisplayLength + 100) diff --git a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift index 376b3de0e2..6fd5e1553f 100644 --- a/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift +++ b/apple/TableProTests/Core/Services/PersistedTabRoundTripTests.swift @@ -41,6 +41,24 @@ struct PersistedTabRoundTripTests { #expect(restored.pendingRestoredSort?[1].direction == .ascending) } + @Test("Wrap Text round-trips with the tab, and a tab saved before it takes the setting it is restored under") + func wrapsTextRoundTrip() throws { + var tab = tableTab() + tab.wrapsText = true + let persisted = tab.toPersistedTab() + #expect(persisted.wrapsText == true) + let decoded = try JSONDecoder().decode(PersistedTab.self, from: JSONEncoder().encode(persisted)) + #expect(QueryTab(from: decoded, defaultPageSize: 1_000).wrapsText) + + tab.wrapsText = false + #expect(!QueryTab(from: tab.toPersistedTab(), defaultPageSize: 1_000, defaultWrapsText: true).wrapsText) + + let legacy = PersistedTab(id: UUID(), title: "Users", query: "SELECT 1", tabType: .table, tableName: "users") + #expect(legacy.wrapsText == nil) + #expect(QueryTab(from: legacy, defaultPageSize: 1_000, defaultWrapsText: true).wrapsText) + #expect(!QueryTab(from: legacy, defaultPageSize: 1_000).wrapsText) + } + @Test("Sort columns without a resolved name are dropped from persistence") func sortColumnsWithoutNameAreDropped() { var tab = tableTab() diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 6e8110f87e..d8ebaadf97 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -66,6 +66,20 @@ struct SettingsFieldDecodingTests { #expect(decoded.rowCopyFormat == .csvWithHeaders) } + @Test("Data Grid settings saved before Wrap text in cells leave it off, and a choice round-trips") + func wrapTextDefaultsToOff() throws { + let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) + #expect(legacy.wrapText == false) + #expect(DataGridSettings.default.wrapText == false) + + var chosen = DataGridSettings.default + chosen.wrapText = true + let decoded = try decode(DataGridSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.wrapText) + + #expect(try decode(DataGridSettings.self, #"{"wrapText":"yes"}"#).wrapText == false) + } + @Test("Data Grid settings saved before results kept per run keep every result, and a choice round-trips") func resultSetsKeptPerRunDefaultsToNoLimit() throws { let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) diff --git a/apple/TableProTests/Views/DataGrid/DataGridCellTextTests.swift b/apple/TableProTests/Views/DataGrid/DataGridCellTextTests.swift index 2da127284e..de6c801d51 100644 --- a/apple/TableProTests/Views/DataGrid/DataGridCellTextTests.swift +++ b/apple/TableProTests/Views/DataGrid/DataGridCellTextTests.swift @@ -34,6 +34,18 @@ struct DataGridCellTextTests { #expect(text.sanitizedForCellDisplay == flattened(text, keepingLoneCarriageReturns: false)) } + @Test( + "A wrapping cell keeps each break as one LF and drops one that ends the value", + arguments: [ + ("plain", "plain"), ("a\nb", "a\nb"), ("a\r\nb", "a\nb"), ("a\rb", "a\nb"), ("a\u{0B}b\u{0C}c", "a\nb\nc"), + ("a\u{85}b", "a\nb"), ("a\u{2028}b\u{2029}c", "a\nb\nc"), ("a\n", "a"), ("a\r\n", "a"), ("a\n\n", "a\n"), + ("\n", ""), ("a\r\n\r\nb", "a\n\nb"), ("Việt\u{2028}Nam\r", "Việt\nNam"), ("", ""), + ] + ) + func wrappingKeepsLineBreaks(text: String, expected: String) { + #expect(text.keepingLineBreaksForCell == expected) + } + @Test("A value with no break comes back as it was") func unbrokenTextIsUnchanged() { let text = String(repeating: "Tiếng Việt ", count: 1_000) diff --git a/apple/TableProTests/Views/DataGrid/DataGridWordWrapTests.swift b/apple/TableProTests/Views/DataGrid/DataGridWordWrapTests.swift new file mode 100644 index 0000000000..e9d6636a79 --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataGridWordWrapTests.swift @@ -0,0 +1,301 @@ +// +// DataGridWordWrapTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +@MainActor +private let heightOfRow = #selector(NSTableViewDelegate.tableView(_:heightOfRow:)) + +@MainActor +private func wrapRows(_ count: Int, long: Set, text: String = String(repeating: "word ", count: 30)) -> TableRows { + TableRows.from( + queryRows: (0.. InMemoryDataGridStateStore { + let store = InMemoryDataGridStateStore(columnLayout: ColumnLayoutState(columnWidths: ["id": 60, "note": 160])) + store.wrapsText = wraps + return store +} + +@MainActor +private func wrapConfiguration(isEditable: Bool = false) -> DataGridConfiguration { + var configuration = DataGridConfiguration() + configuration.commands = [.wrapText] + configuration.isEditable = isEditable + return configuration +} + +@MainActor +private func wrapGrid(_ rows: TableRows, wraps: Bool = true) -> HostedDataGrid { + HostedDataGrid(rows: rows, configuration: wrapConfiguration(), store: wrapStore(wraps: wraps)) +} + +extension GlobalStateSuites { + @Suite(.appSettings { + $0.typography = TypographySettings(editorFontSize: 13, dataGridFontSize: 13) + $0.dataGrid.rowHeight = .normal + $0.dataGrid.showInvisibleCharacters = false + }) + @MainActor + struct DataGridWordWrapTests { + private func lineHeight() -> CGFloat { + DataGridMetrics.lineHeight(of: ThemeEngine.shared.dataGridFonts.regular) + } + + @Test("A grid that does not wrap answers no row heights and keeps the fixed pitch") + func wrapOffIsTheFixedPitchTable() { + let grid = wrapGrid(wrapRows(5, long: [1]), wraps: false) + defer { grid.close() } + + #expect(!grid.controller.responds(to: heightOfRow)) + #expect(!grid.controller.wrapsText) + #expect(grid.main.rect(ofRow: 1).height == grid.main.rowHeight) + #expect(grid.model.display.lineCounts.isEmpty) + } + + @Test("A grid whose store wraps but that does not offer the command stays fixed pitch") + func wrapNeedsTheCommand() { + let grid = HostedDataGrid(rows: wrapRows(5, long: [1]), store: wrapStore(wraps: true)) + defer { grid.close() } + + #expect(!grid.model.wrapsText) + #expect(!grid.controller.responds(to: heightOfRow)) + grid.model.setWrapsText(false) + #expect(grid.main.rect(ofRow: 1).height == grid.main.rowHeight) + } + + @Test("A long value makes its row taller in both panes, and a short row keeps the one-line height") + func longRowGrowsInBothPanes() throws { + let grid = wrapGrid(wrapRows(5, long: [1])) + defer { grid.close() } + + #expect(grid.controller.responds(to: heightOfRow)) + let lines = try #require(grid.model.display.lineCounts[.existing(1)]) + #expect(lines > 1) + let expected = DataGridMetrics.wrappedRowHeight(lines: lines, rowHeight: grid.main.rowHeight, lineHeight: lineHeight()) + #expect(grid.main.rect(ofRow: 1).height == expected) + #expect(grid.frozen.rect(ofRow: 1).height == expected) + #expect(grid.main.rect(ofRow: 0).height == grid.main.rowHeight) + #expect(grid.main.rect(ofRow: 2).minY == grid.frozen.rect(ofRow: 2).minY) + } + + @Test("A row stops growing at ten lines") + func rowIsCappedAtTenLines() { + let grid = wrapGrid(wrapRows(3, long: [1], text: String(repeating: "word ", count: 600))) + defer { grid.close() } + + #expect(grid.model.display.lineCounts[.existing(1)] == DataGridWrapLayout.maximumLines) + #expect(grid.main.rect(ofRow: 1).height == grid.main.rowHeight + 9 * lineHeight()) + } + + @Test("A line break in the value is a line of the row") + func lineBreaksAddLines() { + let grid = wrapGrid(wrapRows(3, long: [1], text: "a\r\nb\u{2028}c")) + defer { grid.close() } + + #expect(grid.model.display.lineCounts[.existing(1)] == 3) + } + + @Test("Widening the column shortens the row once the resize lands") + func resizeMeasuresTheRowsAgain() throws { + let grid = wrapGrid(wrapRows(5, long: [1])) + defer { grid.close() } + let before = grid.main.rect(ofRow: 1).height + let column = try #require(grid.tableColumn(named: "note")) + + column.width = 900 + grid.controller.columnDidResize(column, in: grid.controller.main) + grid.layout() + + let after = grid.main.rect(ofRow: 1).height + #expect(after < before) + #expect(after > grid.main.rowHeight) + #expect(grid.frozen.rect(ofRow: 1).height == after) + } + + @Test("Turning wrap on and off keeps the first visible row and swaps the height path") + func toggleKeepsTheFirstVisibleRow() throws { + let rows = wrapRows(2_000, long: Set(stride(from: 0, to: 2_000, by: 3))) + let grid = wrapGrid(rows, wraps: false) + defer { grid.close() } + let table = grid.main + table.scroll(NSPoint(x: 0, y: table.rect(ofRow: 1_000).minY - grid.controller.headerInset)) + let before = try #require(grid.controller.viewportSample()) + try #require(before.row > 900) + + grid.model.setWrapsText(true) + grid.layout() + + #expect(grid.controller.responds(to: heightOfRow)) + #expect(grid.controller.viewportSample()?.row == before.row) + #expect(table.rect(ofRow: 1_002).height > table.rowHeight) + + grid.model.setWrapsText(false) + grid.layout() + + #expect(!grid.controller.responds(to: heightOfRow)) + #expect(grid.controller.viewportSample()?.row == before.row) + #expect(table.rect(ofRow: 1_002).height == table.rowHeight) + #expect(grid.model.display.lineCounts.isEmpty) + } + + @Test("A row scrolled to past the prewarm window is measured as it arrives, with the prewarm paused") + func rowEnteringTheViewportIsMeasured() { + let grid = wrapGrid(wrapRows(3_000, long: [2_000])) + defer { grid.close() } + grid.controller.pausePrewarm() + #expect(grid.model.display.lineCounts[.existing(2_000)] == nil) + + let table = grid.main + table.scroll(NSPoint(x: 0, y: table.rect(ofRow: 2_000).minY - grid.controller.headerInset)) + + #expect(grid.model.display.lineCounts[.existing(2_000)] != nil) + #expect(table.rect(ofRow: 2_000).height > table.rowHeight) + #expect(grid.frozen.rect(ofRow: 2_000).height == table.rect(ofRow: 2_000).height) + } + + @Test("The frozen pane shows the main pane's first row after a jump, whatever the rows above measure") + func frozenPaneFollowsByRow() throws { + let grid = wrapGrid(wrapRows(3_000, long: Set(stride(from: 0, to: 3_000, by: 2)))) + defer { grid.close() } + let table = grid.main + table.scroll(NSPoint(x: 0, y: table.rect(ofRow: 1_500).minY - grid.controller.headerInset)) + grid.layout() + + let sample = try #require(grid.controller.viewportSample()) + let frozen = grid.frozen + let inset = grid.frozenScrollView.contentView.contentInsets.top + let frozenTop = grid.frozenScrollView.contentView.bounds.minY + inset + let offset = frozenTop - frozen.rect(ofRow: sample.row).minY + #expect(abs(offset - sample.offset) <= 1) + } + + @Test("A value that gets shorter gives its row the one-line height back") + func updatedRowIsMeasuredAgain() { + let grid = wrapGrid(wrapRows(5, long: [1])) + defer { grid.close() } + #expect(grid.main.rect(ofRow: 1).height > grid.main.rowHeight) + + _ = grid.owner.tableRows.edit(row: 1, column: 1, value: .text("x")) + grid.model.apply(.cellChanged(row: 1, column: 1)) + grid.layout() + + #expect(grid.main.rect(ofRow: 1).height == grid.main.rowHeight) + #expect(grid.frozen.rect(ofRow: 1).height == grid.main.rowHeight) + } + + @Test("The first visible row stays at the top of the viewport when its own height changes") + func firstVisibleRowKeepsItsTopWhenItChanges() throws { + let grid = wrapGrid(wrapRows(400, long: [201])) + defer { grid.close() } + let table = grid.main + table.scroll(NSPoint(x: 0, y: table.rect(ofRow: 200).minY - grid.controller.headerInset)) + grid.layout() + let before = try #require(grid.controller.viewportSample()) + try #require(before.row == 200) + + _ = grid.owner.tableRows.edit(row: 200, column: 1, value: .text(String(repeating: "word ", count: 30))) + grid.model.apply(.cellChanged(row: 200, column: 1)) + grid.layout() + + #expect(table.rect(ofRow: 200).height > table.rowHeight) + var sample = try #require(grid.controller.viewportSample()) + #expect(sample.row == 200) + #expect(abs(sample.offset - before.offset) <= 1) + + _ = grid.owner.tableRows.edit(row: 200, column: 1, value: .text("x")) + grid.model.apply(.cellChanged(row: 200, column: 1)) + grid.layout() + + #expect(table.rect(ofRow: 200).height == table.rowHeight) + sample = try #require(grid.controller.viewportSample()) + #expect(sample.row == 200) + #expect(abs(sample.offset - before.offset) <= 1) + } + + @Test("The edit field of a cell in a tall row sits on the row's first line") + func editFieldSitsOnTheFirstLine() throws { + let grid = EditingGrid( + rows: wrapRows(3, long: [1]), + configuration: wrapConfiguration(isEditable: true), + store: wrapStore(wraps: true) + ) + defer { grid.tearDown() } + let table = grid.controller.main.tableView + try #require(table.rect(ofRow: 1).height > table.rowHeight) + + #expect(grid.controller.beginEditingCell(row: 1, displayColumn: 0)) + + #expect(grid.cellView.bounds.height == table.rect(ofRow: 1).height) + #expect(grid.cellView.field.frame.maxY <= table.rowHeight) + #expect(grid.cellView.field.frame.minY >= 0) + } + + @Test("An accessibility stand-in in a tall row is as tall as the row") + func standInCoversTheTallRow() async throws { + let wasActive = DataGridAccessibility.isActive + DataGridAccessibility.isActive = true + defer { DataGridAccessibility.isActive = wasActive } + let grid = wrapGrid(wrapRows(5, long: [1])) + defer { grid.close() } + let index = try #require(grid.tableIndex(ofDisplayPosition: 1)) + + grid.controller.remountAccessibilityCells() + try await waitUntil { grid.main.view(atColumn: index, row: 1, makeIfNecessary: false) is DataGridAccessibilityCellView } + + grid.layout() + let standIn = try #require(grid.main.view(atColumn: index, row: 1, makeIfNecessary: false)) + #expect(standIn.frame.height == grid.main.rect(ofRow: 1).height) + } + + @Test("The header menu offers Wrap Text with a checkmark, only on a grid that offers the command") + func headerMenuOffersWrapText() throws { + let grid = wrapGrid(wrapRows(3, long: [1])) + defer { grid.close() } + let column = try #require(grid.model.columns.column(at: 1)) + let action = #selector(DataGridViewController.toggleWrapText(_:)) + + let item = try #require(grid.controller.headerMenu(for: column)?.items.first { $0.action == action }) + #expect(item.title == String(localized: "Wrap Text")) + #expect(item.state == .on) + #expect(grid.controller.validateMenuItem(item)) + + grid.controller.toggleWrapText(item) + #expect(!grid.model.wrapsText) + let off = try #require(grid.controller.headerMenu(for: column)?.items.first { $0.action == action }) + #expect(off.state == .off) + + let plain = HostedDataGrid(rows: wrapRows(3, long: [1])) + defer { plain.close() } + let plainColumn = try #require(plain.model.columns.column(at: 1)) + let offersIt = plain.controller.headerMenu(for: plainColumn)?.items.contains { $0.action == action } ?? false + #expect(!offersIt) + } + + @Test("The View menu's item is checked by the focused grid, and dimmed by a grid that does not wrap") + func viewMenuItemIsValidatedByTheGrid() { + let grid = wrapGrid(wrapRows(3, long: [1])) + defer { grid.close() } + let item = NSMenuItem(title: "", action: #selector(DataGridViewController.toggleWrapText(_:)), keyEquivalent: "") + + #expect(grid.controller.validateMenuItem(item)) + #expect(item.state == .on) + + let plain = HostedDataGrid(rows: wrapRows(3, long: [1])) + defer { plain.close() } + #expect(!plain.controller.validateMenuItem(item)) + #expect(item.state == .off) + } + } +} diff --git a/apple/TableProTests/Views/DataGrid/DataGridWrapLayoutTests.swift b/apple/TableProTests/Views/DataGrid/DataGridWrapLayoutTests.swift new file mode 100644 index 0000000000..50702655b6 --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataGridWrapLayoutTests.swift @@ -0,0 +1,143 @@ +// +// DataGridWrapLayoutTests.swift +// TableProTests +// + +import AppKit +import CoreText +@testable import TablePro +import Testing + +@MainActor +struct DataGridWrapLayoutTests { + private let font = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) + private var face: DataGridWrapLayout.Face { DataGridWrapLayout.Face(font) } + private var advance: CGFloat { face.widestASCIIAdvance } + private var attributes: [NSAttributedString.Key: Any] { [.font: font, .foregroundColor: NSColor.black] } + + private func lines(_ text: String, width: CGFloat) -> [DataGridWrapLayout.Line] { + let cut = DataGridWrapLayout.bounded(text, width: width, pointSize: font.pointSize) + return DataGridWrapLayout.lines( + of: NSAttributedString(string: cut.text, attributes: attributes), + width: width, + endsCut: cut.isCut, + ellipsisAttributes: attributes + ) + } + + private func lineWidth(of line: CTLine) -> CGFloat { + CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) + } + + private func isTruncated(_ line: DataGridWrapLayout.Line) -> Bool { + line.line !== line.source + } + + @Test("The cap is ten lines") + func capIsTenLines() { + #expect(DataGridWrapLayout.maximumLines == 10) + } + + @Test("A value that fits its column is one line, and so is an empty one") + func shortTextIsOneLine() { + #expect(DataGridWrapLayout.lineCount(of: "abc", width: 200, face: face) == 1) + #expect(DataGridWrapLayout.lineCount(of: "", width: 200, face: face) == 1) + #expect(lines("abc", width: 200).count == 1) + } + + @Test("A long value wraps onto as many lines as its words need, and the draw agrees with the count") + func longTextWraps() { + let text = Array(repeating: "word", count: 12).joined(separator: " ") + let width = advance * 15 + let count = DataGridWrapLayout.lineCount(of: text, width: width, face: face) + #expect(count == 4) + let drawn = lines(text, width: width) + #expect(drawn.count == count) + #expect(drawn.allSatisfy { lineWidth(of: $0.line) <= width + 0.5 }) + } + + @Test("A line break in the value breaks the line, and an empty line counts") + func hardBreaksBreak() { + #expect(DataGridWrapLayout.lineCount(of: "a\nb", width: 400, face: face) == 2) + #expect(DataGridWrapLayout.lineCount(of: "a\n\nb", width: 400, face: face) == 3) + #expect(DataGridWrapLayout.lineCount(of: "a\n", width: 400, face: face) == 2) + #expect(lines("a\nb", width: 400).map(\.start) == [0, 2]) + } + + @Test("A value past ten lines stops at ten, and the tenth ends in an ellipsis inside the width") + func longValueIsCappedWithAnEllipsis() throws { + let text = String(repeating: "word ", count: 400) + let width = advance * 20 + #expect(DataGridWrapLayout.lineCount(of: text, width: width, face: face) == 10) + let drawn = lines(text, width: width) + #expect(drawn.count == 10) + let last = try #require(drawn.last) + #expect(isTruncated(last)) + #expect(lineWidth(of: last.line) <= width + 0.5) + #expect(drawn.dropLast().allSatisfy { !isTruncated($0) }) + } + + @Test("More than ten paragraphs show ten, the tenth followed by an ellipsis") + func manyParagraphsAreCapped() throws { + let text = (1...14).map { "p\($0)" }.joined(separator: "\n") + #expect(DataGridWrapLayout.lineCount(of: text, width: 400, face: face) == 10) + let drawn = lines(text, width: 400) + #expect(drawn.count == 10) + let last = try #require(drawn.last) + let plain = CTLineCreateWithAttributedString(NSAttributedString(string: "p10", attributes: attributes)) + #expect(lineWidth(of: last.line) > lineWidth(of: plain)) + #expect(CTLineGetStringRange(last.line).length == 4) + } + + @Test("Ten lines exactly draw whole, with no ellipsis") + func tenLinesDrawWhole() throws { + let text = (1...10).map { "p\($0)" }.joined(separator: "\n") + let drawn = lines(text, width: 400) + #expect(drawn.count == 10) + #expect(CTLineGetStringRange(try #require(drawn.last).line).length == 3) + } + + @Test("A value far longer than ten lines can show is cut before it is typeset") + func longValueIsBounded() { + let text = String(repeating: "x", count: 10_000) + let cut = DataGridWrapLayout.bounded(text, width: 150, pointSize: 13) + #expect(cut.isCut) + #expect(cut.text.utf16.count <= 10 * 58) + #expect(cut.text.utf16.count >= 10 * 32) + + let megabyte = String(repeating: "đ", count: 600_000) + #expect(DataGridWrapLayout.bounded(megabyte, width: 1_200, pointSize: 13).text.utf16.count <= 10 * 462) + } + + @Test("A value ten lines can hold is left alone, and a cut never splits a character") + func boundKeepsWholeCharacters() { + #expect(!DataGridWrapLayout.bounded("short", width: 150, pointSize: 13).isCut) + let emoji = String(repeating: "😀", count: 2_000) + let cut = DataGridWrapLayout.bounded(emoji, width: 150, pointSize: 13) + #expect(cut.isCut) + #expect(cut.text.unicodeScalars.allSatisfy { $0 == "😀" }) + } + + @Test("A column narrower than a character keeps its row one line") + func narrowColumnStaysOneLine() { + #expect(DataGridWrapLayout.lineCount(of: "some long text here", width: 4, face: face) == 1) + #expect(!DataGridWrapLayout.canWrap(width: 4, font: font)) + } + + @Test("A marked invisible character is as wide as its marker, which can add a line") + func markersTakeRoom() { + let text = String(repeating: "\u{200B}", count: 12) + let width = advance * 12 + #expect(DataGridWrapLayout.lineCount(of: text, width: width, face: face, marksInvisibles: false) == 1) + #expect(DataGridWrapLayout.lineCount(of: text, width: width, face: face, marksInvisibles: true) > 1) + #expect(DataGridWrapLayout.holdsMarkableCharacter(text)) + #expect(!DataGridWrapLayout.holdsMarkableCharacter("plain\ntext")) + } + + @Test("A wrapped row adds one line pitch per extra line to the one-line row height") + func wrappedRowHeight() { + #expect(DataGridMetrics.wrappedRowHeight(lines: 1, rowHeight: 24, lineHeight: 16) == 24) + #expect(DataGridMetrics.wrappedRowHeight(lines: 3, rowHeight: 24, lineHeight: 16) == 56) + #expect(DataGridMetrics.wrappedRowHeight(lines: 0, rowHeight: 24, lineHeight: 16) == 24) + } +} diff --git a/apple/TableProTests/Views/DataGrid/DataTabWrapTextTests.swift b/apple/TableProTests/Views/DataGrid/DataTabWrapTextTests.swift new file mode 100644 index 0000000000..04b8bafdb0 --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataTabWrapTextTests.swift @@ -0,0 +1,61 @@ +// +// DataTabWrapTextTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +extension GlobalStateSuites { + @Suite(.appSettings { $0.dataGrid.wrapText = true }) + @MainActor + struct DataTabWrapTextTests { + @Test("A new tab takes the Wrap text in cells setting, and a later change of the setting leaves it alone") + func newTabTakesTheSetting() throws { + let manager = QueryTabManager() + manager.addTab() + let first = try #require(manager.tabs.last) + #expect(first.wrapsText) + + AppSettingsManager.shared.dataGrid.wrapText = false + #expect(manager.tabs.first { $0.id == first.id }?.wrapsText == true) + + manager.addTab() + #expect(manager.tabs.last?.wrapsText == false) + } + + @Test("The data tab's store reads and writes the tab's flag") + func storeIsBackedByTheTab() throws { + let fixture = CoordinatorFixture() + var tab = QueryTab(title: "Query 1", tabType: .query) + tab.wrapsText = false + fixture.addTab(tab) + let store = QueryTabGridStateStore(tabId: tab.id, coordinator: fixture.coordinator) + #expect(!store.wrapsText) + + store.wrapsText = true + + #expect(fixture.tabManager.tabs.first { $0.id == tab.id }?.wrapsText == true) + #expect(store.wrapsText) + } + + @Test("The data tab's grid offers Wrap Text, and toggling it clears the text formatted for the other mode") + func dataTabGridOffersWrapText() throws { + let fixture = CoordinatorFixture() + var tab = QueryTab(title: "Query 1", tabType: .query) + tab.wrapsText = false + fixture.addTab(tab) + let model = fixture.coordinator.gridModel(forTab: tab.id) + #expect(model.configuration.commands.contains(.wrapText)) + model.display.cache.setBox(RowDisplayBox(["0"]), forID: .existing(0)) + + model.setWrapsText(true) + + #expect(model.wrapsText) + #expect(model.display.keepsLineBreaks) + #expect(model.display.cache.box(forID: .existing(0)) == nil) + #expect(fixture.tabManager.tabs.first { $0.id == tab.id }?.wrapsText == true) + } + } +} diff --git a/core/crates/ffi/src/results/cell_text.rs b/core/crates/ffi/src/results/cell_text.rs index a41a11e211..e0b390c4ae 100644 --- a/core/crates/ffi/src/results/cell_text.rs +++ b/core/crates/ffi/src/results/cell_text.rs @@ -39,6 +39,14 @@ pub(super) fn display(kind: ValueKind, bytes: &[u8], max_chars: usize, out: &mut } } +// As `display`, with each line break kept as one `\n`, for a grid that wraps its cells. +pub(super) fn display_lines(kind: ValueKind, bytes: &[u8], max_chars: usize, out: &mut Vec) -> bool { + match kind { + ValueKind::Bytes => push_hex(bytes, max_chars.saturating_sub(2) / 2, out), + _ => push_lines(bytes, max_chars, out), + } +} + fn push_hex(bytes: &[u8], max_bytes: usize, out: &mut Vec) -> bool { let shown = &bytes[..bytes.len().min(max_bytes)]; out.extend_from_slice(b"0x"); @@ -49,17 +57,65 @@ fn push_hex(bytes: &[u8], max_bytes: usize, out: &mut Vec) -> bool { shown.len() < bytes.len() } -// Control characters become spaces, so a line break or a tab cannot make a row taller or shift a column. +// Control characters and line breaks become spaces, so neither can make a row taller or shift a column. fn push_line(text: &[u8], max_chars: usize, out: &mut Vec) -> bool { let end = char_boundary_after(text, max_chars); - let start = out.len(); - out.extend_from_slice(&text[..end]); - for byte in &mut out[start..] { - if *byte < 0x20 || *byte == 0x7f { - *byte = b' '; + push_shown(&text[..end], false, out); + end < text.len() +} + +// A line break of any form becomes one `\n`, so no grid depends on which forms its text engine breaks at. +fn push_lines(text: &[u8], max_chars: usize, out: &mut Vec) -> bool { + let end = char_boundary_after(text, max_chars); + push_shown(&text[..end], true, out); + end < text.len() +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Shown { + Plain, + Space, + Break, +} + +// The bytes one character takes at the start of `rest`, and how a cell shows it. +fn classify(rest: &[u8]) -> (usize, Shown) { + match rest { + // LF, VT, FF and CR. + [0x0a..=0x0d, ..] => (1, Shown::Break), + [byte, ..] if *byte < 0x20 || *byte == 0x7f => (1, Shown::Space), + // NEL, U+0085. + [0xc2, 0x85, ..] => (2, Shown::Break), + // The other C1 controls, U+0080 to U+009F. + [0xc2, 0x80..=0x9f, ..] => (2, Shown::Space), + // The line and paragraph separators, U+2028 and U+2029. + [0xe2, 0x80, 0xa8 | 0xa9, ..] => (3, Shown::Break), + _ => (1, Shown::Plain), + } +} + +fn push_shown(text: &[u8], keep_breaks: bool, out: &mut Vec) { + out.reserve(text.len()); + let mut plain = 0; + let mut index = 0; + while index < text.len() { + let (length, shown) = classify(&text[index..]); + if shown == Shown::Plain { + index += length; + continue; } + out.extend_from_slice(&text[plain..index]); + // CR LF is one break; flattened, each of the two stays a space as before. + let crlf = keep_breaks && text[index..].starts_with(b"\r\n"); + out.push(if keep_breaks && shown == Shown::Break { + b'\n' + } else { + b' ' + }); + index += if crlf { 2 } else { length }; + plain = index; } - end < text.len() + out.extend_from_slice(&text[plain..]); } fn char_boundary_after(text: &[u8], chars: usize) -> usize { @@ -116,6 +172,72 @@ mod tests { assert_eq!(shown(ValueKind::Text, "👋👋".as_bytes(), 1), ("👋".to_owned(), true)); } + fn lines(kind: ValueKind, bytes: &[u8], max_chars: usize) -> (String, bool) { + let mut out = Vec::new(); + let cut = display_lines(kind, bytes, max_chars, &mut out); + (String::from_utf8(out).unwrap(), cut) + } + + #[test] + fn every_line_break_form_is_one_space_on_one_line() { + assert_eq!( + shown( + ValueKind::Text, + "a\nb\u{b}c\u{c}d\re\u{85}f\u{2028}g\u{2029}h".as_bytes(), + 100 + ), + ("a b c d e f g h".to_owned(), false) + ); + assert_eq!(shown(ValueKind::Text, b"a\r\nb", 100), ("a b".to_owned(), false)); + assert_eq!( + shown(ValueKind::Text, "a\u{80}b\u{9f}c\u{7f}d".as_bytes(), 100), + ("a b c d".to_owned(), false) + ); + assert_eq!( + shown(ValueKind::Text, "é\u{a0}\u{2027}\u{202a}".as_bytes(), 100), + ("é\u{a0}\u{2027}\u{202a}".to_owned(), false) + ); + } + + #[test] + fn kept_line_breaks_are_one_newline_whatever_their_form() { + assert_eq!( + lines( + ValueKind::Text, + "a\nb\u{b}c\u{c}d\re\u{85}f\u{2028}g\u{2029}h".as_bytes(), + 100 + ), + ("a\nb\nc\nd\ne\nf\ng\nh".to_owned(), false) + ); + assert_eq!( + lines(ValueKind::Text, b"a\r\nb\r\rc\n\rd", 100), + ("a\nb\n\nc\n\nd".to_owned(), false) + ); + assert_eq!( + lines(ValueKind::Text, b"a\tb\0c\x1bd", 100), + ("a b c d".to_owned(), false) + ); + assert_eq!(lines(ValueKind::Text, b"last\r\n", 100), ("last\n".to_owned(), false)); + } + + #[test] + fn kept_line_breaks_count_toward_the_cut_as_the_value_holds_them() { + assert_eq!(lines(ValueKind::Text, b"ab\r\ncd", 3), ("ab\n".to_owned(), true)); + assert_eq!(lines(ValueKind::Text, b"ab\r\ncd", 4), ("ab\n".to_owned(), true)); + assert_eq!( + lines(ValueKind::Text, "日\u{2028}本語".as_bytes(), 3), + ("日\n本".to_owned(), true) + ); + assert_eq!( + lines(ValueKind::Bytes, &[0x0a, 0x0d, 0xbe, 0xef], 6), + ("0x0a0d".to_owned(), true) + ); + assert_eq!( + lines(ValueKind::Undecodable, b"money", 100), + ("money".to_owned(), false) + ); + } + #[test] fn a_head_keeps_line_breaks_and_cuts_at_a_character() { assert_eq!( diff --git a/core/crates/ffi/src/results/cursor.rs b/core/crates/ffi/src/results/cursor.rs index 3486ff4630..ffa165e2f6 100644 --- a/core/crates/ffi/src/results/cursor.rs +++ b/core/crates/ffi/src/results/cursor.rs @@ -17,6 +17,8 @@ pub(crate) struct Cursor { raw: Vec, offsets: Vec, text: Vec, + // Set by each fetch: whether its cells keep their line breaks. + keep_breaks: bool, window: TpWindow, } @@ -41,6 +43,7 @@ impl Cursor { raw: Vec::new(), offsets: Vec::new(), text: Vec::new(), + keep_breaks: false, window: TpWindow { first_row: 0, total_rows: 0, @@ -67,6 +70,31 @@ impl Cursor { first_column: u32, column_count: u32, max_chars: u32, + ) -> Option<&TpWindow> { + self.keep_breaks = false; + self.pack(first_row, row_count, first_column, column_count, max_chars) + } + + // As `fetch`, with each line break in a cell kept as one `\n`, for a grid that wraps its cells. + pub(crate) fn fetch_lines( + &mut self, + first_row: u64, + row_count: u32, + first_column: u32, + column_count: u32, + max_chars: u32, + ) -> Option<&TpWindow> { + self.keep_breaks = true; + self.pack(first_row, row_count, first_column, column_count, max_chars) + } + + fn pack( + &mut self, + first_row: u64, + row_count: u32, + first_column: u32, + column_count: u32, + max_chars: u32, ) -> Option<&TpWindow> { let store = self.store.clone(); let state = store.read(); @@ -165,7 +193,12 @@ impl Cursor { Some((kind, value)) => { self.cell_kinds[cell] = kind as u8; self.raw[cell] = value.raw; - if cell_text::display(kind, value.bytes, max_chars, &mut self.text) { + let cut = if self.keep_breaks { + cell_text::display_lines(kind, value.bytes, max_chars, &mut self.text) + } else { + cell_text::display(kind, value.bytes, max_chars, &mut self.text) + }; + if cut { set_bit(&mut self.truncated, cell); } } @@ -318,10 +351,56 @@ mod tests { assert_eq!(tail.texts, [Some("2".to_owned()), Some("4".to_owned())]); } + fn breaks() -> Arc { + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("note", ColumnType::untyped_text(""))].into(); + let store = Arc::new(ResultStore::new(columns)); + store.append(&[ + vec![Value::Text("first\r\nsecond\u{2028}third".to_owned())], + vec![Value::Text("tab\there".to_owned())], + vec![Value::Null], + ]); + store + } + + #[test] + fn a_window_that_keeps_line_breaks_holds_one_newline_per_break() { + let mut cursor = Cursor::new(breaks(), None); + + let window = read(cursor.fetch_lines(0, 50, 0, 1, 100).unwrap()); + + assert_eq!( + window.texts, + [ + Some("first\nsecond\nthird".to_owned()), + Some("tab here".to_owned()), + None + ] + ); + assert_eq!(window.truncated, [false, false, false]); + assert_eq!(window.raw[0], "first\r\nsecond\u{2028}third".len() as i64); + } + + #[test] + fn one_cursor_serves_flat_and_kept_windows_in_turn() { + let mut cursor = Cursor::new(breaks(), None); + + let kept = read(cursor.fetch_lines(0, 1, 0, 1, 7).unwrap()); + let flat = read(cursor.fetch(0, 1, 0, 1, 100).unwrap()); + let again = read(cursor.fetch_lines(0, 1, 0, 1, 100).unwrap()); + + assert_eq!( + (kept.texts, kept.truncated), + (vec![Some("first\n".to_owned())], vec![true]) + ); + assert_eq!(flat.texts, [Some("first second third".to_owned())]); + assert_eq!(again.texts, [Some("first\nsecond\nthird".to_owned())]); + } + #[test] fn a_window_whose_text_could_pass_four_gib_is_refused() { let mut cursor = Cursor::new(store(), None); assert!(cursor.fetch(0, 3, 0, 2, u32::MAX).is_none()); + assert!(cursor.fetch_lines(0, 3, 0, 2, u32::MAX).is_none()); } } diff --git a/core/crates/ffi/src/window_abi.rs b/core/crates/ffi/src/window_abi.rs index 53c41cc83a..1e4375cbc7 100644 --- a/core/crates/ffi/src/window_abi.rs +++ b/core/crates/ffi/src/window_abi.rs @@ -13,9 +13,10 @@ use crate::syntax; /// Cells are column by column: the cell of row `r` and column `c` is /// `(c - first_column) * row_count + (r - first_row)`. A cell's text is /// `text[offsets[cell]..offsets[cell + 1]]`, UTF-8, at most the fetch's -/// `max_chars` characters on one line. `nulls` and `truncated` hold a -/// bit per cell, lowest bit first. `column_kinds` and `cell_kinds` hold -/// a `ValueKind` byte each, and a cell's kind says what its `raw` holds. +/// `max_chars` characters, on one line unless the fetch keeps line +/// breaks. `nulls` and `truncated` hold a bit per cell, lowest bit +/// first. `column_kinds` and `cell_kinds` hold a `ValueKind` byte each, +/// and a cell's kind says what its `raw` holds. #[repr(C)] pub struct TpWindow { pub first_row: u64, @@ -77,6 +78,38 @@ pub unsafe extern "C" fn tablepro_cursor_fetch( fetched.unwrap_or(null()) } +/// As `tablepro_cursor_fetch`, for a grid that wraps its cells: each line +/// break in a cell's text, whatever its form (LF, CR LF, CR, VT, FF, NEL, +/// U+2028, U+2029), is one `\n`. `max_chars` counts the value's +/// characters, so a CR LF counts two. Every other control character is +/// a space, as there. +/// +/// # Safety +/// +/// `cursor` is null or a cursor `ResultSet::open_cursor` returned and no +/// one freed, used by one thread at a time. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn tablepro_cursor_fetch_lines( + cursor: *mut TpCursor, + first_row: u64, + row_count: u32, + first_column: u32, + column_count: u32, + max_chars: u32, +) -> *const TpWindow { + // SAFETY: the caller passes null or a live cursor no other thread uses. + let Some(cursor) = (unsafe { cursor.as_mut() }) else { + return null(); + }; + let fetched = catch_unwind(AssertUnwindSafe(|| { + cursor + .cursor + .fetch_lines(first_row, row_count, first_column, column_count, max_chars) + .map_or(null(), |window| window as *const TpWindow) + })); + fetched.unwrap_or(null()) +} + /// # Safety /// /// `cursor` is null or a cursor `ResultSet::open_cursor` returned, freed diff --git a/core/docs/decisions/0003-result-windows-for-native-grids.md b/core/docs/decisions/0003-result-windows-for-native-grids.md index 5c6a89b653..61d5ed86a4 100644 --- a/core/docs/decisions/0003-result-windows-for-native-grids.md +++ b/core/docs/decisions/0003-result-windows-for-native-grids.md @@ -1,6 +1,6 @@ # 0003: The core owns the result set, and a native grid pulls windows of text -- **Status**: Accepted; amended by 0007; the row limit as the bound on memory superseded by 0020 +- **Status**: Accepted; amended by 0007; the row limit as the bound on memory superseded by 0020; the one-line cell amended by 0041 - **Date**: 2026-11-02 ## Context diff --git a/core/docs/decisions/0041-a-result-window-can-keep-its-line-breaks.md b/core/docs/decisions/0041-a-result-window-can-keep-its-line-breaks.md new file mode 100644 index 0000000000..d4da5b9c4e --- /dev/null +++ b/core/docs/decisions/0041-a-result-window-can-keep-its-line-breaks.md @@ -0,0 +1,43 @@ +# 0041: A result window can keep its line breaks + +- **Status**: Accepted +- **Date**: 2026-11-20 + +## Context + +[0003](0003-result-windows-for-native-grids.md) packs a window's text and cuts it "with control characters made spaces so a cell is one line". The Windows grid now wraps its cells when the user asks (#4329), and a line break in a value has to break the line there. A space cannot be turned back into a break in C#, so the core has to hand the breaks over. + +Two things were wrong with the one-line text as well: + +- `push_line` replaced bytes below 0x20 and 0x7f only. NEL (U+0085), the line separator (U+2028) and the paragraph separator (U+2029) are two and three bytes in UTF-8, so they passed through, and a cell that was meant to be one line reached DirectWrite with a mandatory break in it. +- Each grid had its own idea of a line break: the macOS grid seven forms, the core the C0 controls, the Windows grid's typed text the C0 and C1 controls. + +## Decision + +This amends the one-line cell of 0003. The window keeps two fetches. `tablepro_cursor_fetch` stays as it was, one line per cell. `tablepro_cursor_fetch_lines` is the same window with each line break kept as one `\n`. Both read one set of break forms: LF, CR LF, CR, VT, FF, NEL, U+2028 and U+2029. + +- **One line** (`fetch`): each break form is one space, as is every other C0 and C1 control and DEL. CR LF stays two spaces, as it was. +- **Kept breaks** (`fetch_lines`): each break form is one `\n`, CR LF one `\n` for the pair. Every other control is one space, as in the one-line text, so a tab still cannot shift a column. +- `max_chars` counts the value's own characters in both, before any break is folded. A CR LF counts two, so a kept window can hold fewer characters than the cap, never more, and the 4 GiB bound on a window is the same sum. +- Hex for binary and the type name of an unreadable value are the same in both. +- The window still carries display text only. The full value, with the break forms as stored, comes from the calls 0003 names for the detail pane, the editor and copy. + +## Rationale + +- A second export leaves `tablepro_cursor_fetch`'s signature, its callers and its tests alone. A flag on it would change the ABI every caller links. +- Every form becomes `\n` in the core, so no grid depends on which forms its text engine breaks at. Pango, measured, does not break at VT, FF or NEL; Core Text does; DirectWrite was not measured. One tested function decides instead. +- The same classifier flattens and keeps, so wrap off and wrap on cannot disagree about what a line break is. + +## Consequences + +- The one-line text of a value that holds NEL, U+2028, U+2029 or a C1 control changes: each is now one space, one byte where it was two or three. A test pins the new text (`every_line_break_form_is_one_space_on_one_line`); `text_is_cut_at_a_character_and_kept_on_one_line` and the cursor's window tests hold as they were, since their values hold LF and tab only. +- A kept `\n` may stand for CR LF or another form, as a space may stand for a tab. A grid that copies from display text has to read such a cell whole; the Windows grid marks it lossy ([Windows 0023](../../../windows/docs/decisions/0023-wrapped-cells-and-uneven-rows.md)). +- A trailing break is kept in the window. A grid that does not want an empty last line drops it. +- `window_abi.rs` gained an export, so `windows/src/TablePro.Interop/Generated/WindowMethods.g.cs` was generated again. +- The Linux app reads its rows through the Rust API and has its own display text, so it does not call either fetch. + +## Alternatives considered + +- **A flag on `tablepro_cursor_fetch`.** One export, but an ABI change for every caller and its tests. +- **Keep the stored break forms and let each grid fold them.** Three folds again, and the grid's text engine would see forms it may not break at. +- **Undo the spaces in C#.** A space that was a break cannot be told from one that was typed. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index 9db670cc91..2918fd52dc 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -10,7 +10,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the |---|---|---|---| | [0001](0001-shared-core.md) | One shared Rust core, a native UI per platform | Accepted; SSH on Windows amended by 0008 | The UI-free crates move to `core/crates` and build on Linux, Windows and macOS; each app keeps a native UI and passes its platform services in. | | [0002](0002-uniffi-bindings.md) | One UniFFI API for Swift and C#, with a C ABI beside it | Accepted | UniFFI proc macros in the core; Swift through UniFFI's generator and C# through uniffi-bindgen-cs v0.11.1+v0.31.0, each with a thin layer for cancel, progress, streams and off-UI-thread calls; `extern "C"` and csbindgen for hot paths and as the fallback. | -| [0003](0003-result-windows-for-native-grids.md) | The core owns the result set, and a native grid pulls windows of text | Accepted; amended by 0007; the row limit as the bound on memory superseded by 0020 | A columnar result set in the core; one packed UTF-8 window per visible range with exact, locale-free text; one coalesced rows-arrived callback; Arrow only for bulk export. | +| [0003](0003-result-windows-for-native-grids.md) | The core owns the result set, and a native grid pulls windows of text | Accepted; amended by 0007; the row limit as the bound on memory superseded by 0020; the one-line cell amended by 0041 | A columnar result set in the core; one packed UTF-8 window per visible range with exact, locale-free text; one coalesced rows-arrived callback; Arrow only for bulk export. | | [0004](0004-driver-plugin-abi.md) | Downloadable drivers over a small C ABI of our own | Accepted; superseded for Linux and Windows by 0025 | A static descriptor, minor-version negotiation, protobuf messages, Arrow C Data rows, a runtime per driver and `catch_unwind` at every export; signed per platform, never unloaded, linked statically on iOS. | | [0005](0005-sql-server-transport.md) | SQL Server on tiberius everywhere, with Kerberos added and ODBC as a Windows option | Accepted | tiberius on every platform with SSPI Negotiate added in a fork, Entra ID tokens from the core, and an optional Windows connection type over an installed ODBC Driver 18 for Always Encrypted; msodbcsql18 is never bundled. | | [0006](0006-connection-library.md) | The connection library holds a group tree, manual order and favourites | Accepted; how the Linux app shows groups superseded by linux 0032, the version 2 upgrade by linux 0033 | Groups form a tree by id, connections and groups carry an explicit order, favourites are one ordered list; version 2 group names become top-level groups. | @@ -45,3 +45,4 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0037](0037-swift-apps-own-duckdb-task-threads.md) | The Swift apps run DuckDB's tasks on threads of their own | Accepted | The Swift apps open DuckDB with `threads` and `external_threads` at the processor count and run its tasks on 8 MiB threads of their own, since an ATTACH or `read_duckdb()` reads another file's expressions inside a task any thread may take; a statement that raised the count is followed by taking DuckDB's new threads over, and a count below the pinned one stays refused. | | [0039](0039-dbx-passwords-from-its-key.md) | DBX's passwords are read with the key it keeps in the platform's store | Accepted | DBX's key comes from its key file, then the macOS keychain, Credential Manager or its DPAPI copy, or the Secret Service, through new `ForeignHost::credential_manager` and `secret_service` seams and `DataProtection` entropy; envelopes open with aws-lc-rs once a store is handed over, a host with none reads no DBX password, and one that cannot open them says some were not read. | | [0040](0040-duckdb-prepares-inside-a-transaction-it-runs-in.md) | DuckDB prepares a statement only inside a transaction it runs in | Accepted | DuckDB 2.0 prepares through a PREPARE that never writes, so a binding that takes a sequence value invalidates the database once that prepare commits on its own; the Swift apps run statements they do not stream through `duckdb_query`, and every prepare of user SQL, in the core too, runs inside the session's transaction or one the driver opens for the statement. | +| [0041](0041-a-result-window-can-keep-its-line-breaks.md) | A result window can keep its line breaks | Accepted | `tablepro_cursor_fetch_lines` packs the window `tablepro_cursor_fetch` does with each line break kept as one `\n`, for a grid that wraps its cells; both read one set of break forms (LF, CR LF, CR, VT, FF, NEL, U+2028, U+2029), which the one-line text now shows as spaces in full. | diff --git a/linux/crates/app/src/services/grid/display_text.rs b/linux/crates/app/src/services/grid/display_text.rs index 5f1a90cd4c..b9d394bae4 100644 --- a/linux/crates/app/src/services/grid/display_text.rs +++ b/linux/crates/app/src/services/grid/display_text.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::fmt::Write; use tablepro_core::Value; @@ -10,6 +11,61 @@ use tablepro_linux_platform::settings::DateFormat; /// what its tooltip quotes. pub const DISPLAY_MAX_CHARS: usize = 1_000; +/// The most lines a wrapped cell shows. A constant on every platform, with no setting. +pub const WRAP_MAX_LINES: i32 = 10; + +const LINE_BREAKS: [char; 6] = ['\r', '\u{b}', '\u{c}', '\u{85}', '\u{2028}', '\u{2029}']; + +/// `text` for a cell that wraps: each line break as LF, a CRLF as one, +/// and without one break at its end, which would draw an empty line. +/// Pango breaks at only some of these, so the layout never meets the rest. +pub fn keep_line_breaks(text: &str) -> Cow<'_, str> { + let head = &text[..text.len() - trailing_break_len(text)]; + if !head.contains(LINE_BREAKS) { + return Cow::Borrowed(head); + } + let mut kept = String::with_capacity(head.len()); + let mut chars = head.chars().peekable(); + while let Some(character) = chars.next() { + match character { + '\r' => { + chars.next_if_eq(&'\n'); + kept.push('\n'); + } + other if LINE_BREAKS.contains(&other) => kept.push('\n'), + other => kept.push(other), + } + } + Cow::Owned(kept) +} + +fn trailing_break_len(text: &str) -> usize { + if text.ends_with("\r\n") { + return 2; + } + text.chars() + .next_back() + .filter(|last| *last == '\n' || LINE_BREAKS.contains(last)) + .map_or(0, char::len_utf8) +} + +/// `text` up to `hidden_from`, where its first hidden line starts, ending +/// in an ellipsis. Pango draws none when the cut falls on a line break. +pub fn line_cut(text: &str, hidden_from: usize) -> String { + let mut end = hidden_from.min(text.len()); + while !text.is_char_boundary(end) { + end -= 1; + } + let head = &text[..end]; + let head = head.strip_suffix('\n').unwrap_or(head).trim_end_matches(' '); + let mut cut = String::with_capacity(head.len() + '…'.len_utf8()); + cut.push_str(head); + if !head.ends_with('…') { + cut.push('…'); + } + cut +} + /// What a cell shows for a value. `text` borrows the value where it /// can, so a text cell draws with no copy of its own. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -224,7 +280,9 @@ mod tests { use tablepro_core::column::{BoolStorage, ColumnKind, ColumnType}; use tablepro_core::value::{JsonText, OffsetTimestamp, SqlTime, Temporal, UndecodableReason, UndecodedValue}; - use super::{DISPLAY_MAX_CHARS, DisplayText, display_text, null_text}; + use std::borrow::Cow; + + use super::{DISPLAY_MAX_CHARS, DisplayText, WRAP_MAX_LINES, display_text, keep_line_breaks, line_cut, null_text}; fn text_column() -> ColumnType { ColumnType::untyped_text("text") @@ -398,4 +456,76 @@ mod tests { assert!(display.len() < 1_100, "{}", display.len()); assert!(display.ends_with("… (999000 more bytes)")); } + + #[test] + fn a_wrapped_cell_shows_ten_lines_on_every_platform() { + assert_eq!(WRAP_MAX_LINES, 10); + } + + #[test] + fn every_line_break_form_becomes_one_lf() { + let cases = [ + ("a\nb", "a\nb"), + ("a\r\nb", "a\nb"), + ("a\rb", "a\nb"), + ("a\u{b}b", "a\nb"), + ("a\u{c}b", "a\nb"), + ("a\u{85}b", "a\nb"), + ("a\u{2028}b", "a\nb"), + ("a\u{2029}b", "a\nb"), + ("a\r\n\r\nb", "a\n\nb"), + ("a\n\rb", "a\n\nb"), + ]; + for (value, kept) in cases { + assert_eq!(keep_line_breaks(value), kept, "{value:?}"); + } + } + + #[test] + fn one_trailing_line_break_is_dropped() { + let cases = [ + ("a\n", "a"), + ("a\r\n", "a"), + ("a\r", "a"), + ("a\u{2029}", "a"), + ("a\n\n", "a\n"), + ("a\r\n\r\n", "a\n"), + ("\n", ""), + ("", ""), + ]; + for (value, kept) in cases { + assert_eq!(keep_line_breaks(value), kept, "{value:?}"); + } + } + + #[test] + fn text_with_only_lf_breaks_is_not_copied() { + assert!(matches!( + keep_line_breaks("one\ntwo\tthree"), + Cow::Borrowed("one\ntwo\tthree") + )); + assert!(matches!(keep_line_breaks("one\n"), Cow::Borrowed("one"))); + } + + #[test] + fn a_line_cut_ends_in_one_ellipsis() { + assert_eq!(line_cut("one two three", 8), "one two…"); + assert_eq!(line_cut("one\ntwo\nthree", 8), "one\ntwo…"); + assert_eq!( + line_cut("one\n\nthree", 5), + "one\n…", + "an empty last line keeps its place" + ); + assert_eq!( + line_cut("wait…\nmore", 8), + "wait…", + "the value's own ellipsis is not doubled" + ); + assert_eq!(line_cut("short", 99), "short…"); + } + + #[test] + fn a_line_cut_never_splits_a_character() { + assert_eq!(line_cut("日本語", 4), "日…"); + } } diff --git a/linux/crates/app/src/services/grid/special_characters.rs b/linux/crates/app/src/services/grid/special_characters.rs index e351b49097..adb04dfcd1 100644 --- a/linux/crates/app/src/services/grid/special_characters.rs +++ b/linux/crates/app/src/services/grid/special_characters.rs @@ -190,7 +190,7 @@ fn hex_label(value: u32) -> Cow<'static, str> { Cow::Owned(format!("{value:04X}")) } -/// A one-line view's text with each special character written as its mark. +/// A view's text with each special character written as its mark. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Revealed { pub text: String, @@ -205,8 +205,9 @@ pub struct Mark { } /// `None` when `text` holds nothing to mark, so a plain value costs no copy. -pub fn reveal(text: &str) -> Option { - let mut found = special_characters(text, true).peekable(); +/// `line_breaks` is for a one-line view; a view that breaks its lines keeps LF and CR. +pub fn reveal(text: &str, line_breaks: bool) -> Option { + let mut found = special_characters(text, line_breaks).peekable(); found.peek()?; let mut shown = String::with_capacity(text.len() + 8); let mut marks = Vec::new(); @@ -252,7 +253,7 @@ mod tests { fn plain_text_spaces_and_tabs_are_not_marked() { assert!(marked("plain text\twith a tab", true).is_empty()); assert!(marked("ünïcödé 日本語", true).is_empty()); - assert_eq!(reveal("plain text"), None); + assert_eq!(reveal("plain text", true), None); } #[test] @@ -357,7 +358,7 @@ mod tests { #[test] fn reveal_writes_labels_and_keeps_special_spaces() { - let revealed = reveal("a\u{200b}b\u{a0}c\nd").expect("marks"); + let revealed = reveal("a\u{200b}b\u{a0}c\nd", true).expect("marks"); assert_eq!(revealed.text, "aZWSPb\u{a0}cLFd"); assert_eq!( revealed.marks, @@ -377,4 +378,24 @@ mod tests { ] ); } + + #[test] + fn reveal_keeps_line_breaks_for_a_view_that_breaks_its_lines() { + assert_eq!(reveal("one\ntwo\r\n", false), None); + let revealed = reveal("a\u{200b}b\nc\u{1}", false).expect("marks"); + assert_eq!(revealed.text, "aZWSPb\ncSOH"); + assert_eq!( + revealed.marks, + [ + Mark { + range: 1..5, + labelled: true + }, + Mark { + range: 8..11, + labelled: true + }, + ] + ); + } } diff --git a/linux/crates/app/src/ui/browse_tab/layout.rs b/linux/crates/app/src/ui/browse_tab/layout.rs index 5e12df7429..497cb7c636 100644 --- a/linux/crates/app/src/ui/browse_tab/layout.rs +++ b/linux/crates/app/src/ui/browse_tab/layout.rs @@ -80,12 +80,15 @@ fn more_menu(page_sizes: &[u64]) -> gio::Menu { rows.append(Some(&gettext("_Insert Row")), Some("grid.insert-row")); rows.append(Some(&gettext("_Delete Selected Rows")), Some("grid.delete-rows")); rows.append(Some(&gettext("_Row Details")), Some("grid.show-details")); + let view = gio::Menu::new(); + view.append(Some(&gettext("_Wrap Text")), Some("grid.wrap-text")); let pages = gio::Menu::new(); pages.append(Some(&gettext("First _Page")), Some("browse.first-page")); pages.append(Some(&gettext("_Last Page")), Some("browse.last-page")); let menu = gio::Menu::new(); menu.append_section(None, &actions); menu.append_section(None, &rows); + menu.append_section(None, &view); menu.append_section(None, &pages); menu.append_section(Some(&gettext("Rows per Page")), &page_size_menu(page_sizes)); menu @@ -199,6 +202,7 @@ pub(super) fn grid(tab: &BrowseTab, init: GridInit) -> DataGrid { find: false, filter_by_value: true, share: true, + wrap_text: true, tasks: init.tasks, label: init.label, }); @@ -372,6 +376,24 @@ mod tests { })); } + #[test] + fn the_more_menu_offers_wrap_text() { + let menu = more_menu(&[]); + let offered = (0..menu.n_items()) + .filter_map(|section| menu.item_link(section, "section")) + .any(|section| { + (0..section.n_items()).any(|item| { + section + .item_attribute_value(item, "action", None) + .and_then(|value| value.get::()) + .as_deref() + == Some("grid.wrap-text") + }) + }); + + assert!(offered); + } + #[gtk4::test] fn the_dropdown_shows_a_page_size_set_in_preferences() { let dropdown = gtk::DropDown::default(); diff --git a/linux/crates/app/src/ui/data_grid/columns.rs b/linux/crates/app/src/ui/data_grid/columns.rs index 5d8be38c26..47668eec3d 100644 --- a/linux/crates/app/src/ui/data_grid/columns.rs +++ b/linux/crates/app/src/ui/data_grid/columns.rs @@ -55,6 +55,34 @@ pub struct ColumnPaint { /// The column lines its values up on the last digit. An untyped column /// does once every value it holds is a number. pub numbers: Cell, + pub wrap: Rc, +} + +/// Whether a grid wraps its text, which its cells read as they draw. The +/// grid makes one and every column's paint shares it. +#[derive(Debug, Default)] +pub struct WrapState { + on: Cell, + /// The widest a character of the cells' font is taken to be, in pixels. + wide_px: Cell, +} + +impl WrapState { + pub fn on(&self) -> bool { + self.on.get() + } + + /// The state it had. + pub(super) fn set(&self, on: bool) -> bool { + self.on.replace(on) + } + + /// Whether text of `bytes` can be wider than `width`, so a short value + /// costs no layout. A character takes a byte or more. + pub fn may_overflow(&self, bytes: usize, width: i32) -> bool { + let wide = i64::from(self.wide_px.get()); + wide <= 0 || i64::try_from(bytes).unwrap_or(i64::MAX).saturating_mul(wide) > i64::from(width) + } } /// What the pages read under a column set have held so far. @@ -168,6 +196,7 @@ impl DataGrid { .map(|config| config.settings.grid_preferences().clone()) .unwrap_or_default(), numbers: Cell::new(column.display() == CellDisplay::Number), + wrap: self.imp().wrap.clone(), }); built.view_columns.push(self.build_column(&paint, sorting)); built.paints.push(paint); @@ -239,6 +268,7 @@ impl DataGrid { } }); let column = &paint.column; + let offers_wrap = self.config().is_some_and(|config| config.wrap_text); let view_column = gtk::ColumnViewColumn::builder() .title(&column.name) .factory(&factory) @@ -246,7 +276,7 @@ impl DataGrid { .build(); view_column.set_id(Some(&format!("column-{}", column.index))); view_column.set_sorter(self.sorter_for(column, sorting).as_ref()); - view_column.set_header_menu(Some(&grid_menu::header_menu(column, sorting))); + view_column.set_header_menu(Some(&grid_menu::header_menu(column, sorting, offers_wrap))); view_column } @@ -274,6 +304,19 @@ impl DataGrid { pub(super) fn fonts_changed(&self) { self.size_columns(Measure::Again); row_number_column::fit(self); + self.measure_wrap_glyph(); + } + + /// Twice the font's usual character, so a double-width one is counted. + pub(super) fn measure_wrap_glyph(&self) { + let wrap = &self.imp().wrap; + if !wrap.on() { + return; + } + let context = self.column_view().create_pango_context(); + let metrics = context.metrics(Some(&value_font(&context, self.cell_font().as_deref())), None); + let usual = metrics.approximate_char_width().max(metrics.approximate_digit_width()); + wrap.wide_px.set((pango::units_to_double(usual) * 2.0).ceil() as i32); } /// A grid out of any window hears of no font change, and one sized @@ -978,7 +1021,7 @@ fn sampled_width(context: &pango::Context, font: &pango::FontDescription, texts: if !lines.is_empty() { lines.push('\n'); } - let drawn = super::special_marks::drawn(text, None, marks); + let drawn = super::special_marks::drawn(text, None, marks, true); let offset = u32::try_from(lines.len()).unwrap_or(u32::MAX); for mut attribute in drawn.attributes.iter().flat_map(pango::AttrList::attributes) { attribute.set_start_index(attribute.start_index().saturating_add(offset)); diff --git a/linux/crates/app/src/ui/data_grid/grid_actions.rs b/linux/crates/app/src/ui/data_grid/grid_actions.rs index ddebacfec7..de69770a8f 100644 --- a/linux/crates/app/src/ui/data_grid/grid_actions.rs +++ b/linux/crates/app/src/ui/data_grid/grid_actions.rs @@ -42,6 +42,25 @@ pub(crate) fn enable(grid: &DataGrid, name: &str, enabled: bool) { } } +const WRAP_TEXT: &str = "wrap-text"; + +// Its state is the grid's own, never the setting's, so one tab's choice leaves the others alone. +fn install_wrap_text(grid: &DataGrid) { + if !grid.config().is_some_and(|config| config.wrap_text) { + return; + } + let wrap = gio::SimpleAction::new_stateful(WRAP_TEXT, None, &grid.wraps_text().to_variant()); + let weak = grid.downgrade(); + wrap.connect_change_state(move |action, state| { + let (Some(grid), Some(wraps)) = (weak.upgrade(), state.and_then(glib::Variant::get::)) else { + return; + }; + action.set_state(&wraps.to_variant()); + grid.apply_wrap_text(wraps); + }); + grid.imp().actions.add_action(&wrap); +} + pub fn install(grid: &DataGrid) { install_column_actions(grid); add(grid, "menu", |grid| { @@ -71,6 +90,7 @@ pub fn install(grid: &DataGrid) { details.set_state(&split_view.shows_sidebar().to_variant()); } }); + install_wrap_text(grid); add(grid, "columns", column_chooser::present); add(grid, "highlight-rules", super::highlight_dialog::present); grid.edit().install_actions(grid); @@ -147,6 +167,29 @@ fn install_column_actions(grid: &DataGrid) { } impl DataGrid { + pub(crate) fn wraps_text(&self) -> bool { + self.imp().wrap.on() + } + + /// Wrap long values or draw each on one line, as Wrap Text does. + /// Nothing in a grid that does not offer it. + pub(crate) fn set_wrap_text(&self, wraps: bool) { + if wraps != self.wraps_text() + && let Some(wrap) = self.imp().actions.lookup_action(WRAP_TEXT) + { + wrap.change_state(&wraps.to_variant()); + } + } + + // Every bound cell draws again, which lays it out for the new state and asks for its new height. + fn apply_wrap_text(&self, wraps: bool) { + if self.imp().wrap.set(wraps) == wraps { + return; + } + self.measure_wrap_glyph(); + self.redraw(); + } + /// The data column an action on "the column" means: the cell a menu /// opened on, else the focused cell's. pub(crate) fn target_column(&self) -> Option { diff --git a/linux/crates/app/src/ui/data_grid/grid_cell.rs b/linux/crates/app/src/ui/data_grid/grid_cell.rs index 48be4d52c0..7867b2e77c 100644 --- a/linux/crates/app/src/ui/data_grid/grid_cell.rs +++ b/linux/crates/app/src/ui/data_grid/grid_cell.rs @@ -7,11 +7,13 @@ use gtk4::{self as gtk, glib, pango}; use tablepro_core::Value; use super::columns::ColumnPaint; -use super::special_marks::show_value; +use super::special_marks::{drawn, show_value}; use super::tracked_values::cell_description; use super::{DataGrid, GridRow, ServerValue}; use crate::services::change_tracker::CellState; -use crate::services::grid::display_text::{DisplayText, auto_filled_sentinel, display_text_formatted, null_text}; +use crate::services::grid::display_text::{ + DisplayText, WRAP_MAX_LINES, auto_filled_sentinel, display_text_formatted, keep_line_breaks, line_cut, null_text, +}; use crate::services::grid::{CellLock, GridColumn, HighlightColor}; /// Enough for any number, date or short text. @@ -76,6 +78,33 @@ impl TextAttributes { } } +/// What the text a wrapping cell is bound to needs to be laid out. +#[derive(Debug, Clone, Copy)] +pub struct Wrapped { + /// It holds a line break or a tab, so its length says nothing of its width. + unbounded: bool, + bytes: usize, + /// The value goes on past the text. + truncated: bool, +} + +/// The height a wrapping cell's text takes at a width. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Fit { + width: i32, + height: i32, + /// Where the first line past the last one shown starts. + cut: Option, +} + +/// The text a cell is bound to, kept while the cell draws it cut at a line. +#[derive(Debug)] +pub struct Whole { + text: String, + attributes: Option, + cut: usize, +} + mod imp { use super::*; @@ -94,8 +123,17 @@ mod imp { /// Where a value that is not text is written to draw it, kept from /// one bind to the next. pub scratch: RefCell, + /// The grid wrapped its text when the cell last drew. + pub wraps: Cell, + /// Set while the grid wraps and the bound text can take more than a line. + pub wrapped: Cell>, + pub whole: RefCell>, + /// Worked out in `measure`, so the allocation that follows lays nothing out again. + pub fit: Cell>, #[cfg(test)] pub renders: Cell, + #[cfg(test)] + pub resizes: Cell, } #[glib::object_subclass] @@ -122,6 +160,14 @@ mod imp { } impl WidgetImpl for GridCell { + // Without it GTK never tells the cell how wide it is. + fn request_mode(&self) -> gtk::SizeRequestMode { + match self.wraps.get() { + true => gtk::SizeRequestMode::HeightForWidth, + false => self.parent_request_mode(), + } + } + fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) { let mut size = (0, 0, -1, -1); let mut child = self.obj().first_child(); @@ -137,22 +183,34 @@ mod imp { } child = widget.next_sibling(); } + // From the bound text, since an open editor hides the display. Minimum + // and natural both, since the list takes a row's minimum. + if orientation == gtk::Orientation::Vertical + && let Some(fit) = self.obj().fit(for_size) + { + size.0 = size.0.max(fit.height); + size.1 = size.1.max(fit.height); + } size } fn size_allocate(&self, width: i32, height: i32, baseline: i32) { let cell = self.obj(); + cell.cut_to_fit(width); + let wraps = self.wraps.get(); let mut child = cell.first_child(); while let Some(widget) = child { if widget.should_layout() { - let (offset, available) = if self.editor.borrow().as_ref() == Some(&widget) { - cell.editor_space(width) - } else { - (0, width) + let editing = self.editor.borrow().as_ref() == Some(&widget); + let (offset, available) = if editing { cell.editor_space(width) } else { (0, width) }; + // In a tall row the editor sits on the first line, where the text it edits starts. + let tall = match editing && wraps { + true => widget.measure(gtk::Orientation::Vertical, available).1.min(height), + false => height, }; let transform = gtk::gsk::Transform::new().translate(>k::graphene::Point::new(offset as f32, 0.0)); - widget.allocate(available, height, baseline, Some(transform)); + widget.allocate(available, tall, baseline, Some(transform)); } child = widget.next_sibling(); } @@ -314,15 +372,17 @@ impl GridCell { (false, _) => TextMark::Plain, }; let marks = paint.preferences.snapshot().show_invisible_characters; + let wraps = paint.wrap.on(); + let reflow = self.rewrap(wraps); let null = paint.tracked.with_value(&row, column, |value, computed| { let mut scratch = self.imp().scratch.borrow_mut(); let shown = shown_text(&paint, value, computed, lock.is_none(), &mut scratch); - show_value( - display, - shown.text, - paint.attributes.for_text(text_mark, shown.placeholder), - marks && !shown.placeholder, - ); + let attributes = paint.attributes.for_text(text_mark, shown.placeholder); + // A number or a placeholder is never worth a taller row. + match wraps && !shown.placeholder && !paint.numbers.get() { + true => self.show_wrapped(display, &shown, attributes, marks), + false => show_value(display, shown.text, attributes, marks && !shown.placeholder), + } set_class( display, "dimmed", @@ -333,6 +393,15 @@ impl GridCell { if self.imp().scratch.borrow().capacity() > SCRATCH_KEPT_BYTES { self.imp().scratch.replace(String::new()); } + if wraps { + self.align_in_tall_row(display); + } + // An Inscription asks for no new size when its text changes. + if reflow || (wraps && self.may_wrap()) { + #[cfg(test)] + self.imp().resizes.set(self.imp().resizes.get() + 1); + self.queue_resize(); + } // GTK binds a new row before attaching it to the grid widget tree. let colour = paint.grid.upgrade().and_then(|grid| grid.highlight_of(&row, column)); for each in HighlightColor::ALL { @@ -363,6 +432,149 @@ impl GridCell { } } + /// Lay the cell out for whether its grid wraps. `true` when its row may + /// change height: the grid changed its mind, or the text drawn until + /// now could take more than a line. + fn rewrap(&self, wraps: bool) -> bool { + let imp = self.imp(); + let changed = imp.wraps.replace(wraps) != wraps; + if !changed && !wraps { + return false; + } + let could_wrap = self.may_wrap(); + imp.wrapped.set(None); + imp.whole.replace(None); + imp.fit.set(None); + if !wraps && let Some(display) = self.display() { + display.set_valign(gtk::Align::Center); + display.set_yalign(0.5); + } + changed || could_wrap + } + + /// Where a wrapping grid's cell puts its text: on the first line of + /// its row, level with the row's tallest cell. + fn align_in_tall_row(&self, display: >k::Inscription) { + // Only text that wraps takes the row's height. An Inscription wraps + // into whatever height it gets, so a number or a placeholder stays one line tall. + display.set_valign(match self.imp().wrapped.get() { + Some(_) => gtk::Align::Fill, + None => gtk::Align::Start, + }); + display.set_yalign(0.0); + } + + /// Draw `shown` with its line breaks kept, and its other marks as on one line. + fn show_wrapped( + &self, + display: >k::Inscription, + shown: &DisplayText<'_>, + attributes: Option<&pango::AttrList>, + marks: bool, + ) { + let kept = keep_line_breaks(shown.text); + let drawn = drawn(&kept, attributes, marks, false); + display.set_text(Some(&drawn.text)); + display.set_attributes(drawn.attributes.as_ref()); + self.imp().wrapped.set(Some(Wrapped { + unbounded: drawn.text.contains(['\n', '\t']), + bytes: drawn.text.len(), + truncated: shown.truncated_bytes > 0, + })); + } + + /// Whether the bound text can take more than a line at the cell's width. + fn may_wrap(&self) -> bool { + self.imp().wrapped.get().is_some_and(|wrapped| { + wrapped.unbounded + || self + .paint() + .is_some_and(|paint| paint.wrap.may_overflow(wrapped.bytes, self.width())) + }) + } + + /// The bound text as the cell draws it with nothing cut, and its marks. + pub(super) fn whole_text(&self) -> Option<(String, Option)> { + if let Some(whole) = self.imp().whole.borrow().as_ref() { + return Some((whole.text.clone(), whole.attributes.clone())); + } + let display = self.display()?; + Some((display.text()?.into(), display.attributes())) + } + + /// The height the bound text takes wrapped at `width`, and where it is + /// cut. `None` for a cell that draws one line. + fn fit(&self, width: i32) -> Option { + let wrapped = self.imp().wrapped.get()?; + let fit = self.laid_out(wrapped, width); + self.imp().fit.set(fit); + fit + } + + fn laid_out(&self, wrapped: Wrapped, width: i32) -> Option { + // A column has no width between Size to Fit and the width it then gets. + if width <= 0 { + return None; + } + if !wrapped.unbounded && !self.paint()?.wrap.may_overflow(wrapped.bytes, width) { + return None; + } + let (text, attributes) = self.whole_text()?; + // The text is cut to 1,000 characters already, so Pango never shapes a whole value. + let layout = self.display()?.create_pango_layout(Some(&text)); + layout.set_attributes(attributes.as_ref()); + layout.set_width(width.saturating_mul(pango::SCALE)); + layout.set_wrap(pango::WrapMode::WordChar); + Some(fit_of(&layout, width)) + } + + /// Draw the bound text cut at the last line `width` shows, or whole again. + fn cut_to_fit(&self, width: i32) { + let imp = self.imp(); + if imp.wrapped.get().is_none() { + return; + } + let fit = match imp.fit.get() { + Some(fit) if fit.width == width => Some(fit), + _ => self.fit(width), + }; + let cut = fit.and_then(|fit| fit.cut); + let shown = imp.whole.borrow().as_ref().map(|whole| whole.cut); + if cut == shown { + return; + } + let (Some((text, attributes)), Some(display)) = (self.whole_text(), self.display()) else { + return; + }; + match cut { + Some(at) => { + display.set_text(Some(&line_cut(&text, at))); + display.set_attributes(attributes.as_ref().map(|marks| clipped(marks, at)).as_ref()); + imp.whole.replace(Some(Whole { + text, + attributes, + cut: at, + })); + } + None => { + display.set_text(Some(&text)); + display.set_attributes(attributes.as_ref()); + imp.whole.replace(None); + } + } + } + + /// The cell breaks its text into lines, as a text cell of a grid that wraps does. + pub(super) fn wraps(&self) -> bool { + self.imp().wrapped.get().is_some() + } + + /// The cell draws less than the text it holds says: the value past its + /// first 1,000 characters, or the lines past the last it shows. + pub(super) fn leaves_text_out(&self) -> bool { + self.imp().whole.borrow().is_some() || self.imp().wrapped.get().is_some_and(|wrapped| wrapped.truncated) + } + pub(crate) fn open_editor(&self, editor: &impl IsA) { self.close_editor(); if let Some(closed) = self.imp().closed.take() { @@ -403,6 +615,59 @@ impl GridCell { pub(crate) fn render_count(&self) -> u32 { self.imp().renders.get() } + + /// How often a draw asked for a new size. + #[cfg(test)] + pub(crate) fn resize_count(&self) -> u32 { + self.imp().resizes.get() + } +} + +/// The first `WRAP_MAX_LINES` lines of `layout`. Their height comes from +/// the lines laid out, since the font's own line height is shorter and +/// would hide the last one. +fn fit_of(layout: &pango::Layout, width: i32) -> Fit { + if layout.line_count() <= WRAP_MAX_LINES { + return Fit { + width, + height: pango::units_to_double(layout.size().1).ceil() as i32, + cut: None, + }; + } + let mut lines = layout.iter(); + for _ in 1..WRAP_MAX_LINES { + if !lines.next_line() { + break; + } + } + let (_, last) = lines.line_extents(); + let cut = match lines.next_line() { + true => lines + .line_readonly() + .and_then(|line| usize::try_from(line.start_index()).ok()), + false => None, + }; + Fit { + width, + height: pango::units_to_double(last.y() + last.height()).ceil() as i32, + cut, + } +} + +/// `marks` without those on text from `end` on. One over the whole text, as bold, stays whole. +fn clipped(marks: &pango::AttrList, end: usize) -> pango::AttrList { + let end = u32::try_from(end).unwrap_or(u32::MAX); + let kept = pango::AttrList::new(); + for mut mark in marks.attributes() { + if mark.start_index() >= end { + continue; + } + if mark.end_index() != u32::MAX && mark.end_index() > end { + mark.set_end_index(end); + } + kept.insert(mark); + } + kept } /// An editable cell shows NULL as ``, so it reads apart from an diff --git a/linux/crates/app/src/ui/data_grid/grid_config.rs b/linux/crates/app/src/ui/data_grid/grid_config.rs index eb478c33aa..7af9ac5d45 100644 --- a/linux/crates/app/src/ui/data_grid/grid_config.rs +++ b/linux/crates/app/src/ui/data_grid/grid_config.rs @@ -65,6 +65,8 @@ pub struct GridConfig { pub filter_by_value: bool, // The host can share the rows as a link: an editor's results and a table tab's rows. pub share: bool, + /// The grid offers Wrap Text: a table's rows or a result's, not a key's entries. + pub wrap_text: bool, pub tasks: Tasks, /// What a screen reader calls the grid. pub label: String, diff --git a/linux/crates/app/src/ui/data_grid/grid_menu.rs b/linux/crates/app/src/ui/data_grid/grid_menu.rs index 3898bf7bfd..224b767d22 100644 --- a/linux/crates/app/src/ui/data_grid/grid_menu.rs +++ b/linux/crates/app/src/ui/data_grid/grid_menu.rs @@ -59,6 +59,7 @@ impl GridMenus { let editable = grid.config().is_some_and(|config| config.tracker.is_some()); let references = gio::Menu::new(); let expressions = gio::Menu::new(); + let wraps = grid.config().is_some_and(|config| config.wrap_text); let cell = popover(grid, &cell_menu(grid, &references, &expressions)); let empty = editable.then(|| { popover( @@ -72,7 +73,7 @@ impl GridMenus { let reference_chooser = popover(grid, &gio::Menu::new()); let choices = editable.then(|| popover(grid, &gio::Menu::new())); Self { - row_numbers: popover(grid, &row_numbers_header_menu()), + row_numbers: popover(grid, &row_numbers_header_menu(wraps)), cell, empty, references, @@ -177,7 +178,8 @@ fn cell_menu(grid: &DataGrid, references: &gio::Menu, expressions: &gio::Menu) - item(&gettext("Show Row as _JSON"), "grid.show-row-json"), ]), ); - menu.append_section(None, &column_section(sorts)); + let wraps = config.as_ref().is_some_and(|config| config.wrap_text); + menu.append_section(None, &column_section(sorts, wraps)); let export = item(&gettext("E_xport…"), "grid.export"); // The window's Export Results key reaches the grid of the tab in front. if let Some(key) = crate::application::triggers_for("win.export-results").first() { @@ -198,7 +200,7 @@ fn cell_menu(grid: &DataGrid, references: &gio::Menu, expressions: &gio::Menu) - /// What a header's click and drag do, which no key reaches, so the cell /// menu offers them for the cell's column. -fn column_section(sorts: bool) -> gio::Menu { +fn column_section(sorts: bool, wraps: bool) -> gio::Menu { let column = gio::Menu::new(); if sorts { column.append_item(&hidden_while_disabled( @@ -221,14 +223,24 @@ fn column_section(sorts: bool) -> gio::Menu { item(&gettext("Col_umns…"), "grid.columns"), ]), ); + if wraps { + column.append_section(None, &wrap_section()); + } let menu = gio::Menu::new(); menu.append_submenu(Some(&gettext("Colu_mn")), &column); menu } +/// A check item for the whole grid, in a section of its own: the HIG keeps +/// check items apart from commands. +fn wrap_section() -> gio::Menu { + section([item(&gettext("_Wrap Text"), "grid.wrap-text")]) +} + /// A header's own menu, on a secondary click. It names its column, since -/// GTK opens it without telling the grid. -pub fn header_menu(column: &GridColumn, sorting: GridSorting) -> gio::Menu { +/// GTK opens it without telling the grid. `wraps` is for a grid that +/// offers Wrap Text. +pub fn header_menu(column: &GridColumn, sorting: GridSorting, wraps: bool) -> gio::Menu { let index = (column.index as u32).to_variant(); let at = |label: String, action: &str| { let item = gio::MenuItem::new(Some(&label), None); @@ -257,13 +269,16 @@ pub fn header_menu(column: &GridColumn, sorting: GridSorting) -> gio::Menu { ]), ); menu.append_section(None, §ion([item(&gettext("Col_umns…"), "grid.columns")])); + if wraps { + menu.append_section(None, &wrap_section()); + } menu } /// The row number column's header menu. GTK keeps a header's click for /// sorting, so the header selects the rows from here. The key is /// GtkListBase's `list.select-all`, out of a header menu's reach. -pub fn row_numbers_header_menu() -> gio::Menu { +pub fn row_numbers_header_menu(wraps: bool) -> gio::Menu { let select_all = item(&gettext("Select _All Rows"), "grid.select-all"); if let Some(key) = crate::application::triggers_for("list.select-all").first() { select_all.set_attribute_value("accel", Some(&key.to_variant())); @@ -271,6 +286,9 @@ pub fn row_numbers_header_menu() -> gio::Menu { let menu = gio::Menu::new(); menu.append_section(None, §ion([select_all])); menu.append_section(None, §ion([item(&gettext("Col_umns…"), "grid.columns")])); + if wraps { + menu.append_section(None, &wrap_section()); + } menu } diff --git a/linux/crates/app/src/ui/data_grid/imp.rs b/linux/crates/app/src/ui/data_grid/imp.rs index e25b394e0d..9e324a66da 100644 --- a/linux/crates/app/src/ui/data_grid/imp.rs +++ b/linux/crates/app/src/ui/data_grid/imp.rs @@ -102,6 +102,8 @@ pub struct DataGrid { pub(super) scheme_style: RefCell>, pub(super) applied_date_format: Cell>, pub(super) cell_font: RefCell>, + /// Shared with the cells, which read it as they draw. + pub(super) wrap: std::rc::Rc, } #[glib::object_subclass] diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index a72f1a5384..bac89a696e 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -83,6 +83,9 @@ impl DataGrid { let columns = config.columns.clone(); let sorting = config.sorting; let rules = config.rules.clone(); + // Read once: the setting is what a new grid opens with, and an open one keeps its own. + imp.wrap + .set(config.wrap_text && config.settings.grid_preferences().snapshot().wrap_text); imp.column_view .update_property(&[gtk::accessible::Property::Label(&config.label)]); imp.config.replace(Some(config)); diff --git a/linux/crates/app/src/ui/data_grid/pointer.rs b/linux/crates/app/src/ui/data_grid/pointer.rs index 7bd9e01b93..cf7c1e9b7d 100644 --- a/linux/crates/app/src/ui/data_grid/pointer.rs +++ b/linux/crates/app/src/ui/data_grid/pointer.rs @@ -1,6 +1,6 @@ use gtk4::prelude::*; use gtk4::subclass::prelude::*; -use gtk4::{self as gtk, gdk, glib}; +use gtk4::{self as gtk, gdk, glib, pango}; use super::{DataGrid, GridCell, GridRow}; @@ -130,9 +130,8 @@ pub(super) fn cut_text(view: >k::ColumnView, x: i32, y: i32) -> Option .pick(f64::from(x), f64::from(y), gtk::PickFlags::DEFAULT) .and_then(|picked| GridCell::from_focus(&picked))?; let display = cell.display()?; - let text = display.text().filter(|text| !text.is_empty())?; - let (width, _) = display.create_pango_layout(Some(&text)).pixel_size(); - if width <= display.width() { + let (text, _) = cell.whole_text().filter(|(text, _)| !text.is_empty())?; + if !is_cut(&cell, display, &text) { return None; } let mut shown: String = text.chars().take(TOOLTIP_MAX_CHARS).collect(); @@ -142,6 +141,43 @@ pub(super) fn cut_text(view: >k::ColumnView, x: i32, y: i32) -> Option Some(shown) } +/// Cut means the cell leaves text out, or its text takes more lines than +/// the cell shows. A value with a line break is cut in a one-line cell +/// even when its longest line fits. +fn is_cut(cell: &GridCell, display: >k::Inscription, text: &str) -> bool { + if cell.leaves_text_out() { + return true; + } + let layout = display.create_pango_layout(Some(text)); + // Bold is wider, and a mark's label is smaller. + layout.set_attributes(display.attributes().as_ref()); + if !cell.wraps() { + return layout.line_count() > 1 || layout.pixel_size().0 > display.width(); + } + layout.set_width(display.width().saturating_mul(pango::SCALE)); + layout.set_wrap(pango::WrapMode::WordChar); + layout.line_count() > lines_shown(&layout, display.height()) +} + +/// How many of `layout`'s lines a text of `height` shows: those that end +/// inside it, and always the first. +fn lines_shown(layout: &pango::Layout, height: i32) -> i32 { + let limit = height.saturating_mul(pango::SCALE); + let mut lines = layout.iter(); + let mut shown = 0; + loop { + let (_, line) = lines.line_extents(); + if line.y() + line.height() > limit { + break; + } + shown += 1; + if !lines.next_line() { + break; + } + } + shown.max(1) +} + fn hit_at(grid: &DataGrid, x: f64, y: f64) -> Hit { let view = grid.column_view(); let Some(picked) = view.pick(x, y, gtk::PickFlags::DEFAULT) else { diff --git a/linux/crates/app/src/ui/data_grid/row_number_column.rs b/linux/crates/app/src/ui/data_grid/row_number_column.rs index f675c8ed71..e1547eef38 100644 --- a/linux/crates/app/src/ui/data_grid/row_number_column.rs +++ b/linux/crates/app/src/ui/data_grid/row_number_column.rs @@ -55,10 +55,11 @@ pub fn build(grid: &DataGrid) -> gtk::ColumnViewColumn { factory.connect_unbind(move |_, item| { unwatch(&watches, item.upcast_ref()); }); + let offers_wrap = grid.config().is_some_and(|config| config.wrap_text); let column = gtk::ColumnViewColumn::builder() .title(crate::i18n::pgettext("row number column", "#")) .factory(&factory) - .header_menu(&grid_menu::row_numbers_header_menu()) + .header_menu(&grid_menu::row_numbers_header_menu(offers_wrap)) .resizable(false) .build(); column.set_id(Some("row-numbers")); @@ -102,6 +103,13 @@ fn show_cell(grid: &DataGrid, cell: >k::ColumnViewCell) { ) else { return; }; + // In a row grown by wrapped text the number sits on the text's first line. + let (number_align, icon_align) = match grid.wraps_text() { + true => (gtk::Align::Start, gtk::Align::Start), + false => (gtk::Align::Center, gtk::Align::Fill), + }; + number.set_valign(number_align); + icon.set_valign(icon_align); let state = grid.tracked().row_state(&row); icon.set_icon_name(state.icon()); icon.set_visible(state.icon().is_some()); diff --git a/linux/crates/app/src/ui/data_grid/special_marks.rs b/linux/crates/app/src/ui/data_grid/special_marks.rs index 24fda08e2d..689a4382d9 100644 --- a/linux/crates/app/src/ui/data_grid/special_marks.rs +++ b/linux/crates/app/src/ui/data_grid/special_marks.rs @@ -55,7 +55,7 @@ fn marked_attributes(base: Option<&pango::AttrList>, marks: &[Mark]) -> pango::A attributes } -/// What a one-line view draws for a value: its text, with each special +/// What a cell or field draws for a value: its text, with each special /// character written as its mark while `marks` holds. pub(crate) struct Drawn<'a> { pub text: Cow<'a, str>, @@ -63,9 +63,15 @@ pub(crate) struct Drawn<'a> { } // Drawing and column width both take the value from here, so a column is -// as wide as the marks its cells draw. -pub(crate) fn drawn<'a>(text: &'a str, attributes: Option<&pango::AttrList>, marks: bool) -> Drawn<'a> { - match marks.then(|| reveal(text)).flatten() { +// as wide as the marks its cells draw. `line_breaks` marks LF and CR too, +// for a view that draws one line. +pub(crate) fn drawn<'a>( + text: &'a str, + attributes: Option<&pango::AttrList>, + marks: bool, + line_breaks: bool, +) -> Drawn<'a> { + match marks.then(|| reveal(text, line_breaks)).flatten() { Some(revealed) => Drawn { attributes: Some(marked_attributes(attributes, &revealed.marks)), text: Cow::Owned(revealed.text), @@ -78,7 +84,7 @@ pub(crate) fn drawn<'a>(text: &'a str, attributes: Option<&pango::AttrList>, mar } pub(crate) fn show_value(display: >k::Inscription, text: &str, attributes: Option<&pango::AttrList>, marks: bool) { - let drawn = drawn(text, attributes, marks); + let drawn = drawn(text, attributes, marks, true); display.set_text(Some(&drawn.text)); display.set_attributes(drawn.attributes.as_ref()); } diff --git a/linux/crates/app/src/ui/data_grid/test_grid.rs b/linux/crates/app/src/ui/data_grid/test_grid.rs index 0e711320b7..9edef507ca 100644 --- a/linux/crates/app/src/ui/data_grid/test_grid.rs +++ b/linux/crates/app/src/ui/data_grid/test_grid.rs @@ -112,6 +112,7 @@ pub(crate) struct GridSpec { pub find: bool, pub filter_by_value: bool, pub share: bool, + pub wrap_text: bool, pub policy: Option, pub references: Option, pub dialect: Option, @@ -132,6 +133,7 @@ impl GridSpec { find: false, filter_by_value: true, share: false, + wrap_text: true, policy: None, references: None, dialect: None, @@ -239,6 +241,7 @@ impl Grid { find: spec.find, filter_by_value: spec.filter_by_value, share: spec.share, + wrap_text: spec.wrap_text, tasks: runtime.tasks(), label: "test grid".to_owned(), }; diff --git a/linux/crates/app/src/ui/data_grid/tests/cells.rs b/linux/crates/app/src/ui/data_grid/tests/cells.rs index 11348e366f..69aaa2fa81 100644 --- a/linux/crates/app/src/ui/data_grid/tests/cells.rs +++ b/linux/crates/app/src/ui/data_grid/tests/cells.rs @@ -32,6 +32,7 @@ fn paint() -> Rc { attributes: Rc::new(TextAttributes::new()), preferences: Default::default(), numbers: Cell::new(false), + wrap: Rc::default(), }) } @@ -650,6 +651,7 @@ fn a_cell_can_read_highlights_when_bound_before_it_is_parented() { attributes: Rc::new(TextAttributes::new()), preferences: Default::default(), numbers: Cell::new(false), + wrap: Rc::default(), })); assert!(cell.parent().is_none()); cell.bind(&grid.grid.store().row(0).expect("first row")); diff --git a/linux/crates/app/src/ui/data_grid/tests/gutter.rs b/linux/crates/app/src/ui/data_grid/tests/gutter.rs index 13483a45b7..6344be95e3 100644 --- a/linux/crates/app/src/ui/data_grid/tests/gutter.rs +++ b/linux/crates/app/src/ui/data_grid/tests/gutter.rs @@ -237,13 +237,17 @@ impl Drop for TestStyle { } fn wide_rows(count: i64) -> Grid { + wide_rows_of(count, |id, n| format!("value {id}-{n}")) +} + +fn wide_rows_of(count: i64, value: impl Fn(i64, usize) -> String) -> Grid { use tablepro_core::Value; let mut columns = vec![crate::ui::data_grid::test_grid::named("id", "integer", true)]; columns.extend((0..12).map(|n| crate::ui::data_grid::test_grid::named(&format!("column_{n}"), "text", false))); let rows = (1..=count) .map(|id| { std::iter::once(Value::Int(id)) - .chain((0..12).map(|n| Value::Text(format!("value {id}-{n}")))) + .chain((0..12).map(|n| Value::Text(value(id, n)))) .collect() }) .collect(); @@ -547,6 +551,32 @@ fn the_gutter_matches_font_and_density_changes() { assert_aligned(&grid); } +#[gtk4::test] +fn the_gutter_follows_rows_grown_by_wrapped_text() { + let grid = wide_rows_of(60, |id, n| match (id % 3, n) { + (0, 0) => "several words that wrap ".repeat(6), + _ => format!("value {id}-{n}"), + }); + grid.grid + .data_view_column(1) + .expect("the first text column") + .set_fixed_width(160); + grid.activate("wrap-text"); + sideways(&grid); + after_next_frame(&grid.window); + + let (short, tall) = (row_widget(&grid.cell_of(1, 1)), row_widget(&grid.cell_of(3, 1))); + assert!(tall.height() > short.height(), "no row grew"); + let (_, number) = gutter(&grid.cell_of(3, 1)); + let top = number.compute_bounds(&tall).expect("the number's place in its row"); + assert!( + top.y() + top.height() <= short.height() as f32, + "the number left the first line of its row: {top:?}" + ); + assert_aligned(&grid); + assert_pinned_pixels(&grid); +} + #[gtk4::test] fn the_pinned_gutter_shows_pending_states_and_stripes() { let grid = wide_rows(20); diff --git a/linux/crates/app/src/ui/data_grid/tests/menus.rs b/linux/crates/app/src/ui/data_grid/tests/menus.rs index 9b7c23d149..77238d7a1a 100644 --- a/linux/crates/app/src/ui/data_grid/tests/menus.rs +++ b/linux/crates/app/src/ui/data_grid/tests/menus.rs @@ -67,7 +67,7 @@ fn every_header_action_is_in_the_cell_menus_column_submenu() { let in_cell = action_names(&menu); let header_actions = menu_actions(&header); - assert_eq!(header_actions.len(), 9, "{header_actions:?}"); + assert_eq!(header_actions.len(), 10, "{header_actions:?}"); for (action, column) in &header_actions { assert!(column.is_none_or(|column| column == 1), "{action} names another column"); let counterpart = cell_menu_counterpart(action.as_str()); @@ -95,7 +95,7 @@ fn every_grid_menu_gives_each_item_its_own_access_key() { assert_access_keys(&cell_menu(&grid)); assert_access_keys(&empty); assert_access_keys(&data_column(&grid, 1).header_menu().expect("the header's menu")); - assert_access_keys(&crate::ui::data_grid::grid_menu::row_numbers_header_menu()); + assert_access_keys(&crate::ui::data_grid::grid_menu::row_numbers_header_menu(true)); } #[gtk4::test] @@ -326,7 +326,10 @@ fn the_row_number_headers_menu_selects_every_row() { grid.activate("select-all"); - assert_eq!(action_names(&header), ["grid.select-all", "grid.columns"]); + assert_eq!( + action_names(&header), + ["grid.select-all", "grid.columns", "grid.wrap-text"] + ); assert_eq!( accel_of(&header, "grid.select-all"), Some(Some("a".to_owned())) diff --git a/linux/crates/app/src/ui/data_grid/tests/mod.rs b/linux/crates/app/src/ui/data_grid/tests/mod.rs index f00508e9b3..ce8becbf75 100644 --- a/linux/crates/app/src/ui/data_grid/tests/mod.rs +++ b/linux/crates/app/src/ui/data_grid/tests/mod.rs @@ -9,6 +9,7 @@ mod sorting; mod summary; mod values; mod view; +mod wrap; use gtk4 as gtk; use gtk4::prelude::*; diff --git a/linux/crates/app/src/ui/data_grid/tests/view.rs b/linux/crates/app/src/ui/data_grid/tests/view.rs index fcc9d4fab6..16cd054315 100644 --- a/linux/crates/app/src/ui/data_grid/tests/view.rs +++ b/linux/crates/app/src/ui/data_grid/tests/view.rs @@ -9,12 +9,13 @@ use crate::test_support::wait_until; use crate::ui::data_grid::GridCell; use crate::ui::data_grid::test_grid::{Grid, GridSpec, WAIT, two_text_columns}; -/// Ask the view for a tooltip at the middle of `cell`, as GTK does when -/// the pointer rests there. `true` when one is shown. -fn asks_tooltip(grid: &Grid, cell: &GridCell) -> bool { +/// Ask the view for a tooltip at the middle of the part of `cell` in +/// view, as GTK does when the pointer rests there. `true` when one is shown. +pub(super) fn asks_tooltip(grid: &Grid, cell: &GridCell) -> bool { let view = grid.grid.column_view(); let bounds = cell.compute_bounds(&view).expect("the cell's bounds"); - let x = (bounds.x() + bounds.width() / 2.0) as i32; + let end = (bounds.x() + bounds.width()).min(view.width() as f32); + let x = ((bounds.x() + end) / 2.0) as i32; let y = (bounds.y() + bounds.height() / 2.0) as i32; let tooltip = glib::Object::new::(); view.emit_by_name::("query-tooltip", &[&x, &y, &false, &tooltip]) diff --git a/linux/crates/app/src/ui/data_grid/tests/wrap.rs b/linux/crates/app/src/ui/data_grid/tests/wrap.rs new file mode 100644 index 0000000000..f8acbb3468 --- /dev/null +++ b/linux/crates/app/src/ui/data_grid/tests/wrap.rs @@ -0,0 +1,336 @@ +use gtk4 as gtk; +use gtk4::pango; +use gtk4::prelude::*; +use tablepro_core::Value; + +use super::view::asks_tooltip; +use super::{action_names, cell_menu, data_column, row_widget, submenu, text}; +use crate::test_support::{MemorySettings, after_next_frame, drain_main_context, wait_until}; +use crate::ui::data_grid::test_grid::{Grid, GridSpec, WAIT, two_text_columns}; + +/// The width the wrapped column is held at, a few words wide. +const COLUMN_PX: i32 = 200; + +fn words() -> String { + "word ".repeat(40).trim_end().to_owned() +} + +fn lines(count: usize) -> String { + (0..count).map(|line| format!("l{line}")).collect::>().join("\n") +} + +fn rows_of(values: &[&str]) -> Grid { + let rows = values + .iter() + .zip(1..) + .map(|(value, id)| vec![Value::Int(id), text(value)]) + .collect(); + let grid = Grid::open(two_text_columns(), rows); + data_column(&grid, 1).set_fixed_width(COLUMN_PX); + after_next_frame(&grid.window); + grid +} + +fn row_height(grid: &Grid, id: i64) -> i32 { + row_widget(&grid.cell_of(id, 1)).height() +} + +/// The height of the first row, which every test keeps one line tall. +fn one_line(grid: &Grid) -> i32 { + wait_until(WAIT, || row_height(grid, 1) > 0).expect("the rows are laid out"); + row_height(grid, 1) +} + +fn wrap_state(grid: &Grid) -> Option { + grid.grid + .actions() + .action_state("wrap-text") + .and_then(|state| state.get::()) +} + +fn offers_wrap(menu: &impl IsA) -> bool { + action_names(menu.as_ref()) + .iter() + .any(|action| action == "grid.wrap-text") +} + +#[gtk4::test] +fn a_long_value_grows_its_row_and_a_short_one_stays_one_line() { + let grid = rows_of(&["B", &words(), "one\ntwo\nthree"]); + let one = one_line(&grid); + assert_eq!(row_height(&grid, 2), one, "a row was taller before Wrap Text"); + assert_eq!(row_height(&grid, 3), one); + + grid.activate("wrap-text"); + + wait_until(WAIT, || { + row_height(&grid, 2) > row_height(&grid, 3) && row_height(&grid, 3) > one + }) + .expect("three heights: one line, three lines and a wrapped paragraph"); + assert_eq!(row_height(&grid, 1), one, "a short value's row grew"); + assert_eq!(Grid::display_text(&grid.cell_of(3, 1)), "one\ntwo\nthree"); +} + +#[gtk4::test] +fn turning_wrap_off_returns_every_row_to_one_line() { + let grid = rows_of(&["B", &words(), &lines(30)]); + let one = one_line(&grid); + grid.activate("wrap-text"); + wait_until(WAIT, || row_height(&grid, 2) > one && row_height(&grid, 3) > one).expect("the rows grow"); + + grid.activate("wrap-text"); + + wait_until(WAIT, || row_height(&grid, 2) == one && row_height(&grid, 3) == one) + .expect("the rows go back to one line"); + assert_eq!(wrap_state(&grid), Some(false)); + let cell = grid.cell_of(2, 1); + assert_eq!(cell.request_mode(), gtk::SizeRequestMode::ConstantSize); + assert_eq!(Grid::display_text(&cell), words(), "the cell kept a cut text"); +} + +/// Each grid holds two tall rows, so both stay inside the window: GTK +/// allocates no new height to a row that scrolled out of view. +#[gtk4::test] +fn a_row_stops_at_ten_lines_and_the_text_past_them_ends_in_an_ellipsis() { + let capped = |value: &str| { + let grid = rows_of(&["B", &lines(10), value]); + let one = one_line(&grid); + grid.activate("wrap-text"); + wait_until(WAIT, || { + row_height(&grid, 2) > one && row_height(&grid, 3) == row_height(&grid, 2) + }) + .expect("a value of more than ten lines takes ten lines"); + assert_eq!(Grid::display_text(&grid.cell_of(2, 1)), lines(10), "ten lines were cut"); + Grid::display_text(&grid.cell_of(3, 1)) + }; + + // Pango draws no ellipsis when the cut falls on a line break, so the app writes it. + assert_eq!(capped(&lines(11)), format!("{}…", lines(10))); + assert_eq!(capped(&lines(50)), format!("{}…", lines(10))); + let paragraph = capped(&"x".repeat(900)); + assert!(paragraph.ends_with('…') && !paragraph.ends_with("……"), "{paragraph}"); + assert!(paragraph.len() < 900, "the paragraph was not cut"); +} + +#[gtk4::test] +fn the_cut_at_a_thousand_characters_comes_before_the_cut_at_ten_lines() { + let grid = rows_of(&["B", &"x".repeat(1_500)]); + one_line(&grid); + // Wide enough that the first thousand characters take fewer than ten lines. + data_column(&grid, 1).set_fixed_width(4_000); + + grid.activate("wrap-text"); + after_next_frame(&grid.window); + + let shown = Grid::display_text(&grid.cell_of(2, 1)); + assert!(shown.ends_with("… (500 more bytes)"), "{}", &shown[990..]); + assert!( + asks_tooltip(&grid, &grid.cell_of(2, 1)), + "a value cut short has no tooltip" + ); +} + +#[gtk4::test] +fn a_wrapped_cell_keeps_every_line_break_and_the_other_marks() { + let grid = rows_of(&["B", "a\u{200b}b\nc", "a\r\nb\u{2028}c\u{85}d\n"]); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + assert_eq!(Grid::display_text(&grid.cell_of(2, 1)), "aZWSPbLFc"); + assert_eq!(Grid::display_text(&grid.cell_of(3, 1)), "aCRLFbLSEPcNELdLF"); + + grid.activate("wrap-text"); + drain_main_context(); + + assert_eq!(Grid::display_text(&grid.cell_of(2, 1)), "aZWSPb\nc"); + assert_eq!(Grid::display_text(&grid.cell_of(3, 1)), "a\nb\nc\nd"); + + settings.set_show_invisible_characters(false).expect("store the flag"); + drain_main_context(); + assert_eq!(Grid::display_text(&grid.cell_of(2, 1)), "a\u{200b}b\nc"); + assert_eq!(Grid::display_text(&grid.cell_of(3, 1)), "a\nb\nc\nd"); +} + +#[gtk4::test] +fn editing_the_tallest_cell_keeps_its_row_height_and_edits_on_the_first_line() { + let grid = rows_of(&["B", &words()]); + let one = one_line(&grid); + grid.activate("wrap-text"); + wait_until(WAIT, || row_height(&grid, 2) > one).expect("the row grows"); + let tall = row_height(&grid, 2); + let cell = grid.focus(1, 1); + + assert!(grid.grid.edit().edit_cell(&cell), "the cell took no edit"); + let editor = grid.grid.edit().open_text().expect("an inline editor"); + after_next_frame(&grid.window); + + assert_eq!(row_height(&grid, 2), tall, "the row collapsed under its editor"); + let bounds = editor.compute_bounds(&cell).expect("the editor's place in its cell"); + assert!( + bounds.y() + bounds.height() < cell.height() as f32, + "the editor fills the tall cell: {bounds:?} in {}", + cell.height() + ); + assert!( + bounds.y() < one as f32, + "the editor is below the first line: {bounds:?}" + ); +} + +#[gtk4::test] +fn only_text_that_can_take_more_than_a_line_asks_for_a_new_size() { + let grid = rows_of(&["B", &words()]); + let (short, long) = (grid.cell_of(1, 1), grid.cell_of(2, 1)); + let number = grid.cell_of(2, 0); + one_line(&grid); + assert_eq!(long.resize_count(), 0, "a cell asked for a size with Wrap Text off"); + assert_eq!(long.request_mode(), gtk::SizeRequestMode::ConstantSize); + grid.grid.redraw(); + assert_eq!((short.resize_count(), long.resize_count()), (0, 0)); + + grid.activate("wrap-text"); + wait_until(WAIT, || row_height(&grid, 2) > row_height(&grid, 1)).expect("the row grows"); + assert_eq!(long.request_mode(), gtk::SizeRequestMode::HeightForWidth); + let before = (short.resize_count(), number.resize_count(), long.resize_count()); + let drawn = short.render_count(); + + grid.grid.redraw(); + + assert!(short.render_count() > drawn, "the cells were not drawn again"); + assert_eq!(short.resize_count(), before.0, "a short value asked for a new size"); + assert_eq!(number.resize_count(), before.1, "a number asked for a new size"); + assert!(long.resize_count() > before.2, "a long value kept its old size"); +} + +/// With Wrap Text off a value with a line break shows its first line +/// alone, so it is cut even when its longest line fits. +#[gtk4::test] +fn a_cell_has_a_tooltip_when_it_shows_fewer_lines_than_its_text_has() { + let grid = rows_of(&["B", "ok\nsecond line", &lines(3), &lines(30)]); + let settings = grid.grid.config().expect("a configured grid").settings.clone(); + settings.set_show_invisible_characters(false).expect("store the flag"); + data_column(&grid, 1).set_fixed_width(400); + after_next_frame(&grid.window); + let cell = |id: i64| grid.cell_of(id, 1); + + assert!( + asks_tooltip(&grid, &cell(2)), + "a value cut at its first line has no tooltip" + ); + assert!(!asks_tooltip(&grid, &cell(1)), "a value that fits has a tooltip"); + + let one = one_line(&grid); + grid.activate("wrap-text"); + wait_until(WAIT, || { + row_height(&grid, 4) > row_height(&grid, 3) && row_height(&grid, 3) > one + }) + .expect("the rows grow"); + after_next_frame(&grid.window); + + assert!(!asks_tooltip(&grid, &cell(1))); + assert!(!asks_tooltip(&grid, &cell(2)), "two lines shown in full have a tooltip"); + assert!( + !asks_tooltip(&grid, &cell(3)), + "three lines shown in full have a tooltip" + ); + assert!(asks_tooltip(&grid, &cell(4)), "a value cut at ten lines has no tooltip"); +} + +#[gtk4::test] +fn a_new_grid_opens_with_the_setting_and_an_open_one_keeps_its_own() { + let settings = MemorySettings::new(); + let build = || { + Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + ..GridSpec::table(two_text_columns()) + }, + super::keyed(&[1]), + ) + }; + let before = build(); + assert_eq!(wrap_state(&before), Some(false)); + + settings.get().set_grid_wrap_text(true).expect("store the flag"); + drain_main_context(); + let after = build(); + + assert_eq!(wrap_state(&before), Some(false), "an open grid followed the setting"); + assert_eq!(wrap_state(&after), Some(true), "a new grid ignored the setting"); + assert!(after.grid.wraps_text()); + + before.activate("wrap-text"); + settings.get().set_grid_wrap_text(false).expect("store the flag"); + drain_main_context(); + assert_eq!(wrap_state(&before), Some(true)); + assert_eq!(wrap_state(&after), Some(true), "an open grid followed the setting"); +} + +#[gtk4::test] +fn every_grid_menu_offers_wrap_text_and_a_grid_that_does_not_wrap_offers_none() { + let settings = MemorySettings::new(); + settings.get().set_grid_wrap_text(true).expect("store the flag"); + let build = |wrap_text: bool| { + Grid::build( + GridSpec { + settings: Some(settings.get().clone()), + wrap_text, + ..GridSpec::table(two_text_columns()) + }, + super::keyed(&[1]), + ) + }; + let menus = |grid: &Grid| { + let column = submenu(&cell_menu(grid), "Colu_mn").expect("the cell menu's Column submenu"); + let header = data_column(grid, 1).header_menu().expect("the header's menu"); + let numbers = grid + .grid + .row_numbers_column() + .and_then(|column| column.header_menu()) + .expect("the row number header's menu"); + [offers_wrap(&column), offers_wrap(&header), offers_wrap(&numbers)] + }; + + let offered = build(true); + assert_eq!(menus(&offered), [true; 3]); + assert!(offered.is_enabled("wrap-text")); + + let plain = build(false); + assert_eq!(menus(&plain), [false; 3]); + assert_eq!( + wrap_state(&plain), + None, + "a grid that offers no Wrap Text has its action" + ); + assert!( + !plain.grid.wraps_text(), + "the setting wrapped a grid that offers no Wrap Text" + ); + plain.grid.set_wrap_text(true); + assert!(!plain.grid.wraps_text()); +} + +/// What the cell's height rests on: a positive Pango height shows the +/// lines that fit in it, and text cut at a line break gets no ellipsis. +#[gtk4::test] +fn pango_caps_lines_by_height_and_draws_no_ellipsis_at_a_line_break() { + let ten_lines_of = |text: &str| { + let layout = gtk::Inscription::new(None).create_pango_layout(Some(text)); + layout.set_width(COLUMN_PX * pango::SCALE); + layout.set_wrap(pango::WrapMode::WordChar); + let mut line = layout.iter(); + for _ in 1..10 { + assert!(line.next_line(), "the text has fewer than ten lines"); + } + let (_, tenth) = line.line_extents(); + layout.set_ellipsize(pango::EllipsizeMode::End); + layout.set_height(tenth.y() + tenth.height()); + layout + }; + + let paragraphs = ten_lines_of(&lines(50)); + assert_eq!(paragraphs.line_count(), 10); + assert!(!paragraphs.is_ellipsized(), "Pango now marks a cut at a line break"); + + let paragraph = ten_lines_of(&"x".repeat(1_000)); + assert_eq!(paragraph.line_count(), 10); + assert!(paragraph.is_ellipsized()); +} diff --git a/linux/crates/app/src/ui/editor/results_pane.rs b/linux/crates/app/src/ui/editor/results_pane.rs index 0d8dfe8f18..b433539643 100644 --- a/linux/crates/app/src/ui/editor/results_pane.rs +++ b/linux/crates/app/src/ui/editor/results_pane.rs @@ -58,6 +58,8 @@ mod imp { #[template_child] pub columns_button: TemplateChild, #[template_child] + pub view_button: TemplateChild, + #[template_child] pub transaction_bar: TemplateChild, #[template_child] pub transaction_label: TemplateChild, @@ -80,6 +82,8 @@ mod imp { /// The lines whose page is built, most recently shown first. pub(super) built: RefCell>, pub(super) highlights: RefCell>>, + /// Whether the tab's results wrap their text, from its first result on. A new run keeps it. + pub(super) wrap: Cell>, } #[glib::object_subclass] @@ -301,6 +305,10 @@ impl ResultsPane { } imp.stack.set_visible_child_name(&page_name(index)); let grid = imp.built.borrow().front().and_then(|kept| kept.grid.clone()); + // A page kept from before the tab's last toggle. + if let (Some(grid), Some(wraps)) = (&grid, imp.wrap.get()) { + grid.set_wrap_text(wraps); + } self.show_grid(grid.as_ref()); // A collapsed list covers the result it just picked. if imp.split_view.is_collapsed() { @@ -316,6 +324,24 @@ impl ResultsPane { self.imp().details_toggle.set_visible(grid.is_some()); self.imp().highlight_button.set_visible(grid.is_some()); self.imp().columns_button.set_visible(grid.is_some()); + self.imp().view_button.set_visible(grid.is_some()); + } + + /// A result's grid is built on demand, so the tab's choice lives here: + /// the first grid gives it and every later one takes it. + fn share_wrap(&self, grid: &DataGrid) { + let imp = self.imp(); + match imp.wrap.get() { + Some(wraps) => grid.set_wrap_text(wraps), + None => imp.wrap.set(Some(grid.wraps_text())), + } + let weak = self.downgrade(); + grid.actions() + .connect_action_state_changed(Some("wrap-text"), move |_, _, state| { + if let (Some(pane), Some(wraps)) = (weak.upgrade(), state.get::()) { + pane.imp().wrap.set(Some(wraps)); + } + }); } fn remember_highlights(&self, page: &KeptPage) { @@ -346,6 +372,7 @@ impl ResultsPane { if let Some(grid) = &grid { let rules = imp.highlights.borrow_mut().remove(&index).unwrap_or_default(); grid.set_highlight_rules(rules); + self.share_wrap(grid); } imp.stack.add_named(&widget, Some(&page_name(index))); let evicted: Vec = { @@ -735,6 +762,61 @@ mod tests { assert!(pane.kept_grid(0).expect("new run").highlight_rules().is_empty()); } + #[gtk4::test] + fn wrap_text_follows_the_tab_across_results_eviction_and_a_new_run() { + use crate::ui::data_grid::test_grid::{Grid, GridSpec, named, results}; + use tablepro_core::Value; + + let pane = pane(); + pane.set_page_builder(|_| { + let fixture = Grid::build( + GridSpec::results(vec![named("status", "text", false)]), + results(&[vec![Value::Text("open".to_owned())]]), + ); + fixture.window.set_child(None::<>k4::Widget>); + let grid = fixture.grid.clone(); + Some(ResultPage { + widget: grid.clone().upcast(), + grid: Some(grid), + }) + }); + pane.append(&vec![command(); 10]); + assert!(pane.imp().view_button.is_visible()); + let first = pane.kept_grid(0).expect("first result"); + assert!(!first.wraps_text(), "a result wraps by default"); + + first.set_wrap_text(true); + pane.select(1); + assert!( + pane.kept_grid(1).expect("second result").wraps_text(), + "a result built after the toggle does not wrap" + ); + for index in 2..10 { + pane.select(index); + } + assert!(pane.kept_grid(0).is_none()); + pane.select(0); + assert!(pane.kept_grid(0).expect("restored result").wraps_text()); + pane.rebuild_page(0); + assert!(pane.kept_grid(0).expect("rebuilt result").wraps_text()); + + pane.kept_grid(0).expect("rebuilt result").set_wrap_text(false); + pane.select(9); + assert!( + !pane.kept_grid(9).expect("kept result").wraps_text(), + "a page kept from before the toggle still wraps" + ); + + pane.kept_grid(9).expect("kept result").set_wrap_text(true); + pane.clear(); + assert!(!pane.imp().view_button.is_visible()); + pane.append(&[command()]); + assert!( + pane.kept_grid(0).expect("new run").wraps_text(), + "a new run forgot the tab's choice" + ); + } + #[gtk4::test] fn going_back_to_a_recent_result_keeps_its_page() { let pane = pane(); diff --git a/linux/crates/app/src/ui/key_tab/mod.rs b/linux/crates/app/src/ui/key_tab/mod.rs index e1dd714965..4047c5c63b 100644 --- a/linux/crates/app/src/ui/key_tab/mod.rs +++ b/linux/crates/app/src/ui/key_tab/mod.rs @@ -276,6 +276,7 @@ fn key_grid(key: &str, settings: Rc, tasks: Tasks) -> DataGrid { find: true, filter_by_value: false, share: false, + wrap_text: false, tasks, label: key.to_owned(), }); diff --git a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs index c528b1acff..92132bca9f 100644 --- a/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs +++ b/linux/crates/app/src/ui/preferences_dialog/data_browser_group.rs @@ -36,6 +36,8 @@ mod imp { #[template_child] pub invisibles_row: TemplateChild, #[template_child] + pub wrap_text_row: TemplateChild, + #[template_child] pub date_format_row: TemplateChild, #[template_child] pub default_sort_row: TemplateChild, @@ -138,6 +140,9 @@ impl DataBrowserGroup { gio_settings .bind(keys::SHOW_INVISIBLE_CHARACTERS, &imp.invisibles_row.get(), "active") .build(); + gio_settings + .bind(keys::GRID_WRAP_TEXT, &imp.wrap_text_row.get(), "active") + .build(); bind_choice( &imp.date_format_row.get(), gio_settings, @@ -258,6 +263,22 @@ mod tests { assert!(second.imp().invisibles_row.is_active()); } + #[gtk4::test] + fn wrap_text_switches_follow_each_other_and_external_settings() { + let settings = MemorySettings::new(); + let first = bound_group(&settings); + let second = bound_group(&settings); + assert!(!first.imp().wrap_text_row.is_active(), "wrap is on by default"); + assert_eq!(first.imp().wrap_text_row.title(), "Wrap Text"); + + first.imp().wrap_text_row.set_active(true); + assert!(settings.get().grid_wrap_text()); + assert!(second.imp().wrap_text_row.is_active()); + settings.get().set_grid_wrap_text(false).expect("store the flag"); + assert!(!first.imp().wrap_text_row.is_active()); + assert!(!second.imp().wrap_text_row.is_active()); + } + #[gtk4::test] fn the_group_is_titled_for_the_data_browser() { let settings = MemorySettings::new(); diff --git a/linux/crates/app/src/ui/result_pane/mod.rs b/linux/crates/app/src/ui/result_pane/mod.rs index be31fa900a..3c6ab0d88a 100644 --- a/linux/crates/app/src/ui/result_pane/mod.rs +++ b/linux/crates/app/src/ui/result_pane/mod.rs @@ -89,6 +89,7 @@ pub(crate) fn result_set_page( find: true, filter_by_value: false, share: true, + wrap_text: true, tasks: deps.tasks.clone(), label: name.to_owned(), }); diff --git a/linux/crates/platform/src/settings/grid_preferences.rs b/linux/crates/platform/src/settings/grid_preferences.rs index b8b034d86b..7db2cacc39 100644 --- a/linux/crates/platform/src/settings/grid_preferences.rs +++ b/linux/crates/platform/src/settings/grid_preferences.rs @@ -205,6 +205,8 @@ pub struct GridPreferenceValues { pub row_copy_format: RowCopyFormat, pub auto_show_inspector: bool, pub show_invisible_characters: bool, + /// What a new grid opens with. An open grid keeps its own. + pub wrap_text: bool, } impl Default for GridPreferenceValues { @@ -221,6 +223,7 @@ impl Default for GridPreferenceValues { row_copy_format: RowCopyFormat::Rows, auto_show_inspector: false, show_invisible_characters: true, + wrap_text: false, } } } @@ -232,6 +235,7 @@ impl GridPreferenceValues { row_copy_format: RowCopyFormat::from_nick(&settings.string(keys::ROW_COPY_FORMAT)), auto_show_inspector: settings.boolean(keys::AUTO_SHOW_INSPECTOR), show_invisible_characters: settings.boolean(keys::SHOW_INVISIBLE_CHARACTERS), + wrap_text: settings.boolean(keys::GRID_WRAP_TEXT), default_sort: DefaultSort::from_nick(&settings.string(keys::DEFAULT_SORT)), default_sort_direction: GridSortDirection::from_nick(&settings.string(keys::DEFAULT_SORT_DIRECTION)), show_row_numbers: settings.boolean(keys::SHOW_ROW_NUMBERS), @@ -317,6 +321,7 @@ impl GridPreferences { | keys::ROW_COPY_FORMAT | keys::AUTO_SHOW_INSPECTOR | keys::SHOW_INVISIBLE_CHARACTERS + | keys::GRID_WRAP_TEXT ) && let Some(preferences) = weak.upgrade() { preferences.update(GridPreferenceValues::read(settings)); diff --git a/linux/crates/platform/src/settings/keys.rs b/linux/crates/platform/src/settings/keys.rs index 36d9b8e7a7..a2c2e18904 100644 --- a/linux/crates/platform/src/settings/keys.rs +++ b/linux/crates/platform/src/settings/keys.rs @@ -16,6 +16,7 @@ pub const AUTO_SHOW_INSPECTOR: &str = "auto-show-inspector"; pub const DEFAULT_SORT: &str = "default-sort"; pub const DEFAULT_SORT_DIRECTION: &str = "default-sort-direction"; pub const SHOW_INVISIBLE_CHARACTERS: &str = "show-invisible-characters"; +pub const GRID_WRAP_TEXT: &str = "grid-wrap-text"; pub const DATE_FORMAT: &str = "date-format"; pub const ROW_COPY_FORMAT: &str = "row-copy-format"; pub const STYLE_SCHEME: &str = "style-scheme"; diff --git a/linux/crates/platform/src/settings/mod.rs b/linux/crates/platform/src/settings/mod.rs index 5d7c96e2a6..a54fc8c846 100644 --- a/linux/crates/platform/src/settings/mod.rs +++ b/linux/crates/platform/src/settings/mod.rs @@ -149,6 +149,14 @@ impl AppSettings { self.set_boolean(keys::SHOW_INVISIBLE_CHARACTERS, show) } + pub fn grid_wrap_text(&self) -> bool { + self.grid_preferences().snapshot().wrap_text + } + + pub fn set_grid_wrap_text(&self, wrap: bool) -> Result<(), SettingsError> { + self.set_boolean(keys::GRID_WRAP_TEXT, wrap) + } + pub fn date_format(&self) -> DateFormat { self.grid_preferences().snapshot().date_format } diff --git a/linux/crates/platform/tests/settings.rs b/linux/crates/platform/tests/settings.rs index ad95e06c84..a69a6c92fe 100644 --- a/linux/crates/platform/tests/settings.rs +++ b/linux/crates/platform/tests/settings.rs @@ -654,6 +654,31 @@ async fn invisible_characters_preference_uses_the_shared_snapshot_and_external_u Ok(()) } +#[glib::async_test] +async fn wrap_text_is_off_by_default_and_follows_the_shared_snapshot_and_external_updates() -> TestResult { + use gio::prelude::SettingsExt; + use std::cell::RefCell; + use std::rc::Rc; + + let fixture = Fixture::new()?; + let preferences = fixture.settings.grid_preferences(); + let original = preferences.snapshot(); + let observed = Rc::new(RefCell::new(Vec::new())); + let changes = observed.clone(); + preferences.connect_changed(move |preferences| { + changes.borrow_mut().push(preferences.snapshot().wrap_text); + }); + assert!(!fixture.settings.grid_wrap_text()); + + fixture.settings.set_grid_wrap_text(true)?; + assert!(fixture.settings.grid_wrap_text()); + fixture.settings.gio().set_boolean(keys::GRID_WRAP_TEXT, false)?; + assert!(!fixture.settings.grid_wrap_text()); + assert_eq!(observed.borrow().as_slice(), &[true, false]); + assert!(!original.wrap_text); + Ok(()) +} + #[glib::async_test] async fn date_format_publishes_all_choices_without_changing_other_backends() -> TestResult { use gio::prelude::SettingsExt; diff --git a/linux/data/app.tablepro.TablePro.gschema.xml.in b/linux/data/app.tablepro.TablePro.gschema.xml.in index 53d0504ee4..edcf396611 100644 --- a/linux/data/app.tablepro.TablePro.gschema.xml.in +++ b/linux/data/app.tablepro.TablePro.gschema.xml.in @@ -143,6 +143,12 @@ Whether cells and value fields mark zero-width, control and special space characters. + + false + Wrap text in data grids + Show long values on several lines in a data grid, up to 10 lines per row. Applies to tabs opened afterwards. + + diff --git a/linux/data/resources/ui/preferences-data-browser-group.ui b/linux/data/resources/ui/preferences-data-browser-group.ui index 280989f6b4..1e4e356a84 100644 --- a/linux/data/resources/ui/preferences-data-browser-group.ui +++ b/linux/data/resources/ui/preferences-data-browser-group.ui @@ -55,6 +55,12 @@ Mark zero-width, control and special space characters in cells and value fields + + + Wrap Text + New tabs show long values on up to 10 lines + + Date Format diff --git a/linux/data/resources/ui/results-pane.ui b/linux/data/resources/ui/results-pane.ui index 3c3640cf6e..9f3bdde7d0 100644 --- a/linux/data/resources/ui/results-pane.ui +++ b/linux/data/resources/ui/results-pane.ui @@ -2,6 +2,14 @@ + +
+ + _Wrap Text + grid.wrap-text + +
+