1use crate::types::EntityId;
4use flume::{Receiver, Sender, unbounded};
5use parking_lot::Mutex;
6use serde::Serialize;
7use std::{sync::Arc, thread};
8
9#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
10pub enum EntityEvent {
11 Created,
12 Updated,
13 Removed,
14}
15
16#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
17pub enum AllEvent {
18 Reset,
19}
20
21#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
22pub enum UndoRedoEvent {
23 Undone,
24 Redone,
25 BeginComposite,
26 EndComposite,
27 CancelComposite,
28}
29
30#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
31pub enum LongOperationEvent {
32 Started,
33 Progress,
34 Cancelled,
35 Completed,
36 Failed,
37}
38
39#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
40pub enum DirectAccessEntity {
41 All(AllEvent),
42
43 Root(EntityEvent),
44 Document(EntityEvent),
45 Frame(EntityEvent),
46 Block(EntityEvent),
47 List(EntityEvent),
48 Resource(EntityEvent),
49 Table(EntityEvent),
50 TableCell(EntityEvent),
51}
52
53#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
54pub enum DocumentEditingEvent {
55 InsertText,
56 DeleteText,
57 InsertBlock,
58 InsertImage,
59 InsertFrame,
60 InsertFormattedText,
61 CreateList,
62 InsertList,
63 AddBlockToList,
64 RemoveBlockFromList,
65 InsertFragment,
66 InsertHtmlAtPosition,
67 InsertMarkdownAtPosition,
68 InsertDjotAtPosition,
69 InsertTable,
70 RemoveTable,
71 InsertTableRow,
72 InsertTableColumn,
73 RemoveTableRow,
74 RemoveTableColumn,
75 MergeTableCells,
76 SplitTableCell,
77 WrapBlocksInFrame,
78 UnwrapFrame,
79 UnwrapBlockFromFrame,
80}
81
82#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
83pub enum DocumentFormattingEvent {
84 SetTextFormat,
85 MergeTextFormat,
86 SetBlockFormat,
87 SetFrameFormat,
88 SetTableFormat,
89 SetTableCellFormat,
90 SetListFormat,
91}
92
93#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
94pub enum DocumentIoEvent {
95 ImportPlainText,
96 ExportPlainText,
97 ImportMarkdown,
98 ExportMarkdown,
99 ImportHtml,
100 ExportHtml,
101 ImportDjot,
102 ExportDjot,
103 ExportLatex,
104 ExportDocx,
105}
106
107#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
108pub enum DocumentSearchEvent {
109 FindText,
110 FindAll,
111 ReplaceText,
112 ReplaceRanges,
113}
114
115#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
116pub enum DocumentInspectionEvent {
117 GetDocumentStats,
118 GetTextAtPosition,
119 GetBlockAtPosition,
120 ExtractFragment,
121}
122
123#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
124pub enum Origin {
125 DirectAccess(DirectAccessEntity),
126 UndoRedo(UndoRedoEvent),
127 LongOperation(LongOperationEvent),
128
129 DocumentEditing(DocumentEditingEvent),
130 DocumentFormatting(DocumentFormattingEvent),
131 DocumentIo(DocumentIoEvent),
132 DocumentSearch(DocumentSearchEvent),
133 DocumentInspection(DocumentInspectionEvent),
134}
135
136#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
137pub struct Event {
138 pub origin: Origin,
139 pub ids: Vec<EntityId>,
140 pub data: Option<String>,
141}
142
143impl Event {
144 pub fn origin_string(&self) -> String {
145 match &self.origin {
146 Origin::DirectAccess(entity) => match entity {
147 DirectAccessEntity::All(event) => format!("direct_access_all_{:?}", event),
148 DirectAccessEntity::Root(event) => format!("direct_access_root_{:?}", event),
150 DirectAccessEntity::Document(event) => {
151 format!("direct_access_document_{:?}", event)
152 }
153 DirectAccessEntity::Frame(event) => format!("direct_access_frame_{:?}", event),
154 DirectAccessEntity::Block(event) => format!("direct_access_block_{:?}", event),
155 DirectAccessEntity::List(event) => format!("direct_access_list_{:?}", event),
156 DirectAccessEntity::Resource(event) => {
157 format!("direct_access_resource_{:?}", event)
158 }
159 DirectAccessEntity::Table(event) => format!("direct_access_table_{:?}", event),
160 DirectAccessEntity::TableCell(event) => {
161 format!("direct_access_table_cell_{:?}", event)
162 }
163 },
164 Origin::UndoRedo(event) => format!("undo_redo_{:?}", event),
165 Origin::LongOperation(event) => format!("long_operation_{:?}", event),
166 Origin::DocumentEditing(event) => format!("document_editing_{:?}", event),
168 Origin::DocumentFormatting(event) => format!("document_formatting_{:?}", event),
169 Origin::DocumentIo(event) => format!("document_io_{:?}", event),
170 Origin::DocumentSearch(event) => format!("document_search_{:?}", event),
171 Origin::DocumentInspection(event) => format!("document_inspection_{:?}", event),
172 }
173 .to_lowercase()
174 }
175}
176pub struct EventBuffer {
185 buffering: bool,
186 pending: Vec<Event>,
187}
188
189impl EventBuffer {
190 pub fn new() -> Self {
191 Self {
192 buffering: false,
193 pending: Vec::new(),
194 }
195 }
196
197 pub fn begin_buffering(&mut self) {
199 self.buffering = true;
200 self.pending.clear();
201 }
202
203 pub fn push(&mut self, event: Event) {
208 if self.buffering {
209 self.pending.push(event);
210 }
211 }
212
213 pub fn flush(&mut self) -> Vec<Event> {
216 self.buffering = false;
217 std::mem::take(&mut self.pending)
218 }
219
220 pub fn discard(&mut self) {
222 self.buffering = false;
223 self.pending.clear();
224 }
225
226 pub fn is_buffering(&self) -> bool {
227 self.buffering
228 }
229}
230
231impl Default for EventBuffer {
232 fn default() -> Self {
233 Self::new()
234 }
235}
236
237pub type Queue = Arc<Mutex<Vec<Event>>>;
238
239#[derive(Debug)]
241pub struct EventHub {
242 sender: Sender<Event>,
243 receiver: Receiver<Event>,
244 queue: Queue,
245}
246
247impl Default for EventHub {
248 fn default() -> Self {
249 Self::new()
250 }
251}
252
253impl EventHub {
254 pub fn new() -> Self {
256 let (sender, receiver) = unbounded();
257 EventHub {
258 sender,
259 receiver,
260 queue: Arc::new(Mutex::new(Vec::new())),
261 }
262 }
263
264 pub fn start_event_loop(&self, shutdown_rx: Receiver<()>) -> thread::JoinHandle<()> {
272 let receiver = self.receiver.clone();
273 let queue = self.queue.clone();
274 thread::spawn(move || {
275 loop {
276 let outcome: Result<Option<Event>, ()> = flume::Selector::new()
277 .recv(&receiver, |r| r.map(Some).map_err(|_| ()))
278 .recv(&shutdown_rx, |_| Ok(None))
279 .wait();
280 match outcome {
281 Ok(Some(event)) => {
282 let mut queue = queue.lock();
283 queue.push(event);
284 }
285 Ok(None) | Err(()) => break,
286 }
287 }
288 })
289 }
290
291 pub fn send_event(&self, event: Event) {
293 if let Err(e) = self.sender.send(event) {
294 eprintln!("EventHub: failed to send event (receiver dropped): {e}");
295 }
296 }
297
298 pub fn get_queue(&self) -> Queue {
299 self.queue.clone()
300 }
301
302 pub fn subscribe_receiver(&self) -> Receiver<Event> {
309 self.receiver.clone()
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 #[test]
318 fn test_event_hub_send_and_receive() {
319 let event_hub = EventHub::new();
320 let (shutdown_tx, shutdown_rx) = flume::bounded::<()>(1);
321 let handle = event_hub.start_event_loop(shutdown_rx);
322
323 let event = Event {
324 origin: Origin::DirectAccess(DirectAccessEntity::All(AllEvent::Reset)),
325 ids: vec![EntityId::default()],
326 data: Some("test_data".to_string()),
327 };
328
329 event_hub.send_event(event.clone());
330
331 thread::sleep(std::time::Duration::from_millis(100));
332
333 let queue = event_hub.get_queue();
334 let queue = queue.lock();
335 assert_eq!(queue.len(), 1);
336 assert_eq!(queue[0], event);
337
338 drop(shutdown_tx);
340 handle.join().unwrap();
341 }
342}