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