Skip to content

Commit

Permalink
EnsoGL context abstraction (#3293)
Browse files Browse the repository at this point in the history
  • Loading branch information
wdanilo authored Mar 4, 2022
1 parent d384657 commit f4d236f
Show file tree
Hide file tree
Showing 184 changed files with 3,567 additions and 3,148 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 0 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,9 @@ members = [
"build/rust-scripts",
"lib/rust/*",
"lib/rust/profiler/data",
"lib/rust/not-used/*",
"integration-test"
]

# This directory is not a crate
exclude = ["lib/rust/not-used"]

# The default memebers are those we want to check and test by default.
default-members = ["app/gui", "lib/rust/*"]

Expand Down
2 changes: 1 addition & 1 deletion app/gui/analytics/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ edition = "2021"

[dependencies]
js-sys = { version = "0.3.28" }
wasm-bindgen = { version = "0.2.58", features = ["nightly", "serde-serialize"] }
wasm-bindgen = { version = "0.2.78", features = ["nightly", "serde-serialize"] }
2 changes: 1 addition & 1 deletion app/gui/language/parser/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["unbounded_depth"] }
shrinkwraprs = { version = "0.2.1" }
uuid = { version = "0.8", features = ["serde", "v5", "wasm-bindgen"] }
wasm-bindgen = { version = "0.2.58" }
wasm-bindgen = { version = "0.2.78" }

