]> git.lyx.org Git - lyx.git/blob - development/tools/listFontWithLang.pl
Tools: optimize recognition of some font features in listFontWithLang.pl
[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 GetOptions;
36
37 sub convertlang($);
38 sub extractlist($$$);   # my ($l, $islang, $txt, $rres) = @_;
39 sub getIndex($$);
40 sub getVal($$$);        # my ($l, $txtval, $txtlang) = @_;
41 sub getproperties($$$$);
42 sub correctstyle($);
43
44 # Following fields for a parameter can be defined:
45 # fieldname:         Name of entry in %options
46 # type:              [:=][sif], ':' = optional, '=' = required, 's' = string, 'i' = integer, 'f' = float
47 # alias:             reference to a list of aliases e.g. ["alias1", "alias2", ... ]
48 # listsep:           Separator for multiple data
49 # comment:           Parameter description
50 my %optionsDef = (
51   # help + verbose already handled in 'GetOptions'
52   "l"       => {fieldname => "Lang",
53                 type => "=s", alias=>["lang"],
54                 comment => "Comma separated list of desired languages"},
55   "n"       => {fieldname => "FontName", listsep => ',',
56                 type => "=s", alias => ["name"],
57                 comment => "Select font-names matching these (comma separated) regexes"},
58   "nn"      => {fieldname => "NFontName",
59                 type => "=s", listsep => ',',
60                 comment => "Select font-names NOT matching these (comma separated) regexes"},
61   "pl"      => {fieldname => "PrintLangs", alias => ["printlangs"],
62                 comment => "Print supported languages"},
63   "pf"      => {fieldname => "PrintFiles", alias => ["printfiles"],
64                 comment => "Print font file names"},
65   "p"       => {fieldname => "Property",
66                 type => "=s", listsep => ',',
67                 comment => "Select fonts with properties matching these (comma separated) regexes"},
68   "np"      => {fieldname => "NProperty",
69                 type => "=s", listsep => ',',
70                 comment => "Select fonts with properties NOT matching these (comma separated) regexes"},
71   "pp"      => {fieldname => "PrintProperties", alias => ["printproperties"],
72                 comment => "Print properties from weight, slant and width"},
73   "s"       => {fieldname => "Scripts",
74                 type => "=s", listsep => ',',
75                 comment => "Select fonts with scripts matching these (comma separated) regexes"},
76   "ns"      => {fieldname => "NScripts",
77                 type => "=s", listsep => ',',
78                 comment => "Select fonts with scripts NOT matching these (comma separated) regexes"},
79   "ps"      => {fieldname => "PrintScripts", alias => ["printscripts"],
80                 comment => "Print supported scripts"},
81   "pw"      => {fieldname => "PrintWarnings",
82                 comment => "Print warnings about discarded/overwritten fonts, conflicting styles"},
83 );
84 my %options = %{&handleOptions(\%optionsDef)};
85
86 $options{Lang} = "" if (! defined($options{Lang}));
87
88 #############################################################
89
90 my @langs = split(',', $options{Lang});
91 for my $lg (@langs) {
92   $lg = &convertlang($lg);
93 }
94
95 my $cmd = "fc-list";
96 if (defined($langs[0])) {
97   $cmd .= " :lang=" . join(',', @langs);
98 }
99
100 my $format = "foundry=\"%{foundry}\" postscriptname=\"%{postscriptname}\" fn=\"%{fullname}\" fnl=\"%{fullnamelang}\" family=\"%{family}\" flang=\"%{familylang}\" style=\"%{style}\" stylelang=\"%{stylelang}\"";
101
102 if (exists($options{PrintScripts}) || defined($options{Scripts}) || defined($options{NSpripts})) {
103   $format .= " script=\"%{capability}\"";
104 }
105 if (exists($options{PrintLangs}) || defined($langs[0])) {
106   $format .= " lang=\"%{lang}\"";
107 }
108 if (exists($options{PrintProperties}) || defined($options{Property})) {
109   $format .= " weight=%{weight} slant=%{slant} width=%{width} spacing=%{spacing}";
110 }
111 $format .= " file=\"%{file}\" abcd\\n";
112 $cmd .= " -f '$format'";
113 #print "$cmd\n";
114
115 my %ftypes = (
116   # Dummy internal map
117   0 => "Serif",
118   100 => "Sans",
119   "default" => "Serif",
120 );
121
122 my %weights = (
123   0 => "Thin",
124   40 => "Extralight",
125   50 => "Light",
126   55 => "Semilight",
127   75 => "Book",
128   80 => "Regular",
129   100 => "Medium",
130   180 => "Semibold",
131   200 => "Bold",
132   205 => "Extrabold",
133   210 => "Black",
134 );
135
136 my %slants = (
137   0 => "Roman",
138   100 => "Italic",
139   110 => "Oblique",
140 );
141
142 my %widths = (
143   50 => "Ultracondensed",
144   63 => "Extracondensed",
145   75 => "Condensed",
146   87 => "Semicondensed",
147   100 => "Normal",
148   113 => "Semiexpanded",
149   125 => "Expanded",
150   150 => "Extraexpanded",
151   200 => "Ultraexpanded",
152 );
153
154 my %spacings = (
155   0 => "Proportional",
156   90 => "Dual",
157   100 => "Mono",
158   110 => "Charcell",
159   "default" => "Proportional",
160 );
161
162 # Build reverse mappings, (not needed yet)
163 for my $txt (qw(ftypes weights slants widths spacings)) {
164   my $map;
165   eval "\$map = \\%$txt";
166   for my $key (keys %{$map}) {
167     next if ($key !~ /^\d+$/);
168     my $value = lc($map->{$key});
169     $map->{"r"}->{$value} = $key;
170   }
171 }
172
173 # key:= fontname
174 #     subkey foundry
175 #            subfoundry
176 my %collectedfonts = ();
177 my %fontpriority = (
178   otf => 0,                # type 2, opentype CFF (Compact Font Format)
179   ttc => 1.1,              # type 1 (True Type font Collection)
180   ttf => 1.2,              # type 1 (True Type Font)
181   woff=> 1.3,              # type 1 (Web Open Font Format)
182   t1  => 1.4,              # type 1 (postscript)
183   pfb => 1.5,              # type 1 (Printer Font Binary)
184   pfa => 1.6,              # type 1 (Printer Font Ascii)
185   pcf => 5,                # Bitmap (Packaged Collaboration Files)?
186 );
187 my $nexttype = 6;
188
189 if (open(FI,  "$cmd |")) {
190  NXTLINE: while (my $l = <FI>) {
191     chomp($l);
192     while ($l !~ /abcd$/) {
193       $l .= <FI>;
194       chomp($l);
195     }
196     my $file = "";
197     my $fonttype;
198     if ($l =~ /file=\"([^\"]+)\"/) {
199       $file = $1;
200       #next if ($file !~ /\.(otf|ttf|pfa|pfb|pcf|ttc)$/i);
201       if ($file !~ /\.([a-z0-9]{2,5})$/i) {
202         print "Unhandled extension for file $file\n";
203         next;
204       }
205       $fonttype = lc($1);
206       if (! defined($fontpriority{$fonttype})) {
207         print "Added extension $fonttype for file $file\n";
208         $fontpriority{$fonttype} = $nexttype;
209         $nexttype++;
210       }
211     }
212     my $nfound = 0;
213     my %usedlangs = ();
214     if ($l =~ / lang=\"([^\"]+)\"/) {
215       my @ll = split(/\|/, $1);
216       for my $lx (@ll) {
217         $usedlangs{&convertlang($lx)} = 1;
218       }
219     }
220
221     for my $lang (@langs) {
222       next NXTLINE if (! defined($usedlangs{$lang}));
223     }
224     next if ($nfound);
225     my $style = &getVal($l, "style", "stylelang");
226     $style =~ s/^\\040//;
227     my $fullname = &getVal($l, "fn", "fnl");
228     my $postscriptname = "";
229     if ($l =~ /postscriptname=\"([^\"]+)\"/) {
230       $postscriptname = $1;
231     }
232     my $family = &getVal($l, "family", "flang");
233     $family =~ s/\\040/\-/;
234     my $fontname;
235     if (length($family) < 3) {
236       if (length($postscriptname) < 2) {
237         $fontname = $fullname;
238       }
239       else {
240         $fontname = $postscriptname;
241       }
242     }
243     else {
244       $fontname = "$family $style";
245     }
246     if (defined($options{NFontName})) {
247       for my $fn (@{$options{NFontName}}) {
248         next NXTLINE if ($fontname =~ /$fn/i);
249       }
250     }
251     if (defined($options{FontName})) {
252       for my $fn (@{$options{FontName}}) {
253         next NXTLINE if ($fontname !~ /$fn/i);
254       }
255     }
256     my $props = "";
257     my @errors = ();
258     if (exists($options{PrintProperties}) || defined($options{Property}) || defined($options{NProperty})) {
259       my $properties = getproperties($l, $family, $style, \@errors);
260       if (defined($options{Property})) {
261         for my $pn (@{$options{Property}}) {
262           next NXTLINE if ($properties !~ /$pn/i);
263         }
264       }
265       if (defined($options{NProperty})) {
266         for my $pn (@{$options{NProperty}}) {
267           next NXTLINE if ($properties =~ /$pn/i);
268         }
269       }
270       if (exists($options{PrintProperties})) {
271         $props .= " ($properties)";
272       }
273     }
274
275     if (exists($options{PrintLangs})) {
276       $props .= '(' . join(',', sort keys %usedlangs) . ')';
277     }
278     if (exists($options{PrintScripts}) || defined($options{Scripts}) || defined($options{NScripts})) {
279       my @scripts = ();
280       my $scripts = "";
281       if ($l =~ / script=\"([^\"]+)\"/) {
282         @scripts = split(/\s+/, $1);
283         for my $ent (@scripts) {
284           $ent =~ s/^\s*otlayout://;
285           $ent = lc($ent);
286         }
287         $scripts = join(',', @scripts);
288       }
289       if (exists($options{PrintScripts})) {
290         $props .= "($scripts)";
291       }
292       if (!defined($scripts[0])) {
293         # No script defined in font, so check only $options{Scripts}
294         next NXTLINE if (defined($options{Scripts}));
295       }
296       else {
297         if (defined($options{Scripts})) {
298           for my $s (@{$options{Scripts}}) {
299             next NXTLINE if ($scripts !~ /$s/i);
300           }
301         }
302         if (defined($options{NScripts})) {
303           for my $s (@{$options{NScripts}}) {
304             next NXTLINE if ($scripts =~ /$s/i);
305           }
306         }
307       }
308     }
309     my $foundry = "";
310     if ($l =~ /foundry=\"([^\"]+)\"/) {
311       $foundry = $1;
312       $foundry =~ s/^\s+//;
313       $foundry =~ s/\s+$//;
314     }
315     if (defined($collectedfonts{$fontname}->{$foundry}->{errors})) {
316       # Apparently not the first one, so add some info
317       my $oldfonttype = $collectedfonts{$fontname}->{$foundry}->{fonttype};
318       if (defined($errors[0])) {
319         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, @errors);
320       }
321       if ($fontpriority{$oldfonttype} > $fontpriority{$fonttype}) {
322         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, "Warning: overwriting old info for file: " . $collectedfonts{$fontname}->{$foundry}->{file});
323       }
324       else {
325         push(@{$collectedfonts{$fontname}->{$foundry}->{errors}}, "Warning: discarding new info for file: $file");
326         next;
327       }
328     }
329     else {
330       $collectedfonts{$fontname}->{$foundry}->{errors} = \@errors;
331     }
332     $collectedfonts{$fontname}->{$foundry}->{props} = $props;
333     $collectedfonts{$fontname}->{$foundry}->{file} = $file;
334     $collectedfonts{$fontname}->{$foundry}->{fonttype} = $fonttype;
335   }
336   close(FI);
337 }
338
339 for my $fontname (sort keys %collectedfonts) {
340   my @foundries = sort keys %{$collectedfonts{$fontname}};
341   my $printfoundries = 0;
342   if (defined($foundries[1])) {
343     $printfoundries = 1;
344   }
345   for my $foundry (@foundries) {
346     if (exists($options{PrintWarnings})) {
347       for my $err (@{$collectedfonts{$fontname}->{$foundry}->{errors}}) {
348         print "$err\n";
349       }
350     }
351     my $fn = "Font : $fontname";
352     if ($printfoundries && ($foundry ne "")) {
353       $fn .= " \[$foundry\]";
354     }
355     print $fn;
356     print $collectedfonts{$fontname}->{$foundry}->{props};
357     if (exists($options{PrintFiles})) {
358       print ": " . $collectedfonts{$fontname}->{$foundry}->{file} . "\n";
359     }
360     else {
361       print "\n";
362     }
363   }
364 }
365
366 exit(0);
367 #################################################################################
368 sub convertlang($)
369 {
370   my ($ilang) = @_;
371   if ($ilang =~ /^\s*([a-z]+)([\-_]([a-z]+))?\s*$/i) {
372     my ($x, $y) = ($1, $3);
373     if (defined($y)) {
374       $ilang = lc($x) . '-' . lc($y);
375     }
376     else {
377       $ilang = lc($x);
378     }
379   }
380   return($ilang);
381 }
382
383 sub extractlist($$$)
384 {
385   my ($l, $islang, $txt, $rres) = @_;
386   my @res = ();
387   if ($l =~ /$txt=\"([^\"]+)\"/) {
388     @{res} = split(',', $1);
389     if ($islang) {
390       for my $lg (@res) {
391         $lg = &convertlang($lg);
392       }
393     }
394   }
395   @{$rres} = @res;
396 }
397
398 sub getIndex($$)
399 {
400   my ($lang, $rlangs) = @_;
401   for (my $i = 0; defined($rlangs->[$i]); $i++) {
402     return $i if ($rlangs->[$i] eq $lang);
403   }
404   return(-1);
405 }
406
407 sub getVal($$$)
408 {
409   my ($l, $txtval, $txtlang) = @_;
410   my @values = ();
411   my @langs = ();
412   &extractlist($l, 0, $txtval, \@values);
413   return("") if (! defined($values[0]));
414   &extractlist($l, 1, $txtlang, \@langs);
415   my $i = &getIndex("en", \@langs);
416   return ($values[$i]) if ($i >= 0);
417   return($values[0]);
418 }
419
420 sub getsinglevalue($$$)
421 {
422   my ($l, $txt, $rMap, $rget) = @_;
423   my $val;
424   if ($l =~ / $txt=(\d+)/) {
425     $val = $1;
426     # Search for nearest value to $val
427     if (defined($rMap->{$val})) {
428       return($rMap->{$val});
429     }
430     my $maxv = -1;
431     my $minv = 1000;
432     for my $key (keys %{$rMap}) {
433       next if ($key !~ /^\d+$/);
434       my $diff = abs($key - $val);
435       if ($diff < $minv) {
436         $maxv = $key;
437         $minv = $diff;
438       }
439       elsif ($diff == $minv) {
440         if ($key < $maxv) {
441           $maxv = $key;
442         }
443       }
444     }
445     if (! defined($rMap->{$maxv})) {
446       print "ERROR2: txt=$txt, val=$val\n";
447       exit(-2);
448     }
449     if ($val > $maxv) {
450       return($rMap->{$maxv} . "+$minv");
451     }
452     else {
453       return($rMap->{$maxv} . "-$minv");
454     }
455   }
456   else {
457     return(undef);
458   }
459 }
460
461 sub addTxt($$)
462 {
463   my ($txt, $val) = @_;
464   return("$txt($val)");
465 }
466
467 sub getftype($$)
468 {
469   my ($family, $style) = @_;
470   if ("$family" =~ /arial|helvet|trebuchet/i) {
471     return($ftypes{100}); # Sans Serif
472   }
473   elsif ($family =~ /(sans)[-_ ]?(serif)?/i) {
474     return($ftypes{100}); # Sans Serif
475   }
476   elsif ($family =~ /serif/i) {
477     return($ftypes{0});    # Serif
478   }
479   else {
480     return(undef);
481   }
482 }
483
484 sub getweight($$)
485 {
486   my ($family, $style) = @_;
487   my $result = undef;
488   for my $key (keys %weights) {
489     next if ($key !~ /^\d+$/);
490     my $val = $weights{$key};
491     for my $info ($style, $family) {
492       if ($info =~ /\b$val\b/i) {
493         if ($val eq "Regular") {
494           $result = $val;    # It may refer to width
495         }
496         else {
497           return($val);
498         }
499       }
500     }
501   }
502   return($result);
503 }
504
505 sub getwidth($$)
506 {
507   my ($family, $style) = @_;
508   my $result = undef;
509   for my $key (keys %widths) {
510     next if ($key !~ /^\d+$/);
511     for my $info ($style, $family) {
512       if ($info =~ /\b$widths{$key}\b/i) {
513         return($widths{$key});
514       }
515       if ($info =~ /\bRegular\b/) {
516         if (!defined($result)) {
517           $result = $widths{100};
518         }
519       }
520     }
521   }
522   return($result);
523 }
524
525 sub getslant($$)
526 {
527   my ($family, $style) = @_;
528   for my $key (keys %slants) {
529     next if ($key !~ /^\d+$/);
530     if ($style =~ /\b$slants{$key}\b/i) {
531       return($slants{$key});
532     }
533   }
534   return(undef);
535 }
536
537 sub getspacing($$)
538 {
539   my ($family, $style) = @_;
540   for my $key (keys %spacings) {
541     next if ($key !~ /^\d+$/);
542     if ($style =~ /\b$spacings{$key}\b/i) {
543       return($spacings{$key});
544     }
545   }
546   if ("$family $style" =~ /(mono|typewriter|cursor|fixed)\b/i) {
547     return($spacings{100}); # Mono
548   }
549   else {
550     return(undef);
551   }
552 }
553
554 sub getproperties($$$$)
555 {
556   my ($l, $family, $style, $rerrors) = @_;
557   my $newstyle = &correctstyle($style);
558   my $newfam = &correctstyle($family);
559   my @properties = ();
560
561   for my $txt (qw(ftype weight width slant spacing)) {
562     my ($map, $rget);
563     eval("\$map = " . '\%' . $txt . 's');
564     eval('$rget = \&' . "get$txt");
565     my $val2 = getsinglevalue($l, $txt, $map);
566     my $val1 = $rget->($newfam, $newstyle);
567     my $val;
568     if (defined($val2) && defined($val1) && ($val2 ne $val1)) {
569       push(@{$rerrors}, "Family($family),Style($style): Values for $txt ($val1 != $val2) differ, selecting internal $txt($val2)");
570       $val = $val2;
571     }
572     elsif (! defined($val2)) {
573       $val = $val1;
574     }
575     else {
576       $val = $val2;
577     }
578     if (defined($val)) {
579       push(@properties, &addTxt($txt,$val));
580     }
581     else {
582       if (defined($map->{"default"})) {
583         push(@properties, &addTxt($txt,$map->{"default"}));
584       }
585       else {
586         push(@{$rerrors}, "Undefined value for $txt");
587       }
588     }
589   }
590   return(join(' ', @properties));
591 }
592
593 sub correctstyle($)
594 {
595   my ($style) = @_;
596   $style =~ s/^\\040//;
597   $style =~ s/^\s*\d+\s*//;
598   $style =~ s/\s*\d+$//;
599   $style =~ s/italic/ Italic/i;
600   $style =~ s/oblique/ Oblique/i;
601   $style =~ s/[\-_]/ /g;
602   $style =~ s/\breg\b/Regular/i;
603   $style =~ s/\bregita(lic)?\b/Regular Italic/i;
604   $style =~ s/\bregobl(ique)?\b/Regular Oblique/i;
605   $style =~ s/medium/Medium /i;
606   $style =~ s/\bmedita(lic)?\b/Medium Italic/i;
607   $style =~ s/\bmedobl(ique)?\b/Medium Oblique/i;
608   $style =~ s/\bmed\b/Medium /i;
609   $style =~ s/\bdemi\b/SemiBold/i;
610   $style =~ s/\bex(pd|t)\b/Expanded/i;
611   $style =~ s/semi ?cond(ensed)?/SemiCondensed/i;
612   $style =~ s/[sd]emi ?(bold|bd|bol)/SemiBold/i;
613   $style =~ s/semi ?(expanded|extended|expd)/SemiExpanded/i;
614   $style =~ s/[sd]emi ?light/SemiLight/i;
615   $style =~ s/ultra ?(expanded|extended|expd)/UltraExpanded/i;
616   $style =~ s/light/Light /i;
617   $style =~ s/\blt\b/Light /i;
618   $style =~ s/(ultra|extra)(light|lt)/ExtraLight /i;
619   $style =~ s/\bheavy\b/Extrabold/i;
620   $style =~ s/\bhairline\b/Extralight/i;
621   $style =~ s/\bcond\b/Condensed/i;
622   $style =~ s/(roman)?slanted/ Italic/i;
623   $style =~ s/\bslant\b/Italic/i;
624   $style =~ s/\b(SC|Small(caps(alt)?)?)\b/SmallCaps/i;
625   $style =~ s/w3 mono/Dual/i;
626   $style =~ s/Regul[ea]r/Regular/i;
627   $style =~ s/  +/ /g;
628   return($style);
629 }