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 self.item_views[prev_active_item_ix].1.deactivated(cx);
317 }
318 self.update_active_toolbar(cx);
319 self.focus_active_item(cx);
320 cx.notify();
321 }
322 }
323
324 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
325 let mut index = self.active_item_index;
326 if index > 0 {
327 index -= 1;
328 } else if self.item_views.len() > 0 {
329 index = self.item_views.len() - 1;
330 }
331 self.activate_item(index, cx);
332 }
333
334 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
335 let mut index = self.active_item_index;
336 if index + 1 < self.item_views.len() {
337 index += 1;
338 } else {
339 index = 0;
340 }
341 self.activate_item(index, cx);
342 }
343
344 pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) {
345 if !self.item_views.is_empty() {
346 self.close_item(self.item_views[self.active_item_index].1.id(), cx)
347 }
348 }
349
350 pub fn close_item(&mut self, item_view_id: usize, cx: &mut ViewContext<Self>) {
351 let mut item_ix = 0;
352 self.item_views.retain(|(_, item_view)| {
353 if item_view.id() == item_view_id {
354 if item_ix == self.active_item_index {
355 item_view.deactivated(cx);
356 }
357
358 let mut nav_history = self.nav_history.borrow_mut();
359 if let Some(path) = item_view.project_path(cx) {
360 nav_history.paths_by_item.insert(item_view.id(), path);
361 } else {
362 nav_history.paths_by_item.remove(&item_view.id());
363 }
364
365 item_ix += 1;
366 false
367 } else {
368 item_ix += 1;
369 true
370 }
371 });
372 self.activate_item(
373 cmp::min(
374 self.active_item_index,
375 self.item_views.len().saturating_sub(1),
376 ),
377 cx,
378 );
379
380 if self.item_views.is_empty() {
381 self.update_active_toolbar(cx);
382 cx.emit(Event::Remove);
383 }
384 }
385
386 fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
387 if let Some(active_item) = self.active_item() {
388 cx.focus(active_item);
389 }
390 }
391
392 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
393 cx.emit(Event::Split(direction));
394 }
395
396 pub fn show_toolbar<F, V>(&mut self, cx: &mut ViewContext<Self>, build_toolbar: F)
397 where
398 F: FnOnce(&mut ViewContext<V>) -> V,
399 V: Toolbar,
400 {
401 let type_id = TypeId::of::<V>();
402 let active_item = self.active_item();
403 self.toolbars
404 .entry(type_id)
405 .or_insert_with(|| Box::new(cx.add_view(build_toolbar)));
406 self.active_toolbar_type = Some(type_id);
407 self.active_toolbar_visible = self.toolbars[&type_id].active_item_changed(active_item, cx);
408 cx.notify();
409 }
410
411 pub fn hide_toolbar(&mut self, cx: &mut ViewContext<Self>) {
412 self.active_toolbar_type = None;
413 self.active_toolbar_visible = false;
414 self.focus_active_item(cx);
415 cx.notify();
416 }
417
418 pub fn active_toolbar(&self) -> Option<AnyViewHandle> {
419 let type_id = self.active_toolbar_type?;
420 let toolbar = self.toolbars.get(&type_id)?;
421 if self.active_toolbar_visible {
422 Some(toolbar.to_any())
423 } else {
424 None
425 }
426 }
427
428 fn update_active_toolbar(&mut self, cx: &mut ViewContext<Self>) {
429 if let Some(type_id) = self.active_toolbar_type {
430 if let Some(toolbar) = self.toolbars.get(&type_id) {
431 self.active_toolbar_visible = toolbar.active_item_changed(
432 Some(self.item_views[self.active_item_index].1.clone()),
433 cx,
434 );
435 }
436 }
437 }
438
439 fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
440 let settings = self.settings.borrow();
441 let theme = &settings.theme;
442
443 enum Tabs {}
444 let tabs = MouseEventHandler::new::<Tabs, _, _, _>(cx.view_id(), cx, |mouse_state, cx| {
445 let mut row = Flex::row();
446 for (ix, (_, item_view)) in self.item_views.iter().enumerate() {
447 let is_active = ix == self.active_item_index;
448
449 row.add_child({
450 let tab_style = if is_active {
451 theme.workspace.active_tab.clone()
452 } else {
453 theme.workspace.tab.clone()
454 };
455 let title = item_view.tab_content(&tab_style, cx);
456
457 let mut style = if is_active {
458 theme.workspace.active_tab.clone()
459 } else {
460 theme.workspace.tab.clone()
461 };
462 if ix == 0 {
463 style.container.border.left = false;
464 }
465
466 EventHandler::new(
467 Container::new(
468 Flex::row()
469 .with_child(
470 Align::new({
471 let diameter = 7.0;
472 let icon_color = if item_view.has_conflict(cx) {
473 Some(style.icon_conflict)
474 } else if item_view.is_dirty(cx) {
475 Some(style.icon_dirty)
476 } else {
477 None
478 };
479
480 ConstrainedBox::new(
481 Canvas::new(move |bounds, _, cx| {
482 if let Some(color) = icon_color {
483 let square = RectF::new(
484 bounds.origin(),
485 vec2f(diameter, diameter),
486 );
487 cx.scene.push_quad(Quad {
488 bounds: square,
489 background: Some(color),
490 border: Default::default(),
491 corner_radius: diameter / 2.,
492 });
493 }
494 })
495 .boxed(),
496 )
497 .with_width(diameter)
498 .with_height(diameter)
499 .boxed()
500 })
501 .boxed(),
502 )
503 .with_child(
504 Container::new(Align::new(title).boxed())
505 .with_style(ContainerStyle {
506 margin: Margin {
507 left: style.spacing,
508 right: style.spacing,
509 ..Default::default()
510 },
511 ..Default::default()
512 })
513 .boxed(),
514 )
515 .with_child(
516 Align::new(
517 ConstrainedBox::new(if mouse_state.hovered {
518 let item_id = item_view.id();
519 enum TabCloseButton {}
520 let icon = Svg::new("icons/x.svg");
521 MouseEventHandler::new::<TabCloseButton, _, _, _>(
522 item_id,
523 cx,
524 |mouse_state, _| {
525 if mouse_state.hovered {
526 icon.with_color(style.icon_close_active)
527 .boxed()
528 } else {
529 icon.with_color(style.icon_close).boxed()
530 }
531 },
532 )
533 .with_padding(Padding::uniform(4.))
534 .with_cursor_style(CursorStyle::PointingHand)
535 .on_click(move |cx| {
536 cx.dispatch_action(CloseItem(item_id))
537 })
538 .named("close-tab-icon")
539 } else {
540 Empty::new().boxed()
541 })
542 .with_width(style.icon_width)
543 .boxed(),
544 )
545 .boxed(),
546 )
547 .boxed(),
548 )
549 .with_style(style.container)
550 .boxed(),
551 )
552 .on_mouse_down(move |cx| {
553 cx.dispatch_action(ActivateItem(ix));
554 true
555 })
556 .boxed()
557 })
558 }
559
560 row.add_child(
561 Empty::new()
562 .contained()
563 .with_border(theme.workspace.tab.container.border)
564 .flexible(0., true)
565 .named("filler"),
566 );
567
568 row.boxed()
569 });
570
571 ConstrainedBox::new(tabs.boxed())
572 .with_height(theme.workspace.tab.height)
573 .named("tabs")
574 }
575}
576
577impl Entity for Pane {
578 type Event = Event;
579}
580
581impl View for Pane {
582 fn ui_name() -> &'static str {
583 "Pane"
584 }
585
586 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
587 if let Some(active_item) = self.active_item() {
588 Flex::column()
589 .with_child(self.render_tabs(cx))
590 .with_children(
591 self.active_toolbar()
592 .as_ref()
593 .map(|view| ChildView::new(view).boxed()),
594 )
595 .with_child(ChildView::new(active_item).flexible(1., true).boxed())
596 .named("pane")
597 } else {
598 Empty::new().named("pane")
599 }
600 }
601
602 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
603 self.focus_active_item(cx);
604 }
605}
606
607impl<T: Toolbar> ToolbarHandle for ViewHandle<T> {
608 fn active_item_changed(
609 &self,
610 item: Option<Box<dyn ItemViewHandle>>,
611 cx: &mut MutableAppContext,
612 ) -> bool {
613 self.update(cx, |this, cx| this.active_item_changed(item, cx))
614 }
615
616 fn to_any(&self) -> AnyViewHandle {
617 self.into()
618 }
619}
620
621impl ItemNavHistory {
622 pub fn new<T: ItemView>(history: Rc<RefCell<NavHistory>>, item_view: &ViewHandle<T>) -> Self {
623 Self {
624 history,
625 item_view: Rc::new(item_view.downgrade()),
626 }
627 }
628
629 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
630 self.history.clone()
631 }
632
633 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
634 self.history.borrow_mut().push(data, self.item_view.clone());
635 }
636}
637
638impl NavHistory {
639 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
640 self.backward_stack.pop_back()
641 }
642
643 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
644 self.forward_stack.pop_back()
645 }
646
647 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
648 match mode {
649 NavigationMode::Normal => None,
650 NavigationMode::GoingBack => self.pop_backward(),
651 NavigationMode::GoingForward => self.pop_forward(),
652 }
653 }
654
655 fn set_mode(&mut self, mode: NavigationMode) {
656 self.mode = mode;
657 }
658
659 pub fn push<D: 'static + Any>(
660 &mut self,
661 data: Option<D>,
662 item_view: Rc<dyn WeakItemViewHandle>,
663 ) {
664 match self.mode {
665 NavigationMode::Normal => {
666 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
667 self.backward_stack.pop_front();
668 }
669 self.backward_stack.push_back(NavigationEntry {
670 item_view,
671 data: data.map(|data| Box::new(data) as Box<dyn Any>),
672 });
673 self.forward_stack.clear();
674 }
675 NavigationMode::GoingBack => {
676 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
677 self.forward_stack.pop_front();
678 }
679 self.forward_stack.push_back(NavigationEntry {
680 item_view,
681 data: data.map(|data| Box::new(data) as Box<dyn Any>),
682 });
683 }
684 NavigationMode::GoingForward => {
685 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
686 self.backward_stack.pop_front();
687 }
688 self.backward_stack.push_back(NavigationEntry {
689 item_view,
690 data: data.map(|data| Box::new(data) as Box<dyn Any>),
691 });
692 }
693 }
694 }
695}