Skip to content

Commit c28eab2

Browse files
committed
Breaking: Change type of create_surface() functions to expose canvas errors.
Part of fixing #3017.
1 parent b265540 commit c28eab2

File tree

9 files changed

+118
-57
lines changed

9 files changed

+118
-57
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ Additionally `Surface::get_default_config` now returns an Option and returns Non
6363
+ let config = surface.get_default_config(&adapter).expect("Surface unsupported by adapter");
6464
```
6565

66+
#### Fallible surface creation
67+
68+
`Instance::create_surface()` now returns `Result<Surface, CreateSurfaceError>` instead of `Surface`. This allows an error to be returned instead of panicking if the given window is a HTML canvas and obtaining a WebGPU or WebGL 2 context fails. (No other platforms currently report any errors through this path.) By @kpreid in [#3052](https://github.com/gfx-rs/wgpu/pull/3052/)
69+
6670
### Changes
6771

6872
#### General

wgpu-core/src/instance.rs

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -502,45 +502,53 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
502502
&self,
503503
canvas: &web_sys::HtmlCanvasElement,
504504
id_in: Input<G, SurfaceId>,
505-
) -> SurfaceId {
505+
) -> Result<SurfaceId, hal::InstanceError> {
506506
profiling::scope!("Instance::create_surface_webgl_canvas");
507507

508508
let surface = Surface {
509509
presentation: None,
510-
gl: self.instance.gl.as_ref().map(|inst| HalSurface {
511-
raw: {
512-
inst.create_surface_from_canvas(canvas)
513-
.expect("Create surface from canvas")
514-
},
515-
}),
510+
gl: self
511+
.instance
512+
.gl
513+
.as_ref()
514+
.map(|inst| {
515+
Ok(HalSurface {
516+
raw: inst.create_surface_from_canvas(canvas)?,
517+
})
518+
})
519+
.transpose()?,
516520
};
517521

518522
let mut token = Token::root();
519523
let id = self.surfaces.prepare(id_in).assign(surface, &mut token);
520-
id.0
524+
Ok(id.0)
521525
}
522526

523527
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
524528
pub fn create_surface_webgl_offscreen_canvas(
525529
&self,
526530
canvas: &web_sys::OffscreenCanvas,
527531
id_in: Input<G, SurfaceId>,
528-
) -> SurfaceId {
532+
) -> Result<SurfaceId, hal::InstanceError> {
529533
profiling::scope!("Instance::create_surface_webgl_offscreen_canvas");
530534

531535
let surface = Surface {
532536
presentation: None,
533-
gl: self.instance.gl.as_ref().map(|inst| HalSurface {
534-
raw: {
535-
inst.create_surface_from_offscreen_canvas(canvas)
536-
.expect("Create surface from offscreen canvas")
537-
},
538-
}),
537+
gl: self
538+
.instance
539+
.gl
540+
.as_ref()
541+
.map(|inst| {
542+
Ok(HalSurface {
543+
raw: inst.create_surface_from_offscreen_canvas(canvas)?,
544+
})
545+
})
546+
.transpose()?,
539547
};
540548

541549
let mut token = Token::root();
542550
let id = self.surfaces.prepare(id_in).assign(surface, &mut token);
543-
id.0
551+
Ok(id.0)
544552
}
545553

546554
#[cfg(dx12)]

wgpu/Cargo.toml

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ wgsl = ["wgc?/wgsl"]
8383
trace = ["serde", "wgc/trace"]
8484
replay = ["serde", "wgc/replay"]
8585
angle = ["wgc/angle"]
86-
webgl = ["wgc"]
86+
webgl = ["hal", "wgc"]
8787
emscripten = ["webgl"]
8888
vulkan-portability = ["wgc/vulkan-portability"]
8989
expose-ids = []
@@ -100,9 +100,13 @@ optional = true
100100
[dependencies.wgt]
101101
workspace = true
102102

103-
[target.'cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))'.dependencies.hal]
103+
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.hal]
104104
workspace = true
105105

106+
[target.'cfg(target_arch = "wasm32")'.dependencies.hal]
107+
workspace = true
108+
optional = true
109+
106110
[dependencies]
107111
arrayvec.workspace = true
108112
log.workspace = true

wgpu/examples/framework.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ async fn setup<E: Example>(title: &str) -> Setup {
164164
let size = window.inner_size();
165165

166166
#[cfg(any(not(target_arch = "wasm32"), target_os = "emscripten"))]
167-
let surface = instance.create_surface(&window);
167+
let surface = instance.create_surface(&window).unwrap();
168168
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
169169
let surface = {
170170
if let Some(offscreen_canvas_setup) = &offscreen_canvas_setup {
@@ -174,7 +174,8 @@ async fn setup<E: Example>(title: &str) -> Setup {
174174
} else {
175175
instance.create_surface(&window)
176176
}
177-
};
177+
}
178+
.unwrap();
178179

179180
(size, surface)
180181
};

wgpu/examples/hello-triangle/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use winit::{
88
async fn run(event_loop: EventLoop<()>, window: Window) {
99
let size = window.inner_size();
1010
let instance = wgpu::Instance::new(wgpu::Backends::all());
11-
let surface = unsafe { instance.create_surface(&window) };
11+
let surface = unsafe { instance.create_surface(&window) }.unwrap();
1212
let adapter = instance
1313
.request_adapter(&wgpu::RequestAdapterOptions {
1414
power_preference: wgpu::PowerPreference::default(),

wgpu/examples/hello-windows/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ struct Viewport {
2020

2121
impl ViewportDesc {
2222
fn new(window: Window, background: wgpu::Color, instance: &wgpu::Instance) -> Self {
23-
let surface = unsafe { instance.create_surface(&window) };
23+
let surface = unsafe { instance.create_surface(&window) }.unwrap();
2424
Self {
2525
window,
2626
background,

wgpu/src/backend/direct.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -219,24 +219,30 @@ impl Context {
219219
pub fn instance_create_surface_from_canvas(
220220
self: &Arc<Self>,
221221
canvas: &web_sys::HtmlCanvasElement,
222-
) -> Surface {
223-
let id = self.0.create_surface_webgl_canvas(canvas, ());
224-
Surface {
222+
) -> Result<Surface, crate::CreateSurfaceError> {
223+
let id = self
224+
.0
225+
.create_surface_webgl_canvas(canvas, ())
226+
.map_err(|hal::InstanceError| crate::CreateSurfaceError {})?;
227+
Ok(Surface {
225228
id,
226229
configured_device: Mutex::default(),
227-
}
230+
})
228231
}
229232

230233
#[cfg(all(target_arch = "wasm32", feature = "webgl", not(feature = "emscripten")))]
231234
pub fn instance_create_surface_from_offscreen_canvas(
232235
self: &Arc<Self>,
233236
canvas: &web_sys::OffscreenCanvas,
234-
) -> Surface {
235-
let id = self.0.create_surface_webgl_offscreen_canvas(canvas, ());
236-
Surface {
237+
) -> Result<Surface, crate::CreateSurfaceError> {
238+
let id = self
239+
.0
240+
.create_surface_webgl_offscreen_canvas(canvas, ())
241+
.map_err(|hal::InstanceError| crate::CreateSurfaceError {})?;
242+
Ok(Surface {
237243
id,
238244
configured_device: Mutex::default(),
239-
}
245+
})
240246
}
241247

242248
#[cfg(target_os = "windows")]
@@ -943,13 +949,13 @@ impl crate::Context for Context {
943949
&self,
944950
display_handle: raw_window_handle::RawDisplayHandle,
945951
window_handle: raw_window_handle::RawWindowHandle,
946-
) -> Self::SurfaceId {
947-
Surface {
952+
) -> Result<Self::SurfaceId, crate::CreateSurfaceError> {
953+
Ok(Surface {
948954
id: self
949955
.0
950956
.instance_create_surface(display_handle, window_handle, ()),
951957
configured_device: Mutex::new(None),
952-
}
958+
})
953959
}
954960

955961
fn instance_request_adapter(

wgpu/src/backend/web.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,27 +1026,25 @@ impl Context {
10261026
pub fn instance_create_surface_from_canvas(
10271027
&self,
10281028
canvas: &web_sys::HtmlCanvasElement,
1029-
) -> <Self as crate::Context>::SurfaceId {
1029+
) -> Result<<Self as crate::Context>::SurfaceId, crate::CreateSurfaceError> {
10301030
self.create_surface_from_context(canvas.get_context("webgpu"))
1031-
.unwrap()
10321031
}
10331032

10341033
pub fn instance_create_surface_from_offscreen_canvas(
10351034
&self,
10361035
canvas: &web_sys::OffscreenCanvas,
1037-
) -> <Self as crate::Context>::SurfaceId {
1036+
) -> Result<<Self as crate::Context>::SurfaceId, crate::CreateSurfaceError> {
10381037
self.create_surface_from_context(canvas.get_context("webgpu"))
1039-
.unwrap()
10401038
}
10411039

10421040
/// Common portion of public `instance_create_surface_from_*` functions.
10431041
///
1044-
/// Note: Analogous code also exists in the WebGL 2 backend at
1042+
/// Note: Analogous code also exists in the WebGL2 backend at
10451043
/// `wgpu_hal::gles::web::Instance`.
10461044
fn create_surface_from_context(
10471045
&self,
10481046
context_result: Result<Option<js_sys::Object>, wasm_bindgen::JsValue>,
1049-
) -> Result<<Self as crate::Context>::SurfaceId, ()> {
1047+
) -> Result<<Self as crate::Context>::SurfaceId, crate::CreateSurfaceError> {
10501048
let context: js_sys::Object = match context_result {
10511049
Ok(Some(context)) => context,
10521050
Ok(None) => {
@@ -1056,7 +1054,7 @@ impl Context {
10561054
// “not supported” could include “insufficient GPU resources” or “the GPU process
10571055
// previously crashed”. So, we must return it as an `Err` since it could occur
10581056
// for circumstances outside the application author's control.
1059-
return Err(());
1057+
return Err(crate::CreateSurfaceError {});
10601058
}
10611059
Err(js_error) => {
10621060
// <https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext>
@@ -1171,7 +1169,7 @@ impl crate::Context for Context {
11711169
&self,
11721170
_display_handle: raw_window_handle::RawDisplayHandle,
11731171
window_handle: raw_window_handle::RawWindowHandle,
1174-
) -> Self::SurfaceId {
1172+
) -> Result<Self::SurfaceId, crate::CreateSurfaceError> {
11751173
let canvas_attribute = match window_handle {
11761174
raw_window_handle::RawWindowHandle::Web(web_handle) => web_handle.id,
11771175
_ => panic!("expected valid handle for canvas"),

wgpu/src/lib.rs

Lines changed: 56 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ trait Context: Debug + Send + Sized + Sync {
204204
&self,
205205
display_handle: raw_window_handle::RawDisplayHandle,
206206
window_handle: raw_window_handle::RawWindowHandle,
207-
) -> Self::SurfaceId;
207+
) -> Result<Self::SurfaceId, crate::CreateSurfaceError>;
208208
fn instance_request_adapter(
209209
&self,
210210
options: &RequestAdapterOptions<'_>,
@@ -1816,23 +1816,34 @@ impl Instance {
18161816
///
18171817
/// # Safety
18181818
///
1819-
/// - Raw Window Handle must be a valid object to create a surface upon and
1820-
/// must remain valid for the lifetime of the returned surface.
1821-
/// - If not called on the main thread, metal backend will panic.
1819+
/// - `raw_window_handle` must be a valid object to create a surface upon.
1820+
/// - `raw_window_handle` must remain valid until after the returned [`Surface`] is
1821+
/// dropped.
1822+
///
1823+
/// # Errors
1824+
///
1825+
/// - On WebGL2: Will return an error if the browser does not support WebGL2,
1826+
/// or declines to provide GPU access (such as due to a resource shortage).
1827+
///
1828+
/// # Panics
1829+
///
1830+
/// - On macOS/Metal: will panic if not called on the main thread.
1831+
/// - On web: will panic if the `raw_window_handle` does not properly refer to a
1832+
/// canvas element.
18221833
pub unsafe fn create_surface<
18231834
W: raw_window_handle::HasRawWindowHandle + raw_window_handle::HasRawDisplayHandle,
18241835
>(
18251836
&self,
18261837
window: &W,
1827-
) -> Surface {
1828-
Surface {
1838+
) -> Result<Surface, CreateSurfaceError> {
1839+
Ok(Surface {
18291840
context: Arc::clone(&self.context),
18301841
id: Context::instance_create_surface(
18311842
&*self.context,
18321843
raw_window_handle::HasRawDisplayHandle::raw_display_handle(window),
18331844
raw_window_handle::HasRawWindowHandle::raw_window_handle(window),
1834-
),
1835-
}
1845+
)?,
1846+
})
18361847
}
18371848

18381849
/// Creates a surface from `CoreAnimationLayer`.
@@ -1862,29 +1873,42 @@ impl Instance {
18621873
///
18631874
/// The `canvas` argument must be a valid `<canvas>` element to
18641875
/// create a surface upon.
1876+
///
1877+
/// # Errors
1878+
///
1879+
/// - On WebGL2: Will return an error if the browser does not support WebGL2,
1880+
/// or declines to provide GPU access (such as due to a resource shortage).
18651881
#[cfg(all(target_arch = "wasm32", not(feature = "emscripten")))]
1866-
pub fn create_surface_from_canvas(&self, canvas: &web_sys::HtmlCanvasElement) -> Surface {
1867-
Surface {
1882+
pub fn create_surface_from_canvas(
1883+
&self,
1884+
canvas: &web_sys::HtmlCanvasElement,
1885+
) -> Result<Surface, CreateSurfaceError> {
1886+
Ok(Surface {
18681887
context: Arc::clone(&self.context),
1869-
id: self.context.instance_create_surface_from_canvas(canvas),
1870-
}
1888+
id: self.context.instance_create_surface_from_canvas(canvas)?,
1889+
})
18711890
}
18721891

18731892
/// Creates a surface from a `web_sys::OffscreenCanvas`.
18741893
///
18751894
/// The `canvas` argument must be a valid `OffscreenCanvas` object
18761895
/// to create a surface upon.
1896+
///
1897+
/// # Errors
1898+
///
1899+
/// - On WebGL2: Will return an error if the browser does not support WebGL2,
1900+
/// or declines to provide GPU access (such as due to a resource shortage).
18771901
#[cfg(all(target_arch = "wasm32", not(feature = "emscripten")))]
18781902
pub fn create_surface_from_offscreen_canvas(
18791903
&self,
18801904
canvas: &web_sys::OffscreenCanvas,
1881-
) -> Surface {
1882-
Surface {
1905+
) -> Result<Surface, CreateSurfaceError> {
1906+
Ok(Surface {
18831907
context: Arc::clone(&self.context),
18841908
id: self
18851909
.context
1886-
.instance_create_surface_from_offscreen_canvas(canvas),
1887-
}
1910+
.instance_create_surface_from_offscreen_canvas(canvas)?,
1911+
})
18881912
}
18891913

18901914
/// Polls all devices.
@@ -2353,6 +2377,22 @@ impl Display for RequestDeviceError {
23532377

23542378
impl error::Error for RequestDeviceError {}
23552379

2380+
/// [`Instance::create_surface()`] or a related function failed.
2381+
#[derive(Clone, PartialEq, Eq, Debug)]
2382+
#[non_exhaustive]
2383+
pub struct CreateSurfaceError {
2384+
// TODO: Report diagnostic clues
2385+
}
2386+
static_assertions::assert_impl_all!(CreateSurfaceError: Send, Sync);
2387+
2388+
impl Display for CreateSurfaceError {
2389+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2390+
write!(f, "Creating a surface failed")
2391+
}
2392+
}
2393+
2394+
impl error::Error for CreateSurfaceError {}
2395+
23562396
/// Error occurred when trying to async map a buffer.
23572397
#[derive(Clone, PartialEq, Eq, Debug)]
23582398
pub struct BufferAsyncError;

0 commit comments

Comments
 (0)