UndoManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Topten.RichTextKit.Utils
  5. {
  6. /// <summary>
  7. /// Implements an manager for undo operations
  8. /// </summary>
  9. /// <typeparam name="T">A context object type (eg: document type)</typeparam>
  10. public class UndoManager<T>
  11. {
  12. /// <summary>
  13. /// Constructs a new undo manager
  14. /// </summary>
  15. /// <param name="context">The document context object</param>
  16. public UndoManager(T context)
  17. {
  18. _maxUnits = 100;
  19. _context = context;
  20. }
  21. /// <summary>
  22. /// Execute an undo unit and add it to the manager
  23. /// </summary>
  24. /// <param name="unit">The undo unit to execute</param>
  25. public void Do(UndoUnit<T> unit)
  26. {
  27. // Only if not blocked
  28. if (IsBlocked)
  29. throw new InvalidOperationException("Attempt to execute undo operation while blocked");
  30. // Fire start
  31. if (CurrentGroup == null)
  32. OnStartOperation();
  33. // Remember if was modified
  34. bool wasModified = IsModified;
  35. try
  36. {
  37. // Do it
  38. unit.Do(_context);
  39. Add(unit);
  40. }
  41. finally
  42. {
  43. // End operation if not in a group
  44. if (CurrentGroup == null)
  45. OnEndOperation();
  46. // Fire modified changed
  47. if (wasModified != IsModified)
  48. OnModifiedChanged();
  49. }
  50. }
  51. /// <summary>
  52. /// Undoes the last performed operation
  53. /// </summary>
  54. public void Undo()
  55. {
  56. // Check if can
  57. if (!CanUndo)
  58. return;
  59. // Remember if was modified
  60. bool wasModified = IsModified;
  61. // Fire start op
  62. OnStartOperation();
  63. // Seal the currently open item
  64. Seal();
  65. // Undo
  66. Block();
  67. _units[_currentPos - 1].Undo(_context);
  68. Unblock();
  69. // Update position
  70. _currentPos--;
  71. // End operation
  72. OnEndOperation();
  73. // Fire modified event
  74. if (wasModified != IsModified)
  75. OnModifiedChanged();
  76. }
  77. /// <summary>
  78. /// Redoes previously undone operations
  79. /// </summary>
  80. public void Redo()
  81. {
  82. // Check if can
  83. if (!CanRedo)
  84. return;
  85. // Remember if modified
  86. bool wasModified = IsModified;
  87. // Fire start events
  88. OnStartOperation();
  89. // Seal the last item
  90. Seal();
  91. // Undo
  92. Block();
  93. _units[_currentPos].Redo(_context);
  94. Unblock();
  95. // Update position
  96. _currentPos++;
  97. // Fire end events
  98. OnEndOperation();
  99. // Fire modified event
  100. if (wasModified != IsModified)
  101. OnModifiedChanged();
  102. }
  103. /// <summary>
  104. /// Stars a group operation
  105. /// </summary>
  106. /// <param name="description">A user readable description of the operation</param>
  107. /// <returns>An IDisposable that when disposed will close the group</returns>
  108. public IDisposable OpenGroup(string description)
  109. {
  110. return OpenGroup(new UndoGroup<T>(description));
  111. }
  112. /// <summary>
  113. /// Stars a group operation
  114. /// </summary>
  115. /// <param name="group">The UndoGroup to be used</param>
  116. /// <returns>An IDisposable that when disposed will close the group</returns>
  117. public IDisposable OpenGroup(UndoGroup<T> group)
  118. {
  119. if (IsBlocked)
  120. throw new InvalidOperationException("Attempt to add undo group while blocked");
  121. // First group?
  122. if (_openGroups.Count == 0)
  123. OnStartOperation();
  124. // Notified it's open
  125. group.OnOpen(_context);
  126. // Add to stack
  127. _openGroups.Push(group);
  128. // Seal the last item
  129. Seal();
  130. // Return a disposable
  131. if (_groupDisposer == null)
  132. _groupDisposer = new GroupDisposer(this);
  133. return _groupDisposer;
  134. }
  135. /// <summary>
  136. /// Ends the current group operation
  137. /// </summary>
  138. public void CloseGroup()
  139. {
  140. if (IsBlocked)
  141. throw new InvalidOperationException("Attempt to end undo group while blocked");
  142. if (CurrentGroup == null)
  143. throw new InvalidOperationException("Attempt to end unopened undo group");
  144. // Remember the group
  145. var group = CurrentGroup;
  146. // Pop the group and add it to either the outer open
  147. // group, or the main undo stack
  148. Add(_openGroups.Pop());
  149. // Notify closed
  150. group.OnClose(_context);
  151. // End operation if no open groups
  152. if (_openGroups.Count == 0)
  153. OnEndOperation();
  154. }
  155. /// <summary>
  156. /// Clear and reset the undo manager
  157. /// </summary>
  158. public void Clear()
  159. {
  160. _units.Clear();
  161. _currentPos = 0;
  162. _unmodifiedPos = -1;
  163. _openGroups.Clear();
  164. _blockDepth = 0;
  165. }
  166. /// <summary>
  167. /// Check if can undo
  168. /// </summary>
  169. public bool CanUndo
  170. {
  171. get
  172. {
  173. return GetUndoUnit() != null;
  174. }
  175. }
  176. /// <summary>
  177. /// Check if can redo
  178. /// </summary>
  179. public bool CanRedo
  180. {
  181. get
  182. {
  183. return GetRedoUnit() != null;
  184. }
  185. }
  186. /// <summary>
  187. /// Gets the description of the next undo operation
  188. /// </summary>
  189. public string UndoDescription
  190. {
  191. get
  192. {
  193. var unit = GetUndoUnit();
  194. if (unit == null)
  195. return null;
  196. return unit.Description;
  197. }
  198. }
  199. /// <summary>
  200. /// Gets the description of the next redo operation
  201. /// </summary>
  202. public string RedoDescription
  203. {
  204. get
  205. {
  206. var unit = GetRedoUnit();
  207. if (unit == null)
  208. return null;
  209. return unit.Description;
  210. }
  211. }
  212. /// <summary>
  213. /// Event fired when any operation (or group of operations) starts
  214. /// </summary>
  215. public event Action StartOperation;
  216. /// <summary>
  217. /// Event fired when any operation (or group of operations) ends
  218. /// </summary>
  219. public event Action EndOperation;
  220. /// <summary>
  221. /// Fired when the modified state of the document changes
  222. /// </summary>
  223. public event Action ModifiedChanged;
  224. /// <summary>
  225. /// Checks if the document is currently modified
  226. /// </summary>
  227. public bool IsModified
  228. {
  229. get
  230. {
  231. return _unmodifiedPos != _currentPos;
  232. }
  233. }
  234. /// <summary>
  235. /// Mark the document as currently unmodified
  236. /// </summary>
  237. /// <remarks>
  238. /// Typically this method would be called when the document
  239. /// is saved.
  240. /// </remarks>
  241. public void MarkUnmodified()
  242. {
  243. // Remember if was modified
  244. bool wasModified = IsModified;
  245. // Mark as currently unmodified
  246. _unmodifiedPos = _currentPos;
  247. // Prevent additions to the open item
  248. Seal();
  249. // Fire modified changed event
  250. if (wasModified)
  251. OnModifiedChanged();
  252. }
  253. /// <summary>
  254. /// Seals the last item to prevent changes
  255. /// </summary>
  256. public void Seal()
  257. {
  258. if (_units.Count > 0)
  259. _units[_units.Count - 1].Seal();
  260. }
  261. /// <summary>
  262. /// Get the current unsealed unit
  263. /// </summary>
  264. /// <returns>The unsealed unit if available, otherwise null</returns>
  265. public UndoUnit<T> GetUnsealedUnit()
  266. {
  267. // Don't allow coalescing while we have open groups.
  268. if (_openGroups.Count > 0)
  269. return null;
  270. var unit = GetUndoUnit();
  271. if (unit == null)
  272. return null;
  273. if (unit.Sealed)
  274. return null;
  275. return unit;
  276. }
  277. /// <summary>
  278. /// Retrieves the unit that would be executed on Undo
  279. /// </summary>
  280. /// <returns>An UndoUnit, or null</returns>
  281. public UndoUnit<T> GetUndoUnit()
  282. {
  283. if (_currentPos > 0)
  284. return _units[_currentPos - 1];
  285. else
  286. return null;
  287. }
  288. /// <summary>
  289. /// Retrieves the unit that would be executed on Redo
  290. /// </summary>
  291. /// <returns>An UndoUnit, or null</returns>
  292. public UndoUnit<T> GetRedoUnit()
  293. {
  294. if (_currentPos < _units.Count)
  295. return _units[_currentPos];
  296. else
  297. return null;
  298. }
  299. /// <summary>
  300. /// Notifies that an operation (or group of operations) is about to start
  301. /// </summary>
  302. protected virtual void OnStartOperation()
  303. {
  304. StartOperation?.Invoke();
  305. }
  306. /// <summary>
  307. /// Notifies that an operation (or group of operations) has finished
  308. /// </summary>
  309. protected virtual void OnEndOperation()
  310. {
  311. EndOperation?.Invoke();
  312. }
  313. /// <summary>
  314. /// Notifies when the modified state of the document changes
  315. /// </summary>
  316. protected virtual void OnModifiedChanged()
  317. {
  318. ModifiedChanged?.Invoke();
  319. }
  320. /// <summary>
  321. /// Adds a unit to the undo manager without executing it
  322. /// </summary>
  323. /// <param name="unit">The UndoUnit to add</param>
  324. void Add(UndoUnit<T> unit)
  325. {
  326. if (IsBlocked)
  327. throw new InvalidOperationException("Attempt to add undo operation while blocked");
  328. if (CurrentGroup != null)
  329. {
  330. CurrentGroup.Add(unit);
  331. }
  332. else
  333. {
  334. RemoveAllRedoUnits();
  335. _units.Add(unit);
  336. // Limit undo stack size
  337. if (_units.Count > _maxUnits)
  338. {
  339. // Update unmodified index
  340. if (_unmodifiedPos >= 0)
  341. _unmodifiedPos--;
  342. // Remove
  343. _units.RemoveAt(0);
  344. }
  345. else
  346. {
  347. _currentPos++;
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Removes all units in the redo queue
  353. /// </summary>
  354. void RemoveAllRedoUnits()
  355. {
  356. System.Diagnostics.Debug.Assert(_openGroups.Count == 0);
  357. // If the unmodified position has been undone
  358. // we can never get back to clean position
  359. if (_unmodifiedPos > _currentPos)
  360. {
  361. _unmodifiedPos = -1;
  362. }
  363. // Remove redo units
  364. while (_currentPos < _units.Count)
  365. {
  366. _units.RemoveAt(_currentPos);
  367. }
  368. // Seal the last item
  369. Seal();
  370. }
  371. /// <summary>
  372. /// Checks if the undo manager is currently blocked
  373. /// </summary>
  374. bool IsBlocked
  375. {
  376. get
  377. {
  378. return _blockDepth > 0;
  379. }
  380. }
  381. /// <summary>
  382. /// Blocks the undo manager
  383. /// </summary>
  384. void Block()
  385. {
  386. _blockDepth++;
  387. Seal();
  388. }
  389. /// <summary>
  390. /// Unblocks the undo manager
  391. /// </summary>
  392. void Unblock()
  393. {
  394. if (_blockDepth == 0)
  395. throw new InvalidOperationException("Attempt to unblock already unblocked undo manager");
  396. _blockDepth--;
  397. }
  398. /// <summary>
  399. /// Get the currently undo group
  400. /// </summary>
  401. UndoGroup<T> CurrentGroup
  402. {
  403. get
  404. {
  405. if (_openGroups.Count > 0)
  406. return _openGroups.Peek();
  407. else
  408. return null;
  409. }
  410. }
  411. class GroupDisposer : IDisposable
  412. {
  413. public GroupDisposer(UndoManager<T> owner)
  414. {
  415. _owner = owner;
  416. }
  417. UndoManager<T> _owner;
  418. public void Dispose()
  419. {
  420. _owner.CloseGroup();
  421. }
  422. }
  423. // Private members
  424. T _context;
  425. List<UndoUnit<T>> _units = new List<UndoUnit<T>>();
  426. Stack<UndoGroup<T>> _openGroups = new Stack<UndoGroup<T>>();
  427. int _currentPos;
  428. int _unmodifiedPos;
  429. int _maxUnits;
  430. int _blockDepth;
  431. GroupDisposer _groupDisposer;
  432. }
  433. /// <summary>
  434. /// Base class for all undo units
  435. /// </summary>
  436. /// <typeparam name="T">The document context type</typeparam>
  437. public abstract class UndoUnit<T>
  438. {
  439. /// <summary>
  440. /// Constructs a new UndoUnit
  441. /// </summary>
  442. public UndoUnit()
  443. {
  444. }
  445. /// <summary>
  446. /// Constructs a new UndoUnit with a description
  447. /// </summary>
  448. /// <param name="description">The description of this unit</param>
  449. public UndoUnit(string description)
  450. {
  451. _description = description;
  452. }
  453. /// <summary>
  454. /// Gets the description of this undo unit
  455. /// </summary>
  456. public virtual string Description
  457. {
  458. get { return _description; }
  459. protected set { _description = value; }
  460. }
  461. /// <summary>
  462. /// Instructs the unit to execute the "Do" operation
  463. /// </summary>
  464. /// <param name="context">The document context object</param>
  465. public abstract void Do(T context);
  466. /// <summary>
  467. /// Instructs the unit to execute the "ReDo" operation
  468. /// </summary>
  469. /// <remarks>
  470. /// The default implementation simply calls "Do"
  471. /// </remarks>
  472. /// <param name="context">The document context object</param>
  473. public virtual void Redo(T context)
  474. {
  475. Do(context);
  476. }
  477. /// <summary>
  478. /// Instructs the unit to execute the "Undo" operation
  479. /// </summary>
  480. /// <param name="context">The document context object</param>
  481. public abstract void Undo(T context);
  482. /// <summary>
  483. /// Informs the unit that no subsequent coalescing operations
  484. /// will be appended to this unit
  485. /// </summary>
  486. public virtual void Seal()
  487. {
  488. _sealed = true;
  489. }
  490. /// <summary>
  491. /// Checks is this item is sealed
  492. /// </summary>
  493. public bool Sealed => _sealed;
  494. /// <summary>
  495. /// Gets or sets the group that owns this undo unit
  496. /// </summary>
  497. /// <remarks>
  498. /// Will be null if the undo unit isn't within a group operation
  499. /// </remarks>
  500. public UndoGroup<T> Group { get; set; }
  501. // Private members
  502. string _description;
  503. bool _sealed;
  504. }
  505. /// <summary>
  506. /// Implements an Undo unit that groups other units
  507. /// into a single operation
  508. /// </summary>
  509. /// <typeparam name="T">The document context type</typeparam>
  510. public class UndoGroup<T> : UndoUnit<T>
  511. {
  512. /// <summary>
  513. /// Constructs a new UndoGroup with a description
  514. /// </summary>
  515. /// <param name="description">The description</param>
  516. public UndoGroup(string description) : base(description)
  517. {
  518. }
  519. /// <summary>
  520. /// Notifies this group that it's been opened
  521. /// </summary>
  522. /// <param name="context">The document context object</param>
  523. public virtual void OnOpen(T context)
  524. {
  525. }
  526. /// <summary>
  527. /// Notifies this group that it's been closed
  528. /// </summary>
  529. /// <param name="context">The document context object</param>
  530. public virtual void OnClose(T context)
  531. {
  532. }
  533. /// <summary>
  534. /// Adds a unit to this group
  535. /// </summary>
  536. /// <param name="unit">The UndoUnit to be added</param>
  537. public void Add(UndoUnit<T> unit)
  538. {
  539. unit.Group = this;
  540. _units.Add(unit);
  541. }
  542. /// <summary>
  543. /// Inserts an unit to this group
  544. /// </summary>
  545. /// <param name="position">The position at which the unit should be inserted</param>
  546. /// <param name="unit">The UndoUnit to be inserted</param>
  547. public void Insert(int position, UndoUnit<T> unit)
  548. {
  549. unit.Group = this;
  550. _units.Insert(position, unit);
  551. }
  552. /// <summary>
  553. /// Gets the last UndoUnit in this group
  554. /// </summary>
  555. public UndoUnit<T> LastUnit
  556. {
  557. get
  558. {
  559. if (_units.Count > 0)
  560. return _units[_units.Count - 1];
  561. else
  562. return null;
  563. }
  564. }
  565. /// <summary>
  566. /// Get the list of units in this group
  567. /// </summary>
  568. public IReadOnlyList<UndoUnit<T>> Units => _units;
  569. /// <summary>
  570. /// The method on the UndoGroup class is never called by the
  571. /// UndoManager Never. See OnOpen and OnClose instead which
  572. /// are called as the group is constructed
  573. /// </summary>
  574. public override void Do(T context)
  575. {
  576. throw new NotImplementedException();
  577. }
  578. /// <inheritdoc />
  579. public override void Redo(T context)
  580. {
  581. foreach (var u in _units)
  582. {
  583. u.Redo(context);
  584. }
  585. }
  586. /// <inheritdoc />
  587. public override void Undo(T context)
  588. {
  589. foreach (var u in _units.Reverse<UndoUnit<T>>())
  590. {
  591. u.Undo(context);
  592. }
  593. }
  594. // Private members
  595. List<UndoUnit<T>> _units = new List<UndoUnit<T>>();
  596. }
  597. }