summaryrefslogtreecommitdiffstats
path: root/src/svg/svg-length.cpp
blob: a84c38bd4fa6ff20c68eb784d67c175b87cfef19 (plain)
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// SPDX-License-Identifier: GPL-2.0-or-later
/** @file
 * SVG data parser
 *//*
 * Authors: see git history
 
 *   Lauris Kaplinski <lauris@kaplinski.com>
 *   bulia byak <buliabyak@users.sf.net>
 *
 * Copyright (C) 2018 Authors
 * Released under GNU GPL v2+, read the file 'COPYING' for more information.
 */

#include <cmath>
#include <cstring>
#include <string>
#include <glib.h>
#include <iostream>
#include <vector>

#include "svg.h"
#include "stringstream.h"
#include "util/units.h"

static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, char **next);

#ifndef MAX
# define MAX(a,b) ((a < b) ? (b) : (a))
#endif

unsigned int sp_svg_number_read_f(gchar const *str, float *val)
{
    if (!str) {
        return 0;
    }

    char *e;
    float const v = g_ascii_strtod(str, &e);
    if ((gchar const *) e == str) {
        return 0;
    }

    *val = v;
    return 1;
}

unsigned int sp_svg_number_read_d(gchar const *str, double *val)
{
    if (!str) {
        return 0;
    }

    char *e;
    double const v = g_ascii_strtod(str, &e);
    if ((gchar const *) e == str) {
        return 0;
    }

    *val = v;
    return 1;
}

// TODO must add a buffer length parameter for safety:
// rewrite using std::string?
static unsigned int sp_svg_number_write_ui(gchar *buf, unsigned int val)
{
    unsigned int i = 0;
    char c[16u];
    do {
        c[16u - (++i)] = '0' + (val % 10u);
        val /= 10u;
    } while (val > 0u);

    memcpy(buf, &c[16u - i], i);
    buf[i] = 0;

    return i;
}

// TODO unsafe code ignoring bufLen
// rewrite using std::string?
static unsigned int sp_svg_number_write_i(gchar *buf, int bufLen, int val)
{
    int p = 0;
    unsigned int uval;
    if (val < 0) {
        buf[p++] = '-';
        uval = (unsigned int)-val;
    } else {
        uval = (unsigned int)val;
    }

    p += sp_svg_number_write_ui(buf+p, uval);

    return p;
}

// TODO unsafe code ignoring bufLen
// rewrite using std::string?
static unsigned sp_svg_number_write_d(gchar *buf, int bufLen, double val, unsigned int tprec, unsigned int fprec)
{
    /* Process sign */
    int i = 0;
    if (val < 0.0) {
        buf[i++] = '-';
        val = fabs(val);
    }

    /* Determine number of integral digits */
    int idigits = 0;
    if (val >= 1.0) {
        idigits = (int) floor(log10(val)) + 1;
    }

    /* Determine the actual number of fractional digits */
    fprec = MAX(static_cast<int>(fprec), static_cast<int>(tprec) - idigits);
    /* Round value */
    val += 0.5 / pow(10.0, fprec);
    /* Extract integral and fractional parts */
    double dival = floor(val);
    double fval = val - dival;
    /* Write integra */
    if (idigits > (int)tprec) {
        i += sp_svg_number_write_ui(buf + i, (unsigned int)floor(dival/pow(10.0, idigits-tprec) + .5));
        for(unsigned int j=0; j<(unsigned int)idigits-tprec; j++) {
            buf[i+j] = '0';
        }
        i += idigits-tprec;
    } else {
        i += sp_svg_number_write_ui(buf + i, (unsigned int)dival);
    }
    int end_i = i;
    if (fprec > 0 && fval > 0.0) {
        buf[i++] = '.';
        do {
            fval *= 10.0;
            dival = floor(fval);
            fval -= dival;
            int const int_dival = (int) dival;
            buf[i++] = '0' + int_dival;
            if (int_dival != 0) {
                end_i = i;
            }
            fprec -= 1;
        } while(fprec > 0 && fval > 0.0);
    }
    buf[end_i] = 0;
    return end_i;
}

unsigned int sp_svg_number_write_de(gchar *buf, int bufLen, double val, unsigned int tprec, int min_exp)
{
    int eval = (int)floor(log10(fabs(val)));
    if (val == 0.0 || eval < min_exp) {
        return sp_svg_number_write_ui(buf, 0);
    }
    unsigned int maxnumdigitsWithoutExp = // This doesn't include the sign because it is included in either representation
        eval<0?tprec+(unsigned int)-eval+1:
        eval+1<(int)tprec?tprec+1:
        (unsigned int)eval+1;
    unsigned int maxnumdigitsWithExp = tprec + ( eval<0 ? 4 : 3 ); // It's not necessary to take larger exponents into account, because then maxnumdigitsWithoutExp is DEFINITELY larger
    if (maxnumdigitsWithoutExp <= maxnumdigitsWithExp) {
        return sp_svg_number_write_d(buf, bufLen, val, tprec, 0);
    } else {
        val = eval < 0 ? val * pow(10.0, -eval) : val / pow(10.0, eval);
        int p = sp_svg_number_write_d(buf, bufLen, val, tprec, 0);
        buf[p++] = 'e';
        p += sp_svg_number_write_i(buf + p, bufLen - p, eval);
        return p;
    }
}

