session.rs

  1mod failed;
  2mod inert;
  3pub mod running;
  4mod starting;
  5
  6use std::time::Duration;
  7
  8use dap::client::SessionId;
  9use failed::FailedState;
 10use gpui::{
 11    Animation, AnimationExt, AnyElement, App, Entity, EventEmitter, FocusHandle, Focusable,
 12    Subscription, Task, Transformation, WeakEntity, percentage,
 13};
 14use inert::{InertEvent, InertState};
 15use project::Project;
 16use project::debugger::{dap_store::DapStore, session::Session};
 17use project::worktree_store::WorktreeStore;
 18use rpc::proto::{self, PeerId};
 19use running::RunningState;
 20use starting::{StartingEvent, StartingState};
 21use task::DebugTaskDefinition;
 22use ui::{Indicator, prelude::*};
 23use util::ResultExt;
 24use workspace::{
 25    FollowableItem, ViewId, Workspace,
 26    item::{self, Item},
 27};
 28
 29use crate::debugger_panel::DebugPanel;
 30
 31pub(crate) enum DebugSessionState {
 32    Inert(Entity<InertState>),
 33    Starting(Entity<StartingState>),
 34    Failed(Entity<FailedState>),
 35    Running(Entity<running::RunningState>),
 36}
 37
 38impl DebugSessionState {
 39    pub(crate) fn as_running(&self) -> Option<&Entity<running::RunningState>> {
 40        match &self {
 41            DebugSessionState::Running(entity) => Some(entity),
 42            _ => None,
 43        }
 44    }
 45}
 46
 47pub struct DebugSession {
 48    remote_id: Option<workspace::ViewId>,
 49    mode: DebugSessionState,
 50    dap_store: WeakEntity<DapStore>,
 51    debug_panel: WeakEntity<DebugPanel>,
 52    worktree_store: WeakEntity<WorktreeStore>,
 53    workspace: WeakEntity<Workspace>,
 54    _subscriptions: [Subscription; 1],
 55}
 56
 57#[derive(Debug)]
 58pub enum DebugPanelItemEvent {
 59    Close,
 60    Stopped { go_to_stack_frame: bool },
 61}
 62
 63#[derive(Clone, Copy, PartialEq, Eq, Debug)]
 64pub enum ThreadItem {
 65    Console,
 66    LoadedSource,
 67    Modules,
 68    Variables,
 69}
 70
 71impl DebugSession {
 72    pub(super) fn inert(
 73        project: Entity<Project>,
 74        workspace: WeakEntity<Workspace>,
 75        debug_panel: WeakEntity<DebugPanel>,
 76        config: Option<DebugTaskDefinition>,
 77        window: &mut Window,
 78        cx: &mut App,
 79    ) -> Entity<Self> {
 80        let default_cwd = project
 81            .read(cx)
 82            .worktrees(cx)
 83            .next()
 84            .and_then(|tree| tree.read(cx).abs_path().to_str().map(|str| str.to_string()))
 85            .unwrap_or_default();
 86
 87        let inert =
 88            cx.new(|cx| InertState::new(workspace.clone(), &default_cwd, config, window, cx));
 89
 90        let project = project.read(cx);
 91        let dap_store = project.dap_store().downgrade();
 92        let worktree_store = project.worktree_store().downgrade();
 93        cx.new(|cx| {
 94            let _subscriptions = [cx.subscribe_in(&inert, window, Self::on_inert_event)];
 95            Self {
 96                remote_id: None,
 97                mode: DebugSessionState::Inert(inert),
 98                dap_store,
 99                worktree_store,
100                debug_panel,
101                workspace,
102                _subscriptions,
103            }
104        })
105    }
106
107    pub(crate) fn running(
108        project: Entity<Project>,
109        workspace: WeakEntity<Workspace>,
110        session: Entity<Session>,
111        debug_panel: WeakEntity<DebugPanel>,
112        window: &mut Window,
113        cx: &mut App,
114    ) -> Entity<Self> {
115        let mode = cx.new(|cx| RunningState::new(session.clone(), workspace.clone(), window, cx));
116
117        cx.new(|cx| Self {
118            _subscriptions: [cx.subscribe(&mode, |_, _, _, cx| {
119                cx.notify();
120            })],
121            remote_id: None,
122            mode: DebugSessionState::Running(mode),
123            dap_store: project.read(cx).dap_store().downgrade(),
124            debug_panel,
125            worktree_store: project.read(cx).worktree_store().downgrade(),
126            workspace,
127        })
128    }
129
130    pub(crate) fn session_id(&self, cx: &App) -> Option<SessionId> {
131        match &self.mode {
132            DebugSessionState::Inert(_) => None,
133            DebugSessionState::Starting(entity) => Some(entity.read(cx).session_id),
134            DebugSessionState::Failed(_) => None,
135            DebugSessionState::Running(entity) => Some(entity.read(cx).session_id()),
136        }
137    }
138
139    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
140        match &self.mode {
141            DebugSessionState::Inert(_) => {}
142            DebugSessionState::Starting(_entity) => {} // todo(debugger): we need to shutdown the starting process in this case (or recreate it on a breakpoint being hit)
143            DebugSessionState::Failed(_) => {}
144            DebugSessionState::Running(state) => state.update(cx, |state, cx| state.shutdown(cx)),
145        }
146    }
147
148    pub(crate) fn mode(&self) -> &DebugSessionState {
149        &self.mode
150    }
151
152    fn on_inert_event(
153        &mut self,
154        _: &Entity<InertState>,
155        event: &InertEvent,
156        window: &mut Window,
157        cx: &mut Context<Self>,
158    ) {
159        let dap_store = self.dap_store.clone();
160        let InertEvent::Spawned { config } = event;
161        let config = config.clone();
162
163        self.debug_panel
164            .update(cx, |this, _| this.last_inert_config = Some(config.clone()))
165            .log_err();
166
167        let worktree = self
168            .worktree_store
169            .update(cx, |this, _| this.worktrees().next())
170            .ok()
171            .flatten()
172            .expect("worktree-less project");
173        let Ok((new_session_id, task)) = dap_store.update(cx, |store, cx| {
174            store.new_session(config.into(), &worktree, None, cx)
175        }) else {
176            return;
177        };
178        let starting = cx.new(|cx| StartingState::new(new_session_id, task, cx));
179
180        self._subscriptions = [cx.subscribe_in(&starting, window, Self::on_starting_event)];
181        self.mode = DebugSessionState::Starting(starting);
182    }
183
184    fn on_starting_event(
185        &mut self,
186        _: &Entity<StartingState>,
187        event: &StartingEvent,
188        window: &mut Window,
189        cx: &mut Context<Self>,
190    ) {
191        if let StartingEvent::Finished(session) = event {
192            let mode =
193                cx.new(|cx| RunningState::new(session.clone(), self.workspace.clone(), window, cx));
194            self.mode = DebugSessionState::Running(mode);
195        } else if let StartingEvent::Failed = event {
196            self.mode = DebugSessionState::Failed(cx.new(FailedState::new));
197        };
198        cx.notify();
199    }
200}
201impl EventEmitter<DebugPanelItemEvent> for DebugSession {}
202
203impl Focusable for DebugSession {
204    fn focus_handle(&self, cx: &App) -> FocusHandle {
205        match &self.mode {
206            DebugSessionState::Inert(inert_state) => inert_state.focus_handle(cx),
207            DebugSessionState::Starting(starting_state) => starting_state.focus_handle(cx),
208            DebugSessionState::Failed(failed_state) => failed_state.focus_handle(cx),
209            DebugSessionState::Running(running_state) => running_state.focus_handle(cx),
210        }
211    }
212}
213
214impl Item for DebugSession {
215    type Event = DebugPanelItemEvent;
216    fn tab_content(&self, _: item::TabContentParams, _: &Window, cx: &App) -> AnyElement {
217        let (icon, label, color) = match &self.mode {
218            DebugSessionState::Inert(_) => (None, "New Session", Color::Default),
219            DebugSessionState::Starting(_) => (None, "Starting", Color::Default),
220            DebugSessionState::Failed(_) => (
221                Some(Indicator::dot().color(Color::Error)),
222                "Failed",
223                Color::Error,
224            ),
225            DebugSessionState::Running(state) => {
226                if state.read(cx).session().read(cx).is_terminated() {
227                    (
228                        Some(Indicator::dot().color(Color::Error)),
229                        "Terminated",
230                        Color::Error,
231                    )
232                } else {
233                    match state.read(cx).thread_status(cx).unwrap_or_default() {
234                        project::debugger::session::ThreadStatus::Stopped => (
235                            Some(Indicator::dot().color(Color::Conflict)),
236                            state
237                                .read_with(cx, |state, cx| state.thread_status(cx))
238                                .map(|status| status.label())
239                                .unwrap_or("Stopped"),
240                            Color::Conflict,
241                        ),
242                        _ => (
243                            Some(Indicator::dot().color(Color::Success)),
244                            state
245                                .read_with(cx, |state, cx| state.thread_status(cx))
246                                .map(|status| status.label())
247                                .unwrap_or("Running"),
248                            Color::Success,
249                        ),
250                    }
251                }
252            }
253        };
254
255        let is_starting = matches!(self.mode, DebugSessionState::Starting(_));
256
257        h_flex()
258            .gap_2()
259            .children(is_starting.then(|| {
260                Icon::new(IconName::ArrowCircle).with_animation(
261                    "starting-debug-session",
262                    Animation::new(Duration::from_secs(2)).repeat(),
263                    |this, delta| this.transform(Transformation::rotate(percentage(delta))),
264                )
265            }))
266            .when_some(icon, |this, indicator| this.child(indicator))
267            .justify_between()
268            .child(Label::new(label).color(color))
269            .into_any_element()
270    }
271}
272
273impl FollowableItem for DebugSession {
274    fn remote_id(&self) -> Option<workspace::ViewId> {
275        self.remote_id
276    }
277
278    fn to_state_proto(&self, _window: &Window, _cx: &App) -> Option<proto::view::Variant> {
279        None
280    }
281
282    fn from_state_proto(
283        _workspace: Entity<Workspace>,
284        _remote_id: ViewId,
285        _state: &mut Option<proto::view::Variant>,
286        _window: &mut Window,
287        _cx: &mut App,
288    ) -> Option<gpui::Task<gpui::Result<Entity<Self>>>> {
289        None
290    }
291
292    fn add_event_to_update_proto(
293        &self,
294        _event: &Self::Event,
295        _update: &mut Option<proto::update_view::Variant>,
296        _window: &Window,
297        _cx: &App,
298    ) -> bool {
299        // update.get_or_insert_with(|| proto::update_view::Variant::DebugPanel(Default::default()));
300
301        true
302    }
303
304    fn apply_update_proto(
305        &mut self,
306        _project: &Entity<project::Project>,
307        _message: proto::update_view::Variant,
308        _window: &mut Window,
309        _cx: &mut Context<Self>,
310    ) -> gpui::Task<gpui::Result<()>> {
311        Task::ready(Ok(()))
312    }
313
314    fn set_leader_peer_id(
315        &mut self,
316        _leader_peer_id: Option<PeerId>,
317        _window: &mut Window,
318        _cx: &mut Context<Self>,
319    ) {
320    }
321
322    fn to_follow_event(_event: &Self::Event) -> Option<workspace::item::FollowEvent> {
323        None
324    }
325
326    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<workspace::item::Dedup> {
327        if existing.session_id(cx) == self.session_id(cx) {
328            Some(item::Dedup::KeepExisting)
329        } else {
330            None
331        }
332    }
333
334    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
335        true
336    }
337}
338
339impl Render for DebugSession {
340    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
341        match &self.mode {
342            DebugSessionState::Inert(inert_state) => {
343                inert_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
344            }
345            DebugSessionState::Starting(starting_state) => {
346                starting_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
347            }
348            DebugSessionState::Failed(failed_state) => {
349                failed_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
350            }
351            DebugSessionState::Running(running_state) => {
352                running_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
353            }
354        }
355    }
356}