feat(client): redesign native UI, themes, settings and avatars

Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
Loki 2026-10-24 14:23:48 +02:00
parent 44d284a568
commit 8e5ab56611
Signed by: boba
GPG key ID: 253067914055423B
276 changed files with 53546 additions and 3399 deletions

View file

@ -0,0 +1,330 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore glcontext glprobe webglcontextlost webglcontextrestored
use std::rc::Rc;
#[cfg(supports_opengl)]
use std::rc::Weak;
use std::sync::Arc;
use i_slint_core::renderer::{DrawOutcome, Renderer};
use i_slint_core::{graphics::RequestedGraphicsAPI, platform::PlatformError};
#[cfg(supports_opengl)]
use i_slint_renderer_femtovg::{FemtoVGOpenGLRendererExt, opengl};
use i_slint_renderer_femtovg::{FemtoVGRenderer, FemtoVGRendererExt};
use winit::event_loop::ActiveEventLoop;
#[cfg(all(target_arch = "wasm32", supports_opengl))]
use winit::platform::web::WindowExtWebSys;
use super::WinitCompatibleRenderer;
#[cfg(all(supports_opengl, not(target_arch = "wasm32")))]
mod glcontext;
#[cfg(all(supports_opengl, target_os = "windows"))]
mod glprobe;
#[cfg(supports_opengl)]
pub struct GlutinFemtoVGRenderer {
renderer: FemtoVGRenderer<opengl::OpenGLBackend>,
_requested_graphics_api: Option<RequestedGraphicsAPI>,
_shared_backend_data_weak: Weak<crate::SharedBackendData>,
}
#[cfg(supports_opengl)]
impl GlutinFemtoVGRenderer {
pub fn new_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
// Bail out before a window is created, so that the backend can still fall back to
// another renderer.
#[cfg(target_os = "windows")]
if !glprobe::opengl_2_available() {
return Err("The FemtoVG renderer requires an OpenGL 2.0 driver".into());
}
Ok(Box::new(Self {
renderer: FemtoVGRenderer::new_suspended(),
_requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
_shared_backend_data_weak: Rc::downgrade(shared_backend_data),
}))
}
}
#[cfg(supports_opengl)]
impl super::WinitCompatibleRenderer for GlutinFemtoVGRenderer {
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
self.renderer.render().map(|()| DrawOutcome::Success)
}
fn as_core_renderer(&self) -> &dyn Renderer {
&self.renderer
}
fn resume(
&self,
active_event_loop: &ActiveEventLoop,
window_attributes: winit::window::WindowAttributes,
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
) -> Result<Arc<winit::window::Window>, PlatformError> {
#[cfg(not(target_arch = "wasm32"))]
let (winit_window, opengl_context) = glcontext::OpenGLContext::new_context(
window_attributes,
active_event_loop,
self._requested_graphics_api.as_ref().map(TryInto::try_into).transpose()?,
)?;
#[cfg(target_arch = "wasm32")]
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|winit_os_error| {
PlatformError::from(format!(
"FemtoVG Renderer: Could not create winit window wrapper for DOM canvas: {}",
winit_os_error
))
},
)?);
#[cfg(target_family = "wasm")]
let html_canvas = winit_window
.canvas()
.ok_or_else(|| "FemtoVG Renderer: winit didn't return a canvas")?;
self.renderer.set_opengl_context(
#[cfg(not(target_arch = "wasm32"))]
opengl_context,
#[cfg(target_arch = "wasm32")]
html_canvas.clone(),
)?;
#[cfg(target_family = "wasm")]
self.setup_webgl_context_loss_handlers(winit_window.id(), html_canvas);
Ok(winit_window)
}
fn suspend(&self) -> Result<(), PlatformError> {
self.renderer.clear_graphics_context()
}
}
#[cfg(all(supports_opengl, target_family = "wasm"))]
impl GlutinFemtoVGRenderer {
fn setup_webgl_context_loss_handlers(
&self,
window_id: winit::window::WindowId,
html_canvas: web_sys::HtmlCanvasElement,
) {
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
let add_listener = |name, closure: Closure<dyn Fn(web_sys::WebGlContextEvent)>| {
html_canvas
.add_event_listener_with_callback(name, closure.as_ref().unchecked_ref())
.unwrap();
closure.forget();
};
add_listener(
"webglcontextlost",
Closure::wrap(Box::new({
let shared_backend_data_weak = self._shared_backend_data_weak.clone();
move |event: web_sys::WebGlContextEvent| {
let Some(window_adapter) = shared_backend_data_weak
.upgrade()
.and_then(|backend_data| backend_data.window_by_id(window_id))
else {
return;
};
i_slint_core::debug_log!(
"Slint: Suspending renderer due to WebGL context loss"
);
let this = (window_adapter.renderer() as &dyn std::any::Any)
.downcast_ref::<Self>()
.unwrap();
let _ = this.renderer.clear_graphics_context().ok();
// Preventing default is the way to make sure the browser sends a webglcontextrestored event
// when the context is back.
event.prevent_default();
}
}) as Box<dyn Fn(web_sys::WebGlContextEvent)>),
);
add_listener(
"webglcontextrestored",
Closure::wrap(Box::new({
let shared_backend_data_weak = self._shared_backend_data_weak.clone();
let html_canvas = html_canvas.clone();
move |_event: web_sys::WebGlContextEvent| {
let Some(window_adapter) = shared_backend_data_weak
.upgrade()
.and_then(|backend_data| backend_data.window_by_id(window_id))
else {
return;
};
i_slint_core::debug_log!(
"Slint: Restoring renderer due to WebGL context restoration"
);
let this = (window_adapter.renderer() as &dyn std::any::Any)
.downcast_ref::<Self>()
.unwrap();
if this.renderer.set_opengl_context(html_canvas.clone()).is_ok() {
use i_slint_core::platform::WindowAdapter;
window_adapter.request_redraw();
let _ = window_adapter.draw().ok();
}
}
}) as Box<dyn Fn(web_sys::WebGlContextEvent)>),
);
}
}
#[cfg(feature = "renderer-femtovg-wgpu")]
fn wgpu_backends_to_avoid() -> i_slint_core::graphics::wgpu_30::wgpu::Backends {
// On WASM keep GL so wgpu can fall through to WebGL when WebGPU is missing.
#[cfg(not(target_arch = "wasm32"))]
{
i_slint_core::graphics::wgpu_30::default_backends_to_avoid()
}
#[cfg(target_arch = "wasm32")]
{
i_slint_core::graphics::wgpu_30::wgpu::Backends::empty()
}
}
#[cfg(feature = "renderer-femtovg-wgpu")]
pub struct WGPUFemtoVGRenderer {
renderer: FemtoVGRenderer<i_slint_renderer_femtovg::wgpu::WGPUBackend>,
requested_graphics_api: Option<RequestedGraphicsAPI>,
}
#[cfg(feature = "renderer-femtovg-wgpu")]
impl WGPUFemtoVGRenderer {
pub fn new_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
if !i_slint_core::graphics::wgpu_30::any_wgpu30_adapters_with_gpu(
shared_backend_data.requested_graphics_api.clone(),
wgpu_backends_to_avoid(),
) {
return Err(PlatformError::from("WGPU: No GPU adapters found"));
}
Ok(Box::new(Self {
renderer: FemtoVGRenderer::<i_slint_renderer_femtovg::wgpu::WGPUBackend>::new_suspended(
),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
}
#[cfg(feature = "renderer-femtovg-wgpu")]
impl WinitCompatibleRenderer for WGPUFemtoVGRenderer {
#[cfg(target_os = "macos")]
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
self.renderer.set_transparent(transparent);
Ok(())
}
fn render(&self, window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
// Use the Ext entry point so we get the `DrawOutcome` back without changing
// `FemtoVGRenderer::render`'s public `Result<(), _>` signature.
self.renderer.render_transformed_with_post_callback(0., (0., 0.), window.size(), None)
}
fn as_core_renderer(&self) -> &dyn Renderer {
&self.renderer
}
fn suspend(&self) -> Result<(), PlatformError> {
self.renderer.clear_graphics_context()
}
fn resume(
&self,
active_event_loop: &ActiveEventLoop,
window_attributes: winit::window::WindowAttributes,
window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
) -> Result<Arc<winit::window::Window>, PlatformError> {
let transparent = window_attributes.transparent;
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|winit_os_error| {
PlatformError::from(format!(
"Error creating native window for FemtoVG rendering: {}",
winit_os_error
))
},
)?);
let requested_graphics_api = self.requested_graphics_api.clone();
let window_handle = Box::new(winit_window.clone())
as Box<dyn i_slint_core::graphics::wgpu_30::wgpu::DisplayAndWindowHandle>;
let winit_window_for_size = winit_window.clone();
let context = {
let window_adapter = window_adapter_weak.upgrade().ok_or_else(|| {
PlatformError::from("Cannot initialize wgpu: window adapter is destroyed")
})?;
use i_slint_core::platform::WindowAdapter;
i_slint_core::window::WindowInner::from_pub(window_adapter.window()).context().clone()
};
i_slint_core::graphics::wgpu_30::init_instance_adapter_device_queue_surface_then(
&context,
window_handle,
requested_graphics_api,
wgpu_backends_to_avoid(),
move |instance, adapter, device, queue, surface| {
finalize_wgpu_init(
&window_adapter_weak,
&winit_window_for_size,
instance,
adapter,
device,
queue,
surface,
transparent,
)?;
#[cfg(target_arch = "wasm32")]
i_slint_core::debug_log!("Slint: Using FemtoVG WGPU renderer");
Ok(())
},
)?;
Ok(winit_window)
}
}
#[cfg(feature = "renderer-femtovg-wgpu")]
fn finalize_wgpu_init(
window_adapter_weak: &std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
winit_window: &Arc<winit::window::Window>,
instance: i_slint_core::graphics::wgpu_30::wgpu::Instance,
adapter: i_slint_core::graphics::wgpu_30::wgpu::Adapter,
device: i_slint_core::graphics::wgpu_30::wgpu::Device,
queue: i_slint_core::graphics::wgpu_30::wgpu::Queue,
surface: i_slint_core::graphics::wgpu_30::wgpu::Surface<'static>,
transparent: bool,
) -> Result<(), PlatformError> {
let Some(window_adapter) = window_adapter_weak.upgrade() else {
return Ok(());
};
let this = (window_adapter.renderer() as &dyn std::any::Any)
.downcast_ref::<WGPUFemtoVGRenderer>()
.unwrap();
use crate::winit_compat::WindowSurfaceSizeExt;
let slint_size =
crate::winitwindowadapter::physical_size_to_slint(&winit_window.surface_size());
this.renderer.configure_surface_from_init_result(
instance,
adapter,
device,
queue,
surface,
slint_size,
transparent,
);
use i_slint_core::platform::WindowAdapter;
window_adapter.request_redraw();
Ok(())
}

