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