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