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