operation.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. use crate::core::flowy_str::FlowyStr;
  2. use crate::core::interval::Interval;
  3. use crate::errors::OTError;
  4. use serde::{Deserialize, Serialize, __private::Formatter};
  5. use std::fmt::Display;
  6. use std::{
  7. cmp::min,
  8. fmt,
  9. fmt::Debug,
  10. ops::{Deref, DerefMut},
  11. };
  12. pub trait OperationTransform {
  13. /// Merges the operation with `other` into one operation while preserving
  14. /// the changes of both.
  15. ///
  16. /// # Arguments
  17. ///
  18. /// * `other`: The delta gonna to merge.
  19. ///
  20. /// # Examples
  21. ///
  22. /// ```
  23. /// use lib_ot::core::{OperationTransform, PlainTextDeltaBuilder};
  24. /// let document = PlainTextDeltaBuilder::new().build();
  25. /// let delta = PlainTextDeltaBuilder::new().insert("abc").build();
  26. /// let new_document = document.compose(&delta).unwrap();
  27. /// assert_eq!(new_document.content_str().unwrap(), "abc".to_owned());
  28. /// ```
  29. fn compose(&self, other: &Self) -> Result<Self, OTError>
  30. where
  31. Self: Sized;
  32. /// Transforms two operations a and b that happened concurrently and
  33. /// produces two operations a' and b'.
  34. /// (a', b') = a.transform(b)
  35. /// a.compose(b') = b.compose(a')
  36. ///
  37. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  38. where
  39. Self: Sized;
  40. /// Returns the invert delta from the other. It can be used to do the undo operation.
  41. ///
  42. /// # Arguments
  43. ///
  44. /// * `other`: Generate the undo delta for [Other]. [Other] can compose the undo delta to return
  45. /// to the previous state.
  46. ///
  47. /// # Examples
  48. ///
  49. /// ```
  50. /// use lib_ot::core::{OperationTransform, PlainTextDeltaBuilder};
  51. /// let original_document = PlainTextDeltaBuilder::new().build();
  52. /// let delta = PlainTextDeltaBuilder::new().insert("abc").build();
  53. ///
  54. /// let undo_delta = delta.invert(&original_document);
  55. /// let new_document = original_document.compose(&delta).unwrap();
  56. /// let document = new_document.compose(&undo_delta).unwrap();
  57. ///
  58. /// assert_eq!(original_document, document);
  59. ///
  60. /// ```
  61. fn invert(&self, other: &Self) -> Self;
  62. }
  63. /// Each operation can carry attributes. For example, the [RichTextAttributes] has a list of key/value attributes.
  64. /// Such as { bold: true, italic: true }.
  65. ///
  66. /// Because [Operation] is generic over the T, so you must specify the T. For example, the [PlainTextDelta]. It use
  67. /// use [PhantomAttributes] as the T. [PhantomAttributes] does nothing, just a phantom.
  68. ///
  69. pub trait Attributes: Default + Display + Eq + PartialEq + Clone + Debug + OperationTransform {
  70. fn is_empty(&self) -> bool {
  71. true
  72. }
  73. /// Remove the empty attribute which value is None.
  74. fn remove_empty(&mut self) {
  75. // Do nothing
  76. }
  77. fn extend_other(&mut self, _other: Self) {
  78. // Do nothing
  79. }
  80. }
  81. /// [Operation] consists of three types.
  82. /// * Delete
  83. /// * Retain
  84. /// * Insert
  85. ///
  86. /// The [T] should support serde if you want to serialize/deserialize the operation
  87. /// to json string. You could check out the operation_serde.rs for more information.
  88. ///
  89. #[derive(Debug, Clone, Eq, PartialEq)]
  90. pub enum Operation<T: Attributes> {
  91. Delete(usize),
  92. Retain(Retain<T>),
  93. Insert(Insert<T>),
  94. }
  95. impl<T> Operation<T>
  96. where
  97. T: Attributes,
  98. {
  99. pub fn delete(n: usize) -> Self {
  100. Self::Delete(n)
  101. }
  102. /// Create a [Retain] operation with the given attributes
  103. pub fn retain_with_attributes(n: usize, attributes: T) -> Self {
  104. Self::Retain(Retain { n, attributes })
  105. }
  106. /// Create a [Retain] operation without attributes
  107. pub fn retain(n: usize) -> Self {
  108. Self::Retain(Retain {
  109. n,
  110. attributes: T::default(),
  111. })
  112. }
  113. /// Create a [Insert] operation with the given attributes
  114. pub fn insert_with_attributes(s: &str, attributes: T) -> Self {
  115. Self::Insert(Insert {
  116. s: FlowyStr::from(s),
  117. attributes,
  118. })
  119. }
  120. /// Create a [Insert] operation without attributes
  121. pub fn insert(s: &str) -> Self {
  122. Self::Insert(Insert {
  123. s: FlowyStr::from(s),
  124. attributes: T::default(),
  125. })
  126. }
  127. /// Return the String if the operation is [Insert] operation, otherwise return the empty string.
  128. pub fn get_data(&self) -> &str {
  129. match self {
  130. Operation::Delete(_) => "",
  131. Operation::Retain(_) => "",
  132. Operation::Insert(insert) => &insert.s,
  133. }
  134. }
  135. pub fn get_attributes(&self) -> T {
  136. match self {
  137. Operation::Delete(_) => T::default(),
  138. Operation::Retain(retain) => retain.attributes.clone(),
  139. Operation::Insert(insert) => insert.attributes.clone(),
  140. }
  141. }
  142. pub fn set_attributes(&mut self, attributes: T) {
  143. match self {
  144. Operation::Delete(_) => log::error!("Delete should not contains attributes"),
  145. Operation::Retain(retain) => retain.attributes = attributes,
  146. Operation::Insert(insert) => insert.attributes = attributes,
  147. }
  148. }
  149. pub fn has_attribute(&self) -> bool {
  150. !self.get_attributes().is_empty()
  151. }
  152. pub fn len(&self) -> usize {
  153. match self {
  154. Operation::Delete(n) => *n,
  155. Operation::Retain(r) => r.n,
  156. Operation::Insert(i) => i.utf16_size(),
  157. }
  158. }
  159. pub fn is_empty(&self) -> bool {
  160. self.len() == 0
  161. }
  162. #[allow(dead_code)]
  163. pub fn split(&self, index: usize) -> (Option<Operation<T>>, Option<Operation<T>>) {
  164. debug_assert!(index < self.len());
  165. let left;
  166. let right;
  167. match self {
  168. Operation::Delete(n) => {
  169. left = Some(Operation::<T>::delete(index));
  170. right = Some(Operation::<T>::delete(*n - index));
  171. }
  172. Operation::Retain(retain) => {
  173. left = Some(Operation::<T>::delete(index));
  174. right = Some(Operation::<T>::delete(retain.n - index));
  175. }
  176. Operation::Insert(insert) => {
  177. let attributes = self.get_attributes();
  178. left = Some(Operation::<T>::insert_with_attributes(
  179. &insert.s[0..index],
  180. attributes.clone(),
  181. ));
  182. right = Some(Operation::<T>::insert_with_attributes(
  183. &insert.s[index..insert.utf16_size()],
  184. attributes,
  185. ));
  186. }
  187. }
  188. (left, right)
  189. }
  190. /// Returns an operation with the specified width.
  191. /// # Arguments
  192. ///
  193. /// * `interval`: Specify the shrink width of the operation.
  194. ///
  195. /// # Examples
  196. ///
  197. /// ```
  198. /// use lib_ot::core::{Interval, Operation, PhantomAttributes};
  199. /// let operation = Operation::<PhantomAttributes>::insert("1234");
  200. ///
  201. /// let op1 = operation.shrink(Interval::new(0,3)).unwrap();
  202. /// assert_eq!(op1 , Operation::insert("123"));
  203. ///
  204. /// let op2= operation.shrink(Interval::new(3,4)).unwrap();
  205. /// assert_eq!(op2, Operation::insert("4"));
  206. /// ```
  207. pub fn shrink(&self, interval: Interval) -> Option<Operation<T>> {
  208. let op = match self {
  209. Operation::Delete(n) => Operation::delete(min(*n, interval.size())),
  210. Operation::Retain(retain) => {
  211. Operation::retain_with_attributes(min(retain.n, interval.size()), retain.attributes.clone())
  212. }
  213. Operation::Insert(insert) => {
  214. if interval.start > insert.utf16_size() {
  215. Operation::insert("")
  216. } else {
  217. let s = insert.s.sub_str(interval).unwrap_or_else(|| "".to_owned());
  218. Operation::insert_with_attributes(&s, insert.attributes.clone())
  219. }
  220. }
  221. };
  222. match op.is_empty() {
  223. true => None,
  224. false => Some(op),
  225. }
  226. }
  227. pub fn is_delete(&self) -> bool {
  228. if let Operation::Delete(_) = self {
  229. return true;
  230. }
  231. false
  232. }
  233. pub fn is_insert(&self) -> bool {
  234. if let Operation::Insert(_) = self {
  235. return true;
  236. }
  237. false
  238. }
  239. pub fn is_retain(&self) -> bool {
  240. if let Operation::Retain(_) = self {
  241. return true;
  242. }
  243. false
  244. }
  245. pub fn is_plain(&self) -> bool {
  246. match self {
  247. Operation::Delete(_) => true,
  248. Operation::Retain(retain) => retain.is_plain(),
  249. Operation::Insert(insert) => insert.is_plain(),
  250. }
  251. }
  252. }
  253. impl<T> fmt::Display for Operation<T>
  254. where
  255. T: Attributes,
  256. {
  257. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  258. f.write_str("{")?;
  259. match self {
  260. Operation::Delete(n) => {
  261. f.write_fmt(format_args!("delete: {}", n))?;
  262. }
  263. Operation::Retain(r) => {
  264. f.write_fmt(format_args!("{}", r))?;
  265. }
  266. Operation::Insert(i) => {
  267. f.write_fmt(format_args!("{}", i))?;
  268. }
  269. }
  270. f.write_str("}")?;
  271. Ok(())
  272. }
  273. }
  274. #[derive(Clone, Debug, Eq, PartialEq)]
  275. pub struct Retain<T: Attributes> {
  276. pub n: usize,
  277. pub attributes: T,
  278. }
  279. impl<T> fmt::Display for Retain<T>
  280. where
  281. T: Attributes,
  282. {
  283. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  284. if self.attributes.is_empty() {
  285. f.write_fmt(format_args!("retain: {}", self.n))
  286. } else {
  287. f.write_fmt(format_args!("retain: {}, attributes: {}", self.n, self.attributes))
  288. }
  289. }
  290. }
  291. impl<T> Retain<T>
  292. where
  293. T: Attributes,
  294. {
  295. pub fn merge_or_new(&mut self, n: usize, attributes: T) -> Option<Operation<T>> {
  296. // tracing::trace!(
  297. // "merge_retain_or_new_op: len: {:?}, l: {} - r: {}",
  298. // n,
  299. // self.attributes,
  300. // attributes
  301. // );
  302. if self.attributes == attributes {
  303. self.n += n;
  304. None
  305. } else {
  306. Some(Operation::retain_with_attributes(n, attributes))
  307. }
  308. }
  309. pub fn is_plain(&self) -> bool {
  310. self.attributes.is_empty()
  311. }
  312. }
  313. impl<T> std::convert::From<usize> for Retain<T>
  314. where
  315. T: Attributes,
  316. {
  317. fn from(n: usize) -> Self {
  318. Retain {
  319. n,
  320. attributes: T::default(),
  321. }
  322. }
  323. }
  324. impl<T> Deref for Retain<T>
  325. where
  326. T: Attributes,
  327. {
  328. type Target = usize;
  329. fn deref(&self) -> &Self::Target {
  330. &self.n
  331. }
  332. }
  333. impl<T> DerefMut for Retain<T>
  334. where
  335. T: Attributes,
  336. {
  337. fn deref_mut(&mut self) -> &mut Self::Target {
  338. &mut self.n
  339. }
  340. }
  341. #[derive(Clone, Debug, Eq, PartialEq)]
  342. pub struct Insert<T: Attributes> {
  343. pub s: FlowyStr,
  344. pub attributes: T,
  345. }
  346. impl<T> fmt::Display for Insert<T>
  347. where
  348. T: Attributes,
  349. {
  350. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  351. let mut s = self.s.clone();
  352. if s.ends_with('\n') {
  353. s.pop();
  354. if s.is_empty() {
  355. s = "new_line".into();
  356. }
  357. }
  358. if self.attributes.is_empty() {
  359. f.write_fmt(format_args!("insert: {}", s))
  360. } else {
  361. f.write_fmt(format_args!("insert: {}, attributes: {}", s, self.attributes))
  362. }
  363. }
  364. }
  365. impl<T> Insert<T>
  366. where
  367. T: Attributes,
  368. {
  369. pub fn utf16_size(&self) -> usize {
  370. self.s.utf16_len()
  371. }
  372. pub fn merge_or_new_op(&mut self, s: &str, attributes: T) -> Option<Operation<T>> {
  373. if self.attributes == attributes {
  374. self.s += s;
  375. None
  376. } else {
  377. Some(Operation::<T>::insert_with_attributes(s, attributes))
  378. }
  379. }
  380. pub fn is_plain(&self) -> bool {
  381. self.attributes.is_empty()
  382. }
  383. }
  384. impl<T> std::convert::From<String> for Insert<T>
  385. where
  386. T: Attributes,
  387. {
  388. fn from(s: String) -> Self {
  389. Insert {
  390. s: s.into(),
  391. attributes: T::default(),
  392. }
  393. }
  394. }
  395. impl<T> std::convert::From<&str> for Insert<T>
  396. where
  397. T: Attributes,
  398. {
  399. fn from(s: &str) -> Self {
  400. Insert::from(s.to_owned())
  401. }
  402. }
  403. impl<T> std::convert::From<FlowyStr> for Insert<T>
  404. where
  405. T: Attributes,
  406. {
  407. fn from(s: FlowyStr) -> Self {
  408. Insert {
  409. s,
  410. attributes: T::default(),
  411. }
  412. }
  413. }
  414. #[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize)]
  415. pub struct PhantomAttributes();
  416. impl fmt::Display for PhantomAttributes {
  417. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  418. f.write_str("PhantomAttributes")
  419. }
  420. }
  421. impl Attributes for PhantomAttributes {}
  422. impl OperationTransform for PhantomAttributes {
  423. fn compose(&self, _other: &Self) -> Result<Self, OTError> {
  424. Ok(self.clone())
  425. }
  426. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError> {
  427. Ok((self.clone(), other.clone()))
  428. }
  429. fn invert(&self, _other: &Self) -> Self {
  430. self.clone()
  431. }
  432. }