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}
113
114#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
115pub enum DocumentInspectionEvent {
116 GetDocumentStats,
117 GetTextAtPosition,
118 GetBlockAtPosition,
119 ExtractFragment,
120}
121
122#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
123pub enum Origin {
124 DirectAccess(DirectAccessEntity),
125 UndoRedo(UndoRedoEvent),
126 LongOperation(LongOperationEvent),
127
128 DocumentEditing(DocumentEditingEvent),
129 DocumentFormatting(DocumentFormattingEvent),
130 DocumentIo(DocumentIoEvent),
131 DocumentSearch(DocumentSearchEvent),
132 DocumentInspection(DocumentInspectionEvent),
133}
134
135#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize)]
136pub struct Event {
137 pub origin: Origin,
138 pub ids: Vec<EntityId>,
139 pub data: Option<String>,
140}
141
142impl Event {
143 pub fn origin_string(&self) -> String {
144 match &self.origin {
145 Origin::DirectAccess(entity) => match entity {
146 DirectAccessEntity::All(event) => format!("direct_access_all_{:?}", event),
147 DirectAccessEntity::Root(event) => format!("direct_access_root_{:?}", event),
149 DirectAccessEntity::Document(event) => {
150 format!("direct_access_document_{:?}", event)
151 }
152 DirectAccessEntity::Frame(event) => format!("direct_access_frame_{:?}", event),
153 DirectAccessEntity::Block(event) => format!("direct_access_block_{:?}", event),
154 DirectAccessEntity::List(event) => format!("direct_access_list_{:?}", event),
155 DirectAccessEntity::Resource(event) => {
156 format!("direct_access_resource_{:?}", event)
157 }
158 DirectAccessEntity::Table(event) => format!("direct_access_table_{:?}", event),
159 DirectAccessEntity::TableCell(event) => {
160 format!("direct_access_table_cell_{:?}", event)
161 }
162 },
163 Origin::UndoRedo(event) => format!("undo_redo_{:?}", event),
164 Origin::LongOperation(event) => format!("long_operation_{:?}", event),
165 Origin::DocumentEditing(event) => format!("document_editing_{:?}", event),
167 Origin::DocumentFormatting(event) => format!("document_formatting_{:?}", event),
168 Origin::DocumentIo(event) => format!("document_io_{:?}", event),
169 Origin::DocumentSearch(event) => format!("document_search_{:?}", event),
170 Origin::DocumentInspection(event) => format!("document_inspection_{:?}", event),
171 }
172 .to_lowercase()
173 }
174}
175pub struct EventBuffer {
184 buffering: bool,
185 pending: Vec<Event>,
186}
187
188impl EventBuffer {
189 pub fn new() -> Self {
190 Self {
191 buffering: false,
192 pending: Vec::new(),
193 }
194 }
195
196 pub fn begin_buffering(&mut self) {
198 self.buffering = true;
199 self.pending.clear();
200 }
201
202 pub fn push(&mut self, event: Event) {
207 if self.buffering {
208 self.pending.push(event);
209 }
210 }
211
212 pub fn flush(&mut self) -> Vec<Event> {
215 self.buffering = false;
216 std::mem::take(&mut self.pending)
217 }
218
219 pub fn discard(&mut self) {
221 self.buffering = false;
222 self.pending.clear();
223 }
224
225 pub fn is_buffering(&self) -> bool {
226 self.buffering
227 }
228}
229
230impl Default for EventBuffer {
231 fn default() -> Self {
232 Self::new()
233 }
234}
235
236pub type Queue = Arc<Mutex<Vec<Event>>>;
237
238#[derive(Debug)]
240pub struct EventHub {
241 sender: Sender<Event>,
242 receiver: Receiver<Event>,
243 queue: Queue,
244}
245
246impl Default for EventHub {
247 fn default() -> Self {
248 Self::new()
249 }
250}
251
252impl EventHub {
253 pub fn new() -> Self {
255 let (sender, receiver) = unbounded();
256 EventHub {
257 sender,
258 receiver,
259 queue: Arc::new(Mutex::new(Vec::new())),
260 }
261 }
262
263 pub fn start_event_loop(&self, shutdown_rx: Receiver<()>) -> thread::JoinHandle<()> {
271 let receiver = self.receiver.clone();
272 let queue = self.queue.clone();
273 thread::spawn(move || {
274 loop {
275 let outcome: Result<Option<Event>, ()> = flume::Selector::new()
276 .recv(&receiver, |r| r.map(Some).map_err(|_| ()))
277 .recv(&shutdown_rx, |_| Ok(None))
278 .wait();
279 match outcome {
280 Ok(Some(event)) => {
281 let mut queue = queue.lock();
282 queue.push(event);
283 }
284 Ok(None) | Err(()) => break,
285 }
286 }
287 })
288 }
289
290 pub fn send_event(&self, event: Event) {
292 if let Err(e) = self.sender.send(event) {
293 eprintln!("EventHub: failed to send event (receiver dropped): {e}");
294 }
295 }
296
297 pub fn get_queue(&self) -> Queue {
298 self.queue.clone()
299 }
300
301 pub fn subscribe_receiver(&self) -> Receiver<Event> {
308 self.receiver.clone()
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn test_event_hub_send_and_receive() {
318 let event_hub = EventHub::new();
319 let (shutdown_tx, shutdown_rx) = flume::bounded::<()>(1);
320 let handle = event_hub.start_event_loop(shutdown_rx);
321
322 let event = Event {
323 origin: Origin::DirectAccess(DirectAccessEntity::All(AllEvent::Reset)),
324 ids: vec![EntityId::default()],
325 data: Some("test_data".to_string()),
326 };
327
328 event_hub.send_event(event.clone());
329
330 thread::sleep(std::time::Duration::from_millis(100));
331
332 let queue = event_hub.get_queue();
333 let queue = queue.lock();
334 assert_eq!(queue.len(), 1);
335 assert_eq!(queue[0], event);
336
337 drop(shutdown_tx);
339 handle.join().unwrap();
340 }
341}