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