View file

@ -0,0 +1,220 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
use std::{num::NonZeroU32, sync::Arc};
use crate::winit_compat::WindowSurfaceSizeExt;
use glutin::{
config::GlConfig,
context::{ContextApi, ContextAttributesBuilder},
display::GetGlDisplay,
prelude::*,
surface::{SurfaceAttributesBuilder, WindowSurface},
};
use i_slint_core::{graphics::RequestedOpenGLVersion, platform::PlatformError};
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
pub struct OpenGLContext {
context: glutin::context::PossiblyCurrentContext,
surface: glutin::surface::Surface<glutin::surface::WindowSurface>,
winit_window: Arc<winit::window::Window>,
}
unsafe impl i_slint_renderer_femtovg::opengl::OpenGLInterface for OpenGLContext {
fn ensure_current(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if !self.context.is_current() {
self.context.make_current(&self.surface).map_err(|glutin_error| -> PlatformError {
format!("FemtoVG: Error making context current: {glutin_error}").into()
})?;
}
Ok(())
}
fn swap_buffers(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.winit_window.pre_present_notify();
self.surface.swap_buffers(&self.context).map_err(|glutin_error| -> PlatformError {
format!("FemtoVG: Error swapping buffers: {glutin_error}").into()
})?;
Ok(())
}
fn resize(
&self,
width: NonZeroU32,
height: NonZeroU32,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.ensure_current()?;
self.surface.resize(&self.context, width, height);
Ok(())
}
fn get_proc_address(&self, name: &std::ffi::CStr) -> *const std::ffi::c_void {
self.context.display().get_proc_address(name)
}
}
impl OpenGLContext {
pub(crate) fn new_context(
window_attributes: winit::window::WindowAttributes,
active_event_loop: &winit::event_loop::ActiveEventLoop,
requested_opengl_version: Option<RequestedOpenGLVersion>,
) -> Result<(Arc<winit::window::Window>, Self), PlatformError> {
let config_template_builder = glutin::config::ConfigTemplateBuilder::new();
// On macOS, there's only one GL config and that's initialized based on the values in the config template
// builder. So if that one has transparency enabled, it'll show up in the config, and will be set on the
// context later. So we must enable it here, there's no way of enabling it later.
// On EGL/GLX/WGL there are system provided configs that may or may not support transparency. Here in case
// the system doesn't support transparency, we want to fall back to a config that doesn't - better than not
// rendering anything at all. So we don't want to limit the configurations we get to see early on.
// Commented out due to https://github.com/rust-windowing/glutin/issues/1640
#[cfg(target_os = "macos")]
let config_template_builder = config_template_builder.with_transparency(true);
let display_builder = glutin_winit::DisplayBuilder::new()
.with_preference(glutin_winit::ApiPreference::FallbackEgl)
.with_window_attributes(Some(window_attributes.clone()));
let config_picker = |it: Box<dyn Iterator<Item = glutin::config::Config> + '_>| {
it.reduce(|accum, config| {
let transparency_check = config.supports_transparency().unwrap_or(false)
& !accum.supports_transparency().unwrap_or(false);
if transparency_check || config.num_samples() < accum.num_samples() {
config
} else {
accum
}
})
.expect("internal error: Could not find any matching GL configuration")
};
let (window, gl_config) = display_builder
.build(active_event_loop, config_template_builder, config_picker)
.map_err(|glutin_err| {
format!(
"Error creating OpenGL display ({:?}) with glutin: {}",
active_event_loop.display_handle(),
glutin_err
)
})?;
let gl_display = gl_config.display();
let raw_window_handle = window
.as_ref()
.map(|w| w.window_handle())
.transpose()
.map_err(|err| {
format!(
"Failed to retrieve a window handle while creating an OpenGL display: {err:?}"
)
})?
.map(|h| h.as_raw());
let requested_opengl_version =
requested_opengl_version.unwrap_or(RequestedOpenGLVersion::OpenGLES(Some((2, 0))));
let preferred_context_attributes = match requested_opengl_version {
RequestedOpenGLVersion::OpenGL(version) => {
let version =
version.map(|(major, minor)| glutin::context::Version { major, minor });
ContextAttributesBuilder::new()
.with_context_api(ContextApi::OpenGl(version))
.build(raw_window_handle)
}
RequestedOpenGLVersion::OpenGLES(version) => {
let version =
version.map(|(major, minor)| glutin::context::Version { major, minor });
ContextAttributesBuilder::new()
.with_context_api(ContextApi::Gles(version))
.build(raw_window_handle)
}
};
let fallback_context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);
let not_current_gl_context = unsafe {
gl_display
.create_context(&gl_config, &preferred_context_attributes)
.or_else(|_| gl_display.create_context(&gl_config, &fallback_context_attributes))
.map_err(|glutin_err| format!("Cannot create OpenGL context: {glutin_err}"))?
};
let window = match window {
Some(window) => window,
None => glutin_winit::finalize_window(active_event_loop, window_attributes, &gl_config)
.map_err(|winit_os_error| {
format!("Error finalizing window for OpenGL rendering: {winit_os_error}")
})?,
};
let raw_window_handle = window.window_handle().map_err(|err| {
format!("Failed to retrieve a window handle for window we just created: {err:?}")
})?;
let size: winit::dpi::PhysicalSize<u32> = window.surface_size();
let width: std::num::NonZeroU32 = size.width.try_into().map_err(|_| {
format!(
"Attempting to create an OpenGL window surface with an invalid width: {}",
size.width
)
})?;
let height: std::num::NonZeroU32 = size.height.try_into().map_err(|_| {
format!(
"Attempting to create an OpenGL window surface with an invalid height: {}",
size.height
)
})?;
let attrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(
raw_window_handle.as_raw(),
width,
height,
);
let surface = unsafe {
gl_display.create_window_surface(&gl_config, &attrs).map_err(|glutin_err| {
format!("Error creating OpenGL Window surface: {glutin_err}")
})?
};
let context = not_current_gl_context.make_current(&surface)
.map_err(|glutin_error: glutin::error::Error| -> PlatformError {
format!("FemtoVG Renderer: Failed to make newly created OpenGL context current: {glutin_error}")
.into()
})?;
// Align the GL layer to the top-left, so that resizing only invalidates the bottom/right
// part of the window.
#[cfg(target_os = "macos")]
if let raw_window_handle::RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle {
ns_view,
..
}) = window
.window_handle()
.map_err(|e| {
format!(
"Error obtaining window handle to adjust nsview layer contents placement: {e}"
)
})?
.as_raw()
{
let ns_view: &objc2_app_kit::NSView = unsafe { ns_view.cast().as_ref() };
ns_view.setLayerContentsPlacement(objc2_app_kit::NSViewLayerContentsPlacement::TopLeft);
}
// Try to default to vsync and ignore if the driver doesn't support it.
surface
.set_swap_interval(
&context,
glutin::surface::SwapInterval::Wait(NonZeroU32::new(1).unwrap()),
)
.ok();
let window = Arc::new(window);
Ok((window.clone(), Self { context, surface, winit_window: window }))
}
}

