Skip to main content

brep_app/
javascript.rs

1//! In-app scratch scripts. Source is saved only on request and never on a model.
2use crate::{
3    document::Documents,
4    store::{ModelStore, JAVASCRIPT_DRAFT_KEY},
5};
6use crate::automation::hit_keys::HitKeyDoc;
7use eframe::egui;
8use std::collections::HashMap;
9
10/// The window's egui id — one name for the panel, the tests and the host.
11pub const WINDOW_ID: &str = "brep-javascript-editor";
12
13/// The hit keys this window publishes under `__brepJavascriptHit`
14/// (see `automation::hit_keys`); `panel:clip` is the key every scrolling pane
15/// publishes for its visible region, so `click_widget` can wheel a row into view.
16pub static HIT_KEYS: &[HitKeyDoc] = &[
17    HitKeyDoc { panel: "javascript", prefix: "panel:clip", meaning: "the JavaScript editor window's OUTER rect — its whole visible region, frame included, so the title and grip handles below count as in view", command: None },
18    HitKeyDoc { panel: "javascript", prefix: "title", meaning: "a point on the window's title bar — a drag from it MOVES the window", command: None },
19    HitKeyDoc { panel: "javascript", prefix: "grip", meaning: "a point on the window's bottom-right resize corner — a drag from it RESIZES the window in both axes, up to the app surface", command: None },
20    HitKeyDoc { panel: "javascript", prefix: "run", meaning: "run the script in the active document", command: None },
21    HitKeyDoc { panel: "javascript", prefix: "cancel", meaning: "cancel the running script", command: None },
22    HitKeyDoc { panel: "javascript", prefix: "save", meaning: "save the source as the local draft", command: None },
23    HitKeyDoc { panel: "javascript", prefix: "open", meaning: "open a .js file into the editor (native; file-interchange stores only)", command: None },
24    HitKeyDoc { panel: "javascript", prefix: "export", meaning: "export the source as script.js through the file dialog's export door: the Save-file chooser on desktop, a download in the browser", command: None },
25    HitKeyDoc { panel: "javascript", prefix: "help", meaning: "the CAD API and examples collapsing header", command: None },
26    HitKeyDoc { panel: "javascript", prefix: "example", meaning: "load the box example into the editor (inside `help`)", command: None },
27    HitKeyDoc { panel: "javascript", prefix: "source", meaning: "the source editor's scroll region (the free space of the window: it grows with the window)", command: None },
28    HitKeyDoc { panel: "javascript", prefix: "output", meaning: "the output's scroll region, at the bottom of the window", command: None },
29];
30
31const EXAMPLE: &str = r#"// Run adds a box to the current document. Undo removes the whole run.
32cad.document.addFeature("P.CU", { sizeX: 30, sizeY: 20, sizeZ: 10 });
33console.log("Created a box");
34ui.notify("Edit its dimensions in the feature history");
35return { featuresBefore: cad.document.features.length };
36"#;
37
38/// Where Run sends a program when the app has a script runner: the app's
39/// own server's code mode (`crate::mcp::EditorHost`), the same worker, limits
40/// and `sdk.<namespace>.<action>` functions an agent's `run` program gets.
41/// Without one (the web build, a bare test harness) Run uses the plugin
42/// runner's editor action.
43pub trait ScriptHost {
44    /// Whether the runner is up; the first call starts it.
45    fn ready(&self) -> Result<bool, String>;
46    /// Submit a program; answers its execution id.
47    fn run(&self, source: &str) -> Result<String, String>;
48    /// The execution's result once it has ended, `None` while it runs.
49    fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String>;
50    /// Halt it: the worker is killed wherever it is.
51    fn halt(&self, id: &str) -> Result<(), String>;
52}
53
54/// A run on the [`ScriptHost`], in its document. Its edits fold into one
55/// undo group, kept when the program succeeds and rolled back otherwise, as
56/// the plugin runner's transaction is.
57enum Script {
58    Starting { doc: u64, program: String },
59    Running { doc: u64, id: String, token: u64 },
60    /// Ended: the group closes once the document's engine is idle, so a
61    /// staged feature still landing folds in (or rolls back) with the rest.
62    Closing { doc: u64, token: u64, rollback: bool, output: String, since: web_time::Instant, idle: u32 },
63}
64
65/// How long a closing run waits for its document to go idle before the
66/// group closes anyway (an edit still landing then stands on its own).
67const CLOSE_WAIT: std::time::Duration = std::time::Duration::from_secs(30);
68
69/// A closing run's document must read idle this many polls running, and
70/// [`CLOSE_SETTLE`] must have passed: a tool call the program issued just
71/// before it ended (or was killed) may still be on its way to the app's
72/// queue, which drains AFTER this poll in the frame, and its edit belongs in
73/// the group.
74const CLOSE_IDLE_POLLS: u32 = 5;
75const CLOSE_SETTLE: std::time::Duration = std::time::Duration::from_millis(250);
76
77/// An editor script as a program for the [`ScriptHost`]: both are plain
78/// script bodies with top-level `await` and `return`, and `sdk` (every app
79/// command as `await sdk.<namespace>.<action>(args)`) is the runner's global.
80/// The editor adds its own names around the body: `cad.document` (the history
81/// snapshot with `addFeature(type, params, persistentData)`,
82/// `updateFeature(id, params)` (a merge, as `feature_set_params` merges) and
83/// `deleteFeature(id)`), `cad.selection`, `cad.sdk` (the same `sdk`) and
84/// `ui.notify`. The document commands apply in order after the body returns,
85/// and a returned value prints as `Result:`. One leading
86/// `import … from "@brep/cad"` line is dropped, as the runner drops it.
87pub fn program(source: &str) -> String {
88    let source = without_sdk_import(source);
89    format!(
90        r#"const __commands = [];
91const __stage = c => {{ if (__commands.length >= 256) throw Error("too many document commands"); __commands.push(c); }};
92const __snapshot = (await sdk.document.doc_json({{}})).document;
93const __selection = (await sdk.scene.selection({{}})).selection;
94const __document = Object.freeze({{
95  ...__snapshot,
96  addFeature: (type, params = {{}}, persistentData = {{}}) => __stage(() => sdk.features.feature_add(Object.keys(persistentData).length ? {{ type, params, persistent_data: persistentData }} : {{ type, params }})),
97  updateFeature: (id, params) => __stage(() => sdk.features.feature_set_params({{ id, patch: params }})),
98  deleteFeature: id => __stage(() => sdk.history.feature_delete({{ id }})),
99}});
100const __notify = message => console.log(String(message));
101const __result = await (async function (cad, ui) {{
102{source}
103}})(Object.freeze({{ document: __document, selection: __selection, params: {{}}, notify: __notify, sdk }}), Object.freeze({{ notify: __notify }}));
104for (const command of __commands) await command();
105if (__result !== undefined) console.log("Result:", JSON.stringify(__result));
106return null;
107"#
108    )
109}
110
111/// `source` with its first statement blanked when that is an
112/// `import … from "@brep/cad"` line (a script written as an agent's module
113/// would be): the editor's wrapper comes first, so the runner's own strip
114/// never sees it. Its line stays, so the rows below keep their numbers.
115fn without_sdk_import(source: &str) -> String {
116    let Some(first) = source.lines().find(|l| !l.trim().is_empty() && !l.trim_start().starts_with("//")) else { return source.to_string() };
117    let line = first.trim();
118    let import = line.starts_with("import") && (line.ends_with("\"@brep/cad\";") || line.ends_with("\"@brep/cad\"") || line.ends_with("'@brep/cad';") || line.ends_with("'@brep/cad'"));
119    if !import {
120        return source.to_string();
121    }
122    source.replacen(first, "", 1)
123}
124
125/// What a finished execution shows: the outcome, the console lines, and a
126/// module's returned value.
127fn script_output(result: &serde_json::Value) -> String {
128    let mut lines = vec![match result["state"].as_str() {
129        Some("succeeded") => "Completed.".to_string(),
130        Some("cancelled") => "Cancelled.".to_string(),
131        _ => format!("Failed: {}", result["error"]["message"].as_str().unwrap_or("the script failed")),
132    }];
133    if let Some(log) = result["logText"].as_str().filter(|l| !l.is_empty()) {
134        lines.push(log.to_string());
135    }
136    if !result["output"].is_null() {
137        lines.push(format!("Result: {}", result["output"]));
138    }
139    lines.join("\n")
140}
141
142pub struct JavaScriptEditor {
143    pub open: bool,
144    source: String,
145    output: String,
146    pending: Option<u64>, // originating document, retained across tab switches
147    /// The app's script runner, when it has one (see [`ScriptHost`]).
148    pub host: Option<Box<dyn ScriptHost>>,
149    script: Option<Script>,
150    importing: bool,
151    /// This frame's widget rects (egui points) for the automation host; empty
152    /// while the window is closed.
153    hits: HashMap<String, egui::Rect>,
154    /// The window's outer rect this frame, `None` while it is closed.
155    rect: Option<egui::Rect>,
156    /// The surface the window may fill (`ctx.content_rect()`), for the host.
157    surface: egui::Rect,
158    /// "Export .js…" asked: the shell hands these to the file dialog's export
159    /// door ([`Self::take_save_requests`]), which on desktop asks where.
160    exports: Vec<crate::panels::file::SaveRequest>,
161}
162
163
164impl JavaScriptEditor {
165    pub fn running_in(&self, document: u64) -> bool {
166        self.pending == Some(document)
167    }
168
169    pub fn set_source(&mut self, source: String) {
170        self.source = source;
171    }
172
173    pub fn editing_source(ctx: &egui::Context) -> bool {
174        ctx.memory(|memory| memory.has_focus(egui::Id::new("cad-javascript-source")))
175    }
176
177    pub fn new(store: &dyn ModelStore) -> Self {
178        Self {
179            open: false,
180            source: store
181                .read(JAVASCRIPT_DRAFT_KEY)
182                .unwrap_or_else(|| EXAMPLE.into()),
183            output: String::new(),
184            pending: None,
185            host: None,
186            script: None,
187            importing: false,
188            hits: HashMap::new(),
189            exports: Vec::new(),
190            rect: None,
191            surface: egui::Rect::NOTHING,
192        }
193    }
194
195    /// Logical state for the automation host: `rect` is the window's outer
196    /// rect `[x, y, w, h]` in egui points (null while closed), `surface` the
197    /// screen rect it may fill `[w, h]`.
198    pub fn state_json(&self) -> String {
199        let rect = |r: egui::Rect| serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]);
200        serde_json::json!({
201            "open": self.open,
202            "rect": self.rect.map(rect),
203            "surface": [self.surface.width(), self.surface.height()],
204            "running": self.pending.is_some(),
205            "output": self.output,
206        })
207        .to_string()
208    }
209
210    /// The published widget hit-rects (`[x, y, w, h]`, egui points).
211    pub fn hits_json(&self) -> String {
212        crate::automation::hit_rects::hits_json(&self.hits)
213    }
214
215    /// Halt the running script and roll its edits back once its document
216    /// is idle; `output` says why.
217    fn halt_script(&mut self, docs: &mut Documents, output: String) {
218        match self.script.take() {
219            Some(Script::Starting { .. }) => {
220                self.pending = None;
221                self.output = output;
222            }
223            Some(Script::Running { doc, id, token }) => {
224                if let Some(host) = &self.host {
225                    let _ = host.halt(&id);
226                }
227                // Brake a history run the script started, as the app's
228                // cancel button does; a staged feature then rolls back.
229                if let Some(d) = docs.iter_mut().find(|d| d.id() == doc) {
230                    d.engine.cancel_run();
231                }
232                self.script = Some(Script::Closing { doc, token, rollback: true, output, since: web_time::Instant::now(), idle: 0 });
233            }
234            other => self.script = other,
235        }
236    }
237
238    /// One frame of a run on the [`ScriptHost`].
239    fn poll_script(&mut self, ctx: &egui::Context, docs: &mut Documents) {
240        ctx.request_repaint_after(std::time::Duration::from_millis(30));
241        let doc_id = match &self.script {
242            Some(Script::Starting { doc, .. } | Script::Running { doc, .. } | Script::Closing { doc, .. }) => *doc,
243            None => return,
244        };
245        if !docs.iter().any(|d| d.id() == doc_id) {
246            if let (Some(Script::Running { id, .. }), Some(host)) = (&self.script, &self.host) {
247                let _ = host.halt(id);
248            }
249            self.script = None;
250            self.pending = None;
251            self.output = "The script's document was closed.".into();
252            return;
253        }
254        // The app's tools act on the ACTIVE document: a run whose document
255        // is no longer active would write another one.
256        if docs.active_id() != doc_id && matches!(self.script, Some(Script::Starting { .. } | Script::Running { .. })) {
257            return self.halt_script(docs, "Halted: the active document changed while the script ran; its edits were rolled back.".into());
258        }
259        let Some(host) = &self.host else { return };
260        let doc = docs.iter_mut().find(|d| d.id() == doc_id).expect("checked above");
261        match self.script.take() {
262            Some(Script::Starting { doc: d, program }) => match host.ready() {
263                Ok(true) => {
264                    let token = doc.engine.history_group_begin();
265                    match host.run(&program) {
266                        Ok(id) => self.script = Some(Script::Running { doc: d, id, token }),
267                        Err(e) => {
268                            let _ = doc.engine.history_group_end(token, false);
269                            self.pending = None;
270                            self.output = e;
271                        }
272                    }
273                }
274                Ok(false) => self.script = Some(Script::Starting { doc: d, program }),
275                Err(e) => {
276                    self.pending = None;
277                    self.output = e;
278                }
279            },
280            Some(Script::Running { doc: d, id, token }) => match host.result(&id) {
281                Ok(None) => self.script = Some(Script::Running { doc: d, id, token }),
282                Ok(Some(result)) => {
283                    let rollback = result["state"] != "succeeded";
284                    let output = script_output(&result);
285                    self.script = Some(Script::Closing { doc: d, token, rollback, output, since: web_time::Instant::now(), idle: 0 });
286                }
287                Err(e) => self.script = Some(Script::Closing { doc: d, token, rollback: true, output: e, since: web_time::Instant::now(), idle: 0 }),
288            },
289            Some(Script::Closing { doc: d, token, rollback, output, since, idle }) => {
290                doc.engine.pump();
291                let quiet = !doc.engine.run_pending() && !doc.engine.stage_feature_pending();
292                let idle = if quiet { idle + 1 } else { 0 };
293                let settled = idle >= CLOSE_IDLE_POLLS && since.elapsed() >= CLOSE_SETTLE;
294                if !settled && since.elapsed() < CLOSE_WAIT {
295                    self.script = Some(Script::Closing { doc: d, token, rollback, output, since, idle });
296                    return;
297                }
298                self.pending = None;
299                self.output = match doc.engine.history_group_end(token, rollback) {
300                    Ok(true) => format!("{output}\nIts edits were rolled back."),
301                    Ok(false) => output,
302                    Err(e) => format!("{output}\n{e}"),
303                };
304            }
305            None => {}
306        }
307    }
308
309    /// Record a widget's VISIBLE rect for the host.
310    fn hit(&mut self, key: &str, resp: &egui::Response) {
311        self.hits.insert(key.to_string(), resp.interact_rect);
312    }
313
314    pub fn poll(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
315        if self.importing {
316            if let Some(file) = store.take_import() {
317                self.importing = false;
318                match String::from_utf8(file.bytes) {
319                    Ok(source) => self.source = source,
320                    Err(e) => self.output = format!("Cannot open script: {e}"),
321                }
322            }
323        }
324        if self.script.is_some() {
325            return self.poll_script(ctx, docs);
326        }
327        let Some(id) = self.pending else {
328            return;
329        };
330        let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) else {
331            self.pending = None;
332            self.output = "The script's document was closed.".into();
333            return;
334        };
335        doc.engine.pump();
336        let status = doc.engine.plugin_action_status();
337        match status["state"].as_str() {
338            Some("complete") => {
339                let lines: Vec<_> = status["result"]["notifications"]
340                    .as_array()
341                    .into_iter()
342                    .flatten()
343                    .filter_map(|v| v.as_str())
344                    .collect();
345                self.output = format!("Completed.\n{}", lines.join("\n"));
346                self.pending = None;
347            }
348            Some("error") => {
349                self.output = status["error"].as_str().unwrap_or("Script failed").into();
350                self.pending = None;
351            }
352            _ => {
353                ctx.request_repaint_after(std::time::Duration::from_millis(30));
354            }
355        }
356    }
357
358    /// The files "Export .js…" asked to save, once: the shell hands them to
359    /// [`crate::panels::file::FileDialog::request_save_file`].
360    pub fn take_save_requests(&mut self) -> Vec<crate::panels::file::SaveRequest> {
361        std::mem::take(&mut self.exports)
362    }
363
364    pub fn show(&mut self, ctx: &egui::Context, docs: &mut Documents, store: &dyn ModelStore) {
365        self.hits.clear();
366        self.rect = None;
367        self.surface = ctx.content_rect();
368        let mut open = self.open;
369        let shown = egui::Window::new("JavaScript editor").id(egui::Id::new(WINDOW_ID)).open(&mut open)
370            // Under the toolbar / Ribbon like Settings, Plugins and Info: without
371            // a position egui put it over the menu bar (ui-polish-2026-10-28 row 5).
372            .default_pos(crate::panels::below_chrome(ctx, 16.0, 0.0))
373            .default_size(egui::vec2(720.0, 620.0)).min_size(egui::vec2(420.0, 320.0)).resizable(true).show(ctx, |ui| {
374            ui.label(format!("Run in: {}", docs.active().title()));
375            if let Some(id) = self.pending {
376                if let Some(doc) = docs.iter().find(|doc| doc.id() == id) {
377                    ui.horizontal(|ui| {
378                        ui.spinner();
379                        ui.label(format!("Running in: {}", doc.title()));
380                    });
381                }
382            }
383            ui.horizontal(|ui| {
384                let busy = self.pending.is_some() || docs.engine().run_pending()
385                    || docs.engine().plugin_action_status()["state"] == "pending";
386                let run = ui.add_enabled(!busy, egui::Button::new("Run script"));
387                self.hit("run", &run);
388                // `cad.geometry` (kernel solids in an editor body) is the
389                // plugin runner's; such a script stays there.
390                if run.clicked() && self.host.is_some() && !self.source.contains("cad.geometry") {
391                    self.pending = Some(docs.active_id());
392                    self.script = Some(Script::Starting { doc: docs.active_id(), program: program(&self.source) });
393                    self.output = "Running…".into();
394                } else if run.clicked() {
395                    match docs.engine_mut().run_javascript(&self.source) {
396                        Ok(_) => { self.pending = Some(docs.active_id()); self.output = "Running…".into(); }
397                        Err(e) => self.output = e,
398                    }
399                }
400                let cancel = ui.add_enabled(self.pending.is_some(), egui::Button::new("Cancel"));
401                self.hit("cancel", &cancel);
402                if cancel.clicked() && self.script.is_some() {
403                    self.halt_script(docs, "Cancelled.".into());
404                } else if cancel.clicked() {
405                    if let Some(id) = self.pending {
406                        if let Some(doc) = docs.iter_mut().find(|doc| doc.id() == id) {
407                            doc.engine.cancel_plugin_action();
408                        }
409                    }
410                }
411                let save = ui.button("Save draft");
412                self.hit("save", &save);
413                if save.clicked() {
414                    self.output = match store.write(JAVASCRIPT_DRAFT_KEY, &self.source) {
415                        Ok(()) => "Draft saved.".into(), Err(e) => format!("Cannot save draft: {e}"),
416                    };
417                }
418                // Open .js… drives the browser's file input, so only where
419                // there is one. Export leaves through the file dialog's export
420                // door on every platform (the Save-file chooser on desktop),
421                // so it is always offered: gated with Open, desktop had no
422                // way to export a script at all.
423                if store.supports_file_interchange() {
424                    let open = ui.add_enabled(!self.importing, egui::Button::new("Open .js…"));
425                    self.hit("open", &open);
426                    if open.clicked() {
427                        match store.begin_import_filtered(("JavaScript", &["js"])) {
428                            Ok(()) => self.importing = true, Err(e) => self.output = e,
429                        }
430                    }
431                }
432                let export = ui.button("Export .js…");
433                self.hit("export", &export);
434                if export.clicked() {
435                    self.exports.push(crate::panels::file::SaveRequest::text("Export the script", "script.js", self.source.clone()));
436                }
437            });
438            let help = ui.collapsing("CAD API and examples", |ui| {
439                ui.label("Write JavaScript statements. cad.document is a snapshot of the current history; cad.selection contains the current selection.");
440                ui.monospace("cad.document.addFeature(type, params)\ncad.document.updateFeature(id, params)\ncad.document.deleteFeature(id)\nconsole.log / info / warn / error(...)\nui.notify(text)\nreturn { any: 'JSON result' };");
441                ui.label("Built-in types include P.CU (sizeX, sizeY, sizeZ), P.S (radius), and P.CY (radius, height). Successful changes form one undo step. Each Run executes the script again.");
442                if self.host.is_some() {
443                    ui.label("Every app command is a function too: await sdk.<namespace>.<action>(args), the same functions an agent's run program gets (the MCP sdk tool lists and types them). The script is a plain body: await at the top level, and return a value to see it as Result. A failed or cancelled run is rolled back.");
444                }
445                let example = ui.button("Load box example");
446                if example.clicked() { self.source = EXAMPLE.into(); }
447                example
448            });
449            self.hits.insert("help".into(), help.header_response.interact_rect);
450            if let Some(example) = help.body_returned {
451                self.hits.insert("example".into(), example.interact_rect);
452            }
453            // The rest of the window is the editor over the output. Two panels
454            // rather than two capped scroll areas: egui sizes a window's axis to
455            // its CONTENT (its Resize is not resizable, the content ui merely
456            // gets the dragged size as its max rect), so content that does not
457            // fill the dragged size snaps the window back to the content's
458            // height. Panels fill whatever the window is given, so the window
459            // follows the drag — up to the surface, which egui clamps to.
460            // The output panel keeps its own height (draggable at its top edge)
461            // and the editor takes everything above it.
462            egui::containers::panel::Panel::bottom(egui::Id::new("brep-javascript-output"))
463                .resizable(true)
464                .default_size(160.0)
465                .min_size(48.0)
466                .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4)))
467                .show_inside(ui, |ui| {
468                    ui.label("Output");
469                    let output = egui::ScrollArea::both().id_salt("javascript-output").auto_shrink(false).show(ui, |ui| {
470                        ui.add(egui::Label::new(egui::RichText::new(&self.output).monospace()).selectable(true));
471                    });
472                    self.hits.insert("output".into(), output.inner_rect);
473                });
474            egui::CentralPanel::default().frame(egui::Frame::NONE).show_inside(ui, |ui| {
475                // The text box fills the free space, so a click in the empty
476                // area under a short script still lands in the editor. By ROWS:
477                // egui's `TextEdit::min_size` honours only the width, and the
478                // box's height is its rows (or its text, whichever is taller).
479                // Floored, so a box that fills the space never scrolls by the
480                // odd point.
481                let free = ui.available_height();
482                let row = ui.fonts_mut(|f| f.row_height(&egui::TextStyle::Monospace.resolve(ui.style())));
483                let rows = ((free - 4.0) / row).floor().max(4.0) as usize;
484                let source = egui::ScrollArea::both().id_salt("javascript-source").auto_shrink(false).show(ui, |ui| {
485                    ui.add(egui::TextEdit::multiline(&mut self.source).code_editor()
486                        .id(egui::Id::new("cad-javascript-source"))
487                        .desired_rows(rows).desired_width(f32::INFINITY));
488                });
489                self.hits.insert("source".into(), source.inner_rect);
490            });
491        });
492        // Published only while OPEN: egui keeps returning the window through its
493        // fade-out, and a host reading a rect for a window the user just closed
494        // would drag on nothing.
495        if let (Some(shown), true) = (shown, open) {
496            let rect = shown.response.rect;
497            self.rect = Some(rect);
498            // The window's handles, as points egui's own hit zones answer to: the
499            // title bar's centre (a drag moves the window) and a point just inside
500            // the bottom-right corner, within the corner grab radius (a drag
501            // resizes). `panel:clip` is the outer rect so both read as in view.
502            self.hits.insert("panel:clip".into(), rect);
503            self.hits.insert("title".into(), egui::Rect::from_center_size(egui::pos2(rect.center().x, rect.min.y + 12.0), egui::Vec2::ZERO));
504            self.hits.insert("grip".into(), egui::Rect::from_center_size(rect.max - egui::vec2(3.0, 3.0), egui::Vec2::ZERO));
505        } else {
506            self.hits.clear();
507        }
508        self.open = open;
509    }
510}