Working application

This commit is contained in:
elvis
2025-10-17 21:42:41 +02:00
parent 3472a31584
commit 617af61d7c
35 changed files with 8725 additions and 0 deletions

View File

@ -0,0 +1,39 @@
[package]
name = "reaction_systems_gui"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
log = "*"
eframe = "0.32"
anyhow = "1"
serde = { version = "1", optional = true }
colored = "*"
lalrpop-util = "*"
petgraph = ">=0.8"
egui_node_graph2 = { path = "../egui_node_graph2" }
petgraph-graphml = "*"
getrandom = { version = "0.3" }
layout-rs = "0.1"
rfd = "*"
ron = "*"
# rsprocess = { version = "*", git = "https://tautocrono.it/elvis/ReactionSystems.git" }
rsprocess = { version = "*", path = "../../ReactionSystems/rsprocess/" }
assert = { version = "*", path = "../../ReactionSystems/assert/" }
execution = { version = "*", path = "../../ReactionSystems/execution/" }
bisimilarity = { version = "*", path = "../../ReactionSystems/bisimilarity/" }
grammar_separated = { version = "*", path = "../../ReactionSystems/grammar_separated/" }
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-futures = "*"
getrandom = { version = "0.3", features = ["wasm_js"]}
[features]
default = []
persistence = ["serde", "egui_node_graph2/persistence", "eframe/persistence"]

View File

@ -0,0 +1,75 @@
#!/bin/bash
set -eu
script_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$script_path"
OPEN=false
FAST=false
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "build_web.sh [--fast] [--open]"
echo " --fast: skip optimization step"
echo " --open: open the result in a browser"
exit 0
;;
--fast)
shift
FAST=true
;;
--open)
shift
OPEN=true
;;
*)
break
;;
esac
done
# ./setup_web.sh # <- call this first!
CRATE_NAME="reaction_systems_gui"
CRATE_NAME_SNAKE_CASE="${CRATE_NAME//-/_}" # for those who name crates with-kebab-case
# This is required to enable the web_sys clipboard API which egui_web uses
# https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Clipboard.html
# https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
export RUSTFLAGS='--cfg=web_sys_unstable_apis --cfg getrandom_backend="wasm_js"'
# Clear output from old stuff:
rm -f "docs/${CRATE_NAME_SNAKE_CASE}_bg.wasm"
echo "Building rust…"
BUILD=release
cargo build -p "${CRATE_NAME}" --release --all-features --lib --target wasm32-unknown-unknown
# Get the output directory (in the workspace it is in another location)
TARGET=$(cargo metadata --format-version=1 | jq --raw-output .target_directory)
echo "Generating JS bindings for wasm…"
TARGET_NAME="${CRATE_NAME_SNAKE_CASE}.wasm"
wasm-bindgen "${TARGET}/wasm32-unknown-unknown/${BUILD}/${TARGET_NAME}" \
--out-dir docs --no-modules --no-typescript
if [[ "${FAST}" == false ]]; then
echo "Optimizing wasm…"
# to get wasm-opt: apt/brew/dnf install binaryen
wasm-opt "docs/${CRATE_NAME}_bg.wasm" -O2 --fast-math -o "docs/${CRATE_NAME}_bg.wasm" # add -g to get debug symbols
fi
echo "Finished: docs/${CRATE_NAME_SNAKE_CASE}.wasm"
if [[ "${OPEN}" == true ]]; then
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux, ex: Fedora
xdg-open http://localhost:8080/index.html
elif [[ "$OSTYPE" == "msys" ]]; then
# Windows
start http://localhost:8080/index.html
else
# Darwin/MacOS, or something else
open http://localhost:8080/index.html
fi
fi

10
reaction_systems_gui/check.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/bash
# This scripts runs various CI-like checks in a convenient way.
set -eux
cargo check --workspace --all-targets
cargo check --workspace --all-features --lib --target wasm32-unknown-unknown
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings -W clippy::all
cargo test --workspace --all-targets --all-features
cargo test --workspace --doc

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

View File

