"Fossies" - the Fresh Open Source Software Archive

Member "ansifilter-2.18/src/codegenerator.h" (30 Jan 2021, 14747 Bytes) of package /linux/privat/ansifilter-2.18.tar.bz2:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "codegenerator.h" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.17_vs_2.18.

    1 /***************************************************************************
    2                           codegenerator.h  -  description
    3                              -------------------
    4     copyright            : (C) 2007-2021 by Andre Simon
    5     email                : a.simon@mailbox.org
    6  ***************************************************************************/
    7 
    8 /*
    9 This file is part of ANSIFilter.
   10 
   11 ANSIFilter is free software: you can redistribute it and/or modify
   12 it under the terms of the GNU General Public License as published by
   13 the Free Software Foundation, either version 3 of the License, or
   14 (at your option) any later version.
   15 
   16 ANSIFilter is distributed in the hope that it will be useful,
   17 but WITHOUT ANY WARRANTY; without even the implied warranty of
   18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   19 GNU General Public License for more details.
   20 
   21 You should have received a copy of the GNU General Public License
   22 along with ANSIFilter.  If not, see <http://www.gnu.org/licenses/>.
   23 */
   24 
   25 #ifndef CODEPARSER_H
   26 #define CODEPARSER_H
   27 
   28 #include <iostream>
   29 #include <sstream>
   30 #include <string>
   31 #include <vector>
   32 #include <iomanip>
   33 
   34 // Avoid problems with isspace and UTF-8 characters, use iswspace instead
   35 //#include <cctype>
   36 #include <wctype.h>
   37 
   38 #include "elementstyle.h"
   39 
   40 #include "enums.h"
   41 #include "stringtools.h"
   42 
   43 /// The ansifilter namespace contains all classes and data structures needed for parsing input data.
   44 
   45 namespace ansifilter
   46 {
   47 
   48   /** TheDraw output information of individual characters*/
   49   struct TDChar {
   50     unsigned char c;
   51     ElementStyle style;
   52   };
   53 
   54 
   55   class StyleInfo
   56 {
   57 public:
   58 
   59     /// Constructor
   60     StyleInfo() :  fgColor ( "" ), bgColor ( "" ),  isBold (false),isItalic (false),isConcealed (false), isBlink (false), isUnderLine (false)
   61     {
   62     }
   63 
   64     /// Constructor
   65     StyleInfo (  const string& fgc, const string& bgc, bool b, bool i, bool c, bool blink, bool ul ) :
   66         fgColor ( fgc ), bgColor ( bgc ),isBold ( b ), isItalic ( i ), isConcealed ( c ), isBlink (blink), isUnderLine (ul)
   67     {
   68     }
   69 
   70     /// Copy Constructor
   71     StyleInfo ( const StyleInfo& other )
   72     {
   73         fgColor = other.fgColor;
   74         bgColor = other.bgColor;
   75 
   76         isItalic = other.isItalic;
   77         isBold = other.isBold;
   78         isConcealed=other.isConcealed;
   79         isBlink = other.isBlink;
   80         isUnderLine = other.isUnderLine;
   81     }
   82 
   83     /// Operator overloading
   84     StyleInfo& operator= ( const StyleInfo & other )
   85     {
   86         fgColor = other.fgColor;
   87         bgColor = other.bgColor;
   88 
   89         isItalic = other.isItalic;
   90         isBold = other.isBold;
   91         isConcealed=other.isConcealed;
   92         isBlink = other.isBlink;
   93         isUnderLine = other.isUnderLine;
   94 
   95         return *this;
   96     }
   97 
   98     bool operator==(const StyleInfo& r)
   99     {
  100         return this->fgColor==r.fgColor && this->bgColor==r.bgColor && this->isBold==r.isBold
  101                 && this->isItalic==r.isItalic && this->isConcealed==r.isConcealed
  102                 && this->isBlink==r.isBlink && this->isUnderLine==r.isUnderLine;
  103     }
  104 
  105     ~StyleInfo()
  106     {
  107     }
  108 
  109     string fgColor;    ///< foreground color
  110     string bgColor;    ///< background color
  111     bool isBold, isItalic, isConcealed, isBlink, isUnderLine;  ///< style properties
  112    };
  113 
  114 /** \brief Base class for escape sequence parsing.
  115 
  116     The virtual class provides escape sequence parsing functionality.<br>
  117     The derived classes have to define the output format.<br>
  118     Codegenerator is a singleton class.
  119 
  120 * @author Andre Simon
  121 */
  122 
  123 class CodeGenerator
  124 {
  125 
  126 public:
  127 
  128     virtual ~CodeGenerator();
  129 
  130     /**
  131       Get appropriate Codegenerator instance
  132       \param type Output file type (TEXT, PANGO, HTML, RTF, LATEX, TEX)
  133     */
  134     static CodeGenerator* getInstance(OutputType type);
  135 
  136     /**
  137       Delete Codegenerator instance (this is intended for SWIG integration,
  138       in normal C++ code the result should be saved in an auto_ptr)
  139       \param CodeGenerator* CodeGenerator instance
  140     */
  141     static void deleteInstance(CodeGenerator* inst)
  142     {
  143         if (inst) delete inst;
  144     }
  145 
  146     /**
  147      Generates output file
  148      \param inFileName Path of input file (if empty use stdin)
  149      \param outFileName Path of output file (if empty use stdout)
  150      \return ParseError
  151     */
  152     ParseError generateFile(const string &inFileName, const string &outFileName);
  153 
  154     /**
  155      Generates output string from input string
  156      \param input input code string
  157      \return formatted output code
  158     */
  159     string generateString(const string &input);
  160 
  161     /**
  162      Generates output string from input file
  163      \param inFileName file path
  164      \return formatted output code
  165     */
  166     string generateStringFromFile(const string &inFileName);
  167 
  168     /**
  169      Generates output file from input string
  170      \param sourceStr input string
  171      \param outFileName output file path
  172      \param title document title
  173      \return formatted output code
  174     */
  175     ParseError generateFileFromString (const string &sourceStr,
  176                                        const string &outFileName,
  177                                        const string &title);
  178 
  179     /** Generate a stylesheet with the styles found in the document
  180     \param outPath Output path
  181     \return true if successful
  182      */
  183     virtual bool printDynamicStyleFile ( const string &outPath );
  184 
  185     /**
  186      Overrides default colours by user defined values; resets palette to default if mapPath is empty
  187      \param mapPath path of map file
  188      \return true if parsing was successful
  189     */
  190     bool setColorMap(const string& mapPath);
  191 
  192     /** tell parser to omit document header and footer
  193        \param  flag true if output should be fragmented
  194     */
  195     void setFragmentCode(bool flag);
  196 
  197     /** \return fragment flag */
  198     bool getFragmentCode();
  199 
  200     /** tell parser to use this font as base font
  201     \param s the font name, e.g. "Courier New"
  202      */
  203     void setFont(const string& s);
  204 
  205     /** \return base font */
  206     const string getFont() const ;
  207 
  208     /** tell parser to use this size as base font size
  209     \param s the font size, e.g. "12"
  210      */
  211     void setFontSize(const string& s);
  212 
  213     /** \return base font size*/
  214     const string getFontSize();
  215 
  216     /** Set encloding
  217       \param encodingName encoding name
  218     */
  219     void setEncoding(const string& encodingName);
  220 
  221     /** \param title Document title */
  222     void setTitle(const string & title);
  223 
  224     /** \return Document title */
  225     string getTitle();
  226 
  227     /** \param path style sheet path*/
  228     void setStyleSheet(const string & path);
  229 
  230     /** \param b set to true if text formatting should be stripped */
  231     void setPlainOutput(bool b)
  232     {
  233         ignoreFormatting=b;
  234     }
  235 
  236     /** \param b set to true if HTML anchors should be added to line numbers */
  237     void setAddAnchors(bool b, bool self=false)
  238     {
  239         addAnchors=b;
  240         addFunnyAnchors=self;
  241     }
  242 
  243     /** \param b set to true if the input stream is not closed after reaching EOF */
  244     void setContinueReading(bool b)
  245     {
  246         readAfterEOF=b;
  247     }
  248 
  249      /** \param b set to true if the output should not be terminated with EOL*/
  250     void setOmitTrailingCR(bool b)
  251     {
  252         omitTrailingCR=b;
  253     }
  254 
  255     /** \param b set to true if the output should not contain a version info comment*/
  256     void setOmitVersionInfo(bool b)
  257     {
  258         omitVersionInfo=b;
  259     }
  260 
  261     /** \return plain outputting flag */
  262     bool getPlainOutput()
  263     {
  264         return ignoreFormatting;
  265     }
  266 
  267     /** \return continue reading from input stream flag */
  268     bool getContinueReading()
  269     {
  270         return readAfterEOF;
  271     }
  272 
  273     /** \param lineWrappingStyle wrapping style
  274         \param lineLength maximum length  per wrapped text line */
  275     void setPreformatting ( WrapMode lineWrappingStyle,unsigned int lineLength);
  276 
  277     /** \param b set to true if line numbers should be added */
  278     void setShowLineNumbers(bool flag);
  279 
  280     /** \param b set to true if line numbers of wrapped lines should be omitted */
  281     void setWrapNoNumbers(bool flag);
  282 
  283     /** \param b set to true if input is ASCII art codepage 437 file  */
  284     void setParseCodePage437(bool flag);
  285 
  286     /** \param b set to true if input is an ASCII art BIN file*/
  287     void setParseAsciiBin(bool flag);
  288 
  289     /** \param b set to true if input is an Tundra art BIN file*/
  290     void setParseAsciiTundra(bool flag);
  291 
  292     /** \param b set to true if K clear sequences should be ignored*/
  293     void setIgnoreClearSeq(bool flag);
  294 
  295     /** \param b set to true if CSI sequences should be ignored*/
  296     void setIgnoreCSISeq(bool flag);
  297 
  298     /** \param b set dimensions of ASCII art virtual console */
  299     void setAsciiArtSize(int width, int height);
  300 
  301     /** tell parser to use dynamic stylesheets derived from the document's formatting
  302        \param  flag true
  303     */
  304     void setApplyDynStyles(bool flag);
  305 
  306     /** Set SVG dimensions
  307         \param w page width
  308         \param h page height
  309     */
  310     void setSVGSize ( const string& w, const string& h );
  311 
  312 protected:
  313 
  314     /** \param type Output type */
  315     CodeGenerator(ansifilter::OutputType type);
  316 
  317     CodeGenerator() {}
  318 
  319     /** \param c Character to be masked
  320         \return Escape sequence of output format */
  321     virtual string maskCharacter(unsigned char c) = 0;
  322 
  323     /** \param c Character to be masked
  324      \return Codepage 437 escape sequence of output format */
  325     virtual string maskCP437Character(unsigned char c) { return maskCharacter(c); }
  326 
  327     /** \param uri URI
  328      *  \param txt Description
  329      \return returns link formatting sequence */
  330     virtual string getHyperlink(string uri, string txt) { return txt+"["+uri+"]"; }
  331 
  332     /** Tag for inserting line feeds*/
  333     string newLineTag;
  334 
  335     /** SVG document dimensions */
  336     string width, height;
  337 
  338     /** file input*/
  339     istream *in;
  340 
  341     /** file output*/
  342     ostream *out;
  343 
  344     /** line buffer*/
  345     ostringstream lineBuf;
  346 
  347     bool tagIsOpen; ///< a reminder to close an open tag
  348 
  349     string styleCommentOpen,  ///< open comment delimiter
  350            styleCommentClose; ///< close comment delimiter
  351 
  352     /** Encoding name */
  353     string encoding;
  354 
  355     /** Encoding name */
  356     string docTitle;
  357 
  358     string spacer;
  359 
  360     /** Test if header and footer should be omitted */
  361     bool fragmentOutput;
  362 
  363     /** The base font to use */
  364     string font ;
  365 
  366     /** The base font size to use */
  367     string fontSize ;
  368 
  369     /** Style sheet path */
  370     string styleSheetPath;
  371 
  372     /** Width of line numbers */
  373     unsigned int lineNumberWidth;
  374 
  375     /** Current line number */
  376     unsigned int lineNumber;
  377     bool showLineNumbers,     ///< show line numbers
  378          numberWrappedLines,  ///< also show number of wrapped lines
  379          numberCurrentLine,   ///< output number of current line
  380          addAnchors,          ///< add HTML anchor to line number
  381          addFunnyAnchors,     ///< add HTML links to themselves
  382          applyDynStyles;      ///< insert dynamic style references instead of inline styles
  383 
  384     bool omitVersionInfo;     ///< do not print version info comment
  385     bool parseCP437;          ///< treat input as CP437 file
  386     bool parseAsciiBin;       ///< treat input as BIN or XBIN file
  387     bool parseAsciiTundra;    ///< treat input as Tundra file
  388 
  389     /** Processes input data */
  390     void processInput();
  391 
  392     virtual void insertLineNumber ();
  393 
  394     /** \return true id encoding is defined */
  395     bool encodingDefined()
  396     {
  397         return StringTools::lowerCase(encoding)!="none";
  398     }
  399 
  400     /** convert a rgb triple to HTML color notation
  401     @param rgb RGB input values
  402     @return HTML color string
  403     */
  404     string rgb2html(unsigned char* rgb);
  405 
  406     string rgb2html(int r, int g, int b);
  407 
  408     /// 16 basic colors
  409     static unsigned char workingPalette[16][3];
  410     static unsigned char defaultPalette[16][3];
  411 
  412     ElementStyle elementStyle;
  413 
  414     vector<StyleInfo> documentStyles;
  415 
  416 private:
  417 
  418     CodeGenerator(const CodeGenerator&) {}
  419 
  420     CodeGenerator& operator=(CodeGenerator&)
  421     {
  422         return *this;
  423     }
  424 
  425     /** parses string to extract ANSI sequence information
  426         @param line text line
  427         @param begin starting position within line
  428         @param end ending position within line
  429         @return true if sequence was recognized */
  430     bool parseSGRParameters(const string& line, size_t begin, size_t end);
  431 
  432     /** parses Codepage 437 sequence information
  433         @param line text line
  434         @param begin starting position within line
  435         @param end ending position within line
  436         */
  437     void parseCodePage437Seq(string line, size_t begin, size_t end);
  438 
  439     /** Prints document footer
  440         @return footer */
  441     virtual string getFooter() = 0;
  442 
  443     /** Prints document body*/
  444     virtual void printBody() = 0;
  445 
  446     /** Prints document header
  447         @return header
  448     */
  449     virtual string getHeader() = 0;
  450 
  451     /** Resets parser to origin state, call this after every file conversion */
  452     void reset();
  453 
  454     /** Output format type*/
  455     OutputType outputType;
  456 
  457     virtual string getOpenTag() = 0;  ///< returns opening formatting sequence
  458     virtual string getCloseTag() = 0; ///< returns closing formatting sequence
  459 
  460     bool ignoreFormatting; ///< ignore color and font face information
  461     bool readAfterEOF;     ///< continue reading after EOF occoured
  462     bool omitTrailingCR;   ///< do not print EOL at the end of output
  463     bool ignClearSeq;      ///< ignore clear sequence ESC K
  464     bool ignCSISeq;       ///< ignore CSIs (may interfere with UTF-8 input)
  465 
  466     TDChar* termBuffer;
  467     int curX, curY, memX, memY, maxY; ///< cursor position for Codepage 437 sequences
  468     int asciiArtWidth;        ///< virtual console column count
  469     int asciiArtHeight;       ///< virtual console line count
  470     unsigned int lineWrapLen; ///< max line length before wrapping
  471 
  472     ElementStyle memStyle;
  473 
  474     /** clear line buffer
  475     */
  476     void printNewLine(bool eof=false);
  477 
  478     /** convert an xterm color value (0-253) to 3 unsigned chars rgb
  479         @param color xterm color
  480         @param rgb RGB output values */
  481     void xterm2rgb(unsigned char color, unsigned char* rgb);
  482 
  483     /**Print content of virtual terminal buffer. Deletes buffer. */
  484     void printTermBuffer();
  485 
  486     /**Parses BIN ASCII art file */
  487     void parseBinFile();
  488 
  489     /**Parses XBIN ASCII art file */
  490     void parseXBinFile();
  491 
  492     /**Parses Tundra ASCII art file */
  493     void parseTundraFile();
  494 
  495     /**allocate virtual terminal buffer */
  496     void allocateTermBuffer();
  497 
  498     /** @return true if stream begins with XBIN id  */
  499     bool streamIsXBIN();
  500 
  501      /** @return true if stream begins with Tundra id  */
  502     bool streamIsTundra();
  503 
  504     /// the 6 value iterations in the xterm color cube
  505     static const unsigned char valuerange[] ;
  506 };
  507 
  508 }
  509 
  510 #endif