//! Project commands: `project.open`, `project.openDialog`, `project.close`, //! `project.children`. use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::params::{parse, project_path}; use crate::journal::{self, Journal}; use crate::workspace::{Workspace, path_string, vfs_error}; use crate::{Command, CommandSpec, Effect, EngineError, Event, Outcome, State}; /// `project.openDialog`: asks the host to show the folder picker; the host /// runs `project.open` with the chosen folder. pub struct OpenDialog; impl Command for OpenDialog { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "project.openDialog", label: "Open Folder…", menu_path: Some("File/Open Folder…"), default_shortcut: Some("Mod+O"), params: "none; returns null and the effect pickFolder: the host shows the folder picker and runs project.open with the choice; cancelling is not an error", } } fn run(&self, _state: &mut State, _params: Value) -> Result { Ok(Outcome::effect(Effect::PickFolder)) } } /// Closes the open project and all its buffers. /// /// # Errors /// [`EngineError::UnsavedChanges`] if a buffer is dirty and `force` is false. pub fn close_project(state: &mut State, force: bool) -> Result<(), EngineError> { if state.project.is_none() { return Ok(()); } let dirty = state.buffers.dirty_ids(); if !force && let Some(first) = dirty.first() { let name = state .buffers .get(*first) .map(|b| path_string(&b.path)) .unwrap_or_default(); let what = if dirty.len() == 1 { name } else { format!("{name} and {} more files", dirty.len() - 1) }; return Err(EngineError::UnsavedChanges(what)); } for id in state.buffers.ids() { journal::forget(state, id); state.buffers.remove(id); state.emit(Event::BufferClosed { id }); } state.journal = None; state.project = None; crate::cmd::goto::close(state); state.emit(Event::ProjectClosed); Ok(()) } /// Params of `project.open`. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct OpenParams { /// Folder to open. path: String, /// Discard unsaved changes of a project that is open. #[serde(default)] force: bool, } /// `project.open`: opens a folder as the project, closing the current one, /// and offers the unsaved texts its recovery journal holds with /// [`Event::RecoveryAvailable`] (only when there are any). pub struct Open; impl Command for Open { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "project.open", label: "Open Folder", menu_path: None, default_shortcut: None, params: "{ path: string (absolute folder), force?: bool (discard unsaved changes of the open project) }; returns { root, name }; emits recoveryAvailable when the recovery journal holds unsaved texts", } } fn run(&self, state: &mut State, params: Value) -> Result { let p: OpenParams = parse(self.spec().id, params)?; let (workspace, events) = Workspace::open(std::path::Path::new(&p.path))?; close_project(state, p.force)?; let root = workspace.project.root().to_path_buf(); state.journal = state .config .as_ref() .map(|c| Journal::new(&c.data_dir, &root)); state.project = Some(workspace); let mut name = String::new(); for event in events { if let Event::ProjectOpened { name: n, .. } = &event { name = n.clone(); } state.emit(event); } let entries = super::recovery::infos(state); if !entries.is_empty() { state.emit(Event::RecoveryAvailable { entries }); } Ok(Outcome::value(json!({ "root": root.to_string_lossy(), "name": name, }))) } } /// Params of `project.close`. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct CloseParams { /// Discard unsaved changes. #[serde(default)] force: bool, } /// `project.close`: closes the project and its buffers. pub struct Close; impl Command for Close { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "project.close", label: "Close Project", menu_path: Some("File/Close Project"), default_shortcut: None, params: "{ force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if a buffer is dirty and force is not set", } } fn enabled(&self, state: &State) -> bool { state.has_project() } fn run(&self, state: &mut State, params: Value) -> Result { let p: CloseParams = parse(self.spec().id, params)?; close_project(state, p.force)?; Ok(Outcome::value(Value::Null)) } } /// Params of `project.children`. #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct ChildrenParams { /// Directory, project-relative; `""` or missing for the root. #[serde(default)] dir: String, } /// One entry of a `project.children` result. #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct EntryOut { /// Display name. name: String, /// Project-relative path. path: String, /// `file`, `directory` or `other`. kind: &'static str, /// Matched by an ignore rule. ignored: bool, /// `normal`, `library` or `excluded`. role: &'static str, } /// `project.children`: lists one directory and watches it for changes. pub struct Children; impl Command for Children { fn spec(&self) -> &CommandSpec { &CommandSpec { id: "project.children", label: "List Directory", menu_path: None, default_shortcut: None, params: "{ dir?: string (project-relative, \"\" = root) }; returns { dir, entries: [{ name, path, kind: file|directory|other, ignored, role: normal|library|excluded }], truncated }", } } fn enabled(&self, state: &State) -> bool { state.has_project() } fn run(&self, state: &mut State, params: Value) -> Result { let p: ChildrenParams = parse(self.spec().id, params)?; let dir = project_path(state, self.spec().id, &p.dir)?; let workspace = state .project .as_mut() .ok_or_else(|| EngineError::Disabled(self.spec().id.to_string()))?; let listing = workspace.project.children(&dir).map_err(vfs_error)?; workspace.touch_dir(&dir); let entries: Vec = listing .entries .into_iter() .map(|e| EntryOut { name: e.name, path: path_string(&e.path), kind: match e.kind { lutra_vfs::EntryKind::File => "file", lutra_vfs::EntryKind::Directory => "directory", lutra_vfs::EntryKind::Other => "other", }, ignored: e.ignored, role: match e.role { lutra_vfs::EntryRole::Normal => "normal", lutra_vfs::EntryRole::Library => "library", lutra_vfs::EntryRole::Excluded => "excluded", }, }) .collect(); Ok(Outcome::value(json!({ "dir": path_string(&dir), "entries": entries, "truncated": listing.truncated, }))) } }