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, cx);
75 });
76 cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
77 pane.activate_item(pane.items.len() - 1, true, true, 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, 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, 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 let Some(item_ix) = pane.read(cx).items.iter().position(|i| i.id() == item.id()) {
408 pane.update(cx, |pane, cx| {
409 pane.activate_item(item_ix, activate_pane, focus_item, cx)
410 });
411 return;
412 }
413
414 item.added_to_pane(workspace, pane.clone(), cx);
415 pane.update(cx, |pane, cx| {
416 // If there is already an active item, then insert the new item
417 // right after it. Otherwise, adjust the `active_item_index` field
418 // before activating the new item, so that in the `activate_item`
419 // method, we can detect that the active item is changing.
420 let item_ix;
421 if pane.active_item_index < pane.items.len() {
422 item_ix = pane.active_item_index + 1
423 } else {
424 item_ix = pane.items.len();
425 pane.active_item_index = usize::MAX;
426 };
427
428 pane.items.insert(item_ix, item);
429 pane.activate_item(item_ix, activate_pane, focus_item, cx);
430 cx.notify();
431 });
432 }
433
434 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
435 self.items.iter()
436 }
437
438 pub fn items_of_type<'a, T: View>(&'a self) -> impl 'a + Iterator<Item = ViewHandle<T>> {
439 self.items
440 .iter()
441 .filter_map(|item| item.to_any().downcast())
442 }
443
444 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
445 self.items.get(self.active_item_index).cloned()
446 }
447
448 pub fn item_for_entry(
449 &self,
450 entry_id: ProjectEntryId,
451 cx: &AppContext,
452 ) -> Option<Box<dyn ItemHandle>> {
453 self.items.iter().find_map(|item| {
454 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == &[entry_id] {
455 Some(item.boxed_clone())
456 } else {
457 None
458 }
459 })
460 }
461
462 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
463 self.items.iter().position(|i| i.id() == item.id())
464 }
465
466 pub fn activate_item(
467 &mut self,
468 index: usize,
469 activate_pane: bool,
470 focus_item: bool,
471 cx: &mut ViewContext<Self>,
472 ) {
473 use NavigationMode::{GoingBack, GoingForward};
474 if index < self.items.len() {
475 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
476 if prev_active_item_ix != self.active_item_index
477 || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
478 {
479 if let Some(prev_item) = self.items.get(prev_active_item_ix) {
480 prev_item.deactivated(cx);
481 }
482 cx.emit(Event::ActivateItem {
483 local: activate_pane,
484 });
485 }
486 self.update_toolbar(cx);
487 if focus_item {
488 self.focus_active_item(cx);
489 }
490 if activate_pane {
491 self.activate(cx);
492 }
493 self.autoscroll = true;
494 cx.notify();
495 }
496 }
497
498 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
499 let mut index = self.active_item_index;
500 if index > 0 {
501 index -= 1;
502 } else if self.items.len() > 0 {
503 index = self.items.len() - 1;
504 }
505 self.activate_item(index, true, true, cx);
506 }
507
508 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
509 let mut index = self.active_item_index;
510 if index + 1 < self.items.len() {
511 index += 1;
512 } else {
513 index = 0;
514 }
515 self.activate_item(index, true, true, cx);
516 }
517
518 pub fn close_active_item(
519 workspace: &mut Workspace,
520 _: &CloseActiveItem,
521 cx: &mut ViewContext<Workspace>,
522 ) -> Option<Task<Result<()>>> {
523 let pane_handle = workspace.active_pane().clone();
524 let pane = pane_handle.read(cx);
525 if pane.items.is_empty() {
526 None
527 } else {
528 let item_id_to_close = pane.items[pane.active_item_index].id();
529 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
530 item_id == item_id_to_close
531 });
532 Some(cx.foreground().spawn(async move {
533 task.await?;
534 Ok(())
535 }))
536 }
537 }
538
539 pub fn close_inactive_items(
540 workspace: &mut Workspace,
541 _: &CloseInactiveItems,
542 cx: &mut ViewContext<Workspace>,
543 ) -> Option<Task<Result<()>>> {
544 let pane_handle = workspace.active_pane().clone();
545 let pane = pane_handle.read(cx);
546 if pane.items.is_empty() {
547 None
548 } else {
549 let active_item_id = pane.items[pane.active_item_index].id();
550 let task =
551 Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
552 Some(cx.foreground().spawn(async move {
553 task.await?;
554 Ok(())
555 }))
556 }
557 }
558
559 pub fn close_item(
560 workspace: &mut Workspace,
561 pane: ViewHandle<Pane>,
562 item_id_to_close: usize,
563 cx: &mut ViewContext<Workspace>,
564 ) -> Task<Result<bool>> {
565 Self::close_items(workspace, pane, cx, move |view_id| {
566 view_id == item_id_to_close
567 })
568 }
569
570 pub fn close_items(
571 workspace: &mut Workspace,
572 pane: ViewHandle<Pane>,
573 cx: &mut ViewContext<Workspace>,
574 should_close: impl 'static + Fn(usize) -> bool,
575 ) -> Task<Result<bool>> {
576 let project = workspace.project().clone();
577
578 // Find the items to close.
579 let mut items_to_close = Vec::new();
580 for item in &pane.read(cx).items {
581 if should_close(item.id()) {
582 items_to_close.push(item.boxed_clone());
583 }
584 }
585
586 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
587 // to focus the singleton buffer when prompting to save that buffer, as opposed
588 // to focusing the multibuffer, because this gives the user a more clear idea
589 // of what content they would be saving.
590 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
591
592 cx.spawn(|workspace, mut cx| async move {
593 let mut saved_project_entry_ids = HashSet::default();
594 for item in items_to_close.clone() {
595 // Find the item's current index and its set of project entries. Avoid
596 // storing these in advance, in case they have changed since this task
597 // was started.
598 let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
599 (pane.index_for_item(&*item), item.project_entry_ids(cx))
600 });
601 let item_ix = if let Some(ix) = item_ix {
602 ix
603 } else {
604 continue;
605 };
606
607 // If an item hasn't yet been associated with a project entry, then always
608 // prompt to save it before closing it. Otherwise, check if the item has
609 // any project entries that are not open anywhere else in the workspace,
610 // AND that the user has not already been prompted to save. If there are
611 // any such project entries, prompt the user to save this item.
612 let should_save = if project_entry_ids.is_empty() {
613 true
614 } else {
615 workspace.read_with(&cx, |workspace, cx| {
616 for item in workspace.items(cx) {
617 if !items_to_close
618 .iter()
619 .any(|item_to_close| item_to_close.id() == item.id())
620 {
621 let other_project_entry_ids = item.project_entry_ids(cx);
622 project_entry_ids
623 .retain(|id| !other_project_entry_ids.contains(&id));
624 }
625 }
626 });
627 project_entry_ids
628 .iter()
629 .any(|id| saved_project_entry_ids.insert(*id))
630 };
631
632 if should_save {
633 if !Self::save_item(project.clone(), &pane, item_ix, &item, true, &mut cx)
634 .await?
635 {
636 break;
637 }
638 }
639
640 // Remove the item from the pane.
641 pane.update(&mut cx, |pane, cx| {
642 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
643 if item_ix == pane.active_item_index {
644 if item_ix + 1 < pane.items.len() {
645 pane.activate_next_item(cx);
646 } else if item_ix > 0 {
647 pane.activate_prev_item(cx);
648 }
649 }
650
651 let item = pane.items.remove(item_ix);
652 cx.emit(Event::RemoveItem);
653 if pane.items.is_empty() {
654 item.deactivated(cx);
655 pane.update_toolbar(cx);
656 cx.emit(Event::Remove);
657 }
658
659 if item_ix < pane.active_item_index {
660 pane.active_item_index -= 1;
661 }
662
663 pane.nav_history
664 .borrow_mut()
665 .set_mode(NavigationMode::ClosingItem);
666 item.deactivated(cx);
667 pane.nav_history
668 .borrow_mut()
669 .set_mode(NavigationMode::Normal);
670
671 if let Some(path) = item.project_path(cx) {
672 pane.nav_history
673 .borrow_mut()
674 .paths_by_item
675 .insert(item.id(), path);
676 } else {
677 pane.nav_history
678 .borrow_mut()
679 .paths_by_item
680 .remove(&item.id());
681 }
682 }
683 });
684 }
685
686 pane.update(&mut cx, |_, cx| cx.notify());
687 Ok(true)
688 })
689 }
690
691 pub async fn save_item(
692 project: ModelHandle<Project>,
693 pane: &ViewHandle<Pane>,
694 item_ix: usize,
695 item: &Box<dyn ItemHandle>,
696 should_prompt_for_save: bool,
697 cx: &mut AsyncAppContext,
698 ) -> Result<bool> {
699 const CONFLICT_MESSAGE: &'static str =
700 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
701 const DIRTY_MESSAGE: &'static str =
702 "This file contains unsaved edits. Do you want to save it?";
703
704 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
705 (
706 item.has_conflict(cx),
707 item.is_dirty(cx),
708 item.can_save(cx),
709 item.is_singleton(cx),
710 )
711 });
712
713 if has_conflict && can_save {
714 let mut answer = pane.update(cx, |pane, cx| {
715 pane.activate_item(item_ix, true, true, cx);
716 cx.prompt(
717 PromptLevel::Warning,
718 CONFLICT_MESSAGE,
719 &["Overwrite", "Discard", "Cancel"],
720 )
721 });
722 match answer.next().await {
723 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
724 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
725 _ => return Ok(false),
726 }
727 } else if is_dirty && (can_save || is_singleton) {
728 let will_autosave = cx.read(|cx| {
729 matches!(
730 cx.global::<Settings>().autosave,
731 Autosave::OnFocusChange | Autosave::OnWindowChange
732 ) && Self::can_autosave_item(item.as_ref(), cx)
733 });
734 let should_save = if should_prompt_for_save && !will_autosave {
735 let mut answer = pane.update(cx, |pane, cx| {
736 pane.activate_item(item_ix, true, true, cx);
737 cx.prompt(
738 PromptLevel::Warning,
739 DIRTY_MESSAGE,
740 &["Save", "Don't Save", "Cancel"],
741 )
742 });
743 match answer.next().await {
744 Some(0) => true,
745 Some(1) => false,
746 _ => return Ok(false),
747 }
748 } else {
749 true
750 };
751
752 if should_save {
753 if can_save {
754 cx.update(|cx| item.save(project, cx)).await?;
755 } else if is_singleton {
756 let start_abs_path = project
757 .read_with(cx, |project, cx| {
758 let worktree = project.visible_worktrees(cx).next()?;
759 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
760 })
761 .unwrap_or(Path::new("").into());
762
763 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
764 if let Some(abs_path) = abs_path.next().await.flatten() {
765 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
766 } else {
767 return Ok(false);
768 }
769 }
770 }
771 }
772 Ok(true)
773 }
774
775 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
776 let is_deleted = item.project_entry_ids(cx).is_empty();
777 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
778 }
779
780 pub fn autosave_item(
781 item: &dyn ItemHandle,
782 project: ModelHandle<Project>,
783 cx: &mut MutableAppContext,
784 ) -> Task<Result<()>> {
785 if Self::can_autosave_item(item, cx) {
786 item.save(project, cx)
787 } else {
788 Task::ready(Ok(()))
789 }
790 }
791
792 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
793 if let Some(active_item) = self.active_item() {
794 cx.focus(active_item);
795 }
796 }
797
798 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
799 cx.emit(Event::Split(direction));
800 }
801
802 fn deploy_split_menu(&mut self, action: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
803 self.split_menu.update(cx, |menu, cx| {
804 menu.show(
805 action.position,
806 vec![
807 ContextMenuItem::item("Split Right", SplitRight),
808 ContextMenuItem::item("Split Left", SplitLeft),
809 ContextMenuItem::item("Split Up", SplitUp),
810 ContextMenuItem::item("Split Down", SplitDown),
811 ],
812 cx,
813 );
814 });
815 }
816
817 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
818 &self.toolbar
819 }
820
821 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
822 let active_item = self
823 .items
824 .get(self.active_item_index)
825 .map(|item| item.as_ref());
826 self.toolbar.update(cx, |toolbar, cx| {
827 toolbar.set_active_pane_item(active_item, cx);
828 });
829 }
830
831 fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
832 let theme = cx.global::<Settings>().theme.clone();
833
834 enum Tabs {}
835 enum Tab {}
836 let pane = cx.handle();
837 MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
838 let autoscroll = if mem::take(&mut self.autoscroll) {
839 Some(self.active_item_index)
840 } else {
841 None
842 };
843 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
844 for (ix, item) in self.items.iter().enumerate() {
845 let is_active = ix == self.active_item_index;
846
847 row.add_child({
848 let tab_style = if is_active {
849 theme.workspace.active_tab.clone()
850 } else {
851 theme.workspace.tab.clone()
852 };
853 let title = item.tab_content(&tab_style, cx);
854
855 let mut style = if is_active {
856 theme.workspace.active_tab.clone()
857 } else {
858 theme.workspace.tab.clone()
859 };
860 if ix == 0 {
861 style.container.border.left = false;
862 }
863
864 MouseEventHandler::new::<Tab, _, _>(ix, cx, |_, cx| {
865 Container::new(
866 Flex::row()
867 .with_child(
868 Align::new({
869 let diameter = 7.0;
870 let icon_color = if item.has_conflict(cx) {
871 Some(style.icon_conflict)
872 } else if item.is_dirty(cx) {
873 Some(style.icon_dirty)
874 } else {
875 None
876 };
877
878 ConstrainedBox::new(
879 Canvas::new(move |bounds, _, cx| {
880 if let Some(color) = icon_color {
881 let square = RectF::new(
882 bounds.origin(),
883 vec2f(diameter, diameter),
884 );
885 cx.scene.push_quad(Quad {
886 bounds: square,
887 background: Some(color),
888 border: Default::default(),
889 corner_radius: diameter / 2.,
890 });
891 }
892 })
893 .boxed(),
894 )
895 .with_width(diameter)
896 .with_height(diameter)
897 .boxed()
898 })
899 .boxed(),
900 )
901 .with_child(
902 Container::new(Align::new(title).boxed())
903 .with_style(ContainerStyle {
904 margin: Margin {
905 left: style.spacing,
906 right: style.spacing,
907 ..Default::default()
908 },
909 ..Default::default()
910 })
911 .boxed(),
912 )
913 .with_child(
914 Align::new(
915 ConstrainedBox::new(if mouse_state.hovered {
916 let item_id = item.id();
917 enum TabCloseButton {}
918 let icon = Svg::new("icons/x.svg");
919 MouseEventHandler::new::<TabCloseButton, _, _>(
920 item_id,
921 cx,
922 |mouse_state, _| {
923 if mouse_state.hovered {
924 icon.with_color(style.icon_close_active)
925 .boxed()
926 } else {
927 icon.with_color(style.icon_close).boxed()
928 }
929 },
930 )
931 .with_padding(Padding::uniform(4.))
932 .with_cursor_style(CursorStyle::PointingHand)
933 .on_click({
934 let pane = pane.clone();
935 move |_, _, cx| {
936 cx.dispatch_action(CloseItem {
937 item_id,
938 pane: pane.clone(),
939 })
940 }
941 })
942 .named("close-tab-icon")
943 } else {
944 Empty::new().boxed()
945 })
946 .with_width(style.icon_width)
947 .boxed(),
948 )
949 .boxed(),
950 )
951 .boxed(),
952 )
953 .with_style(style.container)
954 .boxed()
955 })
956 .on_mouse_down(move |_, cx| {
957 cx.dispatch_action(ActivateItem(ix));
958 })
959 .boxed()
960 })
961 }
962
963 row.add_child(
964 Empty::new()
965 .contained()
966 .with_border(theme.workspace.tab.container.border)
967 .flex(0., true)
968 .named("filler"),
969 );
970
971 row.boxed()
972 })
973 }
974}
975
976impl Entity for Pane {
977 type Event = Event;
978}
979
980impl View for Pane {
981 fn ui_name() -> &'static str {
982 "Pane"
983 }
984
985 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
986 enum SplitIcon {}
987
988 let this = cx.handle();
989
990 Stack::new()
991 .with_child(
992 EventHandler::new(if let Some(active_item) = self.active_item() {
993 Flex::column()
994 .with_child(
995 Flex::row()
996 .with_child(self.render_tabs(cx).flex(1., true).named("tabs"))
997 .with_child(
998 MouseEventHandler::new::<SplitIcon, _, _>(
999 0,
1000 cx,
1001 |mouse_state, cx| {
1002 let theme = &cx.global::<Settings>().theme.workspace;
1003 let style =
1004 theme.pane_button.style_for(mouse_state, false);
1005 Svg::new("icons/split.svg")
1006 .with_color(style.color)
1007 .constrained()
1008 .with_width(style.icon_width)
1009 .aligned()
1010 .contained()
1011 .with_style(style.container)
1012 .constrained()
1013 .with_width(style.button_width)
1014 .with_height(style.button_width)
1015 .aligned()
1016 .boxed()
1017 },
1018 )
1019 .with_cursor_style(CursorStyle::PointingHand)
1020 .on_mouse_down(|position, cx| {
1021 cx.dispatch_action(DeploySplitMenu { position });
1022 })
1023 .boxed(),
1024 )
1025 .constrained()
1026 .with_height(cx.global::<Settings>().theme.workspace.tab.height)
1027 .boxed(),
1028 )
1029 .with_child(ChildView::new(&self.toolbar).boxed())
1030 .with_child(ChildView::new(active_item).flex(1., true).boxed())
1031 .boxed()
1032 } else {
1033 Empty::new().boxed()
1034 })
1035 .on_navigate_mouse_down(move |direction, cx| {
1036 let this = this.clone();
1037 match direction {
1038 NavigationDirection::Back => {
1039 cx.dispatch_action(GoBack { pane: Some(this) })
1040 }
1041 NavigationDirection::Forward => {
1042 cx.dispatch_action(GoForward { pane: Some(this) })
1043 }
1044 }
1045
1046 true
1047 })
1048 .boxed(),
1049 )
1050 .with_child(ChildView::new(&self.split_menu).boxed())
1051 .named("pane")
1052 }
1053
1054 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1055 self.focus_active_item(cx);
1056 }
1057}
1058
1059impl ItemNavHistory {
1060 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1061 self.history.borrow_mut().push(data, self.item.clone(), cx);
1062 }
1063
1064 pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1065 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1066 }
1067
1068 pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1069 self.history
1070 .borrow_mut()
1071 .pop(NavigationMode::GoingForward, cx)
1072 }
1073}
1074
1075impl NavHistory {
1076 fn set_mode(&mut self, mode: NavigationMode) {
1077 self.mode = mode;
1078 }
1079
1080 fn disable(&mut self) {
1081 self.mode = NavigationMode::Disabled;
1082 }
1083
1084 fn enable(&mut self) {
1085 self.mode = NavigationMode::Normal;
1086 }
1087
1088 fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1089 let entry = match mode {
1090 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1091 return None
1092 }
1093 NavigationMode::GoingBack => &mut self.backward_stack,
1094 NavigationMode::GoingForward => &mut self.forward_stack,
1095 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1096 }
1097 .pop_back();
1098 if entry.is_some() {
1099 self.did_update(cx);
1100 }
1101 entry
1102 }
1103
1104 fn push<D: 'static + Any>(
1105 &mut self,
1106 data: Option<D>,
1107 item: Rc<dyn WeakItemHandle>,
1108 cx: &mut MutableAppContext,
1109 ) {
1110 match self.mode {
1111 NavigationMode::Disabled => {}
1112 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1113 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1114 self.backward_stack.pop_front();
1115 }
1116 self.backward_stack.push_back(NavigationEntry {
1117 item,
1118 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1119 });
1120 self.forward_stack.clear();
1121 }
1122 NavigationMode::GoingBack => {
1123 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1124 self.forward_stack.pop_front();
1125 }
1126 self.forward_stack.push_back(NavigationEntry {
1127 item,
1128 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1129 });
1130 }
1131 NavigationMode::GoingForward => {
1132 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1133 self.backward_stack.pop_front();
1134 }
1135 self.backward_stack.push_back(NavigationEntry {
1136 item,
1137 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1138 });
1139 }
1140 NavigationMode::ClosingItem => {
1141 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1142 self.closed_stack.pop_front();
1143 }
1144 self.closed_stack.push_back(NavigationEntry {
1145 item,
1146 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1147 });
1148 }
1149 }
1150 self.did_update(cx);
1151 }
1152
1153 fn did_update(&self, cx: &mut MutableAppContext) {
1154 if let Some(pane) = self.pane.upgrade(cx) {
1155 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1156 }
1157 }
1158}