Skip to main content

strop_engine/editor/document/
remote.rs

1//! Remote provenance stays with its real buffer. Live leases never cross replay.
2use super::{Document, DocumentSource, ReturnPoint};
3use std::fmt::Write;
4use strop_core::Buffer;
5use strop_remote::{
6    ConnectionLease, ReadSelection, RemoteDirectorySnapshot, RemoteEntry, RemoteEntryKind,
7    RemoteSnapshot, RemoteWindow,
8};
9use strop_workspace::RemoteFile;
10
11#[derive(Clone)]
12pub struct RemoteDocument {
13    pub file: RemoteFile,
14    pub window: RemoteWindow,
15    pub selection: ReadSelection,
16    pub connection: Option<ConnectionLease>,
17    pub return_to: Option<ReturnPoint>,
18    pub(crate) write: Option<crate::editor::remote::save::WritePermit>,
19}
20impl std::fmt::Debug for RemoteDocument {
21    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        formatter
23            .debug_struct("RemoteDocument")
24            .field("file", &self.file)
25            .field("window", &self.window)
26            .field("selection", &self.selection)
27            .field("connected", &self.connection.is_some())
28            .field("write_authorized", &self.write.is_some())
29            .finish()
30    }
31}
32
33#[derive(Clone)]
34pub struct RemoteDirectory {
35    pub directory: RemoteFile,
36    pub entries: std::sync::Arc<[RemoteEntry]>,
37    pub visible: Vec<usize>,
38    pub filter: String,
39    pub connection: Option<ConnectionLease>,
40    pub return_to: Option<ReturnPoint>,
41}
42impl std::fmt::Debug for RemoteDirectory {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter
45            .debug_struct("RemoteDirectory")
46            .field("directory", &self.directory)
47            .field("entries", &self.entries.len())
48            .field("filter", &self.filter)
49            .field("connected", &self.connection.is_some())
50            .finish()
51    }
52}
53impl RemoteDirectory {
54    pub fn text(&self) -> String {
55        let size_width = self
56            .visible
57            .iter()
58            .filter_map(|&index| self.entries[index].size)
59            .map(|size| size.get().checked_ilog10().unwrap_or(0) as usize + 1)
60            .max()
61            .unwrap_or(1)
62            .max(5);
63        let mut text = String::new();
64        // fmt::Write on String is infallible; parent attributes were not fetched.
65        let _ = writeln!(text, "d????????? {:>size_width$} ../", "?");
66        for &index in &self.visible {
67            let entry = &self.entries[index];
68            text.push(entry.kind.marker());
69            match entry.permissions {
70                Some(permissions) => {
71                    let _ = write!(text, "{permissions}");
72                }
73                None => text.push_str("?????????"),
74            }
75            match entry.size {
76                Some(size) => {
77                    let _ = write!(text, " {:>size_width$} ", size.get());
78                }
79                None => {
80                    let _ = write!(text, " {:>size_width$} ", "?");
81                }
82            }
83            let name = entry
84                .file
85                .path()
86                .file_name()
87                .unwrap_or_default()
88                .to_string_lossy();
89            text.push_str(&strop_core::layout::printable_text(name));
90            if entry.kind == RemoteEntryKind::Directory {
91                text.push('/');
92            }
93            if entry.kind == RemoteEntryKind::SymbolicLink {
94                text.push('@');
95            }
96            text.push('\n');
97        }
98        text
99    }
100    pub fn parent(&self) -> Result<Option<RemoteFile>, strop_workspace::AddressError> {
101        self.directory
102            .path()
103            .parent()
104            .map(|parent| self.directory.with_path(parent.to_path_buf()))
105            .transpose()
106    }
107    pub fn entry(&self, line: strop_core::id::LineIndex) -> Option<&RemoteEntry> {
108        line.get()
109            .checked_sub(1)
110            .and_then(|line| self.visible.get(line))
111            .and_then(|&index| self.entries.get(index))
112    }
113    /// Entries are grouped directory-first then native-path sorted. Search
114    /// both groups and the sorted visible mapping without scanning the listing.
115    pub(crate) fn line_for(&self, file: &RemoteFile) -> Option<strop_core::id::LineIndex> {
116        if file.endpoint() != self.directory.endpoint() {
117            return None;
118        }
119        let split = self
120            .entries
121            .partition_point(|entry| entry.kind == RemoteEntryKind::Directory);
122        for (offset, entries) in [(0, &self.entries[..split]), (split, &self.entries[split..])] {
123            if let Ok(index) = entries.binary_search_by(|entry| {
124                entry.file.path().as_os_str().cmp(file.path().as_os_str())
125            }) {
126                return self
127                    .visible
128                    .binary_search(&(offset + index))
129                    .ok()
130                    .map(|row| strop_core::id::LineIndex::new(row + 1));
131            }
132        }
133        None
134    }
135}
136
137impl Document {
138    pub fn remote(mut buffer: Buffer, source: RemoteDocument) -> Self {
139        debug_assert!(
140            buffer.path.is_none(),
141            "remote identity cannot become a local file"
142        );
143        buffer.name = Some(source.file.to_string());
144        buffer.readonly = true;
145        Self {
146            buf: buffer,
147            source: DocumentSource::Remote(Box::new(source)),
148        }
149    }
150    pub(crate) fn remote_snapshot(snapshot: RemoteSnapshot, selection: ReadSelection) -> Self {
151        Self::remote(
152            snapshot.buffer,
153            RemoteDocument {
154                file: snapshot.file,
155                window: snapshot.window,
156                selection,
157                connection: Some(snapshot.connection),
158                return_to: None,
159                write: None,
160            },
161        )
162    }
163    pub(crate) fn remote_directory(snapshot: RemoteDirectorySnapshot) -> Self {
164        let mut entries = snapshot.entries;
165        entries.sort_by(|left, right| {
166            let left_directory = left.kind == RemoteEntryKind::Directory;
167            let right_directory = right.kind == RemoteEntryKind::Directory;
168            right_directory.cmp(&left_directory).then_with(|| {
169                left.file
170                    .path()
171                    .as_os_str()
172                    .cmp(right.file.path().as_os_str())
173            })
174        });
175        let directory = RemoteDirectory {
176            directory: snapshot.directory,
177            visible: (0..entries.len()).collect(),
178            entries: entries.into(),
179            filter: String::new(),
180            connection: Some(snapshot.connection),
181            return_to: None,
182        };
183        let buffer = Buffer::from_text(&directory.text());
184        Self::directory(buffer, directory)
185    }
186    pub fn directory(mut buffer: Buffer, source: RemoteDirectory) -> Self {
187        buffer.name = Some(source.directory.to_string());
188        buffer.readonly = true;
189        Self {
190            buf: buffer,
191            source: DocumentSource::RemoteDirectory(Box::new(source)),
192        }
193    }
194    pub fn remote_metadata(&self) -> Option<&RemoteDocument> {
195        match &self.source {
196            DocumentSource::Remote(source) => Some(source),
197            _ => None,
198        }
199    }
200    pub fn directory_metadata_ref(&self) -> Option<&RemoteDirectory> {
201        match &self.source {
202            DocumentSource::RemoteDirectory(source) => Some(source),
203            _ => None,
204        }
205    }
206}
207
208impl Document {
209    pub(crate) fn return_point(&self) -> Option<&ReturnPoint> {
210        match &self.source {
211            DocumentSource::Surface(surface) => surface.content.return_point(),
212            DocumentSource::Remote(source) => source.return_to.as_ref(),
213            DocumentSource::RemoteDirectory(source) => source.return_to.as_ref(),
214            _ => None,
215        }
216    }
217    pub(crate) fn set_return_point(&mut self, point: ReturnPoint) {
218        match &mut self.source {
219            DocumentSource::Surface(surface) => surface.content.set_return_point(point),
220            DocumentSource::Remote(source) => source.return_to = Some(point),
221            DocumentSource::RemoteDirectory(source) => source.return_to = Some(point),
222            _ => {}
223        }
224    }
225}