View file

@ -0,0 +1,142 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore clipchildren clipsiblings doublebuffer owndc
// cSpell: ignore pixelformatdescriptor wndclassw
use std::sync::OnceLock;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Gdi::{GetDC, HDC, ReleaseDC};
use windows::Win32::Graphics::OpenGL::{
ChoosePixelFormat, PFD_DOUBLEBUFFER, PFD_DRAW_TO_WINDOW, PFD_MAIN_PLANE, PFD_SUPPORT_OPENGL,
PFD_TYPE_RGBA, PIXELFORMATDESCRIPTOR, SetPixelFormat, wglCreateContext, wglDeleteContext,
wglGetCurrentContext, wglGetCurrentDC, wglGetProcAddress, wglMakeCurrent,
};
use windows::Win32::UI::WindowsAndMessaging::{
CS_OWNDC, CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, UnregisterClassW,
WINDOW_EX_STYLE, WNDCLASSW, WS_CLIPCHILDREN, WS_CLIPSIBLINGS, WS_OVERLAPPED,
};
use windows::core::{s, w};
pub fn opengl_2_available() -> bool {
static AVAILABLE: OnceLock<bool> = OnceLock::new();
// A probe that couldn't run says nothing about the driver, and glutin may still
// reach a working one through EGL.
*AVAILABLE.get_or_init(|| unsafe { probe() }.unwrap_or(true))
}
/// Every Windows installation has an opengl32.dll, but in virtual machines it often provides
/// only OpenGL 1.1, without the shader entry points. Creating a context still succeeds there,
/// so probe with a throwaway window and context up-front.
///
/// Returns `None` if the probe couldn't run, which says nothing about the driver.
unsafe fn probe() -> Option<bool> {
unsafe {
let class_name = w!("SlintOpenGLProbe");
let window_class = WNDCLASSW {
style: CS_OWNDC,
lpfnWndProc: Some(window_proc),
lpszClassName: class_name,
..Default::default()
};
if RegisterClassW(&window_class) == 0 {
return None;
}
// WGL requires a window that clips its children and siblings.
let available = CreateWindowExW(
WINDOW_EX_STYLE::default(),
class_name,
w!(""),
WS_OVERLAPPED | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
0,
0,
1,
1,
None,
None,
None,
None,
)
.ok()
.and_then(|window| {
let available = probe_window(window);
let _ = DestroyWindow(window);
available
});
let _ = UnregisterClassW(class_name, None);
available
}
}
unsafe extern "system" fn window_proc(
window: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
unsafe { DefWindowProcW(window, message, wparam, lparam) }
}
unsafe fn probe_window(window: HWND) -> Option<bool> {
unsafe {
let hdc = GetDC(Some(window));
if hdc.is_invalid() {
return None;
}
let available = probe_device_context(hdc);
ReleaseDC(Some(window), hdc);
available
}
}
unsafe fn probe_device_context(hdc: HDC) -> Option<bool> {
unsafe {
let pixel_format_descriptor = PIXELFORMATDESCRIPTOR {
nSize: std::mem::size_of::<PIXELFORMATDESCRIPTOR>() as u16,
nVersion: 1,
dwFlags: PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
iPixelType: PFD_TYPE_RGBA,
cColorBits: 32,
cDepthBits: 24,
iLayerType: PFD_MAIN_PLANE.0 as u8,
..Default::default()
};
let pixel_format = ChoosePixelFormat(hdc, &pixel_format_descriptor);
if pixel_format == 0 {
return None;
}
SetPixelFormat(hdc, pixel_format, &pixel_format_descriptor).ok()?;
let context = wglCreateContext(hdc).ok()?;
// Restore whatever was current before, so that probing from a thread that already
// renders through WGL is harmless.
let previous_context = wglGetCurrentContext();
let previous_hdc = wglGetCurrentDC();
let available = wglMakeCurrent(hdc, context).is_ok().then(|| {
let address = wglGetProcAddress(s!("glCreateShader")).map_or(0, |entry| entry as usize);
let _ = wglMakeCurrent(previous_hdc, previous_context);
// Besides null, some drivers report a missing entry point as 1, 2, 3 or -1.
!matches!(address, 0 | 1 | 2 | 3 | usize::MAX)
});
let _ = wglDeleteContext(context);
available
}
}
#[test]
fn probe_runs() {
// The answer depends on the machine, so this only covers the probe running to completion.
opengl_2_available();
}

