1use anyhow::Result;
  2use async_recursion::async_recursion;
  3use collections::HashSet;
  4use futures::{StreamExt as _, stream::FuturesUnordered};
  5use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity};
  6use project::Project;
  7use serde::{Deserialize, Serialize};
  8use std::path::PathBuf;
  9use ui::{App, Context, Pixels, Window};
 10use util::ResultExt as _;
 11
 12use db::{
 13    query,
 14    sqlez::{domain::Domain, statement::Statement, thread_safe_connection::ThreadSafeConnection},
 15    sqlez_macros::sql,
 16};
 17use workspace::{
 18    ItemHandle, ItemId, Member, Pane, PaneAxis, PaneGroup, SerializableItem as _, Workspace,
 19    WorkspaceDb, WorkspaceId,
 20};
 21
 22use crate::{
 23    TerminalView, default_working_directory,
 24    terminal_panel::{TerminalPanel, new_terminal_pane},
 25};
 26
 27pub(crate) fn serialize_pane_group(
 28    pane_group: &PaneGroup,
 29    active_pane: &Entity<Pane>,
 30    cx: &mut App,
 31) -> SerializedPaneGroup {
 32    build_serialized_pane_group(&pane_group.root, active_pane, cx)
 33}
 34
 35fn build_serialized_pane_group(
 36    pane_group: &Member,
 37    active_pane: &Entity<Pane>,
 38    cx: &mut App,
 39) -> SerializedPaneGroup {
 40    match pane_group {
 41        Member::Axis(PaneAxis {
 42            axis,
 43            members,
 44            flexes,
 45            bounding_boxes: _,
 46        }) => SerializedPaneGroup::Group {
 47            axis: SerializedAxis(*axis),
 48            children: members
 49                .iter()
 50                .map(|member| build_serialized_pane_group(member, active_pane, cx))
 51                .collect::<Vec<_>>(),
 52            flexes: Some(flexes.lock().clone()),
 53        },
 54        Member::Pane(pane_handle) => {
 55            SerializedPaneGroup::Pane(serialize_pane(pane_handle, pane_handle == active_pane, cx))
 56        }
 57    }
 58}
 59
 60fn serialize_pane(pane: &Entity<Pane>, active: bool, cx: &mut App) -> SerializedPane {
 61    let mut items_to_serialize = HashSet::default();
 62    let pane = pane.read(cx);
 63    let children = pane
 64        .items()
 65        .filter_map(|item| {
 66            let terminal_view = item.act_as::<TerminalView>(cx)?;
 67            if terminal_view.read(cx).terminal().read(cx).task().is_some() {
 68                None
 69            } else {
 70                let id = item.item_id().as_u64();
 71                items_to_serialize.insert(id);
 72                Some(id)
 73            }
 74        })
 75        .collect::<Vec<_>>();
 76    let active_item = pane
 77        .active_item()
 78        .map(|item| item.item_id().as_u64())
 79        .filter(|active_id| items_to_serialize.contains(active_id));
 80
 81    let pinned_count = pane.pinned_count();
 82    SerializedPane {
 83        active,
 84        children,
 85        active_item,
 86        pinned_count,
 87    }
 88}
 89
 90pub(crate) fn deserialize_terminal_panel(
 91    workspace: WeakEntity<Workspace>,
 92    project: Entity<Project>,
 93    database_id: WorkspaceId,
 94    serialized_panel: SerializedTerminalPanel,
 95    window: &mut Window,
 96    cx: &mut App,
 97) -> Task<anyhow::Result<Entity<TerminalPanel>>> {
 98    window.spawn(cx, async move |cx| {
 99        let terminal_panel = workspace.update_in(cx, |workspace, window, cx| {
100            cx.new(|cx| {
101                let mut panel = TerminalPanel::new(workspace, window, cx);
102                panel.height = serialized_panel.height.map(|h| h.round());
103                panel.width = serialized_panel.width.map(|w| w.round());
104                panel
105            })
106        })?;
107        match &serialized_panel.items {
108            SerializedItems::NoSplits(item_ids) => {
109                let items = deserialize_terminal_views(
110                    database_id,
111                    project,
112                    workspace,
113                    item_ids.as_slice(),
114                    cx,
115                )
116                .await;
117                let active_item = serialized_panel.active_item_id;
118                terminal_panel.update_in(cx, |terminal_panel, window, cx| {
119                    terminal_panel.active_pane.update(cx, |pane, cx| {
120                        populate_pane_items(pane, items, active_item, window, cx);
121                    });
122                })?;
123            }
124            SerializedItems::WithSplits(serialized_pane_group) => {
125                let center_pane = deserialize_pane_group(
126                    workspace,
127                    project,
128                    terminal_panel.clone(),
129                    database_id,
130                    serialized_pane_group,
131                    cx,
132                )
133                .await;
134                if let Some((center_group, active_pane)) = center_pane {
135                    terminal_panel.update(cx, |terminal_panel, _| {
136                        terminal_panel.center = PaneGroup::with_root(center_group);
137                        terminal_panel.active_pane =
138                            active_pane.unwrap_or_else(|| terminal_panel.center.first_pane());
139                    })?;
140                }
141            }
142        }
143
144        Ok(terminal_panel)
145    })
146}
147
148fn populate_pane_items(
149    pane: &mut Pane,
150    items: Vec<Entity<TerminalView>>,
151    active_item: Option<u64>,
152    window: &mut Window,
153    cx: &mut Context<Pane>,
154) {
155    let mut item_index = pane.items_len();
156    let mut active_item_index = None;
157    for item in items {
158        if Some(item.item_id().as_u64()) == active_item {
159            active_item_index = Some(item_index);
160        }
161        pane.add_item(Box::new(item), false, false, None, window, cx);
162        item_index += 1;
163    }
164    if let Some(index) = active_item_index {
165        pane.activate_item(index, false, false, window, cx);
166    }
167}
168
169#[async_recursion(?Send)]
170async fn deserialize_pane_group(
171    workspace: WeakEntity<Workspace>,
172    project: Entity<Project>,
173    panel: Entity<TerminalPanel>,
174    workspace_id: WorkspaceId,
175    serialized: &SerializedPaneGroup,
176    cx: &mut AsyncWindowContext,
177) -> Option<(Member, Option<Entity<Pane>>)> {
178    match serialized {
179        SerializedPaneGroup::Group {
180            axis,
181            flexes,
182            children,
183        } => {
184            let mut current_active_pane = None;
185            let mut members = Vec::new();
186            for child in children {
187                if let Some((new_member, active_pane)) = deserialize_pane_group(
188                    workspace.clone(),
189                    project.clone(),
190                    panel.clone(),
191                    workspace_id,
192                    child,
193                    cx,
194                )
195                .await
196                {
197                    members.push(new_member);
198                    current_active_pane = current_active_pane.or(active_pane);
199                }
200            }
201
202            if members.is_empty() {
203                return None;
204            }
205
206            if members.len() == 1 {
207                return Some((members.remove(0), current_active_pane));
208            }
209
210            Some((
211                Member::Axis(PaneAxis::load(axis.0, members, flexes.clone())),
212                current_active_pane,
213            ))
214        }
215        SerializedPaneGroup::Pane(serialized_pane) => {
216            let active = serialized_pane.active;
217            let new_items = deserialize_terminal_views(
218                workspace_id,
219                project.clone(),
220                workspace.clone(),
221                serialized_pane.children.as_slice(),
222                cx,
223            )
224            .await;
225
226            let pane = panel
227                .update_in(cx, |terminal_panel, window, cx| {
228                    new_terminal_pane(
229                        workspace.clone(),
230                        project.clone(),
231                        terminal_panel.active_pane.read(cx).is_zoomed(),
232                        window,
233                        cx,
234                    )
235                })
236                .log_err()?;
237            let active_item = serialized_pane.active_item;
238            let pinned_count = serialized_pane.pinned_count;
239            let terminal = pane
240                .update_in(cx, |pane, window, cx| {
241                    populate_pane_items(pane, new_items, active_item, window, cx);
242                    pane.set_pinned_count(pinned_count);
243                    // Avoid blank panes in splits
244                    if pane.items_len() == 0 {
245                        let working_directory = workspace
246                            .update(cx, |workspace, cx| default_working_directory(workspace, cx))
247                            .ok()
248                            .flatten();
249                        let terminal = project.update(cx, |project, cx| {
250                            project.create_terminal_shell(working_directory, cx)
251                        });
252                        Some(Some(terminal))
253                    } else {
254                        Some(None)
255                    }
256                })
257                .ok()
258                .flatten()?;
259            if let Some(terminal) = terminal {
260                let terminal = terminal.await.ok()?;
261                pane.update_in(cx, |pane, window, cx| {
262                    let terminal_view = Box::new(cx.new(|cx| {
263                        TerminalView::new(
264                            terminal,
265                            workspace.clone(),
266                            Some(workspace_id),
267                            project.downgrade(),
268                            window,
269                            cx,
270                        )
271                    }));
272                    pane.add_item(terminal_view, true, false, None, window, cx);
273                })
274                .ok()?;
275            }
276            Some((Member::Pane(pane.clone()), active.then_some(pane)))
277        }
278    }
279}
280
281async fn deserialize_terminal_views(
282    workspace_id: WorkspaceId,
283    project: Entity<Project>,
284    workspace: WeakEntity<Workspace>,
285    item_ids: &[u64],
286    cx: &mut AsyncWindowContext,
287) -> Vec<Entity<TerminalView>> {
288    let mut items = Vec::with_capacity(item_ids.len());
289    let mut deserialized_items = item_ids
290        .iter()
291        .map(|item_id| {
292            cx.update(|window, cx| {
293                TerminalView::deserialize(
294                    project.clone(),
295                    workspace.clone(),
296                    workspace_id,
297                    *item_id,
298                    window,
299                    cx,
300                )
301            })
302            .unwrap_or_else(|e| Task::ready(Err(e.context("no window present"))))
303        })
304        .collect::<FuturesUnordered<_>>();
305    while let Some(item) = deserialized_items.next().await {
306        if let Some(item) = item.log_err() {
307            items.push(item);
308        }
309    }
310    items
311}
312
313#[derive(Debug, Serialize, Deserialize)]
314pub(crate) struct SerializedTerminalPanel {
315    pub items: SerializedItems,
316    // A deprecated field, kept for backwards compatibility for the code before terminal splits were introduced.
317    pub active_item_id: Option<u64>,
318    pub width: Option<Pixels>,
319    pub height: Option<Pixels>,
320}
321
322#[derive(Debug, Serialize, Deserialize)]
323#[serde(untagged)]
324pub(crate) enum SerializedItems {
325    // The data stored before terminal splits were introduced.
326    NoSplits(Vec<u64>),
327    WithSplits(SerializedPaneGroup),
328}
329
330#[derive(Debug, Serialize, Deserialize)]
331pub(crate) enum SerializedPaneGroup {
332    Pane(SerializedPane),
333    Group {
334        axis: SerializedAxis,
335        flexes: Option<Vec<f32>>,
336        children: Vec<SerializedPaneGroup>,
337    },
338}
339
340#[derive(Debug, Serialize, Deserialize)]
341pub(crate) struct SerializedPane {
342    pub active: bool,
343    pub children: Vec<u64>,
344    pub active_item: Option<u64>,
345    #[serde(default)]
346    pub pinned_count: usize,
347}
348
349#[derive(Debug)]
350pub(crate) struct SerializedAxis(pub Axis);
351
352impl Serialize for SerializedAxis {
353    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
354    where
355        S: serde::Serializer,
356    {
357        match self.0 {
358            Axis::Horizontal => serializer.serialize_str("horizontal"),
359            Axis::Vertical => serializer.serialize_str("vertical"),
360        }
361    }
362}
363
364impl<'de> Deserialize<'de> for SerializedAxis {
365    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
366    where
367        D: serde::Deserializer<'de>,
368    {
369        let s = String::deserialize(deserializer)?;
370        match s.as_str() {
371            "horizontal" => Ok(SerializedAxis(Axis::Horizontal)),
372            "vertical" => Ok(SerializedAxis(Axis::Vertical)),
373            invalid => Err(serde::de::Error::custom(format!(
374                "Invalid axis value: '{invalid}'"
375            ))),
376        }
377    }
378}
379
380pub struct TerminalDb(ThreadSafeConnection);
381
382impl Domain for TerminalDb {
383    const NAME: &str = stringify!(TerminalDb);
384
385    const MIGRATIONS: &[&str] = &[
386        sql!(
387            CREATE TABLE terminals (
388                workspace_id INTEGER,
389                item_id INTEGER UNIQUE,
390                working_directory BLOB,
391                PRIMARY KEY(workspace_id, item_id),
392                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
393                ON DELETE CASCADE
394            ) STRICT;
395        ),
396        // Remove the unique constraint on the item_id table
397        // SQLite doesn't have a way of doing this automatically, so
398        // we have to do this silly copying.
399        sql!(
400            CREATE TABLE terminals2 (
401                workspace_id INTEGER,
402                item_id INTEGER,
403                working_directory BLOB,
404                PRIMARY KEY(workspace_id, item_id),
405                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
406                ON DELETE CASCADE
407            ) STRICT;
408
409            INSERT INTO terminals2 (workspace_id, item_id, working_directory)
410            SELECT workspace_id, item_id, working_directory FROM terminals;
411
412            DROP TABLE terminals;
413
414            ALTER TABLE terminals2 RENAME TO terminals;
415        ),
416        sql! (
417            ALTER TABLE terminals ADD COLUMN working_directory_path TEXT;
418            UPDATE terminals SET working_directory_path = CAST(working_directory AS TEXT);
419        ),
420    ];
421}
422
423db::static_connection!(TERMINAL_DB, TerminalDb, [WorkspaceDb]);
424
425impl TerminalDb {
426    query! {
427       pub async fn update_workspace_id(
428            new_id: WorkspaceId,
429            old_id: WorkspaceId,
430            item_id: ItemId
431        ) -> Result<()> {
432            UPDATE terminals
433            SET workspace_id = ?
434            WHERE workspace_id = ? AND item_id = ?
435        }
436    }
437
438    pub async fn save_working_directory(
439        &self,
440        item_id: ItemId,
441        workspace_id: WorkspaceId,
442        working_directory: PathBuf,
443    ) -> Result<()> {
444        log::debug!(
445            "Saving working directory {working_directory:?} for item {item_id} in workspace {workspace_id:?}"
446        );
447        let query =
448            "INSERT INTO terminals(item_id, workspace_id, working_directory, working_directory_path)
449            VALUES (?1, ?2, ?3, ?4)
450            ON CONFLICT DO UPDATE SET
451                item_id = ?1,
452                workspace_id = ?2,
453                working_directory = ?3,
454                working_directory_path = ?4"
455        ;
456        self.write(move |conn| {
457            let mut statement = Statement::prepare(conn, query)?;
458            let mut next_index = statement.bind(&item_id, 1)?;
459            next_index = statement.bind(&workspace_id, next_index)?;
460            next_index = statement.bind(&working_directory, next_index)?;
461            statement.bind(
462                &working_directory.to_string_lossy().into_owned(),
463                next_index,
464            )?;
465            statement.exec()
466        })
467        .await
468    }
469
470    query! {
471        pub fn get_working_directory(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
472            SELECT working_directory
473            FROM terminals
474            WHERE item_id = ? AND workspace_id = ?
475        }
476    }
477}