length.rs 11.4 KB
Newer Older
1 2 3
extern crate libc;
extern crate glib;

4 5
use std::f64;

6 7 8
use self::glib::translate::*;

use strtod::*;
9 10
use drawing_ctx;
use drawing_ctx::RsvgDrawingCtx;
11 12 13

/* Keep this in sync with ../../rsvg-private.h:LengthUnit */
#[repr(C)]
14
#[derive(Debug, PartialEq, Copy, Clone)]
15 16 17 18 19 20 21 22 23 24 25 26
pub enum LengthUnit {
    Default,
    Percent,
    FontEm,
    FontEx,
    Inch,
    RelativeLarger,
    RelativeSmaller
}

/* Keep this in sync with ../../rsvg-private.h:LengthDir */
#[repr(C)]
27
#[derive(Debug, PartialEq, Copy, Clone)]
28 29 30 31 32 33 34 35 36 37 38 39
pub enum LengthDir {
    Horizontal,
    Vertical,
    Both
}

/* This is *not* an opaque struct; it is actually visible to the C code.  It is so
 * that the remaining C code can create RsvgLength values as part of existing
 * structures or objects, without allocations on the heap.
 */
/* Keep this in sync with ../../rsvg-private.h:RsvgLength */
#[repr(C)]
40
#[derive(Debug, PartialEq, Copy, Clone)]
41 42 43 44 45 46
pub struct RsvgLength {
    length: f64,
    unit: LengthUnit,
    dir: LengthDir
}

47 48 49 50 51 52 53 54 55 56
impl Default for RsvgLength {
    fn default () -> RsvgLength {
        RsvgLength {
            length: 0.0,
            unit:   LengthUnit::Default,
            dir:    LengthDir::Both
        }
    }
}

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
const POINTS_PER_INCH: f64 = 72.0;
const CM_PER_INCH:     f64 = 2.54;
const MM_PER_INCH:     f64 = 25.4;
const PICA_PER_INCH:   f64 = 6.0;

fn compute_named_size (name: &str) -> f64 {
    let power: f64;

    match name {
        "xx-small" => { power = -3.0; },
        "x-small"  => { power = -2.0; },
        "small"    => { power = -1.0; },
        "medium"   => { power = 0.0; },
        "large"    => { power = 1.0; },
        "x-large"  => { power = 2.0; },
        "xx-large" => { power = 3.0; },
        _          => { return 0.0; }
    }

    12.0 * 1.2f64.powf (power) / POINTS_PER_INCH
}

#[no_mangle]
pub extern fn rsvg_length_parse (string: *const libc::c_char, dir: LengthDir) -> RsvgLength {
    let my_string = unsafe { &String::from_glib_none (string) };

83
    RsvgLength::parse (my_string, dir)
84 85 86 87 88 89 90 91 92 93
}