View file

@ -0,0 +1,210 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
use std::rc::Rc;
use std::sync::Arc;
use crate::winit_compat::WindowSurfaceSizeExt;
use crate::winitwindowadapter::physical_size_to_slint;
use i_slint_core::graphics::RequestedGraphicsAPI;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::DrawOutcome;
use i_slint_renderer_skia::SkiaRenderer;
pub struct WinitSkiaRenderer {
renderer: SkiaRenderer,
requested_graphics_api: Option<RequestedGraphicsAPI>,
}
impl WinitSkiaRenderer {
pub fn new_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(not(target_os = "android"))]
pub fn new_software_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_software(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(not(ios_and_friends))]
pub fn new_opengl_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_opengl(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(target_vendor = "apple")]
pub fn new_metal_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_metal(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(supports_vulkan)]
pub fn new_vulkan_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_vulkan(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(target_family = "windows")]
pub fn new_direct3d_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_direct3d(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
#[cfg(feature = "unstable-wgpu-29")]
pub fn new_wgpu_29_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_wgpu_29(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
// skia depends on default features which includes wgpu_30, so this is always available
pub fn new_wgpu_30_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn super::WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SkiaRenderer::default_wgpu_30(&shared_backend_data.skia_context),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
pub fn factory_for_graphics_api(
requested_graphics_api: Option<&RequestedGraphicsAPI>,
) -> Result<
fn(
&Rc<crate::SharedBackendData>,
) -> Result<Box<dyn crate::WinitCompatibleRenderer>, PlatformError>,
PlatformError,
> {
match requested_graphics_api {
Some(api) => {
match api {
RequestedGraphicsAPI::OpenGL(_) => {
#[cfg(not(ios_and_friends))]
return Ok(Self::new_opengl_suspended);
#[cfg(ios_and_friends)]
return Err(format!(
"OpenGL rendering requested but this is not supported on iOS"
)
.into());
}
RequestedGraphicsAPI::Metal => {
#[cfg(target_vendor = "apple")]
return Ok(Self::new_metal_suspended);
#[cfg(not(target_vendor = "apple"))]
return Err("Metal rendering requested but this is only supported on Apple platforms".to_string().into());
}
RequestedGraphicsAPI::Vulkan => {
#[cfg(supports_vulkan)]
return Ok(Self::new_vulkan_suspended);
#[cfg(not(supports_vulkan))]
return Err(
"Vulkan rendering requested but renderer-skia-vulkan is not enabled"
.to_string()
.into(),
);
}
RequestedGraphicsAPI::Direct3D => {
#[cfg(target_family = "windows")]
return Ok(Self::new_direct3d_suspended);
#[cfg(not(target_family = "windows"))]
return Err(
"Direct3D rendering requested but this is only supported on Windows"
.to_string()
.into(),
);
}
#[cfg(feature = "unstable-wgpu-29")]
RequestedGraphicsAPI::WGPU29(..) => Ok(Self::new_wgpu_29_suspended),
#[cfg(feature = "unstable-wgpu-30")]
RequestedGraphicsAPI::WGPU30(..) => Ok(Self::new_wgpu_30_suspended),
}
}
None => Ok(Self::new_suspended),
}
}
}
impl super::WinitCompatibleRenderer for WinitSkiaRenderer {
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
self.renderer.render()
}
fn as_core_renderer(&self) -> &dyn i_slint_core::renderer::Renderer {
&self.renderer
}
fn suspend(&self) -> Result<(), PlatformError> {
self.renderer.set_pre_present_callback(None);
self.renderer.suspend()
}
#[cfg(target_os = "macos")]
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
self.renderer.set_transparent(transparent)
}
fn resume(
&self,
active_event_loop: &winit::event_loop::ActiveEventLoop,
window_attributes: winit::window::WindowAttributes,
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
) -> Result<Arc<winit::window::Window>, PlatformError> {
let transparent = window_attributes.transparent;
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|winit_os_error| {
PlatformError::from(format!(
"Error creating native window for Skia rendering: {}",
winit_os_error
))
},
)?);
let size = winit_window.surface_size();
self.renderer.set_window_handle(
winit_window.clone(),
winit_window.clone(),
physical_size_to_slint(&size),
self.requested_graphics_api.clone(),
transparent,
)?;
self.renderer.set_pre_present_callback(Some(Box::new({
let winit_window = winit_window.clone();
move || {
winit_window.pre_present_notify();
}
})));
Ok(winit_window)
}
}

