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, FocusableView, Model, PromptLevel, Render, Task, View,
12 ViewContext, 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, Tooltip};
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| Tooltip::new(text.clone())).into())
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 FocusableView for Pane {
1903 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1904 self.focus_handle.clone()
1905 }
1906}
1907
1908impl Render for Pane {
1909 type Element = Focusable<Self, Div<Self>>;
1910
1911 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1912 v_stack()
1913 .key_context("Pane")
1914 .track_focus(&self.focus_handle)
1915 .on_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx))
1916 .on_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx))
1917 .on_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx))
1918 .on_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx))
1919 .size_full()
1920 .on_action(|pane: &mut Self, action, cx| {
1921 pane.close_active_item(action, cx)
1922 .map(|task| task.detach_and_log_err(cx));
1923 })
1924 .child(self.render_tab_bar(cx))
1925 .child(div() /* todo!(toolbar) */)
1926 .child(if let Some(item) = self.active_item() {
1927 div().flex_1().child(item.to_any())
1928 } else {
1929 // todo!()
1930 div().child("Empty Pane")
1931 })
1932
1933 // enum MouseNavigationHandler {}
1934
1935 // MouseEventHandler::new::<MouseNavigationHandler, _>(0, cx, |_, cx| {
1936 // let active_item_index = self.active_item_index;
1937
1938 // if let Some(active_item) = self.active_item() {
1939 // Flex::column()
1940 // .with_child({
1941 // let theme = theme::current(cx).clone();
1942
1943 // let mut stack = Stack::new();
1944
1945 // enum TabBarEventHandler {}
1946 // stack.add_child(
1947 // MouseEventHandler::new::<TabBarEventHandler, _>(0, cx, |_, _| {
1948 // Empty::new()
1949 // .contained()
1950 // .with_style(theme.workspace.tab_bar.container)
1951 // })
1952 // .on_down(
1953 // MouseButton::Left,
1954 // move |_, this, cx| {
1955 // this.activate_item(active_item_index, true, true, cx);
1956 // },
1957 // ),
1958 // );
1959 // let tooltip_style = theme.tooltip.clone();
1960 // let tab_bar_theme = theme.workspace.tab_bar.clone();
1961
1962 // let nav_button_height = tab_bar_theme.height;
1963 // let button_style = tab_bar_theme.nav_button;
1964 // let border_for_nav_buttons = tab_bar_theme
1965 // .tab_style(false, false)
1966 // .container
1967 // .border
1968 // .clone();
1969
1970 // let mut tab_row = Flex::row()
1971 // .with_child(nav_button(
1972 // "icons/arrow_left.svg",
1973 // button_style.clone(),
1974 // nav_button_height,
1975 // tooltip_style.clone(),
1976 // self.can_navigate_backward(),
1977 // {
1978 // move |pane, cx| {
1979 // if let Some(workspace) = pane.workspace.upgrade(cx) {
1980 // let pane = cx.weak_handle();
1981 // cx.window_context().defer(move |cx| {
1982 // workspace.update(cx, |workspace, cx| {
1983 // workspace
1984 // .go_back(pane, cx)
1985 // .detach_and_log_err(cx)
1986 // })
1987 // })
1988 // }
1989 // }
1990 // },
1991 // super::GoBack,
1992 // "Go Back",
1993 // cx,
1994 // ))
1995 // .with_child(
1996 // nav_button(
1997 // "icons/arrow_right.svg",
1998 // button_style.clone(),
1999 // nav_button_height,
2000 // tooltip_style,
2001 // self.can_navigate_forward(),
2002 // {
2003 // move |pane, cx| {
2004 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2005 // let pane = cx.weak_handle();
2006 // cx.window_context().defer(move |cx| {
2007 // workspace.update(cx, |workspace, cx| {
2008 // workspace
2009 // .go_forward(pane, cx)
2010 // .detach_and_log_err(cx)
2011 // })
2012 // })
2013 // }
2014 // }
2015 // },
2016 // super::GoForward,
2017 // "Go Forward",
2018 // cx,
2019 // )
2020 // .contained()
2021 // .with_border(border_for_nav_buttons),
2022 // )
2023 // .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
2024
2025 // if self.has_focus {
2026 // let render_tab_bar_buttons = self.render_tab_bar_buttons.clone();
2027 // tab_row.add_child(
2028 // (render_tab_bar_buttons)(self, cx)
2029 // .contained()
2030 // .with_style(theme.workspace.tab_bar.pane_button_container)
2031 // .flex(1., false)
2032 // .into_any(),
2033 // )
2034 // }
2035
2036 // stack.add_child(tab_row);
2037 // stack
2038 // .constrained()
2039 // .with_height(theme.workspace.tab_bar.height)
2040 // .flex(1., false)
2041 // .into_any_named("tab bar")
2042 // })
2043 // .with_child({
2044 // enum PaneContentTabDropTarget {}
2045 // dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
2046 // self,
2047 // 0,
2048 // self.active_item_index + 1,
2049 // !self.can_split,
2050 // if self.can_split { Some(100.) } else { None },
2051 // cx,
2052 // {
2053 // let toolbar = self.toolbar.clone();
2054 // let toolbar_hidden = toolbar.read(cx).hidden();
2055 // move |_, cx| {
2056 // Flex::column()
2057 // .with_children(
2058 // (!toolbar_hidden)
2059 // .then(|| ChildView::new(&toolbar, cx).expanded()),
2060 // )
2061 // .with_child(
2062 // ChildView::new(active_item.as_any(), cx).flex(1., true),
2063 // )
2064 // }
2065 // },
2066 // )
2067 // .flex(1., true)
2068 // })
2069 // .with_child(ChildView::new(&self.tab_context_menu, cx))
2070 // .into_any()
2071 // } else {
2072 // enum EmptyPane {}
2073 // let theme = theme::current(cx).clone();
2074
2075 // dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {
2076 // self.render_blank_pane(&theme, cx)
2077 // })
2078 // .on_down(MouseButton::Left, |_, _, cx| {
2079 // cx.focus_parent();
2080 // })
2081 // .into_any()
2082 // }
2083 // })
2084 // .on_down(
2085 // MouseButton::Navigate(NavigationDirection::Back),
2086 // move |_, pane, cx| {
2087 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2088 // let pane = cx.weak_handle();
2089 // cx.window_context().defer(move |cx| {
2090 // workspace.update(cx, |workspace, cx| {
2091 // workspace.go_back(pane, cx).detach_and_log_err(cx)
2092 // })
2093 // })
2094 // }
2095 // },
2096 // )
2097 // .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
2098 // move |_, pane, cx| {
2099 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2100 // let pane = cx.weak_handle();
2101 // cx.window_context().defer(move |cx| {
2102 // workspace.update(cx, |workspace, cx| {
2103 // workspace.go_forward(pane, cx).detach_and_log_err(cx)
2104 // })
2105 // })
2106 // }
2107 // }
2108 // })
2109 // .into_any_named("pane")
2110 }
2111
2112 // fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
2113 // if !self.has_focus {
2114 // self.has_focus = true;
2115 // cx.emit(Event::Focus);
2116 // cx.notify();
2117 // }
2118
2119 // self.toolbar.update(cx, |toolbar, cx| {
2120 // toolbar.focus_changed(true, cx);
2121 // });
2122
2123 // if let Some(active_item) = self.active_item() {
2124 // if cx.is_self_focused() {
2125 // // Pane was focused directly. We need to either focus a view inside the active item,
2126 // // or focus the active item itself
2127 // if let Some(weak_last_focused_view) =
2128 // self.last_focused_view_by_item.get(&active_item.id())
2129 // {
2130 // if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
2131 // cx.focus(&last_focused_view);
2132 // return;
2133 // } else {
2134 // self.last_focused_view_by_item.remove(&active_item.id());
2135 // }
2136 // }
2137
2138 // cx.focus(active_item.as_any());
2139 // } else if focused != self.tab_bar_context_menu.handle {
2140 // self.last_focused_view_by_item
2141 // .insert(active_item.id(), focused.downgrade());
2142 // }
2143 // }
2144 // }
2145
2146 // fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2147 // self.has_focus = false;
2148 // self.toolbar.update(cx, |toolbar, cx| {
2149 // toolbar.focus_changed(false, cx);
2150 // });
2151 // cx.notify();
2152 // }
2153
2154 // fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
2155 // Self::reset_to_default_keymap_context(keymap);
2156 // }
2157}
2158
2159impl ItemNavHistory {
2160 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2161 self.history.push(data, self.item.clone(), cx);
2162 }
2163
2164 pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2165 self.history.pop(NavigationMode::GoingBack, cx)
2166 }
2167
2168 pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2169 self.history.pop(NavigationMode::GoingForward, cx)
2170 }
2171}
2172
2173impl NavHistory {
2174 pub fn for_each_entry(
2175 &self,
2176 cx: &AppContext,
2177 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2178 ) {
2179 let borrowed_history = self.0.lock();
2180 borrowed_history
2181 .forward_stack
2182 .iter()
2183 .chain(borrowed_history.backward_stack.iter())
2184 .chain(borrowed_history.closed_stack.iter())
2185 .for_each(|entry| {
2186 if let Some(project_and_abs_path) =
2187 borrowed_history.paths_by_item.get(&entry.item.id())
2188 {
2189 f(entry, project_and_abs_path.clone());
2190 } else if let Some(item) = entry.item.upgrade() {
2191 if let Some(path) = item.project_path(cx) {
2192 f(entry, (path, None));
2193 }
2194 }
2195 })
2196 }
2197
2198 pub fn set_mode(&mut self, mode: NavigationMode) {
2199 self.0.lock().mode = mode;
2200 }
2201
2202 pub fn mode(&self) -> NavigationMode {
2203 self.0.lock().mode
2204 }
2205
2206 pub fn disable(&mut self) {
2207 self.0.lock().mode = NavigationMode::Disabled;
2208 }
2209
2210 pub fn enable(&mut self) {
2211 self.0.lock().mode = NavigationMode::Normal;
2212 }
2213
2214 pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2215 let mut state = self.0.lock();
2216 let entry = match mode {
2217 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2218 return None
2219 }
2220 NavigationMode::GoingBack => &mut state.backward_stack,
2221 NavigationMode::GoingForward => &mut state.forward_stack,
2222 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2223 }
2224 .pop_back();
2225 if entry.is_some() {
2226 state.did_update(cx);
2227 }
2228 entry
2229 }
2230
2231 pub fn push<D: 'static + Send + Any>(
2232 &mut self,
2233 data: Option<D>,
2234 item: Arc<dyn WeakItemHandle>,
2235 cx: &mut WindowContext,
2236 ) {
2237 let state = &mut *self.0.lock();
2238 match state.mode {
2239 NavigationMode::Disabled => {}
2240 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2241 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2242 state.backward_stack.pop_front();
2243 }
2244 state.backward_stack.push_back(NavigationEntry {
2245 item,
2246 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2247 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2248 });
2249 state.forward_stack.clear();
2250 }
2251 NavigationMode::GoingBack => {
2252 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2253 state.forward_stack.pop_front();
2254 }
2255 state.forward_stack.push_back(NavigationEntry {
2256 item,
2257 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2258 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2259 });
2260 }
2261 NavigationMode::GoingForward => {
2262 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2263 state.backward_stack.pop_front();
2264 }
2265 state.backward_stack.push_back(NavigationEntry {
2266 item,
2267 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2268 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2269 });
2270 }
2271 NavigationMode::ClosingItem => {
2272 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2273 state.closed_stack.pop_front();
2274 }
2275 state.closed_stack.push_back(NavigationEntry {
2276 item,
2277 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2278 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2279 });
2280 }
2281 }
2282 state.did_update(cx);
2283 }
2284
2285 pub fn remove_item(&mut self, item_id: EntityId) {
2286 let mut state = self.0.lock();
2287 state.paths_by_item.remove(&item_id);
2288 state
2289 .backward_stack
2290 .retain(|entry| entry.item.id() != item_id);
2291 state
2292 .forward_stack
2293 .retain(|entry| entry.item.id() != item_id);
2294 state
2295 .closed_stack
2296 .retain(|entry| entry.item.id() != item_id);
2297 }
2298
2299 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2300 self.0.lock().paths_by_item.get(&item_id).cloned()
2301 }
2302}
2303
2304impl NavHistoryState {
2305 pub fn did_update(&self, cx: &mut WindowContext) {
2306 if let Some(pane) = self.pane.upgrade() {
2307 cx.defer(move |cx| {
2308 pane.update(cx, |pane, cx| pane.history_updated(cx));
2309 });
2310 }
2311 }
2312}
2313
2314// pub struct PaneBackdrop<V> {
2315// child_view: usize,
2316// child: AnyElement<V>,
2317// }
2318
2319// impl<V> PaneBackdrop<V> {
2320// pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2321// PaneBackdrop {
2322// child,
2323// child_view: pane_item_view,
2324// }
2325// }
2326// }
2327
2328// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2329// type LayoutState = ();
2330
2331// type PaintState = ();
2332
2333// fn layout(
2334// &mut self,
2335// constraint: gpui::SizeConstraint,
2336// view: &mut V,
2337// cx: &mut ViewContext<V>,
2338// ) -> (Vector2F, Self::LayoutState) {
2339// let size = self.child.layout(constraint, view, cx);
2340// (size, ())
2341// }
2342
2343// fn paint(
2344// &mut self,
2345// bounds: RectF,
2346// visible_bounds: RectF,
2347// _: &mut Self::LayoutState,
2348// view: &mut V,
2349// cx: &mut ViewContext<V>,
2350// ) -> Self::PaintState {
2351// let background = theme::current(cx).editor.background;
2352
2353// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2354
2355// cx.scene().push_quad(gpui::Quad {
2356// bounds: RectF::new(bounds.origin(), bounds.size()),
2357// background: Some(background),
2358// ..Default::default()
2359// });
2360
2361// let child_view_id = self.child_view;
2362// cx.scene().push_mouse_region(
2363// MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2364// gpui::platform::MouseButton::Left,
2365// move |_, _: &mut V, cx| {
2366// let window = cx.window();
2367// cx.app_context().focus(window, Some(child_view_id))
2368// },
2369// ),
2370// );
2371
2372// cx.scene().push_layer(Some(bounds));
2373// self.child.paint(bounds.origin(), visible_bounds, view, cx);
2374// cx.scene().pop_layer();
2375// }
2376
2377// fn rect_for_text_range(
2378// &self,
2379// range_utf16: std::ops::Range<usize>,
2380// _bounds: RectF,
2381// _visible_bounds: RectF,
2382// _layout: &Self::LayoutState,
2383// _paint: &Self::PaintState,
2384// view: &V,
2385// cx: &gpui::ViewContext<V>,
2386// ) -> Option<RectF> {
2387// self.child.rect_for_text_range(range_utf16, view, cx)
2388// }
2389
2390// fn debug(
2391// &self,
2392// _bounds: RectF,
2393// _layout: &Self::LayoutState,
2394// _paint: &Self::PaintState,
2395// view: &V,
2396// cx: &gpui::ViewContext<V>,
2397// ) -> serde_json::Value {
2398// gpui::json::json!({
2399// "type": "Pane Back Drop",
2400// "view": self.child_view,
2401// "child": self.child.debug(view, cx),
2402// })
2403// }
2404// }
2405
2406fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2407 let path = buffer_path
2408 .as_ref()
2409 .and_then(|p| p.path.to_str())
2410 .unwrap_or(&"This buffer");
2411 let path = truncate_and_remove_front(path, 80);
2412 format!("{path} contains unsaved edits. Do you want to save it?")
2413}
2414
2415// todo!("uncomment tests")
2416// #[cfg(test)]
2417// mod tests {
2418// use super::*;
2419// use crate::item::test::{TestItem, TestProjectItem};
2420// use gpui::TestAppContext;
2421// use project::FakeFs;
2422// use settings::SettingsStore;
2423
2424// #[gpui::test]
2425// async fn test_remove_active_empty(cx: &mut TestAppContext) {
2426// init_test(cx);
2427// let fs = FakeFs::new(cx.background());
2428
2429// let project = Project::test(fs, None, cx).await;
2430// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2431// let workspace = window.root(cx);
2432// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2433
2434// pane.update(cx, |pane, cx| {
2435// assert!(pane
2436// .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2437// .is_none())
2438// });
2439// }
2440
2441// #[gpui::test]
2442// async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2443// cx.foreground().forbid_parking();
2444// init_test(cx);
2445// let fs = FakeFs::new(cx.background());
2446
2447// let project = Project::test(fs, None, cx).await;
2448// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2449// let workspace = window.root(cx);
2450// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2451
2452// // 1. Add with a destination index
2453// // a. Add before the active item
2454// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2455// pane.update(cx, |pane, cx| {
2456// pane.add_item(
2457// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2458// false,
2459// false,
2460// Some(0),
2461// cx,
2462// );
2463// });
2464// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2465
2466// // b. Add after the active item
2467// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2468// pane.update(cx, |pane, cx| {
2469// pane.add_item(
2470// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2471// false,
2472// false,
2473// Some(2),
2474// cx,
2475// );
2476// });
2477// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2478
2479// // c. Add at the end of the item list (including off the length)
2480// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2481// pane.update(cx, |pane, cx| {
2482// pane.add_item(
2483// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2484// false,
2485// false,
2486// Some(5),
2487// cx,
2488// );
2489// });
2490// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2491
2492// // 2. Add without a destination index
2493// // a. Add with active item at the start of the item list
2494// set_labeled_items(&pane, ["A*", "B", "C"], cx);
2495// pane.update(cx, |pane, cx| {
2496// pane.add_item(
2497// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2498// false,
2499// false,
2500// None,
2501// cx,
2502// );
2503// });
2504// set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2505
2506// // b. Add with active item at the end of the item list
2507// set_labeled_items(&pane, ["A", "B", "C*"], cx);
2508// pane.update(cx, |pane, cx| {
2509// pane.add_item(
2510// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2511// false,
2512// false,
2513// None,
2514// cx,
2515// );
2516// });
2517// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2518// }
2519
2520// #[gpui::test]
2521// async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2522// cx.foreground().forbid_parking();
2523// init_test(cx);
2524// let fs = FakeFs::new(cx.background());
2525
2526// let project = Project::test(fs, None, cx).await;
2527// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2528// let workspace = window.root(cx);
2529// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2530
2531// // 1. Add with a destination index
2532// // 1a. Add before the active item
2533// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2534// pane.update(cx, |pane, cx| {
2535// pane.add_item(d, false, false, Some(0), cx);
2536// });
2537// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2538
2539// // 1b. Add after the active item
2540// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2541// pane.update(cx, |pane, cx| {
2542// pane.add_item(d, false, false, Some(2), cx);
2543// });
2544// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2545
2546// // 1c. Add at the end of the item list (including off the length)
2547// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2548// pane.update(cx, |pane, cx| {
2549// pane.add_item(a, false, false, Some(5), cx);
2550// });
2551// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2552
2553// // 1d. Add same item to active index
2554// let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2555// pane.update(cx, |pane, cx| {
2556// pane.add_item(b, false, false, Some(1), cx);
2557// });
2558// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2559
2560// // 1e. Add item to index after same item in last position
2561// let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2562// pane.update(cx, |pane, cx| {
2563// pane.add_item(c, false, false, Some(2), cx);
2564// });
2565// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2566
2567// // 2. Add without a destination index
2568// // 2a. Add with active item at the start of the item list
2569// let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2570// pane.update(cx, |pane, cx| {
2571// pane.add_item(d, false, false, None, cx);
2572// });
2573// assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2574
2575// // 2b. Add with active item at the end of the item list
2576// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2577// pane.update(cx, |pane, cx| {
2578// pane.add_item(a, false, false, None, cx);
2579// });
2580// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2581
2582// // 2c. Add active item to active item at end of list
2583// let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2584// pane.update(cx, |pane, cx| {
2585// pane.add_item(c, false, false, None, cx);
2586// });
2587// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2588
2589// // 2d. Add active item to active item at start of list
2590// let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2591// pane.update(cx, |pane, cx| {
2592// pane.add_item(a, false, false, None, cx);
2593// });
2594// assert_item_labels(&pane, ["A*", "B", "C"], cx);
2595// }
2596
2597// #[gpui::test]
2598// async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2599// cx.foreground().forbid_parking();
2600// init_test(cx);
2601// let fs = FakeFs::new(cx.background());
2602
2603// let project = Project::test(fs, None, cx).await;
2604// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2605// let workspace = window.root(cx);
2606// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2607
2608// // singleton view
2609// pane.update(cx, |pane, cx| {
2610// let item = TestItem::new()
2611// .with_singleton(true)
2612// .with_label("buffer 1")
2613// .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2614
2615// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2616// });
2617// assert_item_labels(&pane, ["buffer 1*"], cx);
2618
2619// // new singleton view with the same project entry
2620// pane.update(cx, |pane, cx| {
2621// let item = TestItem::new()
2622// .with_singleton(true)
2623// .with_label("buffer 1")
2624// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2625
2626// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2627// });
2628// assert_item_labels(&pane, ["buffer 1*"], cx);
2629
2630// // new singleton view with different project entry
2631// pane.update(cx, |pane, cx| {
2632// let item = TestItem::new()
2633// .with_singleton(true)
2634// .with_label("buffer 2")
2635// .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2636// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2637// });
2638// assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2639
2640// // new multibuffer view with the same project entry
2641// pane.update(cx, |pane, cx| {
2642// let item = TestItem::new()
2643// .with_singleton(false)
2644// .with_label("multibuffer 1")
2645// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2646
2647// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2648// });
2649// assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2650
2651// // another multibuffer view with the same project entry
2652// pane.update(cx, |pane, cx| {
2653// let item = TestItem::new()
2654// .with_singleton(false)
2655// .with_label("multibuffer 1b")
2656// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2657
2658// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2659// });
2660// assert_item_labels(
2661// &pane,
2662// ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2663// cx,
2664// );
2665// }
2666
2667// #[gpui::test]
2668// async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2669// init_test(cx);
2670// let fs = FakeFs::new(cx.background());
2671
2672// let project = Project::test(fs, None, cx).await;
2673// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2674// let workspace = window.root(cx);
2675// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2676
2677// add_labeled_item(&pane, "A", false, cx);
2678// add_labeled_item(&pane, "B", false, cx);
2679// add_labeled_item(&pane, "C", false, cx);
2680// add_labeled_item(&pane, "D", false, cx);
2681// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2682
2683// pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2684// add_labeled_item(&pane, "1", false, cx);
2685// assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2686
2687// pane.update(cx, |pane, cx| {
2688// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2689// })
2690// .unwrap()
2691// .await
2692// .unwrap();
2693// assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2694
2695// pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2696// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2697
2698// pane.update(cx, |pane, cx| {
2699// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2700// })
2701// .unwrap()
2702// .await
2703// .unwrap();
2704// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2705
2706// pane.update(cx, |pane, cx| {
2707// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2708// })
2709// .unwrap()
2710// .await
2711// .unwrap();
2712// assert_item_labels(&pane, ["A", "C*"], cx);
2713
2714// pane.update(cx, |pane, cx| {
2715// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2716// })
2717// .unwrap()
2718// .await
2719// .unwrap();
2720// assert_item_labels(&pane, ["A*"], cx);
2721// }
2722
2723// #[gpui::test]
2724// async fn test_close_inactive_items(cx: &mut TestAppContext) {
2725// init_test(cx);
2726// let fs = FakeFs::new(cx.background());
2727
2728// let project = Project::test(fs, None, cx).await;
2729// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2730// let workspace = window.root(cx);
2731// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2732
2733// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2734
2735// pane.update(cx, |pane, cx| {
2736// pane.close_inactive_items(&CloseInactiveItems, cx)
2737// })
2738// .unwrap()
2739// .await
2740// .unwrap();
2741// assert_item_labels(&pane, ["C*"], cx);
2742// }
2743
2744// #[gpui::test]
2745// async fn test_close_clean_items(cx: &mut TestAppContext) {
2746// init_test(cx);
2747// let fs = FakeFs::new(cx.background());
2748
2749// let project = Project::test(fs, None, cx).await;
2750// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2751// let workspace = window.root(cx);
2752// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2753
2754// add_labeled_item(&pane, "A", true, cx);
2755// add_labeled_item(&pane, "B", false, cx);
2756// add_labeled_item(&pane, "C", true, cx);
2757// add_labeled_item(&pane, "D", false, cx);
2758// add_labeled_item(&pane, "E", false, cx);
2759// assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2760
2761// pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2762// .unwrap()
2763// .await
2764// .unwrap();
2765// assert_item_labels(&pane, ["A^", "C*^"], cx);
2766// }
2767
2768// #[gpui::test]
2769// async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2770// init_test(cx);
2771// let fs = FakeFs::new(cx.background());
2772
2773// let project = Project::test(fs, None, cx).await;
2774// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2775// let workspace = window.root(cx);
2776// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2777
2778// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2779
2780// pane.update(cx, |pane, cx| {
2781// pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2782// })
2783// .unwrap()
2784// .await
2785// .unwrap();
2786// assert_item_labels(&pane, ["C*", "D", "E"], cx);
2787// }
2788
2789// #[gpui::test]
2790// async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2791// init_test(cx);
2792// let fs = FakeFs::new(cx.background());
2793
2794// let project = Project::test(fs, None, cx).await;
2795// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2796// let workspace = window.root(cx);
2797// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2798
2799// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2800
2801// pane.update(cx, |pane, cx| {
2802// pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2803// })
2804// .unwrap()
2805// .await
2806// .unwrap();
2807// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2808// }
2809
2810// #[gpui::test]
2811// async fn test_close_all_items(cx: &mut TestAppContext) {
2812// init_test(cx);
2813// let fs = FakeFs::new(cx.background());
2814
2815// let project = Project::test(fs, None, cx).await;
2816// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2817// let workspace = window.root(cx);
2818// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2819
2820// add_labeled_item(&pane, "A", false, cx);
2821// add_labeled_item(&pane, "B", false, cx);
2822// add_labeled_item(&pane, "C", false, cx);
2823// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2824
2825// pane.update(cx, |pane, cx| {
2826// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2827// })
2828// .unwrap()
2829// .await
2830// .unwrap();
2831// assert_item_labels(&pane, [], cx);
2832
2833// add_labeled_item(&pane, "A", true, cx);
2834// add_labeled_item(&pane, "B", true, cx);
2835// add_labeled_item(&pane, "C", true, cx);
2836// assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2837
2838// let save = pane
2839// .update(cx, |pane, cx| {
2840// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2841// })
2842// .unwrap();
2843
2844// cx.foreground().run_until_parked();
2845// window.simulate_prompt_answer(2, cx);
2846// save.await.unwrap();
2847// assert_item_labels(&pane, [], cx);
2848// }
2849
2850// fn init_test(cx: &mut TestAppContext) {
2851// cx.update(|cx| {
2852// cx.set_global(SettingsStore::test(cx));
2853// theme::init((), cx);
2854// crate::init_settings(cx);
2855// Project::init_settings(cx);
2856// });
2857// }
2858
2859// fn add_labeled_item(
2860// pane: &ViewHandle<Pane>,
2861// label: &str,
2862// is_dirty: bool,
2863// cx: &mut TestAppContext,
2864// ) -> Box<ViewHandle<TestItem>> {
2865// pane.update(cx, |pane, cx| {
2866// let labeled_item =
2867// Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2868// pane.add_item(labeled_item.clone(), false, false, None, cx);
2869// labeled_item
2870// })
2871// }
2872
2873// fn set_labeled_items<const COUNT: usize>(
2874// pane: &ViewHandle<Pane>,
2875// labels: [&str; COUNT],
2876// cx: &mut TestAppContext,
2877// ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2878// pane.update(cx, |pane, cx| {
2879// pane.items.clear();
2880// let mut active_item_index = 0;
2881
2882// let mut index = 0;
2883// let items = labels.map(|mut label| {
2884// if label.ends_with("*") {
2885// label = label.trim_end_matches("*");
2886// active_item_index = index;
2887// }
2888
2889// let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2890// pane.add_item(labeled_item.clone(), false, false, None, cx);
2891// index += 1;
2892// labeled_item
2893// });
2894
2895// pane.activate_item(active_item_index, false, false, cx);
2896
2897// items
2898// })
2899// }
2900
2901// // Assert the item label, with the active item label suffixed with a '*'
2902// fn assert_item_labels<const COUNT: usize>(
2903// pane: &ViewHandle<Pane>,
2904// expected_states: [&str; COUNT],
2905// cx: &mut TestAppContext,
2906// ) {
2907// pane.read_with(cx, |pane, cx| {
2908// let actual_states = pane
2909// .items
2910// .iter()
2911// .enumerate()
2912// .map(|(ix, item)| {
2913// let mut state = item
2914// .as_any()
2915// .downcast_ref::<TestItem>()
2916// .unwrap()
2917// .read(cx)
2918// .label
2919// .clone();
2920// if ix == pane.active_item_index {
2921// state.push('*');
2922// }
2923// if item.is_dirty(cx) {
2924// state.push('^');
2925// }
2926// state
2927// })
2928// .collect::<Vec<_>>();
2929
2930// assert_eq!(
2931// actual_states, expected_states,
2932// "pane items do not match expectation"
2933// );
2934// })
2935// }
2936// }
2937
2938#[derive(Clone, Debug)]
2939struct DraggedTab {
2940 title: String,
2941}
2942
2943impl Render for DraggedTab {
2944 type Element = Div<Self>;
2945
2946 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2947 div().w_8().h_4().bg(gpui::red())
2948 }
2949}