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