zed/gpui/src/elements/svg.rs

118 lines
3 KiB
Rust
Raw Normal View History

use std::borrow::Cow;
use serde_json::json;
2021-03-10 04:00:51 +00:00
use crate::{
2021-04-06 11:44:38 +00:00
color::ColorU,
geometry::{
rect::RectF,
vector::{vec2f, Vector2F},
},
scene, AfterLayoutContext, DebugContext, Element, Event, EventContext, LayoutContext,
PaintContext, SizeConstraint,
2021-03-10 04:00:51 +00:00
};
pub struct Svg {
path: Cow<'static, str>,
2021-04-06 11:44:38 +00:00
color: ColorU,
2021-03-10 04:00:51 +00:00
}
impl Svg {
pub fn new(path: impl Into<Cow<'static, str>>) -> Self {
2021-04-06 11:44:38 +00:00
Self {
path: path.into(),
2021-04-06 11:44:38 +00:00
color: ColorU::black(),
}
}
pub fn with_color(mut self, color: ColorU) -> Self {
self.color = color;
self
2021-03-10 04:00:51 +00:00
}
}
impl Element for Svg {
2021-04-06 11:44:38 +00:00
type LayoutState = Option<usvg::Tree>;
type PaintState = ();
2021-03-10 04:00:51 +00:00
fn layout(
&mut self,
2021-04-06 11:44:38 +00:00
constraint: SizeConstraint,
ctx: &mut LayoutContext,
) -> (Vector2F, Self::LayoutState) {
2021-04-06 11:44:38 +00:00
match ctx.asset_cache.svg(&self.path) {
Ok(tree) => {
let size = if constraint.max.x().is_infinite() && constraint.max.y().is_infinite() {
let rect = from_usvg_rect(tree.svg_node().view_box.rect);
rect.size()
} else {
let max_size = constraint.max;
let svg_size = from_usvg_rect(tree.svg_node().view_box.rect).size();
2021-04-06 11:44:38 +00:00
if max_size.x().is_infinite()
|| max_size.x() / max_size.y() > svg_size.x() / svg_size.y()
{
vec2f(svg_size.x() * max_size.y() / svg_size.y(), max_size.y())
} else {
vec2f(max_size.x(), svg_size.y() * max_size.x() / svg_size.x())
}
};
(size, Some(tree))
}
Err(error) => {
log::error!("{}", error);
(constraint.min, None)
}
}
2021-03-10 04:00:51 +00:00
}
fn after_layout(&mut self, _: Vector2F, _: &mut Self::LayoutState, _: &mut AfterLayoutContext) {
2021-03-10 04:00:51 +00:00
}
2021-04-06 11:44:38 +00:00
fn paint(&mut self, bounds: RectF, svg: &mut Self::LayoutState, ctx: &mut PaintContext) {
if let Some(svg) = svg.clone() {
ctx.scene.push_icon(scene::Icon {
bounds,
svg,
path: self.path.clone(),
color: self.color,
});
}
2021-03-10 04:00:51 +00:00
}
fn dispatch_event(
&mut self,
_: &Event,
2021-04-06 11:44:38 +00:00
_: RectF,
_: &mut Self::LayoutState,
_: &mut Self::PaintState,
_: &mut EventContext,
) -> bool {
2021-03-10 04:00:51 +00:00
false
}
fn debug(
&self,
bounds: RectF,
_: &Self::LayoutState,
_: &Self::PaintState,
_: &DebugContext,
) -> serde_json::Value {
json!({
"type": "Svg",
"bounds": bounds.to_json(),
"path": self.path,
"color": self.color.to_json(),
})
}
2021-03-10 04:00:51 +00:00
}
2021-04-06 11:44:38 +00:00
use crate::json::ToJson;
2021-04-06 11:44:38 +00:00
fn from_usvg_rect(rect: usvg::Rect) -> RectF {
RectF::new(
vec2f(rect.x() as f32, rect.y() as f32),
vec2f(rect.width() as f32, rect.height() as f32),
)
}