Struct glifparser::component::GlifComponent
source · pub struct GlifComponent {
pub base: String,
pub filename: Option<PathBuf>,
pub xScale: IntegerOrFloat,
pub xyScale: IntegerOrFloat,
pub yxScale: IntegerOrFloat,
pub yScale: IntegerOrFloat,
pub xOffset: IntegerOrFloat,
pub yOffset: IntegerOrFloat,
pub identifier: Option<String>,
}Fields§
§base: String§filename: Option<PathBuf>§xScale: IntegerOrFloat§xyScale: IntegerOrFloat§yxScale: IntegerOrFloat§yScale: IntegerOrFloat§xOffset: IntegerOrFloat§yOffset: IntegerOrFloat§identifier: Option<String>Implementations§
source§impl GlifComponent
impl GlifComponent
sourcepub fn new() -> Self
pub fn new() -> Self
Examples found in repository?
src/glif/read.rs (line 283)
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
pub fn read_ufo_glif_pedantic<PD: PointData>(glif: &str, pedantry: Pedantry) -> Result<Glif<PD>, GlifParserError> {
let mut glif = xmltree::Element::parse(glif.as_bytes())?;
let mut ret = Glif::new();
if glif.name != "glyph" {
return Err(input_error!("Root element not <glyph>"))
}
if glif.attributes.get("format").ok_or(input_error!("no format in <glyph>"))? != "2" {
return Err(input_error!("<glyph> format not 2"))
}
ret.name = glif
.attributes
.get("name")
.ok_or(input_error!("<glyph> has no name"))?
.clone();
ret.components.root = ret.name.clone();
let advance = glif
.take_child("advance");
ret.width = if let Some(a) = advance {
let width = a.attributes
.get("width")
.ok_or(input_error!("<advance> has no width"))?;
let widthc = width.parse::<u64>();
match widthc {
Err(e) => if let Ok((f, false)) = width.parse::<f32>().map(|f|(f, f.is_subnormal())) {
const FLOATPOINTWARNING: &str = "Floating point value given as <advance> width — OpenType `hmtx` / `vmtx` will truncate it";
if !pedantry.should_mend() {
Err(input_error!(FLOATPOINTWARNING))?
}
log::warn!("{}, so we do too!", FLOATPOINTWARNING);
Some(f as u64)
} else {
log::trace!("<advance> parsing as int rose {:?}", e);
Err(input_error!("<advance> width neither int nor downgradable (not subnormal) float!"))?
},
Ok(i) => Some(i)
}
} else {
None
};
let mut unicodes = vec![];
while let Some(u) = glif.take_child("unicode") {
let unicodehex = u
.attributes
.get("hex")
.ok_or(input_error!("<unicode> has no hex"))?;
unicodes.push(
char::from_u32(
u32::from_str_radix(unicodehex, 16)
.or(Err(input_error!("<unicode> hex not int")))?
)
.ok_or(input_error!("<unicode> char conversion failed"))?,
);
}
ret.unicode = unicodes;
let mut anchors: Vec<Anchor<PD>> = Vec::new();
while let Some(anchor_el) = glif.take_child("anchor") {
let mut anchor = GlifAnchor::default();
anchor.x = anchor_el
.attributes
.get("x")
.ok_or(input_error!("<anchor> missing x"))?
.parse()
.or(Err(input_error!("<anchor> x not integer/float")))?;
anchor.y = anchor_el
.attributes
.get("y")
.ok_or(input_error!("<anchor> missing y"))?
.parse()
.or(Err(input_error!("<anchor> y not integer/float")))?;
anchor.class = anchor_el
.attributes
.get("name")
.map(|a|GlifStringLenOne::try_from(a.clone()))
.map_or(None, |r|r.ok());
anchors.push(Anchor::from_glif(&anchor, pedantry)?);
}
ret.anchors = anchors;
#[cfg(feature = "glifimage")] {
let mut images: Vec<GlifImage> = Vec::new();
while let Some(image_el) = glif.take_child("image") {
let filename = path::PathBuf::from(image_el
.attributes
.get("fileName")
.ok_or(input_error!("<image> missing fileName"))?);
let mut gimage = GlifImage::from_filename(filename)?;
load_matrix_and_identifier!(image_el, gimage, (xScale, xyScale, yxScale, yScale, xOffset, yOffset));
if let Some(color) = image_el.attributes.get("color") {
gimage.color = Some(color.parse()?);
}
images.push(gimage);
}
ret.images = images;
}
let mut guidelines: Vec<Guideline<PD>> = Vec::new();
while let Some(guideline_el) = glif.take_child("guideline") {
let gx = guideline_el
.attributes
.get("x")
.ok_or(input_error!("<guideline> missing x"))?
.parse()
.or(Err(input_error!("<guideline> x not float")))?;
let gy = guideline_el
.attributes
.get("y")
.ok_or(input_error!("<guideline> missing y"))?
.parse()
.or(Err(input_error!("<guideline> x not float")))?;
let angle: IntegerOrFloat = guideline_el
.attributes
.get("angle")
.ok_or(input_error!("<guideline> missing angle"))?
.as_str()
.try_into()
.or(Err(input_error!("<guideline> angle not float")))?;
let mut guideline = Guideline::from_x_y_angle(gx, gy, angle);
if let Some(color) = guideline_el.attributes.get("color") {
guideline.color = Some(color.parse()?);
}
guideline.name = guideline_el.attributes.get("name").map(|n|n.clone());
guideline.identifier = guideline_el.attributes.get("identifier").map(|i|i.clone());
guidelines.push(guideline);
}
ret.guidelines = guidelines;
if let Some(note_el) = glif.take_child("note") {
note_el.get_text().map(|t|ret.note=Some(t.into_owned()));
}
let mut goutline: GlifOutline = GlifOutline::new();
let outline_el = glif.take_child("outline");
if let Some(mut outline_elu) = outline_el {
while let Some(mut contour_el) = outline_elu.take_child("contour") {
let mut gcontour: GlifContour = Vec::new();
while let Some(point_el) = contour_el.take_child("point") {
let mut gpoint = GlifPoint::new();
gpoint.x = point_el
.attributes
.get("x")
.ok_or(input_error!("<point> missing x"))?
.parse()
.or(Err(input_error!("<point> x not float")))?;
gpoint.y = point_el
.attributes
.get("y")
.ok_or(input_error!("<point> missing y"))?
.parse()
.or(Err(input_error!("<point> y not float")))?;
match point_el.attributes.get("name") {
Some(n) => gpoint.name = Some(n.clone()),
None => {}
}
gpoint.ptype = point_el.attributes.get("type").as_ref().map(|s| s.as_str()).unwrap_or("offcurve").into();
match point_el.attributes.get("smooth") {
Some(s) => if s == "yes" {
if gpoint.ptype != PointType::OffCurve {
gpoint.smooth = true;
} else {
log::error!("Ignoring illogical `smooth=yes` on offcurve point");
}
},
_ => {}
}
if gpoint.ptype.is_valid() {
gcontour.push(gpoint);
} else {
Err(GlifInputError(format!("Shouldn't write <point type={}> to UFO .glif!", gpoint.ptype)))?;
}
}
if gcontour.len() > 0 {
goutline.push(gcontour);
}
}
while let Some(component_el) = outline_elu.take_child("component") {
let mut gcomponent = GlifComponent::new();
load_matrix_and_identifier!(component_el, gcomponent, (xScale, xyScale, yxScale, yScale, xOffset, yOffset));
gcomponent.base = component_el.attributes.get("base").ok_or(input_error!("<component> missing base"))?.clone();
ret.components.vec.push(gcomponent);
}
}
#[cfg(feature = "glifserde")]
if let Some(mut lib) = glif.take_child("lib") {
let mut plist_temp: Vec<u8> = vec![];
lib.name = String::from("plist");
match lib.write(&mut plist_temp).map(|()|plist::from_bytes(&plist_temp)) {
Ok(Ok(lib_p)) => ret.lib = Lib::Plist(lib_p),
Err(e) => {
log::error!("Failed to serialize .glif lib as XML? Error: {:?}", e);
ret.lib = Lib::Xml(lib)
},
Ok(Err(e)) => {
log::error!("Failed to deserialize .glif lib XML as plist? Error: {:?}", e);
}
}
}
#[cfg(not(feature = "glifserde"))]
if let Some(_) = glif.take_child("lib") {
log::warn!("Without glifserde, cannot decode plist!")
}
goutline.figure_type();
ret.order = goutline.otype.into();
let outline: Outline<PD> = goutline.try_into()?;
if outline.len() > 0 || ret.components.vec.len() > 0 {
ret.outline = Some(outline);
}
Ok(ret)
}source§impl GlifComponent
impl GlifComponent
sourcepub fn matrix(&self) -> GlifMatrix
pub fn matrix(&self) -> GlifMatrix
Examples found in repository?
src/component.rs (line 113)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
pub fn to_component<PD: PointData>(&self) -> Result<Component<PD>, GlifParserError> {
let gliffn = &self.filename.as_ref().ok_or(GlifParserError::GlifFilenameNotSet(self.base.clone()))?;
let mut ret = Component::new();
ret.matrix = self.matrix().into();
ret.glif.name = self.base.clone();
ret.glif.filename = self.filename.clone();
let component_xml = fs::read_to_string(&gliffn).or(Err(GlifParserError::GlifFilenameNotSet("Glif filename leads to unreadable file".to_string())))?;
let mut newglif: Glif<PD> = glif::read(&component_xml)?;
for component in newglif.components.vec.iter_mut() {
component.set_file_name(&gliffn);
}
ret.glif.components = newglif.components;
ret.glif.anchors = newglif.anchors;
ret.glif.outline = newglif.outline;
Ok(ret)
}source§impl GlifComponent
impl GlifComponent
sourcepub fn set_file_name<F: AsRef<Path>>(&mut self, gliffn: F)
pub fn set_file_name<F: AsRef<Path>>(&mut self, gliffn: F)
Sets the filename of a component relative to its base’s filename (gliffn)
Examples found in repository?
src/glif/read.rs (line 62)
54 55 56 57 58 59 60 61 62 63 64 65 66
pub fn read_ufo_glif_from_filename_pedantic<F: AsRef<path::Path> + Clone, PD: PointData>(filename: F, pedantry: Pedantry) -> Result<Glif<PD>, GlifParserError> {
let glifxml = match fs::read_to_string(&filename) {
Ok(s) => s,
Err(ioe) => Err(GlifParserError::GlifFileIoError(Some(Rc::new(ioe))))?
};
let mut glif: Glif<PD> = read_ufo_glif_pedantic(&glifxml, pedantry)?;
let filenamepb = filename.as_ref().to_path_buf();
for component in glif.components.vec.iter_mut() {
component.set_file_name(&filenamepb);
}
glif.filename = Some(filenamepb);
Ok(glif)
}More examples
src/component.rs (line 119)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
pub fn to_component<PD: PointData>(&self) -> Result<Component<PD>, GlifParserError> {
let gliffn = &self.filename.as_ref().ok_or(GlifParserError::GlifFilenameNotSet(self.base.clone()))?;
let mut ret = Component::new();
ret.matrix = self.matrix().into();
ret.glif.name = self.base.clone();
ret.glif.filename = self.filename.clone();
let component_xml = fs::read_to_string(&gliffn).or(Err(GlifParserError::GlifFilenameNotSet("Glif filename leads to unreadable file".to_string())))?;
let mut newglif: Glif<PD> = glif::read(&component_xml)?;
for component in newglif.components.vec.iter_mut() {
component.set_file_name(&gliffn);
}
ret.glif.components = newglif.components;
ret.glif.anchors = newglif.anchors;
ret.glif.outline = newglif.outline;
Ok(ret)
}sourcepub fn to_component<PD: PointData>(
&self
) -> Result<Component<PD>, GlifParserError>
pub fn to_component<PD: PointData>(
&self
) -> Result<Component<PD>, GlifParserError>
Must have filename set, and that file must be readable, for this to work.
Examples found in repository?
src/component.rs (line 254)
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
fn from(glifcs: &GlifComponents) -> Self {
let mut unique_found = None;
fn component_to_tree<PD: PointData>(component: Component<PD>, uniques: &mut Tree<String>, unique_found: &mut Option<(String, String)>) -> Result<Tree<Component<PD>>, GlifParserError> {
let mut tree = Tree::new(component.clone());
for gc in component.glif.components.vec.iter() {
let component_inner = gc.to_component()?;
uniques.back_mut().unwrap().push_back(Tree::new(gc.base.clone()));
// Generate a list of parents for the backmost node
let parents = match uniques.back() {
Some(mut node) => {
while let Some(nn) = node.back() {
node = nn;
};
let mut parents: Vec<String> = vec![];
while let Some(p) = node.parent() {
parents.push(p.data().clone());
node = p;
}
parents
},
None => vec![]
};
if parents.contains(&gc.base) || gc.base == component.glif.name {
return {
*unique_found = Some((component.glif.name.clone(), gc.base.clone()));
Ok(tree)
}
}
tree.push_back(component_to_tree(component_inner, uniques, unique_found)?);
}
Ok(tree)
}
let mut forest = Forest::new();
let cs: Vec<_> = glifcs.vec.iter().map(|gc| {
let mut uniques: Tree<String> = Tree::new(glifcs.root.clone());
uniques.push_back(Tree::new(gc.base.clone()));
component_to_tree(gc.to_component()?, &mut uniques, &mut unique_found)
}).collect();
for c in cs {
forest.push_back(c?);
}
match unique_found {
Some((base, unique)) => {Err(GlifParserError::GlifComponentsCyclical(format!("in glif {}, {} refers to {}", &glifcs.root, base, unique)))},
None => Ok(forest)
}
}pub fn refers_to<PD: PointData>(&self, glif: &Glif<PD>) -> bool
Trait Implementations§
source§impl Clone for GlifComponent
impl Clone for GlifComponent
source§fn clone(&self) -> GlifComponent
fn clone(&self) -> GlifComponent
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moresource§impl Debug for GlifComponent
impl Debug for GlifComponent
source§impl Default for GlifComponent
impl Default for GlifComponent
source§fn default() -> GlifComponent
fn default() -> GlifComponent
Returns the “default value” for a type. Read more
source§impl<'de> Deserialize<'de> for GlifComponent
impl<'de> Deserialize<'de> for GlifComponent
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
source§impl Hash for GlifComponent
impl Hash for GlifComponent
source§impl IntoXML for GlifComponent
impl IntoXML for GlifComponent
source§impl PartialEq<GlifComponent> for GlifComponent
impl PartialEq<GlifComponent> for GlifComponent
source§fn eq(&self, other: &GlifComponent) -> bool
fn eq(&self, other: &GlifComponent) -> bool
This method tests for
self and other values to be equal, and is used
by ==.