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