View file

@ -0,0 +1,214 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! Delegate the rendering to the [`i_slint_renderer_software::SoftwareRenderer`]
use core::num::NonZeroU32;
use core::ops::DerefMut;
use i_slint_core::graphics::Rgb8Pixel;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::DrawOutcome;
pub use i_slint_renderer_software::SoftwareRenderer;
use i_slint_renderer_software::{PremultipliedRgbaColor, RepaintBufferType, TargetPixel};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use winit::event_loop::ActiveEventLoop;
use super::WinitCompatibleRenderer;
pub struct WinitSoftwareRenderer {
renderer: SoftwareRenderer,
_context: RefCell<Option<softbuffer::Context<Arc<winit::window::Window>>>>,
surface: RefCell<
Option<softbuffer::Surface<Arc<winit::window::Window>, Arc<winit::window::Window>>>,
>,
}
#[repr(transparent)]
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
struct SoftBufferPixel(pub u32);
impl From<SoftBufferPixel> for PremultipliedRgbaColor {
#[inline]
fn from(pixel: SoftBufferPixel) -> Self {
let v = pixel.0;
PremultipliedRgbaColor {
red: (v >> 16) as u8,
green: (v >> 8) as u8,
blue: v as u8,
alpha: (v >> 24) as u8,
}
}
}
impl From<PremultipliedRgbaColor> for SoftBufferPixel {
#[inline]
fn from(pixel: PremultipliedRgbaColor) -> Self {
Self(
(pixel.alpha as u32) << 24
| ((pixel.red as u32) << 16)
| ((pixel.green as u32) << 8)
| (pixel.blue as u32),
)
}
}
impl TargetPixel for SoftBufferPixel {
fn blend(&mut self, color: PremultipliedRgbaColor) {
let mut x = PremultipliedRgbaColor::from(*self);
x.blend(color);
*self = x.into();
}
fn from_rgb(r: u8, g: u8, b: u8) -> Self {
Self(0xff000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32))
}
fn background() -> Self {
Self(0)
}
}
impl WinitSoftwareRenderer {
pub fn new_suspended(
_shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
Ok(Box::new(Self {
renderer: SoftwareRenderer::new(),
_context: RefCell::new(None),
surface: RefCell::new(None),
}))
}
}
impl super::WinitCompatibleRenderer for WinitSoftwareRenderer {
fn render(&self, window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
let size = window.size();
let Some((width, height)) = size.width.try_into().ok().zip(size.height.try_into().ok())
else {
// Nothing to render
return Ok(DrawOutcome::Success);
};
let mut borrowed_surface = self.surface.borrow_mut();
let Some(surface) = borrowed_surface.as_mut() else {
// Nothing to render
return Ok(DrawOutcome::Success);
};
let winit_window = surface.window().clone();
surface
.resize(width, height)
.map_err(|e| format!("Error resizing softbuffer surface: {e}"))?;
let mut target_buffer = surface
.buffer_mut()
.map_err(|e| format!("Error retrieving softbuffer rendering buffer: {e}"))?;
let age = target_buffer.age();
self.renderer.set_repaint_buffer_type(match age {
1 => RepaintBufferType::ReusedBuffer,
2 => RepaintBufferType::SwappedBuffers,
_ => RepaintBufferType::NewBuffer,
});
let region = if std::env::var_os("SLINT_LINE_BY_LINE").is_none() {
let buffer: &mut [SoftBufferPixel] =
bytemuck::cast_slice_mut(target_buffer.deref_mut());
self.renderer.render(buffer, width.get() as usize)
} else {
// SLINT_LINE_BY_LINE is set and this is a debug mode where we also render in a Rgb565Pixel
struct FrameBuffer<'a> {
buffer: &'a mut [u32],
line: Vec<i_slint_renderer_software::Rgb565Pixel>,
}
impl i_slint_renderer_software::LineBufferProvider for FrameBuffer<'_> {
type TargetPixel = i_slint_renderer_software::Rgb565Pixel;
fn process_line(
&mut self,
line: usize,
range: core::ops::Range<usize>,
render_fn: impl FnOnce(&mut [Self::TargetPixel]),
) {
let line_begin = line * self.line.len();
let sub = &mut self.line[..range.len()];
render_fn(sub);
for (dst, src) in self.buffer[line_begin..][range].iter_mut().zip(sub) {
let p = Rgb8Pixel::from(*src);
*dst =
0xff000000 | ((p.r as u32) << 16) | ((p.g as u32) << 8) | (p.b as u32);
}
}
}
self.renderer.render_by_line(FrameBuffer {
buffer: &mut target_buffer,
line: vec![Default::default(); width.get() as usize],
})
};
let damage = region
.iter()
.filter_map(|(pos, size)| {
Some(softbuffer::Rect {
x: pos.x as u32,
y: pos.y as u32,
width: NonZeroU32::new(size.width)?,
height: NonZeroU32::new(size.height)?,
})
})
.collect::<Vec<_>>();
if !damage.is_empty() {
winit_window.pre_present_notify();
target_buffer
.present_with_damage(&damage)
.map_err(|e| format!("Error presenting softbuffer buffer: {e}"))?;
}
Ok(DrawOutcome::Success)
}
fn as_core_renderer(&self) -> &dyn i_slint_core::renderer::Renderer {
&self.renderer
}
fn occluded(&self, _: bool) {
// On X11 and Windows, the buffer is completely cleared when the window is hidden
// and the buffer age doesn't respect that, so clean the partial rendering cache
self.renderer.set_repaint_buffer_type(RepaintBufferType::NewBuffer);
}
fn resume(
&self,
active_event_loop: &ActiveEventLoop,
window_attributes: winit::window::WindowAttributes,
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
) -> Result<Arc<winit::window::Window>, PlatformError> {
let winit_window =
active_event_loop.create_window(window_attributes).map_err(|winit_os_error| {
PlatformError::from(format!(
"Error creating native window for software rendering: {winit_os_error}"
))
})?;
let winit_window = Arc::new(winit_window);
let context = softbuffer::Context::new(winit_window.clone())
.map_err(|e| format!("Error creating softbuffer context: {e}"))?;
let surface = softbuffer::Surface::new(&context, winit_window.clone()).map_err(
|softbuffer_error| format!("Error creating softbuffer surface: {softbuffer_error}"),
)?;
*self._context.borrow_mut() = Some(context);
*self.surface.borrow_mut() = Some(surface);
Ok(winit_window)
}
fn suspend(&self) -> Result<(), PlatformError> {
drop(self.surface.borrow_mut().take());
drop(self._context.borrow_mut().take());
Ok(())
}
}

