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