RTF阅读器编写

来源:互联网 发布:淘宝店被关了怎么处理 编辑:程序博客网 时间:2024/05/20 10:52
 
如何写一个RTF阅读器
There are three basic things that an RTF reader must do:
1.      Separate text from RTF controls.
2.      Parse an RTF control.
3.      Dispatch an RTF control.
Separating text from RTF controls is relatively simple, because all RTF controls begin with a backslash. Therefore, any incoming character that is not a backslash is text and will be handled as text.
Parsing an RTF control is also relatively simple. An RTF control is either (a) a sequence of alphabetic characters followed by an optional numeric parameter, or (b) a single non-alphanumeric character.
Dispatching an RTF control, on the other hand, is relatively complicated. A recursive-descent parser tends to be overly strict because RTF is intentionally vague about the order of various properties relative to one another. However, whatever method you use to dispatch an RTF control, your RTF reader should do the following:
·      Ignore control words you don’t understand
Many RTF readers crash when they come across an unknown RTF control. Because Microsoft is continually adding new RTF controls, this limits an RTF reader to working with the RTF from one particular product (usually some version of Word for Windows).
·      Always understand /*
One of the most important things an RTF reader can do is to understand the /* control. This control introduces a destination that is not part of the document. It tells the RTF reader that if the reader does not understand the next control word, then it should skip the entire enclosing group.
·      Remember that binary data can occur when you’re skipping RTF
A simple way to skip a group in RTF is to keep a running count of the opening braces that the RTF reader has encountered in the RTF stream. When the RTF reader sees an opening brace, it increments the count. When the reader sees a closing brace, it decrements the count.When the count becomes negative, the end of the group has been found. Unfortunately, this doesn’t work when the RTF file contains a /bin control; the reader must explicitly check each control word found to see if it is a /bin control, and, if a /bin control is found, skip that many bytes before resuming its scanning for braces.
一个RTF阅读器工具的例子
The Microsoft Word Processing Conversions group uses a table-driven approach to reading RTF. This approach allows the most flexibility in reading RTF but makes it difficult to detect incorrect RTF. An RTF reader that is based on this approach is presented in this section. This reader works exactly as described in the RTF specification and uses the principles of operation described in the RTF specification as well. This reader is designed to be simple to understand but is not intended to be very efficient. This RTF reader also implements the three design principles listed in the previous section.
The RTF reader consists of the following four files:
·      Rtfdecl.h, which contains the prototypes for all the functions in the RTF reader
·      Rtftype.h, which contains the types used in the RTF reader
·      Rtfreadr.c, which contains the main program, the main loop of the RTF reader, and the RTF control parser
·      Rtfactn.c, which contains the dispatch routines for the RTF reader
Rtfdecl.h
Rtfdecl.h is straightforward and requires little explanation.
Rtfreadr.c
Like rtfdecl.h, rtfreadr.c is also reasonably straightforward. The function ecRtfParse separates text from RTF controls and handles text, and the function ecParseRtfKeyword parses an RTF control and also collects any parameter that follows the RTF control.
Rtftype.h
Rtftype.h begins by declaring a sample set of character, paragraph, section, and document properties. These structures are present to demonstrate how the dispatch routines can modify any particular property and are not actually used to format text.
For example, the following enumeration describes which destination text should be routed to:
typedef enum { rdsNorm, rdsSkip } RDS;
Because this is just a sample RTF reader, there are only two destinations. A more complicated reader would add an entry to this enumeration for each destination supported [for example, headers, footnotes, endnotes, comments (annotations), bookmarks, and pictures].
The following enumeration describes the internal state of the RTF parser:
typedef enum { risNorm, risBin, risHex } RIS;
This is entirely separate from the state of the dispatch routines and the destination state; other RTF readers may not necessarily have anything similar to this.
The following structure encapsulates the state that must be saved at a group start and restored at a group end:
typedef struct save
{
struct save *pNext;
CHP chp;
PAP pap;
SEP sep;
DOP dop;
RDS rds;
RIS ris;
} SAVE;
The following enumeration describes a set of classes for RTF controls:
typedef enum {kwdChar, kwdDest, kwdProp, kwdSpec} KWD;
Use kwdChar for controls that represent special characters (such as /-, /{, or /}).
Use kwdDest for controls that introduce RTF destinations.
Use kwdProp for controls that modify some sort of property.
Use kwdSpec for controls that need to run some specialized code.
The following enumeration defines the number of PROP structures (described later) that will be used. There will typically be an iprop for every field in the character, paragraph, section, and document properties.
typedef enum {ipropBold, ipropItalic, ipropUnderline, ipropLeftInd,
ipropRightInd, ipropFirstInd, ipropCols, ipropPgnX, ipropPgnY,
ipropXaPage, ipropYaPage, ipropXaLeft, ipropXaRight,
ipropYaTop, ipropYaBottom, ipropPgnStart, ipropSbk,
ipropPgnFormat, ipropFacingp, ipropLandscape, ipropJust,
ipropPard, ipropPlain,
ipropMax} IPROP;
The following structure is a very compact way to describe how to locate the address of a particular value in one of the property structures:
typedef enum {actnSpec, actnByte, actnWord} ACTN;
typedef enum {propChp, propPap, propSep, propDop} PROPTYPE;
 
typedef struct propmod
{
ACTN actn;
PROPTYPE prop;
int offset;
} PROP;
The actn field describes the width of the value being described: if the value is a byte, then actn is actnByte; if the value is a word, then actn is actnWord; if the value is neither a byte nor a word, then you can use actnSpec to indicate that some C code needs to be run to set the value. The prop field indicates which property structure is being described; propChp indicates that the value is located within the CHP structure; propPap indicates that the value is located within the PAP structure, and so on. Finally, the offset field contains the offset of the value from the start of the structure. The offsetof() macro is usually used to initialize this field.
The following structure describes how to parse a particular RTF control:
typedef enum {ipfnBin, ipfnHex, ipfnSkipDest } IPFN;
typedef enum {idestPict, idestSkip } IDEST;
 
typedef struct symbol
{
char *szKeyword;
int dflt;
bool fPassDflt;
KWD kwd;
int idx;
} SYM;
szKeyword points to the RTF control being described; kwddescribes the class of the particular RTF control (described earlier); dflt is the default value for this control, and fPassDflt should be nonzero if the value in dflt should be passed to the dispatch routine.
Note fPassDflt is only nonzero for control words that normally set a particular value.For example, the various section break controls typically have nonzero fPassDflt controls, but controls that take parameters should not.
Idx is a generalized index; its use depends on the kwd being used for this control.
·      If kwd is kwdChar, then idx is the character that should be output.
·      If kwd is kwdDest, then idx is the idest for the new destination.
·      If kwd is kwdProp, then idx is the iprop for the appropriate property.
·      If kwd is kwdSpec, then idx is an ipfn for the appropriate function.
With this structure it is very simple to dispatch an RTF control word. Once the reader isolates the RTF control word and its (possibly associated) value, the reader then searches an array of SYM structures to find the RTF control word. If the control word is not found, the RTF reader ignores it, unless the previous control was /*, in which case the reader must scan past an entire group.
If the control word is found, the reader then uses the kwd value from the SYM structure to determine what to do. This is, in fact, exactly what the function ecTranslateKeyword in the file RTFACTN.C does.
Rtfactn.c
Rtfactn.c contains the tables describing the properties and control words, and the routines to evaluate properties (ecApplyPropChange) and to dispatch control words (ecTranslateKeyword).
The tables are the keys to understanding the RTF dispatch routines. The following are some sample entries from both tables, along with a brief explanation of each entry.
Property Table
This table must have an entry for every iprop.
actnByte,   propChp,    offsetof(CHP, fBold),       // ipropBold
This property says that the ipropBold property is a byte parameter bound to chp.fBold.
actnWord,   propPap,    offsetof(PAP, xaRight),     // ipropRightInd
This property says that ipropRightInd is a word parameter bound to pap.xaRight.
actnWord,   propSep,    offsetof(SEP, cCols),       // ipropCols
This property says that ipropCols is a word parameter bound to sep.cCols.
actnSpec,   propChp,    0,                          // ipropPlain
This property says that ipropPlain is a special parameter. Instead of directly evaluating it, ecApplyPropChange will run some custom C code to apply a property change.
Control Word Table
"b",        1,      fFalse,     kwdProp,    ipropBold,
This structure says that the control /b sets the ipropBold property. Because fPassDflt is False, the RTF reader only uses the default value if the control does not have a parameter. If no parameter is provided, the RTF reader uses a value of 1.
"sbknone", sbkNon, fTrue,      kwdProp,    ipropSbk,
This entry says that the control /sbknone sets the ipropSbk property. Because fPassDflt is True, the RTF reader always uses the default value of sbkNon, even if the control has a parameter.
"par",      0,      fFalse,     kwdChar,    0x0a,
This entry says that the control /par is equivalent to a 0x0a (linefeed) character.
"tab",      0,      fFalse,     kwdChar,    0x09,
This entry says that the control /tab is equivalent to a 0x09 (tab) character.
"bin",      0,      fFalse,     kwdSpec,    ipfnBin,
This entry says that the control /bin should run some C code. The particular piece of C code can be located by the ipfnBin parameter.
"fonttbl", 0,      fFalse,     kwdDest,    idestSkip,
This entry says that the control /fonttbl should change to the destination idestSkip.
Rtfdecl.h
// RTF parser declarations

int ecRtfParse(FILE *fp);
int ecPushRtfState(void);
int ecPopRtfState(void);
int ecParseRtfKeyword(FILE *fp);
int ecParseChar(int c);
int ecTranslateKeyword(char *szKeyword, int param, bool fParam);
int ecPrintChar(int ch);
int ecEndGroupAction(RDS rds);
int ecApplyPropChange(IPROP iprop, int val);
int ecChangeDest(IDEST idest);
int ecParseSpecialKeyword(IPFN ipfn);
int ecParseSpecialProperty(IPROP iprop, int val);
int ecParseHexByte(void);

// RTF variable declarations

extern int cGroup;
extern RDS rds;
extern RIS ris;

extern CHP chp;
extern PAP pap;
extern SEP sep;
extern DOP dop;

extern SAVE *psave;
extern long cbBin;
extern long lParam;
extern bool fSkipDestIfUnk;
extern FILE *fpIn;

// RTF parser error codes

#define ecOK 0                      // Everything's fine!
#define ecStackUnderflow    1       // Unmatched '}'
#define ecStackOverflow     2       // Too many '{' -- memory exhausted
#define ecUnmatchedBrace    3       // RTF ended during an open group.
#define ecInvalidHex        4       // invalid hex character found in data
#define ecBadTable          5       // RTF table (sym or prop) invalid
#define ecAssertion         6       // Assertion failure
#define ecEndOfFile         7       // End of file reached while reading RTF
Rtftype.h
typedef 
char bool;
#define fTrue 1
#define fFalse 0

typedef 
struct char_prop
{
    
char fBold;
    
char fUnderline;
    
char fItalic;
}
 CHP;                  // CHaracter Properties

typedef 
enum {justL, justR, justC, justF } JUST;
typedef 
struct para_prop
{
    
int xaLeft;                 // left indent in twips
    int xaRight;                // right indent in twips
    int xaFirst;                // first line indent in twips
    JUST just;                  // justification
}
 PAP;                  // PAragraph Properties

typedef 
enum {sbkNon, sbkCol, sbkEvn, sbkOdd, sbkPg} SBK;
typedef 
enum {pgDec, pgURom, pgLRom, pgULtr, pgLLtr} PGN;
typedef 
struct sect_prop
{
    
int cCols;                  // number of columns
    SBK sbk;                    // section break type
    int xaPgn;                  // x position of page number in twips
    int yaPgn;                  // y position of page number in twips
    PGN pgnFormat;              // how the page number is formatted
}
 SEP;                  // SEction Properties

typedef 
struct doc_prop
{
    
int xaPage;                 // page width in twips
    int yaPage;                 // page height in twips
    int xaLeft;                 // left margin in twips
    int yaTop;                  // top margin in twips
    int xaRight;                // right margin in twips
    int yaBottom;               // bottom margin in twips
    int pgnStart;               // starting page number in twips
    char fFacingp;              // facing pages enabled?
    char fLandscape;            // landscape or portrait?
}
 DOP;                  // DOcument Properties

typedef 
enum { rdsNorm, rdsSkip } RDS;              // Rtf Destination State
typedef enum { risNorm, risBin, risHex } RIS;       // Rtf Internal State

typedef 
struct save             // property save structure
{
    
struct save *pNext;         // next save
    CHP chp;
    PAP pap;
    SEP sep;
    DOP dop;
    RDS rds;
    RIS ris;
}
 SAVE;

// What types of properties are there?
typedef enum {ipropBold, ipropItalic, ipropUnderline, ipropLeftInd,
              ipropRightInd, ipropFirstInd, ipropCols, ipropPgnX,
              ipropPgnY, ipropXaPage, ipropYaPage, ipropXaLeft,
              ipropXaRight, ipropYaTop, ipropYaBottom, ipropPgnStart,
              ipropSbk, ipropPgnFormat, ipropFacingp, ipropLandscape,
              ipropJust, ipropPard, ipropPlain, ipropSectd,
              ipropMax }
 IPROP;

typedef 
enum {actnSpec, actnByte, actnWord} ACTN;
typedef 
enum {propChp, propPap, propSep, propDop} PROPTYPE;

typedef 
struct propmod
{
    ACTN actn;              
// size of value
    PROPTYPE prop;          // structure containing value
    int  offset;            // offset of value from base of structure
}
 PROP;

typedef 
enum {ipfnBin, ipfnHex, ipfnSkipDest } IPFN;
typedef 
enum {idestPict, idestSkip } IDEST;
typedef 
enum {kwdChar, kwdDest, kwdProp, kwdSpec} KWD;

typedef 
struct symbol
{
    
char *szKeyword;        // RTF keyword
    int  dflt;              // default value to use
    bool fPassDflt;         // true to use default value from this table
    KWD  kwd;               // base action to take
    int  idx;               // index into property table if kwd == kwdProp
                            
// index into destination table if kwd == kwdDest
                            
// character to print if kwd == kwdChar
}
 SYM;
Rtfreadr.c
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<ctype.h>
#include 
"rtftype.h"
#include 
"rtfdecl.h"

int cGroup;
bool fSkipDestIfUnk;
long cbBin;
long lParam;

RDS rds;
RIS ris;

CHP chp;
PAP pap;
SEP sep;
DOP dop;

SAVE 
*psave;
FILE 
*fpIn;

//
// %%Function: main
//
// Main loop. Initialize and parse RTF.
//
main(int argc, char *argv[])
{
    FILE 
*fp;
    
int ec;

    fp 
= fpIn = fopen("test.rtf""r");
    
if (!fp)
    
{
        printf (
"Can't open test file! ");
        
return 1;
    }

    
if ((ec = ecRtfParse(fp)) != ecOK)
        printf(
"error %d parsing rtf ", ec);
    
else
        printf(
"Parsed RTF file OK ");
    fclose(fp);
    
return 0;
}


//
// %%Function: ecRtfParse
//
// Step 1:
// Isolate RTF keywords and send them to ecParseRtfKeyword;
// Push and pop state at the start and end of RTF groups;
// Send text to ecParseChar for further processing.
//

int
ecRtfParse(FILE 
*fp)
{
    
int ch;
    
int ec;
    
int cNibble = 2;
    
int b = 0;
    
while ((ch = getc(fp)) != EOF)
    
{
        
if (cGroup < 0)
            
return ecStackUnderflow;
        
if (ris == risBin)                      // if we're parsing binary data, handle it directly
        {
            
if ((ec = ecParseChar(ch)) != ecOK)
                
return ec;
        }

        
else
        
{
            
switch (ch)
            
{
            
case '{':
                
if ((ec = ecPushRtfState()) != ecOK)
                    
return ec;
                
break;
            
case '}':
                
if ((ec = ecPopRtfState()) != ecOK)
                    
return ec;
                
break;
            
case '/':
                
if ((ec = ecParseRtfKeyword(fp)) != ecOK)
                    
return ec;
                
break;
            
case 0x0d:
            
case 0x0a:          // cr and lf are noise characters...
                break;
            
default:
                
if (ris == risNorm)
                
{
                    
if ((ec = ecParseChar(ch)) != ecOK)
                        
return ec;
                }

                
else
                
{               // parsing hex data
                    if (ris != risHex)
                        
return ecAssertion;
                    b 
= b << 4;
                    
if (isdigit(ch))
                        b 
+= (char) ch - '0';
                    
else
                    
{
                        
if (islower(ch))
                        
{
                            
if (ch < 'a' || ch > 'f')
                                
return ecInvalidHex;
                            b 
+= (char) ch - 'a';
                        }

                        
else
                        
{
                            
if (ch < 'A' || ch > 'F')
                                
return ecInvalidHex;
                            b 
+= (char) ch - 'A';
                        }

                    }

                    cNibble
--;
                    
if (!cNibble)
                    
{
                        
if ((ec = ecParseChar(b)) != ecOK)
                            
return ec;
                        cNibble 
= 2;
                        b 
= 0;
ris 
= risNorm;
                    }

                }
                   // end else (ris != risNorm)
                break;
            }
       // switch
        }
           // else (ris != risBin)
    }
               // while
    if (cGroup < 0)
        
return ecStackUnderflow;
    
if (cGroup > 0)
        
return ecUnmatchedBrace;
    
return ecOK;
}


//
// %%Function: ecPushRtfState
//
// Save relevant info on a linked list of SAVE structures.
//

int
ecPushRtfState(
void)
{
    SAVE 
*psaveNew = malloc(sizeof(SAVE));
    
if (!psaveNew)
        
return ecStackOverflow;

    psaveNew 
-> pNext = psave;
    psaveNew 
-> chp = chp;
    psaveNew 
-> pap = pap;
    psaveNew 
-> sep = sep;
    psaveNew 
-> dop = dop;
    psaveNew 
-> rds = rds;
    psaveNew 
-> ris = ris;
    ris 
= risNorm;
    psave 
= psaveNew;
    cGroup
++;
    
return ecOK;
}


//
// %%Function: ecPopRtfState
//
// If we're ending a destination (that is, the destination is changing),
// call ecEndGroupAction.
// Always restore relevant info from the top of the SAVE list.
//

int
ecPopRtfState(
void)
{
    SAVE 
*psaveOld;
    
int ec;

    
if (!psave)
        
return ecStackUnderflow;

    
if (rds != psave->rds)
    
{
        
if ((ec = ecEndGroupAction(rds)) != ecOK)
            
return ec;
    }

    chp 
= psave->chp;
    pap 
= psave->pap;
    sep 
= psave->sep;
    dop 
= psave->dop;
    rds 
= psave->rds;
    ris 
= psave->ris;

    psaveOld 
= psave;
    psave 
= psave->pNext;
    cGroup
--;
    free(psaveOld);
    
return ecOK;
}


//
// %%Function: ecParseRtfKeyword
//
// Step 2:
// get a control word (and its associated value) and
// call ecTranslateKeyword to dispatch the control.
//

int
ecParseRtfKeyword(FILE 
*fp)
{
    
int ch;
    
char fParam = fFalse;
    
char fNeg = fFalse;
    
int param = 0;
    
char *pch;
    
char szKeyword[30];
    
char szParameter[20];

    szKeyword[
0= '
 
Makefile
rtfreadr.exe: rtfactn.obj rtfreadr.obj
    link rtfreadr.obj rtfactn.obj <nul
 
rtfactn.obj: rtfactn.c rtfdecl.h rtftype.h
 
rtfreadr.obj: rtfreadr.c rtfdecl.h rtftype.h
原创粉丝点击