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