1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
use crate::engine::{DisplayMode, DisplayOptions, Engine, ViewerOptions};
use eframe::egui_wgpu;
use eframe::egui_wgpu::CallbackResources;
use eframe::epaint::PaintCallbackInfo;
use egui::{Pos2, Rect, Sense, Ui};
use std::sync::{Arc, Mutex};
use vsvg::{Document, DocumentTrait, LayerTrait, Length};
use wgpu::{CommandBuffer, CommandEncoder, Device, Queue, RenderPass};
/// Widget to display a [`Document`] in an egui application.
///
/// The widget is an egui wrapper around the internal `Engine` instance. It holds the state needed
/// for rendering, such as the scale and pan offset.
///
/// It supports multiple UI features:
/// - GPU-accelerated rendering of the document, typically in the central panel
/// - helper UI functions to act on the widget state (e.g. viewing options and layer visibility)
#[derive(Default)]
pub struct DocumentWidget {
/// document to display
document: Option<Arc<Document>>,
/// viewer options
viewer_options: Arc<Mutex<ViewerOptions>>,
/// pan offset
///
/// The offset is expressed in SVG coordinates, not in pixels. `self.scale` can be used for
/// conversion.
offset: Pos2,
/// scale factor
scale: f32,
/// should fit to view flag
must_fit_to_view: bool,
}
static PEN_WIDTHS_MM: &[f32] = &[
0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.5, 2.0, 3.0,
4.0, 5.0,
];
static PEN_OPACITY_PERCENT: &[u8] = &[100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 5];
impl DocumentWidget {
/// Create a document widget.
///
/// Initially, the document widget is empty. Use [`DocumentWidget::set_document()`] to set its
/// content.
#[must_use]
pub(crate) fn new<'a>(cc: &'a eframe::CreationContext<'a>) -> Option<Self> {
let viewer_options = Arc::new(Mutex::new(ViewerOptions::default()));
// Get the WGPU render state from the eframe creation context. This can also be retrieved
// from `eframe::Frame` when you don't have a `CreationContext` available.
let wgpu_render_state = cc.wgpu_render_state.as_ref()?;
// prepare engine
let engine = Engine::new(wgpu_render_state, viewer_options.clone());
// Because the graphics pipeline must have the same lifetime as the egui render pass,
// instead of storing the pipeline in our `Custom3D` struct, we insert it into the
// `paint_callback_resources` type map, which is stored alongside the render pass.
wgpu_render_state
.renderer
.write()
.callback_resources
.insert(engine);
Some(Self {
document: None,
viewer_options,
offset: Pos2::ZERO,
scale: 1.0,
must_fit_to_view: true,
})
}
pub fn set_document(&mut self, doc: Arc<Document>) {
self.document = Some(doc);
}
pub fn set_tolerance(&mut self, tolerance: f64) {
self.viewer_options
.lock()
.unwrap()
.display_options
.tolerance = tolerance;
}
#[must_use]
pub fn antialias(&self) -> f32 {
self.viewer_options
.lock()
.unwrap()
.display_options
.anti_alias
}
pub fn set_antialias(&self, anti_alias: f32) {
self.viewer_options
.lock()
.unwrap()
.display_options
.anti_alias = anti_alias;
}
#[must_use]
pub fn vertex_count(&self) -> u64 {
self.viewer_options.lock().unwrap().vertex_count
}
#[allow(clippy::missing_panics_doc)]
pub fn ui(&mut self, ui: &mut Ui) {
vsvg::trace_function!();
// do not actually allocate any space, so custom viewer code may use all of the central
// panel
let rect = ui.available_rect_before_wrap();
let response = ui.interact(rect, ui.id(), Sense::click_and_drag());
// fit to view on double click
if response.double_clicked() {
self.must_fit_to_view = true;
}
// fit to view on request
if self.must_fit_to_view {
self.fit_to_view(&rect);
}
// handle mouse input
let old_offset = self.offset;
let old_scale = self.scale;
self.offset -= response.drag_delta() / self.scale;
if let Some(mut pos) = response.hover_pos() {
response.ctx.input(|i| {
self.offset -= i.scroll_delta / self.scale;
self.scale *= i.zoom_delta();
});
// zoom around mouse
pos -= rect.min.to_vec2();
let dz = 1. / old_scale - 1. / self.scale;
self.offset += pos.to_vec2() * dz;
}
#[allow(clippy::float_cmp)]
if old_offset != self.offset || old_scale != self.scale {
self.must_fit_to_view = false;
}
// add the paint callback
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
rect,
DocumentWidgetCallback {
document: self.document.clone(),
origin: cgmath::Point2::new(self.offset.x, self.offset.y),
scale: self.scale,
rect,
},
));
}
#[allow(clippy::too_many_lines)]
pub fn view_menu_ui(&mut self, ui: &mut Ui) {
ui.menu_button("View", |ui| {
ui.set_min_width(200.0);
ui.menu_button("Display Mode", |ui| {
if ui
.radio_value(
&mut self.viewer_options.lock().unwrap().display_mode,
DisplayMode::Preview,
"Preview",
)
.clicked()
{
ui.close_menu();
};
if ui
.radio_value(
&mut self.viewer_options.lock().unwrap().display_mode,
DisplayMode::Outline,
"Outline",
)
.clicked()
{
ui.close_menu();
};
});
ui.separator();
{
let pen_width = &mut self
.viewer_options
.lock()
.unwrap()
.display_options
.line_display_options
.override_width;
ui.menu_button("Override Pen Width", |ui| {
if ui.radio_value(pen_width, None, "Off").clicked() {
ui.close_menu();
}
ui.separator();
for width in PEN_WIDTHS_MM {
if ui
.radio_value(
pen_width,
Some(Length::mm(*width).into()),
format!("{width:.2}mm"),
)
.clicked()
{
ui.close_menu();
}
}
});
}
{
let opacity = &mut self
.viewer_options
.lock()
.unwrap()
.display_options
.line_display_options
.override_opacity;
ui.menu_button("Override Pen Opacity", |ui| {
if ui.radio_value(opacity, None, "Off").clicked() {
ui.close_menu();
}
ui.separator();
for opacity_value in PEN_OPACITY_PERCENT {
#[allow(clippy::cast_lossless)]
if ui
.radio_value(
opacity,
Some(*opacity_value as f32 / 100.0),
format!("{opacity_value}%"),
)
.clicked()
{
ui.close_menu();
}
}
});
}
ui.separator();
ui.checkbox(
&mut self
.viewer_options
.lock()
.unwrap()
.display_options
.show_display_vertices,
"Show points",
);
ui.checkbox(
&mut self
.viewer_options
.lock()
.unwrap()
.display_options
.show_pen_up,
"Show pen-up trajectories",
);
ui.checkbox(
&mut self
.viewer_options
.lock()
.unwrap()
.display_options
.show_bezier_handles,
"Show control points",
);
ui.separator();
if ui.button("Fit to view").clicked() {
self.must_fit_to_view = true;
ui.close_menu();
}
ui.separator();
ui.horizontal(|ui| {
ui.label("AA:");
ui.add(egui::Slider::new(
&mut self
.viewer_options
.lock()
.unwrap()
.display_options
.anti_alias,
0.0..=2.0,
))
.on_hover_text("Renderer anti-aliasing (default: 0.5)");
});
ui.horizontal(|ui| {
ui.label("Tol:");
ui.add(
egui::Slider::new(
&mut self
.viewer_options
.lock()
.unwrap()
.display_options
.tolerance,
0.001..=10.0,
)
.logarithmic(true),
)
.on_hover_text("Tolerance for rendering curves (default: 0.01)");
});
ui.separator();
if ui
.button("Reset")
.on_hover_text("Reset all display options to the default")
.clicked()
{
let options = &mut self.viewer_options.lock().unwrap().display_options;
*options = DisplayOptions {
anti_alias: options.anti_alias,
..DisplayOptions::default()
};
ui.close_menu();
}
});
}
#[allow(clippy::missing_panics_doc)]
pub fn layer_menu_ui(&mut self, ui: &mut Ui) {
ui.menu_button("Layer", |ui| {
let Some(document) = self.document.clone() else {
return;
};
for (lid, layer) in &document.layers {
let mut viewer_options = self.viewer_options.lock().unwrap();
let visibility = viewer_options.layer_visibility.entry(*lid).or_insert(true);
let mut label = format!("Layer {lid}");
if let Some(name) = &layer.metadata().name {
label.push_str(&format!(": {name}"));
}
ui.checkbox(visibility, label);
}
});
}
fn fit_to_view(&mut self, viewport: &Rect) {
vsvg::trace_function!();
let Some(document) = self.document.clone() else {
return;
};
let bounds = if let Some(page_size) = document.metadata().page_size {
if page_size.w() != 0.0 && page_size.h() != 0.0 {
Some(kurbo::Rect::from_points(
(0., 0.),
(page_size.w(), page_size.h()),
))
} else {
document.bounds()
}
} else {
document.bounds()
};
if bounds.is_none() {
return;
}
let bounds = bounds.expect("bounds is not none");
#[allow(clippy::cast_possible_truncation)]
{
let (w, h) = (bounds.width() as f32, bounds.height() as f32);
let (view_w, view_h) = (viewport.width(), viewport.height());
self.scale = 0.95 * f32::min(view_w / w, view_h / h);
self.offset = Pos2::new(
bounds.x0 as f32 - (view_w / self.scale - w) / 2.0,
bounds.y0 as f32 - (view_h / self.scale - h) / 2.0,
);
}
}
}
struct DocumentWidgetCallback {
document: Option<Arc<Document>>,
origin: cgmath::Point2<f32>,
scale: f32,
rect: Rect,
}
impl egui_wgpu::CallbackTrait for DocumentWidgetCallback {
fn prepare(
&self,
device: &Device,
queue: &Queue,
_egui_encoder: &mut CommandEncoder,
callback_resources: &mut CallbackResources,
) -> Vec<CommandBuffer> {
vsvg::trace_scope!("wgpu prepare callback");
let engine: &mut Engine = callback_resources.get_mut().unwrap();
if let Some(document) = self.document.clone() {
engine.set_document(document);
}
engine.prepare(device, queue, self.rect, self.scale, self.origin);
Vec::new()
}
fn paint<'a>(
&'a self,
_info: PaintCallbackInfo,
render_pass: &mut RenderPass<'a>,
callback_resources: &'a CallbackResources,
) {
vsvg::trace_scope!("wgpu paint callback");
let engine: &Engine = callback_resources.get().unwrap();
engine.paint(render_pass);
}
}