[dev-dependencies]
wasm-bindgen-test = { version = "0.3.8" }
Expand Down
2 changes: 1 addition & 1 deletion app/gui/language/span-tree/example/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ span-tree = { path = "../../span-tree" }
enso-web = { path = "../../../../../lib/rust/web" }
enso-prelude = { path = "../../../../../lib/rust/prelude"}
enso-logger = { path = "../../../../../lib/rust/logger"}
wasm-bindgen = { version = "0.2.58", features = [
wasm-bindgen = { version = "0.2.78", features = [
"nightly",
"serde-serialize"
] }
Expand Down
16 changes: 8 additions & 8 deletions app/gui/src/executor/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ use futures::task::LocalFutureObj;
use futures::task::LocalSpawn;
use futures::task::SpawnError;

/// An alias for a main animation loop.
pub type MainLoop = animation::Loop<Box<dyn FnMut(animation::TimeInfo)>>;

/// Executor. Uses a single-threaded `LocalPool` underneath, relying on ensogl's
/// `animation::DynamicLoop` to do as much progress as possible on every animation frame.
#[derive(Debug)]
Expand All @@ -22,7 +25,7 @@ pub struct EventLoopExecutor {
/// Executor's spawner handle.
pub spawner: LocalSpawner,
/// Event loop that calls us on each frame.
event_loop: Option<animation::DynamicLoop>,
event_loop: Option<MainLoop>,
/// Handle to the callback - if dropped, loop would have stopped calling us.
/// Also owns a shared handle to the `executor`.
cb_handle: Option<callback::Handle>,
Expand All @@ -44,14 +47,14 @@ impl EventLoopExecutor {
///loop will live as long as this executor.
pub fn new_running() -> EventLoopExecutor {
let mut executor = EventLoopExecutor::new();
executor.start_running(animation::DynamicLoop::new());
executor.start_running();
executor
}

/// Returns a callback compatible with `animation::DynamicLoop` that once called shall
/// attempt achieving as much progress on this executor's tasks as possible
/// without stalling.
pub fn runner(&self) -> impl animation::DynamicLoopCallback {
pub fn runner(&self) -> impl FnMut(animation::TimeInfo) {
let executor = self.executor.clone();
move |_| {
// Safe, because this is the only place borrowing executor and loop
Expand All @@ -67,11 +70,8 @@ impl EventLoopExecutor {
///
/// The executor will keep copy of this loop handle, so caller is not
/// required to keep it alive.
pub fn start_running(&mut self, event_loop: animation::DynamicLoop) {
let cb = self.runner();

self.cb_handle = Some(event_loop.on_frame(cb));
self.event_loop = Some(event_loop);
fn start_running(&mut self) {
self.event_loop = Some(MainLoop::new(Box::new(self.runner())));
}

/// Stops event loop (previously assigned by `run` method) from calling this
Expand Down
2 changes: 1 addition & 1 deletion app/gui/src/ide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl Ide {

fn alive_log_sending_loop(&self) -> impl Future<Output = ()> + 'static {
let network = &self.network;
let scene = self.ensogl_app.display.scene();
let scene = &self.ensogl_app.display.default_scene;
let mouse = &scene.mouse.frp;
let keyboard = &scene.keyboard.frp;

Expand Down
9 changes: 4 additions & 5 deletions app/gui/src/ide/initializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ impl Initializer {
let executor = setup_global_executor();
executor::global::spawn(async move {
let ide = self.start().await;
web::get_element_by_id("loader")
.map(|t| t.parent_node().map(|p| p.remove_child(&t).unwrap()))
.ok();
web::document
.get_element_by_id("loader")
.map(|t| t.parent_node().map(|p| p.remove_child(&t).unwrap()));
std::mem::forget(ide);
});
std::mem::forget(executor);
Expand All @@ -75,8 +75,7 @@ impl Initializer {
pub async fn start(self) -> Result<Ide, FailedIde> {
info!(self.logger, "Starting IDE with the following config: {self.config:?}");

let root_element = web::get_html_element_by_id("root").unwrap();
let ensogl_app = ensogl::application::Application::new(&root_element);
let ensogl_app = ensogl::application::Application::new("root");
Initializer::register_views(&ensogl_app);
let view = ensogl_app.new_view::<ide_view::root::View>();

Expand Down
4 changes: 0 additions & 4 deletions app/gui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ pub mod transport;
pub use crate::ide::*;
pub use ide_view as view;

use ensogl::system::web;
use wasm_bindgen::prelude::*;

// Those imports are required to have all EnsoGL examples entry points visible in IDE.
Expand All @@ -84,7 +83,6 @@ pub mod prelude {
pub use ast::prelude::*;
pub use enso_prelude::*;
pub use ensogl::prelude::*;
pub use wasm_bindgen::prelude::*;

pub use crate::constants;
pub use crate::controller;
Expand Down Expand Up @@ -116,8 +114,6 @@ pub mod prelude {
#[wasm_bindgen]
#[allow(dead_code)]
pub fn entry_point_ide() {
web::forward_panic_hook_to_error();

ensogl_text_msdf_sys::run_once_initialized(|| {
// Logging of build information.
#[cfg(debug_assertions)]
Expand Down
28 changes: 27 additions & 1 deletion app/gui/src/presenter/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ use crate::executor::global::spawn_stream_handler;
use crate::presenter::graph::state::State;

use enso_frp as frp;
use enso_web::traits::*;
use futures::future::LocalBoxFuture;
use ide_view as view;
use ide_view::graph_editor::component::node as node_view;
use ide_view::graph_editor::component::visualization as visualization_view;
use ide_view::graph_editor::EdgeEndpoint;



// ===============
// === Aliases ===
// ===============
Expand Down Expand Up @@ -609,6 +611,30 @@ impl Graph {

impl controller::upload::DataProvider for ensogl_drop_manager::File {
fn next_chunk(&mut self) -> LocalBoxFuture<FallibleResult<Option<Vec<u8>>>> {
self.read_chunk().map(|f| f.map_err(|e| e.into())).boxed_local()
self.read_chunk()
.map(|f| f.map_err(|e| StringError::new(e.print_to_string()).into()))
.boxed_local()
}
}



// =============
// === Error ===
// =============

/// Generic error representation. This is used only once in the lines above. Probably should be
/// removed in the future.
#[derive(Debug, Fail)]
#[fail(display = "{}", message)]
pub struct StringError {
message: String,
}

impl StringError {
/// Constructor.
pub fn new(message: impl Into<String>) -> StringError {
let message = message.into();
StringError { message }
}
}
22 changes: 11 additions & 11 deletions app/gui/src/transport/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::prelude::*;

use enso_web::event::listener::Slot;
use enso_web::js_to_string;
use enso_web::traits::*;
use failure::Error;
use futures::channel::mpsc;
use json_rpc::Transport;
Expand Down Expand Up @@ -34,8 +34,8 @@ pub enum ConnectingError {

impl ConnectingError {
/// Create a `ConstructionError` value from a JS value describing an error.
pub fn construction_error(js_val: impl AsRef<JsValue>) -> Self {
let text = js_to_string(js_val);
pub fn construction_error(js_val: impl AsRef<enso_web::JsValue>) -> Self {
let text = js_val.as_ref().print_to_string();
ConnectingError::ConstructionError(text)
}
}
Expand All @@ -54,8 +54,8 @@ pub enum SendingError {

impl SendingError {
/// Constructs from the error yielded by one of the JS's WebSocket sending functions.
pub fn from_send_error(error: JsValue) -> SendingError {
SendingError::FailedToSend(js_to_string(&error))
pub fn from_send_error(error: wasm_bindgen::JsValue) -> SendingError {
SendingError::FailedToSend(error.print_to_string())
}
}

Expand Down Expand Up @@ -192,7 +192,7 @@ impl Model {
}

/// Close the socket.
pub fn close(&mut self, reason: &str) -> Result<(), JsValue> {
pub fn close(&mut self, reason: &str) -> Result<(), wasm_bindgen::JsValue> {
// If socket was manually requested to close, it should not try to reconnect then.
self.auto_reconnect = false;
let normal_closure = 1000;
Expand Down Expand Up @@ -229,7 +229,7 @@ impl Model {

/// Establish a new WS connection, using the same URL as the previous one.
/// All callbacks will be transferred to the new connection.
pub fn reconnect(&mut self) -> Result<(), JsValue> {
pub fn reconnect(&mut self) -> Result<(), wasm_bindgen::JsValue> {
if !self.auto_reconnect {
return Err(js_sys::Error::new("Reconnecting has been disabled").into());
}
Expand All @@ -256,7 +256,7 @@ impl Drop for Model {
if let Err(e) = self.close("Rust Value has been dropped.") {
error!(
self.logger,
"Error when closing socket due to being dropped: {js_to_string(&e)}"
"Error when closing socket due to being dropped: {e.print_to_string()}"
)
}
}
Expand Down Expand Up @@ -303,7 +303,7 @@ impl WebSocket {
move |_| {
if let Some(model) = model.upgrade() {
if let Err(e) = model.borrow_mut().reconnect() {
error!(logger, "Failed to reconnect: {js_to_string(&e)}");
error!(logger, "Failed to reconnect: {e.print_to_string()}");
}
}
}
Expand Down Expand Up @@ -379,7 +379,7 @@ impl WebSocket {
///
/// WARNING: `f` works under borrow_mut and must not give away control.
fn send_with_open_socket<F, R>(&mut self, f: F) -> Result<R, Error>
where F: FnOnce(&mut web_sys::WebSocket) -> Result<R, JsValue> {
where F: FnOnce(&mut web_sys::WebSocket) -> Result<R, wasm_bindgen::JsValue> {
// Sending through the closed WebSocket can return Ok() with error only
// appearing in the log. We explicitly check for this to get failure as
// early as possible.
Expand Down Expand Up @@ -433,7 +433,7 @@ impl Transport for WebSocket {
let event = TransportEvent::BinaryMessage(binary_data);
channel::emit(&transmitter_copy, event);
} else {
info!(logger_copy, "Received other kind of message: {js_to_string(e.data())}.");
info!(logger_copy, "Received other kind of message: {e.data().print_to_string()}.");
}
});

Expand Down
2 changes: 1 addition & 1 deletion app/gui/view/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ ordered-float = { version = "2.7.0" }
serde_json = { version = "1.0" }
serde = { version = "1.0", features = ["derive"] }
uuid = { version = "0.8", features = ["serde", "v4", "wasm-bindgen"] }
wasm-bindgen = { version = "0.2.58", features = [
wasm-bindgen = { version = "0.2.78", features = [
"nightly",
"serde-serialize"
] }
Expand Down
2 changes: 1 addition & 1 deletion app/gui/view/debug_scene/interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ ide-view = { path = "../.." }
parser = { path = "../../../language/parser" }
span-tree = { path = "../../../language/span-tree" }
uuid = { version = "0.8", features = ["v4", "wasm-bindgen"] }
wasm-bindgen = { version = "0.2.58", features = ["nightly"] }
wasm-bindgen = { version = "0.2.78", features = ["nightly"] }
18 changes: 9 additions & 9 deletions app/gui/view/debug_scene/interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,8 @@ const STUB_MODULE: &str = "from Base import all\n\nmain = IO.println \"Hello\"\n
#[wasm_bindgen]
#[allow(dead_code)]
pub fn entry_point_interface() {
web::forward_panic_hook_to_console();
web::set_stack_trace_limit();
run_once_initialized(|| {
let app = Application::new(&web::get_html_element_by_id("root").unwrap());
let app = Application::new("root");
init(&app);
mem::forget(app);
});
Expand Down Expand Up @@ -100,10 +98,10 @@ impl DummyTypeGenerator {
// ========================

fn init(app: &Application) {
let _bg = app.display.scene().style_sheet.var(theme::application::background);
let _bg = app.display.default_scene.style_sheet.var(theme::application::background);

let world = &app.display;
let scene = world.scene();
let scene = &world.default_scene;
let camera = scene.camera();
let navigator = Navigator::new(scene, &camera);

Expand Down Expand Up @@ -252,7 +250,9 @@ fn init(app: &Application) {
let mut to_theme_switch = 100;

world
.on_frame(move |_| {
.on
.before_frame
.add(move |_| {
let _keep_alive = &navigator;
let _keep_alive = &root_view;

Expand Down Expand Up @@ -292,9 +292,9 @@ fn init(app: &Application) {
// Temporary code removing the web-loader instance.
// To be changed in the future.
if was_rendered && !loader_hidden {
web::get_element_by_id("loader")
.map(|t| t.parent_node().map(|p| p.remove_child(&t).unwrap()))
.ok();
web::document
.get_element_by_id("loader")
.map(|t| t.parent_node().map(|p| p.remove_child(&t).unwrap()));
loader_hidden = true;
}
was_rendered = true;
Expand Down
2 changes: 1 addition & 1 deletion app/gui/view/debug_scene/visualization/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ ide-view = { path = "../.." }
js-sys = { version = "0.3.28" }
nalgebra = { version = "0.26.1" }
serde_json = { version = "1.0" }
wasm-bindgen = { version = "0.2.58", features = ["nightly"] }
wasm-bindgen = { version = "0.2.78", features = ["nightly"] }
Loading

0 comments on commit f4d236f

Please sign in to comment.