Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,64 @@ import TextStory
/// - Grouping pasted text
///
/// If needed, the automatic undo grouping can be overridden using the `beginGrouping()` and `endGrouping()` methods.
///
/// The undo and redo stacks together hold at most ``maximumHistoryBytes``. A new step that goes over it drops the
/// oldest steps first, as `levelsOfUndo` does for `UndoManager`, measured in bytes so one whole-document replace cannot
/// outweigh thousands of keystrokes.
public class CEUndoManager: UndoManager {
/// The default ``maximumHistoryBytes``: enough for several whole-document replaces of a large script.
public static let defaultMaximumHistoryBytes = 32 * 1_024 * 1_024

/// Represents a group of mutations that should be treated as one mutation when undoing/redoing.
struct UndoGroup {
var mutations: [Mutation]
/// What the group's mutations hold, in bytes.
var bytes: Int

init(mutations: [Mutation]) {
self.mutations = mutations
self.bytes = mutations.reduce(0) { $0 + $1.bytes }
}

mutating func append(_ mutation: Mutation) {
mutations.append(mutation)
bytes += mutation.bytes
}
}

/// A single undo mutation.
struct Mutation {
var mutation: TextMutation
var inverse: TextMutation

/// The text both sides keep, as UTF-16, plus the mutation itself, so even an empty one is charged.
var bytes: Int {
(mutation.string.utf16.count + inverse.string.utf16.count) * MemoryLayout<UInt16>.size
+ MemoryLayout<Mutation>.stride
}
}

public struct History {
var undoStack: [UndoGroup]
var redoStack: [UndoGroup]

public var isEmpty: Bool { undoStack.isEmpty && redoStack.isEmpty }

/// What the history holds, in bytes, charged the way ``CEUndoManager/maximumHistoryBytes`` is.
public var bytes: Int {
undoStack.reduce(0) { $0 + $1.bytes } + redoStack.reduce(0) { $0 + $1.bytes }
}
}

/// The most the undo and redo stacks may hold together, in bytes of text. The newest step is kept even when it
/// alone is larger, so the edit just made can always be undone. Zero means no limit.
public var maximumHistoryBytes = CEUndoManager.defaultMaximumHistoryBytes {
didSet { trimToBudget() }
}

/// What the undo and redo stacks hold now, in bytes.
public private(set) var historyBytes = 0

private var _isUndoing: Bool = false
private var _isRedoing: Bool = false

Expand Down Expand Up @@ -200,6 +239,7 @@ public class CEUndoManager: UndoManager {
public func clearStack() {
undoStack.removeAll()
redoStack.removeAll()
historyBytes = 0
}

public var history: History {
Expand All @@ -210,8 +250,10 @@ public class CEUndoManager: UndoManager {
public func restore(_ history: History) {
undoStack = history.undoStack
redoStack = history.redoStack
historyBytes = history.bytes
isGrouping = false
shouldBreakNextGroup = true
trimToBudget()
}

// MARK: - Mutations
Expand Down Expand Up @@ -268,12 +310,36 @@ public class CEUndoManager: UndoManager {
let lastMutation = undoStack.last?.mutations.last,
!shouldBreakNextGroup,
isGrouping || shouldContinueGroup(newMutation, lastMutation: lastMutation) {
undoStack[undoStack.count - 1].mutations.append(newMutation)
undoStack[undoStack.count - 1].append(newMutation)
} else {
undoStack.append(UndoGroup(mutations: [newMutation]))
shouldBreakNextGroup = false
}
historyBytes += newMutation.bytes - redoStack.reduce(0) { $0 + $1.bytes }
redoStack.removeAll()
trimToBudget()
}

/// Drops the oldest steps until the history fits ``maximumHistoryBytes``: the bottom of the undo stack, then the
/// bottom of the redo stack, which is the step furthest from the text. One step always stays.
private func trimToBudget() {
guard maximumHistoryBytes > 0, historyBytes > maximumHistoryBytes else { return }
var bytes = historyBytes
var droppedUndo = 0
while bytes > maximumHistoryBytes, droppedUndo < undoStack.count,
undoStack.count - droppedUndo + redoStack.count > 1 {
bytes -= undoStack[droppedUndo].bytes
droppedUndo += 1
}
var droppedRedo = 0
while bytes > maximumHistoryBytes, droppedRedo < redoStack.count,
undoStack.count - droppedUndo + redoStack.count - droppedRedo > 1 {
bytes -= redoStack[droppedRedo].bytes
droppedRedo += 1
}
undoStack.removeFirst(droppedUndo)
redoStack.removeFirst(droppedRedo)
historyBytes = bytes
}

// MARK: - Grouping
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import AppKit
@testable import TableProTextEngine
import Testing

@MainActor
struct UndoBudgetTests {
private static let step = String(repeating: "x", count: 1_000)

private func makeTextView() throws -> (TextView, CEUndoManager) {
let textView = TextView(string: "")
return (textView, try #require(textView.editorUndoManager))
}

// One undo step per call, as a paste or a Format Query is.
private func appendStep(_ text: String, to textView: TextView, undoManager: CEUndoManager) {
undoManager.beginUndoGrouping()
textView.replaceCharacters(in: NSRange(location: textView.textStorage.length, length: 0), with: text)
undoManager.endUndoGrouping()
}

private func stepBytes(_ undoManager: CEUndoManager) -> Int {
undoManager.historyBytes / max(undoManager.undoCount + undoManager.redoCount, 1)
}

@Test("Steps past the budget drop the oldest, and the newest still undo in order")
func oldestStepsAreDropped() throws {
let (textView, undoManager) = try makeTextView()
appendStep(Self.step, to: textView, undoManager: undoManager)
let perStep = stepBytes(undoManager)
undoManager.maximumHistoryBytes = perStep * 3

for _ in 1..<10 {
appendStep(Self.step, to: textView, undoManager: undoManager)
#expect(undoManager.historyBytes <= undoManager.maximumHistoryBytes)
}

#expect(undoManager.undoCount == 3)
for remaining in [9, 8, 7] {
undoManager.undo()
#expect(textView.textStorage.length == remaining * Self.step.count)
}
#expect(!undoManager.canUndo)
}

@Test("A step larger than the whole budget is kept, so it can still be undone")
func oversizedStepIsKept() throws {
let (textView, undoManager) = try makeTextView()
undoManager.maximumHistoryBytes = 100
appendStep("SELECT 1", to: textView, undoManager: undoManager)

appendStep(Self.step, to: textView, undoManager: undoManager)

#expect(undoManager.undoCount == 1)
undoManager.undo()
#expect(textView.string == "SELECT 1")
#expect(!undoManager.canUndo)
}

@Test("A whole-document replace is charged both the old and the new text")
func replaceChargesBothSides() throws {
let (textView, undoManager) = try makeTextView()
appendStep(Self.step, to: textView, undoManager: undoManager)
let insertOnly = undoManager.historyBytes

undoManager.beginUndoGrouping()
textView.replaceCharacters(in: NSRange(location: 0, length: textView.textStorage.length), with: Self.step)
undoManager.endUndoGrouping()

let replace = undoManager.historyBytes - insertOnly
#expect(replace >= Self.step.utf16.count * 2 * MemoryLayout<UInt16>.size)
}

@Test("The redo stack counts toward the budget, and a restored history is trimmed to it")
func redoStackIsBounded() throws {
let (textView, undoManager) = try makeTextView()
for _ in 0..<6 {
appendStep(Self.step, to: textView, undoManager: undoManager)
}
let perStep = stepBytes(undoManager)
for _ in 0..<4 {
undoManager.undo()
}
let history = undoManager.history
#expect(history.bytes == undoManager.historyBytes)

undoManager.clearStack()
#expect(undoManager.historyBytes == 0)
undoManager.maximumHistoryBytes = perStep * 3
undoManager.restore(history)

// The two undo steps are older than the four redo steps, so they go first, then the furthest redo.
#expect(undoManager.undoCount == 0)
#expect(undoManager.redoCount == 3)
#expect(undoManager.historyBytes <= undoManager.maximumHistoryBytes)
undoManager.redo()
#expect(textView.textStorage.length == 3 * Self.step.count)
}

@Test("A budget of zero keeps every step")
func zeroBudgetIsUnlimited() throws {
let (textView, undoManager) = try makeTextView()
undoManager.maximumHistoryBytes = 0
for _ in 0..<50 {
appendStep(Self.step, to: textView, undoManager: undoManager)
}
#expect(undoManager.undoCount == 50)
}
}
1 change: 1 addition & 0 deletions apple/changelog.d/4584.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The SQL editor's undo history now holds at most 32 MB per query tab, dropping the oldest steps first.
Loading