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