View file

@ -0,0 +1,96 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
//! Delegate the rendering to vello, through
//! [`i_slint_renderer_anyrender::VelloRenderer`].
use std::rc::Rc;
use std::sync::Arc;
use i_slint_core::graphics::RequestedGraphicsAPI;
use i_slint_core::platform::PlatformError;
use i_slint_core::renderer::{DrawOutcome, Renderer};
use i_slint_renderer_anyrender::VelloRenderer;
use winit::event_loop::ActiveEventLoop;
use super::WinitCompatibleRenderer;
pub struct WinitVelloRenderer {
renderer: VelloRenderer,
requested_graphics_api: Option<RequestedGraphicsAPI>,
}
impl WinitVelloRenderer {
pub fn new_suspended(
shared_backend_data: &Rc<crate::SharedBackendData>,
) -> Result<Box<dyn WinitCompatibleRenderer>, PlatformError> {
if !i_slint_core::graphics::wgpu_29::any_wgpu29_adapters_with_gpu(
shared_backend_data.requested_graphics_api.clone(),
i_slint_core::graphics::wgpu_29::default_backends_to_avoid(),
) {
return Err(PlatformError::from("WGPU: No GPU adapters found"));
}
Ok(Box::new(Self {
renderer: VelloRenderer::new_vello(),
requested_graphics_api: shared_backend_data.requested_graphics_api.clone(),
}))
}
}
impl WinitCompatibleRenderer for WinitVelloRenderer {
fn render(&self, _window: &i_slint_core::api::Window) -> Result<DrawOutcome, PlatformError> {
self.renderer.render()
}
fn as_core_renderer(&self) -> &dyn Renderer {
&self.renderer
}
fn suspend(&self) -> Result<(), PlatformError> {
// Also releases the winit window the callback holds on to.
self.renderer.set_pre_present_callback(None);
self.renderer.suspend_window();
Ok(())
}
#[cfg(target_os = "macos")]
fn set_transparent(&self, transparent: bool) -> Result<(), PlatformError> {
self.renderer.set_transparent(transparent);
Ok(())
}
fn resume(
&self,
active_event_loop: &ActiveEventLoop,
window_attributes: winit::window::WindowAttributes,
_window_adapter_weak: std::rc::Weak<crate::winitwindowadapter::WinitWindowAdapter>,
) -> Result<Arc<winit::window::Window>, PlatformError> {
let transparent = window_attributes.transparent;
let winit_window = Arc::new(active_event_loop.create_window(window_attributes).map_err(
|winit_os_error| {
PlatformError::from(format!(
"Error creating native window for vello rendering: {winit_os_error}"
))
},
)?);
let size = winit_window.inner_size();
self.renderer.resume_window(
winit_window.clone(),
size.width.max(1),
size.height.max(1),
transparent,
self.requested_graphics_api.clone(),
)?;
self.renderer.set_pre_present_callback(Some(Box::new({
let winit_window = winit_window.clone();
move || {
winit_window.pre_present_notify();
}
})));
Ok(winit_window)
}
}