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