1// mod dragged_item_receiver;
2
3use crate::{
4 item::{Item, ItemHandle, WeakItemHandle},
5 toolbar::Toolbar,
6 workspace_settings::{AutosaveSetting, WorkspaceSettings},
7 SplitDirection, Workspace,
8};
9use anyhow::Result;
10use collections::{HashMap, HashSet, VecDeque};
11use gpui2::{
12 AppContext, AsyncWindowContext, EntityId, EventEmitter, Model, PromptLevel, Task, View,
13 ViewContext, VisualContext, WeakView, WindowContext,
14};
15use parking_lot::Mutex;
16use project2::{Project, ProjectEntryId, ProjectPath};
17use serde::Deserialize;
18use settings2::Settings;
19use std::{
20 any::Any,
21 cmp, fmt, mem,
22 path::{Path, PathBuf},
23 sync::{
24 atomic::{AtomicUsize, Ordering},
25 Arc,
26 },
27};
28use util::truncate_and_remove_front;
29
30#[derive(PartialEq, Clone, Copy, Deserialize, Debug)]
31#[serde(rename_all = "camelCase")]
32pub enum SaveIntent {
33 /// write all files (even if unchanged)
34 /// prompt before overwriting on-disk changes
35 Save,
36 /// write any files that have local changes
37 /// prompt before overwriting on-disk changes
38 SaveAll,
39 /// always prompt for a new path
40 SaveAs,
41 /// prompt "you have unsaved changes" before writing
42 Close,
43 /// write all dirty files, don't prompt on conflict
44 Overwrite,
45 /// skip all save-related behavior
46 Skip,
47}
48
49// #[derive(Clone, Deserialize, PartialEq)]
50// pub struct ActivateItem(pub usize);
51
52// #[derive(Clone, PartialEq)]
53// pub struct CloseItemById {
54// pub item_id: usize,
55// pub pane: WeakView<Pane>,
56// }
57
58// #[derive(Clone, PartialEq)]
59// pub struct CloseItemsToTheLeftById {
60// pub item_id: usize,
61// pub pane: WeakView<Pane>,
62// }
63
64// #[derive(Clone, PartialEq)]
65// pub struct CloseItemsToTheRightById {
66// pub item_id: usize,
67// pub pane: WeakView<Pane>,
68// }
69
70// #[derive(Clone, PartialEq, Debug, Deserialize, Default)]
71// #[serde(rename_all = "camelCase")]
72// pub struct CloseActiveItem {
73// pub save_intent: Option<SaveIntent>,
74// }
75
76// #[derive(Clone, PartialEq, Debug, Deserialize)]
77// #[serde(rename_all = "camelCase")]
78// pub struct CloseAllItems {
79// pub save_intent: Option<SaveIntent>,
80// }
81
82// todo!()
83// actions!(
84// pane,
85// [
86// ActivatePrevItem,
87// ActivateNextItem,
88// ActivateLastItem,
89// CloseInactiveItems,
90// CloseCleanItems,
91// CloseItemsToTheLeft,
92// CloseItemsToTheRight,
93// GoBack,
94// GoForward,
95// ReopenClosedItem,
96// SplitLeft,
97// SplitUp,
98// SplitRight,
99// SplitDown,
100// ]
101// );
102
103// impl_actions!(pane, [ActivateItem, CloseActiveItem, CloseAllItems]);
104
105const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
106
107pub fn init(cx: &mut AppContext) {
108 // todo!()
109 // cx.add_action(Pane::toggle_zoom);
110 // cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
111 // pane.activate_item(action.0, true, true, cx);
112 // });
113 // cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
114 // pane.activate_item(pane.items.len() - 1, true, true, cx);
115 // });
116 // cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
117 // pane.activate_prev_item(true, cx);
118 // });
119 // cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
120 // pane.activate_next_item(true, cx);
121 // });
122 // cx.add_async_action(Pane::close_active_item);
123 // cx.add_async_action(Pane::close_inactive_items);
124 // cx.add_async_action(Pane::close_clean_items);
125 // cx.add_async_action(Pane::close_items_to_the_left);
126 // cx.add_async_action(Pane::close_items_to_the_right);
127 // cx.add_async_action(Pane::close_all_items);
128 // cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
129 // cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
130 // cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
131 // cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
132}
133
134pub enum Event {
135 AddItem { item: Box<dyn ItemHandle> },
136 ActivateItem { local: bool },
137 Remove,
138 RemoveItem { item_id: EntityId },
139 Split(SplitDirection),
140 ChangeItemTitle,
141 Focus,
142 ZoomIn,
143 ZoomOut,
144}
145
146impl fmt::Debug for Event {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 match self {
149 Event::AddItem { item } => f.debug_struct("AddItem").field("item", &item.id()).finish(),
150 Event::ActivateItem { local } => f
151 .debug_struct("ActivateItem")
152 .field("local", local)
153 .finish(),
154 Event::Remove => f.write_str("Remove"),
155 Event::RemoveItem { item_id } => f
156 .debug_struct("RemoveItem")
157 .field("item_id", item_id)
158 .finish(),
159 Event::Split(direction) => f
160 .debug_struct("Split")
161 .field("direction", direction)
162 .finish(),
163 Event::ChangeItemTitle => f.write_str("ChangeItemTitle"),
164 Event::Focus => f.write_str("Focus"),
165 Event::ZoomIn => f.write_str("ZoomIn"),
166 Event::ZoomOut => f.write_str("ZoomOut"),
167 }
168 }
169}
170
171pub struct Pane {
172 items: Vec<Box<dyn ItemHandle>>,
173 activation_history: Vec<EntityId>,
174 zoomed: bool,
175 active_item_index: usize,
176 // last_focused_view_by_item: HashMap<usize, AnyWeakViewHandle>,
177 autoscroll: bool,
178 nav_history: NavHistory,
179 toolbar: View<Toolbar>,
180 // tab_bar_context_menu: TabBarContextMenu,
181 // tab_context_menu: ViewHandle<ContextMenu>,
182 workspace: WeakView<Workspace>,
183 project: Model<Project>,
184 has_focus: bool,
185 // can_drop: Rc<dyn Fn(&DragAndDrop<Workspace>, &WindowContext) -> bool>,
186 // can_split: bool,
187 // render_tab_bar_buttons: Rc<dyn Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement<Pane>>,
188}
189
190pub struct ItemNavHistory {
191 history: NavHistory,
192 item: Arc<dyn WeakItemHandle>,
193}
194
195#[derive(Clone)]
196pub struct NavHistory(Arc<Mutex<NavHistoryState>>);
197
198struct NavHistoryState {
199 mode: NavigationMode,
200 backward_stack: VecDeque<NavigationEntry>,
201 forward_stack: VecDeque<NavigationEntry>,
202 closed_stack: VecDeque<NavigationEntry>,
203 paths_by_item: HashMap<EntityId, (ProjectPath, Option<PathBuf>)>,
204 pane: WeakView<Pane>,
205 next_timestamp: Arc<AtomicUsize>,
206}
207
208#[derive(Copy, Clone)]
209pub enum NavigationMode {
210 Normal,
211 GoingBack,
212 GoingForward,
213 ClosingItem,
214 ReopeningClosedItem,
215 Disabled,
216}
217
218impl Default for NavigationMode {
219 fn default() -> Self {
220 Self::Normal
221 }
222}
223
224pub struct NavigationEntry {
225 pub item: Arc<dyn WeakItemHandle>,
226 pub data: Option<Box<dyn Any + Send>>,
227 pub timestamp: usize,
228}
229
230// pub struct DraggedItem {
231// pub handle: Box<dyn ItemHandle>,
232// pub pane: WeakView<Pane>,
233// }
234
235// pub enum ReorderBehavior {
236// None,
237// MoveAfterActive,
238// MoveToIndex(usize),
239// }
240
241// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
242// enum TabBarContextMenuKind {
243// New,
244// Split,
245// }
246
247// struct TabBarContextMenu {
248// kind: TabBarContextMenuKind,
249// handle: ViewHandle<ContextMenu>,
250// }
251
252// impl TabBarContextMenu {
253// fn handle_if_kind(&self, kind: TabBarContextMenuKind) -> Option<ViewHandle<ContextMenu>> {
254// if self.kind == kind {
255// return Some(self.handle.clone());
256// }
257// None
258// }
259// }
260
261// #[allow(clippy::too_many_arguments)]
262// fn nav_button<A: Action, F: 'static + Fn(&mut Pane, &mut ViewContext<Pane>)>(
263// svg_path: &'static str,
264// style: theme2::Interactive<theme2::IconButton>,
265// nav_button_height: f32,
266// tooltip_style: TooltipStyle,
267// enabled: bool,
268// on_click: F,
269// tooltip_action: A,
270// action_name: &str,
271// cx: &mut ViewContext<Pane>,
272// ) -> AnyElement<Pane> {
273// MouseEventHandler::new::<A, _>(0, cx, |state, _| {
274// let style = if enabled {
275// style.style_for(state)
276// } else {
277// style.disabled_style()
278// };
279// Svg::new(svg_path)
280// .with_color(style.color)
281// .constrained()
282// .with_width(style.icon_width)
283// .aligned()
284// .contained()
285// .with_style(style.container)
286// .constrained()
287// .with_width(style.button_width)
288// .with_height(nav_button_height)
289// .aligned()
290// .top()
291// })
292// .with_cursor_style(if enabled {
293// CursorStyle::PointingHand
294// } else {
295// CursorStyle::default()
296// })
297// .on_click(MouseButton::Left, move |_, toolbar, cx| {
298// on_click(toolbar, cx)
299// })
300// .with_tooltip::<A>(
301// 0,
302// action_name.to_string(),
303// Some(Box::new(tooltip_action)),
304// tooltip_style,
305// cx,
306// )
307// .contained()
308// .into_any_named("nav button")
309// }
310
311impl EventEmitter for Pane {
312 type Event = Event;
313}
314
315impl Pane {
316 pub fn new(
317 workspace: WeakView<Workspace>,
318 project: Model<Project>,
319 next_timestamp: Arc<AtomicUsize>,
320 cx: &mut ViewContext<Self>,
321 ) -> Self {
322 // todo!("context menu")
323 // let pane_view_id = cx.view_id();
324 // let context_menu = cx.add_view(|cx| ContextMenu::new(pane_view_id, cx));
325 // context_menu.update(cx, |menu, _| {
326 // menu.set_position_mode(OverlayPositionMode::Local)
327 // });
328
329 let handle = cx.view().downgrade();
330 Self {
331 items: Vec::new(),
332 activation_history: Vec::new(),
333 zoomed: false,
334 active_item_index: 0,
335 // last_focused_view_by_item: Default::default(),
336 autoscroll: false,
337 nav_history: NavHistory(Arc::new(Mutex::new(NavHistoryState {
338 mode: NavigationMode::Normal,
339 backward_stack: Default::default(),
340 forward_stack: Default::default(),
341 closed_stack: Default::default(),
342 paths_by_item: Default::default(),
343 pane: handle.clone(),
344 next_timestamp,
345 }))),
346 toolbar: cx.build_view(|_| Toolbar::new()),
347 // tab_bar_context_menu: TabBarContextMenu {
348 // kind: TabBarContextMenuKind::New,
349 // handle: context_menu,
350 // },
351 // tab_context_menu: cx.add_view(|cx| ContextMenu::new(pane_view_id, cx)),
352 workspace,
353 project,
354 has_focus: false,
355 // can_drop: Rc::new(|_, _| true),
356 // can_split: true,
357 // render_tab_bar_buttons: Rc::new(move |pane, cx| {
358 // Flex::row()
359 // // New menu
360 // .with_child(Self::render_tab_bar_button(
361 // 0,
362 // "icons/plus.svg",
363 // false,
364 // Some(("New...".into(), None)),
365 // cx,
366 // |pane, cx| pane.deploy_new_menu(cx),
367 // |pane, cx| {
368 // pane.tab_bar_context_menu
369 // .handle
370 // .update(cx, |menu, _| menu.delay_cancel())
371 // },
372 // pane.tab_bar_context_menu
373 // .handle_if_kind(TabBarContextMenuKind::New),
374 // ))
375 // .with_child(Self::render_tab_bar_button(
376 // 1,
377 // "icons/split.svg",
378 // false,
379 // Some(("Split Pane".into(), None)),
380 // cx,
381 // |pane, cx| pane.deploy_split_menu(cx),
382 // |pane, cx| {
383 // pane.tab_bar_context_menu
384 // .handle
385 // .update(cx, |menu, _| menu.delay_cancel())
386 // },
387 // pane.tab_bar_context_menu
388 // .handle_if_kind(TabBarContextMenuKind::Split),
389 // ))
390 // .with_child({
391 // let icon_path;
392 // let tooltip_label;
393 // if pane.is_zoomed() {
394 // icon_path = "icons/minimize.svg";
395 // tooltip_label = "Zoom In";
396 // } else {
397 // icon_path = "icons/maximize.svg";
398 // tooltip_label = "Zoom In";
399 // }
400
401 // Pane::render_tab_bar_button(
402 // 2,
403 // icon_path,
404 // pane.is_zoomed(),
405 // Some((tooltip_label, Some(Box::new(ToggleZoom)))),
406 // cx,
407 // move |pane, cx| pane.toggle_zoom(&Default::default(), cx),
408 // move |_, _| {},
409 // None,
410 // )
411 // })
412 // .into_any()
413 // }),
414 }
415 }
416
417 // pub(crate) fn workspace(&self) -> &WeakView<Workspace> {
418 // &self.workspace
419 // }
420
421 pub fn has_focus(&self) -> bool {
422 self.has_focus
423 }
424
425 // pub fn active_item_index(&self) -> usize {
426 // self.active_item_index
427 // }
428
429 // pub fn on_can_drop<F>(&mut self, can_drop: F)
430 // where
431 // F: 'static + Fn(&DragAndDrop<Workspace>, &WindowContext) -> bool,
432 // {
433 // self.can_drop = Rc::new(can_drop);
434 // }
435
436 // pub fn set_can_split(&mut self, can_split: bool, cx: &mut ViewContext<Self>) {
437 // self.can_split = can_split;
438 // cx.notify();
439 // }
440
441 // pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
442 // self.toolbar.update(cx, |toolbar, cx| {
443 // toolbar.set_can_navigate(can_navigate, cx);
444 // });
445 // cx.notify();
446 // }
447
448 // pub fn set_render_tab_bar_buttons<F>(&mut self, cx: &mut ViewContext<Self>, render: F)
449 // where
450 // F: 'static + Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement<Pane>,
451 // {
452 // self.render_tab_bar_buttons = Rc::new(render);
453 // cx.notify();
454 // }
455
456 pub fn nav_history_for_item<T: Item>(&self, item: &View<T>) -> ItemNavHistory {
457 ItemNavHistory {
458 history: self.nav_history.clone(),
459 item: Arc::new(item.downgrade()),
460 }
461 }
462
463 pub fn nav_history(&self) -> &NavHistory {
464 &self.nav_history
465 }
466
467 pub fn nav_history_mut(&mut self) -> &mut NavHistory {
468 &mut self.nav_history
469 }
470
471 pub fn disable_history(&mut self) {
472 self.nav_history.disable();
473 }
474
475 pub fn enable_history(&mut self) {
476 self.nav_history.enable();
477 }
478
479 pub fn can_navigate_backward(&self) -> bool {
480 !self.nav_history.0.lock().backward_stack.is_empty()
481 }
482
483 pub fn can_navigate_forward(&self) -> bool {
484 !self.nav_history.0.lock().forward_stack.is_empty()
485 }
486
487 fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
488 self.toolbar.update(cx, |_, cx| cx.notify());
489 }
490
491 pub(crate) fn open_item(
492 &mut self,
493 project_entry_id: ProjectEntryId,
494 focus_item: bool,
495 cx: &mut ViewContext<Self>,
496 build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
497 ) -> Box<dyn ItemHandle> {
498 let mut existing_item = None;
499 for (index, item) in self.items.iter().enumerate() {
500 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [project_entry_id]
501 {
502 let item = item.boxed_clone();
503 existing_item = Some((index, item));
504 break;
505 }
506 }
507
508 if let Some((index, existing_item)) = existing_item {
509 self.activate_item(index, focus_item, focus_item, cx);
510 existing_item
511 } else {
512 let new_item = build_item(cx);
513 self.add_item(new_item.clone(), true, focus_item, None, cx);
514 new_item
515 }
516 }
517
518 pub fn add_item(
519 &mut self,
520 item: Box<dyn ItemHandle>,
521 activate_pane: bool,
522 focus_item: bool,
523 destination_index: Option<usize>,
524 cx: &mut ViewContext<Self>,
525 ) {
526 if item.is_singleton(cx) {
527 if let Some(&entry_id) = item.project_entry_ids(cx).get(0) {
528 let project = self.project.read(cx);
529 if let Some(project_path) = project.path_for_entry(entry_id, cx) {
530 let abs_path = project.absolute_path(&project_path, cx);
531 self.nav_history
532 .0
533 .lock()
534 .paths_by_item
535 .insert(item.id(), (project_path, abs_path));
536 }
537 }
538 }
539 // If no destination index is specified, add or move the item after the active item.
540 let mut insertion_index = {
541 cmp::min(
542 if let Some(destination_index) = destination_index {
543 destination_index
544 } else {
545 self.active_item_index + 1
546 },
547 self.items.len(),
548 )
549 };
550
551 // Does the item already exist?
552 let project_entry_id = if item.is_singleton(cx) {
553 item.project_entry_ids(cx).get(0).copied()
554 } else {
555 None
556 };
557
558 let existing_item_index = self.items.iter().position(|existing_item| {
559 if existing_item.id() == item.id() {
560 true
561 } else if existing_item.is_singleton(cx) {
562 existing_item
563 .project_entry_ids(cx)
564 .get(0)
565 .map_or(false, |existing_entry_id| {
566 Some(existing_entry_id) == project_entry_id.as_ref()
567 })
568 } else {
569 false
570 }
571 });
572
573 if let Some(existing_item_index) = existing_item_index {
574 // If the item already exists, move it to the desired destination and activate it
575
576 if existing_item_index != insertion_index {
577 let existing_item_is_active = existing_item_index == self.active_item_index;
578
579 // If the caller didn't specify a destination and the added item is already
580 // the active one, don't move it
581 if existing_item_is_active && destination_index.is_none() {
582 insertion_index = existing_item_index;
583 } else {
584 self.items.remove(existing_item_index);
585 if existing_item_index < self.active_item_index {
586 self.active_item_index -= 1;
587 }
588 insertion_index = insertion_index.min(self.items.len());
589
590 self.items.insert(insertion_index, item.clone());
591
592 if existing_item_is_active {
593 self.active_item_index = insertion_index;
594 } else if insertion_index <= self.active_item_index {
595 self.active_item_index += 1;
596 }
597 }
598
599 cx.notify();
600 }
601
602 self.activate_item(insertion_index, activate_pane, focus_item, cx);
603 } else {
604 self.items.insert(insertion_index, item.clone());
605 if insertion_index <= self.active_item_index {
606 self.active_item_index += 1;
607 }
608
609 self.activate_item(insertion_index, activate_pane, focus_item, cx);
610 cx.notify();
611 }
612
613 cx.emit(Event::AddItem { item });
614 }
615
616 pub fn items_len(&self) -> usize {
617 self.items.len()
618 }
619
620 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> + DoubleEndedIterator {
621 self.items.iter()
622 }
623
624 // pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
625 // self.items
626 // .iter()
627 // .filter_map(|item| item.as_any().clone().downcast())
628 // }
629
630 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
631 self.items.get(self.active_item_index).cloned()
632 }
633
634 // pub fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Vector2F> {
635 // self.items
636 // .get(self.active_item_index)?
637 // .pixel_position_of_cursor(cx)
638 // }
639
640 // pub fn item_for_entry(
641 // &self,
642 // entry_id: ProjectEntryId,
643 // cx: &AppContext,
644 // ) -> Option<Box<dyn ItemHandle>> {
645 // self.items.iter().find_map(|item| {
646 // if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
647 // Some(item.boxed_clone())
648 // } else {
649 // None
650 // }
651 // })
652 // }
653
654 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
655 self.items.iter().position(|i| i.id() == item.id())
656 }
657
658 // pub fn toggle_zoom(&mut self, _: &ToggleZoom, cx: &mut ViewContext<Self>) {
659 // // Potentially warn the user of the new keybinding
660 // let workspace_handle = self.workspace().clone();
661 // cx.spawn(|_, mut cx| async move { notify_of_new_dock(&workspace_handle, &mut cx) })
662 // .detach();
663
664 // if self.zoomed {
665 // cx.emit(Event::ZoomOut);
666 // } else if !self.items.is_empty() {
667 // if !self.has_focus {
668 // cx.focus_self();
669 // }
670 // cx.emit(Event::ZoomIn);
671 // }
672 // }
673
674 pub fn activate_item(
675 &mut self,
676 index: usize,
677 activate_pane: bool,
678 focus_item: bool,
679 cx: &mut ViewContext<Self>,
680 ) {
681 use NavigationMode::{GoingBack, GoingForward};
682
683 if index < self.items.len() {
684 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
685 if prev_active_item_ix != self.active_item_index
686 || matches!(self.nav_history.mode(), GoingBack | GoingForward)
687 {
688 if let Some(prev_item) = self.items.get(prev_active_item_ix) {
689 prev_item.deactivated(cx);
690 }
691
692 cx.emit(Event::ActivateItem {
693 local: activate_pane,
694 });
695 }
696
697 if let Some(newly_active_item) = self.items.get(index) {
698 self.activation_history
699 .retain(|&previously_active_item_id| {
700 previously_active_item_id != newly_active_item.id()
701 });
702 self.activation_history.push(newly_active_item.id());
703 }
704
705 self.update_toolbar(cx);
706
707 if focus_item {
708 self.focus_active_item(cx);
709 }
710
711 self.autoscroll = true;
712 cx.notify();
713 }
714 }
715
716 // pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
717 // let mut index = self.active_item_index;
718 // if index > 0 {
719 // index -= 1;
720 // } else if !self.items.is_empty() {
721 // index = self.items.len() - 1;
722 // }
723 // self.activate_item(index, activate_pane, activate_pane, cx);
724 // }
725
726 // pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
727 // let mut index = self.active_item_index;
728 // if index + 1 < self.items.len() {
729 // index += 1;
730 // } else {
731 // index = 0;
732 // }
733 // self.activate_item(index, activate_pane, activate_pane, cx);
734 // }
735
736 // pub fn close_active_item(
737 // &mut self,
738 // action: &CloseActiveItem,
739 // cx: &mut ViewContext<Self>,
740 // ) -> Option<Task<Result<()>>> {
741 // if self.items.is_empty() {
742 // return None;
743 // }
744 // let active_item_id = self.items[self.active_item_index].id();
745 // Some(self.close_item_by_id(
746 // active_item_id,
747 // action.save_intent.unwrap_or(SaveIntent::Close),
748 // cx,
749 // ))
750 // }
751
752 pub fn close_item_by_id(
753 &mut self,
754 item_id_to_close: EntityId,
755 save_intent: SaveIntent,
756 cx: &mut ViewContext<Self>,
757 ) -> Task<Result<()>> {
758 self.close_items(cx, save_intent, move |view_id| view_id == item_id_to_close)
759 }
760
761 // pub fn close_inactive_items(
762 // &mut self,
763 // _: &CloseInactiveItems,
764 // cx: &mut ViewContext<Self>,
765 // ) -> Option<Task<Result<()>>> {
766 // if self.items.is_empty() {
767 // return None;
768 // }
769
770 // let active_item_id = self.items[self.active_item_index].id();
771 // Some(self.close_items(cx, SaveIntent::Close, move |item_id| {
772 // item_id != active_item_id
773 // }))
774 // }
775
776 // pub fn close_clean_items(
777 // &mut self,
778 // _: &CloseCleanItems,
779 // cx: &mut ViewContext<Self>,
780 // ) -> Option<Task<Result<()>>> {
781 // let item_ids: Vec<_> = self
782 // .items()
783 // .filter(|item| !item.is_dirty(cx))
784 // .map(|item| item.id())
785 // .collect();
786 // Some(self.close_items(cx, SaveIntent::Close, move |item_id| {
787 // item_ids.contains(&item_id)
788 // }))
789 // }
790
791 // pub fn close_items_to_the_left(
792 // &mut self,
793 // _: &CloseItemsToTheLeft,
794 // cx: &mut ViewContext<Self>,
795 // ) -> Option<Task<Result<()>>> {
796 // if self.items.is_empty() {
797 // return None;
798 // }
799 // let active_item_id = self.items[self.active_item_index].id();
800 // Some(self.close_items_to_the_left_by_id(active_item_id, cx))
801 // }
802
803 // pub fn close_items_to_the_left_by_id(
804 // &mut self,
805 // item_id: usize,
806 // cx: &mut ViewContext<Self>,
807 // ) -> Task<Result<()>> {
808 // let item_ids: Vec<_> = self
809 // .items()
810 // .take_while(|item| item.id() != item_id)
811 // .map(|item| item.id())
812 // .collect();
813 // self.close_items(cx, SaveIntent::Close, move |item_id| {
814 // item_ids.contains(&item_id)
815 // })
816 // }
817
818 // pub fn close_items_to_the_right(
819 // &mut self,
820 // _: &CloseItemsToTheRight,
821 // cx: &mut ViewContext<Self>,
822 // ) -> Option<Task<Result<()>>> {
823 // if self.items.is_empty() {
824 // return None;
825 // }
826 // let active_item_id = self.items[self.active_item_index].id();
827 // Some(self.close_items_to_the_right_by_id(active_item_id, cx))
828 // }
829
830 // pub fn close_items_to_the_right_by_id(
831 // &mut self,
832 // item_id: usize,
833 // cx: &mut ViewContext<Self>,
834 // ) -> Task<Result<()>> {
835 // let item_ids: Vec<_> = self
836 // .items()
837 // .rev()
838 // .take_while(|item| item.id() != item_id)
839 // .map(|item| item.id())
840 // .collect();
841 // self.close_items(cx, SaveIntent::Close, move |item_id| {
842 // item_ids.contains(&item_id)
843 // })
844 // }
845
846 // pub fn close_all_items(
847 // &mut self,
848 // action: &CloseAllItems,
849 // cx: &mut ViewContext<Self>,
850 // ) -> Option<Task<Result<()>>> {
851 // if self.items.is_empty() {
852 // return None;
853 // }
854
855 // Some(
856 // self.close_items(cx, action.save_intent.unwrap_or(SaveIntent::Close), |_| {
857 // true
858 // }),
859 // )
860 // }
861
862 pub(super) fn file_names_for_prompt(
863 items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
864 all_dirty_items: usize,
865 cx: &AppContext,
866 ) -> String {
867 /// Quantity of item paths displayed in prompt prior to cutoff..
868 const FILE_NAMES_CUTOFF_POINT: usize = 10;
869 let mut file_names: Vec<_> = items
870 .filter_map(|item| {
871 item.project_path(cx).and_then(|project_path| {
872 project_path
873 .path
874 .file_name()
875 .and_then(|name| name.to_str().map(ToOwned::to_owned))
876 })
877 })
878 .take(FILE_NAMES_CUTOFF_POINT)
879 .collect();
880 let should_display_followup_text =
881 all_dirty_items > FILE_NAMES_CUTOFF_POINT || file_names.len() != all_dirty_items;
882 if should_display_followup_text {
883 let not_shown_files = all_dirty_items - file_names.len();
884 if not_shown_files == 1 {
885 file_names.push(".. 1 file not shown".into());
886 } else {
887 file_names.push(format!(".. {} files not shown", not_shown_files).into());
888 }
889 }
890 let file_names = file_names.join("\n");
891 format!(
892 "Do you want to save changes to the following {} files?\n{file_names}",
893 all_dirty_items
894 )
895 }
896
897 pub fn close_items(
898 &mut self,
899 cx: &mut ViewContext<Pane>,
900 mut save_intent: SaveIntent,
901 should_close: impl 'static + Fn(EntityId) -> bool,
902 ) -> Task<Result<()>> {
903 // Find the items to close.
904 let mut items_to_close = Vec::new();
905 let mut dirty_items = Vec::new();
906 for item in &self.items {
907 if should_close(item.id()) {
908 items_to_close.push(item.boxed_clone());
909 if item.is_dirty(cx) {
910 dirty_items.push(item.boxed_clone());
911 }
912 }
913 }
914
915 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
916 // to focus the singleton buffer when prompting to save that buffer, as opposed
917 // to focusing the multibuffer, because this gives the user a more clear idea
918 // of what content they would be saving.
919 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
920
921 let workspace = self.workspace.clone();
922 cx.spawn(|pane, mut cx| async move {
923 if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
924 let answer = pane.update(&mut cx, |_, cx| {
925 let prompt =
926 Self::file_names_for_prompt(&mut dirty_items.iter(), dirty_items.len(), cx);
927 cx.prompt(
928 PromptLevel::Warning,
929 &prompt,
930 &["Save all", "Discard all", "Cancel"],
931 )
932 })?;
933 match answer.await {
934 Ok(0) => save_intent = SaveIntent::SaveAll,
935 Ok(1) => save_intent = SaveIntent::Skip,
936 _ => {}
937 }
938 }
939 let mut saved_project_items_ids = HashSet::default();
940 for item in items_to_close.clone() {
941 // Find the item's current index and its set of project item models. Avoid
942 // storing these in advance, in case they have changed since this task
943 // was started.
944 let (item_ix, mut project_item_ids) = pane.update(&mut cx, |pane, cx| {
945 (pane.index_for_item(&*item), item.project_item_model_ids(cx))
946 })?;
947 let item_ix = if let Some(ix) = item_ix {
948 ix
949 } else {
950 continue;
951 };
952
953 // Check if this view has any project items that are not open anywhere else
954 // in the workspace, AND that the user has not already been prompted to save.
955 // If there are any such project entries, prompt the user to save this item.
956 let project = workspace.update(&mut cx, |workspace, cx| {
957 for item in workspace.items(cx) {
958 if !items_to_close
959 .iter()
960 .any(|item_to_close| item_to_close.id() == item.id())
961 {
962 let other_project_item_ids = item.project_item_model_ids(cx);
963 project_item_ids.retain(|id| !other_project_item_ids.contains(id));
964 }
965 }
966 workspace.project().clone()
967 })?;
968 let should_save = project_item_ids
969 .iter()
970 .any(|id| saved_project_items_ids.insert(*id));
971
972 if should_save
973 && !Self::save_item(
974 project.clone(),
975 &pane,
976 item_ix,
977 &*item,
978 save_intent,
979 &mut cx,
980 )
981 .await?
982 {
983 break;
984 }
985
986 // Remove the item from the pane.
987 pane.update(&mut cx, |pane, cx| {
988 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
989 pane.remove_item(item_ix, false, cx);
990 }
991 })?;
992 }
993
994 pane.update(&mut cx, |_, cx| cx.notify())?;
995 Ok(())
996 })
997 }
998
999 pub fn remove_item(
1000 &mut self,
1001 item_index: usize,
1002 activate_pane: bool,
1003 cx: &mut ViewContext<Self>,
1004 ) {
1005 self.activation_history
1006 .retain(|&history_entry| history_entry != self.items[item_index].id());
1007
1008 if item_index == self.active_item_index {
1009 let index_to_activate = self
1010 .activation_history
1011 .pop()
1012 .and_then(|last_activated_item| {
1013 self.items.iter().enumerate().find_map(|(index, item)| {
1014 (item.id() == last_activated_item).then_some(index)
1015 })
1016 })
1017 // We didn't have a valid activation history entry, so fallback
1018 // to activating the item to the left
1019 .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
1020
1021 let should_activate = activate_pane || self.has_focus;
1022 self.activate_item(index_to_activate, should_activate, should_activate, cx);
1023 }
1024
1025 let item = self.items.remove(item_index);
1026
1027 cx.emit(Event::RemoveItem { item_id: item.id() });
1028 if self.items.is_empty() {
1029 item.deactivated(cx);
1030 self.update_toolbar(cx);
1031 cx.emit(Event::Remove);
1032 }
1033
1034 if item_index < self.active_item_index {
1035 self.active_item_index -= 1;
1036 }
1037
1038 self.nav_history.set_mode(NavigationMode::ClosingItem);
1039 item.deactivated(cx);
1040 self.nav_history.set_mode(NavigationMode::Normal);
1041
1042 if let Some(path) = item.project_path(cx) {
1043 let abs_path = self
1044 .nav_history
1045 .0
1046 .lock()
1047 .paths_by_item
1048 .get(&item.id())
1049 .and_then(|(_, abs_path)| abs_path.clone());
1050
1051 self.nav_history
1052 .0
1053 .lock()
1054 .paths_by_item
1055 .insert(item.id(), (path, abs_path));
1056 } else {
1057 self.nav_history.0.lock().paths_by_item.remove(&item.id());
1058 }
1059
1060 if self.items.is_empty() && self.zoomed {
1061 cx.emit(Event::ZoomOut);
1062 }
1063
1064 cx.notify();
1065 }
1066
1067 pub async fn save_item(
1068 project: Model<Project>,
1069 pane: &WeakView<Pane>,
1070 item_ix: usize,
1071 item: &dyn ItemHandle,
1072 save_intent: SaveIntent,
1073 cx: &mut AsyncWindowContext,
1074 ) -> Result<bool> {
1075 const CONFLICT_MESSAGE: &str =
1076 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1077
1078 if save_intent == SaveIntent::Skip {
1079 return Ok(true);
1080 }
1081
1082 let (mut has_conflict, mut is_dirty, mut can_save, can_save_as) = cx.update(|_, cx| {
1083 (
1084 item.has_conflict(cx),
1085 item.is_dirty(cx),
1086 item.can_save(cx),
1087 item.is_singleton(cx),
1088 )
1089 })?;
1090
1091 // when saving a single buffer, we ignore whether or not it's dirty.
1092 if save_intent == SaveIntent::Save {
1093 is_dirty = true;
1094 }
1095
1096 if save_intent == SaveIntent::SaveAs {
1097 is_dirty = true;
1098 has_conflict = false;
1099 can_save = false;
1100 }
1101
1102 if save_intent == SaveIntent::Overwrite {
1103 has_conflict = false;
1104 }
1105
1106 if has_conflict && can_save {
1107 let answer = pane.update(cx, |pane, cx| {
1108 pane.activate_item(item_ix, true, true, cx);
1109 cx.prompt(
1110 PromptLevel::Warning,
1111 CONFLICT_MESSAGE,
1112 &["Overwrite", "Discard", "Cancel"],
1113 )
1114 })?;
1115 match answer.await {
1116 Ok(0) => pane.update(cx, |_, cx| item.save(project, cx))?.await?,
1117 Ok(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
1118 _ => return Ok(false),
1119 }
1120 } else if is_dirty && (can_save || can_save_as) {
1121 if save_intent == SaveIntent::Close {
1122 let will_autosave = cx.update(|_, cx| {
1123 matches!(
1124 WorkspaceSettings::get_global(cx).autosave,
1125 AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1126 ) && Self::can_autosave_item(&*item, cx)
1127 })?;
1128 if !will_autosave {
1129 let answer = pane.update(cx, |pane, cx| {
1130 pane.activate_item(item_ix, true, true, cx);
1131 let prompt = dirty_message_for(item.project_path(cx));
1132 cx.prompt(
1133 PromptLevel::Warning,
1134 &prompt,
1135 &["Save", "Don't Save", "Cancel"],
1136 )
1137 })?;
1138 match answer.await {
1139 Ok(0) => {}
1140 Ok(1) => return Ok(true), // Don't save this file
1141 _ => return Ok(false), // Cancel
1142 }
1143 }
1144 }
1145
1146 if can_save {
1147 pane.update(cx, |_, cx| item.save(project, cx))?.await?;
1148 } else if can_save_as {
1149 let start_abs_path = project
1150 .update(cx, |project, cx| {
1151 let worktree = project.visible_worktrees(cx).next()?;
1152 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1153 })?
1154 .unwrap_or_else(|| Path::new("").into());
1155
1156 let abs_path = cx.update(|_, cx| cx.prompt_for_new_path(&start_abs_path))?;
1157 if let Some(abs_path) = abs_path.await.ok().flatten() {
1158 pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
1159 .await?;
1160 } else {
1161 return Ok(false);
1162 }
1163 }
1164 }
1165 Ok(true)
1166 }
1167
1168 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1169 let is_deleted = item.project_entry_ids(cx).is_empty();
1170 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1171 }
1172
1173 pub fn autosave_item(
1174 item: &dyn ItemHandle,
1175 project: Model<Project>,
1176 cx: &mut WindowContext,
1177 ) -> Task<Result<()>> {
1178 if Self::can_autosave_item(item, cx) {
1179 item.save(project, cx)
1180 } else {
1181 Task::ready(Ok(()))
1182 }
1183 }
1184
1185 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1186 todo!();
1187 // if let Some(active_item) = self.active_item() {
1188 // cx.focus(active_item.as_any());
1189 // }
1190 }
1191
1192 // pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1193 // cx.emit(Event::Split(direction));
1194 // }
1195
1196 // fn deploy_split_menu(&mut self, cx: &mut ViewContext<Self>) {
1197 // self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1198 // menu.toggle(
1199 // Default::default(),
1200 // AnchorCorner::TopRight,
1201 // vec![
1202 // ContextMenuItem::action("Split Right", SplitRight),
1203 // ContextMenuItem::action("Split Left", SplitLeft),
1204 // ContextMenuItem::action("Split Up", SplitUp),
1205 // ContextMenuItem::action("Split Down", SplitDown),
1206 // ],
1207 // cx,
1208 // );
1209 // });
1210
1211 // self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1212 // }
1213
1214 // fn deploy_new_menu(&mut self, cx: &mut ViewContext<Self>) {
1215 // self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1216 // menu.toggle(
1217 // Default::default(),
1218 // AnchorCorner::TopRight,
1219 // vec![
1220 // ContextMenuItem::action("New File", NewFile),
1221 // ContextMenuItem::action("New Terminal", NewCenterTerminal),
1222 // ContextMenuItem::action("New Search", NewSearch),
1223 // ],
1224 // cx,
1225 // );
1226 // });
1227
1228 // self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1229 // }
1230
1231 // fn deploy_tab_context_menu(
1232 // &mut self,
1233 // position: Vector2F,
1234 // target_item_id: usize,
1235 // cx: &mut ViewContext<Self>,
1236 // ) {
1237 // let active_item_id = self.items[self.active_item_index].id();
1238 // let is_active_item = target_item_id == active_item_id;
1239 // let target_pane = cx.weak_handle();
1240
1241 // // The `CloseInactiveItems` action should really be called "CloseOthers" and the behaviour should be dynamically based on the tab the action is ran on. Currently, this is a weird action because you can run it on a non-active tab and it will close everything by the actual active tab
1242
1243 // self.tab_context_menu.update(cx, |menu, cx| {
1244 // menu.show(
1245 // position,
1246 // AnchorCorner::TopLeft,
1247 // if is_active_item {
1248 // vec![
1249 // ContextMenuItem::action(
1250 // "Close Active Item",
1251 // CloseActiveItem { save_intent: None },
1252 // ),
1253 // ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1254 // ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1255 // ContextMenuItem::action("Close Items To The Left", CloseItemsToTheLeft),
1256 // ContextMenuItem::action("Close Items To The Right", CloseItemsToTheRight),
1257 // ContextMenuItem::action(
1258 // "Close All Items",
1259 // CloseAllItems { save_intent: None },
1260 // ),
1261 // ]
1262 // } else {
1263 // // In the case of the user right clicking on a non-active tab, for some item-closing commands, we need to provide the id of the tab, for the others, we can reuse the existing command.
1264 // vec![
1265 // ContextMenuItem::handler("Close Inactive Item", {
1266 // let pane = target_pane.clone();
1267 // move |cx| {
1268 // if let Some(pane) = pane.upgrade(cx) {
1269 // pane.update(cx, |pane, cx| {
1270 // pane.close_item_by_id(
1271 // target_item_id,
1272 // SaveIntent::Close,
1273 // cx,
1274 // )
1275 // .detach_and_log_err(cx);
1276 // })
1277 // }
1278 // }
1279 // }),
1280 // ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1281 // ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1282 // ContextMenuItem::handler("Close Items To The Left", {
1283 // let pane = target_pane.clone();
1284 // move |cx| {
1285 // if let Some(pane) = pane.upgrade(cx) {
1286 // pane.update(cx, |pane, cx| {
1287 // pane.close_items_to_the_left_by_id(target_item_id, cx)
1288 // .detach_and_log_err(cx);
1289 // })
1290 // }
1291 // }
1292 // }),
1293 // ContextMenuItem::handler("Close Items To The Right", {
1294 // let pane = target_pane.clone();
1295 // move |cx| {
1296 // if let Some(pane) = pane.upgrade(cx) {
1297 // pane.update(cx, |pane, cx| {
1298 // pane.close_items_to_the_right_by_id(target_item_id, cx)
1299 // .detach_and_log_err(cx);
1300 // })
1301 // }
1302 // }
1303 // }),
1304 // ContextMenuItem::action(
1305 // "Close All Items",
1306 // CloseAllItems { save_intent: None },
1307 // ),
1308 // ]
1309 // },
1310 // cx,
1311 // );
1312 // });
1313 // }
1314
1315 pub fn toolbar(&self) -> &View<Toolbar> {
1316 &self.toolbar
1317 }
1318
1319 pub fn handle_deleted_project_item(
1320 &mut self,
1321 entry_id: ProjectEntryId,
1322 cx: &mut ViewContext<Pane>,
1323 ) -> Option<()> {
1324 let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
1325 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
1326 Some((i, item.id()))
1327 } else {
1328 None
1329 }
1330 })?;
1331
1332 self.remove_item(item_index_to_delete, false, cx);
1333 self.nav_history.remove_item(item_id);
1334
1335 Some(())
1336 }
1337
1338 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1339 let active_item = self
1340 .items
1341 .get(self.active_item_index)
1342 .map(|item| item.as_ref());
1343 self.toolbar.update(cx, |toolbar, cx| {
1344 toolbar.set_active_item(active_item, cx);
1345 });
1346 }
1347
1348 // fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Element<Self> {
1349 // let theme = theme::current(cx).clone();
1350
1351 // let pane = cx.handle().downgrade();
1352 // let autoscroll = if mem::take(&mut self.autoscroll) {
1353 // Some(self.active_item_index)
1354 // } else {
1355 // None
1356 // };
1357
1358 // let pane_active = self.has_focus;
1359
1360 // enum Tabs {}
1361 // let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1362 // for (ix, (item, detail)) in self
1363 // .items
1364 // .iter()
1365 // .cloned()
1366 // .zip(self.tab_details(cx))
1367 // .enumerate()
1368 // {
1369 // let git_status = item
1370 // .project_path(cx)
1371 // .and_then(|path| self.project.read(cx).entry_for_path(&path, cx))
1372 // .and_then(|entry| entry.git_status());
1373
1374 // let detail = if detail == 0 { None } else { Some(detail) };
1375 // let tab_active = ix == self.active_item_index;
1376
1377 // row.add_child({
1378 // enum TabDragReceiver {}
1379 // let mut receiver =
1380 // dragged_item_receiver::<TabDragReceiver, _, _>(self, ix, ix, true, None, cx, {
1381 // let item = item.clone();
1382 // let pane = pane.clone();
1383 // let detail = detail.clone();
1384
1385 // let theme = theme::current(cx).clone();
1386 // let mut tooltip_theme = theme.tooltip.clone();
1387 // tooltip_theme.max_text_width = None;
1388 // let tab_tooltip_text =
1389 // item.tab_tooltip_text(cx).map(|text| text.into_owned());
1390
1391 // let mut tab_style = theme
1392 // .workspace
1393 // .tab_bar
1394 // .tab_style(pane_active, tab_active)
1395 // .clone();
1396 // let should_show_status = settings::get::<ItemSettings>(cx).git_status;
1397 // if should_show_status && git_status != None {
1398 // tab_style.label.text.color = match git_status.unwrap() {
1399 // GitFileStatus::Added => tab_style.git.inserted,
1400 // GitFileStatus::Modified => tab_style.git.modified,
1401 // GitFileStatus::Conflict => tab_style.git.conflict,
1402 // };
1403 // }
1404
1405 // move |mouse_state, cx| {
1406 // let hovered = mouse_state.hovered();
1407
1408 // enum Tab {}
1409 // let mouse_event_handler =
1410 // MouseEventHandler::new::<Tab, _>(ix, cx, |_, cx| {
1411 // Self::render_tab(
1412 // &item,
1413 // pane.clone(),
1414 // ix == 0,
1415 // detail,
1416 // hovered,
1417 // &tab_style,
1418 // cx,
1419 // )
1420 // })
1421 // .on_down(MouseButton::Left, move |_, this, cx| {
1422 // this.activate_item(ix, true, true, cx);
1423 // })
1424 // .on_click(MouseButton::Middle, {
1425 // let item_id = item.id();
1426 // move |_, pane, cx| {
1427 // pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1428 // .detach_and_log_err(cx);
1429 // }
1430 // })
1431 // .on_down(
1432 // MouseButton::Right,
1433 // move |event, pane, cx| {
1434 // pane.deploy_tab_context_menu(event.position, item.id(), cx);
1435 // },
1436 // );
1437
1438 // if let Some(tab_tooltip_text) = tab_tooltip_text {
1439 // mouse_event_handler
1440 // .with_tooltip::<Self>(
1441 // ix,
1442 // tab_tooltip_text,
1443 // None,
1444 // tooltip_theme,
1445 // cx,
1446 // )
1447 // .into_any()
1448 // } else {
1449 // mouse_event_handler.into_any()
1450 // }
1451 // }
1452 // });
1453
1454 // if !pane_active || !tab_active {
1455 // receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1456 // }
1457
1458 // receiver.as_draggable(
1459 // DraggedItem {
1460 // handle: item,
1461 // pane: pane.clone(),
1462 // },
1463 // {
1464 // let theme = theme::current(cx).clone();
1465
1466 // let detail = detail.clone();
1467 // move |_, dragged_item: &DraggedItem, cx: &mut ViewContext<Workspace>| {
1468 // let tab_style = &theme.workspace.tab_bar.dragged_tab;
1469 // Self::render_dragged_tab(
1470 // &dragged_item.handle,
1471 // dragged_item.pane.clone(),
1472 // false,
1473 // detail,
1474 // false,
1475 // &tab_style,
1476 // cx,
1477 // )
1478 // }
1479 // },
1480 // )
1481 // })
1482 // }
1483
1484 // // Use the inactive tab style along with the current pane's active status to decide how to render
1485 // // the filler
1486 // let filler_index = self.items.len();
1487 // let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1488 // enum Filler {}
1489 // row.add_child(
1490 // dragged_item_receiver::<Filler, _, _>(self, 0, filler_index, true, None, cx, |_, _| {
1491 // Empty::new()
1492 // .contained()
1493 // .with_style(filler_style.container)
1494 // .with_border(filler_style.container.border)
1495 // })
1496 // .flex(1., true)
1497 // .into_any_named("filler"),
1498 // );
1499
1500 // row
1501 // }
1502
1503 // fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1504 // let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1505
1506 // let mut tab_descriptions = HashMap::default();
1507 // let mut done = false;
1508 // while !done {
1509 // done = true;
1510
1511 // // Store item indices by their tab description.
1512 // for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1513 // if let Some(description) = item.tab_description(*detail, cx) {
1514 // if *detail == 0
1515 // || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1516 // {
1517 // tab_descriptions
1518 // .entry(description)
1519 // .or_insert(Vec::new())
1520 // .push(ix);
1521 // }
1522 // }
1523 // }
1524
1525 // // If two or more items have the same tab description, increase their level
1526 // // of detail and try again.
1527 // for (_, item_ixs) in tab_descriptions.drain() {
1528 // if item_ixs.len() > 1 {
1529 // done = false;
1530 // for ix in item_ixs {
1531 // tab_details[ix] += 1;
1532 // }
1533 // }
1534 // }
1535 // }
1536
1537 // tab_details
1538 // }
1539
1540 // fn render_tab(
1541 // item: &Box<dyn ItemHandle>,
1542 // pane: WeakView<Pane>,
1543 // first: bool,
1544 // detail: Option<usize>,
1545 // hovered: bool,
1546 // tab_style: &theme::Tab,
1547 // cx: &mut ViewContext<Self>,
1548 // ) -> AnyElement<Self> {
1549 // let title = item.tab_content(detail, &tab_style, cx);
1550 // Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1551 // }
1552
1553 // fn render_dragged_tab(
1554 // item: &Box<dyn ItemHandle>,
1555 // pane: WeakView<Pane>,
1556 // first: bool,
1557 // detail: Option<usize>,
1558 // hovered: bool,
1559 // tab_style: &theme::Tab,
1560 // cx: &mut ViewContext<Workspace>,
1561 // ) -> AnyElement<Workspace> {
1562 // let title = item.dragged_tab_content(detail, &tab_style, cx);
1563 // Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1564 // }
1565
1566 // fn render_tab_with_title<T: View>(
1567 // title: AnyElement<T>,
1568 // item: &Box<dyn ItemHandle>,
1569 // pane: WeakView<Pane>,
1570 // first: bool,
1571 // hovered: bool,
1572 // tab_style: &theme::Tab,
1573 // cx: &mut ViewContext<T>,
1574 // ) -> AnyElement<T> {
1575 // let mut container = tab_style.container.clone();
1576 // if first {
1577 // container.border.left = false;
1578 // }
1579
1580 // let buffer_jewel_element = {
1581 // let diameter = 7.0;
1582 // let icon_color = if item.has_conflict(cx) {
1583 // Some(tab_style.icon_conflict)
1584 // } else if item.is_dirty(cx) {
1585 // Some(tab_style.icon_dirty)
1586 // } else {
1587 // None
1588 // };
1589
1590 // Canvas::new(move |bounds, _, _, cx| {
1591 // if let Some(color) = icon_color {
1592 // let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1593 // cx.scene().push_quad(Quad {
1594 // bounds: square,
1595 // background: Some(color),
1596 // border: Default::default(),
1597 // corner_radii: (diameter / 2.).into(),
1598 // });
1599 // }
1600 // })
1601 // .constrained()
1602 // .with_width(diameter)
1603 // .with_height(diameter)
1604 // .aligned()
1605 // };
1606
1607 // let title_element = title.aligned().contained().with_style(ContainerStyle {
1608 // margin: Margin {
1609 // left: tab_style.spacing,
1610 // right: tab_style.spacing,
1611 // ..Default::default()
1612 // },
1613 // ..Default::default()
1614 // });
1615
1616 // let close_element = if hovered {
1617 // let item_id = item.id();
1618 // enum TabCloseButton {}
1619 // let icon = Svg::new("icons/x.svg");
1620 // MouseEventHandler::new::<TabCloseButton, _>(item_id, cx, |mouse_state, _| {
1621 // if mouse_state.hovered() {
1622 // icon.with_color(tab_style.icon_close_active)
1623 // } else {
1624 // icon.with_color(tab_style.icon_close)
1625 // }
1626 // })
1627 // .with_padding(Padding::uniform(4.))
1628 // .with_cursor_style(CursorStyle::PointingHand)
1629 // .on_click(MouseButton::Left, {
1630 // let pane = pane.clone();
1631 // move |_, _, cx| {
1632 // let pane = pane.clone();
1633 // cx.window_context().defer(move |cx| {
1634 // if let Some(pane) = pane.upgrade(cx) {
1635 // pane.update(cx, |pane, cx| {
1636 // pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1637 // .detach_and_log_err(cx);
1638 // });
1639 // }
1640 // });
1641 // }
1642 // })
1643 // .into_any_named("close-tab-icon")
1644 // .constrained()
1645 // } else {
1646 // Empty::new().constrained()
1647 // }
1648 // .with_width(tab_style.close_icon_width)
1649 // .aligned();
1650
1651 // let close_right = settings::get::<ItemSettings>(cx).close_position.right();
1652
1653 // if close_right {
1654 // Flex::row()
1655 // .with_child(buffer_jewel_element)
1656 // .with_child(title_element)
1657 // .with_child(close_element)
1658 // } else {
1659 // Flex::row()
1660 // .with_child(close_element)
1661 // .with_child(title_element)
1662 // .with_child(buffer_jewel_element)
1663 // }
1664 // .contained()
1665 // .with_style(container)
1666 // .constrained()
1667 // .with_height(tab_style.height)
1668 // .into_any()
1669 // }
1670
1671 // pub fn render_tab_bar_button<
1672 // F1: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
1673 // F2: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
1674 // >(
1675 // index: usize,
1676 // icon: &'static str,
1677 // is_active: bool,
1678 // tooltip: Option<(&'static str, Option<Box<dyn Action>>)>,
1679 // cx: &mut ViewContext<Pane>,
1680 // on_click: F1,
1681 // on_down: F2,
1682 // context_menu: Option<ViewHandle<ContextMenu>>,
1683 // ) -> AnyElement<Pane> {
1684 // enum TabBarButton {}
1685
1686 // let mut button = MouseEventHandler::new::<TabBarButton, _>(index, cx, |mouse_state, cx| {
1687 // let theme = &settings2::get::<ThemeSettings>(cx).theme.workspace.tab_bar;
1688 // let style = theme.pane_button.in_state(is_active).style_for(mouse_state);
1689 // Svg::new(icon)
1690 // .with_color(style.color)
1691 // .constrained()
1692 // .with_width(style.icon_width)
1693 // .aligned()
1694 // .constrained()
1695 // .with_width(style.button_width)
1696 // .with_height(style.button_width)
1697 // })
1698 // .with_cursor_style(CursorStyle::PointingHand)
1699 // .on_down(MouseButton::Left, move |_, pane, cx| on_down(pane, cx))
1700 // .on_click(MouseButton::Left, move |_, pane, cx| on_click(pane, cx))
1701 // .into_any();
1702 // if let Some((tooltip, action)) = tooltip {
1703 // let tooltip_style = settings::get::<ThemeSettings>(cx).theme.tooltip.clone();
1704 // button = button
1705 // .with_tooltip::<TabBarButton>(index, tooltip, action, tooltip_style, cx)
1706 // .into_any();
1707 // }
1708
1709 // Stack::new()
1710 // .with_child(button)
1711 // .with_children(
1712 // context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),
1713 // )
1714 // .flex(1., false)
1715 // .into_any_named("tab bar button")
1716 // }
1717
1718 // fn render_blank_pane(&self, theme: &Theme, _cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1719 // let background = theme.workspace.background;
1720 // Empty::new()
1721 // .contained()
1722 // .with_background_color(background)
1723 // .into_any()
1724 // }
1725
1726 // pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1727 // self.zoomed = zoomed;
1728 // cx.notify();
1729 // }
1730
1731 // pub fn is_zoomed(&self) -> bool {
1732 // self.zoomed
1733 // }
1734}
1735
1736// impl Entity for Pane {
1737// type Event = Event;
1738// }
1739
1740// impl View for Pane {
1741// fn ui_name() -> &'static str {
1742// "Pane"
1743// }
1744
1745// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1746// enum MouseNavigationHandler {}
1747
1748// MouseEventHandler::new::<MouseNavigationHandler, _>(0, cx, |_, cx| {
1749// let active_item_index = self.active_item_index;
1750
1751// if let Some(active_item) = self.active_item() {
1752// Flex::column()
1753// .with_child({
1754// let theme = theme::current(cx).clone();
1755
1756// let mut stack = Stack::new();
1757
1758// enum TabBarEventHandler {}
1759// stack.add_child(
1760// MouseEventHandler::new::<TabBarEventHandler, _>(0, cx, |_, _| {
1761// Empty::new()
1762// .contained()
1763// .with_style(theme.workspace.tab_bar.container)
1764// })
1765// .on_down(
1766// MouseButton::Left,
1767// move |_, this, cx| {
1768// this.activate_item(active_item_index, true, true, cx);
1769// },
1770// ),
1771// );
1772// let tooltip_style = theme.tooltip.clone();
1773// let tab_bar_theme = theme.workspace.tab_bar.clone();
1774
1775// let nav_button_height = tab_bar_theme.height;
1776// let button_style = tab_bar_theme.nav_button;
1777// let border_for_nav_buttons = tab_bar_theme
1778// .tab_style(false, false)
1779// .container
1780// .border
1781// .clone();
1782
1783// let mut tab_row = Flex::row()
1784// .with_child(nav_button(
1785// "icons/arrow_left.svg",
1786// button_style.clone(),
1787// nav_button_height,
1788// tooltip_style.clone(),
1789// self.can_navigate_backward(),
1790// {
1791// move |pane, cx| {
1792// if let Some(workspace) = pane.workspace.upgrade(cx) {
1793// let pane = cx.weak_handle();
1794// cx.window_context().defer(move |cx| {
1795// workspace.update(cx, |workspace, cx| {
1796// workspace
1797// .go_back(pane, cx)
1798// .detach_and_log_err(cx)
1799// })
1800// })
1801// }
1802// }
1803// },
1804// super::GoBack,
1805// "Go Back",
1806// cx,
1807// ))
1808// .with_child(
1809// nav_button(
1810// "icons/arrow_right.svg",
1811// button_style.clone(),
1812// nav_button_height,
1813// tooltip_style,
1814// self.can_navigate_forward(),
1815// {
1816// move |pane, cx| {
1817// if let Some(workspace) = pane.workspace.upgrade(cx) {
1818// let pane = cx.weak_handle();
1819// cx.window_context().defer(move |cx| {
1820// workspace.update(cx, |workspace, cx| {
1821// workspace
1822// .go_forward(pane, cx)
1823// .detach_and_log_err(cx)
1824// })
1825// })
1826// }
1827// }
1828// },
1829// super::GoForward,
1830// "Go Forward",
1831// cx,
1832// )
1833// .contained()
1834// .with_border(border_for_nav_buttons),
1835// )
1836// .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
1837
1838// if self.has_focus {
1839// let render_tab_bar_buttons = self.render_tab_bar_buttons.clone();
1840// tab_row.add_child(
1841// (render_tab_bar_buttons)(self, cx)
1842// .contained()
1843// .with_style(theme.workspace.tab_bar.pane_button_container)
1844// .flex(1., false)
1845// .into_any(),
1846// )
1847// }
1848
1849// stack.add_child(tab_row);
1850// stack
1851// .constrained()
1852// .with_height(theme.workspace.tab_bar.height)
1853// .flex(1., false)
1854// .into_any_named("tab bar")
1855// })
1856// .with_child({
1857// enum PaneContentTabDropTarget {}
1858// dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
1859// self,
1860// 0,
1861// self.active_item_index + 1,
1862// !self.can_split,
1863// if self.can_split { Some(100.) } else { None },
1864// cx,
1865// {
1866// let toolbar = self.toolbar.clone();
1867// let toolbar_hidden = toolbar.read(cx).hidden();
1868// move |_, cx| {
1869// Flex::column()
1870// .with_children(
1871// (!toolbar_hidden)
1872// .then(|| ChildView::new(&toolbar, cx).expanded()),
1873// )
1874// .with_child(
1875// ChildView::new(active_item.as_any(), cx).flex(1., true),
1876// )
1877// }
1878// },
1879// )
1880// .flex(1., true)
1881// })
1882// .with_child(ChildView::new(&self.tab_context_menu, cx))
1883// .into_any()
1884// } else {
1885// enum EmptyPane {}
1886// let theme = theme::current(cx).clone();
1887
1888// dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {
1889// self.render_blank_pane(&theme, cx)
1890// })
1891// .on_down(MouseButton::Left, |_, _, cx| {
1892// cx.focus_parent();
1893// })
1894// .into_any()
1895// }
1896// })
1897// .on_down(
1898// MouseButton::Navigate(NavigationDirection::Back),
1899// move |_, pane, cx| {
1900// if let Some(workspace) = pane.workspace.upgrade(cx) {
1901// let pane = cx.weak_handle();
1902// cx.window_context().defer(move |cx| {
1903// workspace.update(cx, |workspace, cx| {
1904// workspace.go_back(pane, cx).detach_and_log_err(cx)
1905// })
1906// })
1907// }
1908// },
1909// )
1910// .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1911// move |_, pane, cx| {
1912// if let Some(workspace) = pane.workspace.upgrade(cx) {
1913// let pane = cx.weak_handle();
1914// cx.window_context().defer(move |cx| {
1915// workspace.update(cx, |workspace, cx| {
1916// workspace.go_forward(pane, cx).detach_and_log_err(cx)
1917// })
1918// })
1919// }
1920// }
1921// })
1922// .into_any_named("pane")
1923// }
1924
1925// fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1926// if !self.has_focus {
1927// self.has_focus = true;
1928// cx.emit(Event::Focus);
1929// cx.notify();
1930// }
1931
1932// self.toolbar.update(cx, |toolbar, cx| {
1933// toolbar.focus_changed(true, cx);
1934// });
1935
1936// if let Some(active_item) = self.active_item() {
1937// if cx.is_self_focused() {
1938// // Pane was focused directly. We need to either focus a view inside the active item,
1939// // or focus the active item itself
1940// if let Some(weak_last_focused_view) =
1941// self.last_focused_view_by_item.get(&active_item.id())
1942// {
1943// if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1944// cx.focus(&last_focused_view);
1945// return;
1946// } else {
1947// self.last_focused_view_by_item.remove(&active_item.id());
1948// }
1949// }
1950
1951// cx.focus(active_item.as_any());
1952// } else if focused != self.tab_bar_context_menu.handle {
1953// self.last_focused_view_by_item
1954// .insert(active_item.id(), focused.downgrade());
1955// }
1956// }
1957// }
1958
1959// fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1960// self.has_focus = false;
1961// self.toolbar.update(cx, |toolbar, cx| {
1962// toolbar.focus_changed(false, cx);
1963// });
1964// cx.notify();
1965// }
1966
1967// fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
1968// Self::reset_to_default_keymap_context(keymap);
1969// }
1970// }
1971
1972impl ItemNavHistory {
1973 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
1974 self.history.push(data, self.item.clone(), cx);
1975 }
1976
1977 pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1978 self.history.pop(NavigationMode::GoingBack, cx)
1979 }
1980
1981 pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
1982 self.history.pop(NavigationMode::GoingForward, cx)
1983 }
1984}
1985
1986impl NavHistory {
1987 pub fn for_each_entry(
1988 &self,
1989 cx: &AppContext,
1990 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
1991 ) {
1992 let borrowed_history = self.0.lock();
1993 borrowed_history
1994 .forward_stack
1995 .iter()
1996 .chain(borrowed_history.backward_stack.iter())
1997 .chain(borrowed_history.closed_stack.iter())
1998 .for_each(|entry| {
1999 if let Some(project_and_abs_path) =
2000 borrowed_history.paths_by_item.get(&entry.item.id())
2001 {
2002 f(entry, project_and_abs_path.clone());
2003 } else if let Some(item) = entry.item.upgrade() {
2004 if let Some(path) = item.project_path(cx) {
2005 f(entry, (path, None));
2006 }
2007 }
2008 })
2009 }
2010
2011 pub fn set_mode(&mut self, mode: NavigationMode) {
2012 self.0.lock().mode = mode;
2013 }
2014
2015 pub fn mode(&self) -> NavigationMode {
2016 self.0.lock().mode
2017 }
2018
2019 pub fn disable(&mut self) {
2020 self.0.lock().mode = NavigationMode::Disabled;
2021 }
2022
2023 pub fn enable(&mut self) {
2024 self.0.lock().mode = NavigationMode::Normal;
2025 }
2026
2027 pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2028 let mut state = self.0.lock();
2029 let entry = match mode {
2030 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2031 return None
2032 }
2033 NavigationMode::GoingBack => &mut state.backward_stack,
2034 NavigationMode::GoingForward => &mut state.forward_stack,
2035 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2036 }
2037 .pop_back();
2038 if entry.is_some() {
2039 state.did_update(cx);
2040 }
2041 entry
2042 }
2043
2044 pub fn push<D: 'static + Send + Any>(
2045 &mut self,
2046 data: Option<D>,
2047 item: Arc<dyn WeakItemHandle>,
2048 cx: &mut WindowContext,
2049 ) {
2050 let state = &mut *self.0.lock();
2051 match state.mode {
2052 NavigationMode::Disabled => {}
2053 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2054 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2055 state.backward_stack.pop_front();
2056 }
2057 state.backward_stack.push_back(NavigationEntry {
2058 item,
2059 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2060 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2061 });
2062 state.forward_stack.clear();
2063 }
2064 NavigationMode::GoingBack => {
2065 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2066 state.forward_stack.pop_front();
2067 }
2068 state.forward_stack.push_back(NavigationEntry {
2069 item,
2070 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2071 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2072 });
2073 }
2074 NavigationMode::GoingForward => {
2075 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2076 state.backward_stack.pop_front();
2077 }
2078 state.backward_stack.push_back(NavigationEntry {
2079 item,
2080 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2081 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2082 });
2083 }
2084 NavigationMode::ClosingItem => {
2085 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2086 state.closed_stack.pop_front();
2087 }
2088 state.closed_stack.push_back(NavigationEntry {
2089 item,
2090 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2091 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2092 });
2093 }
2094 }
2095 state.did_update(cx);
2096 }
2097
2098 pub fn remove_item(&mut self, item_id: EntityId) {
2099 let mut state = self.0.lock();
2100 state.paths_by_item.remove(&item_id);
2101 state
2102 .backward_stack
2103 .retain(|entry| entry.item.id() != item_id);
2104 state
2105 .forward_stack
2106 .retain(|entry| entry.item.id() != item_id);
2107 state
2108 .closed_stack
2109 .retain(|entry| entry.item.id() != item_id);
2110 }
2111
2112 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2113 self.0.lock().paths_by_item.get(&item_id).cloned()
2114 }
2115}
2116
2117impl NavHistoryState {
2118 pub fn did_update(&self, cx: &mut WindowContext) {
2119 if let Some(pane) = self.pane.upgrade() {
2120 cx.defer(move |cx| {
2121 pane.update(cx, |pane, cx| pane.history_updated(cx));
2122 });
2123 }
2124 }
2125}
2126
2127// pub struct PaneBackdrop<V> {
2128// child_view: usize,
2129// child: AnyElement<V>,
2130// }
2131
2132// impl<V> PaneBackdrop<V> {
2133// pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2134// PaneBackdrop {
2135// child,
2136// child_view: pane_item_view,
2137// }
2138// }
2139// }
2140
2141// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2142// type LayoutState = ();
2143
2144// type PaintState = ();
2145
2146// fn layout(
2147// &mut self,
2148// constraint: gpui::SizeConstraint,
2149// view: &mut V,
2150// cx: &mut ViewContext<V>,
2151// ) -> (Vector2F, Self::LayoutState) {
2152// let size = self.child.layout(constraint, view, cx);
2153// (size, ())
2154// }
2155
2156// fn paint(
2157// &mut self,
2158// bounds: RectF,
2159// visible_bounds: RectF,
2160// _: &mut Self::LayoutState,
2161// view: &mut V,
2162// cx: &mut ViewContext<V>,
2163// ) -> Self::PaintState {
2164// let background = theme::current(cx).editor.background;
2165
2166// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2167
2168// cx.scene().push_quad(gpui::Quad {
2169// bounds: RectF::new(bounds.origin(), bounds.size()),
2170// background: Some(background),
2171// ..Default::default()
2172// });
2173
2174// let child_view_id = self.child_view;
2175// cx.scene().push_mouse_region(
2176// MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2177// gpui::platform::MouseButton::Left,
2178// move |_, _: &mut V, cx| {
2179// let window = cx.window();
2180// cx.app_context().focus(window, Some(child_view_id))
2181// },
2182// ),
2183// );
2184
2185// cx.scene().push_layer(Some(bounds));
2186// self.child.paint(bounds.origin(), visible_bounds, view, cx);
2187// cx.scene().pop_layer();
2188// }
2189
2190// fn rect_for_text_range(
2191// &self,
2192// range_utf16: std::ops::Range<usize>,
2193// _bounds: RectF,
2194// _visible_bounds: RectF,
2195// _layout: &Self::LayoutState,
2196// _paint: &Self::PaintState,
2197// view: &V,
2198// cx: &gpui::ViewContext<V>,
2199// ) -> Option<RectF> {
2200// self.child.rect_for_text_range(range_utf16, view, cx)
2201// }
2202
2203// fn debug(
2204// &self,
2205// _bounds: RectF,
2206// _layout: &Self::LayoutState,
2207// _paint: &Self::PaintState,
2208// view: &V,
2209// cx: &gpui::ViewContext<V>,
2210// ) -> serde_json::Value {
2211// gpui::json::json!({
2212// "type": "Pane Back Drop",
2213// "view": self.child_view,
2214// "child": self.child.debug(view, cx),
2215// })
2216// }
2217// }
2218
2219fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2220 let path = buffer_path
2221 .as_ref()
2222 .and_then(|p| p.path.to_str())
2223 .unwrap_or(&"This buffer");
2224 let path = truncate_and_remove_front(path, 80);
2225 format!("{path} contains unsaved edits. Do you want to save it?")
2226}
2227
2228// todo!("uncomment tests")
2229// #[cfg(test)]
2230// mod tests {
2231// use super::*;
2232// use crate::item::test::{TestItem, TestProjectItem};
2233// use gpui::TestAppContext;
2234// use project::FakeFs;
2235// use settings::SettingsStore;
2236
2237// #[gpui::test]
2238// async fn test_remove_active_empty(cx: &mut TestAppContext) {
2239// init_test(cx);
2240// let fs = FakeFs::new(cx.background());
2241
2242// let project = Project::test(fs, None, cx).await;
2243// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2244// let workspace = window.root(cx);
2245// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2246
2247// pane.update(cx, |pane, cx| {
2248// assert!(pane
2249// .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2250// .is_none())
2251// });
2252// }
2253
2254// #[gpui::test]
2255// async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2256// cx.foreground().forbid_parking();
2257// init_test(cx);
2258// let fs = FakeFs::new(cx.background());
2259
2260// let project = Project::test(fs, None, cx).await;
2261// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2262// let workspace = window.root(cx);
2263// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2264
2265// // 1. Add with a destination index
2266// // a. Add before the active item
2267// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2268// pane.update(cx, |pane, cx| {
2269// pane.add_item(
2270// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2271// false,
2272// false,
2273// Some(0),
2274// cx,
2275// );
2276// });
2277// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2278
2279// // b. Add after the active item
2280// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2281// pane.update(cx, |pane, cx| {
2282// pane.add_item(
2283// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2284// false,
2285// false,
2286// Some(2),
2287// cx,
2288// );
2289// });
2290// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2291
2292// // c. Add at the end of the item list (including off the length)
2293// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2294// pane.update(cx, |pane, cx| {
2295// pane.add_item(
2296// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2297// false,
2298// false,
2299// Some(5),
2300// cx,
2301// );
2302// });
2303// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2304
2305// // 2. Add without a destination index
2306// // a. Add with active item at the start of the item list
2307// set_labeled_items(&pane, ["A*", "B", "C"], cx);
2308// pane.update(cx, |pane, cx| {
2309// pane.add_item(
2310// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2311// false,
2312// false,
2313// None,
2314// cx,
2315// );
2316// });
2317// set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2318
2319// // b. Add with active item at the end of the item list
2320// set_labeled_items(&pane, ["A", "B", "C*"], cx);
2321// pane.update(cx, |pane, cx| {
2322// pane.add_item(
2323// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2324// false,
2325// false,
2326// None,
2327// cx,
2328// );
2329// });
2330// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2331// }
2332
2333// #[gpui::test]
2334// async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2335// cx.foreground().forbid_parking();
2336// init_test(cx);
2337// let fs = FakeFs::new(cx.background());
2338
2339// let project = Project::test(fs, None, cx).await;
2340// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2341// let workspace = window.root(cx);
2342// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2343
2344// // 1. Add with a destination index
2345// // 1a. Add before the active item
2346// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2347// pane.update(cx, |pane, cx| {
2348// pane.add_item(d, false, false, Some(0), cx);
2349// });
2350// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2351
2352// // 1b. Add after the active item
2353// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2354// pane.update(cx, |pane, cx| {
2355// pane.add_item(d, false, false, Some(2), cx);
2356// });
2357// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2358
2359// // 1c. Add at the end of the item list (including off the length)
2360// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2361// pane.update(cx, |pane, cx| {
2362// pane.add_item(a, false, false, Some(5), cx);
2363// });
2364// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2365
2366// // 1d. Add same item to active index
2367// let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2368// pane.update(cx, |pane, cx| {
2369// pane.add_item(b, false, false, Some(1), cx);
2370// });
2371// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2372
2373// // 1e. Add item to index after same item in last position
2374// let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2375// pane.update(cx, |pane, cx| {
2376// pane.add_item(c, false, false, Some(2), cx);
2377// });
2378// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2379
2380// // 2. Add without a destination index
2381// // 2a. Add with active item at the start of the item list
2382// let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2383// pane.update(cx, |pane, cx| {
2384// pane.add_item(d, false, false, None, cx);
2385// });
2386// assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2387
2388// // 2b. Add with active item at the end of the item list
2389// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2390// pane.update(cx, |pane, cx| {
2391// pane.add_item(a, false, false, None, cx);
2392// });
2393// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2394
2395// // 2c. Add active item to active item at end of list
2396// let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2397// pane.update(cx, |pane, cx| {
2398// pane.add_item(c, false, false, None, cx);
2399// });
2400// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2401
2402// // 2d. Add active item to active item at start of list
2403// let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2404// pane.update(cx, |pane, cx| {
2405// pane.add_item(a, false, false, None, cx);
2406// });
2407// assert_item_labels(&pane, ["A*", "B", "C"], cx);
2408// }
2409
2410// #[gpui::test]
2411// async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2412// cx.foreground().forbid_parking();
2413// init_test(cx);
2414// let fs = FakeFs::new(cx.background());
2415
2416// let project = Project::test(fs, None, cx).await;
2417// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2418// let workspace = window.root(cx);
2419// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2420
2421// // singleton view
2422// pane.update(cx, |pane, cx| {
2423// let item = TestItem::new()
2424// .with_singleton(true)
2425// .with_label("buffer 1")
2426// .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2427
2428// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2429// });
2430// assert_item_labels(&pane, ["buffer 1*"], cx);
2431
2432// // new singleton view with the same project entry
2433// pane.update(cx, |pane, cx| {
2434// let item = TestItem::new()
2435// .with_singleton(true)
2436// .with_label("buffer 1")
2437// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2438
2439// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2440// });
2441// assert_item_labels(&pane, ["buffer 1*"], cx);
2442
2443// // new singleton view with different project entry
2444// pane.update(cx, |pane, cx| {
2445// let item = TestItem::new()
2446// .with_singleton(true)
2447// .with_label("buffer 2")
2448// .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2449// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2450// });
2451// assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2452
2453// // new multibuffer view with the same project entry
2454// pane.update(cx, |pane, cx| {
2455// let item = TestItem::new()
2456// .with_singleton(false)
2457// .with_label("multibuffer 1")
2458// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2459
2460// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2461// });
2462// assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2463
2464// // another multibuffer view with the same project entry
2465// pane.update(cx, |pane, cx| {
2466// let item = TestItem::new()
2467// .with_singleton(false)
2468// .with_label("multibuffer 1b")
2469// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2470
2471// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2472// });
2473// assert_item_labels(
2474// &pane,
2475// ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2476// cx,
2477// );
2478// }
2479
2480// #[gpui::test]
2481// async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2482// init_test(cx);
2483// let fs = FakeFs::new(cx.background());
2484
2485// let project = Project::test(fs, None, cx).await;
2486// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2487// let workspace = window.root(cx);
2488// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2489
2490// add_labeled_item(&pane, "A", false, cx);
2491// add_labeled_item(&pane, "B", false, cx);
2492// add_labeled_item(&pane, "C", false, cx);
2493// add_labeled_item(&pane, "D", false, cx);
2494// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2495
2496// pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2497// add_labeled_item(&pane, "1", false, cx);
2498// assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2499
2500// pane.update(cx, |pane, cx| {
2501// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2502// })
2503// .unwrap()
2504// .await
2505// .unwrap();
2506// assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2507
2508// pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2509// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2510
2511// pane.update(cx, |pane, cx| {
2512// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2513// })
2514// .unwrap()
2515// .await
2516// .unwrap();
2517// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2518
2519// pane.update(cx, |pane, cx| {
2520// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2521// })
2522// .unwrap()
2523// .await
2524// .unwrap();
2525// assert_item_labels(&pane, ["A", "C*"], cx);
2526
2527// pane.update(cx, |pane, cx| {
2528// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2529// })
2530// .unwrap()
2531// .await
2532// .unwrap();
2533// assert_item_labels(&pane, ["A*"], cx);
2534// }
2535
2536// #[gpui::test]
2537// async fn test_close_inactive_items(cx: &mut TestAppContext) {
2538// init_test(cx);
2539// let fs = FakeFs::new(cx.background());
2540
2541// let project = Project::test(fs, None, cx).await;
2542// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2543// let workspace = window.root(cx);
2544// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2545
2546// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2547
2548// pane.update(cx, |pane, cx| {
2549// pane.close_inactive_items(&CloseInactiveItems, cx)
2550// })
2551// .unwrap()
2552// .await
2553// .unwrap();
2554// assert_item_labels(&pane, ["C*"], cx);
2555// }
2556
2557// #[gpui::test]
2558// async fn test_close_clean_items(cx: &mut TestAppContext) {
2559// init_test(cx);
2560// let fs = FakeFs::new(cx.background());
2561
2562// let project = Project::test(fs, None, cx).await;
2563// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2564// let workspace = window.root(cx);
2565// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2566
2567// add_labeled_item(&pane, "A", true, cx);
2568// add_labeled_item(&pane, "B", false, cx);
2569// add_labeled_item(&pane, "C", true, cx);
2570// add_labeled_item(&pane, "D", false, cx);
2571// add_labeled_item(&pane, "E", false, cx);
2572// assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2573
2574// pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2575// .unwrap()
2576// .await
2577// .unwrap();
2578// assert_item_labels(&pane, ["A^", "C*^"], cx);
2579// }
2580
2581// #[gpui::test]
2582// async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2583// init_test(cx);
2584// let fs = FakeFs::new(cx.background());
2585
2586// let project = Project::test(fs, None, cx).await;
2587// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2588// let workspace = window.root(cx);
2589// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2590
2591// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2592
2593// pane.update(cx, |pane, cx| {
2594// pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2595// })
2596// .unwrap()
2597// .await
2598// .unwrap();
2599// assert_item_labels(&pane, ["C*", "D", "E"], cx);
2600// }
2601
2602// #[gpui::test]
2603// async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2604// init_test(cx);
2605// let fs = FakeFs::new(cx.background());
2606
2607// let project = Project::test(fs, None, cx).await;
2608// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2609// let workspace = window.root(cx);
2610// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2611
2612// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2613
2614// pane.update(cx, |pane, cx| {
2615// pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2616// })
2617// .unwrap()
2618// .await
2619// .unwrap();
2620// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2621// }
2622
2623// #[gpui::test]
2624// async fn test_close_all_items(cx: &mut TestAppContext) {
2625// init_test(cx);
2626// let fs = FakeFs::new(cx.background());
2627
2628// let project = Project::test(fs, None, cx).await;
2629// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2630// let workspace = window.root(cx);
2631// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2632
2633// add_labeled_item(&pane, "A", false, cx);
2634// add_labeled_item(&pane, "B", false, cx);
2635// add_labeled_item(&pane, "C", false, cx);
2636// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2637
2638// pane.update(cx, |pane, cx| {
2639// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2640// })
2641// .unwrap()
2642// .await
2643// .unwrap();
2644// assert_item_labels(&pane, [], cx);
2645
2646// add_labeled_item(&pane, "A", true, cx);
2647// add_labeled_item(&pane, "B", true, cx);
2648// add_labeled_item(&pane, "C", true, cx);
2649// assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2650
2651// let save = pane
2652// .update(cx, |pane, cx| {
2653// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2654// })
2655// .unwrap();
2656
2657// cx.foreground().run_until_parked();
2658// window.simulate_prompt_answer(2, cx);
2659// save.await.unwrap();
2660// assert_item_labels(&pane, [], cx);
2661// }
2662
2663// fn init_test(cx: &mut TestAppContext) {
2664// cx.update(|cx| {
2665// cx.set_global(SettingsStore::test(cx));
2666// theme::init((), cx);
2667// crate::init_settings(cx);
2668// Project::init_settings(cx);
2669// });
2670// }
2671
2672// fn add_labeled_item(
2673// pane: &ViewHandle<Pane>,
2674// label: &str,
2675// is_dirty: bool,
2676// cx: &mut TestAppContext,
2677// ) -> Box<ViewHandle<TestItem>> {
2678// pane.update(cx, |pane, cx| {
2679// let labeled_item =
2680// Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2681// pane.add_item(labeled_item.clone(), false, false, None, cx);
2682// labeled_item
2683// })
2684// }
2685
2686// fn set_labeled_items<const COUNT: usize>(
2687// pane: &ViewHandle<Pane>,
2688// labels: [&str; COUNT],
2689// cx: &mut TestAppContext,
2690// ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2691// pane.update(cx, |pane, cx| {
2692// pane.items.clear();
2693// let mut active_item_index = 0;
2694
2695// let mut index = 0;
2696// let items = labels.map(|mut label| {
2697// if label.ends_with("*") {
2698// label = label.trim_end_matches("*");
2699// active_item_index = index;
2700// }
2701
2702// let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2703// pane.add_item(labeled_item.clone(), false, false, None, cx);
2704// index += 1;
2705// labeled_item
2706// });
2707
2708// pane.activate_item(active_item_index, false, false, cx);
2709
2710// items
2711// })
2712// }
2713
2714// // Assert the item label, with the active item label suffixed with a '*'
2715// fn assert_item_labels<const COUNT: usize>(
2716// pane: &ViewHandle<Pane>,
2717// expected_states: [&str; COUNT],
2718// cx: &mut TestAppContext,
2719// ) {
2720// pane.read_with(cx, |pane, cx| {
2721// let actual_states = pane
2722// .items
2723// .iter()
2724// .enumerate()
2725// .map(|(ix, item)| {
2726// let mut state = item
2727// .as_any()
2728// .downcast_ref::<TestItem>()
2729// .unwrap()
2730// .read(cx)
2731// .label
2732// .clone();
2733// if ix == pane.active_item_index {
2734// state.push('*');
2735// }
2736// if item.is_dirty(cx) {
2737// state.push('^');
2738// }
2739// state
2740// })
2741// .collect::<Vec<_>>();
2742
2743// assert_eq!(
2744// actual_states, expected_states,
2745// "pane items do not match expectation"
2746// );
2747// })
2748// }
2749// }