Implementing persistence for the terminal working directory, found an issue with my current data model. :(

This commit is contained in:
Mikayla Maki 2022-11-19 15:14:13 -08:00
parent cb1d2cd1f2
commit a8ed95e1dc
10 changed files with 113 additions and 21 deletions

2
Cargo.lock generated
View File

@ -5889,6 +5889,7 @@ dependencies = [
"anyhow", "anyhow",
"client", "client",
"context_menu", "context_menu",
"db",
"dirs 4.0.0", "dirs 4.0.0",
"editor", "editor",
"futures 0.3.25", "futures 0.3.25",
@ -7659,7 +7660,6 @@ dependencies = [
"serde_json", "serde_json",
"settings", "settings",
"smallvec", "smallvec",
"sqlez",
"theme", "theme",
"util", "util",
] ]

View File

@ -1,11 +1,15 @@
pub mod kvp; pub mod kvp;
// Re-export indoc and sqlez so clients only need to include us
pub use indoc::indoc;
pub use lazy_static;
pub use sqlez;
use std::fs::{create_dir_all, remove_dir_all}; use std::fs::{create_dir_all, remove_dir_all};
use std::path::Path; use std::path::Path;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use anyhow::Result; use anyhow::Result;
use indoc::indoc;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use sqlez::connection::Connection; use sqlez::connection::Connection;
use sqlez::domain::{Domain, Migrator}; use sqlez::domain::{Domain, Migrator};
@ -54,17 +58,17 @@ pub fn write_db_to<D: Domain, P: AsRef<Path>>(
#[macro_export] #[macro_export]
macro_rules! connection { macro_rules! connection {
($id:ident: $t:ident<$d:ty>) => { ($id:ident: $t:ident<$d:ty>) => {
pub struct $t(::sqlez::thread_safe_connection::ThreadSafeConnection<$d>); pub struct $t(::db::sqlez::thread_safe_connection::ThreadSafeConnection<$d>);
impl ::std::ops::Deref for $t { impl ::std::ops::Deref for $t {
type Target = ::sqlez::thread_safe_connection::ThreadSafeConnection<$d>; type Target = ::db::sqlez::thread_safe_connection::ThreadSafeConnection<$d>;
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
&self.0 &self.0
} }
} }
lazy_static! { ::db::lazy_static::lazy_static! {
pub static ref $id: $t = $t(if cfg!(any(test, feature = "test-support")) { pub static ref $id: $t = $t(if cfg!(any(test, feature = "test-support")) {
::db::open_memory_db(None) ::db::open_memory_db(None)
} else { } else {

View File

@ -3,7 +3,6 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use db::connection; use db::connection;
use indoc::indoc; use indoc::indoc;
use lazy_static::lazy_static;
use sqlez::domain::Domain; use sqlez::domain::Domain;
use workspace::{ItemId, Workspace, WorkspaceId}; use workspace::{ItemId, Workspace, WorkspaceId};
@ -22,7 +21,11 @@ impl Domain for Editor {
item_id INTEGER NOT NULL, item_id INTEGER NOT NULL,
workspace_id BLOB NOT NULL, workspace_id BLOB NOT NULL,
path BLOB NOT NULL, path BLOB NOT NULL,
PRIMARY KEY(item_id, workspace_id) PRIMARY KEY(item_id, workspace_id),
FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) STRICT; ) STRICT;
"}] "}]
} }

View File

@ -17,6 +17,7 @@ settings = { path = "../settings" }
theme = { path = "../theme" } theme = { path = "../theme" }
util = { path = "../util" } util = { path = "../util" }
workspace = { path = "../workspace" } workspace = { path = "../workspace" }
db = { path = "../db" }
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "a51dbe25d67e84d6ed4261e640d3954fbdd9be45" } alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "a51dbe25d67e84d6ed4261e640d3954fbdd9be45" }
procinfo = { git = "https://github.com/zed-industries/wezterm", rev = "5cd757e5f2eb039ed0c6bb6512223e69d5efc64d", default-features = false } procinfo = { git = "https://github.com/zed-industries/wezterm", rev = "5cd757e5f2eb039ed0c6bb6512223e69d5efc64d", default-features = false }
smallvec = { version = "1.6", features = ["union"] } smallvec = { version = "1.6", features = ["union"] }

View File

@ -0,0 +1,61 @@
use std::path::{Path, PathBuf};
use db::{connection, indoc, sqlez::domain::Domain};
use util::{iife, ResultExt};
use workspace::{ItemId, Workspace, WorkspaceId};
use crate::Terminal;
connection!(TERMINAL_CONNECTION: TerminalDb<(Workspace, Terminal)>);
impl Domain for Terminal {
fn name() -> &'static str {
"terminal"
}
fn migrations() -> &'static [&'static str] {
&[indoc! {"
CREATE TABLE terminals (
item_id INTEGER,
workspace_id BLOB,
working_directory BLOB,
PRIMARY KEY(item_id, workspace_id),
FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) STRICT;
"}]
}
}
impl TerminalDb {
pub fn save_working_directory(
&self,
item_id: ItemId,
workspace_id: &WorkspaceId,
working_directory: &Path,
) {
iife!({
self.exec_bound::<(ItemId, &WorkspaceId, &Path)>(indoc! {"
INSERT OR REPLACE INTO terminals(item_id, workspace_id, working_directory)
VALUES (?, ?, ?)
"})?((item_id, workspace_id, working_directory))
})
.log_err();
}
pub fn get_working_directory(
&self,
item_id: ItemId,
workspace_id: &WorkspaceId,
) -> Option<PathBuf> {
iife!({
self.select_row_bound::<(ItemId, &WorkspaceId), PathBuf>(indoc! {"
SELECT working_directory
FROM terminals
WHERE item_id = ? workspace_id = ?"})?((item_id, workspace_id))
})
.log_err()
.flatten()
}
}

View File

@ -1,4 +1,5 @@
pub mod mappings; pub mod mappings;
mod persistence;
pub mod terminal_container_view; pub mod terminal_container_view;
pub mod terminal_element; pub mod terminal_element;
pub mod terminal_view; pub mod terminal_view;
@ -32,9 +33,11 @@ use mappings::mouse::{
alt_scroll, grid_point, mouse_button_report, mouse_moved_report, mouse_side, scroll_report, alt_scroll, grid_point, mouse_button_report, mouse_moved_report, mouse_side, scroll_report,
}; };
use persistence::TERMINAL_CONNECTION;
use procinfo::LocalProcessInfo; use procinfo::LocalProcessInfo;
use settings::{AlternateScroll, Settings, Shell, TerminalBlink}; use settings::{AlternateScroll, Settings, Shell, TerminalBlink};
use util::ResultExt; use util::ResultExt;
use workspace::{ItemId, WorkspaceId};
use std::{ use std::{
cmp::min, cmp::min,
@ -281,6 +284,8 @@ impl TerminalBuilder {
blink_settings: Option<TerminalBlink>, blink_settings: Option<TerminalBlink>,
alternate_scroll: &AlternateScroll, alternate_scroll: &AlternateScroll,
window_id: usize, window_id: usize,
item_id: ItemId,
workspace_id: WorkspaceId,
) -> Result<TerminalBuilder> { ) -> Result<TerminalBuilder> {
let pty_config = { let pty_config = {
let alac_shell = shell.clone().and_then(|shell| match shell { let alac_shell = shell.clone().and_then(|shell| match shell {
@ -385,6 +390,8 @@ impl TerminalBuilder {
last_mouse_position: None, last_mouse_position: None,
next_link_id: 0, next_link_id: 0,
selection_phase: SelectionPhase::Ended, selection_phase: SelectionPhase::Ended,
workspace_id,
item_id,
}; };
Ok(TerminalBuilder { Ok(TerminalBuilder {
@ -528,6 +535,8 @@ pub struct Terminal {
scroll_px: f32, scroll_px: f32,
next_link_id: usize, next_link_id: usize,
selection_phase: SelectionPhase, selection_phase: SelectionPhase,
item_id: ItemId,
workspace_id: WorkspaceId,
} }
impl Terminal { impl Terminal {
@ -567,7 +576,17 @@ impl Terminal {
cx.emit(Event::Wakeup); cx.emit(Event::Wakeup);
if self.update_process_info() { if self.update_process_info() {
cx.emit(Event::TitleChanged) cx.emit(Event::TitleChanged);
if let Some(foreground_info) = self.foreground_process_info {
cx.background().spawn(async move {
TERMINAL_CONNECTION.save_working_directory(
self.item_id,
&self.workspace_id,
&foreground_info.cwd,
);
});
}
} }
} }
AlacTermEvent::ColorRequest(idx, fun_ptr) => { AlacTermEvent::ColorRequest(idx, fun_ptr) => {

View File

@ -1,3 +1,4 @@
use crate::persistence::TERMINAL_CONNECTION;
use crate::terminal_view::TerminalView; use crate::terminal_view::TerminalView;
use crate::{Event, Terminal, TerminalBuilder, TerminalError}; use crate::{Event, Terminal, TerminalBuilder, TerminalError};
@ -13,7 +14,7 @@ use workspace::{
item::{Item, ItemEvent}, item::{Item, ItemEvent},
ToolbarItemLocation, Workspace, ToolbarItemLocation, Workspace,
}; };
use workspace::{register_deserializable_item, Pane}; use workspace::{register_deserializable_item, ItemId, Pane, WorkspaceId};
use project::{LocalWorktree, Project, ProjectPath}; use project::{LocalWorktree, Project, ProjectPath};
use settings::{AlternateScroll, Settings, WorkingDirectory}; use settings::{AlternateScroll, Settings, WorkingDirectory};
@ -89,6 +90,8 @@ impl TerminalContainer {
pub fn new( pub fn new(
working_directory: Option<PathBuf>, working_directory: Option<PathBuf>,
modal: bool, modal: bool,
item_id: ItemId,
workspace_id: WorkspaceId,
cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
) -> Self { ) -> Self {
let settings = cx.global::<Settings>(); let settings = cx.global::<Settings>();
@ -115,6 +118,8 @@ impl TerminalContainer {
settings.terminal_overrides.blinking.clone(), settings.terminal_overrides.blinking.clone(),
scroll, scroll,
cx.window_id(), cx.window_id(),
item_id,
workspace_id,
) { ) {
Ok(terminal) => { Ok(terminal) => {
let terminal = cx.add_model(|cx| terminal.subscribe(cx)); let terminal = cx.add_model(|cx| terminal.subscribe(cx));
@ -386,13 +391,14 @@ impl Item for TerminalContainer {
fn deserialize( fn deserialize(
_project: ModelHandle<Project>, _project: ModelHandle<Project>,
_workspace: WeakViewHandle<Workspace>, _workspace: WeakViewHandle<Workspace>,
_workspace_id: workspace::WorkspaceId, workspace_id: workspace::WorkspaceId,
_item_id: workspace::ItemId, item_id: workspace::ItemId,
cx: &mut ViewContext<Pane>, cx: &mut ViewContext<Pane>,
) -> Task<anyhow::Result<ViewHandle<Self>>> { ) -> Task<anyhow::Result<ViewHandle<Self>>> {
// TODO: Pull the current working directory out of the DB. let working_directory = TERMINAL_CONNECTION.get_working_directory(item_id, &workspace_id);
Task::ready(Ok(cx.add_view(|cx| {
Task::ready(Ok(cx.add_view(|cx| TerminalContainer::new(None, false, cx)))) TerminalContainer::new(working_directory, false, cx)
})))
} }
} }

View File

@ -30,7 +30,6 @@ language = { path = "../language" }
menu = { path = "../menu" } menu = { path = "../menu" }
project = { path = "../project" } project = { path = "../project" }
settings = { path = "../settings" } settings = { path = "../settings" }
sqlez = { path = "../sqlez" }
theme = { path = "../theme" } theme = { path = "../theme" }
util = { path = "../util" } util = { path = "../util" }
async-recursion = "1.0.0" async-recursion = "1.0.0"

View File

@ -9,10 +9,9 @@ use anyhow::{anyhow, bail, Result, Context};
use db::connection; use db::connection;
use gpui::Axis; use gpui::Axis;
use indoc::indoc; use indoc::indoc;
use lazy_static::lazy_static;
use sqlez::domain::Domain; use db::sqlez::domain::Domain;
use util::{iife, unzip_option, ResultExt}; use util::{iife, unzip_option, ResultExt};
use crate::dock::DockPosition; use crate::dock::DockPosition;

View File

@ -8,12 +8,12 @@ use anyhow::Result;
use async_recursion::async_recursion; use async_recursion::async_recursion;
use gpui::{AsyncAppContext, Axis, ModelHandle, Task, ViewHandle}; use gpui::{AsyncAppContext, Axis, ModelHandle, Task, ViewHandle};
use project::Project; use db::sqlez::{
use settings::DockAnchor;
use sqlez::{
bindable::{Bind, Column}, bindable::{Bind, Column},
statement::Statement, statement::Statement,
}; };
use project::Project;
use settings::DockAnchor;
use util::ResultExt; use util::ResultExt;
use crate::{dock::DockPosition, ItemDeserializers, Member, Pane, PaneAxis, Workspace}; use crate::{dock::DockPosition, ItemDeserializers, Member, Pane, PaneAxis, Workspace};
@ -228,8 +228,8 @@ impl Column for DockPosition {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use db::sqlez::connection::Connection;
use settings::DockAnchor; use settings::DockAnchor;
use sqlez::connection::Connection;
use super::WorkspaceId; use super::WorkspaceId;