1use super::{ItemHandle, SplitDirection};
2use crate::{toolbar::Toolbar, Item, WeakItemHandle, Workspace};
3use anyhow::Result;
4use collections::{HashMap, HashSet, VecDeque};
5use futures::StreamExt;
6use gpui::{
7 actions,
8 elements::*,
9 geometry::{rect::RectF, vector::vec2f},
10 impl_actions, impl_internal_actions,
11 platform::{CursorStyle, NavigationDirection},
12 AppContext, AsyncAppContext, Entity, ModelHandle, MutableAppContext, PromptLevel, Quad,
13 RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
14};
15use project::{Project, ProjectEntryId, ProjectPath};
16use serde::Deserialize;
17use settings::Settings;
18use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
19use util::ResultExt;
20
21actions!(
22 pane,
23 [
24 ActivatePrevItem,
25 ActivateNextItem,
26 CloseActiveItem,
27 CloseInactiveItems,
28 ]
29);
30
31#[derive(Clone, Deserialize)]
32pub struct Split(pub SplitDirection);
33
34#[derive(Clone)]
35pub struct CloseItem {
36 pub item_id: usize,
37 pub pane: WeakViewHandle<Pane>,
38}
39
40#[derive(Clone, Deserialize)]
41pub struct ActivateItem(pub usize);
42
43#[derive(Clone, Deserialize)]
44pub struct GoBack {
45 #[serde(skip_deserializing)]
46 pub pane: Option<WeakViewHandle<Pane>>,
47}
48
49#[derive(Clone, Deserialize)]
50pub struct GoForward {
51 #[serde(skip_deserializing)]
52 pub pane: Option<WeakViewHandle<Pane>>,
53}
54
55impl_actions!(pane, [Split, GoBack, GoForward]);
56impl_internal_actions!(pane, [CloseItem, ActivateItem]);
57
58const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
59
60pub fn init(cx: &mut MutableAppContext) {
61 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
62 pane.activate_item(action.0, true, true, cx);
63 });
64 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
65 pane.activate_prev_item(cx);
66 });
67 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
68 pane.activate_next_item(cx);
69 });
70 cx.add_async_action(Pane::close_active_item);
71 cx.add_async_action(Pane::close_inactive_items);
72 cx.add_async_action(|workspace: &mut Workspace, action: &CloseItem, cx| {
73 let pane = action.pane.upgrade(cx)?;
74 let task = Pane::close_item(workspace, pane, action.item_id, cx);
75 Some(cx.foreground().spawn(async move {
76 task.await?;
77 Ok(())
78 }))
79 });
80 cx.add_action(|pane: &mut Pane, action: &Split, cx| {
81 pane.split(action.0, cx);
82 });
83 cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
84 Pane::go_back(
85 workspace,
86 action
87 .pane
88 .as_ref()
89 .and_then(|weak_handle| weak_handle.upgrade(cx)),
90 cx,
91 )
92 .detach();
93 });
94 cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
95 Pane::go_forward(
96 workspace,
97 action
98 .pane
99 .as_ref()
100 .and_then(|weak_handle| weak_handle.upgrade(cx)),
101 cx,
102 )
103 .detach();
104 });
105}
106
107pub enum Event {
108 Activate,
109 ActivateItem { local: bool },
110 Remove,
111 Split(SplitDirection),
112}
113
114pub struct Pane {
115 items: Vec<Box<dyn ItemHandle>>,
116 active_item_index: usize,
117 autoscroll: bool,
118 nav_history: Rc<RefCell<NavHistory>>,
119 toolbar: ViewHandle<Toolbar>,
120}
121
122pub struct ItemNavHistory {
123 history: Rc<RefCell<NavHistory>>,
124 item: Rc<dyn WeakItemHandle>,
125}
126
127#[derive(Default)]
128pub struct NavHistory {
129 mode: NavigationMode,
130 backward_stack: VecDeque<NavigationEntry>,
131 forward_stack: VecDeque<NavigationEntry>,
132 paths_by_item: HashMap<usize, ProjectPath>,
133}
134
135#[derive(Copy, Clone)]
136enum NavigationMode {
137 Normal,
138 GoingBack,
139 GoingForward,
140 Disabled,
141}
142
143impl Default for NavigationMode {
144 fn default() -> Self {
145 Self::Normal
146 }
147}
148
149pub struct NavigationEntry {
150 pub item: Rc<dyn WeakItemHandle>,
151 pub data: Option<Box<dyn Any>>,
152}
153
154impl Pane {
155 pub fn new(cx: &mut ViewContext<Self>) -> Self {
156 Self {
157 items: Vec::new(),
158 active_item_index: 0,
159 autoscroll: false,
160 nav_history: Default::default(),
161 toolbar: cx.add_view(|_| Toolbar::new()),
162 }
163 }
164
165 pub fn nav_history(&self) -> &Rc<RefCell<NavHistory>> {
166 &self.nav_history
167 }
168
169 pub fn activate(&self, cx: &mut ViewContext<Self>) {
170 cx.emit(Event::Activate);
171 }
172
173 pub fn go_back(
174 workspace: &mut Workspace,
175 pane: Option<ViewHandle<Pane>>,
176 cx: &mut ViewContext<Workspace>,
177 ) -> Task<()> {
178 Self::navigate_history(
179 workspace,
180 pane.unwrap_or_else(|| workspace.active_pane().clone()),
181 NavigationMode::GoingBack,
182 cx,
183 )
184 }
185
186 pub fn go_forward(
187 workspace: &mut Workspace,
188 pane: Option<ViewHandle<Pane>>,
189 cx: &mut ViewContext<Workspace>,
190 ) -> Task<()> {
191 Self::navigate_history(
192 workspace,
193 pane.unwrap_or_else(|| workspace.active_pane().clone()),
194 NavigationMode::GoingForward,
195 cx,
196 )
197 }
198
199 fn navigate_history(
200 workspace: &mut Workspace,
201 pane: ViewHandle<Pane>,
202 mode: NavigationMode,
203 cx: &mut ViewContext<Workspace>,
204 ) -> Task<()> {
205 workspace.activate_pane(pane.clone(), cx);
206
207 let to_load = pane.update(cx, |pane, cx| {
208 loop {
209 // Retrieve the weak item handle from the history.
210 let entry = pane.nav_history.borrow_mut().pop(mode)?;
211
212 // If the item is still present in this pane, then activate it.
213 if let Some(index) = entry
214 .item
215 .upgrade(cx)
216 .and_then(|v| pane.index_for_item(v.as_ref()))
217 {
218 let prev_active_item_index = pane.active_item_index;
219 pane.nav_history.borrow_mut().set_mode(mode);
220 pane.activate_item(index, true, true, cx);
221 pane.nav_history
222 .borrow_mut()
223 .set_mode(NavigationMode::Normal);
224
225 let mut navigated = prev_active_item_index != pane.active_item_index;
226 if let Some(data) = entry.data {
227 navigated |= pane.active_item()?.navigate(data, cx);
228 }
229
230 if navigated {
231 break None;
232 }
233 }
234 // If the item is no longer present in this pane, then retrieve its
235 // project path in order to reopen it.
236 else {
237 break pane
238 .nav_history
239 .borrow_mut()
240 .paths_by_item
241 .get(&entry.item.id())
242 .cloned()
243 .map(|project_path| (project_path, entry));
244 }
245 }
246 });
247
248 if let Some((project_path, entry)) = to_load {
249 // If the item was no longer present, then load it again from its previous path.
250 let pane = pane.downgrade();
251 let task = workspace.load_path(project_path, cx);
252 cx.spawn(|workspace, mut cx| async move {
253 let task = task.await;
254 if let Some(pane) = pane.upgrade(&cx) {
255 if let Some((project_entry_id, build_item)) = task.log_err() {
256 pane.update(&mut cx, |pane, _| {
257 pane.nav_history.borrow_mut().set_mode(mode);
258 });
259 let item = workspace.update(&mut cx, |workspace, cx| {
260 Self::open_item(
261 workspace,
262 pane.clone(),
263 project_entry_id,
264 true,
265 cx,
266 build_item,
267 )
268 });
269 pane.update(&mut cx, |pane, cx| {
270 pane.nav_history
271 .borrow_mut()
272 .set_mode(NavigationMode::Normal);
273 if let Some(data) = entry.data {
274 item.navigate(data, cx);
275 }
276 });
277 } else {
278 workspace
279 .update(&mut cx, |workspace, cx| {
280 Self::navigate_history(workspace, pane, mode, cx)
281 })
282 .await;
283 }
284 }
285 })
286 } else {
287 Task::ready(())
288 }
289 }
290
291 pub(crate) fn open_item(
292 workspace: &mut Workspace,
293 pane: ViewHandle<Pane>,
294 project_entry_id: ProjectEntryId,
295 focus_item: bool,
296 cx: &mut ViewContext<Workspace>,
297 build_item: impl FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
298 ) -> Box<dyn ItemHandle> {
299 let existing_item = pane.update(cx, |pane, cx| {
300 for (ix, item) in pane.items.iter().enumerate() {
301 if item.project_entry_ids(cx).as_slice() == &[project_entry_id] {
302 let item = item.boxed_clone();
303 pane.activate_item(ix, true, focus_item, cx);
304 return Some(item);
305 }
306 }
307 None
308 });
309 if let Some(existing_item) = existing_item {
310 existing_item
311 } else {
312 let item = build_item(cx);
313 Self::add_item(workspace, pane, item.boxed_clone(), true, focus_item, cx);
314 item
315 }
316 }
317
318 pub(crate) fn add_item(
319 workspace: &mut Workspace,
320 pane: ViewHandle<Pane>,
321 item: Box<dyn ItemHandle>,
322 activate_pane: bool,
323 focus_item: bool,
324 cx: &mut ViewContext<Workspace>,
325 ) {
326 // Prevent adding the same item to the pane more than once.
327 if let Some(item_ix) = pane.read(cx).items.iter().position(|i| i.id() == item.id()) {
328 pane.update(cx, |pane, cx| {
329 pane.activate_item(item_ix, activate_pane, focus_item, cx)
330 });
331 return;
332 }
333
334 item.set_nav_history(pane.read(cx).nav_history.clone(), cx);
335 item.added_to_pane(workspace, pane.clone(), cx);
336 pane.update(cx, |pane, cx| {
337 let item_idx = cmp::min(pane.active_item_index + 1, pane.items.len());
338 pane.items.insert(item_idx, item);
339 pane.activate_item(item_idx, activate_pane, focus_item, cx);
340 cx.notify();
341 });
342 }
343
344 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
345 self.items.iter()
346 }
347
348 pub fn items_of_type<'a, T: View>(&'a self) -> impl 'a + Iterator<Item = ViewHandle<T>> {
349 self.items
350 .iter()
351 .filter_map(|item| item.to_any().downcast())
352 }
353
354 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
355 self.items.get(self.active_item_index).cloned()
356 }
357
358 pub fn item_for_entry(
359 &self,
360 entry_id: ProjectEntryId,
361 cx: &AppContext,
362 ) -> Option<Box<dyn ItemHandle>> {
363 self.items.iter().find_map(|item| {
364 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == &[entry_id] {
365 Some(item.boxed_clone())
366 } else {
367 None
368 }
369 })
370 }
371
372 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
373 self.items.iter().position(|i| i.id() == item.id())
374 }
375
376 pub fn activate_item(
377 &mut self,
378 index: usize,
379 activate_pane: bool,
380 focus_item: bool,
381 cx: &mut ViewContext<Self>,
382 ) {
383 use NavigationMode::{GoingBack, GoingForward};
384 if index < self.items.len() {
385 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
386 if matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
387 || (prev_active_item_ix != self.active_item_index
388 && prev_active_item_ix < self.items.len())
389 {
390 self.items[prev_active_item_ix].deactivated(cx);
391 cx.emit(Event::ActivateItem {
392 local: activate_pane,
393 });
394 }
395 self.update_toolbar(cx);
396 if focus_item {
397 self.focus_active_item(cx);
398 }
399 if activate_pane {
400 self.activate(cx);
401 }
402 self.autoscroll = true;
403 cx.notify();
404 }
405 }
406
407 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
408 let mut index = self.active_item_index;
409 if index > 0 {
410 index -= 1;
411 } else if self.items.len() > 0 {
412 index = self.items.len() - 1;
413 }
414 self.activate_item(index, true, true, cx);
415 }
416
417 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
418 let mut index = self.active_item_index;
419 if index + 1 < self.items.len() {
420 index += 1;
421 } else {
422 index = 0;
423 }
424 self.activate_item(index, true, true, cx);
425 }
426
427 fn close_active_item(
428 workspace: &mut Workspace,
429 _: &CloseActiveItem,
430 cx: &mut ViewContext<Workspace>,
431 ) -> Option<Task<Result<()>>> {
432 let pane_handle = workspace.active_pane().clone();
433 let pane = pane_handle.read(cx);
434 if pane.items.is_empty() {
435 None
436 } else {
437 let item_id_to_close = pane.items[pane.active_item_index].id();
438 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
439 item_id == item_id_to_close
440 });
441 Some(cx.foreground().spawn(async move {
442 task.await?;
443 Ok(())
444 }))
445 }
446 }
447
448 pub fn close_inactive_items(
449 workspace: &mut Workspace,
450 _: &CloseInactiveItems,
451 cx: &mut ViewContext<Workspace>,
452 ) -> Option<Task<Result<()>>> {
453 let pane_handle = workspace.active_pane().clone();
454 let pane = pane_handle.read(cx);
455 if pane.items.is_empty() {
456 None
457 } else {
458 let active_item_id = pane.items[pane.active_item_index].id();
459 let task =
460 Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
461 Some(cx.foreground().spawn(async move {
462 task.await?;
463 Ok(())
464 }))
465 }
466 }
467
468 pub fn close_item(
469 workspace: &mut Workspace,
470 pane: ViewHandle<Pane>,
471 item_id_to_close: usize,
472 cx: &mut ViewContext<Workspace>,
473 ) -> Task<Result<bool>> {
474 Self::close_items(workspace, pane, cx, move |view_id| {
475 view_id == item_id_to_close
476 })
477 }
478
479 pub fn close_items(
480 workspace: &mut Workspace,
481 pane: ViewHandle<Pane>,
482 cx: &mut ViewContext<Workspace>,
483 should_close: impl 'static + Fn(usize) -> bool,
484 ) -> Task<Result<bool>> {
485 let project = workspace.project().clone();
486
487 // Find the items to close.
488 let mut items_to_close = Vec::new();
489 for item in &pane.read(cx).items {
490 if should_close(item.id()) {
491 items_to_close.push(item.boxed_clone());
492 }
493 }
494
495 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
496 // to focus the singleton buffer when prompting to save that buffer, as opposed
497 // to focusing the multibuffer, because this gives the user a more clear idea
498 // of what content they would be saving.
499 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
500
501 cx.spawn(|workspace, mut cx| async move {
502 let mut saved_project_entry_ids = HashSet::default();
503 for item in items_to_close.clone() {
504 // Find the item's current index and its set of project entries. Avoid
505 // storing these in advance, in case they have changed since this task
506 // was started.
507 let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
508 (pane.index_for_item(&*item), item.project_entry_ids(cx))
509 });
510 let item_ix = if let Some(ix) = item_ix {
511 ix
512 } else {
513 continue;
514 };
515
516 // If an item hasn't yet been associated with a project entry, then always
517 // prompt to save it before closing it. Otherwise, check if the item has
518 // any project entries that are not open anywhere else in the workspace,
519 // AND that the user has not already been prompted to save. If there are
520 // any such project entries, prompt the user to save this item.
521 let should_save = if project_entry_ids.is_empty() {
522 true
523 } else {
524 workspace.read_with(&cx, |workspace, cx| {
525 for item in workspace.items(cx) {
526 if !items_to_close
527 .iter()
528 .any(|item_to_close| item_to_close.id() == item.id())
529 {
530 let other_project_entry_ids = item.project_entry_ids(cx);
531 project_entry_ids
532 .retain(|id| !other_project_entry_ids.contains(&id));
533 }
534 }
535 });
536 project_entry_ids
537 .iter()
538 .any(|id| saved_project_entry_ids.insert(*id))
539 };
540
541 if should_save {
542 if !Self::save_item(project.clone(), &pane, item_ix, &item, true, &mut cx)
543 .await?
544 {
545 break;
546 }
547 }
548
549 // Remove the item from the pane.
550 pane.update(&mut cx, |pane, cx| {
551 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
552 if item_ix == pane.active_item_index {
553 if item_ix + 1 < pane.items.len() {
554 pane.activate_next_item(cx);
555 } else if item_ix > 0 {
556 pane.activate_prev_item(cx);
557 }
558 }
559
560 let item = pane.items.remove(item_ix);
561 if pane.items.is_empty() {
562 item.deactivated(cx);
563 pane.update_toolbar(cx);
564 cx.emit(Event::Remove);
565 }
566
567 if item_ix < pane.active_item_index {
568 pane.active_item_index -= 1;
569 }
570
571 let mut nav_history = pane.nav_history.borrow_mut();
572 if let Some(path) = item.project_path(cx) {
573 nav_history.paths_by_item.insert(item.id(), path);
574 } else {
575 nav_history.paths_by_item.remove(&item.id());
576 }
577 }
578 });
579 }
580
581 pane.update(&mut cx, |_, cx| cx.notify());
582 Ok(true)
583 })
584 }
585
586 pub async fn save_item(
587 project: ModelHandle<Project>,
588 pane: &ViewHandle<Pane>,
589 item_ix: usize,
590 item: &Box<dyn ItemHandle>,
591 should_prompt_for_save: bool,
592 cx: &mut AsyncAppContext,
593 ) -> Result<bool> {
594 const CONFLICT_MESSAGE: &'static str =
595 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
596 const DIRTY_MESSAGE: &'static str =
597 "This file contains unsaved edits. Do you want to save it?";
598
599 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
600 (
601 item.has_conflict(cx),
602 item.is_dirty(cx),
603 item.can_save(cx),
604 item.is_singleton(cx),
605 )
606 });
607
608 if has_conflict && can_save {
609 let mut answer = pane.update(cx, |pane, cx| {
610 pane.activate_item(item_ix, true, true, cx);
611 cx.prompt(
612 PromptLevel::Warning,
613 CONFLICT_MESSAGE,
614 &["Overwrite", "Discard", "Cancel"],
615 )
616 });
617 match answer.next().await {
618 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
619 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
620 _ => return Ok(false),
621 }
622 } else if is_dirty && (can_save || is_singleton) {
623 let should_save = if should_prompt_for_save {
624 let mut answer = pane.update(cx, |pane, cx| {
625 pane.activate_item(item_ix, true, true, cx);
626 cx.prompt(
627 PromptLevel::Warning,
628 DIRTY_MESSAGE,
629 &["Save", "Don't Save", "Cancel"],
630 )
631 });
632 match answer.next().await {
633 Some(0) => true,
634 Some(1) => false,
635 _ => return Ok(false),
636 }
637 } else {
638 true
639 };
640
641 if should_save {
642 if can_save {
643 cx.update(|cx| item.save(project, cx)).await?;
644 } else if is_singleton {
645 let start_abs_path = project
646 .read_with(cx, |project, cx| {
647 let worktree = project.visible_worktrees(cx).next()?;
648 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
649 })
650 .unwrap_or(Path::new("").into());
651
652 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
653 if let Some(abs_path) = abs_path.next().await.flatten() {
654 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
655 } else {
656 return Ok(false);
657 }
658 }
659 }
660 }
661 Ok(true)
662 }
663
664 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
665 if let Some(active_item) = self.active_item() {
666 cx.focus(active_item);
667 }
668 }
669
670 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
671 cx.emit(Event::Split(direction));
672 }
673
674 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
675 &self.toolbar
676 }
677
678 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
679 let active_item = self
680 .items
681 .get(self.active_item_index)
682 .map(|item| item.as_ref());
683 self.toolbar.update(cx, |toolbar, cx| {
684 toolbar.set_active_pane_item(active_item, cx);
685 });
686 }
687
688 fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
689 let theme = cx.global::<Settings>().theme.clone();
690
691 enum Tabs {}
692 let pane = cx.handle();
693 let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
694 let autoscroll = if mem::take(&mut self.autoscroll) {
695 Some(self.active_item_index)
696 } else {
697 None
698 };
699 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
700 for (ix, item) in self.items.iter().enumerate() {
701 let is_active = ix == self.active_item_index;
702
703 row.add_child({
704 let tab_style = if is_active {
705 theme.workspace.active_tab.clone()
706 } else {
707 theme.workspace.tab.clone()
708 };
709 let title = item.tab_content(&tab_style, cx);
710
711 let mut style = if is_active {
712 theme.workspace.active_tab.clone()
713 } else {
714 theme.workspace.tab.clone()
715 };
716 if ix == 0 {
717 style.container.border.left = false;
718 }
719
720 EventHandler::new(
721 Container::new(
722 Flex::row()
723 .with_child(
724 Align::new({
725 let diameter = 7.0;
726 let icon_color = if item.has_conflict(cx) {
727 Some(style.icon_conflict)
728 } else if item.is_dirty(cx) {
729 Some(style.icon_dirty)
730 } else {
731 None
732 };
733
734 ConstrainedBox::new(
735 Canvas::new(move |bounds, _, cx| {
736 if let Some(color) = icon_color {
737 let square = RectF::new(
738 bounds.origin(),
739 vec2f(diameter, diameter),
740 );
741 cx.scene.push_quad(Quad {
742 bounds: square,
743 background: Some(color),
744 border: Default::default(),
745 corner_radius: diameter / 2.,
746 });
747 }
748 })
749 .boxed(),
750 )
751 .with_width(diameter)
752 .with_height(diameter)
753 .boxed()
754 })
755 .boxed(),
756 )
757 .with_child(
758 Container::new(Align::new(title).boxed())
759 .with_style(ContainerStyle {
760 margin: Margin {
761 left: style.spacing,
762 right: style.spacing,
763 ..Default::default()
764 },
765 ..Default::default()
766 })
767 .boxed(),
768 )
769 .with_child(
770 Align::new(
771 ConstrainedBox::new(if mouse_state.hovered {
772 let item_id = item.id();
773 enum TabCloseButton {}
774 let icon = Svg::new("icons/x.svg");
775 MouseEventHandler::new::<TabCloseButton, _, _>(
776 item_id,
777 cx,
778 |mouse_state, _| {
779 if mouse_state.hovered {
780 icon.with_color(style.icon_close_active)
781 .boxed()
782 } else {
783 icon.with_color(style.icon_close).boxed()
784 }
785 },
786 )
787 .with_padding(Padding::uniform(4.))
788 .with_cursor_style(CursorStyle::PointingHand)
789 .on_click({
790 let pane = pane.clone();
791 move |_, cx| {
792 cx.dispatch_action(CloseItem {
793 item_id,
794 pane: pane.clone(),
795 })
796 }
797 })
798 .named("close-tab-icon")
799 } else {
800 Empty::new().boxed()
801 })
802 .with_width(style.icon_width)
803 .boxed(),
804 )
805 .boxed(),
806 )
807 .boxed(),
808 )
809 .with_style(style.container)
810 .boxed(),
811 )
812 .on_mouse_down(move |cx| {
813 cx.dispatch_action(ActivateItem(ix));
814 true
815 })
816 .boxed()
817 })
818 }
819
820 row.add_child(
821 Empty::new()
822 .contained()
823 .with_border(theme.workspace.tab.container.border)
824 .flex(0., true)
825 .named("filler"),
826 );
827
828 row.boxed()
829 });
830
831 ConstrainedBox::new(tabs.boxed())
832 .with_height(theme.workspace.tab.height)
833 .named("tabs")
834 }
835}
836
837impl Entity for Pane {
838 type Event = Event;
839}
840
841impl View for Pane {
842 fn ui_name() -> &'static str {
843 "Pane"
844 }
845
846 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
847 let this = cx.handle();
848
849 EventHandler::new(if let Some(active_item) = self.active_item() {
850 Flex::column()
851 .with_child(self.render_tabs(cx))
852 .with_child(ChildView::new(&self.toolbar).boxed())
853 .with_child(ChildView::new(active_item).flex(1., true).boxed())
854 .boxed()
855 } else {
856 Empty::new().boxed()
857 })
858 .on_navigate_mouse_down(move |direction, cx| {
859 let this = this.clone();
860 match direction {
861 NavigationDirection::Back => cx.dispatch_action(GoBack { pane: Some(this) }),
862 NavigationDirection::Forward => cx.dispatch_action(GoForward { pane: Some(this) }),
863 }
864
865 true
866 })
867 .named("pane")
868 }
869
870 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
871 self.focus_active_item(cx);
872 }
873}
874
875impl ItemNavHistory {
876 pub fn new<T: Item>(history: Rc<RefCell<NavHistory>>, item: &ViewHandle<T>) -> Self {
877 Self {
878 history,
879 item: Rc::new(item.downgrade()),
880 }
881 }
882
883 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
884 self.history.clone()
885 }
886
887 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
888 self.history.borrow_mut().push(data, self.item.clone());
889 }
890}
891
892impl NavHistory {
893 pub fn disable(&mut self) {
894 self.mode = NavigationMode::Disabled;
895 }
896
897 pub fn enable(&mut self) {
898 self.mode = NavigationMode::Normal;
899 }
900
901 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
902 self.backward_stack.pop_back()
903 }
904
905 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
906 self.forward_stack.pop_back()
907 }
908
909 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
910 match mode {
911 NavigationMode::Normal | NavigationMode::Disabled => None,
912 NavigationMode::GoingBack => self.pop_backward(),
913 NavigationMode::GoingForward => self.pop_forward(),
914 }
915 }
916
917 fn set_mode(&mut self, mode: NavigationMode) {
918 self.mode = mode;
919 }
920
921 pub fn push<D: 'static + Any>(&mut self, data: Option<D>, item: Rc<dyn WeakItemHandle>) {
922 match self.mode {
923 NavigationMode::Disabled => {}
924 NavigationMode::Normal => {
925 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
926 self.backward_stack.pop_front();
927 }
928 self.backward_stack.push_back(NavigationEntry {
929 item,
930 data: data.map(|data| Box::new(data) as Box<dyn Any>),
931 });
932 self.forward_stack.clear();
933 }
934 NavigationMode::GoingBack => {
935 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
936 self.forward_stack.pop_front();
937 }
938 self.forward_stack.push_back(NavigationEntry {
939 item,
940 data: data.map(|data| Box::new(data) as Box<dyn Any>),
941 });
942 }
943 NavigationMode::GoingForward => {
944 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
945 self.backward_stack.pop_front();
946 }
947 self.backward_stack.push_back(NavigationEntry {
948 item,
949 data: data.map(|data| Box::new(data) as Box<dyn Any>),
950 });
951 }
952 }
953 }
954}