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