@ -0,0 +1,209 @@
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Disable zooming: -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<title>eframe template</title>
<style>
html {
touch-action: manipulation;
}
/* dark mode preference support */
body {
background: #909090;
}
@media (prefers-color-scheme: dark) {
body {
background: #404040;
}
}
html, body {
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
width: 100%;
height: 100%;
}
#rscanvas {
width: 100%;
height: 100%;
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 0%;
left: 50%;
transform: translate(-50%, 0%);
}
.loading {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
font-family: Ubuntu-Light, Helvetica, sans-serif;
}
/* ---------------------------------------------- */
/* Loading animation from https://loading.io/css/ */
.lds-dual-ring {
display: inline-block;
width: 24px;
height: 24px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 24px;
height: 24px;
margin: 0px;
border-radius: 50%;
border: 3px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<link rel="manifest" href="./manifest.json">
<script>
// register ServiceWorker
window.onload = () => {
'use strict';
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./sw.js');
}
}
</script>
</head>
<body>
<!-- The WASM code will resize this canvas to cover the entire screen -->
<canvas id="rscanvas"></canvas>
<div class="loading" id="loading">
Loading…&nbsp;&nbsp;
<div class="lds-dual-ring"></div>
</div>
<script>
// The `--no-modules`-generated JS from `wasm-bindgen` attempts to use
// `WebAssembly.instantiateStreaming` to instantiate the wasm module,
// but this doesn't work with `file://` urls. This example is frequently
// viewed by simply opening `index.html` in a browser (with a `file://`
// url), so it would fail if we were to call this function!
//
// Work around this for now by deleting the function to ensure that the
// `no_modules.js` script doesn't have access to it. You won't need this
// hack when deploying over HTTP.
delete WebAssembly.instantiateStreaming;
</script>
<!-- This is the JS generated by the `wasm-bindgen` CLI tool -->
<script src="reaction_systems_gui.js"></script>
<script>
console.debug("Loading wasm…");
// We'll defer our execution until the wasm is ready to go.
// Here we tell bindgen the path to the wasm file so it can start
// initialization and return to us a promise when it's done.
wasm_bindgen("./reaction_systems_gui_bg.wasm")
.then(on_wasm_loaded)
.catch(console.error);
function on_wasm_loaded() {
console.log("loaded wasm, starting egui app…");
// // This call installs a bunch of callbacks and then returns:
// wasm_bindgen.start("the_canvas_id");
let rscanvas = document.getElementById("rscanvas");
let handle = new wasm_bindgen.WebHandle();
function check_for_panic() {
if (handle.has_panicked()) {
console.error("The egui app has crashed");
// The demo app already logs the panic message and callstack, but you
// can access them like this if you want to show them in the html:
// console.error(`${handle.panic_message()}`);
// console.error(`${handle.panic_callstack()}`);
// document.getElementById("the_canvas_id").remove();
// document.getElementById("center_text").innerHTML = `
// <p>
// The egui app has crashed.
// </p>
// <p style="font-size:10px" align="left">
// ${handle.panic_message()}
// </p>
// <p style="font-size:14px">
// See the console for details.
// </p>
// <p style="font-size:14px">
// Reload the page to try again.
// </p>`;
} else {
let delay_ms = 1000;
setTimeout(check_for_panic, delay_ms);
}
}
check_for_panic();
handle.start(rscanvas).then(on_app_started).catch(on_error);
console.log("egui app started.");
document.getElementById("loading").remove();
}
function on_app_started(handle) {
// Call `handle.destroy()` to stop. Uncomment to quick result:
// setTimeout(() => { handle.destroy(); handle.free()) }, 2000)
console.debug("App started.");
// document.getElementById("center_text").innerHTML = '';
// Make sure the canvas is focused so it can receive keyboard events right away:
rscanvas.focus();
}
function on_error(error) {
console.error("Failed to start: " + error);
rscanvas.remove();
// document.getElementById("center_text").innerHTML = `
// <p>
// An error occurred during loading:
// </p>
// <p style="font-family:Courier New">
// ${error}
// </p>
// <p style="font-size:14px">
// Make sure you use a modern browser with WebGL and WASM enabled.
// </p>`;
}
</script>
</body>
</html>

View File

@ -0,0 +1,14 @@
{
"name": "Egui Template PWA",
"short_name": "egui-template-pwa",
"icons": [{
"src": "./icon-256.png",
"sizes": "256x256",
"type": "image/png"
}],
"lang": "en-US",
"start_url": "./index.html",
"display": "standalone",
"background_color": "white",
"theme_color": "white"
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -0,0 +1,25 @@
var cacheName = 'egui-template-pwa';
var filesToCache = [
'./',
'./index.html',
'./reaction_systems_gui.js',
'./reaction_systems_gui_bg.wasm',
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll(filesToCache);
})
);
});
/* Serve cached content when offline */
self.addEventListener('fetch', function (e) {
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
})
);
});

