diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Extensions/CTTypesetter+SuggestLineBreak.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Extensions/CTTypesetter+SuggestLineBreak.swift index 25bb4b80fb..e2fea1bde9 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Extensions/CTTypesetter+SuggestLineBreak.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Extensions/CTTypesetter+SuggestLineBreak.swift @@ -1,20 +1,7 @@ -// -// CTTypesetter+SuggestLineBreak.swift -// TableProTextEngine -// -// Created by Khan Winter on 4/24/25. -// - import AppKit extension CTTypesetter { - /// Suggest a line break for the given line break strategy. - /// - Parameters: - /// - typesetter: The typesetter to use. - /// - strategy: The strategy that determines a valid line break. - /// - startingOffset: Where to start breaking. - /// - constrainingWidth: The available space for the line. - /// - Returns: An offset relative to the entire string indicating where to break. + // Returns an offset into the whole string, not a length. func suggestLineBreak( using string: NSAttributedString, strategy: LineBreakStrategy, @@ -37,20 +24,12 @@ extension CTTypesetter { } } - /// Suggest a line break for the character break strategy. - /// - Parameters: - /// - typesetter: The typesetter to use. - /// - startingOffset: Where to start breaking. - /// - constrainingWidth: The available space for the line. - /// - Returns: An offset relative to the entire string indicating where to break. private func suggestLineBreakForCharacter( string: NSAttributedString, startingOffset: Int, constrainingWidth: CGFloat ) -> Int { var breakIndex: Int - // Check if we need to skip to an attachment - breakIndex = startingOffset + CTTypesetterSuggestClusterBreak(self, startingOffset, constrainingWidth) guard breakIndex < string.length else { return breakIndex @@ -64,12 +43,6 @@ extension CTTypesetter { return breakIndex } - /// Suggest a line break for the word break strategy. - /// - Parameters: - /// - typesetter: The typesetter to use. - /// - startingOffset: Where to start breaking. - /// - constrainingWidth: The available space for the line. - /// - Returns: An offset relative to the entire string indicating where to break. private func suggestLineBreakForWord( string: NSAttributedString, subrange: NSRange, @@ -79,11 +52,12 @@ extension CTTypesetter { if breakIndex >= subrange.max { return breakIndex } - if checkIfLineBreakOnCRLF(breakIndex, for: string) { + let text = string.string as NSString + if LineBreakCharacters.isCRLF(endingAt: breakIndex, in: text) { return breakIndex + 1 } - let hangingEnd = endOfHangingSpaces(from: breakIndex, before: subrange.max, in: string) + let hangingEnd = endOfHangingSpaces(from: breakIndex, before: subrange.max, in: text) if hangingEnd > breakIndex { return hangingEnd } @@ -101,7 +75,7 @@ extension CTTypesetter { // breaks after the nearest punctuation rather than mid-word. var index = breakIndex - 1 while breakIndex - index < 100 && index > subrange.location { - if ensureCharacterCanBreakLine(at: index, for: string) { + if LineBreakCharacters.canBreakLine(at: index, in: text) { return index + 1 } index -= 1 @@ -110,9 +84,8 @@ extension CTTypesetter { return breakIndex } - /// Spaces and tabs past the edge stay on the line they follow instead of opening the next one. - private func endOfHangingSpaces(from index: Int, before end: Int, in string: NSAttributedString) -> Int { - let text = string.string as NSString + // Spaces and tabs past the edge stay on the line they follow instead of opening the next one. + private func endOfHangingSpaces(from index: Int, before end: Int, in text: NSString) -> Int { var hangingEnd = index while hangingEnd < end { let character = text.character(at: hangingEnd) @@ -121,26 +94,28 @@ extension CTTypesetter { } return hangingEnd } +} - /// Ensures the character at the given index can break a line. - /// - Parameter index: The index to check at. - /// - Returns: True, if the character is a whitespace or punctuation character. - private func ensureCharacterCanBreakLine(at index: Int, for string: NSAttributedString) -> Bool { - let subrange = (string.string as NSString).rangeOfComposedCharacterSequence(at: index) - let set = CharacterSet(charactersIn: (string.string as NSString).substring(with: subrange)) - return set.isSubset(of: .whitespacesAndNewlines) || set.isSubset(of: .punctuationCharacters) - } +enum LineBreakCharacters { + private static let whitespace = CharacterSet.whitespacesAndNewlines + private static let punctuation = CharacterSet.punctuationCharacters - /// Check if the break index is on a CRLF (`\r\n`) character, indicating a valid break position. - /// - Parameter breakIndex: The index to check in the string. - /// - Returns: True, if the break index lies after the `\n` character in a `\r\n` sequence. - private func checkIfLineBreakOnCRLF(_ breakIndex: Int, for string: NSAttributedString) -> Bool { - guard breakIndex - 1 > 0 && breakIndex + 1 <= string.length else { + // True when the composed sequence at `index` is all whitespace or all punctuation. A unit that is a whole + // scalar in neither set already rules its sequence out, so a letter or digit costs no substring. + static func canBreakLine(at index: Int, in text: NSString) -> Bool { + let unit = text.character(at: index) + if !UTF16.isLeadSurrogate(unit), !UTF16.isTrailSurrogate(unit), let scalar = Unicode.Scalar(unit), + !whitespace.contains(scalar), !punctuation.contains(scalar) { return false } - let substringRange = NSRange(location: breakIndex - 1, length: 2) - let substring = string.attributedSubstring(from: substringRange).string + let scalars = text.substring(with: text.rangeOfComposedCharacterSequence(at: index)).unicodeScalars + return scalars.allSatisfy { whitespace.contains($0) } || scalars.allSatisfy { punctuation.contains($0) } + } - return substring == LineEnding.carriageReturnLineFeed.rawValue + static func isCRLF(endingAt breakIndex: Int, in text: NSString) -> Bool { + guard breakIndex - 1 > 0 && breakIndex + 1 <= text.length else { + return false + } + return text.character(at: breakIndex - 1) == 0x0D && text.character(at: breakIndex) == 0x0A } } diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/TypesetterWordBreakTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/TypesetterWordBreakTests.swift index cf07d32edc..9ff7cd72ae 100644 --- a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/TypesetterWordBreakTests.swift +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/TypesetterWordBreakTests.swift @@ -1,8 +1,3 @@ -// -// TypesetterWordBreakTests.swift -// TableProTextEngineTests -// - import AppKit import Foundation @testable import TableProTextEngine @@ -15,7 +10,7 @@ struct TypesetterWordBreakTests { .font: NSFont.monospacedSystemFont(ofSize: 12, weight: .regular) ] - /// The text of each wrapped fragment when a line is `columns` characters wide. + // The text of each wrapped fragment when a line is `columns` characters wide. private func fragments(_ text: String, columns: Int) -> [String] { let characterWidth = ("x" as NSString).size(withAttributes: Self.attributes).width let length = (text as NSString).length @@ -83,4 +78,99 @@ struct TypesetterWordBreakTests { #expect(wrapped.joined() == text) #expect((wrapped.first?.count ?? 0) > "日本語。".count) } + + @Test("A run with no punctuation in reach breaks at the edge") + func unbreakableRunBreaksAtTheEdge() { + let run = String(repeating: "a", count: 300) + #expect(fragments(run, columns: 120).map { $0.count } == [120, 120, 60]) + } + + @Test("Punctuation 99 characters back from the edge is in reach, 100 back is not") + func punctuationSearchReachesBack99Characters() { + func run(underscoreAt offset: Int) -> String { + var characters = Array(repeating: "a", count: 300) + characters[offset] = "_" + return characters.joined() + } + + #expect(fragments(run(underscoreAt: 21), columns: 120).first?.count == 22) + #expect(fragments(run(underscoreAt: 20), columns: 120).first?.count == 120) + } + + // The search walks back from the edge to one past the fragment's start, which here is the low surrogate. + @Test("Supplementary punctuation whose low surrogate is the last offset searched still breaks after it") + func supplementaryPunctuationAtTheSearchsEnd() { + let text = "\u{1E95E}" + String(repeating: "a", count: 200) + #expect(fragments(text, columns: 30).first == "\u{1E95E}") + } + + @Test("The break test answers what the composed-sequence rule answers, at every offset of 2,000 strings") + func breakTestMatchesTheComposedSequenceRule() { + var generator = SplitMix64(seed: 0x5EED_1E55) + var mismatches: [String] = [] + for _ in 0..<2_000 { + let text = Self.generatedText(using: &generator) + let reference = NSAttributedString(string: text as String) + for index in 0.. Bool { + let subrange = (string.string as NSString).rangeOfComposedCharacterSequence(at: index) + let set = CharacterSet(charactersIn: (string.string as NSString).substring(with: subrange)) + return set.isSubset(of: .whitespacesAndNewlines) || set.isSubset(of: .punctuationCharacters) + } + + private static func referenceIsCRLF(_ breakIndex: Int, for string: NSAttributedString) -> Bool { + guard breakIndex - 1 > 0 && breakIndex + 1 <= string.length else { + return false + } + return string.attributedSubstring(from: NSRange(location: breakIndex - 1, length: 2)).string == "\r\n" + } + + private static let pieces: [[unichar]] = { + let strings = [ + "a", "Z", "x9", "0", "_", ".", ",", "-", "(", ")", "\"", "'", "/", ":", ";", "!", "?", "#", "%", "&", "*", "@", + "[", "]", "{", "}", "\\", "$", "+", "<", "=", ">", "^", "`", "|", "~", + " ", "\t", "\n", "\r", "\r\n", "\u{00A0}", "\u{3000}", "\u{200B}", "\u{2028}", "\u{0085}", + ".\u{0301}", ",\u{20DD}", "_\u{0308}", " \u{0301}", "\u{0301}", "\u{0600}1", "\u{0600}.", + "😀", "👩‍💻", "👍🏽", "🇻🇳", "1\u{FE0F}\u{20E3}", "日本", "。", "、", "「", "」", "ー", "\u{1100}\u{1161}", + "\u{10100}", "\u{1039F}", "\u{1E95E}", "\u{12470}", "\u{1D400}", "\u{20000}", + ] + return strings.map { Array($0.utf16) } + [[0xD800], [0xDC00], [0xDBFF, 0x41], [0x2E, 0xDC00]] + }() + + private static func generatedText(using generator: inout SplitMix64) -> NSString { + var units: [unichar] = [] + let count = Int.random(in: 1...24, using: &generator) + for _ in 0.. UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var value = state + value = (value ^ (value >> 30)) &* 0xBF58_476D_1CE4_E5B9 + value = (value ^ (value >> 27)) &* 0x94D0_49BB_1331_11EB + return value ^ (value >> 31) + } } diff --git a/apple/TablePro/Core/Services/Formatting/JsonReindenter.swift b/apple/TablePro/Core/Services/Formatting/JsonReindenter.swift index c6e40a8bb1..39df751de5 100644 --- a/apple/TablePro/Core/Services/Formatting/JsonReindenter.swift +++ b/apple/TablePro/Core/Services/Formatting/JsonReindenter.swift @@ -1,20 +1,15 @@ -// -// JsonReindenter.swift -// TablePro -// - import Foundation +import TableProEditorKit internal enum JsonReindenter { - private static let maxLength = 500_000 + // The editor's own ceiling: past it the editor drops colors and folding, so indented text stops there too. + private static let maxLength = EditorHighlighting.maxHighlightableCharacters private static let defaultIndent = " " + // Nil for invalid JSON, and for valid JSON whose indented text would pass the editor's ceiling. static func reindentIfValid(_ source: String, indent: String = defaultIndent) -> String? { guard (source as NSString).length <= maxLength else { return nil } - guard let node = JsonSyntaxParser.parse(source) else { return nil } - var output = "" - writePretty(node, into: &output, indent: indent, depth: 0) - return output + return JsonLayoutWriter.write(source, indent: Array(indent.utf8), maximumLength: maxLength) } static func reindent(_ source: String, indent: String = defaultIndent) -> String { @@ -24,72 +19,243 @@ internal enum JsonReindenter { // An edit keeps the stored value's layout: a value stored on one line stays compact, a formatted one takes the // editor's lines rather than losing every line break. static func staged(_ edited: String, keepingLayoutOf stored: String?) -> String { - guard let stored, stored.trimmingCharacters(in: .whitespacesAndNewlines).contains(where: \.isNewline) else { - return normalize(edited) - } - return edited + keepsLayout(of: stored) ? edited : normalize(edited) + } + + // For a caller that already holds `normalize(edited)`. + static func staged(_ edited: String, compact: String, keepingLayoutOf stored: String?) -> String { + keepsLayout(of: stored) ? edited : compact } static func normalize(_ source: String) -> String { guard (source as NSString).length <= maxLength else { return source } - guard let node = JsonSyntaxParser.parse(source) else { return source } - var output = "" - writeCompact(node, into: &output) - return output - } - - private static func writePretty(_ node: JsonSyntaxNode, into output: inout String, indent: String, depth: Int) { - switch node { - case .string(let raw), .number(let raw), .literal(let raw): - output += raw - case .object(let pairs): - guard !pairs.isEmpty else { - output += "{}" - return + return JsonLayoutWriter.write(source, indent: nil, maximumLength: .max) ?? source + } + + private static func keepsLayout(of stored: String?) -> Bool { + guard let stored else { return false } + return stored.trimmingCharacters(in: .whitespacesAndNewlines).contains(where: \.isNewline) + } +} + +// Writes a document indented or compact in one pass over its UTF-8, with no node tree. It accepts exactly what +// `JsonSyntaxParser` accepts: ASCII whitespace, lax numbers, 512 levels, nothing after the value, strings copied as +// written. A backslash skips one byte here and one scalar there, which agree because a UTF-8 continuation byte is +// never a quote or a backslash. +private struct JsonLayoutWriter { + private static let maxDepth = 512 + + private let source: UnsafeBufferPointer + private let indent: [UInt8]? + private let indentLength: Int + private let maximumLength: Int + private var index = 0 + private var depth = 0 + private var output: [UInt8] = [] + // UTF-16 units written, the unit `maximumLength` counts in. + private var written = 0 + + static func write(_ source: String, indent: [UInt8]?, maximumLength: Int) -> String? { + var source = source + source.makeContiguousUTF8() + let result = source.utf8.withContiguousStorageIfAvailable { bytes in + var writer = JsonLayoutWriter(source: bytes, indent: indent, maximumLength: maximumLength) + return writer.run() + } + if let result { + return result + } + return Array(source.utf8).withUnsafeBufferPointer { bytes in + var writer = JsonLayoutWriter(source: bytes, indent: indent, maximumLength: maximumLength) + return writer.run() + } + } + + private init(source: UnsafeBufferPointer, indent: [UInt8]?, maximumLength: Int) { + self.source = source + self.indent = indent + self.indentLength = indent.map { Self.utf16Length(of: $0[...]) } ?? 0 + self.maximumLength = maximumLength + output.reserveCapacity(indent == nil ? source.count : source.count + source.count / 2) + } + + private mutating func run() -> String? { + skipWhitespace() + guard writeValue() else { return nil } + skipWhitespace() + guard index == source.count, written <= maximumLength else { return nil } + return String(decoding: output, as: UTF8.self) // swiftlint:disable:this optional_data_string_conversion + } + + private mutating func writeValue() -> Bool { + guard index < source.count, written <= maximumLength else { return false } + switch source[index] { + case UInt8(ascii: "{"): return writeContainer(closing: UInt8(ascii: "}"), hasKeys: true) + case UInt8(ascii: "["): return writeContainer(closing: UInt8(ascii: "]"), hasKeys: false) + case UInt8(ascii: "\""): return copyString() + case UInt8(ascii: "t"), UInt8(ascii: "f"), UInt8(ascii: "n"): return copyLiteral() + default: return copyNumber() + } + } + + private mutating func writeContainer(closing: UInt8, hasKeys: Bool) -> Bool { + guard depth < Self.maxDepth else { return false } + depth += 1 + defer { depth -= 1 } + let opening = source[index] + index += 1 + skipWhitespace() + if index < source.count, source[index] == closing { + index += 1 + append(opening) + append(closing) + return true + } + append(opening) + var isFirst = true + while true { + skipWhitespace() + if !isFirst { + append(UInt8(ascii: ",")) } - output += "{\n" - let childPad = String(repeating: indent, count: depth + 1) - for (offset, pair) in pairs.enumerated() { - output += childPad + pair.key + ": " - writePretty(pair.value, into: &output, indent: indent, depth: depth + 1) - output += offset == pairs.count - 1 ? "\n" : ",\n" + isFirst = false + appendLineBreak(depth: depth) + if hasKeys { + guard index < source.count, source[index] == UInt8(ascii: "\""), copyString() else { return false } + skipWhitespace() + guard index < source.count, source[index] == UInt8(ascii: ":") else { return false } + index += 1 + append(UInt8(ascii: ":")) + if indent != nil { + append(UInt8(ascii: " ")) + } + skipWhitespace() } - output += String(repeating: indent, count: depth) + "}" - case .array(let elements): - guard !elements.isEmpty else { - output += "[]" - return + guard writeValue() else { return false } + skipWhitespace() + guard index < source.count else { return false } + if source[index] == UInt8(ascii: ",") { + index += 1 + continue + } + if source[index] == closing { + index += 1 + appendLineBreak(depth: depth - 1) + append(closing) + return true + } + return false + } + } + + private mutating func copyString() -> Bool { + let start = index + index += 1 + while index < source.count { + let byte = source[index] + if byte == UInt8(ascii: "\\") { + index += 2 + continue } - output += "[\n" - let childPad = String(repeating: indent, count: depth + 1) - for (offset, element) in elements.enumerated() { - output += childPad - writePretty(element, into: &output, indent: indent, depth: depth + 1) - output += offset == elements.count - 1 ? "\n" : ",\n" + if byte == UInt8(ascii: "\"") { + index += 1 + copy(from: start) + return true } - output += String(repeating: indent, count: depth) + "]" + index += 1 } + return false } - private static func writeCompact(_ node: JsonSyntaxNode, into output: inout String) { - switch node { - case .string(let raw), .number(let raw), .literal(let raw): - output += raw - case .object(let pairs): - output += "{" - for (offset, pair) in pairs.enumerated() { - output += pair.key + ":" - writeCompact(pair.value, into: &output) - if offset != pairs.count - 1 { output += "," } + private mutating func copyNumber() -> Bool { + let start = index + if index < source.count, source[index] == UInt8(ascii: "-") { index += 1 } + guard consumeDigits() else { return false } + if index < source.count, source[index] == UInt8(ascii: ".") { + index += 1 + guard consumeDigits() else { return false } + } + if index < source.count, source[index] == UInt8(ascii: "e") || source[index] == UInt8(ascii: "E") { + index += 1 + if index < source.count, source[index] == UInt8(ascii: "+") || source[index] == UInt8(ascii: "-") { + index += 1 } - output += "}" - case .array(let elements): - output += "[" - for (offset, element) in elements.enumerated() { - writeCompact(element, into: &output) - if offset != elements.count - 1 { output += "," } + guard consumeDigits() else { return false } + } + copy(from: start) + return true + } + + private mutating func consumeDigits() -> Bool { + guard index < source.count, Self.isDigit(source[index]) else { return false } + while index < source.count, Self.isDigit(source[index]) { index += 1 } + return true + } + + private mutating func copyLiteral() -> Bool { + let literal: [UInt8] + switch source[index] { + case UInt8(ascii: "t"): literal = Self.trueBytes + case UInt8(ascii: "f"): literal = Self.falseBytes + default: literal = Self.nullBytes + } + guard matches(literal) else { return false } + let start = index + index += literal.count + copy(from: start) + return true + } + + private static let trueBytes = Array("true".utf8) + private static let falseBytes = Array("false".utf8) + private static let nullBytes = Array("null".utf8) + + private func matches(_ literal: [UInt8]) -> Bool { + guard index + literal.count <= source.count else { return false } + for offset in literal.indices where source[index + offset] != literal[offset] { + return false + } + return true + } + + private mutating func skipWhitespace() { + while index < source.count { + switch source[index] { + case UInt8(ascii: " "), UInt8(ascii: "\t"), UInt8(ascii: "\n"), UInt8(ascii: "\r"): index += 1 + default: return } - output += "]" } } + + private mutating func append(_ byte: UInt8) { + output.append(byte) + written += 1 + } + + private mutating func appendLineBreak(depth: Int) { + guard let indent else { return } + append(UInt8(ascii: "\n")) + for _ in 0..(of bytes: Bytes) -> Int where Bytes.Element == UInt8 { + var length = 0 + for byte in bytes where byte & 0xC0 != 0x80 { + length += byte >= 0xF0 ? 2 : 1 + } + return length + } + + private static func isDigit(_ byte: UInt8) -> Bool { + byte >= UInt8(ascii: "0") && byte <= UInt8(ascii: "9") + } } diff --git a/apple/TablePro/Core/Utilities/SQL/JsonRowConverter.swift b/apple/TablePro/Core/Utilities/SQL/JsonRowConverter.swift index ddfa831950..4e3f81c47d 100644 --- a/apple/TablePro/Core/Utilities/SQL/JsonRowConverter.swift +++ b/apple/TablePro/Core/Utilities/SQL/JsonRowConverter.swift @@ -1,8 +1,3 @@ -// -// JsonRowConverter.swift -// TablePro -// - import Foundation import TableProPluginKit @@ -10,9 +5,10 @@ internal struct JsonRowConverter { internal let columns: [String] internal let columnTypes: [ColumnType] - private static let maxRows = 50_000 + static let maxRows = 50_000 - func generateJson(rows: [[PluginCellValue]]) -> String { + // A cancelled call stops within 256 rows and returns what it wrote, which the caller drops. + func generateJson(rows: [[PluginCellValue]], isCancelled: () -> Bool = { false }) -> String { let cappedRows = rows.prefix(Self.maxRows) let rowCount = cappedRows.count @@ -21,11 +17,12 @@ internal struct JsonRowConverter { } var result = String() - result.reserveCapacity(rowCount * columns.count * 100) - result.append("[\n") for (rowIdx, row) in cappedRows.enumerated() { + if rowIdx & 255 == 0, isCancelled() { + return result + } result.append(" {\n") for (colIdx, column) in columns.enumerated() { @@ -121,13 +118,10 @@ internal struct JsonRowConverter { var iter = scalars.makeIterator() guard var ch = iter.next() else { return false } - // Optional leading minus if ch == "-" { guard let next = iter.next() else { return false }; ch = next } - // Integer part: "0" or [1-9][0-9]* guard ch >= "0" && ch <= "9" else { return false } if ch == "0" { - // "0" must not be followed by another digit if let next = iter.next() { ch = next } else { return true } } else { while true { @@ -137,7 +131,6 @@ internal struct JsonRowConverter { } } - // Optional fractional part if ch == "." { guard let next = iter.next(), next >= "0" && next <= "9" else { return false } while true { @@ -147,7 +140,6 @@ internal struct JsonRowConverter { } } - // Optional exponent if ch == "e" || ch == "E" { guard var next = iter.next() else { return false } if next == "+" || next == "-" { @@ -159,7 +151,7 @@ internal struct JsonRowConverter { guard remaining >= "0" && remaining <= "9" else { return false } } } else { - return false // Unexpected trailing character + return false } return true diff --git a/apple/TablePro/Core/Utilities/SQL/ResultJsonSerializer.swift b/apple/TablePro/Core/Utilities/SQL/ResultJsonSerializer.swift index 1bb897caff..41ff2bcd38 100644 --- a/apple/TablePro/Core/Utilities/SQL/ResultJsonSerializer.swift +++ b/apple/TablePro/Core/Utilities/SQL/ResultJsonSerializer.swift @@ -1,43 +1,30 @@ -// -// ResultJsonSerializer.swift -// TablePro -// - import Foundation import TableProPluginKit -/// The one place a result set becomes JSON. -/// -/// The results pane's JSON view and the grid's Copy as JSON render the same rows, so they share -/// this rather than each deciding for itself which rows and columns to include. Both follow the -/// grid as shown: display order, no hidden columns, current column order. -/// -/// They part company on pending deletions, because they answer different questions. The JSON view -/// shows what a Save would leave behind, so it excludes rows marked for deletion; a JSON document -/// has no way to mark one, and leaving it in is what made a delete look like it did nothing. Copy -/// as JSON copies the rows you selected, the same as every other Copy as, so it passes no deletions -/// and keeps them all. +// The JSON view and Copy as JSON render the same rows, as the grid shows them: display order, no hidden columns, +// current column order. The view leaves out rows marked for deletion, since it shows what a Save leaves behind and a +// document cannot mark a row; Copy as JSON passes no deletions, like every other Copy as. internal enum ResultJsonSerializer { internal struct Output { let json: String + // Rows in the document, which stops at `JsonRowConverter.maxRows`. let rowCount: Int - /// How many rows were left out because they are marked for deletion. Counted here rather - /// than derived by the caller, so the disclosure can never claim a row was held back that - /// was not in the document to begin with. + // Counted here, so the disclosure never names a row that was not in the document to begin with. let skippedDeletedCount: Int + // The converter writes the two-space layout itself. Only a JSON column's raw text, or a row with no columns + // (written `{` and `}` on two lines), can differ from it. + let isIndented: Bool } - /// - Parameter selectedDisplayIndices: display positions to narrow to. Empty means every - /// displayed row, which is what an untouched result set shows. - /// - Parameter deletedRowIDs: rows marked for deletion but not yet saved. - /// Empty, the default, serialises every row. + // Empty selectedDisplayIndices means every displayed row; empty deletedRowIDs keeps every row. internal static func serialize( tableRows: TableRows, displayIDs: [RowID]?, selectedDisplayIndices: Set, deletedRowIDs: Set = [], defaultedCells: [RowID: Set] = [:], - columns projection: VisibleColumnProjection + columns projection: VisibleColumnProjection, + isCancelled: () -> Bool = { false } ) -> Output { let read = DisplayedResultReader.read( tableRows: tableRows, @@ -50,19 +37,17 @@ internal enum ResultJsonSerializer { let converter = JsonRowConverter(columns: read.columns, columnTypes: read.columnTypes) return Output( - json: converter.generateJson(rows: read.rows), - rowCount: read.rows.count, - skippedDeletedCount: read.skippedDeletedCount + json: converter.generateJson(rows: read.rows, isCancelled: isCancelled), + rowCount: min(read.rows.count, JsonRowConverter.maxRows), + skippedDeletedCount: read.skippedDeletedCount, + isIndented: !read.columns.isEmpty && !read.columnTypes.contains { $0.isJsonType } ) } } internal extension VisibleColumnProjection { - /// Builds a projection from the layout the user arranged in the grid. - /// - /// Reads the persisted layout rather than the live `NSTableView` columns, because the grid is - /// not mounted while the results pane is showing JSON. Duplicate column names cannot be mapped - /// back to a single index, so a result with duplicates keeps every column. + // From the saved layout, not the live columns: the grid is not mounted while the pane shows JSON. Duplicate names + // cannot map back to one index, so a result with duplicates keeps every column. static func fromColumnLayout(_ layout: ColumnLayoutState, columns: [String]) -> VisibleColumnProjection { guard Set(columns).count == columns.count else { return .identity } guard !layout.hiddenColumns.isEmpty || layout.columnOrder != nil else { return .identity } diff --git a/apple/TablePro/Models/UI/JsonFieldEditingModel.swift b/apple/TablePro/Models/UI/JsonFieldEditingModel.swift index bbf7ffe86f..9a86dc8752 100644 --- a/apple/TablePro/Models/UI/JsonFieldEditingModel.swift +++ b/apple/TablePro/Models/UI/JsonFieldEditingModel.swift @@ -1,30 +1,12 @@ -// -// JsonFieldEditingModel.swift -// TablePro -// - import Foundation -/// The editing model behind the row inspector's JSON field: what the editor shows, and when that -/// text and the stored value have to be reconciled. -/// -/// It lives outside the view because the defect it exists to prevent is a fixpoint between two -/// mirrors of one value, and a fixpoint is only testable if it can be driven without a window. -/// -/// The rule is ``lastSynced``: the editor's text and the stored value are known to agree at that -/// string, so a value arriving from the store that still means the same thing is this editor's own -/// write coming back and is ignored. A value stored on one line is staged compacted, so the two agree -/// in meaning rather than in bytes, and a comparison against the editor's displayed text cannot tell -/// an echo from an external change on its own. -/// -/// Adopting an echo is what let a keystroke be overwritten by the value it had just replaced, and -/// then pushed back, forever: one keystroke produced 6,944 body evaluations in 30 seconds at 100% -/// CPU, and the typed character was discarded (#3051). +// The inspector JSON field's text and the stored value are two mirrors of one value. They agree at `lastSynced`, so +// a value from the store that still means the same thing is this editor's own write coming back and is ignored. +// Adopting that echo overwrote a keystroke with the value it replaced and pushed it back, forever (#3051). internal struct JsonFieldEditingModel: Equatable, Sendable { private(set) var displayText: String - /// The last text the editor published, in display form. Never the stored form, which has been - /// through `JsonReindenter.normalize` and would compare unequal to everything the editor holds. + // In display form: the stored form went through `JsonReindenter.normalize` and never equals what the editor holds. private var lastSynced: String internal init(storedValue: String) { @@ -33,28 +15,27 @@ internal struct JsonFieldEditingModel: Equatable, Sendable { self.lastSynced = opening } - /// The user typed. Returns the value to write into the field's binding, or nil when the text - /// already agrees with the store and writing it would only start another round. + // Nil when the text already agrees with the store and writing it would only start another round. internal mutating func typed(_ text: String) -> String? { displayText = text - guard text != lastSynced else { return nil } + guard !Self.isLiterallyEqual(text, lastSynced) else { return nil } lastSynced = text return text } - /// The field's binding delivered a value. Returns whether the editor adopted it. - /// - /// Anything that still means what ``lastSynced`` means is this editor's own write coming back, - /// compacted by `MultiRowEditState` or dropped by it because the value matched the stored one - /// again. Everything else is a real external change: Set NULL, Set DEFAULT, Set EMPTY, an SQL - /// function, or a commit from the pop-out value window. - /// - /// `JsonReindenter.normalize` returns its source unchanged when the document does not parse, so - /// a half-typed value is compared exactly rather than reported equal to something else. + // Whether the editor adopted the value. One that normalizes to `lastSynced` is an echo, compacted or dropped by + // `MultiRowEditState`; anything else is external: Set NULL, Set DEFAULT, Set EMPTY, an SQL function, the value window. + // `normalize` returns invalid JSON unchanged, so a half-typed value compares exactly. internal mutating func received(_ value: String) -> Bool { - guard JsonReindenter.normalize(value) != JsonReindenter.normalize(lastSynced) else { return false } + guard !Self.isLiterallyEqual(value, lastSynced), + JsonReindenter.normalize(value) != JsonReindenter.normalize(lastSynced) else { return false } displayText = JsonReindenter.reindent(value) lastSynced = displayText return true } + + // String's == walks a bridged multi-megabyte text through Unicode normalization; the editor's text is bridged. + private static func isLiterallyEqual(_ lhs: String, _ rhs: String) -> Bool { + (lhs as NSString).isEqual(to: rhs) + } } diff --git a/apple/TablePro/Models/UI/MultiRowEditState.swift b/apple/TablePro/Models/UI/MultiRowEditState.swift index 2842465463..d81de1b523 100644 --- a/apple/TablePro/Models/UI/MultiRowEditState.swift +++ b/apple/TablePro/Models/UI/MultiRowEditState.swift @@ -1,8 +1,3 @@ -// -// MultiRowEditState.swift -// TablePro -// - import Combine import Foundation import TableProPluginKit @@ -475,10 +470,11 @@ final class MultiRowEditState: ObservableObject { private static func resolvePendingValue(_ value: String?, original: String?, isJson: Bool) -> String? { if isJson, let value, !value.isEmpty { - if let original, JsonReindenter.normalize(original) == JsonReindenter.normalize(value) { + let compact = JsonReindenter.normalize(value) + if let original, JsonReindenter.normalize(original) == compact { return nil } - return JsonReindenter.staged(value, keepingLayoutOf: original) + return JsonReindenter.staged(value, compact: compact, keepingLayoutOf: original) } if value == original || (original == nil && value == "") { return nil diff --git a/apple/TablePro/Views/Results/ResultsJsonView.swift b/apple/TablePro/Views/Results/ResultsJsonView.swift index 6a04df3448..2b014240a0 100644 --- a/apple/TablePro/Views/Results/ResultsJsonView.swift +++ b/apple/TablePro/Views/Results/ResultsJsonView.swift @@ -1,8 +1,3 @@ -// -// ResultsJsonView.swift -// TablePro -// - import SwiftUI import TableProPluginKit @@ -50,9 +45,10 @@ internal struct ResultsJsonView: View { self.columnLayout = columnLayout self._viewMode = State(initialValue: AppSettingsManager.shared.editor.jsonViewerPreferredMode) self._resolvedRowCount = State( - initialValue: selectedRowIDs.isEmpty - ? (displayIDs?.count ?? tableRows.count) - : selectedRowIDs.count + initialValue: min( + selectedRowIDs.isEmpty ? (displayIDs?.count ?? tableRows.count) : selectedRowIDs.count, + JsonRowConverter.maxRows + ) ) } @@ -210,16 +206,14 @@ internal struct ResultsJsonView: View { let defaulted = defaultedCells let layout = columnLayout - let result = await Task.detached(priority: .userInitiated) { - Self.computeJson( - tableRows: snapshot, - displayIDs: ids, - selectedIndices: selectedIndices, - deletedRowIDs: deletedIDs, - defaultedCells: defaulted, - columnLayout: layout - ) - }.value + let result = await Self.render( + tableRows: snapshot, + displayIDs: ids, + selectedIndices: selectedIndices, + deletedRowIDs: deletedIDs, + defaultedCells: defaulted, + columnLayout: layout + ) guard !Task.isCancelled else { return } cachedJson = result.json @@ -244,16 +238,42 @@ internal struct ResultsJsonView: View { let resolvedCount: Int let skippedDeletedCount: Int let parseResult: Result + + static var cancelled: RenderedJson { + RenderedJson(json: "", pretty: "", resolvedCount: 0, skippedDeletedCount: 0, parseResult: .failure(.invalidJSON)) + } } - // Same serializer as Copy as JSON. + // Off the main actor and in the caller's task, so a newer render key cancels the render it replaces. + @concurrent + nonisolated static func render( + tableRows: TableRows, + displayIDs: [RowID]?, + selectedIndices: Set, + deletedRowIDs: Set, + defaultedCells: [RowID: Set], + columnLayout: ColumnLayoutState + ) async -> RenderedJson { + computeJson( + tableRows: tableRows, + displayIDs: displayIDs, + selectedIndices: selectedIndices, + deletedRowIDs: deletedRowIDs, + defaultedCells: defaultedCells, + columnLayout: columnLayout, + isCancelled: { Task.isCancelled } + ) + } + + // Same serializer as Copy as JSON. A cancelled call returns early with an empty result the caller drops. nonisolated static func computeJson( tableRows: TableRows, displayIDs: [RowID]?, selectedIndices: Set, deletedRowIDs: Set = [], defaultedCells: [RowID: Set] = [:], - columnLayout: ColumnLayoutState + columnLayout: ColumnLayoutState, + isCancelled: () -> Bool = { false } ) -> RenderedJson { let output = ResultJsonSerializer.serialize( tableRows: tableRows, @@ -261,11 +281,15 @@ internal struct ResultsJsonView: View { selectedDisplayIndices: selectedIndices, deletedRowIDs: deletedRowIDs, defaultedCells: defaultedCells, - columns: .fromColumnLayout(columnLayout, columns: tableRows.columns) + columns: .fromColumnLayout(columnLayout, columns: tableRows.columns), + isCancelled: isCancelled ) + guard !isCancelled() else { return .cancelled } + let pretty = output.isIndented ? output.json : (output.json.prettyPrintedAsJson() ?? output.json) + guard !isCancelled() else { return .cancelled } return RenderedJson( json: output.json, - pretty: output.json.prettyPrintedAsJson() ?? output.json, + pretty: pretty, resolvedCount: output.rowCount, skippedDeletedCount: output.skippedDeletedCount, parseResult: JSONTreeDocument.parse(output.json) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift index 3b3b35a614..a69c7a4c87 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift @@ -1,8 +1,3 @@ -// -// JsonEditorView.swift -// TablePro -// - import SwiftUI internal struct JsonEditorView: View { @@ -10,25 +5,28 @@ internal struct JsonEditorView: View { var onPopOut: ((String) -> Void)? var isExpanded = false - @State private var model: JsonFieldEditingModel - @State private var openedDocument: UUID? - // Moves each time the text is replaced from outside, which gives the editor a new history. - @State private var replacements = 0 + @StateObject private var editor: JsonFieldEditor - init(context: FieldEditorContext, onPopOut: ((String) -> Void)? = nil, isExpanded: Bool = false) { + init( + context: FieldEditorContext, + onPopOut: ((String) -> Void)? = nil, + isExpanded: Bool = false, + makeEditor: @escaping @MainActor (String, UUID?) -> JsonFieldEditor = JsonFieldEditor.init + ) { self.context = context self.onPopOut = onPopOut self.isExpanded = isExpanded - self._model = State(wrappedValue: JsonFieldEditingModel(storedValue: context.value.wrappedValue)) - self._openedDocument = State(wrappedValue: context.documentID) + let value = context.value.wrappedValue + let documentID = context.documentID + self._editor = StateObject(wrappedValue: makeEditor(value, documentID)) } // Through the model: binding `$model.displayText` directly would publish the model's own corrections. private var editorText: Binding { Binding( - get: { model.displayText }, + get: { editor.model.displayText }, set: { typed in - guard !context.isReadOnly, let value = model.typed(typed) else { return } + guard !context.isReadOnly, let value = editor.typed(typed) else { return } context.value.wrappedValue = value } ) @@ -49,7 +47,7 @@ internal struct JsonEditorView: View { text: editorText, isEditable: !context.isReadOnly, accessibilityIdentifier: "inspector-json-field", - documentID: AnyHashable(replacements) + documentID: AnyHashable(editor.replacements) ) .valueWell(clipsContent: true) } @@ -58,13 +56,7 @@ internal struct JsonEditorView: View { .accessibilityElement(children: .contain) // The argument, never `context`: the action's context is a render behind and undid every keystroke (#3051). .onChange(of: JsonFieldSource(documentID: context.documentID, value: context.value.wrappedValue)) { source in - if source.documentID != openedDocument { - openedDocument = source.documentID - model = JsonFieldEditingModel(storedValue: source.value) - replacements &+= 1 - } else if model.received(source.value) { - replacements &+= 1 - } + editor.sync(documentID: source.documentID, value: source.value) } } @@ -77,7 +69,7 @@ internal struct JsonEditorView: View { HStack(spacing: 8) { Spacer(minLength: 4) Button(String(localized: "Open in Window"), systemImage: "arrow.up.forward.app") { - onPopOut(model.displayText) + onPopOut(editor.model.displayText) } .labelStyle(.iconOnly) .buttonStyle(.borderless) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/JsonFieldEditor.swift b/apple/TablePro/Views/RowInspector/FieldEditors/JsonFieldEditor.swift new file mode 100644 index 0000000000..951cc01194 --- /dev/null +++ b/apple/TablePro/Views/RowInspector/FieldEditors/JsonFieldEditor.swift @@ -0,0 +1,30 @@ +import Combine +import Foundation + +// A `@StateObject` so the model is built once per field: a `@State` seed reindents the value on every parent body. +@MainActor +internal final class JsonFieldEditor: ObservableObject { + @Published private(set) var model: JsonFieldEditingModel + // Moves each time the text is replaced from outside, which gives the editor a new history. + @Published private(set) var replacements = 0 + private var openedDocument: UUID? + + internal init(storedValue: String, documentID: UUID?) { + model = JsonFieldEditingModel(storedValue: storedValue) + openedDocument = documentID + } + + internal func typed(_ text: String) -> String? { + model.typed(text) + } + + internal func sync(documentID: UUID?, value: String) { + if documentID != openedDocument { + openedDocument = documentID + model = JsonFieldEditingModel(storedValue: value) + replacements &+= 1 + } else if model.received(value) { + replacements &+= 1 + } + } +} diff --git a/apple/TableProTests/Core/Services/Formatting/ConsoleRequestFormatterTests.swift b/apple/TableProTests/Core/Services/Formatting/ConsoleRequestFormatterTests.swift index 91cf17fa1f..a3911fcf5b 100644 --- a/apple/TableProTests/Core/Services/Formatting/ConsoleRequestFormatterTests.swift +++ b/apple/TableProTests/Core/Services/Formatting/ConsoleRequestFormatterTests.swift @@ -1,8 +1,3 @@ -// -// ConsoleRequestFormatterTests.swift -// TableProTests -// - import Foundation import TableProPluginKit import Testing @@ -86,7 +81,7 @@ struct ConsoleRequestFormatterTests { } } - /// Each line is one record to these endpoints, so indenting a lone document splits it into broken records. + // Each line is one record to these endpoints, so indenting a lone document splits it into broken records. @Test("A line-delimited body keeps one document per line, even when it holds only one") func lineDelimitedBodyIsVerbatim() throws { let typesenseImport = """ @@ -102,8 +97,8 @@ struct ConsoleRequestFormatterTests { #expect(try formatted(bulkDelete) == bulkDelete) } - /// Formatting a selection puts the selection's own leading and trailing whitespace back, so the - /// formatter returning it as well doubled it. + // Formatting a selection puts the selection's own leading and trailing whitespace back, so the + // formatter returning it as well doubled it. @Test("The result is trimmed like every other formatter's") func resultIsTrimmed() throws { let selection = "\nGET /a/_search\n{\"size\":1}\n" @@ -122,8 +117,8 @@ struct ConsoleRequestFormatterTests { #expect(QueryFormatterFactory.make(for: .postgresql) is SQLQueryFormatter) } - /// The SQL formatter turned `HSET user:1` into `HSET user :1`, `put /config/name` into - /// `put / config / name`, and `person:tobie` into `person :tobie`: each a different command. + // The SQL formatter turned `HSET user:1` into `HSET user :1`, `put /config/name` into + // `put / config / name`, and `person:tobie` into `person :tobie`: each a different command. @Test("A command line or a plugin's own language is not run through the SQL formatter", arguments: [ DatabaseType.redis, .etcd, .surrealdb, .kafka ]) @@ -131,4 +126,12 @@ struct ConsoleRequestFormatterTests { #expect(QueryFormatterFactory.make(for: databaseType) == nil) #expect(!QueryFormatterFactory.supportsFormatting(databaseType)) } + + @Test("Format indents a request body over half a million characters") + func formatsALargeBody() throws { + let blob = String(repeating: "a", count: 600_000) + let request = "POST /products/_doc\n{\"blob\":\"\(blob)\",\"size\":1}" + + #expect(try formatted(request) == "POST /products/_doc\n{\n \"blob\": \"\(blob)\",\n \"size\": 1\n}") + } } diff --git a/apple/TableProTests/Core/Services/Formatting/JsonReindenterTests.swift b/apple/TableProTests/Core/Services/Formatting/JsonReindenterTests.swift index 88fab2ee25..b06fa5d17e 100644 --- a/apple/TableProTests/Core/Services/Formatting/JsonReindenterTests.swift +++ b/apple/TableProTests/Core/Services/Formatting/JsonReindenterTests.swift @@ -1,8 +1,3 @@ -// -// JsonReindenterTests.swift -// TableProTests -// - import Foundation import Testing @@ -116,14 +111,104 @@ struct JsonReindenterTests { #expect(JsonReindenter.normalize(input) == "{\"z\":9007199254740993,\"a\":2}") } - @Test("Oversized input is returned unchanged") + @Test("Input past the editor's two million characters is returned unchanged") func sizeCap() { - let big = "{\"a\":\"" + String(repeating: "x", count: 500_001) + "\"}" + let big = "{\"a\":\"" + String(repeating: "x", count: 2_000_001) + "\"}" #expect(JsonReindenter.reindentIfValid(big) == nil) #expect(JsonReindenter.reindent(big) == big) #expect(JsonReindenter.normalize(big) == big) } + @Test("A value over half a million characters is indented and compacted") + func valueInTheBandIsLaidOut() throws { + let value = String(repeating: "x", count: 600_000) + let source = "{\"a\":\"\(value)\",\"b\":[1,2]}" + let pretty = try #require(JsonReindenter.reindentIfValid(source)) + + #expect(pretty == "{\n \"a\": \"\(value)\",\n \"b\": [\n 1,\n 2\n ]\n}") + #expect(JsonReindenter.normalize(pretty) == source) + } + + // `{"a":"…"}` indents to its content plus 13 characters. + @Test("The cap counts the indented text in UTF-16 units", arguments: [ + ("x", 1_999_987, true), ("x", 1_999_988, false), + ("\u{E9}", 1_999_987, true), ("\u{E9}", 1_999_988, false), + ("\u{1F600}", 999_993, true), ("\u{1F600}", 999_994, false), + ]) + func capCountsTheIndentedText(character: String, count: Int, fits: Bool) { + let source = "{\"a\":\"" + String(repeating: character, count: count) + "\"}" + let pretty = JsonReindenter.reindentIfValid(source) + + #expect((pretty != nil) == fits) + if let pretty { + #expect((pretty as NSString).length <= 2_000_000) + } + } + + @Test("A value whose indented text passes the cap stays on its line but still compacts") + func indentedTextPastTheCap() { + let elements = Array(repeating: "1", count: 600_000) + let source = "[" + elements.joined(separator: ", ") + "]" + #expect((source as NSString).length < 2_000_000) + + #expect(JsonReindenter.reindentIfValid(source) == nil) + #expect(JsonReindenter.reindent(source) == source) + #expect(JsonReindenter.normalize(source) == "[" + elements.joined(separator: ",") + "]") + } + + // The reference recurses with bigger frames than the writer, and 512 levels overflow a test thread's stack. + @Test("The writer lays out what the syntax parser's tree lays out, indented and compact") + func writerMatchesTheParsersTree() async { + let mismatches = await Self.onLargeStack { + Self.corpus.filter { source in + JsonReindenter.reindentIfValid(source) != ReferenceLayout.pretty(source) + || JsonReindenter.normalize(source) != ReferenceLayout.compact(source) + } + } + #expect(mismatches.isEmpty, "\(mismatches.prefix(3).map { $0.debugDescription })") + } + + private static func onLargeStack(_ body: @escaping @Sendable () -> Value) async -> Value { + await withCheckedContinuation { continuation in + let thread = Thread { continuation.resume(returning: body()) } + thread.stackSize = 16 << 20 + thread.start() + } + } + + private static let truncated = #"{"a":[1,-2.5e-3,{"b":"x\"y\\"}],"c":true,"d":null,"é":"😀","e":{}}"# + + private static let corpus: [String] = { + var corpus = [ + #"{"z":1,"a":2,"m":3}"#, #"{"id":9007199254740993}"#, #"{"value":3.141592653589793238}"#, + #""hello""#, "42", "true", "false", "null", " -3.5e10 ", "[1,2,3]", "{}", "[]", #"{"a":{},"b":[]}"#, + "not json {", #"{"a":1} extra"#, #"{"a":[1,{"b":2}],"c":"x"}"#, #"{"path":"a\/b","emoji":"\uD83D\uDE00"}"#, + #"{"text":"{not:structure}"}"#, "{\n \"a\": 1,\n \"b\": [ 2, 3 ]\n}", #"{ "z": 9007199254740993, "a": 2 }"#, + #""a\"b\\c\n""#, #"["\u0041", "\t", "\/"]"#, #""\uD800""#, #""\uDC00x""#, #"["\uD83D", "\uDE00"]"#, + #""\é""#, #""a\😀b""#, #""\é"#, #""\"#, #""\""#, #""\\""#, + "007", "-0", "1.", ".5", "-", "1e", "1e+", "1E-2", "01.10e+05", "--1", "+1", "1.2.3", "1e5e5", "-01", + "tru", "nul", "nulll", "[true,false,null]", "[truefalse]", #"{"a":nul}"#, + "\t{\r\n\"a\"\t:\n1}\n", "\u{00A0}1", "1\u{00A0}", "\u{FEFF}{}", + #"{"名前":"値","emoji":"👩‍💻","flag":"🇻🇳"}"#, "[\"e\u{301}\", \"\u{0600}1\"]", + "{,}", #"{"a":1,}"#, "[1,]", "[,1]", #"{"a"}"#, #"{"a":}"#, "{1:2}", "]", "}", "", " ", #""""#, "\"", #"""x"#, + "[[]]", "[{},[]]", #"{"a":[{"b":[{}]}]}"#, "[ [ ] , { } ]", #"{"a" : 1 , "b" : [ ] }"#, + ] + for depth in [511, 512, 513] { + corpus.append(String(repeating: "[", count: depth) + String(repeating: "]", count: depth)) + corpus.append(String(repeating: #"{"a":"#, count: depth) + "1" + String(repeating: "}", count: depth)) + corpus.append(String(repeating: "[1,", count: depth) + "2" + String(repeating: "]", count: depth)) + } + let scalars = Array(truncated.unicodeScalars) + for length in 0...scalars.count { + var prefix = String.UnicodeScalarView() + prefix.append(contentsOf: scalars[0.. String? { + guard let node = JsonSyntaxParser.parse(source) else { return nil } + var output = "" + writePretty(node, into: &output, depth: 0) + return output + } + + static func compact(_ source: String) -> String { + guard let node = JsonSyntaxParser.parse(source) else { return source } + var output = "" + writeCompact(node, into: &output) + return output + } + + private static func writePretty(_ node: JsonSyntaxNode, into output: inout String, depth: Int) { + switch node { + case .string(let raw), .number(let raw), .literal(let raw): + output += raw + case .object(let pairs): + guard !pairs.isEmpty else { + output += "{}" + return + } + output += "{\n" + let childPad = String(repeating: " ", count: depth + 1) + for (offset, pair) in pairs.enumerated() { + output += childPad + pair.key + ": " + writePretty(pair.value, into: &output, depth: depth + 1) + output += offset == pairs.count - 1 ? "\n" : ",\n" + } + output += String(repeating: " ", count: depth) + "}" + case .array(let elements): + guard !elements.isEmpty else { + output += "[]" + return + } + output += "[\n" + let childPad = String(repeating: " ", count: depth + 1) + for (offset, element) in elements.enumerated() { + output += childPad + writePretty(element, into: &output, depth: depth + 1) + output += offset == elements.count - 1 ? "\n" : ",\n" + } + output += String(repeating: " ", count: depth) + "]" + } + } + + private static func writeCompact(_ node: JsonSyntaxNode, into output: inout String) { + switch node { + case .string(let raw), .number(let raw), .literal(let raw): + output += raw + case .object(let pairs): + output += "{" + for (offset, pair) in pairs.enumerated() { + output += pair.key + ":" + writeCompact(pair.value, into: &output) + if offset != pairs.count - 1 { output += "," } + } + output += "}" + case .array(let elements): + output += "[" + for (offset, element) in elements.enumerated() { + writeCompact(element, into: &output) + if offset != elements.count - 1 { output += "," } + } + output += "]" + } + } +} diff --git a/apple/TableProTests/Core/Utilities/JsonRowConverterTests.swift b/apple/TableProTests/Core/Utilities/JsonRowConverterTests.swift index 975bf5bd2a..6a257de52b 100644 --- a/apple/TableProTests/Core/Utilities/JsonRowConverterTests.swift +++ b/apple/TableProTests/Core/Utilities/JsonRowConverterTests.swift @@ -1,8 +1,3 @@ -// -// JsonRowConverterTests.swift -// TableProTests -// - import Foundation import TableProPluginKit @@ -412,4 +407,30 @@ struct JsonRowConverterTests { #expect(result.contains("\"__DEFAULT\"")) } + + @Test("Cancellation is checked every 256 rows and stops the document there") + func cancellationStopsBeforeTheLastRow() { + let converter = makeConverter(columns: ["id"], columnTypes: [.integer(rawType: nil)]) + let rows: [[PluginCellValue]] = (0..<1_000).map { [.text("\($0)")] } + var checks = 0 + + let json = converter.generateJson(rows: rows) { + checks += 1 + return checks > 2 + } + + #expect(checks == 3) + #expect(json.contains("\"id\": 511")) + #expect(!json.contains("\"id\": 512")) + } + + @Test("Without cancellation every row up to the cap is written") + func uncancelledWritesEveryRow() { + let converter = makeConverter(columns: ["id"], columnTypes: [.integer(rawType: nil)]) + let rows: [[PluginCellValue]] = (0..<1_000).map { [.text("\($0)")] } + + let json = converter.generateJson(rows: rows) + + #expect(json.hasSuffix("\"id\": 999\n }\n]")) + } } diff --git a/apple/TableProTests/Core/Utilities/ResultJsonSerializerTests.swift b/apple/TableProTests/Core/Utilities/ResultJsonSerializerTests.swift index 7cc4edbde5..5f9ff5dea4 100644 --- a/apple/TableProTests/Core/Utilities/ResultJsonSerializerTests.swift +++ b/apple/TableProTests/Core/Utilities/ResultJsonSerializerTests.swift @@ -1,10 +1,5 @@ -// -// ResultJsonSerializerTests.swift -// TableProTests -// -// The JSON results view and the grid's Copy as JSON share one serializer and part company on one -// thing: pending deletions. Copy as JSON passes none, so it keeps every selected row. -// +// The JSON results view and the grid's Copy as JSON share one serializer and part company on one +// thing: pending deletions. Copy as JSON passes none, so it keeps every selected row. import Foundation import TableProPluginKit @@ -80,4 +75,19 @@ struct ResultJsonSerializerTests { #expect(output.rowCount == 0) #expect(output.json == "[]") } + + @Test("Past the document's row cap the count is the rows written, so Copy as JSON still copies") + func rowCountStopsAtTheCap() { + let rows = ContiguousArray((0..<50_001).map { Row(id: .existing($0), values: [.text("r\($0)")]) }) + let output = ResultJsonSerializer.serialize( + tableRows: TableRows(rows: rows, columns: ["name"], columnTypes: [.text(rawType: nil)]), + displayIDs: nil, + selectedDisplayIndices: [], + columns: .identity + ) + + #expect(output.rowCount == 50_000) + #expect(output.json.contains("\"r49999\"")) + #expect(!output.json.contains("\"r50000\"")) + } } diff --git a/apple/TableProTests/Extensions/StringJsonTests.swift b/apple/TableProTests/Extensions/StringJsonTests.swift index 5b9ca19eca..6935a03d8e 100644 --- a/apple/TableProTests/Extensions/StringJsonTests.swift +++ b/apple/TableProTests/Extensions/StringJsonTests.swift @@ -1,10 +1,3 @@ -// -// StringJsonTests.swift -// TableProTests -// -// Tests for String+JSON pretty-printing extension -// - import Foundation import TableProPluginKit import Testing @@ -88,6 +81,14 @@ struct StringJsonTests { #expect(!"123".looksLikeJson) } + @Test("Pretty Print copies a value over half a million characters indented") + func prettyPrintsAValueInTheBand() throws { + let value = "{\"blob\":\"" + String(repeating: "a", count: 600_000) + "\"}" + let result = try #require(value.prettyPrintedAsJson()) + + #expect(result.hasPrefix("{\n \"blob\": \"aaa")) + } + @Test("Slashes are preserved as written") func slashesPreserved() throws { let input = "{\"url\":\"https://example.com/path/to/resource\"}" diff --git a/apple/TableProTests/Models/UI/JsonFieldEditingModelTests.swift b/apple/TableProTests/Models/UI/JsonFieldEditingModelTests.swift index 73baa1faa3..97a464e0f1 100644 --- a/apple/TableProTests/Models/UI/JsonFieldEditingModelTests.swift +++ b/apple/TableProTests/Models/UI/JsonFieldEditingModelTests.swift @@ -1,8 +1,3 @@ -// -// JsonFieldEditingModelTests.swift -// TableProTests -// - import Foundation import TableProPluginKit import Testing @@ -122,4 +117,22 @@ struct JsonFieldEditingModelTests { let adopted = model.received("{\"b\": ") #expect(adopted) } + + @Test("A value over half a million characters opens indented") + func valueInTheBandOpensIndented() { + let blob = String(repeating: "a", count: 600_000) + let model = JsonFieldEditingModel(storedValue: "{\"blob\":\"\(blob)\",\"id\":1}") + + #expect(model.displayText == "{\n \"blob\": \"\(blob)\",\n \"id\": 1\n}") + } + + @Test("The store answering with the exact text last synced is refused") + func literalEchoIsRefused() { + var model = JsonFieldEditingModel(storedValue: "{\"a\":1}") + + let adopted = model.received(model.displayText) + + #expect(!adopted) + #expect(model.displayText == JsonReindenter.reindent("{\"a\":1}")) + } } diff --git a/apple/TableProTests/Models/UI/MultiRowEditStateJsonTests.swift b/apple/TableProTests/Models/UI/MultiRowEditStateJsonTests.swift index 72af1a5769..bcf193ddc9 100644 --- a/apple/TableProTests/Models/UI/MultiRowEditStateJsonTests.swift +++ b/apple/TableProTests/Models/UI/MultiRowEditStateJsonTests.swift @@ -1,8 +1,3 @@ -// -// MultiRowEditStateJsonTests.swift -// TableProTests -// - import Foundation import TableProPluginKit import Testing @@ -92,4 +87,17 @@ struct MultiRowEditStateJsonTests { state.updateField(at: 0, value: "hello") #expect(state.fields[0].hasEdit == false) } + + @Test("A whitespace-only edit of a value over half a million characters is not staged; a real one is, compact") + func valueInTheBand() { + let blob = String(repeating: "a", count: 600_000) + let original = "{\"blob\":\"\(blob)\",\"id\":1}" + let state = makeState(value: original, type: .json(rawType: "jsonb")) + + state.updateField(at: 0, value: "{\n \"blob\": \"\(blob)\",\n \"id\": 1\n}") + #expect(state.fields[0].hasEdit == false) + + state.updateField(at: 0, value: "{\n \"blob\": \"\(blob)\",\n \"id\": 2\n}") + #expect(state.fields[0].pendingValue == "{\"blob\":\"\(blob)\",\"id\":2}") + } } diff --git a/apple/TableProTests/Views/ArrayValueEditorModelTests.swift b/apple/TableProTests/Views/ArrayValueEditorModelTests.swift index 98c5aba6ae..149fa6975e 100644 --- a/apple/TableProTests/Views/ArrayValueEditorModelTests.swift +++ b/apple/TableProTests/Views/ArrayValueEditorModelTests.swift @@ -1,10 +1,3 @@ -// -// ArrayValueEditorModelTests.swift -// TableProTests -// -// Tests for the array cell editor's row model. -// - import Foundation @testable import TablePro import TableProPluginKit @@ -88,9 +81,9 @@ struct ArrayValueEditorModelTests { private let storedDocument = #"{"id": 1, "name": "example"}"# - /// PostgreSQL stores `json` text verbatim, so a cell the user only looked at must write back - /// the bytes the server sent. The editor shows every element pretty-printed, and without this - /// pressing OK would rewrite all of them. + // PostgreSQL stores `json` text verbatim, so a cell the user only looked at must write back + // the bytes the server sent. The editor shows every element pretty-printed, and without this + // pressing OK would rewrite all of them. @Test("An element the user only read commits the bytes the server sent") func keepsUntouchedJsonElementByteIdentical() { var rows = ArrayValueEditorModel.rows(from: [.value(storedDocument), .value(#"{"id": 2}"#)]) @@ -116,8 +109,8 @@ struct ArrayValueEditorModelTests { #expect(PostgresArrayLiteralCodec.parse(literal) == [.value(#"{"id":3}"#)]) } - /// A scalar array can hold text that happens to parse as JSON, and there retyping the - /// whitespace inside it is a real edit rather than the same document. + // A scalar array can hold text that happens to parse as JSON, and there retyping the + // whitespace inside it is a real edit rather than the same document. @Test("The rule is confined to JSON elements") func leavesScalarElementsAlone() { var rows = ArrayValueEditorModel.rows(from: [.value(storedDocument)]) @@ -147,9 +140,9 @@ struct ArrayValueEditorModelTests { #expect(long.summary?.count == 9) } - /// The element list rebuilds on every keystroke in the detail editor, so parsing each visible - /// element per render is unbounded work on the main actor. Past the cap an element is previewed - /// from its prefix and reports no verdict rather than a wrong one. + // The element list rebuilds on every keystroke in the detail editor, so parsing each visible + // element per render is unbounded work on the main actor. Past the cap an element is previewed + // from its prefix and reports no verdict rather than a wrong one. @Test("An element too large to inspect is previewed without being parsed") func doesNotParseAnOversizeElement() { let oversize = "{\"k\": \"" + String(repeating: "x", count: 8_000) + "\"}" @@ -161,4 +154,18 @@ struct ArrayValueEditorModelTests { let oversizeAndBroken = "{" + String(repeating: "x", count: 8_000) #expect(ArrayValueEditorModel.jsonDisplay(of: .value(oversizeAndBroken)).isValid) } + + @Test("An element over half a million characters commits compact when edited and as stored when only reindented") + func committedElementInTheBand() { + let blob = String(repeating: "a", count: 600_000) + let stored = "{\"blob\": \"\(blob)\", \"id\": 1}" + let reindented = "{\n \"blob\": \"\(blob)\",\n \"id\": 1\n}" + let edited = "{\n \"blob\": \"\(blob)\",\n \"id\": 2\n}" + + let untouched = ArrayEditorRow(element: .value(reindented), originalElement: .value(stored)) + let changed = ArrayEditorRow(element: .value(edited), originalElement: .value(stored)) + + #expect(ArrayValueEditorModel.committedElement(untouched, elementEditor: .json) == .value(stored)) + #expect(ArrayValueEditorModel.committedElement(changed, elementEditor: .json) == .value("{\"blob\":\"\(blob)\",\"id\":2}")) + } } diff --git a/apple/TableProTests/Views/Results/JSONTreeDocumentTests.swift b/apple/TableProTests/Views/Results/JSONTreeDocumentTests.swift index 7cb8511faf..409d5d9052 100644 --- a/apple/TableProTests/Views/Results/JSONTreeDocumentTests.swift +++ b/apple/TableProTests/Views/Results/JSONTreeDocumentTests.swift @@ -1,8 +1,3 @@ -// -// JSONTreeDocumentTests.swift -// TableProTests -// - import Foundation import Testing @@ -112,4 +107,11 @@ struct JSONTreeDocumentTests { #expect(outcome(JSONTreeDocument(displayText: "{\"a\":")) == .invalidJSON) #expect(outcome(JSONTreeDocument(displayText: "not json")) == .invalidJSON) } + + @Test("A valid document over half a million characters reports too large rather than invalid") + func documentInTheBandIsTooLarge() { + let document = "{\"blob\": \"" + String(repeating: "a", count: 600_000) + "\"}" + + #expect(outcome(JSONTreeDocument(displayText: document)) == .tooLarge) + } } diff --git a/apple/TableProTests/Views/Results/JSONViewerWindowCommitTests.swift b/apple/TableProTests/Views/Results/JSONViewerWindowCommitTests.swift index 9db90b2b44..1134488743 100644 --- a/apple/TableProTests/Views/Results/JSONViewerWindowCommitTests.swift +++ b/apple/TableProTests/Views/Results/JSONViewerWindowCommitTests.swift @@ -1,15 +1,10 @@ -// -// JSONViewerWindowCommitTests.swift -// TableProTests -// - import Foundation import Testing @testable import TablePro -/// Closing an `NSWindow` in a test kills the host, so the window's Save is tested as the decision -/// it makes: the saved text against the baseline the window was opened with. +// Closing an `NSWindow` in a test kills the host, so the window's Save is tested as the decision +// it makes: the saved text against the baseline the window was opened with. struct JSONViewerWindowCommitTests { private let stored = #"{"qty":1,"sku":"A-1"}"# private let edited = #"{"qty":25,"sku":"A-1"}"# @@ -75,4 +70,13 @@ struct JSONViewerWindowCommitTests { #expect(commit(saving: "{oops", baseline: "{oops") == nil) #expect(commit(saving: "{oops", baseline: stored) == "{oops") } + + @Test("A whitespace-only Save of a document over half a million characters writes nothing") + func whitespaceSaveInTheBand() { + let blob = String(repeating: "a", count: 600_000) + let stored = "{\"blob\":\"\(blob)\",\"qty\":1}" + + #expect(commit(saving: "{\n \"blob\": \"\(blob)\",\n \"qty\": 1\n}", baseline: stored) == nil) + #expect(commit(saving: "{\n \"blob\": \"\(blob)\",\n \"qty\": 2\n}", baseline: stored) == "{\"blob\":\"\(blob)\",\"qty\":2}") + } } diff --git a/apple/TableProTests/Views/Results/ResultsJsonViewTests.swift b/apple/TableProTests/Views/Results/ResultsJsonViewTests.swift index 167773b1fa..42dfb8996d 100644 --- a/apple/TableProTests/Views/Results/ResultsJsonViewTests.swift +++ b/apple/TableProTests/Views/Results/ResultsJsonViewTests.swift @@ -1,8 +1,3 @@ -// -// ResultsJsonViewTests.swift -// TableProTests -// - import Foundation import TableProPluginKit import Testing @@ -276,4 +271,79 @@ struct ResultsJsonViewTests { #expect(first.lowerBound < second.lowerBound) } } + + @Test("With no JSON column the serializer's text is already indented and is shown as it is") + func noJsonColumnSkipsTheReindent() { + let result = compute(selectedIndices: []) + + #expect(result.pretty == result.json) + #expect(result.pretty == JsonReindenter.reindent(result.json)) + } + + @Test("A JSON column's value is still indented in the text view") + func jsonColumnIsIndented() { + let tableRows = TableRows( + rows: [Row(id: .existing(0), values: [.text("a"), .text(#"{"k":[1,2]}"#)])], + columns: ["name", "meta"], + columnTypes: [.text(rawType: nil), .json(rawType: "jsonb")] + ) + + let result = ResultsJsonView.computeJson( + tableRows: tableRows, + displayIDs: nil, + selectedIndices: [], + columnLayout: ColumnLayoutState() + ) + + #expect(result.json.contains(#""meta": {"k":[1,2]}"#)) + #expect(result.pretty == JsonReindenter.reindent(result.json)) + #expect(result.pretty.contains("\"meta\": {\n \"k\": [\n 1,")) + } + + @Test("With every column hidden each row shows as an empty object") + func everyColumnHiddenShowsEmptyObjects() { + var layout = ColumnLayoutState() + layout.hiddenColumns = ["status", "name"] + + let result = compute(selectedIndices: [0, 1], columnLayout: layout) + + #expect(result.pretty == "[\n {},\n {}\n]") + } + + @Test("A result past the document's row cap counts only the rows the document holds") + func countsTheRowsTheDocumentHolds() { + let rows = ContiguousArray((0..<50_001).map { Row(id: .existing($0), values: [.text("r\($0)")]) }) + let tableRows = TableRows(rows: rows, columns: ["name"], columnTypes: [.text(rawType: nil)]) + + let result = ResultsJsonView.computeJson( + tableRows: tableRows, + displayIDs: nil, + selectedIndices: [], + columnLayout: ColumnLayoutState() + ) + + #expect(result.resolvedCount == 50_000) + #expect(!result.json.contains("\"r50000\"")) + } + + @Test("A render whose task is cancelled returns early with nothing to show") + func cancelledRenderReturnsEarly() async { + let tableRows = makeTableRows() + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + return await ResultsJsonView.render( + tableRows: tableRows, + displayIDs: nil, + selectedIndices: [], + deletedRowIDs: [], + defaultedCells: [:], + columnLayout: ColumnLayoutState() + ) + } + + let result = await task.value + + #expect(result.json.isEmpty) + #expect(result.resolvedCount == 0) + } } diff --git a/apple/TableProTests/Views/RowInspector/JsonFieldEditorTests.swift b/apple/TableProTests/Views/RowInspector/JsonFieldEditorTests.swift new file mode 100644 index 0000000000..2994871394 --- /dev/null +++ b/apple/TableProTests/Views/RowInspector/JsonFieldEditorTests.swift @@ -0,0 +1,108 @@ +import AppKit +import Combine +import SwiftUI +@testable import TablePro +import TableProTestSupport +import Testing + +@MainActor +struct JsonFieldEditorTests { + @MainActor + private final class Counts: ObservableObject { + @Published var tick = 0 + var bodies = 0 + var editors = 0 + } + + private struct Parent: View { + @ObservedObject var counts: Counts + + var body: some View { + counts.bodies += 1 + return JsonEditorView( + context: FieldEditorContext( + columnName: "meta", + columnType: .json(rawType: "JSON"), + isLongText: true, + value: .constant(#"{"row": 1}"#), + originalValue: #"{"row": 1}"#, + valueState: .value(#"{"row": 1}"#), + isReadOnly: false, + documentID: Parent.document + ), + makeEditor: { [counts] value, documentID in + counts.editors += 1 + return JsonFieldEditor(storedValue: value, documentID: documentID) + } + ) + } + + static let document = UUID() + } + + @Test("Evaluating the parent's body again builds no second model") + func parentBodyBuildsOneModel() async throws { + let counts = Counts() + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 320, height: 300), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = NSHostingView(rootView: Parent(counts: counts)) + defer { window.orderOut(nil) } + window.layoutIfNeeded() + try await waitUntil { counts.bodies >= 1 } + + counts.tick += 1 + try await waitUntil { + window.layoutIfNeeded() + return counts.bodies >= 2 + } + counts.tick += 1 + try await waitUntil { + window.layoutIfNeeded() + return counts.bodies >= 3 + } + + #expect(counts.editors == 1) + } + + @Test("Another document reseeds the model once and gives the editor a new history") + func newDocumentReseedsOnce() { + let editor = JsonFieldEditor(storedValue: #"{"a":1}"#, documentID: UUID()) + let next = UUID() + + editor.sync(documentID: next, value: #"{"b":2}"#) + #expect(editor.replacements == 1) + #expect(editor.model.displayText == JsonReindenter.reindent(#"{"b":2}"#)) + + editor.sync(documentID: next, value: #"{"b":2}"#) + #expect(editor.replacements == 1) + } + + @Test("The editor's own text coming back is refused and keeps the history") + func ownTextIsRefused() throws { + let document = UUID() + let editor = JsonFieldEditor(storedValue: #"{"a":1}"#, documentID: document) + let typed = "{\n \"a\": 2\n}" + let published = try #require(editor.typed(typed)) + + editor.sync(documentID: document, value: published) + + #expect(editor.replacements == 0) + #expect(editor.model.displayText == typed) + } + + @Test("Set NULL empties the field and starts a new history") + func setNullIsAdopted() { + let document = UUID() + let editor = JsonFieldEditor(storedValue: #"{"a":1}"#, documentID: document) + + editor.sync(documentID: document, value: "") + + #expect(editor.replacements == 1) + #expect(editor.model.displayText.isEmpty) + } +} diff --git a/apple/changelog.d/4427.fixed.1.md b/apple/changelog.d/4427.fixed.1.md new file mode 100644 index 0000000000..d49da0075c --- /dev/null +++ b/apple/changelog.d/4427.fixed.1.md @@ -0,0 +1 @@ +JSON values over 500,000 characters showed unindented in the inspector, the JSON viewer and Pretty Print. diff --git a/apple/changelog.d/4427.fixed.2.md b/apple/changelog.d/4427.fixed.2.md new file mode 100644 index 0000000000..af1458c95e --- /dev/null +++ b/apple/changelog.d/4427.fixed.2.md @@ -0,0 +1 @@ +The JSON result view counted rows past the 50,000 it shows. diff --git a/apple/changelog.d/4427.fixed.md b/apple/changelog.d/4427.fixed.md new file mode 100644 index 0000000000..aaa55a333e --- /dev/null +++ b/apple/changelog.d/4427.fixed.md @@ -0,0 +1 @@ +Stepping through rows with a large JSON value in the inspector took seconds per row.