1
//! Eval bridge and routing logic for `App`.
2
//!
3
//! Methods that touch `console_eval`, submit nomiscript forms, route replies,
4
//! and keep the tab-fetch state machines in sync all live here so `app.rs`
5
//! stays focused on pure state shape and navigation.
6

            
7
use crate::tabs::nms::ConsoleState;
8
use cli_core::eval::config_text;
9
use cli_core::render::{WireValue, parse_wire};
10

            
11
use crate::app::App;
12
use crate::app::deliver::refresh_after;
13
use crate::app::pending::rejection;
14
use crate::form::Form;
15
use crate::route::{Route, RouteCtx};
16
use crate::tabs::config::ConfigTab;
17
use crate::tabs::fetch::Fetch;
18
use crate::tabs::list::ListTab;
19
use crate::tabs::nms::format_result;
20
use crate::tabs::nms_eval::{DrainItem, MAIN_STREAM, UNAVAILABLE};
21
use crate::view::ViewId;
22
use crate::window::WindowId;
23

            
24
impl App {
25
46
    pub fn submit_console_form(&mut self, console: WindowId, form: String) {
26
46
        if let Some(state) = self.win_mut::<ConsoleState>(console) {
27
46
            state.push_scrollback(format!("> {form}"));
28
46
            state.reset_scroll();
29
        }
30
46
        if self.console_eval.is_none() {
31
10
            self.notify(vec!["console not connected".to_string()]);
32
10
            return;
33
36
        }
34
36
        let id = self
35
36
            .console_stream(console)
36
36
            .and_then(|stream| self.submit_routed(stream, Some(console), RouteCtx::None, form));
37
36
        if id.is_none() {
38
1
            self.notify(vec![UNAVAILABLE.to_string()]);
39
35
        }
40
46
    }
41

            
42
    /// The stream of console `console`; its first call opens it.
43
36
    fn console_stream(&mut self, console: WindowId) -> Option<u32> {
44
36
        if let Some(stream) = self.win::<ConsoleState>(console)?.stream {
45
4
            return Some(stream);
46
32
        }
47
32
        let stream = self.console_eval.as_mut()?.open_stream()?;
48
32
        self.win_mut::<ConsoleState>(console)?.stream = Some(stream);
49
32
        Some(stream)
50
36
    }
51

            
52
    /// Closes the stream of console `console` when it had opened one.
53
685
    pub(super) fn close_console_stream(&mut self, console: WindowId) {
54
685
        let stream = self.win::<ConsoleState>(console).and_then(|c| c.stream);
55
685
        if let (Some(stream), Some(eval)) = (stream, &mut self.console_eval) {
56
2
            eval.close(stream);
57
683
        }
58
685
    }
59

            
60
    /// Submits `form` to the front-most console window, or to a new one; returns it.
61
7
    pub fn submit_to_console(&mut self, form: String) -> WindowId {
62
7
        let console = self.window_or_open(ViewId::Console).window;
63
7
        self.submit_console_form(console, form);
64
7
        console
65
7
    }
66

            
67
    /// Shows the first line of an app notice in the status bar; the whole text goes to the log.
68
18
    pub(super) fn notify(&mut self, lines: Vec<String>) {
69
18
        let Some(first) = lines.first() else {
70
1
            return;
71
        };
72
17
        tracing::warn!("{}", lines.join("\n"));
73
17
        let mut shown = first.clone();
74
17
        if lines.len() > 1 {
75
1
            shown.push_str(" … (see log)");
76
16
        }
77
17
        self.set_status(shown);
78
18
    }
79

            
80
    /// Aborts what the front console is evaluating.
81
5
    pub fn interrupt_console(&mut self) {
82
5
        let stream = self.front::<ConsoleState>().and_then(|c| c.stream);
83
5
        if let (Some(stream), Some(eval)) = (stream, &mut self.console_eval) {
84
4
            eval.interrupt(stream);
85
1
        }
86
5
    }
87

            
88
    /// Applies every ready reply; `true` when there was one, so the screen is stale.
89
864
    pub fn drain_eval(&mut self) -> bool {
90
        let items = {
91
864
            let Some(eval) = &mut self.console_eval else {
92
124
                return false;
93
            };
94
740
            eval.drain()
95
        };
96
740
        let any = !items.is_empty();
97
740
        for item in items {
98
107
            self.apply_drained(item);
99
        }
100
740
        any
101
864
    }
102

            
103
107
    pub(super) fn apply_drained(&mut self, item: DrainItem) {
104
107
        match item {
105
106
            DrainItem::Routed { id, wire } => self.route_reply(id, &wire),
106
1
            DrainItem::Unroutable(wire) => self.notify(format_result(&wire)),
107
        }
108
107
    }
109

            
110
73
    pub fn fetch_config(&mut self, window: WindowId) {
111
73
        let Some(seq) = self
112
73
            .win_mut::<ConfigTab>(window)
113
73
            .map(|tab| tab.seq.advance())
114
        else {
115
            return;
116
        };
117
73
        let ctx = RouteCtx::Config { seq };
118
73
        if let Some(id) = self.dispatch_eval(window, ctx, "(list-config)".to_string())
119
25
            && let Some(config) = self.win_mut::<ConfigTab>(window)
120
        {
121
25
            config.set_loading(id);
122
48
        }
123
73
    }
124

            
125
576
    pub(super) fn ensure_list_loaded(&mut self, window: WindowId) {
126
576
        let Some(list) = self.win::<ListTab>(window) else {
127
            return;
128
        };
129
576
        if !matches!(list.state, Fetch::Idle) {
130
            return;
131
576
        }
132
576
        let form = list.request_form();
133
576
        if let Some(id) = self.dispatch_eval(window, RouteCtx::None, form)
134
214
            && let Some(list) = self.win_mut::<ListTab>(window)
135
        {
136
214
            list.set_loading_id(id);
137
362
        }
138
576
    }
139

            
140
    /// Submit `form` to the eval worker, insert a `Route` to `window`, and return the id.
141
    ///
142
    /// Returns `None` when no console is attached or its ids ran out.
143
1507
    pub(super) fn dispatch_eval(
144
1507
        &mut self,
145
1507
        window: WindowId,
146
1507
        ctx: RouteCtx,
147
1507
        form: String,
148
1507
    ) -> Option<i64> {
149
1507
        self.submit_routed(MAIN_STREAM, Some(window), ctx, form)
150
1507
    }
151

            
152
    /// Like `dispatch_eval`, for a reply that belongs to the app or a dialog.
153
355
    pub(super) fn dispatch_app_eval(&mut self, ctx: RouteCtx, form: String) -> Option<i64> {
154
355
        self.submit_routed(MAIN_STREAM, None, ctx, form)
155
355
    }
156

            
157
1898
    fn submit_routed(
158
1898
        &mut self,
159
1898
        stream: u32,
160
1898
        target: Option<WindowId>,
161
1898
        ctx: RouteCtx,
162
1898
        form: String,
163
1898
    ) -> Option<i64> {
164
1898
        let eval = self.console_eval.as_mut()?;
165
1307
        let id = eval.submit(stream, form)?;
166
1305
        self.pending_routes.insert(id, Route { target, ctx });
167
1305
        Some(id)
168
1898
    }
169

            
170
    /// Drop the filter of Transactions window `window` and fetch the whole list again.
171
7
    pub fn clear_transaction_filter(&mut self, window: WindowId) {
172
7
        self.next_filter_seq(window);
173
7
        if self
174
7
            .win_mut::<ListTab>(window)
175
7
            .is_some_and(ListTab::clear_filter)
176
        {
177
7
            self.load_window(window);
178
        }
179
7
    }
180

            
181
    /// Route one drained reply to its destination window, or, if the id has
182
    /// no pending route, show the reply as an orphan-warn status. A reply to the
183
    /// pending form's own request settles the form first.
184
838
    pub(crate) fn route_reply(&mut self, id: i64, wire: &str) {
185
838
        if let Some(route) = self.take_orphan_route(id) {
186
28
            self.settle_orphan(route, wire);
187
28
            return;
188
810
        }
189
810
        let form = self.take_pending_form(id);
190
810
        let route = self.pending_routes.remove(&id);
191
810
        let mutates = route.as_ref().is_some_and(|route| route.ctx.mutates());
192
810
        let target = route.as_ref().and_then(|route| route.target);
193
810
        let failed = parse_wire(wire).is_err();
194
810
        if !failed && target.is_some() && self.status_owner == target {
195
1
            self.clear_status();
196
809
        }
197
810
        let before = self.status.clone();
198
810
        match (route, form) {
199
80
            (route, Some(form)) => self.settle_pending_form(form, route, wire),
200
726
            (Some(route), None) if self.is_stale_page(&route, id) => {}
201
721
            (Some(route), None) => self.deliver_reply(route, wire),
202
            (None, None) => {
203
4
                let mut lines = format_result(wire);
204
4
                let head = format!("[warn] orphan reply id={id}");
205
4
                match lines.first_mut() {
206
4
                    Some(first) => *first = format!("{head}: {first}"),
207
                    None => lines.push(head),
208
                }
209
4
                self.notify(lines);
210
            }
211
        }
212
810
        if failed && self.status != before {
213
76
            self.status_owner = target.filter(|_| !mutates);
214
734
        }
215
838
    }
216

            
217
    /// The route of request `id` when the window it targeted has closed.
218
838
    fn take_orphan_route(&mut self, id: i64) -> Option<Route> {
219
838
        let target = self.pending_routes.get(&id)?.target?;
220
581
        match self.window_view(target) {
221
553
            Some(_) => None,
222
28
            None => self.pending_routes.remove(&id),
223
        }
224
838
    }
225

            
226
    /// A reply for a closed window is dropped, except that a succeeded mutation still
227
    /// refreshes every window of its kind.
228
28
    fn settle_orphan(&mut self, route: Route, wire: &str) {
229
28
        if matches!(route.ctx, RouteCtx::BulkDelete { .. }) {
230
7
            return self.settle_orphan_bulk(wire);
231
21
        }
232
21
        let Some(kind) = refresh_after(&route.ctx, wire) else {
233
8
            return;
234
        };
235
13
        self.refresh_windows(kind);
236
13
        if matches!(route.ctx, RouteCtx::ConfigSet { .. }) {
237
1
            self.read_ui_config();
238
12
        }
239
28
    }
240

            
241
    /// A page fetch of the Transactions tab nobody waits for any more: a newer
242
    /// request (a filter, a refresh) superseded it.
243
726
    fn is_stale_page(&self, route: &Route, id: i64) -> bool {
244
726
        let Some(window) = route.target else {
245
225
            return false;
246
        };
247
501
        self.window_view(window) == Some(ViewId::Transactions)
248
78
            && matches!(route.ctx, RouteCtx::None)
249
17
            && self
250
17
                .win::<ListTab>(window)
251
17
                .is_some_and(|list| !list.awaits(id))
252
726
    }
253

            
254
80
    fn settle_pending_form(&mut self, form: Form, route: Option<Route>, wire: &str) {
255
80
        match parse_wire(wire) {
256
44
            Ok(WireValue::Value(value)) => match route {
257
                Some(Route {
258
                    ctx: RouteCtx::MergePreview,
259
                    ..
260
8
                }) => self.confirm_merge_preview(form, &value),
261
36
                Some(route) => self.deliver_reply(route, wire),
262
                None => {}
263
            },
264
            Err(e) => {
265
36
                self.rollback_options(&form);
266
36
                self.unlock_pending_form(form, rejection(&e));
267
            }
268
        }
269
80
    }
270
}
271

            
272
/// The text a `get-config` reply holds; a failed or empty read is no value.
273
60
pub(super) fn config_value_in(wire: &str) -> Option<String> {
274
60
    let Ok(WireValue::Value(value)) = parse_wire(wire) else {
275
1
        return None;
276
    };
277
59
    config_text(&value).ok().flatten()
278
60
}