View File

@ -0,0 +1,10 @@
#!/bin/bash
set -eu
# Pre-requisites:
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
cargo update -p wasm-bindgen
# For local tests with `./start_server`:
cargo install basic-http-server

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,163 @@
use std::fmt::Display;
use eframe::egui::{self, Color32, TextFormat, TextStyle};
use egui::text::LayoutJob;
use grammar_separated::user_error::{UserError, UserErrorTypes};
use lalrpop_util::ParseError;
fn create_error<T>(
input_str: &str,
l: usize,
t: T,
r: usize,
expected: Option<Vec<String>>,
error: Option<UserErrorTypes>,
ctx: &eframe::egui::Context,
) -> LayoutJob
where
T: Display,
{
let style = ctx.style();
let monospace_text = TextStyle::Monospace.resolve(&style);
let monospace = TextFormat {
font_id: monospace_text.clone(),
..Default::default()
};
let monospace_red = TextFormat {
font_id: monospace_text.clone(),
color: Color32::RED,
..Default::default()
};
let monospace_blue = TextFormat {
font_id: monospace_text.clone(),
color: Color32::BLUE,
..Default::default()
};
let monospace_green = TextFormat {
font_id: monospace_text,
color: Color32::GREEN,
..Default::default()
};
let mut err = LayoutJob::default();
if let Some(error) = error {
err.append(&format!("{error} "), 0., Default::default());
err.append(&format!("\"{t}\""), 0., monospace_red.clone());
err.append(
&format!(" between positions {l} and {r}."),
0.,
Default::default(),
);
} else {
err.append("Unrecognized token ", 0., Default::default());
err.append(&format!("\"{t}\""), 0., monospace_red.clone());
err.append(
&format!(" between positions {l} and {r}."),
0.,
Default::default(),
);
}
{
if let Some(expected) = expected {
// Temporary debug.
err.append("\nExpected: ", 0., Default::default());
let mut it = expected.iter().peekable();
while let Some(s) = it.next() {
err.append("(", 0., monospace.clone());
err.append(s, 0., monospace_green.clone());
err.append(")", 0., monospace.clone());
if it.peek().is_some() {
err.append(", ", 0., monospace.clone());
}
}
}
}
let right_new_line = input_str[l..]
.find("\n")
.map(|pos| pos + l)
.unwrap_or(input_str.len());
let left_new_line = input_str[..r]
.rfind("\n")
.map(|pos| pos + 1)
.unwrap_or_default();
let line_number = input_str[..l].match_indices('\n').count() + 1;
let pre = format!("{line_number} |");
let line_pos_l = l - left_new_line;
let line_pos_r = r - left_new_line;
err.append(
&format!(
"\nLine {} position {} to {}:\n",
line_number, line_pos_l, line_pos_r,
),
0.,
Default::default(),
);
err.append(&pre, 0., monospace_blue.clone());
err.append(&input_str[left_new_line..l], 0., monospace_green);
err.append(&input_str[l..r], 0., monospace_red.clone());
err.append(&input_str[r..right_new_line], 0., monospace.clone());
err.append("\n", 0., monospace.clone());
err.append(&" ".repeat(pre.len() - 1), 0., monospace.clone());
err.append("|", 0., monospace_blue);
err.append(&" ".repeat(l - left_new_line), 0., monospace.clone());
err.append("^", 0., monospace_red.clone());
if r - l > 1 {
err.append(&" ".repeat(r - l - 2), 0., monospace);
err.append("^", 0., monospace_red);
}
err
}
pub fn reformat_error<T>(
e: ParseError<usize, T, UserError>,
input_str: &str,
ctx: &eframe::egui::Context,
) -> LayoutJob
where
T: Display,
{
let mut job = LayoutJob::default();
match e {
| ParseError::ExtraToken { token: (l, t, r) } => job.append(
&format!(
"Unexpected extra token \"{t}\" between positions {l} \
and {r}."
),
0.,
Default::default(),
),
| ParseError::UnrecognizedEof {
location: _,
expected: _,
} => job.append(
"End of file encountered while parsing.",
0.,
Default::default(),
),
| ParseError::InvalidToken { location } => job.append(
&format!("Invalid token at position {location}."),
0.,
Default::default(),
),
| ParseError::UnrecognizedToken {
token: (l, t, r),
expected,
} => job = create_error(input_str, l, t, r, Some(expected), None, ctx),
| ParseError::User {
error:
UserError {
token: (l, t, r),
error,
},
} => job = create_error(input_str, l, t, r, None, Some(error), ctx),
};
job
}