/* https://www.w3.org/TR/SVG/types.html#DataTypeLength
 * https://www.w3.org/TR/2008/REC-CSS2-20080411/syndata.html#length-units
 *
 * Lengths have units.  When they need to be need resolved to
 * units in the user's coordinate system, some unit types
 * need to know if they are horizontal/vertical/both.  For example,
 * a some_object.width="50%" is 50% with respect to the current
 * viewport's width.  In this case, the @dir argument is used
94
 * inside RsvgLength::normalize(), when it needs to know to what the
95 96
 * length refers.
 */
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
impl RsvgLength {
    pub fn parse (string: &str, dir: LengthDir) -> RsvgLength {
        let unit: LengthUnit;

        let (mut value, rest) = strtod (string);

        match rest.as_ref () {
            "%" => {
                value *= 0.01; // normalize to [0, 1]
                unit = LengthUnit::Percent;
            },

            "em" => {
                unit = LengthUnit::FontEm;
            },

            "ex" => {
                unit = LengthUnit::FontEx;
            },

            "pt" => {
                value /= POINTS_PER_INCH;
                unit = LengthUnit::Inch;
            },

            "in" => {
                unit = LengthUnit::Inch;
            },

            "cm" => {
                value /= CM_PER_INCH;
                unit = LengthUnit::Inch;
            },

            "mm" => {
                value /= MM_PER_INCH;
                unit = LengthUnit::Inch;
            },

            "pc" => {
                value /= PICA_PER_INCH;
                unit = LengthUnit::Inch;
            },

            "larger" => {
                unit = LengthUnit::RelativeLarger;
            },

            "smaller" => {
                unit = LengthUnit::RelativeSmaller;
            },

            "xx-small" |
            "x-small" |
            "small" |
            "medium" |
            "large" |
            "x-large" |
            "xx-large" => {
                value = compute_named_size (rest);
                unit = LengthUnit::Inch;
            },

            _ => {
                unit = LengthUnit::Default;
            }
163 164
        }

165 166 167 168 169
        RsvgLength {
            length: value,
            unit: unit,
            dir: dir
        }
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
    pub fn normalize (&self, draw_ctx: *const RsvgDrawingCtx) -> f64 {
        match self.unit {
            LengthUnit::Default => {
                self.length
            },

            LengthUnit::Percent => {
                let (width, height) = drawing_ctx::get_view_box_size (draw_ctx);

                match self.dir {
                    LengthDir::Horizontal => { self.length * width },
                    LengthDir::Vertical   => { self.length * height },
                    LengthDir::Both       => { self.length * viewport_percentage (width, height) }
                }
            },

            LengthUnit::FontEm => {
                self.length * drawing_ctx::get_normalized_font_size (draw_ctx)
            },

            LengthUnit::FontEx => {
                self.length * drawing_ctx::get_normalized_font_size (draw_ctx) / 2.0
            },

            LengthUnit::Inch => {
                let (dpi_x, dpi_y) = drawing_ctx::get_dpi (draw_ctx);

                match self.dir {
                    LengthDir::Horizontal => { self.length * dpi_x },
                    LengthDir::Vertical   => { self.length * dpi_y },
                    LengthDir::Both       => { self.length * viewport_percentage (dpi_x, dpi_y) }
                }
            },

            // FIXME: these are pending: https://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#propdef-font-size
            LengthUnit::RelativeLarger |
            LengthUnit::RelativeSmaller => { 0.0 }
        }
    }

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    pub fn hand_normalize (&self,
                           pixels_per_inch: f64,
                           width_or_height: f64,
                           font_size: f64) -> f64 {
        match self.unit {
            LengthUnit::Default => { self.length },

            LengthUnit::Percent => { self.length * width_or_height },

            LengthUnit::FontEm => { self.length * font_size },

            LengthUnit::FontEx => { self.length * font_size / 2.0 },

            LengthUnit::Inch => { self.length * pixels_per_inch },

            _ => { 0.0 }
        }
    }
230 231
}

232 233 234 235 236 237 238 239 240 241
fn viewport_percentage (x: f64, y: f64) -> f64 {
    /* https://www.w3.org/TR/SVG/coords.html#Units
     *
     * "For any other length value expressed as a percentage of the viewport, the
     * percentage is calculated as the specified percentage of
     * sqrt((actual-width)**2 + (actual-height)**2))/sqrt(2)."
     */
    return (x * x + y * y).sqrt () / f64::consts::SQRT_2;
}

242
#[no_mangle]
243
pub extern fn rsvg_length_normalize (raw_length: *const RsvgLength, draw_ctx: *const RsvgDrawingCtx) -> f64 {
244 245 246 247 248
    assert! (!raw_length.is_null ());

    let length: &RsvgLength = unsafe { &*raw_length };

    length.normalize (draw_ctx)
249 250 251
}

#[no_mangle]
252
pub extern fn rsvg_length_hand_normalize (raw_length: *const RsvgLength,
253 254 255
                                          pixels_per_inch: f64,
                                          width_or_height: f64,
                                          font_size: f64) -> f64 {
256 257 258 259 260
    assert! (!raw_length.is_null ());

    let length: &RsvgLength = unsafe { &*raw_length };

    length.hand_normalize (pixels_per_inch, width_or_height, font_size)
261 262 263 264 265 266 267 268
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_default () {
269
        assert_eq! (RsvgLength::parse ("42", LengthDir::Horizontal),
270 271 272 273 274
                    RsvgLength {
                        length: 42.0,
                        unit:   LengthUnit::Default,
                        dir:    LengthDir::Horizontal});

275
        assert_eq! (RsvgLength::parse ("-42px", LengthDir::Horizontal),
276 277 278 279 280 281 282 283
                    RsvgLength {
                        length: -42.0,
                        unit:   LengthUnit::Default,
                        dir:    LengthDir::Horizontal});
    }

    #[test]
    fn parses_percent () {
284
        assert_eq! (RsvgLength::parse ("50.0%", LengthDir::Horizontal),
285 286 287 288 289 290 291 292
                    RsvgLength {
                        length: 0.5,
                        unit:   LengthUnit::Percent,
                        dir:    LengthDir::Horizontal});
    }

    #[test]
    fn parses_font_em () {
293
        assert_eq! (RsvgLength::parse ("22.5em", LengthDir::Vertical),
294 295 296 297 298 299 300 301
                    RsvgLength {
                        length: 22.5,
                        unit:   LengthUnit::FontEm,
                        dir:    LengthDir::Vertical });
    }

    #[test]
    fn parses_font_ex () {
302
        assert_eq! (RsvgLength::parse ("22.5ex", LengthDir::Vertical),
303 304 305 306 307 308 309 310
                    RsvgLength {
                        length: 22.5,
                        unit:   LengthUnit::FontEx,
                        dir:    LengthDir::Vertical });
    }

    #[test]
    fn parses_physical_units () {
311
        assert_eq! (RsvgLength::parse ("72pt", LengthDir::Both),
312 313 314 315 316
                    RsvgLength {
                        length: 1.0,
                        unit:   LengthUnit::Inch,
                        dir:    LengthDir::Both });

317
        assert_eq! (RsvgLength::parse ("-22.5in", LengthDir::Both),
318 319 320 321 322
                    RsvgLength {
                        length: -22.5,
                        unit:   LengthUnit::Inch,
                        dir:    LengthDir::Both });

323
        assert_eq! (RsvgLength::parse ("-25.4cm", LengthDir::Both),
324 325 326 327 328
                    RsvgLength {
                        length: -10.0,
                        unit:   LengthUnit::Inch,
                        dir:    LengthDir::Both });

329
        assert_eq! (RsvgLength::parse ("254mm", LengthDir::Both),
330 331 332 333 334
                    RsvgLength {
                        length: 10.0,
                        unit:   LengthUnit::Inch,
                        dir:    LengthDir::Both });

335
        assert_eq! (RsvgLength::parse ("60pc", LengthDir::Both),
336 337 338 339 340 341 342 343
                    RsvgLength {
                        length: 10.0,
                        unit:   LengthUnit::Inch,
                        dir:    LengthDir::Both });
    }

    #[test]
    fn parses_relative_larger () {
344
        assert_eq! (RsvgLength::parse ("larger", LengthDir::Vertical),
345 346 347 348 349 350 351 352
                    RsvgLength {
                        length: 0.0,
                        unit:   LengthUnit::RelativeLarger,
                        dir:    LengthDir::Vertical });
    }

    #[test]
    fn parses_relative_smaller () {
353
        assert_eq! (RsvgLength::parse ("smaller", LengthDir::Vertical),
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
                    RsvgLength {
                        length: 0.0,
                        unit:   LengthUnit::RelativeSmaller,
                        dir:    LengthDir::Vertical });
    }

    #[test]
    fn parses_named_sizes () {
        let names = vec![ "xx-small",
                           "x-small",
                           "small",
                           "medium",
                           "large",
                           "x-large",
                           "xx-large" ];

        let mut previous_value: Option<f64> = None;

        // Just ensure that the values are progressively larger; don't
        // enforce a particular sequence.

        for name in names {
376
            let length = RsvgLength::parse (name, LengthDir::Both);
377 378 379 380 381 382 383 384 385 386 387 388 389 390

            assert_eq! (length.unit, LengthUnit::Inch);
            assert_eq! (length.dir, LengthDir::Both);

            if let Some (v) = previous_value {
                assert! (length.length > v);
            } else {
                previous_value = Some (length.length);
            }

        }

    }
}