1use super::{ItemViewHandle, SplitDirection};
2use crate::{ItemHandle, ItemView, Settings, WeakItemViewHandle, Workspace};
3use collections::{HashMap, VecDeque};
4use gpui::{
5 action,
6 elements::*,
7 geometry::{rect::RectF, vector::vec2f},
8 keymap::Binding,
9 platform::CursorStyle,
10 AnyViewHandle, Entity, MutableAppContext, Quad, RenderContext, Task, View, ViewContext,
11 ViewHandle,
12};
13use postage::watch;
14use project::ProjectPath;
15use std::{
16 any::{Any, TypeId},
17 cell::RefCell,
18 cmp, mem,
19 rc::Rc,
20};
21use util::ResultExt;
22
23action!(Split, SplitDirection);
24action!(ActivateItem, usize);
25action!(ActivatePrevItem);
26action!(ActivateNextItem);
27action!(CloseActiveItem);
28action!(CloseItem, usize);
29action!(GoBack);
30action!(GoForward);
31
32const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
33
34pub fn init(cx: &mut MutableAppContext) {
35 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
36 pane.activate_item(action.0, cx);
37 });
38 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
39 pane.activate_prev_item(cx);
40 });
41 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
42 pane.activate_next_item(cx);
43 });
44 cx.add_action(|pane: &mut Pane, _: &CloseActiveItem, cx| {
45 pane.close_active_item(cx);
46 });
47 cx.add_action(|pane: &mut Pane, action: &CloseItem, cx| {
48 pane.close_item(action.0, cx);
49 });
50 cx.add_action(|pane: &mut Pane, action: &Split, cx| {
51 pane.split(action.0, cx);
52 });
53 cx.add_action(|workspace: &mut Workspace, _: &GoBack, cx| {
54 Pane::go_back(workspace, cx).detach();
55 });
56 cx.add_action(|workspace: &mut Workspace, _: &GoForward, cx| {
57 Pane::go_forward(workspace, cx).detach();
58 });
59
60 cx.add_bindings(vec![
61 Binding::new("shift-cmd-{", ActivatePrevItem, Some("Pane")),
62 Binding::new("shift-cmd-}", ActivateNextItem, Some("Pane")),
63 Binding::new("cmd-w", CloseActiveItem, Some("Pane")),
64 Binding::new("cmd-k up", Split(SplitDirection::Up), Some("Pane")),
65 Binding::new("cmd-k down", Split(SplitDirection::Down), Some("Pane")),
66 Binding::new("cmd-k left", Split(SplitDirection::Left), Some("Pane")),
67 Binding::new("cmd-k right", Split(SplitDirection::Right), Some("Pane")),
68 Binding::new("ctrl--", GoBack, Some("Pane")),
69 Binding::new("shift-ctrl-_", GoForward, Some("Pane")),
70 ]);
71}
72
73pub enum Event {
74 Activate,
75 Remove,
76 Split(SplitDirection),
77}
78
79pub struct Pane {
80 item_views: Vec<(usize, Box<dyn ItemViewHandle>)>,
81 active_item_index: usize,
82 settings: watch::Receiver<Settings>,
83 nav_history: Rc<RefCell<NavHistory>>,
84 toolbars: HashMap<TypeId, Box<dyn ToolbarHandle>>,
85 active_toolbar_type: Option<TypeId>,
86 active_toolbar_visible: bool,
87}
88
89pub trait Toolbar: View {
90 fn active_item_changed(
91 &mut self,
92 item: Option<Box<dyn ItemViewHandle>>,
93 cx: &mut ViewContext<Self>,
94 ) -> bool;
95 fn on_dismiss(&mut self, cx: &mut ViewContext<Self>);
96}
97
98trait ToolbarHandle {
99 fn active_item_changed(
100 &self,
101 item: Option<Box<dyn ItemViewHandle>>,
102 cx: &mut MutableAppContext,
103 ) -> bool;
104 fn on_dismiss(&self, cx: &mut MutableAppContext);
105 fn to_any(&self) -> AnyViewHandle;
106}
107
108pub struct ItemNavHistory {
109 history: Rc<RefCell<NavHistory>>,
110 item_view: Rc<dyn WeakItemViewHandle>,
111}
112
113#[derive(Default)]
114pub struct NavHistory {
115 mode: NavigationMode,
116 backward_stack: VecDeque<NavigationEntry>,
117 forward_stack: VecDeque<NavigationEntry>,
118 paths_by_item: HashMap<usize, ProjectPath>,
119}
120
121#[derive(Copy, Clone)]
122enum NavigationMode {
123 Normal,
124 GoingBack,
125 GoingForward,
126}
127
128impl Default for NavigationMode {
129 fn default() -> Self {
130 Self::Normal
131 }
132}
133
134pub struct NavigationEntry {
135 pub item_view: Rc<dyn WeakItemViewHandle>,
136 pub data: Option<Box<dyn Any>>,
137}
138
139impl Pane {
140 pub fn new(settings: watch::Receiver<Settings>) -> Self {
141 Self {
142 item_views: Vec::new(),
143 active_item_index: 0,
144 settings,
145 nav_history: Default::default(),
146 toolbars: Default::default(),
147 active_toolbar_type: Default::default(),
148 active_toolbar_visible: false,
149 }
150 }
151
152 pub(crate) fn nav_history(&self) -> &Rc<RefCell<NavHistory>> {
153 &self.nav_history
154 }
155
156 pub fn activate(&self, cx: &mut ViewContext<Self>) {
157 cx.emit(Event::Activate);
158 }
159
160 pub fn go_back(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Task<()> {
161 Self::navigate_history(
162 workspace,
163 workspace.active_pane().clone(),
164 NavigationMode::GoingBack,
165 cx,
166 )
167 }
168
169 pub fn go_forward(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Task<()> {
170 Self::navigate_history(
171 workspace,
172 workspace.active_pane().clone(),
173 NavigationMode::GoingForward,
174 cx,
175 )
176 }
177
178 fn navigate_history(
179 workspace: &mut Workspace,
180 pane: ViewHandle<Pane>,
181 mode: NavigationMode,
182 cx: &mut ViewContext<Workspace>,
183 ) -> Task<()> {
184 let to_load = pane.update(cx, |pane, cx| {
185 // Retrieve the weak item handle from the history.
186 let entry = pane.nav_history.borrow_mut().pop(mode)?;
187
188 // If the item is still present in this pane, then activate it.
189 if let Some(index) = entry
190 .item_view
191 .upgrade(cx)
192 .and_then(|v| pane.index_for_item_view(v.as_ref()))
193 {
194 if let Some(item_view) = pane.active_item() {
195 pane.nav_history.borrow_mut().set_mode(mode);
196 item_view.deactivated(cx);
197 pane.nav_history
198 .borrow_mut()
199 .set_mode(NavigationMode::Normal);
200 }
201
202 pane.active_item_index = index;
203 pane.focus_active_item(cx);
204 if let Some(data) = entry.data {
205 pane.active_item()?.navigate(data, cx);
206 }
207 cx.notify();
208 None
209 }
210 // If the item is no longer present in this pane, then retrieve its
211 // project path in order to reopen it.
212 else {
213 pane.nav_history
214 .borrow_mut()
215 .paths_by_item
216 .get(&entry.item_view.id())
217 .cloned()
218 .map(|project_path| (project_path, entry))
219 }
220 });
221
222 if let Some((project_path, entry)) = to_load {
223 // If the item was no longer present, then load it again from its previous path.
224 let pane = pane.downgrade();
225 let task = workspace.load_path(project_path, cx);
226 cx.spawn(|workspace, mut cx| async move {
227 let item = task.await;
228 if let Some(pane) = pane.upgrade(&cx) {
229 if let Some(item) = item.log_err() {
230 workspace.update(&mut cx, |workspace, cx| {
231 pane.update(cx, |p, _| p.nav_history.borrow_mut().set_mode(mode));
232 let item_view = workspace.open_item_in_pane(item, &pane, cx);
233 pane.update(cx, |p, _| {
234 p.nav_history.borrow_mut().set_mode(NavigationMode::Normal)
235 });
236
237 if let Some(data) = entry.data {
238 item_view.navigate(data, cx);
239 }
240 });
241 } else {
242 workspace
243 .update(&mut cx, |workspace, cx| {
244 Self::navigate_history(workspace, pane, mode, cx)
245 })
246 .await;
247 }
248 }
249 })
250 } else {
251 Task::ready(())
252 }
253 }
254
255 pub fn open_item<T>(
256 &mut self,
257 item_handle: T,
258 workspace: &Workspace,
259 cx: &mut ViewContext<Self>,
260 ) -> Box<dyn ItemViewHandle>
261 where
262 T: 'static + ItemHandle,
263 {
264 for (ix, (item_id, item_view)) in self.item_views.iter().enumerate() {
265 if *item_id == item_handle.id() {
266 let item_view = item_view.boxed_clone();
267 self.activate_item(ix, cx);
268 return item_view;
269 }
270 }
271
272 let item_view =
273 item_handle.add_view(cx.window_id(), workspace, self.nav_history.clone(), cx);
274 self.add_item_view(item_view.boxed_clone(), cx);
275 item_view
276 }
277
278 pub fn add_item_view(
279 &mut self,
280 mut item_view: Box<dyn ItemViewHandle>,
281 cx: &mut ViewContext<Self>,
282 ) {
283 item_view.added_to_pane(cx);
284 let item_idx = cmp::min(self.active_item_index + 1, self.item_views.len());
285 self.item_views
286 .insert(item_idx, (item_view.item_id(cx), item_view));
287 self.activate_item(item_idx, cx);
288 cx.notify();
289 }
290
291 pub fn contains_item(&self, item: &dyn ItemHandle) -> bool {
292 let item_id = item.id();
293 self.item_views
294 .iter()
295 .any(|(existing_item_id, _)| *existing_item_id == item_id)
296 }
297
298 pub fn item_views(&self) -> impl Iterator<Item = &Box<dyn ItemViewHandle>> {
299 self.item_views.iter().map(|(_, view)| view)
300 }
301
302 pub fn active_item(&self) -> Option<Box<dyn ItemViewHandle>> {
303 self.item_views
304 .get(self.active_item_index)
305 .map(|(_, view)| view.clone())
306 }
307
308 pub fn index_for_item_view(&self, item_view: &dyn ItemViewHandle) -> Option<usize> {
309 self.item_views
310 .iter()
311 .position(|(_, i)| i.id() == item_view.id())
312 }
313
314 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
315 self.item_views.iter().position(|(id, _)| *id == item.id())
316 }
317
318 pub fn activate_item(&mut self, index: usize, cx: &mut ViewContext<Self>) {
319 if index < self.item_views.len() {
320 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
321 if prev_active_item_ix != self.active_item_index
322 && prev_active_item_ix < self.item_views.len()
323 {
324 self.item_views[prev_active_item_ix].1.deactivated(cx);
325 }
326 self.update_active_toolbar(cx);
327 self.focus_active_item(cx);
328 cx.notify();
329 }
330 }
331
332 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
333 let mut index = self.active_item_index;
334 if index > 0 {
335 index -= 1;
336 } else if self.item_views.len() > 0 {
337 index = self.item_views.len() - 1;
338 }
339 self.activate_item(index, cx);
340 }
341
342 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
343 let mut index = self.active_item_index;
344 if index + 1 < self.item_views.len() {
345 index += 1;
346 } else {
347 index = 0;
348 }
349 self.activate_item(index, cx);
350 }
351
352 pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
353 if !self.item_views.is_empty() {
354 self.close_item(self.item_views[self.active_item_index].1.id(), cx)
355 }
356 }
357
358 pub fn close_item(&mut self, item_view_id: usize, cx: &mut ViewContext<Self>) {
359 let mut item_ix = 0;
360 self.item_views.retain(|(_, item_view)| {
361 if item_view.id() == item_view_id {
362 if item_ix == self.active_item_index {
363 item_view.deactivated(cx);
364 }
365
366 let mut nav_history = self.nav_history.borrow_mut();
367 if let Some(path) = item_view.project_path(cx) {
368 nav_history.paths_by_item.insert(item_view.id(), path);
369 } else {
370 nav_history.paths_by_item.remove(&item_view.id());
371 }
372
373 item_ix += 1;
374 false
375 } else {
376 item_ix += 1;
377 true
378 }
379 });
380 self.activate_item(
381 cmp::min(
382 self.active_item_index,
383 self.item_views.len().saturating_sub(1),
384 ),
385 cx,
386 );
387
388 if self.item_views.is_empty() {
389 self.update_active_toolbar(cx);
390 cx.emit(Event::Remove);
391 }
392
393 cx.notify();
394 }
395
396 fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
397 if let Some(active_item) = self.active_item() {
398 cx.focus(active_item);
399 }
400 }
401
402 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
403 cx.emit(Event::Split(direction));
404 }
405
406 pub fn show_toolbar<F, V>(&mut self, cx: &mut ViewContext<Self>, build_toolbar: F)
407 where
408 F: FnOnce(&mut ViewContext<V>) -> V,
409 V: Toolbar,
410 {
411 let type_id = TypeId::of::<V>();
412 if self.active_toolbar_type != Some(type_id) {
413 self.dismiss_toolbar(cx);
414
415 let active_item = self.active_item();
416 self.toolbars
417 .entry(type_id)
418 .or_insert_with(|| Box::new(cx.add_view(build_toolbar)));
419
420 self.active_toolbar_type = Some(type_id);
421 self.active_toolbar_visible =
422 self.toolbars[&type_id].active_item_changed(active_item, cx);
423 cx.notify();
424 }
425 }
426
427 pub fn dismiss_toolbar(&mut self, cx: &mut ViewContext<Self>) {
428 if let Some(active_toolbar_type) = self.active_toolbar_type.take() {
429 self.toolbars
430 .get_mut(&active_toolbar_type)
431 .unwrap()
432 .on_dismiss(cx);
433 self.active_toolbar_visible = false;
434 self.focus_active_item(cx);
435 cx.notify();
436 }
437 }
438
439 pub fn toolbar<T: Toolbar>(&self) -> Option<ViewHandle<T>> {
440 self.toolbars
441 .get(&TypeId::of::<T>())
442 .and_then(|toolbar| toolbar.to_any().downcast())
443 }
444
445 pub fn active_toolbar(&self) -> Option<AnyViewHandle> {
446 let type_id = self.active_toolbar_type?;
447 let toolbar = self.toolbars.get(&type_id)?;
448 if self.active_toolbar_visible {
449 Some(toolbar.to_any())
450 } else {
451 None
452 }
453 }
454
455 fn update_active_toolbar(&mut self, cx: &mut ViewContext<Self>) {
456 let active_item = self.item_views.get(self.active_item_index);
457 for (toolbar_type_id, toolbar) in &self.toolbars {
458 let visible = toolbar.active_item_changed(active_item.map(|i| i.1.clone()), cx);
459 if Some(*toolbar_type_id) == self.active_toolbar_type {
460 self.active_toolbar_visible = visible;
461 }
462 }
463 }
464
465 fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
466 let settings = self.settings.borrow();
467 let theme = &settings.theme;
468
469 enum Tabs {}
470 let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
471 let mut row = Flex::row();
472 for (ix, (_, item_view)) in self.item_views.iter().enumerate() {
473 let is_active = ix == self.active_item_index;
474
475 row.add_child({
476 let tab_style = if is_active {
477 theme.workspace.active_tab.clone()
478 } else {
479 theme.workspace.tab.clone()
480 };
481 let title = item_view.tab_content(&tab_style, cx);
482
483 let mut style = if is_active {
484 theme.workspace.active_tab.clone()
485 } else {
486 theme.workspace.tab.clone()
487 };
488 if ix == 0 {
489 style.container.border.left = false;
490 }
491
492 EventHandler::new(
493 Container::new(
494 Flex::row()
495 .with_child(
496 Align::new({
497 let diameter = 7.0;
498 let icon_color = if item_view.has_conflict(cx) {
499 Some(style.icon_conflict)
500 } else if item_view.is_dirty(cx) {
501 Some(style.icon_dirty)
502 } else {
503 None
504 };
505
506 ConstrainedBox::new(
507 Canvas::new(move |bounds, _, cx| {
508 if let Some(color) = icon_color {
509 let square = RectF::new(
510 bounds.origin(),
511 vec2f(diameter, diameter),
512 );
513 cx.scene.push_quad(Quad {
514 bounds: square,
515 background: Some(color),
516 border: Default::default(),
517 corner_radius: diameter / 2.,
518 });
519 }
520 })
521 .boxed(),
522 )
523 .with_width(diameter)
524 .with_height(diameter)
525 .boxed()
526 })
527 .boxed(),
528 )
529 .with_child(
530 Container::new(Align::new(title).boxed())
531 .with_style(ContainerStyle {
532 margin: Margin {
533 left: style.spacing,
534 right: style.spacing,
535 ..Default::default()
536 },
537 ..Default::default()
538 })
539 .boxed(),
540 )
541 .with_child(
542 Align::new(
543 ConstrainedBox::new(if mouse_state.hovered {
544 let item_id = item_view.id();
545 enum TabCloseButton {}
546 let icon = Svg::new("icons/x.svg");
547 MouseEventHandler::new::<TabCloseButton, _, _>(
548 item_id,
549 cx,
550 |mouse_state, _| {
551 if mouse_state.hovered {
552 icon.with_color(style.icon_close_active)
553 .boxed()
554 } else {
555 icon.with_color(style.icon_close).boxed()
556 }
557 },
558 )
559 .with_padding(Padding::uniform(4.))
560 .with_cursor_style(CursorStyle::PointingHand)
561 .on_click(move |cx| {
562 cx.dispatch_action(CloseItem(item_id))
563 })
564 .named("close-tab-icon")
565 } else {
566 Empty::new().boxed()
567 })
568 .with_width(style.icon_width)
569 .boxed(),
570 )
571 .boxed(),
572 )
573 .boxed(),
574 )
575 .with_style(style.container)
576 .boxed(),
577 )
578 .on_mouse_down(move |cx| {
579 cx.dispatch_action(ActivateItem(ix));
580 true
581 })
582 .boxed()
583 })
584 }
585
586 row.add_child(
587 Empty::new()
588 .contained()
589 .with_border(theme.workspace.tab.container.border)
590 .flexible(0., true)
591 .named("filler"),
592 );
593
594 row.boxed()
595 });
596
597 ConstrainedBox::new(tabs.boxed())
598 .with_height(theme.workspace.tab.height)
599 .named("tabs")
600 }
601}
602
603impl Entity for Pane {
604 type Event = Event;
605}
606
607impl View for Pane {
608 fn ui_name() -> &'static str {
609 "Pane"
610 }
611
612 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
613 if let Some(active_item) = self.active_item() {
614 Flex::column()
615 .with_child(self.render_tabs(cx))
616 .with_children(
617 self.active_toolbar()
618 .as_ref()
619 .map(|view| ChildView::new(view).boxed()),
620 )
621 .with_child(ChildView::new(active_item).flexible(1., true).boxed())
622 .named("pane")
623 } else {
624 Empty::new().named("pane")
625 }
626 }
627
628 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
629 self.focus_active_item(cx);
630 }
631}
632
633impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
634 fn active_item_changed(
635 &self,
636 item: Option<Box<dyn ItemViewHandle>>,
637 cx: &mut MutableAppContext,
638 ) -> bool {
639 self.update(cx, |this, cx| this.active_item_changed(item, cx))
640 }
641
642 fn on_dismiss(&self, cx: &mut MutableAppContext) {
643 self.update(cx, |this, cx| this.on_dismiss(cx));
644 }
645
646 fn to_any(&self) -> AnyViewHandle {
647 self.into()
648 }
649}
650
651impl ItemNavHistory {
652 pub fn new<T: ItemView>(history: Rc<RefCell<NavHistory>>, item_view: &ViewHandle<T>) -> Self {
653 Self {
654 history,
655 item_view: Rc::new(item_view.downgrade()),
656 }
657 }
658
659 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
660 self.history.clone()
661 }
662
663 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
664 self.history.borrow_mut().push(data, self.item_view.clone());
665 }
666}
667
668impl NavHistory {
669 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
670 self.backward_stack.pop_back()
671 }
672
673 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
674 self.forward_stack.pop_back()
675 }
676
677 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
678 match mode {
679 NavigationMode::Normal => None,
680 NavigationMode::GoingBack => self.pop_backward(),
681 NavigationMode::GoingForward => self.pop_forward(),
682 }
683 }
684
685 fn set_mode(&mut self, mode: NavigationMode) {
686 self.mode = mode;
687 }
688
689 pub fn push<D: 'static + Any>(
690 &mut self,
691 data: Option<D>,
692 item_view: Rc<dyn WeakItemViewHandle>,
693 ) {
694 match self.mode {
695 NavigationMode::Normal => {
696 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
697 self.backward_stack.pop_front();
698 }
699 self.backward_stack.push_back(NavigationEntry {
700 item_view,
701 data: data.map(|data| Box::new(data) as Box<dyn Any>),
702 });
703 self.forward_stack.clear();
704 }
705 NavigationMode::GoingBack => {
706 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
707 self.forward_stack.pop_front();
708 }
709 self.forward_stack.push_back(NavigationEntry {
710 item_view,
711 data: data.map(|data| Box::new(data) as Box<dyn Any>),
712 });
713 }
714 NavigationMode::GoingForward => {
715 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
716 self.backward_stack.pop_front();
717 }
718 self.backward_stack.push_back(NavigationEntry {
719 item_view,
720 data: data.map(|data| Box::new(data) as Box<dyn Any>),
721 });
722 }
723 }
724 }
725}