View File

@ -0,0 +1,18 @@
#![forbid(unsafe_code)]
#![warn(clippy::all, rust_2018_idioms)]
// Forbid warnings in release builds
#![cfg_attr(not(debug_assertions), deny(warnings))]
mod app;
mod app_logic;
mod helper;
pub use app::AppHandle;
// If compiling for web
#[cfg(target_arch = "wasm32")]
mod web;
// Export endpoints for wasm
#[cfg(target_arch = "wasm32")]
pub use web::*;

View File

@ -0,0 +1,29 @@
#![cfg_attr(not(debug_assertions), deny(warnings))]
#![warn(clippy::all, rust_2018_idioms)]
// hide console window on Windows in release
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use reaction_systems_gui::AppHandle;
// When compiling natively:
#[cfg(not(target_arch = "wasm32"))]
fn main() {
use eframe::egui::Visuals;
eframe::run_native(
"Reaction Systems",
eframe::NativeOptions::default(),
Box::new(|cc| {
cc.egui_ctx.set_visuals(Visuals::dark());
#[cfg(feature = "persistence")]
{
Ok(Box::new(AppHandle::new(cc)))
}
#[cfg(not(feature = "persistence"))]
{
Ok(Box::<AppHandle>::default())
}
}),
)
.expect("Failed to run native example");
}

View File

@ -0,0 +1,77 @@
#![allow(clippy::mem_forget)] // False positives from #[wasm_bindgen] macro
use eframe::wasm_bindgen::prelude::*;
use eframe::wasm_bindgen::{self};
use crate::app::NodeGraphExample;
#[derive(Clone)]
#[wasm_bindgen()]
pub struct WebHandle {
runner: eframe::WebRunner,
}
#[wasm_bindgen()]
impl WebHandle {
/// Installs a panic hook, then returns.
#[allow(clippy::new_without_default, clippy::allow_attributes)]
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
// Redirect [`log`] message to `console.log` and friends:
let log_level = if cfg!(debug_assertions) {
log::LevelFilter::Trace
} else {
log::LevelFilter::Debug
};
eframe::WebLogger::init(log_level).ok();
Self {
runner: eframe::WebRunner::new(),
}
}
/// Call this once from JavaScript to start the app.
#[wasm_bindgen]
pub async fn start(
&self,
canvas: eframe::web_sys::HtmlCanvasElement,
) -> Result<(), wasm_bindgen::JsValue> {
self.runner
.start(
canvas,
eframe::WebOptions::default(),
Box::new(|_cc| {
#[cfg(feature = "persistence")]
{
Ok(Box::new(NodeGraphExample::new(_cc)))
}
#[cfg(not(feature = "persistence"))]
{
Ok(Box::<NodeGraphExample>::default())
}
}),
)
.await
}
#[wasm_bindgen]
pub fn destroy(&self) {
self.runner.destroy();
}
/// The JavaScript can check whether or not the app has crashed:
#[wasm_bindgen]
pub fn has_panicked(&self) -> bool {
self.runner.has_panicked()
}
#[wasm_bindgen]
pub fn panic_message(&self) -> Option<String> {
self.runner.panic_summary().map(|s| s.message())
}
#[wasm_bindgen]
pub fn panic_callstack(&self) -> Option<String> {
self.runner.panic_summary().map(|s| s.callstack())
}
}

View File

@ -0,0 +1,12 @@
#!/bin/bash
set -eu
# Starts a local web-server that serves the contents of the `doc/` folder,
# which is the folder to where the web version is compiled.
# cargo install basic-http-server
echo "open http://localhost:8080"
(cd docs && basic-http-server --addr 127.0.0.1:8080 .)
# (cd docs && python3 -m http.server 8080 --bind 127.0.0.1)