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