% \iffalse meta-comment
%
% Copyright (C) 2013 by Enrico Gregorio 
% <Enrico dot Gregorio at univr dot it>
% -------------------------------------------------------
% 
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any
% later version. The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3 or later is part of all distributions
% of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status `maintained'.
% 
% The Current Maintainer of this work is Enrico Gregorio.
%
% This work consists of the files
%   feynmp-auto.dtx 
%   feynmp-auto.ins
% and the derived file feynmp-auto.sty.
%
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{feynmp-auto.dtx}
%</driver>
%<package>\NeedsTeXFormat{LaTeX2e}[2008/04/05]
%<package>\ProvidesPackage{feynmp-auto}
%<*package>
    [2013/05/03 v1.1 Automatic processing of feynmp graphics]
%</package>
%
%<*driver>
\documentclass{ltxdoc}
\usepackage[T1]{fontenc}
\usepackage{lmodern,hologo}
\EnableCrossrefs
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{feynmp-auto.dtx}
  \PrintChanges
  \PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{129}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \changes{v1.1}{2013/05/03}{Added `force' option}
% \changes{v1.0}{2013/03/12}{Initial version}
%
% \GetFileInfo{feynmp-auto.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\!,\@empty,\@gobble,\@gobbletwo}
% \DoNotIndex{\@ifpackageloaded,\@ifpackagewith,\@ifundefined,\@namedef}
% \DoNotIndex{\@nil,\@onlypreamble,\@tempa,\@tempb,\@tempswafalse,\def}
% \DoNotIndex{\@tempswatrue,\^,\-,\active,\begingroup,\catcode,\@car,\@cdr}
% \DoNotIndex{\edef,\else,\endgroup,\endinput,\expandafter,\fi,\if}
% \DoNotIndex{\if@tempswa,\ifcase,\ifnum,\ifx,\lccode,\let,\lowercase}
% \DoNotIndex{\MessageBreak,\next,\number,\numexpr,\or,\PackageError}
% \DoNotIndex{\PackageWarning,\PackageWarningNoLine,\strip@prefix,\@@end}
% \DoNotIndex{\relax,\space,\string,\DeclareOption,\ProcessOptions}
% \DoNotIndex{\meaning,\ifdefined,\csname,\chardef,\endcsname,\protect}
% \DoNotIndex{\@outfmf,\closeout,\CurrentOption,\equaltojobname,\fmfcmd}
% \DoNotIndex{\fmf@revision,\if@fmfio,\IfFileExists,\ifmeasuring@}
% \DoNotIndex{\immediate,\jobname,\openout,\p@rcent,\PassOptionsToPackage}
% \DoNotIndex{\RequirePackage,\write,\z@,\newif}
%
% \title{The \textsf{feynmp-auto} package\thanks{This document
%   corresponds to \textsf{feynmp-auto}~\fileversion, dated \filedate.}}
% \author{Enrico Gregorio \\ \texttt{Enrico dot Gregorio at univr dot it}}
%
% \maketitle
%
% \section{The package}
%
% This package is just a wrapper around \textsf{feynmp}; it receives
% exactly the same options as that package and works in exactly the
% same way, so refer to its documentation for the specific commands
% and environments. There is just one option specific to
% \textsf{feynmp-auto}: with
% \begin{flushleft}
% \verb|\usepackage[force]{feynmp-auto}|
% \end{flushleft}
% the checks whether the \hologo{METAPOST} files are not changed from
% the previous \hologo{LaTeX} run get disabled. This option might come
% handy when one is switching from \textsf{feynmp} to
% \textsf{feynmp-auto} or, possibly, for the very final runs where one
% wants to be \emph{really} sure that everything is updated.
%
% What the present package adds is the automatic call of 
% \hologo{METAPOST} at \verb|\end{fmffile}|, taking advantage of the
% fact that, starting from \hologo{TeX}~Live 2012, \hologo{METAPOST}
% has been added to the external programs that are available in the
% \emph{restricted shell escape}, that is, programs that are
% considered safe and so callable from inside every run of
% \hologo{LaTeX} (with all available engines).
%
% However the call of \hologo{METAPOST} can be made only when the
% output file containing the \hologo{METAPOST} code is closed, so
% two runs of \hologo{LaTeX} are necessary anyway in order to include
% the graphics. The benefit of using this package is that it's not
% necessary to go to the shell or to open the output file for
% compiling it.
%
% With \hologo{pdfLaTeX} or \hologo{LuaLaTeX} the \hologo{METAPOST}
% run will not be performed if the file hasn't changed from the
% previous run thanks to the \verb|\pdfmdfivesum| feature available
% with \hologo{pdfTeX} and emulated for \hologo{LuaTeX} via Heiko
% Oberdiek's \textsf{pdftexcmds} package. This feature is not
% available with \hologo{XeTeX}, so when using \hologo{XeLaTeX} the
% call of \hologo{METAPOST} will be performed at each run.
%
% Finally, we add also the \verb|\DeclareGraphicsRule| commands that
% are needed for loading the MPS files.
%
% \subsection*{Notes}
%
% Some \hologo{TeX} distributions, notably \hologo{MiKTeX}, may not
% have enabled \hologo{METAPOST} in the restricted shell, so this
% package will do no good in this case, but it doesn't harm either.
% This fact is easily discoverable, because \hologo{LaTeX} won't be
% able to find the compiled MPS files.
%
% Also any \hologo{TeX}~Live distribution earlier than the 2012
% release won't have \hologo{METAPOST} enabled in the restricted shell
% escape, so the package won't work.
%
% In both the above cases, adding the \texttt{-shell-escape} option to
% the call of the \hologo{LaTeX} run is sufficient (but beware for
% security risks and run with the option only files from safe
% sources). The \texttt{-shell-escape} used to be called
% \texttt{-enable-write18} in older versions of \hologo{MiKTeX}, but
% newer versions (the 2.9 in particular) understand both.
%
% The package will emit a warning if shell escape is not enabled,
% which may happen if the call of the engine has the option
% \texttt{-no-shell-escape} (possibly via the front-end settings).
%
% \StopEventually{}
%
% \section{Implementation}
%
% The usual presentation, that we repeat here for completeness.
%\begin{verbatim}
%\ProvidesFile{feynmp-auto.dtx}
%\NeedsTeXFormat{LaTeX2e}[2008/04/05]
%\ProvidesPackage{feynmp-auto}
%  [2013/03/12 v1.0 Automatic processing of feynmp graphics]
%\end{verbatim}
% Now the real macros. First of all we check that the typesetting
% engine is sufficiently recent to include \hologo{eTeX}
% extensions.
%    \begin{macrocode}
\@ifundefined{eTeXversion}
  {\PackageError{feynmp-auto}{LaTeX engine too old, aborting}
   {Please upgrade your TeX system}\@@end}{}
