Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP - wasm_bindgen backend for eventloop-2.0 #845

Closed
wants to merge 14 commits into from
Closed
20 changes: 18 additions & 2 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
paths:
- target

wasm-test:
emscripten-test:
working_directory: ~/winit
docker:
- image: tomaka/rustc-emscripten
Expand All @@ -43,7 +43,22 @@ jobs:
key: wasm-test-cache-{{ checksum "Cargo.toml" }}
- run: cargo build --example window --target wasm32-unknown-emscripten
- save_cache:
key: emscripten-test-cache-{{ checksum "Cargo.toml" }}
paths:
- target

websys-test:
working_directory: ~/winit
docker:
- image: tomaka/rustc-emscripten
steps:
- run: apt-get -qq update && apt-get install -y git
- checkout
- restore_cache:
key: wasm-test-cache-{{ checksum "Cargo.toml" }}
- run: cargo build --example wasm_bindgen --target wasm32-unknown-unknown --features websys
- save_cache:
key: websys-test-cache-{{ checksum "Cargo.toml" }}
paths:
- target

Expand All @@ -53,4 +68,5 @@ workflows:
jobs:
- android-test
- asmjs-test
- wasm-test
- emscripten-test
- websys-test
24 changes: 24 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ categories = ["gui"]
[package.metadata.docs.rs]
features = ["serde"]

[features]
websys = ["wasm-bindgen", "web-sys"]

[dependencies]
lazy_static = "1"
libc = "0.2"
Expand Down Expand Up @@ -72,3 +75,24 @@ percent-encoding = "1.0"

[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", target_os = "windows"))'.dependencies.parking_lot]
version = "0.8"

[target.'cfg(target_arch = "wasm32")'.dependencies.wasm-bindgen]
version = "0.2"
optional = true

[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.4"
optional = true
features = [
'Document',
'Element',
'HtmlElement',
'HtmlCanvasElement',
'CanvasRenderingContext2d',
'MouseEvent',
'Node',
'Window',
'console',
'CssStyleDeclaration',
'DomRect',
]
74 changes: 74 additions & 0 deletions examples/wasm_bindgen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
extern crate web_sys;
extern crate wasm_bindgen;

extern crate winit;
use winit::window::WindowBuilder;
use winit::event::{Event, WindowEvent};
use winit::event_loop::{EventLoop, ControlFlow};
use winit::platform::websys::WebsysWindowExt;
use winit::platform::websys::WebsysWindowBuilderExt;

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;

// A macro to provide `println!(..)`-style syntax for `console.log` logging.
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
}
}

// use wee_alloc if it is available
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
struct App {}

#[wasm_bindgen]
impl App {
pub fn new() -> App {
App{}
}

pub fn run(&self) {
// create an event loop
let event_loop = EventLoop::new();

// create a window and associate it with the event loop
let window = WindowBuilder::new()
.with_title("A fantastic window!")
.with_canvas_id("test")
.build(&event_loop)
.unwrap();

// do some drawing
let canvas = window.get_canvas();
let ctx = canvas.get_context("2d").unwrap().unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>().unwrap();
ctx.begin_path();
ctx.arc(95.0, 50.0, 40.0, 0.0, 2.0 * 3.14159).unwrap();
ctx.stroke();

// run forever
//
// when using wasm_bindgen, this will currently throw a js
// exception once all browser event handlers have been installed.
event_loop.run(|event, _, control_flow| {

match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => *control_flow = ControlFlow::Exit,
_ => *control_flow = ControlFlow::Poll,
}
});
}
}

pub fn main() {
let app = App::new();
app.run();
}
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ extern crate percent_encoding;
extern crate smithay_client_toolkit as sctk;
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))]
extern crate calloop;
#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "websys"))]
extern crate wasm_bindgen;
#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "websys"))]
extern crate web_sys;

pub mod dpi;
#[macro_use]
Expand Down
1 change: 1 addition & 0 deletions src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ pub mod ios;
pub mod macos;
pub mod unix;
pub mod windows;
pub mod websys;

pub mod desktop;
33 changes: 33 additions & 0 deletions src/platform/websys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
extern crate wasm_bindgen;
extern crate web_sys;

use platform_impl::window::ElementSelection;
use window::{Window, WindowBuilder};

pub trait WebsysWindowExt {
fn get_canvas<'a>(&'a self) -> &'a web_sys::HtmlCanvasElement;
}

impl WebsysWindowExt for Window {
fn get_canvas<'a>(&'a self) -> &'a web_sys::HtmlCanvasElement {
&self.window.canvas
}
}

pub trait WebsysWindowBuilderExt {
fn with_canvas_id(self, canvas_id: &str) -> WindowBuilder;

fn with_container_id(self, container_id: &str) -> WindowBuilder;
}

impl WebsysWindowBuilderExt for WindowBuilder {
fn with_canvas_id(mut self, canvas_id: &str) -> WindowBuilder {
self.platform_specific.element = ElementSelection::CanvasId(canvas_id.to_string());
self
}

fn with_container_id(mut self, container_id: &str) -> WindowBuilder {
self.platform_specific.element = ElementSelection::ContainerId(container_id.to_string());
self
}
}
5 changes: 4 additions & 1 deletion src/platform_impl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ mod platform;
#[cfg(target_os = "emscripten")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: Will emscripten conflict with websys with some targets?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't believe so, the target triple used for websys is wasm32-unknown-unknown. i would assume that if someone is building for wasm32-unknown-emscripten they wouldn't also have the websys feature set. i could add something like target_os = "unknown" to the cfg condition below (line21) to be safe

#[path="emscripten/mod.rs"]
mod platform;
#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "websys"))]
#[path="websys/mod.rs"]
mod platform;

#[cfg(all(not(target_os = "ios"), not(target_os = "windows"), not(target_os = "linux"),
not(target_os = "macos"), not(target_os = "android"), not(target_os = "dragonfly"),
not(target_os = "freebsd"), not(target_os = "netbsd"), not(target_os = "openbsd"),
not(target_os = "emscripten")))]
not(target_os = "emscripten"), not(all(target_arch = "wasm32", feature="websys"))))]
compile_error!("The platform you're compiling for is not supported by winit");
19 changes: 19 additions & 0 deletions src/platform_impl/websys/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::convert::From;

use ::event::WindowEvent as WindowEvent;
use ::event::DeviceId as WDeviceId;
use ::event::{ElementState, MouseButton};

use ::web_sys::MouseEvent;
use super::window::DeviceId;

impl From<MouseEvent> for WindowEvent {
fn from(event: MouseEvent) -> Self {
WindowEvent::MouseInput {
device_id: WDeviceId(DeviceId::dummy()),
state: ElementState::Pressed,
button: MouseButton::Left,
modifiers: Default::default()
}
}
}
Loading