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