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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use {
    crate::{
        makepad_file_protocol::{
            DirectoryEntry,
            FileNodeData,
            FileTreeData,
            FileError,
            FileNotification,
            FileRequest,
            FileResponse,
        },
    },
    std::{
        cmp::Ordering,
        fmt,
        fs,
        path::{Path, PathBuf},
        sync::{Arc, RwLock},
    },
};

pub struct FileServer {
    // The id for the next connection
    next_connection_id: usize,
    // State that is shared between every connection
    shared: Arc<RwLock<Shared >>,
}

impl FileServer {
    /// Creates a new collab server rooted at the given path.
    pub fn new<P: Into<PathBuf >> (root_path: P) -> FileServer {
        FileServer {
            next_connection_id: 0,
            shared: Arc::new(RwLock::new(Shared {
                root_path: root_path.into(),
            })),
        }
    }
    
    /// Creates a new connection to this collab server, and returns a handle for the connection.
    ///
    /// The given `notification_sender` is called whenever the server wants to send a notification
    /// for this connection. The embedder is responsible for sending the notification.
    pub fn connect(&mut self, notification_sender: Box<dyn NotificationSender>) -> FileServerConnection {
        let connection_id = ConnectionId(self.next_connection_id);
        self.next_connection_id += 1;
        FileServerConnection {
            _connection_id:connection_id,
            shared: self.shared.clone(),
            _notification_sender: notification_sender
        }
    }
}

/// A connection to a collab server.
pub struct FileServerConnection {
    // The id for this connection.
    _connection_id: ConnectionId,
    // State is shared between every connection.
    shared: Arc<RwLock<Shared >>,
    // Used to send notifications for this connection.
    _notification_sender: Box<dyn NotificationSender>,
}

impl FileServerConnection {
    /// Handles the given `request` for this connection, and returns the corresponding response.
    ///
    /// The embedder is responsible for receiving requests, calling this method to handle them, and
    /// sending back the response.
    pub fn handle_request(&self, request: FileRequest) -> FileResponse {
        
        
        match request {
            FileRequest::LoadFileTree {with_data} => FileResponse::LoadFileTree(self.load_file_tree(with_data)),
            FileRequest::OpenFile(path) => FileResponse::OpenFile(self.open_file(path)),
            FileRequest::SaveFile(path, delta) => FileResponse::SaveFile(self.save_file(path, delta)),
        }
    }
    
    // Handles a `LoadFileTree` request.
    fn load_file_tree(&self, with_data: bool) -> Result<FileTreeData, FileError> {
        // A recursive helper function for traversing the entries of a directory and creating the
        // data structures that describe them.
        fn get_directory_entries(path: &Path, with_data: bool) -> Result<Vec<DirectoryEntry>, FileError> {
            let mut entries = Vec::new();
            for entry in fs::read_dir(path).map_err( | error | FileError::Unknown(error.to_string())) ? {
                // We can't get the entry for some unknown reason. Raise an error.
                let entry = entry.map_err( | error | FileError::Unknown(error.to_string())) ?;
                // Get the path for the entry.
                let entry_path = entry.path();
                // Get the file name for the entry.
                let name = entry.file_name();
                if let Ok(name_string) = name.into_string() {
                    if entry_path.is_dir() && name_string == "target"
                        || name_string.starts_with('.') {
                        // Skip over directories called "target". This is sort of a hack. The reason
                        // it's here is that the "target" directory for Rust projects is huge, and
                        // our current implementation of the file tree widget is not yet fast enough
                        // to display vast numbers of nodes. We paper over this by pretending the
                        // "target" directory does not exist.
                        continue;
                    }
                }
                else {
                    // Skip over entries with a non UTF-8 file name.
                    continue;
                }
                // Create a `DirectoryEntry` for this entry and add it to the list of entries.
                entries.push(DirectoryEntry {
                    name: entry.file_name().to_string_lossy().to_string(),
                    node: if entry_path.is_dir() {
                        // If this entry is a subdirectory, recursively create `DirectoryEntry`'s
                        // for its entries as well.
                        FileNodeData::Directory {
                            entries: get_directory_entries(&entry_path, with_data) ?,
                        }
                    } else if entry_path.is_file() {
                        if with_data {
                            let bytes: Vec<u8> = fs::read(&entry_path).map_err(
                                | error | FileError::Unknown(error.to_string())
                            ) ?;
                            FileNodeData::File {data: Some(bytes)}
                        }
                        else {
                            FileNodeData::File {data: None}
                        }
                    }
                    else {
                        // If this entry is neither a directory or a file, skip it. This ignores
                        // things such as symlinks, for which we are not yet sure how we want to
                        // handle them.
                        continue
                    },
                });
            }
            
            // Sort all the entries by name, directories first, and files second.
            entries.sort_by( | entry_0, entry_1 | {
                match &entry_0.node {
                    FileNodeData::Directory {..} => match &entry_1.node {
                        FileNodeData::Directory {..} => entry_0.name.cmp(&entry_1.name),
                        FileNodeData::File {..} => Ordering::Less
                    }
                    FileNodeData::File {..} => match &entry_1.node {
                        FileNodeData::Directory {..} => Ordering::Greater,
                        FileNodeData::File {..} => entry_0.name.cmp(&entry_1.name)
                    }
                }
            });
            Ok(entries)
        }
        
        let root_path = self.shared.read().unwrap().root_path.clone();
        
        let root = FileNodeData::Directory {
            entries: get_directory_entries(&root_path, with_data) ?,
        };
        Ok(FileTreeData {root_path: "".into(), root})
    }
    
