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