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