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
218            let pane = panel
219                .update_in(cx, |terminal_panel, window, cx| {
220                    new_terminal_pane(
221                        workspace.clone(),
222                        project.clone(),
223                        terminal_panel.active_pane.read(cx).is_zoomed(),
224                        window,
225                        cx,
226                    )
227                })
228                .log_err()?;
229            let active_item = serialized_pane.active_item;
230            let pinned_count = serialized_pane.pinned_count;
231            let new_items = deserialize_terminal_views(
232                workspace_id,
233                project.clone(),
234                workspace.clone(),
235                serialized_pane.children.as_slice(),
236                cx,
237            );
238            cx.spawn({
239                let pane = pane.downgrade();
240                async move |cx| {
241                    let new_items = new_items.await;
242
243                    let items = pane.update_in(cx, |pane, window, cx| {
244                        populate_pane_items(pane, new_items, active_item, window, cx);
245                        pane.set_pinned_count(pinned_count);
246                        pane.items_len()
247                    });
248                    // Avoid blank panes in splits
249                    if items.is_ok_and(|items| items == 0) {
250                        let working_directory = workspace
251                            .update(cx, |workspace, cx| default_working_directory(workspace, cx))
252                            .ok()
253                            .flatten();
254                        let Some(terminal) = project
255                            .update(cx, |project, cx| {
256                                project.create_terminal_shell(working_directory, cx)
257                            })
258                            .log_err()
259                        else {
260                            return;
261                        };
262
263                        let terminal = terminal.await.log_err();
264                        pane.update_in(cx, |pane, window, cx| {
265                            if let Some(terminal) = terminal {
266                                let terminal_view = Box::new(cx.new(|cx| {
267                                    TerminalView::new(
268                                        terminal,
269                                        workspace.clone(),
270                                        Some(workspace_id),
271                                        project.downgrade(),
272                                        window,
273                                        cx,
274                                    )
275                                }));
276                                pane.add_item(terminal_view, true, false, None, window, cx);
277                            }
278                        })
279                        .ok();
280                    }
281                }
282            })
283            .detach();
284            Some((Member::Pane(pane.clone()), active.then_some(pane)))
285        }
286    }
287}
288
289fn deserialize_terminal_views(
290    workspace_id: WorkspaceId,
291    project: Entity<Project>,
292    workspace: WeakEntity<Workspace>,
293    item_ids: &[u64],
294    cx: &mut AsyncWindowContext,
295) -> impl Future<Output = Vec<Entity<TerminalView>>> + use<> {
296    let mut deserialized_items = item_ids
297        .iter()
298        .map(|item_id| {
299            cx.update(|window, cx| {
300                TerminalView::deserialize(
301                    project.clone(),
302                    workspace.clone(),
303                    workspace_id,
304                    *item_id,
305                    window,
306                    cx,
307                )
308            })
309            .unwrap_or_else(|e| Task::ready(Err(e.context("no window present"))))
310        })
311        .collect::<FuturesUnordered<_>>();
312    async move {
313        let mut items = Vec::with_capacity(deserialized_items.len());
314        while let Some(item) = deserialized_items.next().await {
315            if let Some(item) = item.log_err() {
316                items.push(item);
317            }
318        }
319        items
320    }
321}
322
323#[derive(Debug, Serialize, Deserialize)]
324pub(crate) struct SerializedTerminalPanel {
325    pub items: SerializedItems,
326    // A deprecated field, kept for backwards compatibility for the code before terminal splits were introduced.
327    pub active_item_id: Option<u64>,
328    pub width: Option<Pixels>,
329    pub height: Option<Pixels>,
330}
331
332#[derive(Debug, Serialize, Deserialize)]
333#[serde(untagged)]
334pub(crate) enum SerializedItems {
335    // The data stored before terminal splits were introduced.
336    NoSplits(Vec<u64>),
337    WithSplits(SerializedPaneGroup),
338}
339
340#[derive(Debug, Serialize, Deserialize)]
341pub(crate) enum SerializedPaneGroup {
342    Pane(SerializedPane),
343    Group {
344        axis: SerializedAxis,
345        flexes: Option<Vec<f32>>,
346        children: Vec<SerializedPaneGroup>,
347    },
348}
349
350#[derive(Debug, Serialize, Deserialize)]
351pub(crate) struct SerializedPane {
352    pub active: bool,
353    pub children: Vec<u64>,
354    pub active_item: Option<u64>,
355    #[serde(default)]
356    pub pinned_count: usize,
357}
358
359#[derive(Debug)]
360pub(crate) struct SerializedAxis(pub Axis);
361
362impl Serialize for SerializedAxis {
363    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
364    where
365        S: serde::Serializer,
366    {
367        match self.0 {
368            Axis::Horizontal => serializer.serialize_str("horizontal"),
369            Axis::Vertical => serializer.serialize_str("vertical"),
370        }
371    }
372}
373
374impl<'de> Deserialize<'de> for SerializedAxis {
375    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
376    where
377        D: serde::Deserializer<'de>,
378    {
379        let s = String::deserialize(deserializer)?;
380        match s.as_str() {
381            "horizontal" => Ok(SerializedAxis(Axis::Horizontal)),
382            "vertical" => Ok(SerializedAxis(Axis::Vertical)),
383            invalid => Err(serde::de::Error::custom(format!(
384                "Invalid axis value: '{invalid}'"
385            ))),
386        }
387    }
388}
389
390pub struct TerminalDb(ThreadSafeConnection);
391
392impl Domain for TerminalDb {
393    const NAME: &str = stringify!(TerminalDb);
394
395    const MIGRATIONS: &[&str] = &[
396        sql!(
397            CREATE TABLE terminals (
398                workspace_id INTEGER,
399                item_id INTEGER UNIQUE,
400                working_directory BLOB,
401                PRIMARY KEY(workspace_id, item_id),
402                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
403                ON DELETE CASCADE
404            ) STRICT;
405        ),
406        // Remove the unique constraint on the item_id table
407        // SQLite doesn't have a way of doing this automatically, so
408        // we have to do this silly copying.
409        sql!(
410            CREATE TABLE terminals2 (
411                workspace_id INTEGER,
412                item_id INTEGER,
413                working_directory BLOB,
414                PRIMARY KEY(workspace_id, item_id),
415                FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
416                ON DELETE CASCADE
417            ) STRICT;
418
419            INSERT INTO terminals2 (workspace_id, item_id, working_directory)
420            SELECT workspace_id, item_id, working_directory FROM terminals;
421
422            DROP TABLE terminals;
423
424            ALTER TABLE terminals2 RENAME TO terminals;
425        ),
426        sql! (
427            ALTER TABLE terminals ADD COLUMN working_directory_path TEXT;
428            UPDATE terminals SET working_directory_path = CAST(working_directory AS TEXT);
429        ),
430    ];
431}
432
433db::static_connection!(TERMINAL_DB, TerminalDb, [WorkspaceDb]);
434
435impl TerminalDb {
436    query! {
437       pub async fn update_workspace_id(
438            new_id: WorkspaceId,
439            old_id: WorkspaceId,
440            item_id: ItemId
441        ) -> Result<()> {
442            UPDATE terminals
443            SET workspace_id = ?
444            WHERE workspace_id = ? AND item_id = ?
445        }
446    }
447
448    pub async fn save_working_directory(
449        &self,
450        item_id: ItemId,
451        workspace_id: WorkspaceId,
452        working_directory: PathBuf,
453    ) -> Result<()> {
454        log::debug!(
455            "Saving working directory {working_directory:?} for item {item_id} in workspace {workspace_id:?}"
456        );
457        let query =
458            "INSERT INTO terminals(item_id, workspace_id, working_directory, working_directory_path)
459            VALUES (?1, ?2, ?3, ?4)
460            ON CONFLICT DO UPDATE SET
461                item_id = ?1,
462                workspace_id = ?2,
463                working_directory = ?3,
464                working_directory_path = ?4"
465        ;
466        self.write(move |conn| {
467            let mut statement = Statement::prepare(conn, query)?;
468            let mut next_index = statement.bind(&item_id, 1)?;
469            next_index = statement.bind(&workspace_id, next_index)?;
470            next_index = statement.bind(&working_directory, next_index)?;
471            statement.bind(
472                &working_directory.to_string_lossy().into_owned(),
473                next_index,
474            )?;
475            statement.exec()
476        })
477        .await
478    }
479
480    query! {
481        pub fn get_working_directory(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
482            SELECT working_directory
483            FROM terminals
484            WHERE item_id = ? AND workspace_id = ?
485        }
486    }
487}