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