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