SVGLength::SVGLength()
    : _set(false)
    , unit(NONE)
    , value(0)
    , computed(0)
{
}

/* Length */

bool SVGLength::read(gchar const *str)
{
    if (!str) {
        return false;
    }

    SVGLength::Unit u;
    float v;
    float c;
    if (!sp_svg_length_read_lff(str, &u, &v, &c, nullptr)) {
        return false;
    }

    if (!std::isfinite(v)) {
        return false;
    }

    _set = true;
    unit = u;
    value = v;
    computed = c;

    return true;
}

static bool svg_length_absolute_unit(SVGLength::Unit u)
{
    return (u != SVGLength::EM && u != SVGLength::EX && u != SVGLength::PERCENT);
}

bool SVGLength::readAbsolute(gchar const *str)
{
    if (!str) {
        return false;
    }

    SVGLength::Unit u;
    float v;
    float c;
    if (!sp_svg_length_read_lff(str, &u, &v, &c, nullptr)) {
        return false;
    }

    if (svg_length_absolute_unit(u) == false) {
        return false;
    }

    _set = true;
    unit = u;
    value = v;
    computed = c;

    return true;
}


unsigned int sp_svg_length_read_computed_absolute(gchar const *str, float *length)
{
    if (!str) {
        return 0;
    }

    SVGLength::Unit unit;
    float computed;
    if (!sp_svg_length_read_lff(str, &unit, nullptr, &computed, nullptr)) {
        // failed to read
        return 0;
    }

    if (svg_length_absolute_unit(unit) == false) {
        return 0;
    }

    *length = computed;

    return 1;
}

std::vector<SVGLength> sp_svg_length_list_read(gchar const *str)
{
    if (!str) {
        return std::vector<SVGLength>();
    }

    SVGLength::Unit unit;
    float value;
    float computed;
    char *next = (char *) str;
    std::vector<SVGLength> list;

    while (sp_svg_length_read_lff(next, &unit, &value, &computed, &next)) {

        SVGLength length;
        length.set(unit, value, computed);
        list.push_back(length);

        while (next && *next &&
               (*next == ',' || *next == ' ' || *next == '\n' || *next == '\r' || *next == '\t')) {
            // the list can be comma- or space-separated, but we will be generous and accept
            // a mix, including newlines and tabs
            next++;
        }

        if (!next || !*next) {
            break;
        }
    }

    return list;
}


#define UVAL(a,b) (((unsigned int) (a) << 8) | (unsigned int) (b))

static unsigned sp_svg_length_read_lff(gchar const *str, SVGLength::Unit *unit, float *val, float *computed, char **next)
{
/* note: this function is sometimes fed a string with several consecutive numbers, e.g. by sp_svg_length_list_read.
So after the number, the string does not necessarily have a \0 or a unit, it might also contain a space or comma and then the next number!
*/

    if (!str) {
        return 0;
    }

    gchar const *e;
    float const v = g_ascii_strtod(str, (char **) &e);
    if (e == str) {
        return 0;
    }

    if (!e[0]) {
        /* Unitless */
        if (unit) {
            *unit = SVGLength::NONE;
        }
        if (val) {
            *val = v;
        }
        if (computed) {
            *computed = v;
        }
        if (next) {
            *next = nullptr; // no more values
        }
        return 1;
    } else if (!g_ascii_isalnum(e[0])) {
        /* Unitless or percent */
        if (e[0] == '%') {
            /* Percent */
            if (e[1] && g_ascii_isalnum(e[1])) {
                return 0;
            }
            if (unit) {
                *unit = SVGLength::PERCENT;
            }
            if (val) {
                *val = v * 0.01;
            }
            if (computed) {
                *computed = v * 0.01;
            }
            if (next) {
                *next = (char *) e + 1;
            }
            return 1;
        } else if (g_ascii_isspace(e[0]) && e[1] && g_ascii_isalpha(e[1])) {
            return 0; // spaces between value and unit are not allowed
        } else {
            /* Unitless */
            if (unit) {
                *unit = SVGLength::NONE;
            }
            if (val) {
                *val = v;
            }
            if (computed) {
                *computed = v;
            }
            if (next) {
                *next = (char *) e;
            }
            return 1;
        }
    } else if (e[1] && !g_ascii_isalnum(e[2])) {
        /* TODO: Allow the number of px per inch to vary (document preferences, X server
         * or whatever).  E.g. don't fill in computed here, do it at the same time as
         * percentage units are done. */
        unsigned int const uval = UVAL(e[0], e[1]);
        switch (uval) {
            case UVAL('p','x'):
                if (unit) {
                    *unit = SVGLength::PX;
                }
                if (computed) {
                    *computed = v;
                }
                break;
            case UVAL('p','t'):
                if (unit) {
                    *unit = SVGLength::PT;
                }
                if (computed) {
                    *computed = Inkscape::Util::Quantity::convert(v, "pt", "px");
                }
                break;
            case UVAL('p','c'):
                if (unit) {
                    *unit = SVGLength::PC;
                }
                if (computed) {
                    *computed = Inkscape::Util::Quantity::convert(v, "pc", "px");
                }
                break;
            case UVAL('m','m'):
                if (unit) {
                    *unit = SVGLength::MM;
                }
                if (computed) {
                    *computed = Inkscape::Util::Quantity::convert(v, "mm", "px");
                }
                break;
            case UVAL('c','m'):
                if (unit) {
                    *unit = SVGLength::CM;
                }
                if (computed) {
                    *computed = Inkscape::Util::Quantity::convert(v, "cm", "px");
                }
                break;
            case UVAL('i','n'):
                if (unit) {
                    *unit = SVGLength::INCH;
                }
                if (computed) {
                    *computed = Inkscape::Util::Quantity::convert(v, "in", "px");
                }
                break;
            case UVAL('e','m'):
                if (unit) {
                    *unit = SVGLength::EM;
                }
                break;
            case UVAL('e','x'):
                if (unit) {
                    *unit = SVGLength::EX;
                }
                break;
            default:
                /* Invalid */
                return 0;
                break;
        }
        if (val) {
            *val = v;
        }
        if (next) {
            *next = (char *) e + 2;
        }
        return 1;
    }

    /* Invalid */
    return 0;
}

