session.rs

  1mod failed;
  2mod inert;
  3pub mod running;
  4mod starting;
  5
  6use std::time::Duration;
  7
  8use dap::client::SessionId;
  9use dap::DebugAdapterConfig;
 10use failed::FailedState;
 11use gpui::{
 12    percentage, Animation, AnimationExt, AnyElement, App, Entity, EventEmitter, FocusHandle,
 13    Focusable, Subscription, Task, Transformation, WeakEntity,
 14};
 15use inert::{InertEvent, InertState};
 16use project::debugger::{dap_store::DapStore, session::Session};
 17use project::worktree_store::WorktreeStore;
 18use project::Project;
 19use rpc::proto::{self, PeerId};
 20use running::RunningState;
 21use starting::{StartingEvent, StartingState};
 22use ui::prelude::*;
 23use util::ResultExt;
 24use workspace::{
 25    item::{self, Item},
 26    FollowableItem, ViewId, Workspace,
 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<DebugAdapterConfig>,
 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, &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 (label, color) = match &self.mode {
218            DebugSessionState::Inert(_) => ("New Session", Color::Default),
219            DebugSessionState::Starting(_) => ("Starting", Color::Default),
220            DebugSessionState::Failed(_) => ("Failed", Color::Error),
221            DebugSessionState::Running(state) => (
222                state
223                    .read_with(cx, |state, cx| state.thread_status(cx))
224                    .map(|status| status.label())
225                    .unwrap_or("Running"),
226                Color::Default,
227            ),
228        };
229
230        let is_starting = matches!(self.mode, DebugSessionState::Starting(_));
231
232        h_flex()
233            .gap_1()
234            .children(is_starting.then(|| {
235                Icon::new(IconName::ArrowCircle).with_animation(
236                    "starting-debug-session",
237                    Animation::new(Duration::from_secs(2)).repeat(),
238                    |this, delta| this.transform(Transformation::rotate(percentage(delta))),
239                )
240            }))
241            .child(Label::new(label).color(color))
242            .into_any_element()
243    }
244}
245
246impl FollowableItem for DebugSession {
247    fn remote_id(&self) -> Option<workspace::ViewId> {
248        self.remote_id
249    }
250
251    fn to_state_proto(&self, _window: &Window, _cx: &App) -> Option<proto::view::Variant> {
252        None
253    }
254
255    fn from_state_proto(
256        _workspace: Entity<Workspace>,
257        _remote_id: ViewId,
258        _state: &mut Option<proto::view::Variant>,
259        _window: &mut Window,
260        _cx: &mut App,
261    ) -> Option<gpui::Task<gpui::Result<Entity<Self>>>> {
262        None
263    }
264
265    fn add_event_to_update_proto(
266        &self,
267        _event: &Self::Event,
268        _update: &mut Option<proto::update_view::Variant>,
269        _window: &Window,
270        _cx: &App,
271    ) -> bool {
272        // update.get_or_insert_with(|| proto::update_view::Variant::DebugPanel(Default::default()));
273
274        true
275    }
276
277    fn apply_update_proto(
278        &mut self,
279        _project: &Entity<project::Project>,
280        _message: proto::update_view::Variant,
281        _window: &mut Window,
282        _cx: &mut Context<Self>,
283    ) -> gpui::Task<gpui::Result<()>> {
284        Task::ready(Ok(()))
285    }
286
287    fn set_leader_peer_id(
288        &mut self,
289        _leader_peer_id: Option<PeerId>,
290        _window: &mut Window,
291        _cx: &mut Context<Self>,
292    ) {
293    }
294
295    fn to_follow_event(_event: &Self::Event) -> Option<workspace::item::FollowEvent> {
296        None
297    }
298
299    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<workspace::item::Dedup> {
300        if existing.session_id(cx) == self.session_id(cx) {
301            Some(item::Dedup::KeepExisting)
302        } else {
303            None
304        }
305    }
306
307    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
308        true
309    }
310}
311
312impl Render for DebugSession {
313    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
314        match &self.mode {
315            DebugSessionState::Inert(inert_state) => {
316                inert_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
317            }
318            DebugSessionState::Starting(starting_state) => {
319                starting_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
320            }
321            DebugSessionState::Failed(failed_state) => {
322                failed_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
323            }
324            DebugSessionState::Running(running_state) => {
325                running_state.update(cx, |this, cx| this.render(window, cx).into_any_element())
326            }
327        }
328    }
329}