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, Model, PromptLevel, Render, Task, View, ViewContext, VisualContext,
12 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 self.activate_item(index_to_activate, should_activate, should_activate, cx);
1021 }
1022
1023 let item = self.items.remove(item_index);
1024
1025 cx.emit(Event::RemoveItem { item_id: item.id() });
1026 if self.items.is_empty() {
1027 item.deactivated(cx);
1028 self.update_toolbar(cx);
1029 cx.emit(Event::Remove);
1030 }
1031
1032 if item_index < self.active_item_index {
1033 self.active_item_index -= 1;
1034 }
1035
1036 self.nav_history.set_mode(NavigationMode::ClosingItem);
1037 item.deactivated(cx);
1038 self.nav_history.set_mode(NavigationMode::Normal);
1039
1040 if let Some(path) = item.project_path(cx) {
1041 let abs_path = self
1042 .nav_history
1043 .0
1044 .lock()
1045 .paths_by_item
1046 .get(&item.id())
1047 .and_then(|(_, abs_path)| abs_path.clone());
1048
1049 self.nav_history
1050 .0
1051 .lock()
1052 .paths_by_item
1053 .insert(item.id(), (path, abs_path));
1054 } else {
1055 self.nav_history.0.lock().paths_by_item.remove(&item.id());
1056 }
1057
1058 if self.items.is_empty() && self.zoomed {
1059 cx.emit(Event::ZoomOut);
1060 }
1061
1062 cx.notify();
1063 }
1064
1065 pub async fn save_item(
1066 project: Model<Project>,
1067 pane: &WeakView<Pane>,
1068 item_ix: usize,
1069 item: &dyn ItemHandle,
1070 save_intent: SaveIntent,
1071 cx: &mut AsyncWindowContext,
1072 ) -> Result<bool> {
1073 const CONFLICT_MESSAGE: &str =
1074 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1075
1076 if save_intent == SaveIntent::Skip {
1077 return Ok(true);
1078 }
1079
1080 let (mut has_conflict, mut is_dirty, mut can_save, can_save_as) = cx.update(|_, cx| {
1081 (
1082 item.has_conflict(cx),
1083 item.is_dirty(cx),
1084 item.can_save(cx),
1085 item.is_singleton(cx),
1086 )
1087 })?;
1088
1089 // when saving a single buffer, we ignore whether or not it's dirty.
1090 if save_intent == SaveIntent::Save {
1091 is_dirty = true;
1092 }
1093
1094 if save_intent == SaveIntent::SaveAs {
1095 is_dirty = true;
1096 has_conflict = false;
1097 can_save = false;
1098 }
1099
1100 if save_intent == SaveIntent::Overwrite {
1101 has_conflict = false;
1102 }
1103
1104 if has_conflict && can_save {
1105 let answer = pane.update(cx, |pane, cx| {
1106 pane.activate_item(item_ix, true, true, cx);
1107 cx.prompt(
1108 PromptLevel::Warning,
1109 CONFLICT_MESSAGE,
1110 &["Overwrite", "Discard", "Cancel"],
1111 )
1112 })?;
1113 match answer.await {
1114 Ok(0) => pane.update(cx, |_, cx| item.save(project, cx))?.await?,
1115 Ok(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
1116 _ => return Ok(false),
1117 }
1118 } else if is_dirty && (can_save || can_save_as) {
1119 if save_intent == SaveIntent::Close {
1120 let will_autosave = cx.update(|_, cx| {
1121 matches!(
1122 WorkspaceSettings::get_global(cx).autosave,
1123 AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1124 ) && Self::can_autosave_item(&*item, cx)
1125 })?;
1126 if !will_autosave {
1127 let answer = pane.update(cx, |pane, cx| {
1128 pane.activate_item(item_ix, true, true, cx);
1129 let prompt = dirty_message_for(item.project_path(cx));
1130 cx.prompt(
1131 PromptLevel::Warning,
1132 &prompt,
1133 &["Save", "Don't Save", "Cancel"],
1134 )
1135 })?;
1136 match answer.await {
1137 Ok(0) => {}
1138 Ok(1) => return Ok(true), // Don't save this file
1139 _ => return Ok(false), // Cancel
1140 }
1141 }
1142 }
1143
1144 if can_save {
1145 pane.update(cx, |_, cx| item.save(project, cx))?.await?;
1146 } else if can_save_as {
1147 let start_abs_path = project
1148 .update(cx, |project, cx| {
1149 let worktree = project.visible_worktrees(cx).next()?;
1150 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1151 })?
1152 .unwrap_or_else(|| Path::new("").into());
1153
1154 let abs_path = cx.update(|_, cx| cx.prompt_for_new_path(&start_abs_path))?;
1155 if let Some(abs_path) = abs_path.await.ok().flatten() {
1156 pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
1157 .await?;
1158 } else {
1159 return Ok(false);
1160 }
1161 }
1162 }
1163 Ok(true)
1164 }
1165
1166 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1167 let is_deleted = item.project_entry_ids(cx).is_empty();
1168 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1169 }
1170
1171 pub fn autosave_item(
1172 item: &dyn ItemHandle,
1173 project: Model<Project>,
1174 cx: &mut WindowContext,
1175 ) -> Task<Result<()>> {
1176 if Self::can_autosave_item(item, cx) {
1177 item.save(project, cx)
1178 } else {
1179 Task::ready(Ok(()))
1180 }
1181 }
1182
1183 pub fn focus(&mut self, cx: &mut ViewContext<Pane>) {
1184 cx.focus(&self.focus_handle);
1185 }
1186
1187 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1188 if let Some(active_item) = self.active_item() {
1189 let focus_handle = active_item.focus_handle(cx);
1190 cx.focus(&focus_handle);
1191 }
1192 }
1193
1194 // pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1195 // cx.emit(Event::Split(direction));
1196 // }
1197
1198 // fn deploy_split_menu(&mut self, cx: &mut ViewContext<Self>) {
1199 // self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1200 // menu.toggle(
1201 // Default::default(),
1202 // AnchorCorner::TopRight,
1203 // vec![
1204 // ContextMenuItem::action("Split Right", SplitRight),
1205 // ContextMenuItem::action("Split Left", SplitLeft),
1206 // ContextMenuItem::action("Split Up", SplitUp),
1207 // ContextMenuItem::action("Split Down", SplitDown),
1208 // ],
1209 // cx,
1210 // );
1211 // });
1212
1213 // self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1214 // }
1215
1216 // fn deploy_new_menu(&mut self, cx: &mut ViewContext<Self>) {
1217 // self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1218 // menu.toggle(
1219 // Default::default(),
1220 // AnchorCorner::TopRight,
1221 // vec![
1222 // ContextMenuItem::action("New File", NewFile),
1223 // ContextMenuItem::action("New Terminal", NewCenterTerminal),
1224 // ContextMenuItem::action("New Search", NewSearch),
1225 // ],
1226 // cx,
1227 // );
1228 // });
1229
1230 // self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1231 // }
1232
1233 // fn deploy_tab_context_menu(
1234 // &mut self,
1235 // position: Vector2F,
1236 // target_item_id: usize,
1237 // cx: &mut ViewContext<Self>,
1238 // ) {
1239 // let active_item_id = self.items[self.active_item_index].id();
1240 // let is_active_item = target_item_id == active_item_id;
1241 // let target_pane = cx.weak_handle();
1242
1243 // // The `CloseInactiveItems` action should really be called "CloseOthers" and the behaviour should be dynamically based on the tab the action is ran on. Currently, this is a weird action because you can run it on a non-active tab and it will close everything by the actual active tab
1244
1245 // self.tab_context_menu.update(cx, |menu, cx| {
1246 // menu.show(
1247 // position,
1248 // AnchorCorner::TopLeft,
1249 // if is_active_item {
1250 // vec![
1251 // ContextMenuItem::action(
1252 // "Close Active Item",
1253 // CloseActiveItem { save_intent: None },
1254 // ),
1255 // ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1256 // ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1257 // ContextMenuItem::action("Close Items To The Left", CloseItemsToTheLeft),
1258 // ContextMenuItem::action("Close Items To The Right", CloseItemsToTheRight),
1259 // ContextMenuItem::action(
1260 // "Close All Items",
1261 // CloseAllItems { save_intent: None },
1262 // ),
1263 // ]
1264 // } else {
1265 // // In the case of the user right clicking on a non-active tab, for some item-closing commands, we need to provide the id of the tab, for the others, we can reuse the existing command.
1266 // vec![
1267 // ContextMenuItem::handler("Close Inactive Item", {
1268 // let pane = target_pane.clone();
1269 // move |cx| {
1270 // if let Some(pane) = pane.upgrade(cx) {
1271 // pane.update(cx, |pane, cx| {
1272 // pane.close_item_by_id(
1273 // target_item_id,
1274 // SaveIntent::Close,
1275 // cx,
1276 // )
1277 // .detach_and_log_err(cx);
1278 // })
1279 // }
1280 // }
1281 // }),
1282 // ContextMenuItem::action("Close Inactive Items", CloseInactiveItems),
1283 // ContextMenuItem::action("Close Clean Items", CloseCleanItems),
1284 // ContextMenuItem::handler("Close Items To The Left", {
1285 // let pane = target_pane.clone();
1286 // move |cx| {
1287 // if let Some(pane) = pane.upgrade(cx) {
1288 // pane.update(cx, |pane, cx| {
1289 // pane.close_items_to_the_left_by_id(target_item_id, cx)
1290 // .detach_and_log_err(cx);
1291 // })
1292 // }
1293 // }
1294 // }),
1295 // ContextMenuItem::handler("Close Items To The Right", {
1296 // let pane = target_pane.clone();
1297 // move |cx| {
1298 // if let Some(pane) = pane.upgrade(cx) {
1299 // pane.update(cx, |pane, cx| {
1300 // pane.close_items_to_the_right_by_id(target_item_id, cx)
1301 // .detach_and_log_err(cx);
1302 // })
1303 // }
1304 // }
1305 // }),
1306 // ContextMenuItem::action(
1307 // "Close All Items",
1308 // CloseAllItems { save_intent: None },
1309 // ),
1310 // ]
1311 // },
1312 // cx,
1313 // );
1314 // });
1315 // }
1316
1317 pub fn toolbar(&self) -> &View<Toolbar> {
1318 &self.toolbar
1319 }
1320
1321 pub fn handle_deleted_project_item(
1322 &mut self,
1323 entry_id: ProjectEntryId,
1324 cx: &mut ViewContext<Pane>,
1325 ) -> Option<()> {
1326 let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
1327 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
1328 Some((i, item.id()))
1329 } else {
1330 None
1331 }
1332 })?;
1333
1334 self.remove_item(item_index_to_delete, false, cx);
1335 self.nav_history.remove_item(item_id);
1336
1337 Some(())
1338 }
1339
1340 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1341 let active_item = self
1342 .items
1343 .get(self.active_item_index)
1344 .map(|item| item.as_ref());
1345 self.toolbar.update(cx, |toolbar, cx| {
1346 toolbar.set_active_item(active_item, cx);
1347 });
1348 }
1349
1350 fn render_tab(
1351 &self,
1352 ix: usize,
1353 item: &Box<dyn ItemHandle>,
1354 detail: usize,
1355 cx: &mut ViewContext<'_, Pane>,
1356 ) -> impl Component<Self> {
1357 let label = item.tab_content(Some(detail), cx);
1358 let close_icon = || {
1359 let id = item.id();
1360
1361 div()
1362 .id(item.id())
1363 .invisible()
1364 .group_hover("", |style| style.visible())
1365 .child(IconButton::new("close_tab", Icon::Close).on_click(
1366 move |pane: &mut Self, cx| {
1367 pane.close_item_by_id(id, SaveIntent::Close, cx)
1368 .detach_and_log_err(cx);
1369 },
1370 ))
1371 };
1372
1373 let (text_color, tab_bg, tab_hover_bg, tab_active_bg) = match ix == self.active_item_index {
1374 false => (
1375 cx.theme().colors().text_muted,
1376 cx.theme().colors().tab_inactive_background,
1377 cx.theme().colors().ghost_element_hover,
1378 cx.theme().colors().ghost_element_active,
1379 ),
1380 true => (
1381 cx.theme().colors().text,
1382 cx.theme().colors().tab_active_background,
1383 cx.theme().colors().element_hover,
1384 cx.theme().colors().element_active,
1385 ),
1386 };
1387
1388 let close_right = ItemSettings::get_global(cx).close_position.right();
1389
1390 div()
1391 .group("")
1392 .id(item.id())
1393 .cursor_pointer()
1394 .when_some(item.tab_tooltip_text(cx), |div, text| {
1395 div.tooltip(move |_, cx| cx.build_view(|cx| TextTooltip::new(text.clone())))
1396 })
1397 // .on_drag(move |pane, cx| pane.render_tab(ix, item.boxed_clone(), detail, cx))
1398 // .drag_over::<DraggedTab>(|d| d.bg(cx.theme().colors().element_drop_target))
1399 // .on_drop(|_view, state: View<DraggedTab>, cx| {
1400 // eprintln!("{:?}", state.read(cx));
1401 // })
1402 .flex()
1403 .items_center()
1404 .justify_center()
1405 // todo!("Nate - I need to do some work to balance all the items in the tab once things stablize")
1406 .map(|this| {
1407 if close_right {
1408 this.pl_3().pr_1()
1409 } else {
1410 this.pr_1().pr_3()
1411 }
1412 })
1413 .py_1()
1414 .bg(tab_bg)
1415 .border_color(cx.theme().colors().border)
1416 .map(|this| match ix.cmp(&self.active_item_index) {
1417 cmp::Ordering::Less => this.border_l(),
1418 cmp::Ordering::Equal => this.border_r(),
1419 cmp::Ordering::Greater => this.border_l().border_r(),
1420 })
1421 // .hover(|h| h.bg(tab_hover_bg))
1422 // .active(|a| a.bg(tab_active_bg))
1423 .child(
1424 div()
1425 .flex()
1426 .items_center()
1427 .gap_1()
1428 .text_color(text_color)
1429 .children(if item.has_conflict(cx) {
1430 Some(
1431 IconElement::new(Icon::ExclamationTriangle)
1432 .size(ui::IconSize::Small)
1433 .color(TextColor::Warning),
1434 )
1435 } else if item.is_dirty(cx) {
1436 Some(
1437 IconElement::new(Icon::ExclamationTriangle)
1438 .size(ui::IconSize::Small)
1439 .color(TextColor::Info),
1440 )
1441 } else {
1442 None
1443 })
1444 .children(if !close_right {
1445 Some(close_icon())
1446 } else {
1447 None
1448 })
1449 .child(label)
1450 .children(if close_right {
1451 Some(close_icon())
1452 } else {
1453 None
1454 }),
1455 )
1456 }
1457
1458 fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl Component<Self> {
1459 div()
1460 .group("tab_bar")
1461 .id("tab_bar")
1462 .w_full()
1463 .flex()
1464 .bg(cx.theme().colors().tab_bar_background)
1465 // Left Side
1466 .child(
1467 div()
1468 .relative()
1469 .px_1()
1470 .flex()
1471 .flex_none()
1472 .gap_2()
1473 // Nav Buttons
1474 .child(
1475 div()
1476 .right_0()
1477 .flex()
1478 .items_center()
1479 .gap_px()
1480 .child(IconButton::new("navigate_backward", Icon::ArrowLeft).state(
1481 InteractionState::Enabled.if_enabled(self.can_navigate_backward()),
1482 ))
1483 .child(IconButton::new("navigate_forward", Icon::ArrowRight).state(
1484 InteractionState::Enabled.if_enabled(self.can_navigate_forward()),
1485 )),
1486 ),
1487 )
1488 .child(
1489 div().flex_1().h_full().child(
1490 div().id("tabs").flex().overflow_x_scroll().children(
1491 self.items
1492 .iter()
1493 .enumerate()
1494 .zip(self.tab_details(cx))
1495 .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1496 ),
1497 ),
1498 )
1499 // Right Side
1500 .child(
1501 div()
1502 // We only use absolute here since we don't
1503 // have opacity or `hidden()` yet
1504 .absolute()
1505 .neg_top_7()
1506 .px_1()
1507 .flex()
1508 .flex_none()
1509 .gap_2()
1510 .group_hover("tab_bar", |this| this.top_0())
1511 // Nav Buttons
1512 .child(
1513 div()
1514 .flex()
1515 .items_center()
1516 .gap_px()
1517 .child(IconButton::new("plus", Icon::Plus))
1518 .child(IconButton::new("split", Icon::Split)),
1519 ),
1520 )
1521 }
1522
1523 // fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Element<Self> {
1524 // let theme = theme::current(cx).clone();
1525
1526 // let pane = cx.handle().downgrade();
1527 // let autoscroll = if mem::take(&mut self.autoscroll) {
1528 // Some(self.active_item_index)
1529 // } else {
1530 // None
1531 // };
1532
1533 // let pane_active = self.has_focus;
1534
1535 // enum Tabs {}
1536 // let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1537 // for (ix, (item, detail)) in self
1538 // .items
1539 // .iter()
1540 // .cloned()
1541 // .zip(self.tab_details(cx))
1542 // .enumerate()
1543 // {
1544 // let git_status = item
1545 // .project_path(cx)
1546 // .and_then(|path| self.project.read(cx).entry_for_path(&path, cx))
1547 // .and_then(|entry| entry.git_status());
1548
1549 // let detail = if detail == 0 { None } else { Some(detail) };
1550 // let tab_active = ix == self.active_item_index;
1551
1552 // row.add_child({
1553 // enum TabDragReceiver {}
1554 // let mut receiver =
1555 // dragged_item_receiver::<TabDragReceiver, _, _>(self, ix, ix, true, None, cx, {
1556 // let item = item.clone();
1557 // let pane = pane.clone();
1558 // let detail = detail.clone();
1559
1560 // let theme = theme::current(cx).clone();
1561 // let mut tooltip_theme = theme.tooltip.clone();
1562 // tooltip_theme.max_text_width = None;
1563 // let tab_tooltip_text =
1564 // item.tab_tooltip_text(cx).map(|text| text.into_owned());
1565
1566 // let mut tab_style = theme
1567 // .workspace
1568 // .tab_bar
1569 // .tab_style(pane_active, tab_active)
1570 // .clone();
1571 // let should_show_status = settings::get::<ItemSettings>(cx).git_status;
1572 // if should_show_status && git_status != None {
1573 // tab_style.label.text.color = match git_status.unwrap() {
1574 // GitFileStatus::Added => tab_style.git.inserted,
1575 // GitFileStatus::Modified => tab_style.git.modified,
1576 // GitFileStatus::Conflict => tab_style.git.conflict,
1577 // };
1578 // }
1579
1580 // move |mouse_state, cx| {
1581 // let hovered = mouse_state.hovered();
1582
1583 // enum Tab {}
1584 // let mouse_event_handler =
1585 // MouseEventHandler::new::<Tab, _>(ix, cx, |_, cx| {
1586 // Self::render_tab(
1587 // &item,
1588 // pane.clone(),
1589 // ix == 0,
1590 // detail,
1591 // hovered,
1592 // &tab_style,
1593 // cx,
1594 // )
1595 // })
1596 // .on_down(MouseButton::Left, move |_, this, cx| {
1597 // this.activate_item(ix, true, true, cx);
1598 // })
1599 // .on_click(MouseButton::Middle, {
1600 // let item_id = item.id();
1601 // move |_, pane, cx| {
1602 // pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1603 // .detach_and_log_err(cx);
1604 // }
1605 // })
1606 // .on_down(
1607 // MouseButton::Right,
1608 // move |event, pane, cx| {
1609 // pane.deploy_tab_context_menu(event.position, item.id(), cx);
1610 // },
1611 // );
1612
1613 // if let Some(tab_tooltip_text) = tab_tooltip_text {
1614 // mouse_event_handler
1615 // .with_tooltip::<Self>(
1616 // ix,
1617 // tab_tooltip_text,
1618 // None,
1619 // tooltip_theme,
1620 // cx,
1621 // )
1622 // .into_any()
1623 // } else {
1624 // mouse_event_handler.into_any()
1625 // }
1626 // }
1627 // });
1628
1629 // if !pane_active || !tab_active {
1630 // receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1631 // }
1632
1633 // receiver.as_draggable(
1634 // DraggedItem {
1635 // handle: item,
1636 // pane: pane.clone(),
1637 // },
1638 // {
1639 // let theme = theme::current(cx).clone();
1640
1641 // let detail = detail.clone();
1642 // move |_, dragged_item: &DraggedItem, cx: &mut ViewContext<Workspace>| {
1643 // let tab_style = &theme.workspace.tab_bar.dragged_tab;
1644 // Self::render_dragged_tab(
1645 // &dragged_item.handle,
1646 // dragged_item.pane.clone(),
1647 // false,
1648 // detail,
1649 // false,
1650 // &tab_style,
1651 // cx,
1652 // )
1653 // }
1654 // },
1655 // )
1656 // })
1657 // }
1658
1659 // // Use the inactive tab style along with the current pane's active status to decide how to render
1660 // // the filler
1661 // let filler_index = self.items.len();
1662 // let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1663 // enum Filler {}
1664 // row.add_child(
1665 // dragged_item_receiver::<Filler, _, _>(self, 0, filler_index, true, None, cx, |_, _| {
1666 // Empty::new()
1667 // .contained()
1668 // .with_style(filler_style.container)
1669 // .with_border(filler_style.container.border)
1670 // })
1671 // .flex(1., true)
1672 // .into_any_named("filler"),
1673 // );
1674
1675 // row
1676 // }
1677
1678 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1679 let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1680
1681 let mut tab_descriptions = HashMap::default();
1682 let mut done = false;
1683 while !done {
1684 done = true;
1685
1686 // Store item indices by their tab description.
1687 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1688 if let Some(description) = item.tab_description(*detail, cx) {
1689 if *detail == 0
1690 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1691 {
1692 tab_descriptions
1693 .entry(description)
1694 .or_insert(Vec::new())
1695 .push(ix);
1696 }
1697 }
1698 }
1699
1700 // If two or more items have the same tab description, increase eir level
1701 // of detail and try again.
1702 for (_, item_ixs) in tab_descriptions.drain() {
1703 if item_ixs.len() > 1 {
1704 done = false;
1705 for ix in item_ixs {
1706 tab_details[ix] += 1;
1707 }
1708 }
1709 }
1710 }
1711
1712 tab_details
1713 }
1714
1715 // fn render_tab(
1716 // item: &Box<dyn ItemHandle>,
1717 // pane: WeakView<Pane>,
1718 // first: bool,
1719 // detail: Option<usize>,
1720 // hovered: bool,
1721 // tab_style: &theme::Tab,
1722 // cx: &mut ViewContext<Self>,
1723 // ) -> AnyElement<Self> {
1724 // let title = item.tab_content(detail, &tab_style, cx);
1725 // Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1726 // }
1727
1728 // fn render_dragged_tab(
1729 // item: &Box<dyn ItemHandle>,
1730 // pane: WeakView<Pane>,
1731 // first: bool,
1732 // detail: Option<usize>,
1733 // hovered: bool,
1734 // tab_style: &theme::Tab,
1735 // cx: &mut ViewContext<Workspace>,
1736 // ) -> AnyElement<Workspace> {
1737 // let title = item.dragged_tab_content(detail, &tab_style, cx);
1738 // Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1739 // }
1740
1741 // fn render_tab_with_title<T: View>(
1742 // title: AnyElement<T>,
1743 // item: &Box<dyn ItemHandle>,
1744 // pane: WeakView<Pane>,
1745 // first: bool,
1746 // hovered: bool,
1747 // tab_style: &theme::Tab,
1748 // cx: &mut ViewContext<T>,
1749 // ) -> AnyElement<T> {
1750 // let mut container = tab_style.container.clone();
1751 // if first {
1752 // container.border.left = false;
1753 // }
1754
1755 // let buffer_jewel_element = {
1756 // let diameter = 7.0;
1757 // let icon_color = if item.has_conflict(cx) {
1758 // Some(tab_style.icon_conflict)
1759 // } else if item.is_dirty(cx) {
1760 // Some(tab_style.icon_dirty)
1761 // } else {
1762 // None
1763 // };
1764
1765 // Canvas::new(move |bounds, _, _, cx| {
1766 // if let Some(color) = icon_color {
1767 // let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1768 // cx.scene().push_quad(Quad {
1769 // bounds: square,
1770 // background: Some(color),
1771 // border: Default::default(),
1772 // corner_radii: (diameter / 2.).into(),
1773 // });
1774 // }
1775 // })
1776 // .constrained()
1777 // .with_width(diameter)
1778 // .with_height(diameter)
1779 // .aligned()
1780 // };
1781
1782 // let title_element = title.aligned().contained().with_style(ContainerStyle {
1783 // margin: Margin {
1784 // left: tab_style.spacing,
1785 // right: tab_style.spacing,
1786 // ..Default::default()
1787 // },
1788 // ..Default::default()
1789 // });
1790
1791 // let close_element = if hovered {
1792 // let item_id = item.id();
1793 // enum TabCloseButton {}
1794 // let icon = Svg::new("icons/x.svg");
1795 // MouseEventHandler::new::<TabCloseButton, _>(item_id, cx, |mouse_state, _| {
1796 // if mouse_state.hovered() {
1797 // icon.with_color(tab_style.icon_close_active)
1798 // } else {
1799 // icon.with_color(tab_style.icon_close)
1800 // }
1801 // })
1802 // .with_padding(Padding::uniform(4.))
1803 // .with_cursor_style(CursorStyle::PointingHand)
1804 // .on_click(MouseButton::Left, {
1805 // let pane = pane.clone();
1806 // move |_, _, cx| {
1807 // let pane = pane.clone();
1808 // cx.window_context().defer(move |cx| {
1809 // if let Some(pane) = pane.upgrade(cx) {
1810 // pane.update(cx, |pane, cx| {
1811 // pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1812 // .detach_and_log_err(cx);
1813 // });
1814 // }
1815 // });
1816 // }
1817 // })
1818 // .into_any_named("close-tab-icon")
1819 // .constrained()
1820 // } else {
1821 // Empty::new().constrained()
1822 // }
1823 // .with_width(tab_style.close_icon_width)
1824 // .aligned();
1825
1826 // let close_right = settings::get::<ItemSettings>(cx).close_position.right();
1827
1828 // if close_right {
1829 // Flex::row()
1830 // .with_child(buffer_jewel_element)
1831 // .with_child(title_element)
1832 // .with_child(close_element)
1833 // } else {
1834 // Flex::row()
1835 // .with_child(close_element)
1836 // .with_child(title_element)
1837 // .with_child(buffer_jewel_element)
1838 // }
1839 // .contained()
1840 // .with_style(container)
1841 // .constrained()
1842 // .with_height(tab_style.height)
1843 // .into_any()
1844 // }
1845
1846 // pub fn render_tab_bar_button<
1847 // F1: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
1848 // F2: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
1849 // >(
1850 // index: usize,
1851 // icon: &'static str,
1852 // is_active: bool,
1853 // tooltip: Option<(&'static str, Option<Box<dyn Action>>)>,
1854 // cx: &mut ViewContext<Pane>,
1855 // on_click: F1,
1856 // on_down: F2,
1857 // context_menu: Option<ViewHandle<ContextMenu>>,
1858 // ) -> AnyElement<Pane> {
1859 // enum TabBarButton {}
1860
1861 // let mut button = MouseEventHandler::new::<TabBarButton, _>(index, cx, |mouse_state, cx| {
1862 // let theme = &settings2::get::<ThemeSettings>(cx).theme.workspace.tab_bar;
1863 // let style = theme.pane_button.in_state(is_active).style_for(mouse_state);
1864 // Svg::new(icon)
1865 // .with_color(style.color)
1866 // .constrained()
1867 // .with_width(style.icon_width)
1868 // .aligned()
1869 // .constrained()
1870 // .with_width(style.button_width)
1871 // .with_height(style.button_width)
1872 // })
1873 // .with_cursor_style(CursorStyle::PointingHand)
1874 // .on_down(MouseButton::Left, move |_, pane, cx| on_down(pane, cx))
1875 // .on_click(MouseButton::Left, move |_, pane, cx| on_click(pane, cx))
1876 // .into_any();
1877 // if let Some((tooltip, action)) = tooltip {
1878 // let tooltip_style = settings::get::<ThemeSettings>(cx).theme.tooltip.clone();
1879 // button = button
1880 // .with_tooltip::<TabBarButton>(index, tooltip, action, tooltip_style, cx)
1881 // .into_any();
1882 // }
1883
1884 // Stack::new()
1885 // .with_child(button)
1886 // .with_children(
1887 // context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),
1888 // )
1889 // .flex(1., false)
1890 // .into_any_named("tab bar button")
1891 // }
1892
1893 // fn render_blank_pane(&self, theme: &Theme, _cx: &mut ViewContext<Self>) -> AnyElement<Self> {
1894 // let background = theme.workspace.background;
1895 // Empty::new()
1896 // .contained()
1897 // .with_background_color(background)
1898 // .into_any()
1899 // }
1900
1901 pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1902 self.zoomed = zoomed;
1903 cx.notify();
1904 }
1905
1906 pub fn is_zoomed(&self) -> bool {
1907 self.zoomed
1908 }
1909}
1910
1911// impl Entity for Pane {
1912// type Event = Event;
1913// }
1914
1915impl Render for Pane {
1916 type Element = Div<Self>;
1917
1918 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1919 v_stack()
1920 .key_context("Pane")
1921 .size_full()
1922 .on_action(|pane: &mut Self, action, cx| {
1923 pane.close_active_item(action, cx)
1924 .map(|task| task.detach_and_log_err(cx));
1925 })
1926 .child(self.render_tab_bar(cx))
1927 .child(div() /* todo!(toolbar) */)
1928 .child(if let Some(item) = self.active_item() {
1929 div().flex_1().child(item.to_any())
1930 } else {
1931 // todo!()
1932 div().child("Empty Pane")
1933 })
1934
1935 // enum MouseNavigationHandler {}
1936
1937 // MouseEventHandler::new::<MouseNavigationHandler, _>(0, cx, |_, cx| {
1938 // let active_item_index = self.active_item_index;
1939
1940 // if let Some(active_item) = self.active_item() {
1941 // Flex::column()
1942 // .with_child({
1943 // let theme = theme::current(cx).clone();
1944
1945 // let mut stack = Stack::new();
1946
1947 // enum TabBarEventHandler {}
1948 // stack.add_child(
1949 // MouseEventHandler::new::<TabBarEventHandler, _>(0, cx, |_, _| {
1950 // Empty::new()
1951 // .contained()
1952 // .with_style(theme.workspace.tab_bar.container)
1953 // })
1954 // .on_down(
1955 // MouseButton::Left,
1956 // move |_, this, cx| {
1957 // this.activate_item(active_item_index, true, true, cx);
1958 // },
1959 // ),
1960 // );
1961 // let tooltip_style = theme.tooltip.clone();
1962 // let tab_bar_theme = theme.workspace.tab_bar.clone();
1963
1964 // let nav_button_height = tab_bar_theme.height;
1965 // let button_style = tab_bar_theme.nav_button;
1966 // let border_for_nav_buttons = tab_bar_theme
1967 // .tab_style(false, false)
1968 // .container
1969 // .border
1970 // .clone();
1971
1972 // let mut tab_row = Flex::row()
1973 // .with_child(nav_button(
1974 // "icons/arrow_left.svg",
1975 // button_style.clone(),
1976 // nav_button_height,
1977 // tooltip_style.clone(),
1978 // self.can_navigate_backward(),
1979 // {
1980 // move |pane, cx| {
1981 // if let Some(workspace) = pane.workspace.upgrade(cx) {
1982 // let pane = cx.weak_handle();
1983 // cx.window_context().defer(move |cx| {
1984 // workspace.update(cx, |workspace, cx| {
1985 // workspace
1986 // .go_back(pane, cx)
1987 // .detach_and_log_err(cx)
1988 // })
1989 // })
1990 // }
1991 // }
1992 // },
1993 // super::GoBack,
1994 // "Go Back",
1995 // cx,
1996 // ))
1997 // .with_child(
1998 // nav_button(
1999 // "icons/arrow_right.svg",
2000 // button_style.clone(),
2001 // nav_button_height,
2002 // tooltip_style,
2003 // self.can_navigate_forward(),
2004 // {
2005 // move |pane, cx| {
2006 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2007 // let pane = cx.weak_handle();
2008 // cx.window_context().defer(move |cx| {
2009 // workspace.update(cx, |workspace, cx| {
2010 // workspace
2011 // .go_forward(pane, cx)
2012 // .detach_and_log_err(cx)
2013 // })
2014 // })
2015 // }
2016 // }
2017 // },
2018 // super::GoForward,
2019 // "Go Forward",
2020 // cx,
2021 // )
2022 // .contained()
2023 // .with_border(border_for_nav_buttons),
2024 // )
2025 // .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
2026
2027 // if self.has_focus {
2028 // let render_tab_bar_buttons = self.render_tab_bar_buttons.clone();
2029 // tab_row.add_child(
2030 // (render_tab_bar_buttons)(self, cx)
2031 // .contained()
2032 // .with_style(theme.workspace.tab_bar.pane_button_container)
2033 // .flex(1., false)
2034 // .into_any(),
2035 // )
2036 // }
2037
2038 // stack.add_child(tab_row);
2039 // stack
2040 // .constrained()
2041 // .with_height(theme.workspace.tab_bar.height)
2042 // .flex(1., false)
2043 // .into_any_named("tab bar")
2044 // })
2045 // .with_child({
2046 // enum PaneContentTabDropTarget {}
2047 // dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
2048 // self,
2049 // 0,
2050 // self.active_item_index + 1,
2051 // !self.can_split,
2052 // if self.can_split { Some(100.) } else { None },
2053 // cx,
2054 // {
2055 // let toolbar = self.toolbar.clone();
2056 // let toolbar_hidden = toolbar.read(cx).hidden();
2057 // move |_, cx| {
2058 // Flex::column()
2059 // .with_children(
2060 // (!toolbar_hidden)
2061 // .then(|| ChildView::new(&toolbar, cx).expanded()),
2062 // )
2063 // .with_child(
2064 // ChildView::new(active_item.as_any(), cx).flex(1., true),
2065 // )
2066 // }
2067 // },
2068 // )
2069 // .flex(1., true)
2070 // })
2071 // .with_child(ChildView::new(&self.tab_context_menu, cx))
2072 // .into_any()
2073 // } else {
2074 // enum EmptyPane {}
2075 // let theme = theme::current(cx).clone();
2076
2077 // dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {
2078 // self.render_blank_pane(&theme, cx)
2079 // })
2080 // .on_down(MouseButton::Left, |_, _, cx| {
2081 // cx.focus_parent();
2082 // })
2083 // .into_any()
2084 // }
2085 // })
2086 // .on_down(
2087 // MouseButton::Navigate(NavigationDirection::Back),
2088 // move |_, pane, cx| {
2089 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2090 // let pane = cx.weak_handle();
2091 // cx.window_context().defer(move |cx| {
2092 // workspace.update(cx, |workspace, cx| {
2093 // workspace.go_back(pane, cx).detach_and_log_err(cx)
2094 // })
2095 // })
2096 // }
2097 // },
2098 // )
2099 // .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
2100 // move |_, pane, cx| {
2101 // if let Some(workspace) = pane.workspace.upgrade(cx) {
2102 // let pane = cx.weak_handle();
2103 // cx.window_context().defer(move |cx| {
2104 // workspace.update(cx, |workspace, cx| {
2105 // workspace.go_forward(pane, cx).detach_and_log_err(cx)
2106 // })
2107 // })
2108 // }
2109 // }
2110 // })
2111 // .into_any_named("pane")
2112 }
2113
2114 // fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
2115 // if !self.has_focus {
2116 // self.has_focus = true;
2117 // cx.emit(Event::Focus);
2118 // cx.notify();
2119 // }
2120
2121 // self.toolbar.update(cx, |toolbar, cx| {
2122 // toolbar.focus_changed(true, cx);
2123 // });
2124
2125 // if let Some(active_item) = self.active_item() {
2126 // if cx.is_self_focused() {
2127 // // Pane was focused directly. We need to either focus a view inside the active item,
2128 // // or focus the active item itself
2129 // if let Some(weak_last_focused_view) =
2130 // self.last_focused_view_by_item.get(&active_item.id())
2131 // {
2132 // if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
2133 // cx.focus(&last_focused_view);
2134 // return;
2135 // } else {
2136 // self.last_focused_view_by_item.remove(&active_item.id());
2137 // }
2138 // }
2139
2140 // cx.focus(active_item.as_any());
2141 // } else if focused != self.tab_bar_context_menu.handle {
2142 // self.last_focused_view_by_item
2143 // .insert(active_item.id(), focused.downgrade());
2144 // }
2145 // }
2146 // }
2147
2148 // fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2149 // self.has_focus = false;
2150 // self.toolbar.update(cx, |toolbar, cx| {
2151 // toolbar.focus_changed(false, cx);
2152 // });
2153 // cx.notify();
2154 // }
2155
2156 // fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
2157 // Self::reset_to_default_keymap_context(keymap);
2158 // }
2159}
2160
2161impl ItemNavHistory {
2162 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2163 self.history.push(data, self.item.clone(), cx);
2164 }
2165
2166 pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2167 self.history.pop(NavigationMode::GoingBack, cx)
2168 }
2169
2170 pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2171 self.history.pop(NavigationMode::GoingForward, cx)
2172 }
2173}
2174
2175impl NavHistory {
2176 pub fn for_each_entry(
2177 &self,
2178 cx: &AppContext,
2179 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2180 ) {
2181 let borrowed_history = self.0.lock();
2182 borrowed_history
2183 .forward_stack
2184 .iter()
2185 .chain(borrowed_history.backward_stack.iter())
2186 .chain(borrowed_history.closed_stack.iter())
2187 .for_each(|entry| {
2188 if let Some(project_and_abs_path) =
2189 borrowed_history.paths_by_item.get(&entry.item.id())
2190 {
2191 f(entry, project_and_abs_path.clone());
2192 } else if let Some(item) = entry.item.upgrade() {
2193 if let Some(path) = item.project_path(cx) {
2194 f(entry, (path, None));
2195 }
2196 }
2197 })
2198 }
2199
2200 pub fn set_mode(&mut self, mode: NavigationMode) {
2201 self.0.lock().mode = mode;
2202 }
2203
2204 pub fn mode(&self) -> NavigationMode {
2205 self.0.lock().mode
2206 }
2207
2208 pub fn disable(&mut self) {
2209 self.0.lock().mode = NavigationMode::Disabled;
2210 }
2211
2212 pub fn enable(&mut self) {
2213 self.0.lock().mode = NavigationMode::Normal;
2214 }
2215
2216 pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2217 let mut state = self.0.lock();
2218 let entry = match mode {
2219 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2220 return None
2221 }
2222 NavigationMode::GoingBack => &mut state.backward_stack,
2223 NavigationMode::GoingForward => &mut state.forward_stack,
2224 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2225 }
2226 .pop_back();
2227 if entry.is_some() {
2228 state.did_update(cx);
2229 }
2230 entry
2231 }
2232
2233 pub fn push<D: 'static + Send + Any>(
2234 &mut self,
2235 data: Option<D>,
2236 item: Arc<dyn WeakItemHandle>,
2237 cx: &mut WindowContext,
2238 ) {
2239 let state = &mut *self.0.lock();
2240 match state.mode {
2241 NavigationMode::Disabled => {}
2242 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2243 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2244 state.backward_stack.pop_front();
2245 }
2246 state.backward_stack.push_back(NavigationEntry {
2247 item,
2248 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2249 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2250 });
2251 state.forward_stack.clear();
2252 }
2253 NavigationMode::GoingBack => {
2254 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2255 state.forward_stack.pop_front();
2256 }
2257 state.forward_stack.push_back(NavigationEntry {
2258 item,
2259 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2260 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2261 });
2262 }
2263 NavigationMode::GoingForward => {
2264 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2265 state.backward_stack.pop_front();
2266 }
2267 state.backward_stack.push_back(NavigationEntry {
2268 item,
2269 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2270 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2271 });
2272 }
2273 NavigationMode::ClosingItem => {
2274 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2275 state.closed_stack.pop_front();
2276 }
2277 state.closed_stack.push_back(NavigationEntry {
2278 item,
2279 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2280 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2281 });
2282 }
2283 }
2284 state.did_update(cx);
2285 }
2286
2287 pub fn remove_item(&mut self, item_id: EntityId) {
2288 let mut state = self.0.lock();
2289 state.paths_by_item.remove(&item_id);
2290 state
2291 .backward_stack
2292 .retain(|entry| entry.item.id() != item_id);
2293 state
2294 .forward_stack
2295 .retain(|entry| entry.item.id() != item_id);
2296 state
2297 .closed_stack
2298 .retain(|entry| entry.item.id() != item_id);
2299 }
2300
2301 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2302 self.0.lock().paths_by_item.get(&item_id).cloned()
2303 }
2304}
2305
2306impl NavHistoryState {
2307 pub fn did_update(&self, cx: &mut WindowContext) {
2308 if let Some(pane) = self.pane.upgrade() {
2309 cx.defer(move |cx| {
2310 pane.update(cx, |pane, cx| pane.history_updated(cx));
2311 });
2312 }
2313 }
2314}
2315
2316// pub struct PaneBackdrop<V> {
2317// child_view: usize,
2318// child: AnyElement<V>,
2319// }
2320
2321// impl<V> PaneBackdrop<V> {
2322// pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2323// PaneBackdrop {
2324// child,
2325// child_view: pane_item_view,
2326// }
2327// }
2328// }
2329
2330// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2331// type LayoutState = ();
2332
2333// type PaintState = ();
2334
2335// fn layout(
2336// &mut self,
2337// constraint: gpui::SizeConstraint,
2338// view: &mut V,
2339// cx: &mut ViewContext<V>,
2340// ) -> (Vector2F, Self::LayoutState) {
2341// let size = self.child.layout(constraint, view, cx);
2342// (size, ())
2343// }
2344
2345// fn paint(
2346// &mut self,
2347// bounds: RectF,
2348// visible_bounds: RectF,
2349// _: &mut Self::LayoutState,
2350// view: &mut V,
2351// cx: &mut ViewContext<V>,
2352// ) -> Self::PaintState {
2353// let background = theme::current(cx).editor.background;
2354
2355// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2356
2357// cx.scene().push_quad(gpui::Quad {
2358// bounds: RectF::new(bounds.origin(), bounds.size()),
2359// background: Some(background),
2360// ..Default::default()
2361// });
2362
2363// let child_view_id = self.child_view;
2364// cx.scene().push_mouse_region(
2365// MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2366// gpui::platform::MouseButton::Left,
2367// move |_, _: &mut V, cx| {
2368// let window = cx.window();
2369// cx.app_context().focus(window, Some(child_view_id))
2370// },
2371// ),
2372// );
2373
2374// cx.scene().push_layer(Some(bounds));
2375// self.child.paint(bounds.origin(), visible_bounds, view, cx);
2376// cx.scene().pop_layer();
2377// }
2378
2379// fn rect_for_text_range(
2380// &self,
2381// range_utf16: std::ops::Range<usize>,
2382// _bounds: RectF,
2383// _visible_bounds: RectF,
2384// _layout: &Self::LayoutState,
2385// _paint: &Self::PaintState,
2386// view: &V,
2387// cx: &gpui::ViewContext<V>,
2388// ) -> Option<RectF> {
2389// self.child.rect_for_text_range(range_utf16, view, cx)
2390// }
2391
2392// fn debug(
2393// &self,
2394// _bounds: RectF,
2395// _layout: &Self::LayoutState,
2396// _paint: &Self::PaintState,
2397// view: &V,
2398// cx: &gpui::ViewContext<V>,
2399// ) -> serde_json::Value {
2400// gpui::json::json!({
2401// "type": "Pane Back Drop",
2402// "view": self.child_view,
2403// "child": self.child.debug(view, cx),
2404// })
2405// }
2406// }
2407
2408fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2409 let path = buffer_path
2410 .as_ref()
2411 .and_then(|p| p.path.to_str())
2412 .unwrap_or(&"This buffer");
2413 let path = truncate_and_remove_front(path, 80);
2414 format!("{path} contains unsaved edits. Do you want to save it?")
2415}
2416
2417// todo!("uncomment tests")
2418// #[cfg(test)]
2419// mod tests {
2420// use super::*;
2421// use crate::item::test::{TestItem, TestProjectItem};
2422// use gpui::TestAppContext;
2423// use project::FakeFs;
2424// use settings::SettingsStore;
2425
2426// #[gpui::test]
2427// async fn test_remove_active_empty(cx: &mut TestAppContext) {
2428// init_test(cx);
2429// let fs = FakeFs::new(cx.background());
2430
2431// let project = Project::test(fs, None, cx).await;
2432// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2433// let workspace = window.root(cx);
2434// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2435
2436// pane.update(cx, |pane, cx| {
2437// assert!(pane
2438// .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2439// .is_none())
2440// });
2441// }
2442
2443// #[gpui::test]
2444// async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2445// cx.foreground().forbid_parking();
2446// init_test(cx);
2447// let fs = FakeFs::new(cx.background());
2448
2449// let project = Project::test(fs, None, cx).await;
2450// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2451// let workspace = window.root(cx);
2452// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2453
2454// // 1. Add with a destination index
2455// // a. Add before the active item
2456// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2457// pane.update(cx, |pane, cx| {
2458// pane.add_item(
2459// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2460// false,
2461// false,
2462// Some(0),
2463// cx,
2464// );
2465// });
2466// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2467
2468// // b. Add after the active item
2469// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2470// pane.update(cx, |pane, cx| {
2471// pane.add_item(
2472// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2473// false,
2474// false,
2475// Some(2),
2476// cx,
2477// );
2478// });
2479// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2480
2481// // c. Add at the end of the item list (including off the length)
2482// set_labeled_items(&pane, ["A", "B*", "C"], cx);
2483// pane.update(cx, |pane, cx| {
2484// pane.add_item(
2485// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2486// false,
2487// false,
2488// Some(5),
2489// cx,
2490// );
2491// });
2492// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2493
2494// // 2. Add without a destination index
2495// // a. Add with active item at the start of the item list
2496// set_labeled_items(&pane, ["A*", "B", "C"], cx);
2497// pane.update(cx, |pane, cx| {
2498// pane.add_item(
2499// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2500// false,
2501// false,
2502// None,
2503// cx,
2504// );
2505// });
2506// set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2507
2508// // b. Add with active item at the end of the item list
2509// set_labeled_items(&pane, ["A", "B", "C*"], cx);
2510// pane.update(cx, |pane, cx| {
2511// pane.add_item(
2512// Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2513// false,
2514// false,
2515// None,
2516// cx,
2517// );
2518// });
2519// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2520// }
2521
2522// #[gpui::test]
2523// async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2524// cx.foreground().forbid_parking();
2525// init_test(cx);
2526// let fs = FakeFs::new(cx.background());
2527
2528// let project = Project::test(fs, None, cx).await;
2529// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2530// let workspace = window.root(cx);
2531// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2532
2533// // 1. Add with a destination index
2534// // 1a. Add before the active item
2535// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2536// pane.update(cx, |pane, cx| {
2537// pane.add_item(d, false, false, Some(0), cx);
2538// });
2539// assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2540
2541// // 1b. Add after the active item
2542// let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2543// pane.update(cx, |pane, cx| {
2544// pane.add_item(d, false, false, Some(2), cx);
2545// });
2546// assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2547
2548// // 1c. Add at the end of the item list (including off the length)
2549// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2550// pane.update(cx, |pane, cx| {
2551// pane.add_item(a, false, false, Some(5), cx);
2552// });
2553// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2554
2555// // 1d. Add same item to active index
2556// let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2557// pane.update(cx, |pane, cx| {
2558// pane.add_item(b, false, false, Some(1), cx);
2559// });
2560// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2561
2562// // 1e. Add item to index after same item in last position
2563// let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2564// pane.update(cx, |pane, cx| {
2565// pane.add_item(c, false, false, Some(2), cx);
2566// });
2567// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2568
2569// // 2. Add without a destination index
2570// // 2a. Add with active item at the start of the item list
2571// let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2572// pane.update(cx, |pane, cx| {
2573// pane.add_item(d, false, false, None, cx);
2574// });
2575// assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2576
2577// // 2b. Add with active item at the end of the item list
2578// let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2579// pane.update(cx, |pane, cx| {
2580// pane.add_item(a, false, false, None, cx);
2581// });
2582// assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2583
2584// // 2c. Add active item to active item at end of list
2585// let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2586// pane.update(cx, |pane, cx| {
2587// pane.add_item(c, false, false, None, cx);
2588// });
2589// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2590
2591// // 2d. Add active item to active item at start of list
2592// let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2593// pane.update(cx, |pane, cx| {
2594// pane.add_item(a, false, false, None, cx);
2595// });
2596// assert_item_labels(&pane, ["A*", "B", "C"], cx);
2597// }
2598
2599// #[gpui::test]
2600// async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2601// cx.foreground().forbid_parking();
2602// init_test(cx);
2603// let fs = FakeFs::new(cx.background());
2604
2605// let project = Project::test(fs, None, cx).await;
2606// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2607// let workspace = window.root(cx);
2608// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2609
2610// // singleton view
2611// pane.update(cx, |pane, cx| {
2612// let item = TestItem::new()
2613// .with_singleton(true)
2614// .with_label("buffer 1")
2615// .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2616
2617// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2618// });
2619// assert_item_labels(&pane, ["buffer 1*"], cx);
2620
2621// // new singleton view with the same project entry
2622// pane.update(cx, |pane, cx| {
2623// let item = TestItem::new()
2624// .with_singleton(true)
2625// .with_label("buffer 1")
2626// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2627
2628// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2629// });
2630// assert_item_labels(&pane, ["buffer 1*"], cx);
2631
2632// // new singleton view with different project entry
2633// pane.update(cx, |pane, cx| {
2634// let item = TestItem::new()
2635// .with_singleton(true)
2636// .with_label("buffer 2")
2637// .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2638// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2639// });
2640// assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2641
2642// // new multibuffer view with the same project entry
2643// pane.update(cx, |pane, cx| {
2644// let item = TestItem::new()
2645// .with_singleton(false)
2646// .with_label("multibuffer 1")
2647// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2648
2649// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2650// });
2651// assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2652
2653// // another multibuffer view with the same project entry
2654// pane.update(cx, |pane, cx| {
2655// let item = TestItem::new()
2656// .with_singleton(false)
2657// .with_label("multibuffer 1b")
2658// .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2659
2660// pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2661// });
2662// assert_item_labels(
2663// &pane,
2664// ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2665// cx,
2666// );
2667// }
2668
2669// #[gpui::test]
2670// async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2671// init_test(cx);
2672// let fs = FakeFs::new(cx.background());
2673
2674// let project = Project::test(fs, None, cx).await;
2675// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2676// let workspace = window.root(cx);
2677// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2678
2679// add_labeled_item(&pane, "A", false, cx);
2680// add_labeled_item(&pane, "B", false, cx);
2681// add_labeled_item(&pane, "C", false, cx);
2682// add_labeled_item(&pane, "D", false, cx);
2683// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2684
2685// pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2686// add_labeled_item(&pane, "1", false, cx);
2687// assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2688
2689// pane.update(cx, |pane, cx| {
2690// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2691// })
2692// .unwrap()
2693// .await
2694// .unwrap();
2695// assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2696
2697// pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2698// assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2699
2700// pane.update(cx, |pane, cx| {
2701// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2702// })
2703// .unwrap()
2704// .await
2705// .unwrap();
2706// assert_item_labels(&pane, ["A", "B*", "C"], cx);
2707
2708// pane.update(cx, |pane, cx| {
2709// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2710// })
2711// .unwrap()
2712// .await
2713// .unwrap();
2714// assert_item_labels(&pane, ["A", "C*"], cx);
2715
2716// pane.update(cx, |pane, cx| {
2717// pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2718// })
2719// .unwrap()
2720// .await
2721// .unwrap();
2722// assert_item_labels(&pane, ["A*"], cx);
2723// }
2724
2725// #[gpui::test]
2726// async fn test_close_inactive_items(cx: &mut TestAppContext) {
2727// init_test(cx);
2728// let fs = FakeFs::new(cx.background());
2729
2730// let project = Project::test(fs, None, cx).await;
2731// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2732// let workspace = window.root(cx);
2733// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2734
2735// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2736
2737// pane.update(cx, |pane, cx| {
2738// pane.close_inactive_items(&CloseInactiveItems, cx)
2739// })
2740// .unwrap()
2741// .await
2742// .unwrap();
2743// assert_item_labels(&pane, ["C*"], cx);
2744// }
2745
2746// #[gpui::test]
2747// async fn test_close_clean_items(cx: &mut TestAppContext) {
2748// init_test(cx);
2749// let fs = FakeFs::new(cx.background());
2750
2751// let project = Project::test(fs, None, cx).await;
2752// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2753// let workspace = window.root(cx);
2754// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2755
2756// add_labeled_item(&pane, "A", true, cx);
2757// add_labeled_item(&pane, "B", false, cx);
2758// add_labeled_item(&pane, "C", true, cx);
2759// add_labeled_item(&pane, "D", false, cx);
2760// add_labeled_item(&pane, "E", false, cx);
2761// assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2762
2763// pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2764// .unwrap()
2765// .await
2766// .unwrap();
2767// assert_item_labels(&pane, ["A^", "C*^"], cx);
2768// }
2769
2770// #[gpui::test]
2771// async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2772// init_test(cx);
2773// let fs = FakeFs::new(cx.background());
2774
2775// let project = Project::test(fs, None, cx).await;
2776// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2777// let workspace = window.root(cx);
2778// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2779
2780// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2781
2782// pane.update(cx, |pane, cx| {
2783// pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2784// })
2785// .unwrap()
2786// .await
2787// .unwrap();
2788// assert_item_labels(&pane, ["C*", "D", "E"], cx);
2789// }
2790
2791// #[gpui::test]
2792// async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2793// init_test(cx);
2794// let fs = FakeFs::new(cx.background());
2795
2796// let project = Project::test(fs, None, cx).await;
2797// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2798// let workspace = window.root(cx);
2799// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2800
2801// set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2802
2803// pane.update(cx, |pane, cx| {
2804// pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2805// })
2806// .unwrap()
2807// .await
2808// .unwrap();
2809// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2810// }
2811
2812// #[gpui::test]
2813// async fn test_close_all_items(cx: &mut TestAppContext) {
2814// init_test(cx);
2815// let fs = FakeFs::new(cx.background());
2816
2817// let project = Project::test(fs, None, cx).await;
2818// let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2819// let workspace = window.root(cx);
2820// let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2821
2822// add_labeled_item(&pane, "A", false, cx);
2823// add_labeled_item(&pane, "B", false, cx);
2824// add_labeled_item(&pane, "C", false, cx);
2825// assert_item_labels(&pane, ["A", "B", "C*"], cx);
2826
2827// pane.update(cx, |pane, cx| {
2828// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2829// })
2830// .unwrap()
2831// .await
2832// .unwrap();
2833// assert_item_labels(&pane, [], cx);
2834
2835// add_labeled_item(&pane, "A", true, cx);
2836// add_labeled_item(&pane, "B", true, cx);
2837// add_labeled_item(&pane, "C", true, cx);
2838// assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2839
2840// let save = pane
2841// .update(cx, |pane, cx| {
2842// pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2843// })
2844// .unwrap();
2845
2846// cx.foreground().run_until_parked();
2847// window.simulate_prompt_answer(2, cx);
2848// save.await.unwrap();
2849// assert_item_labels(&pane, [], cx);
2850// }
2851
2852// fn init_test(cx: &mut TestAppContext) {
2853// cx.update(|cx| {
2854// cx.set_global(SettingsStore::test(cx));
2855// theme::init((), cx);
2856// crate::init_settings(cx);
2857// Project::init_settings(cx);
2858// });
2859// }
2860
2861// fn add_labeled_item(
2862// pane: &ViewHandle<Pane>,
2863// label: &str,
2864// is_dirty: bool,
2865// cx: &mut TestAppContext,
2866// ) -> Box<ViewHandle<TestItem>> {
2867// pane.update(cx, |pane, cx| {
2868// let labeled_item =
2869// Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2870// pane.add_item(labeled_item.clone(), false, false, None, cx);
2871// labeled_item
2872// })
2873// }
2874
2875// fn set_labeled_items<const COUNT: usize>(
2876// pane: &ViewHandle<Pane>,
2877// labels: [&str; COUNT],
2878// cx: &mut TestAppContext,
2879// ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2880// pane.update(cx, |pane, cx| {
2881// pane.items.clear();
2882// let mut active_item_index = 0;
2883
2884// let mut index = 0;
2885// let items = labels.map(|mut label| {
2886// if label.ends_with("*") {
2887// label = label.trim_end_matches("*");
2888// active_item_index = index;
2889// }
2890
2891// let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2892// pane.add_item(labeled_item.clone(), false, false, None, cx);
2893// index += 1;
2894// labeled_item
2895// });
2896
2897// pane.activate_item(active_item_index, false, false, cx);
2898
2899// items
2900// })
2901// }
2902
2903// // Assert the item label, with the active item label suffixed with a '*'
2904// fn assert_item_labels<const COUNT: usize>(
2905// pane: &ViewHandle<Pane>,
2906// expected_states: [&str; COUNT],
2907// cx: &mut TestAppContext,
2908// ) {
2909// pane.read_with(cx, |pane, cx| {
2910// let actual_states = pane
2911// .items
2912// .iter()
2913// .enumerate()
2914// .map(|(ix, item)| {
2915// let mut state = item
2916// .as_any()
2917// .downcast_ref::<TestItem>()
2918// .unwrap()
2919// .read(cx)
2920// .label
2921// .clone();
2922// if ix == pane.active_item_index {
2923// state.push('*');
2924// }
2925// if item.is_dirty(cx) {
2926// state.push('^');
2927// }
2928// state
2929// })
2930// .collect::<Vec<_>>();
2931
2932// assert_eq!(
2933// actual_states, expected_states,
2934// "pane items do not match expectation"
2935// );
2936// })
2937// }
2938// }
2939
2940#[derive(Clone, Debug)]
2941struct DraggedTab {
2942 title: String,
2943}
2944
2945impl Render for DraggedTab {
2946 type Element = Div<Self>;
2947
2948 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2949 div().w_8().h_4().bg(gpui::red())
2950 }
2951}