Skip to main content

swls_core/
document.rs

1//! Editor lifecycle of documents: `didOpen` / `didClose`.
2//!
3//! A URL can be both a document the server loaded by itself ([`Background`]:
4//! LOV ontologies, `owl:imports`, configured ontologies and shapes) and one the
5//! user opens in the editor, e.g. after goto-definition into the ontology cache.
6//! They share one entity, with these rules:
7//!
8//! - While the editor has it [`Open`], the editor buffer is the document's text.
9//!   Edits are analysed like any open document, but never reach the shared store
10//!   ([`load_store`](crate::store::load_store) skips open documents), and a late
11//!   background load does not overwrite the buffer
12//!   ([`spawn_background`](crate::systems::spawn_background)).
13//! - On close, a background document gets the server's copy back: the file on
14//!   disk (for the cache, the server's snapshot; for the user's own file, what
15//!   they saved), or the [`Snapshot`] taken on open.
16//!
17//! The LSP has no way to make a document read-only in the editor. Cache files
18//! are read-only on disk, and opening one shows a notice explaining that edits
19//! are not used.
20
21use std::collections::HashMap;
22
23use bevy_ecs::prelude::*;
24
25use crate::{
26    feature::{diagnostics::DiagnosticPublisher, parse::Label as ParseLabel},
27    lsp_types::{Diagnostic, DiagnosticSeverity, Position, Range, TextDocumentItem, Url},
28    prelude::*,
29};
30
31/// Diagnostic reason of the notice shown on an open cache file.
32const CACHED_COPY: &str = "cached_copy";
33
34/// Open `item` in the editor and parse it. Returns its entity.
35pub fn open_document(world: &mut World, item: TextDocumentItem) -> Entity {
36    let url = item.uri.clone();
37
38    // Keep the server's copy of a background document before the editor buffer
39    // replaces it.
40    let mut background = false;
41    if let Some(e) = find_document(world, &url) {
42        let entity = world.entity(e);
43        background = entity.contains::<Background>();
44        if background && !entity.contains::<Open>() && !entity.contains::<Snapshot>() {
45            if let Some(source) = entity.get::<Source>() {
46                let snapshot = Snapshot(source.0.clone());
47                world.entity_mut(e).insert(snapshot);
48            }
49        }
50    }
51
52    // Publish the notice before spawning: spawning already runs the parse
53    // schedule, whose diagnostics are merged with it.
54    let is_cache = world
55        .get_resource::<Fs>()
56        .is_some_and(|fs| fs.0.is_cache_url(&url));
57    if background && is_cache {
58        if let Some(mut publisher) = world.get_resource_mut::<DiagnosticPublisher>() {
59            let _ = publisher.publish(&item, vec![cached_copy_notice()], CACHED_COPY);
60        }
61    }
62
63    let lang_id = Some(item.language_id.clone());
64    let spawn = spawn_or_insert(
65        url.clone(),
66        (
67            Source(item.text.clone()),
68            Label(url.clone()),
69            RopeC(LineIndex::new(&item.text)),
70            Wrapped(item.clone()),
71            DocumentLinks(Vec::new()),
72            Open,
73            Types(HashMap::new()),
74        ),
75        lang_id,
76        (),
77    );
78    let entity = spawn(world);
79
80    world.run_schedule(ParseLabel);
81    world.flush();
82    entity
83}
84
85fn cached_copy_notice() -> Diagnostic {
86    Diagnostic {
87        range: Range::new(Position::new(0, 0), Position::new(0, 0)),
88        severity: Some(DiagnosticSeverity::INFORMATION),
89        source: Some(String::from("SWLS")),
90        message: String::from(
91            "This is a copy cached by swls. Edits are not used by the language server \
92             and are reverted when the file is closed.",
93        ),
94        ..Default::default()
95    }
96}
97
98/// Outcome of [`close_document`].
99#[derive(Debug)]
100pub enum Closed {
101    /// No document with that URL.
102    Unknown,
103    /// A document only the editor had; it no longer publishes diagnostics.
104    Editor,
105    /// A background document: give it back the server's copy with
106    /// [`restore_background`], from disk or else from `snapshot`.
107    Background {
108        entity: Entity,
109        snapshot: Option<String>,
110    },
111}
112
113/// The editor closed `url`: stop treating it as open and clear its diagnostics.
114pub fn close_document(world: &mut World, url: &Url) -> Closed {
115    let Some(entity) = find_document(world, url) else {
116        return Closed::Unknown;
117    };
118
119    let mut e = world.entity_mut(entity);
120    e.remove::<Open>();
121    let background = e.contains::<Background>();
122    let snapshot = e.take::<Snapshot>().map(|s| s.0);
123
124    if let Some(mut publisher) = world.get_resource_mut::<DiagnosticPublisher>() {
125        let _ = publisher.clear(url);
126    }
127
128    if background {
129        Closed::Background { entity, snapshot }
130    } else {
131        Closed::Editor
132    }
133}
134
135/// Give a closed background document the server's `content` back and reparse
136/// it, which reloads its triples in the store.
137/// A background document's file was deleted: drop its triples and shapes, and
138/// the document itself, unless the editor has it open.
139pub fn remove_background(world: &mut World, url: &Url) {
140    let Some(entity) = find_document(world, url) else {
141        return;
142    };
143    let e = world.entity(entity);
144    if e.contains::<Open>() || !e.contains::<Background>() {
145        return;
146    }
147    let had_shapes = e.contains::<crate::systems::ShaclShapes>();
148    if let Some(label) = e.get::<Label>() {
149        world
150            .resource::<crate::store::Store>()
151            .remove_document(label);
152    }
153    world.despawn(entity);
154    let mut revisions = world.resource_mut::<Revisions>();
155    revisions.store += 1;
156    if had_shapes {
157        revisions.shapes += 1;
158    }
159    world.run_schedule(ParseLabel);
160    world.flush();
161}
162
163/// The editor saved `url`. For one of the user's own background documents
164/// (not a cache file), the saved content now feeds the shared store, so other
165/// documents see its classes and properties. Unsaved edits never do.
166pub fn save_document(world: &mut World, url: &Url) {
167    let Some(entity) = find_document(world, url) else {
168        return;
169    };
170    let is_cache = world
171        .get_resource::<Fs>()
172        .is_some_and(|fs| fs.0.is_cache_url(url));
173    let e = world.entity(entity);
174    if is_cache || !e.contains::<Background>() || !e.contains::<Open>() {
175        return;
176    }
177    let (Some(label), Some(triples)) = (e.get::<Label>(), e.get::<Triples>()) else {
178        return;
179    };
180    world
181        .resource::<crate::store::Store>()
182        .load_document(label, triples);
183    // Closing the document restores this saved version.
184    let saved = e.get::<Source>().map(|s| Snapshot(s.0.clone()));
185    if let Some(saved) = saved {
186        world.entity_mut(entity).insert(saved);
187    }
188    world.resource_mut::<Revisions>().store += 1;
189    world.run_schedule(ParseLabel);
190    world.flush();
191}
192
193pub fn restore_background(world: &mut World, entity: Entity, content: String) {
194    if world.get_entity(entity).is_err() {
195        return;
196    }
197    world
198        .entity_mut(entity)
199        .insert((RopeC(LineIndex::new(&content)), Source(content)));
200    world.run_schedule(ParseLabel);
201    world.flush();
202}