%    \end{macrocode}
%
% \subsection{Options}
% All options are passed to \textsf{feynmp}
%    \begin{macrocode}
\newif\iffnmpa@force
\DeclareOption{force}{\fnmpa@forcetrue}
\DeclareOption*{\PassOptionsToPackage{\CurrentOption}{feynmp}}
\ProcessOptions\relax
%    \end{macrocode}
%
% \subsection{Required packages and preliminary code}
%    \begin{macrocode}
\RequirePackage{feynmp}
\RequirePackage{ifpdf,ifxetex}
\RequirePackage{pdftexcmds}
\ifnum\pdf@shellescape=\z@
  \PackageWarningNoLine{feynmp-auto}
    {The automatic feature can't be used\MessageBreak
     because `shell escape' is disabled}
\fi
\ifpdf
  \DeclareGraphicsRule{*}{mps}{*}{}
\fi
\ifxetex
  \DeclareGraphicsRule{*}{eps}{*}{}
\fi
%    \end{macrocode}
%
% \subsection{Avoiding useless runs}
% With the \verb|pdfmdfivesum| feature, we can spare useless runs of
% \hologo{METAPOST}. Its presence is controlled by checking if
% \verb|\pdf@filemdfivesum| has been defined by \textsf{pdftexcmds}.
%    \begin{macrocode}
\ifdefined\pdf@filemdfivesum
%    \end{macrocode}
% In this case we define a default value for \verb|fnmpa@mdfivesum|
% and three macros for doing comparison. If the \hologo{METAPOST} file
% doesn't exist in the first place, we'll simply run \hologo{METAPOST}
% when \verb|\end{fmffile}| is scanned. Otherwise we store in
% \verb|fnmpa@mdfivesum| the \mbox{MD-5} hash of the file for later
% comparison.
%    \begin{macrocode}
  \def\fnmpa@mdfivesum{0}
  \def\fnmpa@gethash{%
    \IfFileExists{\thefmffile.mp}
      {\edef\fnmpa@mdfivesum{\pdf@filemdfivesum{\thefmffile.mp}}}
      {}%
  }
  \def\fnmpa@processmp{%
    \IfFileExists{\thefmffile.mp}
      {\fnmpa@compare}
      {}%
  }
  \def\fnmpa@compare{%
    \ifnum\pdf@strcmp{\fnmpa@mdfivesum}{\pdf@filemdfivesum{\thefmffile.mp}}=\z@
      % do nothing, the files is unmodified
    \else
      \immediate\write18{mpost \thefmffile}%
    \fi
  }
%    \end{macrocode}
% If the \mbox{MD-5} feature is not available (that is, with
% \hologo{XeLaTeX}), we don't set up any check.
%    \begin{macrocode}
\else
  \let\fnmpa@gethash\relax
  \def\fnmpa@processmp{%
    \IfFileExists{\thefmffile.mp}{\immediate\write18{mpost \thefmffile}}{}%
  }
\fi
%    \end{macrocode}
% If the \texttt{force} option has been given, then we override in the
% same way the macros. A bit of code duplication, but this avoids
% complicated conditional nestings.
%    \begin{macrocode}
\iffnmpa@force
  \let\fnmpa@gethash\relax
  \def\fnmpa@processmp{%
    \IfFileExists{\thefmffile.mp}{\immediate\write18{mpost \thefmffile}}{}%
  }
\fi
%    \end{macrocode}
%
% \subsection*{Patching the macros of \textsf{feynmp}}
% We finally need to inject the code in the macros responsible for the
% \texttt{fmffile} environment. In \verb|\fmffile| we add the checks
% for the \mbox{MD-5} sums:
%    \begin{macrocode}
\def\fmffile#1{%
  \def\thefmffile{#1}%
  \equaltojobname{\thefmffile}{%
    \PackageError{feynmp}
      {The argument of \fmffile MUST NOT be identical\MessageBreak
       to the name of your main input file!  I will use fmfdefault.mf\MessageBreak
       this time around, but you'd better fix your code now!}%
      {Invalid argument to \string\fmffile!}%
    \def\thefmffile{fmfdefault}}{}%
  \if@fmfio
    \fnmpa@gethash % Added
    \@ifundefined{ifmeasuring@}%
      {}%
      {\def\if@fmfio{\ifmeasuring@\else}}%
    \immediate\openout\@outfmf=\thefmffile.mp\relax
    \fmfcmd{\p@rcent\space \thefmffile.mp -- do not edit, %
            generated automatically by \jobname.tex^^J%
            input feynmp^^J%
            require_RCS_revision "\fmf@revision";}%
  \fi
  \setcounter{fmfgraph}{0}}
%    \end{macrocode}
% In \verb|\endfmffile| we add the processing of the \hologo{METAPOST}
% file:
%    \begin{macrocode}
\def\endfmffile{%
  \fmfcmd{\p@rcent\space the end.^^J%
          end.^^J%
          endinput;}%
  \if@fmfio
    \immediate\closeout\@outfmf
  \fi
  \fnmpa@processmp % Added
  \let\thefmffile\relax
}
%    \end{macrocode}
% \Finale
\endinput