]> git.lyx.org Git - features.git/blob - development/tools/listFontWithLang.pl
f4f0ba1daaee0388d35942fe6eb6c15c8940b839
[features.git] / development / tools / listFontWithLang.pl
1 #! /usr/bin/env perl
2 # -*- mode: perl; -*-
3
4 # file listFontWithLang.pl
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING
7 # or at http://www.lyx.org/about/licence.php
8 #
9 # author Kornel Benko
10 # Full author contact details are available in the file CREDITS
11 # or at https://www.lyx.org/Credits
12 #
13 # Usage: listFontWithLang.pl <options>
14 #   Displays installed system font names selected by <options>
15 #   Option-strings with more that 1 char need be prefixed by '--'
16 #
17 # Option to get list of options: -h
18 #
19 # Some equivalencies for instance with option -n
20 #       -n arial
21 #       -N=arial
22 #       --nAme=Arial
23 #       --name arial
24 # Options and option-parameter are case insensitive
25
26 BEGIN {
27     use File::Spec;
28     my $p = File::Spec->rel2abs( __FILE__ );
29     $p =~ s/[\/\\]?[^\/\\]+$//;
30     unshift(@INC, $p);
31 }
32
33 use strict;
34 use warnings;
35 use Encode;
36 use GetOptions;
37
38 sub convertlang($);
39 sub extractlist($$$);   # my ($l, $islang, $txt, $rres) = @_;
40 sub getIndexes($$);
41 sub getVal($$$);        # my ($l, $txtval, $txtlang) = @_;
42 sub getproperties($$$$);
43 sub ismathfont($$);
44 sub correctstyle($);
45 sub decimalUnicode($);
46 sub contains($$);
47 sub sprintIntervalls($);
48
49 # Following fields for a parameter can be defined:
50 # fieldname:         Name of entry in %options
51 # type:              [:=][sif], ':' = optional, '=' = required, 's' = string, 'i' = integer, 'f' = float
52 # alias:             reference to a list of aliases e.g. ["alias1", "alias2", ... ]
53 # listsep:           Separator for multiple data
54 # comment:           Parameter description
55 my @optionsDef = (
56   # help + verbose already handled in 'GetOptions'
57   ["n",
58    {fieldname => "FontName", listsep => ',',
59     type => "=s", alias => ["name"],
60     comment => "Select font-names matching these (comma separated) regexes"},],
61   ["nn",
62    {fieldname => "NFontName",
63     type => "=s", listsep => ',',
64     comment => "Select font-names NOT matching these (comma separated) regexes"},],
65   ["p",
66    {fieldname => "Property",
67     type => "=s", listsep => ',',
68     comment => "Select fonts with properties matching these (comma separated) regexes"},],
69   ["np",
70    {fieldname => "NProperty",
71     type => "=s", listsep => ',',
72     comment => "Select fonts with properties NOT matching these (comma separated) regexes"},],
73   ["s",
74    {fieldname => "Scripts",
75     type => "=s", listsep => ',',
76     comment => "Select fonts with scripts matching these (comma separated) regexes"},],
77   ["ns",
78    {fieldname => "NScripts",
79     type => "=s", listsep => ',',
80     comment => "Select fonts with scripts NOT matching these (comma separated) regexes"},],
81   ["math",
82    {fieldname => "Math",
83     comment => "Select fonts probably containing math glyphs"},],
84   ["c",
85    {fieldname => "Contains",  alias => ["contains"],
86     type => "=s", listsep => ',',
87     comment => "Select fonts containing all these (possibly comma separated) glyphs",
88     comment2 => "____example: -c=\"0-9,u+32-u+x7f\"",}],
89   ["nc",
90    {fieldname => "NContains",
91     type => "=s", listsep => ',',
92     comment => "Select fonts NOT containing any of these (possibly comma separated) glyphs",
93     comment2 => "____example: --nc=\"0-9,u+32-u+x7f\"",}],
94   ["l",
95    {fieldname => "Lang",
96     type => "=s", alias=>["lang"],
97     comment => "Comma separated list of desired languages"},],
98   ["pc",
99    {fieldname => "PrintCharset", alias => ["printcharset"],
100     comment => "Print intervals of supported unicode character values"},],
101   ["pl",
102    {fieldname => "PrintLangs", alias => ["printlangs"],
103     comment => "Print supported languages"},],
104   ["pp",
105    {fieldname => "PrintProperties", alias => ["printproperties"],
106     comment => "Print properties from weight, slant and width"},],
107   ["ps",
108    {fieldname => "PrintScripts", alias => ["printscripts"],
109     comment => "Print supported scripts"},],
110   ["pf",
111    {fieldname => "PrintFiles", alias => ["printfiles"],
112     comment => "Print font file names"},],
113   ["pw",
114    {fieldname => "PrintWarnings",
115     comment => "Print warnings about discarded/overwritten fonts, conflicting styles"},],
116 );
117 my %options = %{&handleOptions(\@optionsDef)};
118
119 $options{Lang} = "" if (! defined($options{Lang}));
120
121 #############################################################
122
123 my @langs = split(',', $options{Lang});
124 for my $lg (@langs) {
125   $lg = &convertlang($lg);
126 }
127
128 for my $charFld ("Contains", "NContains") {
129   if (defined($options{$charFld})) {
130     my %glyphs = ();         # To ignore duplicates
131     for my $a1 (@{$options{$charFld}}) {
132       for my $e (decimalUnicode($a1)) {
133         $glyphs{$e} = 1;
134       }
135     }
136     # create intervalls
137     my @glyphs = sort {$a <=> $b;} keys %glyphs;
138
139     # $options{$charFld} no longer needed, so use it for unicode-point intervalls
140     $options{$charFld} = [];
141     my ($first, $last) = (undef, undef);
142     for my $i (@glyphs) {
143       if (! defined($last)) {
144         $first = $i;
145         $last = $i;
146         next;
147       }
148       if ($i == $last+1) {
149         $last = $i;
150         next;
151       }
152       push(@{$options{$charFld}}, [$first, $last]);
153       $first = $i;
154       $last = $i;
155     }
156     if (defined($last)) {
157       push(@{$options{$charFld}}, [$first, $last]);
158     }
159     if (exists($options{verbose})) {
160       if ($charFld eq "Contains") {
161         print "Checking for unicode-points: " . &sprintIntervalls($options{$charFld}) . "\n";
162       }
163       else {
164         print "Ignore if matching unicode-points: " . &sprintIntervalls($options{$charFld}) . "\n";
165       }
166     }
167   }
168 }
169
170 my $cmd = "fc-list";
171 if (defined($langs[0])) {
172   $cmd .= " :lang=" . join(',', @langs);
173 }
174
175 my $format = "foundry=\"%{foundry}\"" .
176     " postscriptname=\"%{postscriptname}\"" .
177     " fn=\"%{fullname}\" fnl=\"%{fullnamelang}\"" .
178     " family=\"%{family}\" flang=\"%{familylang}\" " .
179     " style=\"%{style}\" stylelang=\"%{stylelang}\"";
180
181 if (exists($options{PrintScripts}) || defined($options{Scripts}) || defined($options{NScripts}) || exists($options{Math})) {
182   $format .= " script=\"%{capability}\"";
183 }
184 if (exists($options{PrintLangs}) || defined($langs[0])) {
185   $format .= " lang=\"%{lang}\"";
186 }
187 if (exists($options{PrintProperties}) || defined($options{Property}) || defined($options{NProperty})) {
188   $format .= " weight=%{weight} slant=%{slant} width=%{width} spacing=%{spacing}";
189 }
190 if (defined($options{Contains}) || defined($options{NContains}) || exists($options{PrintCharset})) {
191   $format .= " charset=\"%{charset}\"";
192 }
193 $format .= " file=\"%{file}\" abcd\\n";
194 $cmd .= " -f '$format'";
195 #print "$cmd\n";
196
197 my %ftypes = (
198   # Dummy internal map
199   0 => "Serif",
200   100 => "Sans",
201   110 => "Script",
202   120 => "Fraktur",
203   125 => "DoubleStroke",
204   130 => "Fancy",
205   140 => "Initials",
206   200 => "Symbol",
207   "default" => "Serif",
208 );
209
210 my %weights = (
211   0 => "Thin",
212   40 => "Extralight",
213   50 => "Light",
214   55 => "Semilight",
215   75 => "Book",
216   80 => "Regular",
217   100 => "Medium",
218   180 => "Semibold",
219   200 => "Bold",
220   205 => "Extrabold",
221   210 => "Black",
222   215 => "ExtraBlack",
223 );
224
225 my %slants = (
226   0 => "Roman",
227   100 => "Italic",
228   110 => "Oblique",
229 );
230
231 my %widths = (
232   50 => "Ultracondensed",
233   63 => "Extracondensed",
234   75 => "Condensed",
235   87 => "Semicondensed",
236   100 => "Normal",
237   113 => "Semiexpanded",
238   125 => "Expanded",
239   150 => "Extraexpanded",
240   200 => "Ultraexpanded",
241 );
242
243 my %spacings = (
244   0 => "Proportional",
245   90 => "Dual",
246   100 => "Mono",
247   110 => "Charcell",
248   "default" => "Proportional",
249 );
250
251 # Build reverse mappings, (not needed yet)
252 for my $txt (qw(ftypes weights slants widths spacings)) {
253   my $map;
254   eval "\$map = \\%$txt";
255   for my $key (keys %{$map}) {
256     next if ($key !~ /^\d+$/);
257     my $value = lc($map->{$key});
258     $map->{"r"}->{$value} = $key;
259   }
260 }
261
262 # key:= fontname
263 #     subkey foundry
264 #            subfoundry
265 my %collectedfonts = ();
266 my %fontpriority = (
267   otf => 0,                # type 2, opentype CFF (Compact Font Format)
268   ttc => 1.1,              # type 1 (True Type font Collection)
269   ttf => 1.2,              # type 1 (True Type Font)
270   woff=> 1.3,              # type 1 (Web Open Font Format)
271   t1  => 1.4,              # type 1 (postscript)
272   pfb => 1.5,              # type 1 (Printer Font Binary)
273   pfa => 1.6,              # type 1 (Printer Font Ascii)
274   pcf => 5,                # Bitmap (Packaged Collaboration Files)?
275 );
276 my $nexttype = 6;
277
278 # list of regexes for known sans serif fonts
279 my %sansFonts = (
280   "value" => 100,          # Sans serif
281   "a" => qr/^(aharoni|arial|andika|angostura|anonymous|arab|aroania|arimo|asap)/i,
282   "b" => qr/^b(aekmuk|ebas|erenika|eteckna|euron|lue)/i,
283   "c" => qr/^c(abin|aliban|antarell|arbon|arlito|handas|hivo|mu bright|omfortaa|omi[cx]|oolvetica|ortoba|ousine|uprum|wtex(hei|yen)|yklop|ypro)/i,
284   "d" => qr/^(d2coding|dimnah|dosis|dyuthi)/i,
285   "e" => qr/^(electron|engebrechtre)/i,
286   "f" => qr/^(fandolhei|fetamont|fira|font awesome 5|forgotten)/i,
287   "g" => qr/^(gardiner|garuda|gfs ?neo|gillius|granada|graph|guanine|gunplay)/i,
288   "h" => qr/^(hack|hani|haramain|harano|harmattan|hor\b)/i,
289   "i" => qr/^(ibm plex|ikarius|inconsolata|induni.?h|iwona)/i,
290   "j" => qr/^(jara|jura)/i,
291   "k" => qr/^(kalimati|kanji|karla|karma|kayrawan|kenyan|keraleeyam|khalid|khmer [or]|kiloji|klaudia|ko[mn]atu|kurier|kustom)/i,
292   "l" => qr/^l(aksaman|arabie|ato|eague|exend|exigulim|ibel|iberation|ibre franklin|ibris|inux biolinum|obster|ogix|ohit|oma)/i,
293   "m" => qr/^m(\+ |anchu|anjari|arcellus|ashq|eera|etal|igmix|igu|ikachan|intspirit|iriam ?clm|ona|onlam|ono(fonto|id|isome|noki)|ontserrat|otoyal|ukti|usica)/i,
294   "n" => qr/^(nachlieli|nada|nafees|nagham|nanum(barunpen|square)|nice)/i,
295   "o" => qr/^(ocr|okolaks|opendyslexic|ostorah|ouhud|over|oxygen)/i,
296   "p" => qr/^(padauk|pagul|paktype|pakenham|palladio|petra|phetsarath|play\b|poiret|port\b|primer\b|prociono|pt\b|purisa)/i,
297   "q" => qr/^(qt(ancient|helvet|avanti|doghaus|eratype|eurotype|floraline|frank|fritz|future|greece|howard|letter|optimum)|quercus)/i,
298   "r" => qr/^(rachana|radio\b|raleway|ricty|roboto|rosario)/i,
299   "s" => qr/^(salem|samanata|sawasdee|shado|sharja|simple|sophia|soul|source|switzera)/i,
300   "t" => qr/^(tarablus|teen|texgyre(adventor|heros)|tiresias|trebuchet|tscu|tuffy)/i,
301   "u" => qr/^(ubuntu|ukij (bom|chechek|cjk|diwani|ekran|elipbe|inchike|jelliy|kufi|qara|qolyazma|teng|title|tor)|umpush|un ?(dinaru|jamo|graphic|taza|vada|yetgul)|uni(kurd|space|versalis)|uroob|urw ?classico)/i,
302   "v" => qr/^(veranda|vn ?urwclassico)/i,
303   "w" => qr/^(waree)/i,
304   "y" => qr/^(yanone)/i,
305   "z" => qr/^(zekton|zero)/i,
306 );
307 my %scriptFonts = (
308   "value" => 110,          # Script
309   "c" => qr/^(chancery)/i,
310   "d" => qr/^(dancing)/i,
311   "e" => qr/^(elegante)/i,
312   "j" => qr/^jsmath.?(rsfs)/i,
313   "k" => qr/^(kaushan|karumbi|kristi)/i,
314   "m" => qr/^(mathjax_script|miama)/i,
315   "n" => qr/^(nanum (brush|pen) script)/i,
316   "q" => qr/^qt(arabian|boulevard|brushstroke|chancery|coronation|florencia|handwriting|linostroke|merry|pandora|slogan)/i,
317   "r" => qr/^((romande.*|ruf)script|rsfs)/i,
318   "u" => qr/^(un ?pilgi|urw ?chancery)/i,
319 );
320
321 my %fraktFonts = (
322   "value" => 120,          # Fraktur
323   "e" => qr/^eufm/i,
324   "j" => qr/^(jsmath.?euf)/i,
325   "m" => qr/^(missaali)/i,
326   "o" => qr/^(oldania)/i,
327   "q" => qr/^qt(blackforest|cloisteredmonk|dublinirish|fraktur|heidelbergtype|(lino|london)scroll)/i,
328 );
329
330 my %fancyFonts = (
331   "value" => 130,          # Fancy
332   "c" => qr/^(cretino)/i,
333   "d" => qr/^dseg/i,
334   "f" => qr/^frederika/i,
335   "g" => qr/^(gfs.?theo)/i,
336   "k" => qr/^keter|kicking|kredit|kouzan|kerkis calligraphic/i,
337 );
338
339 my %initialFonts = (
340   "value" => 140,          # Initials
341   "e" => qr/^(eb.?garamond.?init)/i,
342   "l" => qr/^(libertinus|linux).*initials/i,
343   "y" => qr/^(yinit)/i,
344 );
345
346 my %symbolFonts = (
347   "value" => 200,          # Symbol
348   "a" => qr/^(academicons)/i,
349   "c" => qr/^(caladings|ccicons|chess|cmsy|cmex)/i,
350   "d" => qr/^(dingbats|drmsym|d05)/i,
351   "e" => qr/^(elusiveicons|emoji|esint|euterpe)/i,
352   "f" => qr/^(fandol.?brail|fdsymbol|fourierorns|font(awesome|ello|.?mfizz))/i,
353   "g" => qr/^(gan.?clm|gfs.?(baskerville|gazis|olga|porson|solomos|(bodoni|didot|complutum).?classic))/i,
354   "h" => qr/^(hots)/i,
355   "j" => qr/^jsmath.?(msam|cmsy|masm|msbm|wasy|cmex|stmary)/i,
356   "m" => qr/^(marvosym|material|msam|msbm)/i,
357   "n" => qr/^(noto.*emoji)/i,
358   "o" => qr/^(octicons)/i,
359   "q" => qr/^(qtdingbits)/i,
360   "s" => qr/^stmary/i,
361   "t" => qr/^(typicons|twemoji)/i,
362   "w" => qr/^(webdings|wasy)/i,
363 );
364
365 if (open(FI,  "$cmd |")) {
366  NXTLINE: while (my $l = <FI>) {
367     chomp($l);
368     while ($l !~ /abcd$/) {
369       $l .= <FI>;
370       chomp($l);
371     }
372     my $file = "";
373     my $fonttype;
374     if ($l =~ /file=\"([^\"]+)\"/) {
375       $file = $1;
376       #next if ($file !~ /\.(otf|ttf|pfa|pfb|pcf|ttc)$/i);
377       if ($file !~ /\.([a-z0-9]{2,5})$/i) {
378         print "Unhandled extension for file $file\n";
379         next;
380       }
381       $fonttype = lc($1);
382       if (! defined($fontpriority{$fonttype})) {
383         print "Added extension $fonttype for file $file\n";
384         $fontpriority{$fonttype} = $nexttype;
385         $nexttype++;
386       }
387     }
388     my %usedlangs = ();
389     if ($l =~ / lang=\"([^\"]+)\"/) {
390       my @ll = split(/\|/, $1);
391       for my $lx (@ll) {
392         $usedlangs{&convertlang($lx)} = 1;
393       }
394     }
395
396     for my $lang (@langs) {
397       next NXTLINE if (! defined($usedlangs{$lang}));
398     }
399     my $style = &getVal($l, "style", "stylelang");
400     $style =~ s/^\\040//;
401     my $fullname = &getVal($l, "fn", "fnl");
402     my $postscriptname = "";
403     if ($l =~ /postscriptname=\"([^\"]+)\"/) {
404       $postscriptname = $1;
405     }
406     my $family = &getVal($l, "family", "flang");
407     $family =~ s/\\040/\-/;
408     my $fontname;
409     if (length($fullname) < 3) {
410       if (length($postscriptname) < 2) {
411         $fontname = "$family $style";
412       }
413       else {
414         $fontname = $postscriptname;
415       }
416     }
417     else {
418       $fontname = $fullname;
419     }
420     if (defined($options{NFontName})) {
421       for my $fn (@{$options{NFontName}}) {
422         next NXTLINE if ($fontname =~ /$fn/i);
423       }
424     }
425     if (defined($options{FontName})) {
426       for my $fn (@{$options{FontName}}) {
427         next NXTLINE if ($fontname !~ /$fn/i);
428       }
429     }
430     my @charlist = ();
431     if (defined($options{Contains}) || defined($options{NContains}) || exists($options{PrintCharset})) {
432       if ($l =~ / charset=\"([^\"]+)\"/) {
433         my @list = split(/\s+/, $1);
434         for my $e (@list) {
435           my ($l, $h) = split('-', $e);
436           $h = $l if (! defined($h));
437           push(@charlist, [hex($l), hex($h)]);
438         }
439       }
440       if (defined($options{Contains})) {
441         for my $g (@{$options{Contains}}) {
442           next NXTLINE if (! contains($g, \@charlist));
443         }
444       }
445       if (defined($options{NContains})) {
446         for my $g (@{$options{NContains}}) {
447           # Ignore if ANY char exist in @charlist
448           for (my $i = $g->[0]; $i <= $g->[1]; $i++) {
449             next NXTLINE if (contains([$i,$i], \@charlist));
450           }
451         }
452       }
453     }
454     my $props = "";
455     my @errors = ();
456     if (exists($options{PrintProperties}) || defined($options{Property}) || defined($options{NProperty})) {
457       my $properties = getproperties($l, $fontname, $style, \@errors);
458       if (defined($options{Property})) {
459         for my $pn (@{$options{Property}}) {
460           next NXTLINE if ($properties !~ /$pn/i);
461         }
462       }
463       if (defined($options{NProperty})) {
464         for my $pn (@{$options{NProperty}}) {
465           next NXTLINE if ($properties =~ /$pn/i);
466         }
467       }
468       if (exists($options{PrintProperties})) {
469         $props .= " ($properties)";
470       }
471     }
472
473     if (exists($options{PrintLangs})) {
474       $props .= '(' . join(',', sort keys %usedlangs) . ')';
475     }
476     if (exists($options{PrintCharset})) {
477       $props .= '(' . &sprintIntervalls(\@charlist) . ')';
478     }
479     if (exists($options{PrintScripts}) || defined($options{Scripts}) || defined($options{NScripts}) || exists($options{Math})) {
480       my @scripts = ();
481       my $scripts = "";
482       if ($l =~ / script=\"([^\"]+)\"/) {
483         @scripts = split(/\s+/, $1);
484         for my $ent (@scripts) {
485           $ent =~ s/^\s*otlayout://;
486           $ent = lc($ent);
487         }
488         $scripts = join(',', @scripts);
489       }
490       if (exists($options{Math})) {
491         next NXTLINE if (! &ismathfont($fontname,\@scripts));
492       }
493       if (exists($options{PrintScripts})) {
494         $props .= "($scripts)";
495       }
496       if (!defined($scripts[0])) {
497         # No script defined in font, so check only $options{Scripts}
498         next NXTLINE if (defined($options{Scripts}));
499       }
500       else {
501         if (defined($options{Scripts})) {
502           for my $s (@{$options{Scripts}}) {
503             next NXTLINE if ($scripts !~ /$s/i);
504           }
505         }
506         if (defined($options{NScripts})) {
507           for my $s (@{$options{NScripts}}) {
508             next NXTLINE if ($scripts =~ /$s/i);
509           }
510         }
511       }
512     }
513     my $foundry = "";
514     if ($l =~ /foundry=\"([^\"]+)\"/) {
515       $foundry = $1;
516       $foundry =~ s/^\s+//;
517       $foundry =~ s/\s+$//;
518     }
519     if (defined($collectedfonts{$fontname}->{$foundry}->{errors})) {
520       # Apparently not the first one, so add some info
521       my $oldfonttype = $collectedfonts{$fontname}->{$foundry}->{fonttype};
522       if (defined($errors[0])) {
523         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, @errors);
524       }
525       if ($fontpriority{$oldfonttype} > $fontpriority{$fonttype}) {
526         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, "Warning: overwriting old info for file: " . $collectedfonts{$fontname}->{$foundry}->{file});
527       }
528       else {
529         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, "Warning: discarding new info for file: $file");
530         next;
531       }
532     }
533     else {
534       $collectedfonts{$fontname}->{$foundry}->{errors} = \@errors;
535     }
536     $collectedfonts{$fontname}->{$foundry}->{props} = $props;
537     $collectedfonts{$fontname}->{$foundry}->{file} = $file;
538     $collectedfonts{$fontname}->{$foundry}->{fonttype} = $fonttype;
539   }
540   close(FI);
541 }
542
543 for my $fontname (sort keys %collectedfonts) {
544   my @foundries = sort keys %{$collectedfonts{$fontname}};
545   my $printfoundries = 0;
546   if (defined($foundries[1])) {
547     $printfoundries = 1;
548   }
549   for my $foundry (@foundries) {
550     if (exists($options{PrintWarnings})) {
551       for my $err (@{$collectedfonts{$fontname}->{$foundry}->{errors}}) {
552         print "$err\n";
553       }
554     }
555     my $fn = "Font : $fontname";
556     if ($printfoundries && ($foundry ne "")) {
557       $fn .= " \[$foundry\]";
558     }
559     print $fn;
560     print $collectedfonts{$fontname}->{$foundry}->{props};
561     if (exists($options{PrintFiles})) {
562       print ": " . $collectedfonts{$fontname}->{$foundry}->{file} . "\n";
563     }
564     else {
565       print "\n";
566     }
567   }
568 }
569
570 exit(0);
571 #################################################################################
572 sub convertlang($)
573 {
574   my ($ilang) = @_;
575   if ($ilang =~ /^\s*([a-z]+)([\-_]([a-z]+))?\s*$/i) {
576     my ($x, $y) = ($1, $3);
577     if (defined($y)) {
578       $ilang = lc($x) . '-' . lc($y);
579     }
580     else {
581       $ilang = lc($x);
582     }
583   }
584   return($ilang);
585 }
586
587 sub extractlist($$$)
588 {
589   my ($l, $islang, $txt, $rres) = @_;
590   my @res = ();
591   if ($l =~ /$txt=\"([^\"]+)\"/) {
592     @res = split(',', $1);
593     if ($islang) {
594       for my $lg (@res) {
595         $lg = &convertlang($lg);
596       }
597     }
598   }
599   @{$rres} = @res;
600 }
601
602 sub getIndexes($$)
603 {
604   my ($lang, $rlangs) = @_;
605   my @res = ();
606
607   for (my $i = 0; defined($rlangs->[$i]); $i++) {
608     if ($rlangs->[$i] eq $lang) {
609       push(@res, $i);
610     }
611   }
612   return(\@res);
613 }
614
615 sub getVal($$$)
616 {
617   my ($l, $txtval, $txtlang) = @_;
618   my @values = ();
619   my @langs = ();
620   &extractlist($l, 0, $txtval, \@values);
621   return("") if (! defined($values[0]));
622   &extractlist($l, 1, $txtlang, \@langs);
623   my $i = &getIndexes("en", \@langs);
624   my $res = "";
625   for my $k (@{$i}) {
626     if (defined($values[$k]) && (length($values[$k]) > length($res))) {
627       $res = $values[$k];
628     }
629   }
630   return($values[0]) if ($res eq "");
631   return($res);
632 }
633
634 sub getsinglevalue($$$)
635 {
636   my ($l, $txt, $rMap, $rget) = @_;
637   my $val;
638   if ($l =~ / $txt=(\d+)/) {
639     $val = $1;
640     # Search for nearest value to $val
641     if (defined($rMap->{$val})) {
642       return($rMap->{$val});
643     }
644     my $maxv = -1;
645     my $minv = 1000;
646     for my $key (keys %{$rMap}) {
647       next if ($key !~ /^\d+$/);
648       my $diff = abs($key - $val);
649       if ($diff < $minv) {
650         $maxv = $key;
651         $minv = $diff;
652       }
653       elsif ($diff == $minv) {
654         if ($key < $maxv) {
655           $maxv = $key;
656         }
657       }
658     }
659     if (! defined($rMap->{$maxv})) {
660       print "ERROR2: txt=$txt, val=$val\n";
661       exit(-2);
662     }
663     if ($val > $maxv) {
664       return($rMap->{$maxv} . "+$minv");
665     }
666     else {
667       return($rMap->{$maxv} . "-$minv");
668     }
669   }
670   else {
671     return(undef);
672   }
673 }
674
675 sub addTxt($$)
676 {
677   my ($txt, $val) = @_;
678   return("$txt($val)");
679 }
680
681 sub getftype($$)
682 {
683   my ($fontname, $style) = @_;
684   if ($fontname =~ /(sans)[-_ ]?(serif)?/i) {
685     return($ftypes{100}); # Sans Serif
686   }
687   elsif ($fontname =~ /gothic|dotum|gulim/i) {
688     if ($fontname =~ /bisrat gothic/i) {
689       return($ftypes{0});    # Serif
690     }
691     else {
692       return($ftypes{100}); # Sans Serif
693     }
694   }
695   elsif ($style eq "PatchSans" && $fontname eq "font") {
696     return($ftypes{200});  # Symbol
697   }
698   elsif ($fontname =~ /serif|times|mincho|batang/i) {
699     if ($fontname =~ /good times/i) {
700       return($ftypes{100}); # Sans Serif
701     }
702     elsif ($fontname !~ /initials/i) {
703       return($ftypes{0});    # Serif
704     }
705   }
706   elsif ($fontname =~ /bbold|msbm|^dsrom/i) {
707     return($ftypes{125});  # Double stroke (math font)
708   }
709   # Now check for fonts without a hint in font name
710   if ($fontname =~ /^([a-z])/i) {
711     my $key = lc($1);
712     for my $rFonts (\%sansFonts, \%scriptFonts, \%fraktFonts, \%fancyFonts, \%initialFonts, \%symbolFonts) {
713       if (defined($rFonts->{$key})) {
714         if ($fontname =~ $rFonts->{$key}) {
715           return($ftypes{$rFonts->{"value"}});
716         }
717       }
718     }
719   }
720   if ("$fontname" =~ /^bpg/i) {
721     if ("$fontname" =~ /bpg (courier gpl|elite)/i) {
722       return($ftypes{0});    # Serif
723     }
724     else {
725       return($ftypes{100}); # Sans Serif
726     }
727   }
728   elsif ("$fontname" =~ /^dustismo/i) {
729     if ("$fontname" =~ /^dustismo roman/i) {
730       return($ftypes{0});    # Serif
731     }
732     else {
733       return($ftypes{100}); # Sans Serif
734     }
735   }
736   elsif ("$fontname" =~ /^go\b/i) {
737     if ("$fontname" =~ /^go mono/i) {
738       return($ftypes{0});    # Serif
739     }
740     else {
741       return($ftypes{100}); # Sans Serif
742     }
743   }
744   else {
745     return(undef);
746   }
747 }
748
749 sub getweight($$)
750 {
751   my ($fontname, $style) = @_;
752   my $result = undef;
753   for my $info ($style, $fontname) {
754     for my $key (keys %weights) {
755       next if ($key !~ /^\d+$/);
756       my $val = $weights{$key};
757       if ($info =~ /\b$val\b/i) {
758         return($val);
759       }
760     }
761   }
762   return($result);
763 }
764
765 sub getwidth($$)
766 {
767   my ($fontname, $style) = @_;
768   my $result = undef;
769   for my $key (keys %widths) {
770     next if ($key !~ /^\d+$/);
771     for my $info ($style, $fontname) {
772       if ($info =~ /\b$widths{$key}\b/i) {
773         return($widths{$key});
774       }
775       if ($info =~ /\bRegular\b/) {
776         if (!defined($result)) {
777           $result = $widths{100};
778         }
779       }
780     }
781   }
782   return($result);
783 }
784
785 sub getslant($$)
786 {
787   my ($fontname, $style) = @_;
788   for my $key (keys %slants) {
789     next if ($key !~ /^\d+$/);
790     if ($style =~ /\b$slants{$key}\b/i) {
791       return($slants{$key});
792     }
793   }
794   return(undef);
795 }
796
797 sub getspacing($$)
798 {
799   my ($fontname, $style) = @_;
800   for my $key (keys %spacings) {
801     next if ($key !~ /^\d+$/);
802     if ($style =~ /\b$spacings{$key}\b/i) {
803       return($spacings{$key});
804     }
805   }
806   if ("$fontname $style" =~ /(\bmono\b|luximono|typewriter|cursor|fixed)\b/i) {
807     return($spacings{100}); # Mono
808   }
809   else {
810     return(undef);
811   }
812 }
813
814 sub ismathfont($$)
815 {
816   my ($fontname, $rCapability) = @_;
817
818   return 1 if ($fontname =~ /math/i);
819   for my $cap (@{$rCapability}) {
820     return 1 if ($cap eq "math");
821   }
822   return 0;
823 }
824
825 sub getproperties($$$$)
826 {
827   my ($l, $fontname, $style, $rerrors) = @_;
828   my $newstyle = &correctstyle($style);
829   my $newfam = &correctstyle($fontname);
830   my @properties = ();
831
832   for my $txt (qw(ftype weight width slant spacing)) {
833     my ($map, $rget);
834     eval("\$map = " . '\%' . $txt . 's');
835     eval('$rget = \&' . "get$txt");
836     my $val2 = getsinglevalue($l, $txt, $map);
837     my $val1 = $rget->($newfam, $newstyle);
838     my $val;
839     if (defined($val2) && defined($val1) && ($val2 ne $val1)) {
840       if (($txt =~/^(weight|slant)$/) && ($newstyle =~ /$val1/)){
841         # style overrides weight and slant
842         push(@{$rerrors}, "Fontname($fontname),Style($style): Values for $txt ($val1 != $val2) differ, pick $val1 from style");
843         $val = $val1;
844       }
845       elsif ($newfam =~ /$val1/) {
846         push(@{$rerrors}, "Fontname($fontname),Style($style): Values for $txt ($val1 != $val2) differ, pick $val1 from fontname");
847         $val = $val1;
848       }
849       else {
850         push(@{$rerrors}, "Fontname($fontname),Style($style): Values for $txt ($val1 != $val2) differ, pick $val2 from $txt-property");
851         $val = $val2;
852       }
853     }
854     elsif (! defined($val2)) {
855       $val = $val1;
856     }
857     else {
858       $val = $val2;
859     }
860     if (defined($val)) {
861       push(@properties, &addTxt($txt,$val));
862     }
863     else {
864       if (defined($map->{"default"})) {
865         push(@properties, &addTxt($txt,$map->{"default"}));
866       }
867       else {
868         push(@{$rerrors}, "Undefined value for $txt");
869       }
870     }
871   }
872   return(join(' ', @properties));
873 }
874
875 sub correctstyle($)
876 {
877   my ($style) = @_;
878   $style =~ s/^\\040//;
879   $style =~ s/^\s*\d+\s*//;
880   $style =~ s/\s*\d+$//;
881   $style =~ s/italic/ Italic/i;
882   $style =~ s/oblique/ Oblique/i;
883   $style =~ s/[\-_]/ /g;
884   $style =~ s/\breg\b/Regular/i;
885   $style =~ s/\bregita(lic)?\b/Regular Italic/i;
886   $style =~ s/\bregobl(ique)?\b/Regular Oblique/i;
887   $style =~ s/medium/Medium /i;
888   $style =~ s/\bmedita(lic)?\b/Medium Italic/i;
889   $style =~ s/\bmedobl(ique)?\b/Medium Oblique/i;
890   $style =~ s/\bmed\b/Medium /i;
891   $style =~ s/\bdemi\b/SemiBold/i;
892   $style =~ s/\bex(pd|t)\b/Expanded/i;
893   $style =~ s/semi ?cond(ensed)?/SemiCondensed/i;
894   $style =~ s/[sd]emi ?(bold|bd|bol)/SemiBold/i;
895   $style =~ s/semi ?(expanded|extended|expd)/SemiExpanded/i;
896   $style =~ s/[sd]emi ?light/SemiLight/i;
897   $style =~ s/ultra ?(expanded|extended|expd)/UltraExpanded/i;
898   $style =~ s/light/Light /i;
899   $style =~ s/\blt\b/Light /i;
900   $style =~ s/(ultra|extra)(light|lt)/ExtraLight /i;
901   $style =~ s/\bheavy\b/Extrabold/i;
902   $style =~ s/\bhairline\b/Extralight/i;
903   $style =~ s/\bcond\b/Condensed/i;
904   $style =~ s/(roman)?slanted/ Italic/i;
905   $style =~ s/\bslant\b/Italic/i;
906   $style =~ s/\b(SC|Small(caps(alt)?)?)\b/SmallCaps/i;
907   $style =~ s/w3 mono/Dual/i;
908   $style =~ s/Regul[ea]r/Regular/i;
909   $style =~ s/Megablack/ExtraBlack/i;
910   $style =~ s/  +/ /g;
911   return($style);
912 }
913
914 # return list of unicode values of the input string
915 #Allow input of intervals (e.g. 'a-z')
916 sub decimalUnicode($)
917 {
918   my ($a) = @_;
919   my @res = ();
920   # Convert to unicode chars first
921   while ($a =~ /^(.*)u\+(0?x[\da-f]+|\d+)(.*)$/i) {
922     my ($prev, $d, $post) = ($1, $2, $3);
923     if ($d =~ /^0?x(.+)$/) {
924       $d = hex($1);
925     }
926     my $chr = encode('utf-8', chr($d));
927     $a = $prev . $chr . $post;
928   }
929   # $a is now a string of unicode chars
930   my $u = decode('utf-8', $a);
931   my @a = split(//, $u);
932   my $interval = 0;
933   my $start = undef;
934   for my $x (@a) {
935     if ($x eq '-') {    # Interval
936       $interval = 1;
937       next;
938     }
939     if ($interval && defined($start)) {
940       if (ord($x) < $start) {
941         for (my $i = $start - 1; $i >= ord($x); $i--) {
942           push(@res, $i);
943         }
944       }
945       else {
946         for (my $i = $start + 1; $i <= ord($x); $i++) {
947           push(@res, $i);
948         }
949       }
950       $start = undef;
951     }
952     else {
953       $start = ord($x);
954       push(@res, $start);
955     }
956     $interval = 0;
957   }
958   return(@res);
959 }
960
961
962 # check if the glyph-values in interval @{$ri} are contained
963 # in one of the (sorted) intervals
964 sub contains($$)
965 {
966   # ok if
967   # ...re0..........re1...
968   # ......start..end......
969   my ($ri, $rList) = @_;
970   my $start = $ri->[0];
971   my $end = $ri->[1];
972
973   for my $re (@{$rList}) {
974     next if ($re->[1] < $start);
975     # now we found a possible matching interval
976     return 1 if (($start >= $re->[0]) && ($end <= $re->[1]));
977     return 0;
978   }
979   return 0;
980 }
981
982 sub sprintIntervalls($)
983 {
984   my ($rList) = @_;
985   my @out = ();
986   for my $rE (@{$rList}) {
987     if ($rE->[0] != $rE->[1]) {
988       push(@out, $rE->[0] . '-' . $rE->[1]);
989     }
990     else {
991       push(@out, $rE->[0]);
992     }
993   }
994   return join(',', @out);
995 }