unsigned int sp_svg_length_read_ldd(gchar const *str, SVGLength::Unit *unit, double *value, double *computed)
{
    float a;
    float b;
    unsigned int r = sp_svg_length_read_lff(str, unit, &a, &b, nullptr);
    if (r) {
        if (value) {
            *value = a;
        }
        if (computed) {
            *computed = b;
        }
    }
    return r;
}

std::string SVGLength::write() const
{
    return sp_svg_length_write_with_units(*this);
}

void SVGLength::set(SVGLength::Unit u, float v)
{
    _set = true;
    unit = u;
    Glib::ustring hack("px");
    switch( unit ) {
        case NONE:
        case PX:
        case EM:
        case EX:
        case PERCENT:
            break;
        case PT:
            hack = "pt";
            break;
        case PC:
            hack = "pc";
            break;
        case MM:
            hack = "pt";
            break;
        case CM:
            hack = "pt";
            break;
        case INCH:
            hack = "pt";
            break;
        default:
            break;
    }
    value = v;
    computed =  Inkscape::Util::Quantity::convert(v, hack, "px");
}

void SVGLength::set(SVGLength::Unit u, float v, float c)
{
    _set = true;
    unit = u;
    value = v;
    computed = c;
}

void SVGLength::unset(SVGLength::Unit u, float v, float c)
{
    _set = false;
    unit = u;
    value = v;
    computed = c;
}

void SVGLength::scale(double scale)
{
    value *= scale;
    computed *= scale;
}

void SVGLength::update(double em, double ex, double scale)
{
    if (unit == EM) {
        computed = value * em;
    } else if (unit == EX) {
        computed = value * ex;
    } else if (unit == PERCENT) {
        computed = value * scale;
    }
}

double sp_svg_read_percentage(char const *str, double def)
{
    if (str == nullptr) {
        return def;
    }

    char *u;
    double v = g_ascii_strtod(str, &u);
    while (isspace(*u)) {
        if (*u == '\0') {
            return v;
        }
        u++;
    }
    if (*u == '%') {
        v /= 100.0;
    }

    return v;
}

gchar const *sp_svg_length_get_css_units(SVGLength::Unit unit)
{
    switch (unit) {
        case SVGLength::NONE: return "";
        case SVGLength::PX: return "";
        case SVGLength::PT: return "pt";
        case SVGLength::PC: return "pc";
        case SVGLength::MM: return "mm";
        case SVGLength::CM: return "cm";
        case SVGLength::INCH: return "in";
        case SVGLength::EM: return "em";
        case SVGLength::EX: return "ex";
        case SVGLength::PERCENT: return "%";
    }
    return "";
}

/**
 * N.B.\ This routine will sometimes return strings with `e' notation, so is unsuitable for CSS
 * lengths (which don't allow scientific `e' notation).
 */
std::string sp_svg_length_write_with_units(SVGLength const &length)
{
    Inkscape::SVGOStringStream os;
    if (length.unit == SVGLength::PERCENT) {
        os << 100*length.value << sp_svg_length_get_css_units(length.unit);
    } else {
        os << length.value << sp_svg_length_get_css_units(length.unit);
    }
    return os.str();
}


void SVGLength::readOrUnset(gchar const *str, Unit u, float v, float c)
{
    if (!read(str)) {
        unset(u, v, c);
    }
}


/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8 :