%!PS
% Copyright (C) 2001-2023 Artifex Software, Inc.
% All Rights Reserved.
%
% This software is provided AS-IS with no warranty, either express or
% implied.
%
% This software is distributed under license and may not be copied,
% modified or distributed except as expressly authorized under the terms
% of the license contained in the file LICENSE in this distribution.
%
% Refer to licensing information at http://www.artifex.com or contact
% Artifex Software, Inc.,  39 Mesa Street, Suite 108A, San Francisco,
% CA 94129, USA, for further information.
%

% Create a Fontmap format file after scanning the FONTPATH directories
%
% From Ghostscript version 9.50 onwards the default operation is to run with
% SAFER defined; this disables a number of PostScript operators, specifically
% in this case the .sort operator, which is used by this program. In order
% to use this program you must run with -dNOSAFER.
%
% Example usage:
%   windows:  gswin32c -dNOSAFER -q -sFONTPATH=c:/windows/fonts genfontmap.ps > myFontmap
%
%   unix:     gs -dNOSAFER -q -sFONTPATH=/usr/local/fonts genfontmap.ps > myFontmap
%
% The myFontmap file created by the above can be renamed to Fontmap and
% placed in the LIBPATH directory.

/=error { (%stderr) (w) file exch writestring } def

% First make sure there is a FONTPATH defined
FONTPATH length 0 eq {
  (\n  Specify a FONTPATH using -sFONTPATH or GS_FONTPATH in order to\n) =error
  (  generate a Fontmap file from the fonts found in those folders.\n\n) =error
  flush quit
} if

% Since version 9.50, ensure we are running in NOSAFER so that .sort is available
/NOSAFER where {/NOSAFER get not}{true} ifelse
{
  (\n  You must use the '-dNOSAFER' option in order to execute this program.\n\n) =error
  flush quit
} if

QUIET not {
  (\n  You must use the '-q' option in order to generate a clean Fontmap.\n\n) =error
  flush quit
} if

% -------------------------------------------------------------------------

/Initial_count Fontmap length def

( ) cvn findfont pop	% force the scan

% Create an array so we can sort it

mark
Fontmap { [ 3 1 roll ] } forall
.nativeFontmap { [ 3 1 roll ] } forall
counttomark array astore exch pop

% sort the array
{ 0 get 100 string cvs exch 0 get 100 string cvs gt } .sort

% Now print it out in Fontmap format
(% This Fontmap generated by genfontmap.ps\n) =
{
  dup 0 get 		% get the name of the font
  % Since the name might be Unicode, write it as a string
  100 string cvs ==only
  (	) print 1 get 0 get ==only ( ;) =
} forall
flush

(\ngenfontmap completed OK. ) =error
Fontmap length .nativeFontmap length add Initial_count sub 10 string cvs =error
( new fonts added.\n\n) =error
quit