1use super::{ItemHandle, SplitDirection};
2use crate::{toolbar::Toolbar, Item, WeakItemHandle, Workspace};
3use anyhow::Result;
4use collections::{HashMap, 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.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 which 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 cx.spawn(|workspace, mut cx| async move {
496 for item in items_to_close.clone() {
497 let (item_ix, project_entry_ids) = pane.read_with(&cx, |pane, cx| {
498 (
499 pane.index_for_item(item.as_ref()),
500 item.project_entry_ids(cx),
501 )
502 });
503
504 let item_ix = if let Some(ix) = item_ix {
505 ix
506 } else {
507 continue;
508 };
509
510 // An item should be saved if either it has *no* project entries, or if it
511 // has project entries that don't exist anywhere else in the workspace.
512 let mut should_save = project_entry_ids.is_empty();
513 let mut project_entry_ids_to_save = project_entry_ids;
514 workspace.read_with(&cx, |workspace, cx| {
515 for item in workspace.items(cx) {
516 if !items_to_close
517 .iter()
518 .any(|item_to_close| item_to_close.id() == item.id())
519 {
520 let project_entry_ids = item.project_entry_ids(cx);
521 project_entry_ids_to_save.retain(|id| !project_entry_ids.contains(&id));
522 }
523 }
524 });
525 if !project_entry_ids_to_save.is_empty() {
526 should_save = true;
527 }
528
529 if should_save
530 && !Self::save_item(project.clone(), &pane, item_ix, &item, true, &mut cx)
531 .await?
532 {
533 break;
534 }
535
536 pane.update(&mut cx, |pane, cx| {
537 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
538 if item_ix == pane.active_item_index {
539 if item_ix + 1 < pane.items.len() {
540 pane.activate_next_item(cx);
541 } else if item_ix > 0 {
542 pane.activate_prev_item(cx);
543 }
544 }
545
546 let item = pane.items.remove(item_ix);
547 if pane.items.is_empty() {
548 item.deactivated(cx);
549 pane.update_toolbar(cx);
550 cx.emit(Event::Remove);
551 }
552
553 if item_ix < pane.active_item_index {
554 pane.active_item_index -= 1;
555 }
556
557 let mut nav_history = pane.nav_history.borrow_mut();
558 if let Some(path) = item.project_path(cx) {
559 nav_history.paths_by_item.insert(item.id(), path);
560 } else {
561 nav_history.paths_by_item.remove(&item.id());
562 }
563 }
564 });
565 }
566
567 pane.update(&mut cx, |_, cx| cx.notify());
568 Ok(true)
569 })
570 }
571
572 pub async fn save_item(
573 project: ModelHandle<Project>,
574 pane: &ViewHandle<Pane>,
575 item_ix: usize,
576 item: &Box<dyn ItemHandle>,
577 should_prompt_for_save: bool,
578 cx: &mut AsyncAppContext,
579 ) -> Result<bool> {
580 const CONFLICT_MESSAGE: &'static str =
581 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
582 const DIRTY_MESSAGE: &'static str =
583 "This file contains unsaved edits. Do you want to save it?";
584
585 let (has_conflict, is_dirty, can_save, can_save_as) = cx.read(|cx| {
586 (
587 item.has_conflict(cx),
588 item.is_dirty(cx),
589 item.can_save(cx),
590 item.can_save_as(cx),
591 )
592 });
593
594 if has_conflict && can_save {
595 let mut answer = pane.update(cx, |pane, cx| {
596 pane.activate_item(item_ix, true, true, cx);
597 cx.prompt(
598 PromptLevel::Warning,
599 CONFLICT_MESSAGE,
600 &["Overwrite", "Discard", "Cancel"],
601 )
602 });
603 match answer.next().await {
604 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
605 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
606 _ => return Ok(false),
607 }
608 } else if is_dirty && (can_save || can_save_as) {
609 let should_save = if should_prompt_for_save {
610 let mut answer = pane.update(cx, |pane, cx| {
611 pane.activate_item(item_ix, true, true, cx);
612 cx.prompt(
613 PromptLevel::Warning,
614 DIRTY_MESSAGE,
615 &["Save", "Don't Save", "Cancel"],
616 )
617 });
618 match answer.next().await {
619 Some(0) => true,
620 Some(1) => false,
621 _ => return Ok(false),
622 }
623 } else {
624 true
625 };
626
627 if should_save {
628 if can_save {
629 cx.update(|cx| item.save(project, cx)).await?;
630 } else if can_save_as {
631 let start_abs_path = project
632 .read_with(cx, |project, cx| {
633 let worktree = project.visible_worktrees(cx).next()?;
634 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
635 })
636 .unwrap_or(Path::new("").into());
637
638 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
639 if let Some(abs_path) = abs_path.next().await.flatten() {
640 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
641 } else {
642 return Ok(false);
643 }
644 }
645 }
646 }
647 Ok(true)
648 }
649
650 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
651 if let Some(active_item) = self.active_item() {
652 cx.focus(active_item);
653 }
654 }
655
656 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
657 cx.emit(Event::Split(direction));
658 }
659
660 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
661 &self.toolbar
662 }
663
664 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
665 let active_item = self
666 .items
667 .get(self.active_item_index)
668 .map(|item| item.as_ref());
669 self.toolbar.update(cx, |toolbar, cx| {
670 toolbar.set_active_pane_item(active_item, cx);
671 });
672 }
673
674 fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
675 let theme = cx.global::<Settings>().theme.clone();
676
677 enum Tabs {}
678 let pane = cx.handle();
679 let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
680 let autoscroll = if mem::take(&mut self.autoscroll) {
681 Some(self.active_item_index)
682 } else {
683 None
684 };
685 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
686 for (ix, item) in self.items.iter().enumerate() {
687 let is_active = ix == self.active_item_index;
688
689 row.add_child({
690 let tab_style = if is_active {
691 theme.workspace.active_tab.clone()
692 } else {
693 theme.workspace.tab.clone()
694 };
695 let title = item.tab_content(&tab_style, cx);
696
697 let mut style = if is_active {
698 theme.workspace.active_tab.clone()
699 } else {
700 theme.workspace.tab.clone()
701 };
702 if ix == 0 {
703 style.container.border.left = false;
704 }
705
706 EventHandler::new(
707 Container::new(
708 Flex::row()
709 .with_child(
710 Align::new({
711 let diameter = 7.0;
712 let icon_color = if item.has_conflict(cx) {
713 Some(style.icon_conflict)
714 } else if item.is_dirty(cx) {
715 Some(style.icon_dirty)
716 } else {
717 None
718 };
719
720 ConstrainedBox::new(
721 Canvas::new(move |bounds, _, cx| {
722 if let Some(color) = icon_color {
723 let square = RectF::new(
724 bounds.origin(),
725 vec2f(diameter, diameter),
726 );
727 cx.scene.push_quad(Quad {
728 bounds: square,
729 background: Some(color),
730 border: Default::default(),
731 corner_radius: diameter / 2.,
732 });
733 }
734 })
735 .boxed(),
736 )
737 .with_width(diameter)
738 .with_height(diameter)
739 .boxed()
740 })
741 .boxed(),
742 )
743 .with_child(
744 Container::new(Align::new(title).boxed())
745 .with_style(ContainerStyle {
746 margin: Margin {
747 left: style.spacing,
748 right: style.spacing,
749 ..Default::default()
750 },
751 ..Default::default()
752 })
753 .boxed(),
754 )
755 .with_child(
756 Align::new(
757 ConstrainedBox::new(if mouse_state.hovered {
758 let item_id = item.id();
759 enum TabCloseButton {}
760 let icon = Svg::new("icons/x.svg");
761 MouseEventHandler::new::<TabCloseButton, _, _>(
762 item_id,
763 cx,
764 |mouse_state, _| {
765 if mouse_state.hovered {
766 icon.with_color(style.icon_close_active)
767 .boxed()
768 } else {
769 icon.with_color(style.icon_close).boxed()
770 }
771 },
772 )
773 .with_padding(Padding::uniform(4.))
774 .with_cursor_style(CursorStyle::PointingHand)
775 .on_click({
776 let pane = pane.clone();
777 move |_, cx| {
778 cx.dispatch_action(CloseItem {
779 item_id,
780 pane: pane.clone(),
781 })
782 }
783 })
784 .named("close-tab-icon")
785 } else {
786 Empty::new().boxed()
787 })
788 .with_width(style.icon_width)
789 .boxed(),
790 )
791 .boxed(),
792 )
793 .boxed(),
794 )
795 .with_style(style.container)
796 .boxed(),
797 )
798 .on_mouse_down(move |cx| {
799 cx.dispatch_action(ActivateItem(ix));
800 true
801 })
802 .boxed()
803 })
804 }
805
806 row.add_child(
807 Empty::new()
808 .contained()
809 .with_border(theme.workspace.tab.container.border)
810 .flex(0., true)
811 .named("filler"),
812 );
813
814 row.boxed()
815 });
816
817 ConstrainedBox::new(tabs.boxed())
818 .with_height(theme.workspace.tab.height)
819 .named("tabs")
820 }
821}
822
823impl Entity for Pane {
824 type Event = Event;
825}
826
827impl View for Pane {
828 fn ui_name() -> &'static str {
829 "Pane"
830 }
831
832 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
833 let this = cx.handle();
834
835 EventHandler::new(if let Some(active_item) = self.active_item() {
836 Flex::column()
837 .with_child(self.render_tabs(cx))
838 .with_child(ChildView::new(&self.toolbar).boxed())
839 .with_child(ChildView::new(active_item).flex(1., true).boxed())
840 .boxed()
841 } else {
842 Empty::new().boxed()
843 })
844 .on_navigate_mouse_down(move |direction, cx| {
845 let this = this.clone();
846 match direction {
847 NavigationDirection::Back => cx.dispatch_action(GoBack { pane: Some(this) }),
848 NavigationDirection::Forward => cx.dispatch_action(GoForward { pane: Some(this) }),
849 }
850
851 true
852 })
853 .named("pane")
854 }
855
856 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
857 self.focus_active_item(cx);
858 }
859}
860
861impl ItemNavHistory {
862 pub fn new<T: Item>(history: Rc<RefCell<NavHistory>>, item: &ViewHandle<T>) -> Self {
863 Self {
864 history,
865 item: Rc::new(item.downgrade()),
866 }
867 }
868
869 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
870 self.history.clone()
871 }
872
873 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
874 self.history.borrow_mut().push(data, self.item.clone());
875 }
876}
877
878impl NavHistory {
879 pub fn disable(&mut self) {
880 self.mode = NavigationMode::Disabled;
881 }
882
883 pub fn enable(&mut self) {
884 self.mode = NavigationMode::Normal;
885 }
886
887 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
888 self.backward_stack.pop_back()
889 }
890
891 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
892 self.forward_stack.pop_back()
893 }
894
895 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
896 match mode {
897 NavigationMode::Normal | NavigationMode::Disabled => None,
898 NavigationMode::GoingBack => self.pop_backward(),
899 NavigationMode::GoingForward => self.pop_forward(),
900 }
901 }
902
903 fn set_mode(&mut self, mode: NavigationMode) {
904 self.mode = mode;
905 }
906
907 pub fn push<D: 'static + Any>(&mut self, data: Option<D>, item: Rc<dyn WeakItemHandle>) {
908 match self.mode {
909 NavigationMode::Disabled => {}
910 NavigationMode::Normal => {
911 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
912 self.backward_stack.pop_front();
913 }
914 self.backward_stack.push_back(NavigationEntry {
915 item,
916 data: data.map(|data| Box::new(data) as Box<dyn Any>),
917 });
918 self.forward_stack.clear();
919 }
920 NavigationMode::GoingBack => {
921 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
922 self.forward_stack.pop_front();
923 }
924 self.forward_stack.push_back(NavigationEntry {
925 item,
926 data: data.map(|data| Box::new(data) as Box<dyn Any>),
927 });
928 }
929 NavigationMode::GoingForward => {
930 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
931 self.backward_stack.pop_front();
932 }
933 self.backward_stack.push_back(NavigationEntry {
934 item,
935 data: data.map(|data| Box::new(data) as Box<dyn Any>),
936 });
937 }
938 }
939 }
940}