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 if let Some(type_id) = self.active_toolbar_type {
453 if let Some(toolbar) = self.toolbars.get(&type_id) {
454 self.active_toolbar_visible = toolbar.active_item_changed(
455 self.item_views
456 .get(self.active_item_index)
457 .map(|i| i.1.clone()),
458 cx,
459 );
460 }
461 }
462 }
463
464 fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
465 let settings = self.settings.borrow();
466 let theme = &settings.theme;
467
468 enum Tabs {}
469 let tabs = MouseEventHandler::new::<Tabs, _, _, _>(cx.view_id(), cx, |mouse_state, cx| {
470 let mut row = Flex::row();
471 for (ix, (_, item_view)) in self.item_views.iter().enumerate() {
472 let is_active = ix == self.active_item_index;
473
474 row.add_child({
475 let tab_style = if is_active {
476 theme.workspace.active_tab.clone()
477 } else {
478 theme.workspace.tab.clone()
479 };
480 let title = item_view.tab_content(&tab_style, cx);
481
482 let mut style = if is_active {
483 theme.workspace.active_tab.clone()
484 } else {
485 theme.workspace.tab.clone()
486 };
487 if ix == 0 {
488 style.container.border.left = false;
489 }
490
491 EventHandler::new(
492 Container::new(
493 Flex::row()
494 .with_child(
495 Align::new({
496 let diameter = 7.0;
497 let icon_color = if item_view.has_conflict(cx) {
498 Some(style.icon_conflict)
499 } else if item_view.is_dirty(cx) {
500 Some(style.icon_dirty)
501 } else {
502 None
503 };
504
505 ConstrainedBox::new(
506 Canvas::new(move |bounds, _, cx| {
507 if let Some(color) = icon_color {
508 let square = RectF::new(
509 bounds.origin(),
510 vec2f(diameter, diameter),
511 );
512 cx.scene.push_quad(Quad {
513 bounds: square,
514 background: Some(color),
515 border: Default::default(),
516 corner_radius: diameter / 2.,
517 });
518 }
519 })
520 .boxed(),
521 )
522 .with_width(diameter)
523 .with_height(diameter)
524 .boxed()
525 })
526 .boxed(),
527 )
528 .with_child(
529 Container::new(Align::new(title).boxed())
530 .with_style(ContainerStyle {
531 margin: Margin {
532 left: style.spacing,
533 right: style.spacing,
534 ..Default::default()
535 },
536 ..Default::default()
537 })
538 .boxed(),
539 )
540 .with_child(
541 Align::new(
542 ConstrainedBox::new(if mouse_state.hovered {
543 let item_id = item_view.id();
544 enum TabCloseButton {}
545 let icon = Svg::new("icons/x.svg");
546 MouseEventHandler::new::<TabCloseButton, _, _, _>(
547 item_id,
548 cx,
549 |mouse_state, _| {
550 if mouse_state.hovered {
551 icon.with_color(style.icon_close_active)
552 .boxed()
553 } else {
554 icon.with_color(style.icon_close).boxed()
555 }
556 },
557 )
558 .with_padding(Padding::uniform(4.))
559 .with_cursor_style(CursorStyle::PointingHand)
560 .on_click(move |cx| {
561 cx.dispatch_action(CloseItem(item_id))
562 })
563 .named("close-tab-icon")
564 } else {
565 Empty::new().boxed()
566 })
567 .with_width(style.icon_width)
568 .boxed(),
569 )
570 .boxed(),
571 )
572 .boxed(),
573 )
574 .with_style(style.container)
575 .boxed(),
576 )
577 .on_mouse_down(move |cx| {
578 cx.dispatch_action(ActivateItem(ix));
579 true
580 })
581 .boxed()
582 })
583 }
584
585 row.add_child(
586 Empty::new()
587 .contained()
588 .with_border(theme.workspace.tab.container.border)
589 .flexible(0., true)
590 .named("filler"),
591 );
592
593 row.boxed()
594 });
595
596 ConstrainedBox::new(tabs.boxed())
597 .with_height(theme.workspace.tab.height)
598 .named("tabs")
599 }
600}
601
602impl Entity for Pane {
603 type Event = Event;
604}
605
606impl View for Pane {
607 fn ui_name() -> &'static str {
608 "Pane"
609 }
610
611 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
612 if let Some(active_item) = self.active_item() {
613 Flex::column()
614 .with_child(self.render_tabs(cx))
615 .with_children(
616 self.active_toolbar()
617 .as_ref()
618 .map(|view| ChildView::new(view).boxed()),
619 )
620 .with_child(ChildView::new(active_item).flexible(1., true).boxed())
621 .named("pane")
622 } else {
623 Empty::new().named("pane")
624 }
625 }
626
627 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
628 self.focus_active_item(cx);
629 }
630}
631
632impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
633 fn active_item_changed(
634 &self,
635 item: Option<Box<dyn ItemViewHandle>>,
636 cx: &mut MutableAppContext,
637 ) -> bool {
638 self.update(cx, |this, cx| this.active_item_changed(item, cx))
639 }
640
641 fn on_dismiss(&self, cx: &mut MutableAppContext) {
642 self.update(cx, |this, cx| this.on_dismiss(cx));
643 }
644
645 fn to_any(&self) -> AnyViewHandle {
646 self.into()
647 }
648}
649
650impl ItemNavHistory {
651 pub fn new<T: ItemView>(history: Rc<RefCell<NavHistory>>, item_view: &ViewHandle<T>) -> Self {
652 Self {
653 history,
654 item_view: Rc::new(item_view.downgrade()),
655 }
656 }
657
658 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
659 self.history.clone()
660 }
661
662 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
663 self.history.borrow_mut().push(data, self.item_view.clone());
664 }
665}
666
667impl NavHistory {
668 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
669 self.backward_stack.pop_back()
670 }
671
672 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
673 self.forward_stack.pop_back()
674 }
675
676 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
677 match mode {
678 NavigationMode::Normal => None,
679 NavigationMode::GoingBack => self.pop_backward(),
680 NavigationMode::GoingForward => self.pop_forward(),
681 }
682 }
683
684 fn set_mode(&mut self, mode: NavigationMode) {
685 self.mode = mode;
686 }
687
688 pub fn push<D: 'static + Any>(
689 &mut self,
690 data: Option<D>,
691 item_view: Rc<dyn WeakItemViewHandle>,
692 ) {
693 match self.mode {
694 NavigationMode::Normal => {
695 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
696 self.backward_stack.pop_front();
697 }
698 self.backward_stack.push_back(NavigationEntry {
699 item_view,
700 data: data.map(|data| Box::new(data) as Box<dyn Any>),
701 });
702 self.forward_stack.clear();
703 }
704 NavigationMode::GoingBack => {
705 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
706 self.forward_stack.pop_front();
707 }
708 self.forward_stack.push_back(NavigationEntry {
709 item_view,
710 data: data.map(|data| Box::new(data) as Box<dyn Any>),
711 });
712 }
713 NavigationMode::GoingForward => {
714 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
715 self.backward_stack.pop_front();
716 }
717 self.backward_stack.push_back(NavigationEntry {
718 item_view,
719 data: data.map(|data| Box::new(data) as Box<dyn Any>),
720 });
721 }
722 }
723 }
724}