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