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