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