1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! Constructors, file IO, event-channel wiring, and ID generation
//!
//! Provides the various ways to build an `EditorDocument` (empty, from a
//! string, from disk), the persistence helpers, and the private `emit`
//! helper shared with the editing submodules.
use super::EditorDocument;
#[cfg(feature = "std")]
use super::EventSender;
use crate::core::errors::{EditorError, Result};
use crate::core::history::UndoManager;
use ass_core::parser::Script;
#[cfg(feature = "std")]
use crate::events::DocumentEvent;
#[cfg(not(feature = "std"))]
use alloc::{format, string::String};
impl EditorDocument {
/// Create a new empty document
pub fn new() -> Self {
Self {
#[cfg(feature = "rope")]
text_rope: ropey::Rope::new(),
#[cfg(not(feature = "rope"))]
text_content: String::new(),
id: Self::generate_id(),
modified: false,
file_path: None,
#[cfg(feature = "plugins")]
registry_integration: None,
history: UndoManager::new(),
#[cfg(feature = "std")]
event_tx: None,
#[cfg(feature = "stream")]
incremental_parser: crate::core::incremental::IncrementalParser::new(),
validator: crate::utils::validator::LazyValidator::new(),
}
}
/// Create a new document with event channel
#[cfg(feature = "std")]
pub fn with_event_channel(event_tx: EventSender) -> Self {
let mut doc = Self::new();
doc.event_tx = Some(event_tx);
doc
}
/// Create document from file path
#[cfg(feature = "std")]
pub fn from_file(path: &str) -> Result<Self> {
use std::fs;
let content = fs::read_to_string(path).map_err(|e| EditorError::IoError(e.to_string()))?;
let mut doc = Self::from_content(&content)?;
doc.file_path = Some(path.to_string());
Ok(doc)
}
/// Save document to file
#[cfg(feature = "std")]
pub fn save(&mut self) -> Result<()> {
if let Some(path) = self.file_path.clone() {
self.save_to_file(&path)
} else {
Err(EditorError::IoError(
"No file path set for document".to_string(),
))
}
}
/// Save document to specific file path
#[cfg(feature = "std")]
pub fn save_to_file(&mut self, path: &str) -> Result<()> {
use std::fs;
let content = self.text();
fs::write(path, content).map_err(|e| EditorError::IoError(e.to_string()))?;
self.modified = false;
self.file_path = Some(path.to_string());
Ok(())
}
/// Create document with specific ID
pub fn with_id(id: String) -> Self {
let mut doc = Self::new();
doc.id = id;
doc
}
/// Emit an event to the event channel
#[cfg(feature = "std")]
pub(super) fn emit(&mut self, event: DocumentEvent) {
if let Some(tx) = &mut self.event_tx {
let _ = tx.send(event);
}
}
/// Set the event channel for this document
#[cfg(feature = "std")]
pub fn set_event_channel(&mut self, event_tx: EventSender) {
self.event_tx = Some(event_tx);
}
/// Check if document has an event channel
#[cfg(feature = "std")]
pub fn has_event_channel(&self) -> bool {
self.event_tx.is_some()
}
/// Load document from string content
///
/// Creates a new `EditorDocument` from ASS subtitle content. The content
/// is validated during creation to ensure it's parseable.
///
/// # Examples
///
/// ```
/// use ass_editor::EditorDocument;
///
/// let content = r#"
/// [Script Info]
/// Title: My Subtitle
///
/// [V4+ Styles]
/// Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
/// Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1
///
/// [Events]
/// Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
/// Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Hello World
/// "#;
///
/// let doc = EditorDocument::from_content(content).unwrap();
/// assert!(doc.text().contains("Hello World"));
/// ```
///
/// # Errors
///
/// Returns `Err` if the content cannot be parsed as valid ASS format.
pub fn from_content(content: &str) -> Result<Self> {
// Validate that content can be parsed
let _ = Script::parse(content).map_err(EditorError::from)?;
#[cfg(feature = "stream")]
let mut incremental_parser = crate::core::incremental::IncrementalParser::new();
#[cfg(feature = "stream")]
incremental_parser.initialize_cache(content);
Ok(Self {
#[cfg(feature = "rope")]
text_rope: ropey::Rope::from_str(content),
#[cfg(not(feature = "rope"))]
text_content: content.to_string(),
id: Self::generate_id(),
modified: false,
file_path: None,
#[cfg(feature = "plugins")]
registry_integration: None,
history: UndoManager::new(),
#[cfg(feature = "std")]
event_tx: None,
#[cfg(feature = "stream")]
incremental_parser,
validator: crate::utils::validator::LazyValidator::new(),
})
}
/// Generate unique document ID
fn generate_id() -> String {
// Simple ID generation - in production might use UUID
#[cfg(feature = "std")]
{
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!("doc_{timestamp}")
}
#[cfg(not(feature = "std"))]
{
use core::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
let id = COUNTER.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
format!("doc_{id}")
}
}
}