Skip to main content

Mountain/ApplicationState/DTO/
DocumentStateDTO.rs

1//! # DocumentStateDTO
2//!
3//! # RESPONSIBILITY
4//! - Data transfer object for text document state
5//! - Serializable format for gRPC/IPC transmission
6//! - Used by Mountain to track document lifecycle and sync with Air
7//!
8//! # FIELDS
9//! - URI: Unique document resource identifier
10//! - LanguageIdentifier: Language ID for syntax highlighting
11//! - Version: Client-side version for change tracking
12//! - Lines: Document content split into lines
13//! - EOL: End-of-line sequence (\n or \r\n)
14//! - IsDirty: Indicates unsaved changes
15//! - Encoding: File encoding (e.g., utf8)
16//! - VersionIdentifier: Internal version for host tracking
17//!
18//! TODO (Mountain→Air Split): If Air implements a background document sync
19//! service, consider delegating delta change validation or conflict resolution
20//! to Air. For now, Mountain handles this synchronously to ensure UI
21//! responsiveness.
22
23use CommonLibrary::{Error::CommonError::CommonError, Utility::Serialization::URLSerializationHelper};
24use serde::{Deserialize, Serialize};
25use serde_json::Value;
26use url::Url;
27
28use crate::{ApplicationState::Internal::TextProcessing::AnalyzeTextLinesAndEOL::AnalyzeTextLinesAndEOL, dev_log};
29use super::{RPCModelContentChangeDTO::RPCModelContentChangeDTO, RPCRangeDTO::RPCRangeDTO};
30
31/// Maximum line count for a document to prevent memory exhaustion
32const MAX_DOCUMENT_LINES:usize = 1_000_000;
33
34/// Maximum line length to prevent line-based denial of service
35const MAX_LINE_LENGTH:usize = 100_000;
36
37/// Maximum language identifier string length
38const MAX_LANGUAGE_ID_LENGTH:usize = 128;
39
40/// Represents the complete in-memory state of a single text document.
41#[derive(Serialize, Deserialize, Clone, Debug)]
42#[serde(rename_all = "camelCase")]
43pub struct DocumentStateDTO {
44	/// The unique resource identifier for this document.
45	#[serde(rename = "uri", with = "URLSerializationHelper")]
46	pub URI:Url,
47
48	/// The VS Code language identifier (e.g., "rust", "typescript").
49	#[serde(skip_serializing_if = "String::is_empty")]
50	pub LanguageIdentifier:String,
51
52	/// The version number, incremented on each change from the client.
53	pub Version:i64,
54
55	/// The content of the document, split into lines.
56	pub Lines:Vec<String>,
57
58	/// The detected end-of-line sequence (e.g., `\n` or `\r\n`).
59	#[serde(rename = "eol")]
60	pub EOL:String,
61
62	/// A flag indicating if the in-memory version has unsaved changes.
63	pub IsDirty:bool,
64
65	/// The detected file encoding (e.g., "utf8").
66	pub Encoding:String,
67
68	/// An internal version number, used for tracking changes within the host.
69	pub VersionIdentifier:i64,
70}
71
72impl DocumentStateDTO {
73	/// Creates a new `DocumentStateDTO` from its initial content with
74	/// validation.
75	///
76	/// # Arguments
77	/// * `URI` - The document resource URI
78	/// * `LanguageIdentifier` - Optional language ID for syntax highlighting
79	/// * `Content` - The initial document content
80	///
81	/// # Returns
82	/// Result containing the DTO or an error if validation fails
83	///
84	/// # Errors
85	/// Returns `CommonError` if:
86	/// - Language identifier exceeds maximum length
87	/// - Document exceeds maximum line count
88	/// - Any line exceeds maximum length
89	/// - URI is empty
90	pub fn Create(URI:Url, LanguageIdentifier:Option<String>, Content:String) -> Result<Self, CommonError> {
91		// Validate URI is not empty
92		if URI.as_str().is_empty() {
93			return Err(CommonError::InvalidArgument {
94				ArgumentName:"URI".into(),
95				Reason:"URI cannot be empty".into(),
96			});
97		}
98
99		let LanguageID = LanguageIdentifier.unwrap_or_else(|| "plaintext".to_string());
100
101		// Validate language identifier length
102		if LanguageID.len() > MAX_LANGUAGE_ID_LENGTH {
103			return Err(CommonError::InvalidArgument {
104				ArgumentName:"LanguageIdentifier".into(),
105				Reason:format!("Language identifier exceeds maximum length of {} bytes", MAX_LANGUAGE_ID_LENGTH),
106			});
107		}
108
109		let (Lines, EOL) = AnalyzeTextLinesAndEOL(&Content);
110
111		// Validate document line count
112		if Lines.len() > MAX_DOCUMENT_LINES {
113			return Err(CommonError::InvalidArgument {
114				ArgumentName:"Content".into(),
115				Reason:format!("Document exceeds maximum line count of {}", MAX_DOCUMENT_LINES),
116			});
117		}
118
119		// Validate individual line lengths
120		for (Index, Line) in Lines.iter().enumerate() {
121			if Line.len() > MAX_LINE_LENGTH {
122				return Err(CommonError::InvalidArgument {
123					ArgumentName:"Content".into(),
124					Reason:format!("Line {} exceeds maximum length of {} bytes", Index + 1, MAX_LINE_LENGTH),
125				});
126			}
127		}
128
129		let Encoding = "utf8".to_string();
130
131		Ok(Self {
132			URI,
133
134			LanguageIdentifier:LanguageID,
135
136			Version:1,
137
138			Lines,
139
140			EOL,
141
142			IsDirty:false,
143
144			Encoding,
145
146			VersionIdentifier:1,
147		})
148	}
149
150	/// Creates a new `DocumentStateDTO` without validation for internal use.
151	/// This should only be called with trusted data sources.
152	pub fn CreateUnsafe(
153		URI:Url,
154		LanguageIdentifier:String,
155		Lines:Vec<String>,
156		EOL:String,
157		IsDirty:bool,
158		Encoding:String,
159		Version:i64,
160		VersionIdentifier:i64,
161	) -> Self {
162		Self {
163			URI,
164			LanguageIdentifier,
165			Version,
166			Lines,
167			EOL,
168			IsDirty,
169			Encoding,
170			VersionIdentifier,
171		}
172	}
173
174	/// Reconstructs the full text content of the document from its lines.
175	pub fn GetText(&self) -> String { self.Lines.join(&self.EOL) }
176
177	/// Converts the struct to a `serde_json::Value`, useful for notifications.
178	pub fn ToDTO(&self) -> Result<Value, CommonError> {
179		serde_json::to_value(self).map_err(|Error| CommonError::SerializationError { Description:Error.to_string() })
180	}
181
182	/// Applies a set of changes to the document. This can be a full text
183	/// replacement or a collection of delta changes.
184	pub fn ApplyChanges(&mut self, NewVersion:i64, ChangesValue:&Value) -> Result<(), CommonError> {
185		// Ignore stale changes.
186		if NewVersion <= self.Version {
187			return Ok(());
188		}
189
190		// Attempt to deserialize as an array of delta changes first.
191		if let Ok(RPCChange) = serde_json::from_value::<Vec<RPCModelContentChangeDTO>>(ChangesValue.clone()) {
192			dev_log!("model", "applying {} delta change(s) to document {}", RPCChange.len(), self.URI);
193
194			self.Lines = ApplyDeltaChanges(&self.Lines, &self.EOL, &RPCChange);
195		} else if let Some(FullText) = ChangesValue.as_str() {
196			// If it's not deltas, check if it's a full text replacement.
197			let (NewLines, NewEOL) = AnalyzeTextLinesAndEOL(FullText);
198
199			self.Lines = NewLines;
200
201			self.EOL = NewEOL;
202		} else {
203			return Err(CommonError::InvalidArgument {
204				ArgumentName:"ChangesValue".into(),
205
206				Reason:format!(
207					"Invalid change format for {}: expected string or RPCModelContentChangeDTO array.",
208					self.URI
209				),
210			});
211		}
212
213		// Update metadata after changes have been applied.
214		self.Version = NewVersion;
215
216		self.VersionIdentifier += 1;
217
218		self.IsDirty = true;
219
220		Ok(())
221	}
222}
223
224/// Applies delta changes to the document text and returns the updated lines.
225///
226/// This function:
227/// 1. Sorts changes in reverse order (by start position) to prevent offset
228///    corruption
229/// 2. Converts line/column positions to byte offsets in the full text
230/// 3. Applies each change (delete range + insert new text)
231/// 4. Splits the result back into lines
232///
233/// # Arguments
234/// * `Lines` - The current document lines
235/// * `EOL` - The end-of-line sequence to use
236/// * `RPCChange` - Array of changes to apply
237///
238/// # Returns
239/// Updated lines vector after applying all changes
240fn ApplyDeltaChanges(Lines:&[String], EOL:&str, RPCChange:&[RPCModelContentChangeDTO]) -> Vec<String> {
241	// Join lines into full text for offset-based manipulation
242	let mut ResultText = Lines.join(EOL);
243
244	// If no changes, return original lines
245	if RPCChange.is_empty() {
246		return Lines.to_vec();
247	}
248
249	// Sort changes in reverse order of position to prevent offset corruption
250	// When applying multiple changes, earlier changes shift positions for later
251	// changes. By applying from end to beginning, all offsets remain valid.
252	let mut SortedChanges:Vec<&RPCModelContentChangeDTO> = RPCChange.iter().collect();
253	SortedChanges.sort_by(|a, b| CMP_Range_Position(&b.Range, &a.Range));
254
255	// Apply each change to the text
256	for Change in SortedChanges {
257		// Convert (line, column) to byte offset
258		let StartOffset = PositionToOffset(&ResultText, EOL, &Change.Range.StartLineNumber, &Change.Range.StartColumn);
259		let EndOffset = PositionToOffset(&ResultText, EOL, &Change.Range.EndLineNumber, &Change.Range.EndColumn);
260
261		// Validate offsets
262		if StartOffset > EndOffset {
263			dev_log!(
264				"model",
265				"error: invalid range: start ({}) > end ({}) for text length {}",
266				StartOffset,
267				EndOffset,
268				ResultText.len()
269			);
270			continue;
271		}
272
273		let TextLength = ResultText.len();
274		if StartOffset > TextLength || EndOffset > TextLength {
275			dev_log!(
276				"model",
277				"error: out of bounds: start ({}) or end ({}) exceeds text length {}",
278				StartOffset,
279				EndOffset,
280				TextLength
281			);
282			continue;
283		}
284
285		// Remove old text and insert new text
286		// Safe slice operation: validated offsets above
287		let OldText = ResultText.as_bytes();
288		ResultText =
289			String::from_utf8_lossy(&[&OldText[..StartOffset], Change.Text.as_bytes(), &OldText[EndOffset..]].concat())
290				.into_owned();
291	}
292
293	// Re-split the result into lines
294	AnalyzeTextLinesAndEOL(&ResultText).0
295}
296
297/// Converts line/column position to byte offset in text.
298///
299/// VSCode LSP uses 0-based line numbers and 0-based column numbers.
300/// This function matches that convention.
301fn PositionToOffset(Text:&str, EOL:&str, LineNumber:&usize, Column:&usize) -> usize {
302	let Lines:Vec<&str> = Text.split(EOL).collect();
303	let EOLLength = EOL.len();
304
305	let mut Offset = 0;
306
307	// Add length of all preceding lines plus their EOL markers
308	for LineIndex in 0..*LineNumber {
309		if LineIndex < Lines.len() {
310			Offset += Lines[LineIndex].len() + EOLLength;
311		}
312	}
313
314	// Add column offset within the current line
315	if *LineNumber < Lines.len() {
316		// Column is in character positions, convert to byte offset
317		let CurrentLine = Lines[*LineNumber];
318		let CharOffset = CurrentLine
319			.char_indices()
320			.nth(*Column)
321			.map_or(CurrentLine.len(), |(offset, _)| offset);
322		Offset += CharOffset;
323	}
324
325	Offset
326}
327
328/// Compares two RPC ranges to determine their order in the document.
329/// Returns negative if a comes before b, zero if equal, positive if a comes
330/// after b.
331fn CMP_Range_Position(A:&RPCRangeDTO, B:&RPCRangeDTO) -> std::cmp::Ordering {
332	A.StartLineNumber
333		.cmp(&B.StartLineNumber)
334		.then_with(|| A.StartColumn.cmp(&B.StartColumn))
335}