    fn make_full_path(&self, child_path:&String)->PathBuf{
        let mut path = self.shared.read().unwrap().root_path.clone();
        path.push(child_path);
        path
    }
    
    // Handles an `OpenFile` request.
    fn open_file(&self, child_path: String) -> Result<(String, String), FileError> {
        let path = self.make_full_path(&child_path);
        
        let bytes = fs::read(&path).map_err(
            | error | FileError::Unknown(error.to_string())
        ) ?;
        // Converts the file contents to a `Text`. This is necessarily a lossy conversion
        // because `Text` assumes everything is UTF-8 encoded, and this isn't always the
        // case for files on disk (is this a problem?)
        /*let text: Text = Text::from_lines(String::from_utf8_lossy(&bytes)
            .lines()
            .map( | line | line.chars().collect::<Vec<_ >> ())
            .collect::<Vec<_ >>());*/
        
        let text = String::from_utf8_lossy(&bytes);
        Ok((child_path, text.to_string()))
    }
    
    // Handles an `ApplyDelta` request.
    fn save_file(
        &self,
        child_path: String,
        new_content: String,
    ) -> Result<(String, String, String), FileError> {
        let path = self.make_full_path(&child_path);
        
        let old_content = String::from_utf8_lossy(&fs::read(&path).map_err(
            | error | FileError::Unknown(error.to_string())
        ) ?).to_string();

        fs::write(&path, &new_content).map_err(
            | error | FileError::Unknown(error.to_string())
        ) ?;
        
        Ok((child_path, old_content, new_content))
    }
}

/// A trait for sending notifications over a connection.
pub trait NotificationSender: Send {
    /// This method is necessary to create clones of boxed trait objects.
    fn box_clone(&self) -> Box<dyn NotificationSender>;
    
    /// This method is called to send a notification over the corresponding connection.
    fn send_notification(&self, notification: FileNotification);
}

impl<F: Clone + Fn(FileNotification) + Send + 'static> NotificationSender for F {
    fn box_clone(&self) -> Box<dyn NotificationSender> {
        Box::new(self.clone())
    }
    
    fn send_notification(&self, notification: FileNotification) {
        self (notification)
    }
}

impl Clone for Box<dyn NotificationSender> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

impl fmt::Debug for dyn NotificationSender {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "NotificationSender")
    }
}

// State that is shared between every connection.
#[derive(Debug)]
struct Shared {
    root_path: PathBuf,
}

/// An identifier for a connection.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct ConnectionId(usize);