1use super::{SerializedAxis, SerializedWindowBounds};
2use crate::{item::ItemHandle, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId};
3use anyhow::{Context, Result};
4use async_recursion::async_recursion;
5use client::DevServerProjectId;
6use db::sqlez::{
7 bindable::{Bind, Column, StaticColumnCount},
8 statement::Statement,
9};
10use gpui::{AsyncWindowContext, Model, Task, View, WeakView};
11use project::Project;
12use serde::{Deserialize, Serialize};
13use std::{
14 path::{Path, PathBuf},
15 sync::Arc,
16};
17use ui::SharedString;
18use util::ResultExt;
19use uuid::Uuid;
20
21#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
22pub struct SerializedDevServerProject {
23 pub id: DevServerProjectId,
24 pub dev_server_name: String,
25 pub paths: Vec<SharedString>,
26}
27
28#[derive(Debug, PartialEq, Clone)]
29pub struct LocalPaths(Arc<Vec<PathBuf>>);
30
31impl LocalPaths {
32 pub fn new<P: AsRef<Path>>(paths: impl IntoIterator<Item = P>) -> Self {
33 let mut paths: Vec<PathBuf> = paths
34 .into_iter()
35 .map(|p| p.as_ref().to_path_buf())
36 .collect();
37 // Ensure all future `zed workspace1 workspace2` and `zed workspace2 workspace1` calls are using the same workspace.
38 // The actual workspace order is stored in the `LocalPathsOrder` struct.
39 paths.sort();
40 Self(Arc::new(paths))
41 }
42
43 pub fn paths(&self) -> &Arc<Vec<PathBuf>> {
44 &self.0
45 }
46}
47
48impl From<LocalPaths> for SerializedWorkspaceLocation {
49 fn from(local_paths: LocalPaths) -> Self {
50 let order = LocalPathsOrder::default_for_paths(&local_paths);
51 Self::Local(local_paths, order)
52 }
53}
54
55impl StaticColumnCount for LocalPaths {}
56impl Bind for &LocalPaths {
57 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
58 statement.bind(&bincode::serialize(&self.0)?, start_index)
59 }
60}
61
62impl Column for LocalPaths {
63 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
64 let path_blob = statement.column_blob(start_index)?;
65 let paths: Arc<Vec<PathBuf>> = if path_blob.is_empty() {
66 Default::default()
67 } else {
68 bincode::deserialize(path_blob).context("Bincode deserialization of paths failed")?
69 };
70
71 Ok((Self(paths), start_index + 1))
72 }
73}
74
75#[derive(Debug, PartialEq, Clone)]
76pub struct LocalPathsOrder(Vec<usize>);
77
78impl LocalPathsOrder {
79 pub fn new(order: impl IntoIterator<Item = usize>) -> Self {
80 Self(order.into_iter().collect())
81 }
82
83 pub fn order(&self) -> &[usize] {
84 self.0.as_slice()
85 }
86
87 pub fn default_for_paths(paths: &LocalPaths) -> Self {
88 Self::new(0..paths.0.len())
89 }
90}
91
92impl StaticColumnCount for LocalPathsOrder {}
93impl Bind for &LocalPathsOrder {
94 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
95 statement.bind(&bincode::serialize(&self.0)?, start_index)
96 }
97}
98
99impl Column for LocalPathsOrder {
100 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
101 let order_blob = statement.column_blob(start_index)?;
102 let order = if order_blob.is_empty() {
103 Vec::new()
104 } else {
105 bincode::deserialize(order_blob).context("deserializing workspace root order")?
106 };
107
108 Ok((Self(order), start_index + 1))
109 }
110}
111
112impl From<SerializedDevServerProject> for SerializedWorkspaceLocation {
113 fn from(dev_server_project: SerializedDevServerProject) -> Self {
114 Self::DevServer(dev_server_project)
115 }
116}
117
118impl StaticColumnCount for SerializedDevServerProject {}
119impl Bind for &SerializedDevServerProject {
120 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
121 let next_index = statement.bind(&self.id.0, start_index)?;
122 let next_index = statement.bind(&self.dev_server_name, next_index)?;
123 let paths = serde_json::to_string(&self.paths)?;
124 statement.bind(&paths, next_index)
125 }
126}
127
128impl Column for SerializedDevServerProject {
129 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
130 let id = statement.column_int64(start_index)?;
131 let dev_server_name = statement.column_text(start_index + 1)?.to_string();
132 let paths = statement.column_text(start_index + 2)?.to_string();
133 let paths: Vec<SharedString> = if paths.starts_with('[') {
134 serde_json::from_str(&paths).context("JSON deserialization of paths failed")?
135 } else {
136 vec![paths.into()]
137 };
138
139 Ok((
140 Self {
141 id: DevServerProjectId(id as u64),
142 dev_server_name,
143 paths,
144 },
145 start_index + 3,
146 ))
147 }
148}
149
150#[derive(Debug, PartialEq, Clone)]
151pub enum SerializedWorkspaceLocation {
152 Local(LocalPaths, LocalPathsOrder),
153 DevServer(SerializedDevServerProject),
154}
155
156#[derive(Debug, PartialEq, Clone)]
157pub(crate) struct SerializedWorkspace {
158 pub(crate) id: WorkspaceId,
159 pub(crate) location: SerializedWorkspaceLocation,
160 pub(crate) center_group: SerializedPaneGroup,
161 pub(crate) window_bounds: Option<SerializedWindowBounds>,
162 pub(crate) centered_layout: bool,
163 pub(crate) display: Option<Uuid>,
164 pub(crate) docks: DockStructure,
165}
166
167#[derive(Debug, PartialEq, Clone, Default)]
168pub struct DockStructure {
169 pub(crate) left: DockData,
170 pub(crate) right: DockData,
171 pub(crate) bottom: DockData,
172}
173
174impl Column for DockStructure {
175 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
176 let (left, next_index) = DockData::column(statement, start_index)?;
177 let (right, next_index) = DockData::column(statement, next_index)?;
178 let (bottom, next_index) = DockData::column(statement, next_index)?;
179 Ok((
180 DockStructure {
181 left,
182 right,
183 bottom,
184 },
185 next_index,
186 ))
187 }
188}
189
190impl Bind for DockStructure {
191 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
192 let next_index = statement.bind(&self.left, start_index)?;
193 let next_index = statement.bind(&self.right, next_index)?;
194 statement.bind(&self.bottom, next_index)
195 }
196}
197
198#[derive(Debug, PartialEq, Clone, Default)]
199pub struct DockData {
200 pub(crate) visible: bool,
201 pub(crate) active_panel: Option<String>,
202 pub(crate) zoom: bool,
203}
204
205impl Column for DockData {
206 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
207 let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
208 let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
209 let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
210 Ok((
211 DockData {
212 visible: visible.unwrap_or(false),
213 active_panel,
214 zoom: zoom.unwrap_or(false),
215 },
216 next_index,
217 ))
218 }
219}
220
221impl Bind for DockData {
222 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
223 let next_index = statement.bind(&self.visible, start_index)?;
224 let next_index = statement.bind(&self.active_panel, next_index)?;
225 statement.bind(&self.zoom, next_index)
226 }
227}
228
229#[derive(Debug, PartialEq, Clone)]
230pub(crate) enum SerializedPaneGroup {
231 Group {
232 axis: SerializedAxis,
233 flexes: Option<Vec<f32>>,
234 children: Vec<SerializedPaneGroup>,
235 },
236 Pane(SerializedPane),
237}
238
239#[cfg(test)]
240impl Default for SerializedPaneGroup {
241 fn default() -> Self {
242 Self::Pane(SerializedPane {
243 children: vec![SerializedItem::default()],
244 active: false,
245 })
246 }
247}
248
249impl SerializedPaneGroup {
250 #[async_recursion(?Send)]
251 pub(crate) async fn deserialize(
252 self,
253 project: &Model<Project>,
254 workspace_id: WorkspaceId,
255 workspace: WeakView<Workspace>,
256 cx: &mut AsyncWindowContext,
257 ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
258 match self {
259 SerializedPaneGroup::Group {
260 axis,
261 children,
262 flexes,
263 } => {
264 let mut current_active_pane = None;
265 let mut members = Vec::new();
266 let mut items = Vec::new();
267 for child in children {
268 if let Some((new_member, active_pane, new_items)) = child
269 .deserialize(project, workspace_id, workspace.clone(), cx)
270 .await
271 {
272 members.push(new_member);
273 items.extend(new_items);
274 current_active_pane = current_active_pane.or(active_pane);
275 }
276 }
277
278 if members.is_empty() {
279 return None;
280 }
281
282 if members.len() == 1 {
283 return Some((members.remove(0), current_active_pane, items));
284 }
285
286 Some((
287 Member::Axis(PaneAxis::load(axis.0, members, flexes)),
288 current_active_pane,
289 items,
290 ))
291 }
292 SerializedPaneGroup::Pane(serialized_pane) => {
293 let pane = workspace
294 .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
295 .log_err()?;
296 let active = serialized_pane.active;
297 let new_items = serialized_pane
298 .deserialize_to(project, &pane, workspace_id, workspace.clone(), cx)
299 .await
300 .log_err()?;
301
302 if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
303 let pane = pane.upgrade()?;
304 Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
305 } else {
306 let pane = pane.upgrade()?;
307 workspace
308 .update(cx, |workspace, cx| workspace.force_remove_pane(&pane, cx))
309 .log_err()?;
310 None
311 }
312 }
313 }
314 }
315}
316
317#[derive(Debug, PartialEq, Eq, Default, Clone)]
318pub struct SerializedPane {
319 pub(crate) active: bool,
320 pub(crate) children: Vec<SerializedItem>,
321}
322
323impl SerializedPane {
324 pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
325 SerializedPane { children, active }
326 }
327
328 pub async fn deserialize_to(
329 &self,
330 project: &Model<Project>,
331 pane: &WeakView<Pane>,
332 workspace_id: WorkspaceId,
333 workspace: WeakView<Workspace>,
334 cx: &mut AsyncWindowContext,
335 ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
336 let mut item_tasks = Vec::new();
337 let mut active_item_index = None;
338 let mut preview_item_index = None;
339 for (index, item) in self.children.iter().enumerate() {
340 let project = project.clone();
341 item_tasks.push(pane.update(cx, |_, cx| {
342 if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
343 deserializer(project, workspace.clone(), workspace_id, item.item_id, cx)
344 } else {
345 Task::ready(Err(anyhow::anyhow!(
346 "Deserializer does not exist for item kind: {}",
347 item.kind
348 )))
349 }
350 })?);
351 if item.active {
352 active_item_index = Some(index);
353 }
354 if item.preview {
355 preview_item_index = Some(index);
356 }
357 }
358
359 let mut items = Vec::new();
360 for item_handle in futures::future::join_all(item_tasks).await {
361 let item_handle = item_handle.log_err();
362 items.push(item_handle.clone());
363
364 if let Some(item_handle) = item_handle {
365 pane.update(cx, |pane, cx| {
366 pane.add_item(item_handle.clone(), true, true, None, cx);
367 })?;
368 }
369 }
370
371 if let Some(active_item_index) = active_item_index {
372 pane.update(cx, |pane, cx| {
373 pane.activate_item(active_item_index, false, false, cx);
374 })?;
375 }
376
377 if let Some(preview_item_index) = preview_item_index {
378 pane.update(cx, |pane, cx| {
379 if let Some(item) = pane.item_for_index(preview_item_index) {
380 pane.set_preview_item_id(Some(item.item_id()), cx);
381 }
382 })?;
383 }
384
385 anyhow::Ok(items)
386 }
387}
388
389pub type GroupId = i64;
390pub type PaneId = i64;
391pub type ItemId = u64;
392
393#[derive(Debug, PartialEq, Eq, Clone)]
394pub struct SerializedItem {
395 pub kind: Arc<str>,
396 pub item_id: ItemId,
397 pub active: bool,
398 pub preview: bool,
399}
400
401impl SerializedItem {
402 pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool, preview: bool) -> Self {
403 Self {
404 kind: Arc::from(kind.as_ref()),
405 item_id,
406 active,
407 preview,
408 }
409 }
410}
411
412#[cfg(test)]
413impl Default for SerializedItem {
414 fn default() -> Self {
415 SerializedItem {
416 kind: Arc::from("Terminal"),
417 item_id: 100000,
418 active: false,
419 preview: false,
420 }
421 }
422}
423
424impl StaticColumnCount for SerializedItem {
425 fn column_count() -> usize {
426 4
427 }
428}
429impl Bind for &SerializedItem {
430 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
431 let next_index = statement.bind(&self.kind, start_index)?;
432 let next_index = statement.bind(&self.item_id, next_index)?;
433 let next_index = statement.bind(&self.active, next_index)?;
434 statement.bind(&self.preview, next_index)
435 }
436}
437
438impl Column for SerializedItem {
439 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
440 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
441 let (item_id, next_index) = ItemId::column(statement, next_index)?;
442 let (active, next_index) = bool::column(statement, next_index)?;
443 let (preview, next_index) = bool::column(statement, next_index)?;
444 Ok((
445 SerializedItem {
446 kind,
447 item_id,
448 active,
449 preview,
450 },
451 next_index,
452 ))
453 }
454}