8 // A stack for holding integer values
10 Nestmax = 40 // max nesting level of lists, font styles, etc.
14 int n; // next available slot (top of stack is stack[n-1])
15 int slots[Nestmax]; // stack entries
21 Pstate* next; // in stack of Pstates
22 int skipping; // true when we shouldn't add items
23 int skipwhite; // true when we should strip leading space
24 int curfont; // font index for current font
25 int curfg; // current foreground color
26 Background curbg; // current background
27 int curvoff; // current baseline offset
28 uchar curul; // current underline/strike state
29 uchar curjust; // current justify state
30 int curanchor; // current (href) anchor id (if in one), or 0
31 int curstate; // current value of item state
32 int literal; // current literal state
33 int inpar; // true when in a paragraph-like construct
34 int adjsize; // current font size adjustment
35 Item* items; // dummy head of item list we're building
36 Item* lastit; // tail of item list we're building
37 Item* prelastit; // item before lastit
38 Stack fntstylestk; // style stack
39 Stack fntsizestk; // size stack
40 Stack fgstk; // text color stack
41 Stack ulstk; // underline stack
42 Stack voffstk; // vertical offset stack
43 Stack listtypestk; // list type stack
44 Stack listcntstk; // list counter stack
45 Stack juststk; // justification stack
46 Stack hangstk; // hanging stack
63 // Some layout parameters
65 FRKIDMARGIN = 6, // default margin around kid frames
66 IMGHSPACE = 0, // default hspace for images (0 matches IE, Netscape)
67 IMGVSPACE = 0, // default vspace for images
68 FLTIMGHSPACE = 2, // default hspace for float images
69 TABSP = 5, // default cellspacing for tables
70 TABPAD = 1, // default cell padding for tables
71 LISTTAB = 1, // number of tabs to indent lists
72 BQTAB = 1, // number of tabs to indent blockquotes
73 HRSZ = 2, // thickness of horizontal rules
74 SUBOFF = 4, // vertical offset for subscripts
75 SUPOFF = 6, // vertical offset for superscripts
76 NBSP = 160 // non-breaking space character
79 // These tables must be sorted
80 static StringInt *align_tab;
81 static AsciiInt _align_tab[] = {
82 {"baseline", ALbaseline},
86 {"justify", ALjustify},
92 #define NALIGNTAB (sizeof(_align_tab)/sizeof(StringInt))
94 static StringInt *input_tab;
95 static AsciiInt _input_tab[] = {
97 {"checkbox", Fcheckbox},
101 {"password", Fpassword},
107 #define NINPUTTAB (sizeof(_input_tab)/sizeof(StringInt))
109 static StringInt *clear_tab;
110 static AsciiInt _clear_tab[] = {
111 {"all", IFcleft|IFcright},
115 #define NCLEARTAB (sizeof(_clear_tab)/sizeof(StringInt))
117 static StringInt *fscroll_tab;
118 static AsciiInt _fscroll_tab[] = {
119 {"auto", FRhscrollauto|FRvscrollauto},
121 {"yes", FRhscroll|FRvscroll},
123 #define NFSCROLLTAB (sizeof(_fscroll_tab)/sizeof(StringInt))
125 static StringInt *shape_tab;
126 static AsciiInt _shape_tab[] = {
128 {"circle", SHcircle},
132 {"rectangle", SHrect}
134 #define NSHAPETAB (sizeof(_shape_tab)/sizeof(StringInt))
136 static StringInt *method_tab;
137 static AsciiInt _method_tab[] = {
141 #define NMETHODTAB (sizeof(_method_tab)/sizeof(StringInt))
144 static char* _roman[15]= {
145 "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
146 "XI", "XII", "XIII", "XIV", "XV"
152 LTdisc, LTsquare, LTcircle, LT1, LTa, LTA, LTi, LTI
159 BLBA = (BL|SPBefore|SPAfter)
162 // blockbrk[tag] is break info for a block level element, or one
163 // of a few others that get the same treatment re ending open paragraphs
164 // and requiring a line break / vertical space before them.
165 // If we want a line of space before the given element, SPBefore is OR'd in.
166 // If we want a line of space after the given element, SPAfter is OR'd in.
168 static uchar blockbrk[Numtags]= {
183 /*Tblockquote*/ BLBA,
271 // attrinfo is information about attributes.
272 // The AGEN value means that the attribute is generic (applies to almost all elements)
273 static uchar attrinfo[Numattrs]= {
275 /*Aaccept_charset*/ 0,
343 /*Aondblclick*/ AGEN,
345 /*Aonkeypress*/ AGEN,
348 /*Aonmousedown*/ AGEN,
349 /*Aonmousemove*/ AGEN,
350 /*Aonmouseout*/ AGEN,
351 /*Aonmouseover*/ AGEN,
392 static uchar scriptev[Numattrs]= {
394 /*Aaccept_charset*/ 0,
459 /*Aonblur*/ SEonblur,
460 /*Aonchange*/ SEonchange,
461 /*Aonclick*/ SEonclick,
462 /*Aondblclick*/ SEondblclick,
463 /*Aonfocus*/ SEonfocus,
464 /*Aonkeypress*/ SEonkeypress,
465 /*Aonkeyup*/ SEonkeyup,
466 /*Aonload*/ SEonload,
467 /*Aonmousedown*/ SEonmousedown,
468 /*Aonmousemove*/ SEonmousemove,
469 /*Aonmouseout*/ SEonmouseout,
470 /*Aonmouseover*/ SEonmouseover,
471 /*Aonmouseup*/ SEonmouseup,
472 /*Aonreset*/ SEonreset,
473 /*Aonselect*/ SEonselect,
474 /*Aonsubmit*/ SEonsubmit,
475 /*Aonunload*/ SEonunload,
511 // Color lookup table
512 static StringInt *color_tab;
513 static AsciiInt _color_tab[] = {
517 {"fuchsia", 0xFF00FF},
521 {"maroon", 0x800000},
524 {"purple", 0x800080},
526 {"silver", 0xC0C0C0},
531 #define NCOLORS (sizeof(_color_tab)/sizeof(StringInt))
533 static StringInt *targetmap;
534 static int targetmapsize;
537 static int buildinited = 0;
539 #define SMALLBUFSIZE 240
540 #define BIGBUFSIZE 2000
545 static Align aalign(Token* tok);
546 static int acolorval(Token* tok, int attid, int dflt);
547 static void addbrk(Pstate* ps, int sp, int clr);
548 static void additem(Pstate* ps, Item* it, Token* tok);
549 static void addlinebrk(Pstate* ps, int clr);
550 static void addnbsp(Pstate* ps);
551 static void addtext(Pstate* ps, Rune* s);
552 static Dimen adimen(Token* tok, int attid);
553 static int aflagval(Token* tok, int attid);
554 static int aintval(Token* tok, int attid, int dflt);
555 static Rune* astrval(Token* tok, int attid, Rune* dflt);
556 static int atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt);
557 static int atargval(Token* tok, int dflt);
558 static int auintval(Token* tok, int attid, int dflt);
559 static Rune* aurlval(Token* tok, int attid, Rune* dflt, Rune* base);
560 static Rune* aval(Token* tok, int attid);
561 static void buildinit(void);
562 static Pstate* cell_pstate(Pstate* oldps, int ishead);
563 static void changehang(Pstate* ps, int delta);
564 static void changeindent(Pstate* ps, int delta);
565 static int color(Rune* s, int dflt);
566 static void copystack(Stack* tostk, Stack* fromstk);
567 static int dimprint(char* buf, int nbuf, Dimen d);
568 static Pstate* finishcell(Table* curtab, Pstate* psstk);
569 static void finish_table(Table* t);
570 static void freeanchor(Anchor* a);
571 static void freedestanchor(DestAnchor* da);
572 static void freeform(Form* f);
573 static void freeformfield(Formfield* ff);
574 static void freeitem(Item* it);
575 static void freepstate(Pstate* p);
576 static void freepstatestack(Pstate* pshead);
577 static void freescriptevents(SEvent* ehead);
578 static void freetable(Table* t);
579 static Map* getmap(Docinfo* di, Rune* name);
580 static Rune* getpcdata(Token* toks, int tokslen, int* ptoki);
581 static Pstate* lastps(Pstate* psl);
582 static Rune* listmark(uchar ty, int n);
583 static int listtyval(Token* tok, int dflt);
584 static Align makealign(int halign, int valign);
585 static Background makebackground(Rune* imgurl, int color);
586 static Dimen makedimen(int kind, int spec);
587 static Anchor* newanchor(int index, Rune* name, Rune* href, int target, Anchor* link);
588 static Area* newarea(int shape, Rune* href, int target, Area* link);
589 static DestAnchor* newdestanchor(int index, Rune* name, Item* item, DestAnchor* link);
590 static Docinfo* newdocinfo(void);
591 static Genattr* newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, SEvent* events);
592 static Form* newform(int formid, Rune* name, Rune* action,
593 int target, int method, Form* link);
594 static Formfield* newformfield(int ftype, int fieldid, Form* form, Rune* name,
595 Rune* value, int size, int maxlength, Formfield* link);
596 static Item* newifloat(Item* it, int side);
597 static Item* newiformfield(Formfield* ff);
598 static Item* newiimage(Rune* src, Rune* altrep, int align, int width, int height,
599 int hspace, int vspace, int border, int ismap, Map* map);
600 static Item* newirule(int align, int size, int noshade, Dimen wspec);
601 static Item* newispacer(int spkind);
602 static Item* newitable(Table* t);
603 static ItemSource* newitemsource(Docinfo* di);
604 static Item* newitext(Rune* s, int fnt, int fg, int voff, int ul);
605 static Kidinfo* newkidinfo(int isframeset, Kidinfo* link);
606 static Option* newoption(int selected, Rune* value, Rune* display, Option* link);
607 static Pstate* newpstate(Pstate* link);
608 static SEvent* newscriptevent(int type, Rune* script, SEvent* link);
609 static Table* newtable(int tableid, Align align, Dimen width, int border,
610 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link);
611 static Tablecell* newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec,
612 int hspec, Background bg, int flags, Tablecell* link);
613 static Tablerow* newtablerow(Align align, Background bg, int flags, Tablerow* link);
614 static Dimen parsedim(Rune* s, int ns);
615 static void pop(Stack* stk);
616 static void popfontsize(Pstate* ps);
617 static void popfontstyle(Pstate* ps);
618 static void popjust(Pstate* ps);
619 static int popretnewtop(Stack* stk, int dflt);
620 static int push(Stack* stk, int val);
621 static void pushfontsize(Pstate* ps, int sz);
622 static void pushfontstyle(Pstate* ps, int sty);
623 static void pushjust(Pstate* ps, int j);
624 static Item* textit(Pstate* ps, Rune* s);
625 static Rune* removeallwhite(Rune* s);
626 static void resetdocinfo(Docinfo* d);
627 static void setcurfont(Pstate* ps);
628 static void setcurjust(Pstate* ps);
629 static void setdimarray(Token* tok, int attid, Dimen** pans, int* panslen);
630 static Rune* stringalign(int a);
631 static void targetmapinit(void);
632 static int toint(Rune* s);
633 static int top(Stack* stk, int dflt);
634 static void trim_cell(Tablecell* c);
635 static int validalign(Align a);
636 static int validdimen(Dimen d);
637 static int validformfield(Formfield* f);
638 static int validhalign(int a);
639 static int validptr(void* p);
640 static int validStr(Rune* s);
641 static int validtable(Table* t);
642 static int validtablerow(Tablerow* r);
643 static int validtablecol(Tablecol* c);
644 static int validtablecell(Tablecell* c);
645 static int validvalign(int a);
646 static int Iconv(Fmt *f);
652 roman = _cvtstringtab(_roman, nelem(_roman));
653 color_tab = _cvtstringinttab(_color_tab, nelem(_color_tab));
654 method_tab = _cvtstringinttab(_method_tab, nelem(_method_tab));
655 shape_tab = _cvtstringinttab(_shape_tab, nelem(_shape_tab));
656 fscroll_tab = _cvtstringinttab(_fscroll_tab, nelem(_fscroll_tab));
657 clear_tab = _cvtstringinttab(_clear_tab, nelem(_clear_tab));
658 input_tab = _cvtstringinttab(_input_tab, nelem(_input_tab));
659 align_tab = _cvtstringinttab(_align_tab, nelem(_align_tab));
661 fmtinstall('I', Iconv);
667 newitemsource(Docinfo* di)
673 if(di->mediatype != TextHtml) {
674 ps->curstate &= ~IFwrap;
676 pushfontstyle(ps, FntT);
678 is = (ItemSource*)emalloc(sizeof(ItemSource));
692 static Item *getitems(ItemSource* is, uchar* data, int datalen);
694 // Parse an html document and create a list of layout items.
695 // Allocate and return document info in *pdi.
696 // When caller is done with the items, it should call
697 // freeitems on the returned result, and then
698 // freedocinfo(*pdi).
700 parsehtml(uchar* data, int datalen, Rune* pagesrc, int mtype, int chset, Docinfo** pdi)
707 di->src = _Strdup(pagesrc);
708 di->base = _Strdup(pagesrc);
709 di->mediatype = mtype;
712 is = newitemsource(di);
713 it = getitems(is, data, datalen);
714 freepstatestack(is->psstk);
719 // Get a group of tokens for lexer, parse them, and create
720 // a list of layout items.
721 // When caller is done with the items, it should call
722 // freeitems on the returned result.
724 getitems(ItemSource* is, uchar* data, int datalen)
799 doscripts = 0; // for now
803 toks = _gettoks(data, datalen, di->chset, di->mediatype, &tokslen);
805 for(; toki < tokslen; toki++) {
808 fprint(2, "build: curstate %ux, token %T\n", ps->curstate, tok);
817 else if(tag < Numtags + RBRA) {
818 brk = blockbrk[tag - RBRA];
823 addbrk(ps, brksp, 0);
829 // check common case first (Data), then switch statement on tag
831 // Lexing didn't pay attention to SGML record boundary rules:
832 // \n after start tag or before end tag to be discarded.
833 // (Lex has already discarded all \r's).
834 // Some pages assume this doesn't happen in <PRE> text,
835 // so we won't do it if literal is true.
836 // BUG: won't discard \n before a start tag that begins
837 // the next bufferful of tokens.
844 pt = toks[toki - 1].tag;
845 // IE and Netscape both ignore this rule (contrary to spec)
846 // if previous tag was img
847 if(pt < Numtags && pt != Timg && j > 0 && s[0] == '\n')
850 if(toki < tokslen - 1) {
851 nt = toks[toki + 1].tag;
852 if(nt >= RBRA && nt < Numtags + RBRA && j > i && s[j - 1] == '\n')
857 s = _Strsubstr(s, i, j);
863 _trimwhite(s, n, &t, &nt);
876 tok->text = nil; // token doesn't own string anymore
882 // Some abbrevs used in following DTD comments
884 // | TT | I | B | U | STRIKE | BIG | SMALL | SUB | SUP
885 // | EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE
886 // | A | IMG | APPLET | FONT | BASEFONT | BR | SCRIPT | MAP
887 // | INPUT | SELECT | TEXTAREA
888 // %block = P | UL | OL | DIR | MENU | DL | PRE | DL | DIV | CENTER
889 // | BLOCKQUOTE | FORM | ISINDEX | HR | TABLE
890 // %flow = (%text | %block)*
891 // %body.content = (%heading | %text | %block | ADDRESS)*
893 // <!ELEMENT A - - (%text) -(A)>
894 // Anchors are not supposed to be nested, but you sometimes see
895 // href anchors inside destination anchors.
897 if(ps->curanchor != 0) {
899 fprint(2, "warning: nested <A> or missing </A>\n");
902 name = aval(tok, Aname);
903 href = aurlval(tok, Ahref, nil, di->base);
904 // ignore rel, rev, and title attrs
906 target = atargval(tok, di->target);
907 di->anchors = newanchor(++is->nanchors, name, href, target, di->anchors);
909 name = _Strdup(name); // for DestAnchor construction, below
910 ps->curanchor = is->nanchors;
911 ps->curfg = push(&ps->fgstk, di->link);
912 ps->curul = push(&ps->ulstk, ULunder);
915 // add a null item to be destination
916 additem(ps, newispacer(ISPnull), tok);
917 di->dests = newdestanchor(++is->nanchors, name, ps->lastit, di->dests);
922 if(ps->curanchor != 0) {
923 ps->curfg = popretnewtop(&ps->fgstk, di->text);
924 ps->curul = popretnewtop(&ps->ulstk, ULnone);
929 // <!ELEMENT APPLET - - (PARAM | %text)* >
930 // We can't do applets, so ignore PARAMS, and let
931 // the %text contents appear for the alternative rep
934 if(warn && tag == Tapplet)
935 fprint(2, "warning: <APPLET> ignored\n");
938 // <!ELEMENT AREA - O EMPTY>
943 fprint(2, "warning: <AREA> not inside <MAP>\n");
946 map->areas = newarea(atabval(tok, Ashape, shape_tab, NSHAPETAB, SHrect),
947 aurlval(tok, Ahref, nil, di->base),
948 atargval(tok, di->target),
950 setdimarray(tok, Acoords, &map->areas->coords, &map->areas->ncoords);
953 // <!ELEMENT (B|STRONG) - - (%text)*>
956 pushfontstyle(ps, FntB);
974 // <!ELEMENT BASE - O EMPTY>
977 di->base = aurlval(tok, Ahref, di->base, di->base);
980 di->target = atargval(tok, di->target);
983 // <!ELEMENT BASEFONT - O EMPTY>
985 ps->adjsize = aintval(tok, Asize, 3) - 3;
988 // <!ELEMENT (BIG|SMALL) - - (%text)*>
996 pushfontsize(ps, sz);
1004 // <!ELEMENT BLOCKQUOTE - - %body.content>
1006 changeindent(ps, BQTAB);
1009 case Tblockquote+RBRA:
1010 changeindent(ps, -BQTAB);
1013 // <!ELEMENT BODY O O %body.content>
1016 bg = makebackground(nil, acolorval(tok, Abgcolor, di->background.color));
1017 bgurl = aurlval(tok, Abackground, nil, di->base);
1019 if(di->backgrounditem != nil)
1020 freeitem((Item*)di->backgrounditem);
1021 // really should remove old item from di->images list,
1022 // but there should only be one BODY element ...
1023 di->backgrounditem = (Iimage*)newiimage(bgurl, nil, ALnone, 0, 0, 0, 0, 0, 0, nil);
1024 di->backgrounditem->nextimage = di->images;
1025 di->images = di->backgrounditem;
1028 di->background = bg;
1029 di->text = acolorval(tok, Atext, di->text);
1030 di->link = acolorval(tok, Alink, di->link);
1031 di->vlink = acolorval(tok, Avlink, di->vlink);
1032 di->alink = acolorval(tok, Aalink, di->alink);
1033 if(di->text != ps->curfg) {
1034 ps->curfg = di->text;
1040 // HTML spec says ignore things after </body>,
1041 // but IE and Netscape don't
1045 // <!ELEMENT BR - O EMPTY>
1047 addlinebrk(ps, atabval(tok, Aclear, clear_tab, NCLEARTAB, 0));
1050 // <!ELEMENT CAPTION - - (%text;)*>
1054 fprint(2, "warning: <CAPTION> outside <TABLE>\n");
1057 if(curtab->caption != nil) {
1059 fprint(2, "warning: more than one <CAPTION> in <TABLE>\n");
1063 curtab->caption_place = atabval(tok, Aalign, align_tab, NALIGNTAB, ALtop);
1068 if(curtab == nil || nextps == nil) {
1070 fprint(2, "warning: unexpected </CAPTION>\n");
1073 curtab->caption = ps->items->next;
1083 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust);
1092 // <!ELEMENT DD - O %flow >
1094 if(ps->hangstk.n == 0) {
1096 fprint(2, "warning: <DD> not inside <DL\n");
1099 h = top(&ps->hangstk, 0);
1101 changehang(ps, -10*LISTTAB);
1104 push(&ps->hangstk, 0);
1107 //<!ELEMENT (DIR|MENU) - - (LI)+ -(%block) >
1108 //<!ELEMENT (OL|UL) - - (LI)+>
1113 changeindent(ps, LISTTAB);
1114 push(&ps->listtypestk, listtyval(tok, (tag==Tol)? LT1 : LTdisc));
1115 push(&ps->listcntstk, aintval(tok, Astart, 1));
1122 if(ps->listtypestk.n == 0) {
1124 fprint(2, "warning: %T ended no list\n", tok);
1128 pop(&ps->listtypestk);
1129 pop(&ps->listcntstk);
1130 changeindent(ps, -LISTTAB);
1133 // <!ELEMENT DL - - (DT|DD)+ >
1135 changeindent(ps, LISTTAB);
1136 push(&ps->hangstk, 0);
1140 if(ps->hangstk.n == 0) {
1142 fprint(2, "warning: unexpected </DL>\n");
1145 changeindent(ps, -LISTTAB);
1146 if(top(&ps->hangstk, 0) != 0)
1147 changehang(ps, -10*LISTTAB);
1151 // <!ELEMENT DT - O (%text)* >
1153 if(ps->hangstk.n == 0) {
1155 fprint(2, "warning: <DT> not inside <DL>\n");
1158 h = top(&ps->hangstk, 0);
1161 changehang(ps, -10*LISTTAB);
1162 changehang(ps, 10*LISTTAB);
1163 push(&ps->hangstk, 1);
1166 // <!ELEMENT FONT - - (%text)*>
1168 sz = top(&ps->fntsizestk, Normal);
1169 if(_tokaval(tok, Asize, &nsz, 0)) {
1170 if(_prefix(L(Lplus), nsz))
1171 sz = Normal + _Strtol(nsz+1, nil, 10) + ps->adjsize;
1172 else if(_prefix(L(Lminus), nsz))
1173 sz = Normal - _Strtol(nsz+1, nil, 10) + ps->adjsize;
1175 sz = Normal + (_Strtol(nsz, nil, 10) - 3);
1177 ps->curfg = push(&ps->fgstk, acolorval(tok, Acolor, ps->curfg));
1178 pushfontsize(ps, sz);
1182 if(ps->fgstk.n == 0) {
1184 fprint(2, "warning: unexpected </FONT>\n");
1187 ps->curfg = popretnewtop(&ps->fgstk, di->text);
1191 // <!ELEMENT FORM - - %body.content -(FORM) >
1193 if(is->curform != nil) {
1195 fprint(2, "warning: <FORM> nested inside another\n");
1198 action = aurlval(tok, Aaction, di->base, di->base);
1200 name = astrval(tok, Aname, s);
1203 target = atargval(tok, di->target);
1204 method = atabval(tok, Amethod, method_tab, NMETHODTAB, HGet);
1205 if(warn && _tokaval(tok, Aenctype, &enctype, 0) &&
1206 _Strcmp(enctype, L(Lappl_form)))
1207 fprint(2, "form enctype %S not handled\n", enctype);
1208 frm = newform(++is->nforms, name, action, target, method, di->forms);
1214 if(is->curform == nil) {
1216 fprint(2, "warning: unexpected </FORM>\n");
1219 // put fields back in input order
1220 is->curform->fields = (Formfield*)_revlist((List*)is->curform->fields);
1224 // <!ELEMENT FRAME - O EMPTY>
1229 fprint(2, "warning: <FRAME> not in <FRAMESET>\n");
1232 ks->kidinfos = kd = newkidinfo(0, ks->kidinfos);
1233 kd->src = aurlval(tok, Asrc, nil, di->base);
1234 kd->name = aval(tok, Aname);
1235 if(kd->name == nil) {
1236 s = _ltoStr(++is->nframes);
1237 kd->name = _Strdup2(L(Lfr), s);
1240 kd->marginw = auintval(tok, Amarginwidth, 0);
1241 kd->marginh = auintval(tok, Amarginheight, 0);
1242 kd->framebd = auintval(tok, Aframeborder, 1);
1243 kd->flags = atabval(tok, Ascrolling, fscroll_tab, NFSCROLLTAB, kd->flags);
1244 norsz = aflagval(tok, Anoresize);
1246 kd->flags |= FRnoresize;
1249 // <!ELEMENT FRAMESET - - (FRAME|FRAMESET)+>
1251 ks = newkidinfo(1, nil);
1256 ks->next = pks->kidinfos;
1259 ks->nextframeset = pks;
1261 setdimarray(tok, Arows, &ks->rows, &ks->nrows);
1262 if(ks->nrows == 0) {
1263 ks->rows = (Dimen*)emalloc(sizeof(Dimen));
1265 ks->rows[0] = makedimen(Dpercent, 100);
1267 setdimarray(tok, Acols, &ks->cols, &ks->ncols);
1268 if(ks->ncols == 0) {
1269 ks->cols = (Dimen*)emalloc(sizeof(Dimen));
1271 ks->cols[0] = makedimen(Dpercent, 100);
1275 case Tframeset+RBRA:
1276 if(is->kidstk == nil) {
1278 fprint(2, "warning: unexpected </FRAMESET>\n");
1282 // put kids back in original order
1283 // and add blank frames to fill out cells
1284 n = ks->nrows*ks->ncols;
1285 nblank = n - _listlen((List*)ks->kidinfos);
1287 ks->kidinfos = newkidinfo(0, ks->kidinfos);
1288 ks->kidinfos = (Kidinfo*)_revlist((List*)ks->kidinfos);
1289 is->kidstk = is->kidstk->nextframeset;
1290 if(is->kidstk == nil) {
1297 // <!ELEMENT H1 - - (%text;)*>, etc.
1305 if(ps->items == ps->lastit)
1307 addbrk(ps, bramt, IFcleft|IFcright);
1308 sz = Verylarge - (tag - Th1);
1311 pushfontsize(ps, sz);
1312 sty = top(&ps->fntstylestk, FntR);
1315 pushfontstyle(ps, sty);
1316 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1326 addbrk(ps, 1, IFcleft|IFcright);
1333 // HTML spec says ignore regular markup in head,
1334 // but Netscape and IE don't
1342 // <!ELEMENT HR - O EMPTY>
1344 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ALcenter);
1345 sz = auintval(tok, Asize, HRSZ);
1346 wd = adimen(tok, Awidth);
1347 if(dimenkind(wd) == Dnone)
1348 wd = makedimen(Dpercent, 100);
1349 nosh = aflagval(tok, Anoshade);
1350 additem(ps, newirule(al, sz, nosh, wd), tok);
1360 pushfontstyle(ps, FntI);
1363 // <!ELEMENT IMG - O EMPTY>
1366 oldcuranchor = ps->curanchor;
1367 if(_tokaval(tok, Ausemap, &usemap, 0)) {
1368 if(!_prefix(L(Lhash), usemap)) {
1370 fprint(2, "warning: can't handle non-local map %S\n", usemap);
1373 map = getmap(di, usemap+1);
1374 if(ps->curanchor == 0) {
1375 di->anchors = newanchor(++is->nanchors, nil, nil, di->target, di->anchors);
1376 ps->curanchor = is->nanchors;
1380 align = atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom);
1382 if(ps->curanchor != 0)
1384 src = aurlval(tok, Asrc, nil, di->base);
1387 fprint(2, "warning: <img> has no src attribute\n");
1388 ps->curanchor = oldcuranchor;
1391 img = newiimage(src,
1394 auintval(tok, Awidth, 0),
1395 auintval(tok, Aheight, 0),
1396 auintval(tok, Ahspace, IMGHSPACE),
1397 auintval(tok, Avspace, IMGVSPACE),
1398 auintval(tok, Aborder, dfltbd),
1399 aflagval(tok, Aismap),
1401 if(align == ALleft || align == ALright) {
1402 additem(ps, newifloat(img, align), tok);
1403 // if no hspace specified, use FLTIMGHSPACE
1404 if(!_tokaval(tok, Ahspace, &val, 0))
1405 ((Iimage*)img)->hspace = FLTIMGHSPACE;
1409 additem(ps, img, tok);
1412 ((Iimage*)img)->nextimage = di->images;
1413 di->images = (Iimage*)img;
1415 ps->curanchor = oldcuranchor;
1418 // <!ELEMENT INPUT - O EMPTY>
1421 if(is->curform == nil) {
1423 fprint(2, "<INPUT> not inside <FORM>\n");
1426 is->curform->fields = field = newformfield(
1427 atabval(tok, Atype, input_tab, NINPUTTAB, Ftext),
1428 ++is->curform->nfields,
1432 auintval(tok, Asize, 0),
1433 auintval(tok, Amaxlength, 1000),
1434 is->curform->fields);
1435 if(aflagval(tok, Achecked))
1436 field->flags = FFchecked;
1438 switch(field->ftype) {
1442 if(field->size == 0)
1447 if(field->name == nil) {
1449 fprint(2, "warning: checkbox form field missing name\n");
1452 if(field->value == nil)
1453 field->value = _Strdup(L(Lone));
1457 if(field->name == nil || field->value == nil) {
1459 fprint(2, "warning: radio form field missing name or value\n");
1465 if(field->value == nil)
1466 field->value = _Strdup(L(Lsubmit));
1467 if(field->name == nil)
1468 field->name = _Strdup(L(Lnoname));
1472 src = aurlval(tok, Asrc, nil, di->base);
1475 fprint(2, "warning: image form field missing src\n");
1478 // width and height attrs aren't specified in HTML 3.2,
1479 // but some people provide them and they help avoid
1481 field->image = newiimage(src,
1482 astrval(tok, Aalt, L(Lsubmit)),
1483 atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom),
1484 auintval(tok, Awidth, 0), auintval(tok, Aheight, 0),
1486 ii = (Iimage*)field->image;
1487 ii->nextimage = di->images;
1492 if(field->value == nil)
1493 field->value = _Strdup(L(Lreset));
1497 if(field->value == nil)
1498 field->value = _Strdup(L(Lspace));
1501 ffit = newiformfield(field);
1502 additem(ps, ffit, tok);
1503 if(ffit->genattr != nil)
1504 field->events = ffit->genattr->events;
1507 // <!ENTITY ISINDEX - O EMPTY>
1510 prompt = astrval(tok, Aprompt, L(Lindex));
1511 target = atargval(tok, di->target);
1512 additem(ps, textit(ps, prompt), tok);
1513 frm = newform(++is->nforms,
1520 ff = newformfield(Ftext,
1523 _Strdup(L(Lisindex)),
1530 additem(ps, newiformfield(ff), tok);
1534 // <!ELEMENT LI - O %flow>
1536 if(ps->listtypestk.n == 0) {
1538 fprint(2, "<LI> not in list\n");
1541 ty = top(&ps->listtypestk, 0);
1542 ty2 = listtyval(tok, ty);
1545 push(&ps->listtypestk, ty2);
1547 v = aintval(tok, Avalue, top(&ps->listcntstk, 1));
1548 if(ty == LTdisc || ty == LTsquare || ty == LTcircle)
1549 hang = 10*LISTTAB - 3;
1551 hang = 10*LISTTAB - 1;
1552 changehang(ps, hang);
1553 addtext(ps, listmark(ty, v));
1554 push(&ps->listcntstk, v + 1);
1555 changehang(ps, -hang);
1559 // <!ELEMENT MAP - - (AREA)+>
1561 if(_tokaval(tok, Aname, &name, 0))
1562 is->curmap = getmap(di, name);
1569 fprint(2, "warning: unexpected </MAP>\n");
1572 map->areas = (Area*)_revlist((List*)map->areas);
1578 if(_tokaval(tok, Ahttp_equiv, &equiv, 0)) {
1579 val = aval(tok, Acontent);
1581 if(!_Strncmpci(equiv, n, L(Lrefresh)))
1583 else if(!_Strncmpci(equiv, n, L(Lcontent))) {
1585 if(!_Strncmpci(val, n, L(Ljavascript))
1586 || !_Strncmpci(val, n, L(Ljscript1))
1587 || !_Strncmpci(val, n, L(Ljscript)))
1588 di->scripttype = TextJavascript;
1591 fprint(2, "unimplemented script type %S\n", val);
1592 di->scripttype = UnknownType;
1598 // Nobr is NOT in HMTL 4.0, but it is ubiquitous on the web
1601 ps->curstate &= ~IFwrap;
1605 ps->curstate |= IFwrap;
1608 // We do frames, so skip stuff in noframes
1613 case Tnoframes+RBRA:
1617 // We do scripts (if enabled), so skip stuff in noscripts
1623 case Tnoscript+RBRA:
1628 // <!ELEMENT OPTION - O ( //PCDATA)>
1630 if(is->curform == nil || is->curform->fields == nil) {
1632 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1635 field = is->curform->fields;
1636 if(field->ftype != Fselect) {
1638 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1641 val = aval(tok, Avalue);
1642 option = newoption(aflagval(tok, Aselected), val, nil, field->options);
1643 field->options = option;
1644 option->display = getpcdata(toks, tokslen, &toki);
1646 option->value = _Strdup(option->display);
1649 // <!ELEMENT P - O (%text)* >
1651 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1659 // <!ELEMENT PARAM - O EMPTY>
1660 // Do something when we do applets...
1664 // <!ELEMENT PRE - - (%text)* -(IMG|BIG|SMALL|SUB|SUP|FONT) >
1666 ps->curstate &= ~IFwrap;
1669 pushfontstyle(ps, FntT);
1673 ps->curstate |= IFwrap;
1680 // <!ELEMENT SCRIPT - - CDATA>
1683 if(!di->hasscripts) {
1684 if(di->scripttype == TextJavascript) {
1685 // TODO: initialize script if nec.
1691 if(!di->hasscripts) {
1693 fprint(2, "warning: <SCRIPT> ignored\n");
1697 scriptsrc = aurlval(tok, Asrc, nil, di->base);
1699 if(scriptsrc != nil) {
1701 fprint(2, "warning: non-local <SCRIPT> ignored\n");
1705 script = getpcdata(toks, tokslen, &toki);
1709 fprint(2, "script ignored\n");
1719 // <!ELEMENT SELECT - - (OPTION+)>
1721 if(is->curform == nil) {
1723 fprint(2, "<SELECT> not inside <FORM>\n");
1726 field = newformfield(Fselect,
1727 ++is->curform->nfields,
1731 auintval(tok, Asize, 0),
1733 is->curform->fields);
1734 is->curform->fields = field;
1735 if(aflagval(tok, Amultiple))
1736 field->flags = FFmultiple;
1737 ffit = newiformfield(field);
1738 additem(ps, ffit, tok);
1739 if(ffit->genattr != nil)
1740 field->events = ffit->genattr->events;
1741 // throw away stuff until next tag (should be <OPTION>)
1742 s = getpcdata(toks, tokslen, &toki);
1748 if(is->curform == nil || is->curform->fields == nil) {
1750 fprint(2, "warning: unexpected </SELECT>\n");
1753 field = is->curform->fields;
1754 if(field->ftype != Fselect)
1756 // put options back in input order
1757 field->options = (Option*)_revlist((List*)field->options);
1760 // <!ELEMENT (STRIKE|U) - - (%text)*>
1763 ps->curul = push(&ps->ulstk, (tag==Tstrike)? ULmid : ULunder);
1768 if(ps->ulstk.n == 0) {
1770 fprint(2, "warning: unexpected %T\n", tok);
1773 ps->curul = popretnewtop(&ps->ulstk, ULnone);
1776 // <!ELEMENT STYLE - - CDATA>
1779 fprint(2, "warning: unimplemented <STYLE>\n");
1787 // <!ELEMENT (SUB|SUP) - - (%text)*>
1791 ps->curvoff += SUBOFF;
1793 ps->curvoff -= SUPOFF;
1794 push(&ps->voffstk, ps->curvoff);
1795 sz = top(&ps->fntsizestk, Normal);
1796 pushfontsize(ps, sz - 1);
1801 if(ps->voffstk.n == 0) {
1803 fprint(2, "warning: unexpected %T\n", tok);
1806 ps->curvoff = popretnewtop(&ps->voffstk, 0);
1810 // <!ELEMENT TABLE - - (CAPTION?, TR+)>
1813 tab = newtable(++is->ntables,
1815 adimen(tok, Awidth),
1816 aflagval(tok, Aborder),
1817 auintval(tok, Acellspacing, TABSP),
1818 auintval(tok, Acellpadding, TABPAD),
1819 makebackground(nil, acolorval(tok, Abgcolor, ps->curbg.color)),
1829 fprint(2, "warning: unexpected </TABLE>\n");
1832 isempty = (curtab->cells == nil);
1835 fprint(2, "warning: <TABLE> has no cells\n");
1838 ps = finishcell(curtab, ps);
1839 if(curtab->rows != nil)
1840 curtab->rows->flags = 0;
1841 finish_table(curtab);
1845 tabitem = newitable(curtab);
1846 al = curtab->align.halign;
1850 additem(ps, newifloat(tabitem, al), tok);
1854 pushjust(ps, ALcenter);
1860 additem(ps, tabitem, curtab->tabletok);
1866 if(is->tabstk == nil) {
1868 fprint(2, "warning: table stack is wrong\n");
1871 is->tabstk = is->tabstk->next;
1872 curtab->next = di->tables;
1873 di->tables = curtab;
1874 curtab = is->tabstk;
1879 // <!ELEMENT (TH|TD) - O %body.content>
1880 // Cells for a row are accumulated in reverse order.
1881 // We push ps on a stack, and use a new one to accumulate
1882 // the contents of the cell.
1887 fprint(2, "%T outside <TABLE>\n", tok);
1894 ps = finishcell(curtab, ps);
1896 if(curtab->rows != nil)
1898 if(tr == nil || !tr->flags) {
1900 fprint(2, "%T outside row\n", tok);
1901 tr = newtablerow(makealign(ALnone, ALnone),
1902 makebackground(nil, curtab->background.color),
1907 ps = cell_pstate(ps, tag == Tth);
1909 if(aflagval(tok, Anowrap)) {
1911 ps->curstate &= ~IFwrap;
1915 c = newtablecell(curtab->cells==nil? 1 : curtab->cells->cellid+1,
1916 auintval(tok, Arowspan, 1),
1917 auintval(tok, Acolspan, 1),
1919 adimen(tok, Awidth),
1920 auintval(tok, Aheight, 0),
1921 makebackground(nil, acolorval(tok, Abgcolor, tr->background.color)),
1925 ps->curbg = c->background;
1926 if(c->align.halign == ALnone) {
1927 if(tr->align.halign != ALnone)
1928 c->align.halign = tr->align.halign;
1930 c->align.halign = ALcenter;
1932 c->align.halign = ALleft;
1934 if(c->align.valign == ALnone) {
1935 if(tr->align.valign != ALnone)
1936 c->align.valign = tr->align.valign;
1938 c->align.valign = ALmiddle;
1940 c->nextinrow = tr->cells;
1946 if(curtab == nil || curtab->cells == nil) {
1948 fprint(2, "unexpected %T\n", tok);
1951 ps = finishcell(curtab, ps);
1954 // <!ELEMENT TEXTAREA - - ( //PCDATA)>
1956 if(is->curform == nil) {
1958 fprint(2, "<TEXTAREA> not inside <FORM>\n");
1961 field = newformfield(Ftextarea,
1962 ++is->curform->nfields,
1968 is->curform->fields);
1969 is->curform->fields = field;
1970 field->rows = auintval(tok, Arows, 3);
1971 field->cols = auintval(tok, Acols, 50);
1972 field->value = getpcdata(toks, tokslen, &toki);
1973 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttextarea + RBRA)
1974 fprint(2, "warning: <TEXTAREA> data ended by %T\n", &toks[toki + 1]);
1975 ffit = newiformfield(field);
1976 additem(ps, ffit, tok);
1977 if(ffit->genattr != nil)
1978 field->events = ffit->genattr->events;
1981 // <!ELEMENT TITLE - - ( //PCDATA)* -(%head.misc)>
1983 di->doctitle = getpcdata(toks, tokslen, &toki);
1984 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttitle + RBRA)
1985 fprint(2, "warning: <TITLE> data ended by %T\n", &toks[toki + 1]);
1988 // <!ELEMENT TR - O (TH|TD)+>
1989 // rows are accumulated in reverse order in curtab->rows
1993 fprint(2, "warning: <TR> outside <TABLE>\n");
2000 ps = finishcell(curtab, ps);
2001 if(curtab->rows != nil)
2002 curtab->rows->flags = 0;
2003 curtab->rows = newtablerow(aalign(tok),
2004 makebackground(nil, acolorval(tok, Abgcolor, curtab->background.color)),
2010 if(curtab == nil || curtab->rows == nil) {
2012 fprint(2, "warning: unexpected </TR>\n");
2015 ps = finishcell(curtab, ps);
2017 if(tr->cells == nil) {
2019 fprint(2, "warning: empty row\n");
2020 curtab->rows = tr->next;
2027 // <!ELEMENT (TT|CODE|KBD|SAMP) - - (%text)*>
2032 pushfontstyle(ps, FntT);
2035 // Tags that have empty action
2042 case Tbasefont+RBRA:
2059 case Ttextarea+RBRA:
2064 // Tags not implemented
2072 case Tfieldset+RBRA:
2084 case Toptgroup+RBRA:
2090 fprint(2, "warning: unimplemented HTML tag: %S\n", tagnames[tag]);
2096 fprint(2, "warning: unknown HTML tag: %S\n", tok->text);
2100 // some pages omit trailing </table>
2101 while(curtab != nil) {
2103 fprint(2, "warning: <TABLE> not closed\n");
2104 if(curtab->cells != nil) {
2105 ps = finishcell(curtab, ps);
2106 if(curtab->cells == nil) {
2108 fprint(2, "warning: empty table\n");
2111 if(curtab->rows != nil)
2112 curtab->rows->flags = 0;
2113 finish_table(curtab);
2115 additem(ps, newitable(curtab), curtab->tabletok);
2119 if(is->tabstk != nil)
2120 is->tabstk = is->tabstk->next;
2121 curtab->next = di->tables;
2122 di->tables = curtab;
2123 curtab = is->tabstk;
2125 outerps = lastps(ps);
2126 ans = outerps->items->next;
2127 // note: ans may be nil and di->kids not nil, if there's a frameset!
2128 outerps->items = newispacer(ISPnull);
2129 outerps->lastit = outerps->items;
2131 if(ans != nil && di->hasscripts) {
2132 // TODO evalscript(nil);
2138 assert(validitems(ans));
2140 fprint(2, "getitems returning nil\n");
2142 printitems(ans, "getitems returning:");
2147 // Concatenate together maximal set of Data tokens, starting at toks[toki+1].
2148 // Lexer has ensured that there will either be a following non-data token or
2149 // we will be at eof.
2150 // Return emallocd trimmed concatenation, and update *ptoki to last used toki
2152 getpcdata(Token* toks, int tokslen, int* ptoki)
2164 // first find length of answer
2165 toki = (*ptoki) + 1;
2166 while(toki < tokslen) {
2168 if(tok->tag == Data) {
2170 anslen += _Strlen(tok->text);
2175 // now make up the initial answer
2177 ans = _newstr(anslen);
2179 toki = (*ptoki) + 1;
2180 while(toki < tokslen) {
2182 if(tok->tag == Data) {
2184 p = _Stradd(p, tok->text, _Strlen(tok->text));
2190 _trimwhite(ans, anslen, &trimans, &trimanslen);
2191 if(trimanslen != anslen) {
2193 ans = _Strndup(trimans, trimanslen);
2201 // If still parsing head of curtab->cells list, finish it off
2202 // by transferring the items on the head of psstk to the cell.
2203 // Then pop the psstk and return the new psstk.
2205 finishcell(Table* curtab, Pstate* psstk)
2212 if((c->flags&TFparsing)) {
2213 psstknext = psstk->next;
2214 if(psstknext == nil) {
2216 fprint(2, "warning: parse state stack is wrong\n");
2219 c->content = psstk->items->next;
2220 c->flags &= ~TFparsing;
2229 // Make a new Pstate for a cell, based on the old pstate, oldps.
2230 // Also, put the new ps on the head of the oldps stack.
2232 cell_pstate(Pstate* oldps, int ishead)
2237 ps = newpstate(oldps);
2239 ps->curanchor = oldps->curanchor;
2240 copystack(&ps->fntstylestk, &oldps->fntstylestk);
2241 copystack(&ps->fntsizestk, &oldps->fntsizestk);
2242 ps->curfont = oldps->curfont;
2243 ps->curfg = oldps->curfg;
2244 ps->curbg = oldps->curbg;
2245 copystack(&ps->fgstk, &oldps->fgstk);
2246 ps->adjsize = oldps->adjsize;
2248 sty = ps->curfont%NumSize;
2249 ps->curfont = FntB*NumSize + sty;
2254 // Return a new Pstate with default starting state.
2255 // Use link to add it to head of a list, if any.
2257 newpstate(Pstate* link)
2261 ps = (Pstate*)emalloc(sizeof(Pstate));
2262 ps->curfont = DefFnt;
2264 ps->curbg.image = nil;
2265 ps->curbg.color = White;
2267 ps->curjust = ALleft;
2268 ps->curstate = IFwrap;
2269 ps->items = newispacer(ISPnull);
2270 ps->lastit = ps->items;
2271 ps->prelastit = nil;
2276 // Return last Pstate on psl list
2281 while(psl->next != nil)
2286 // Add it to end of ps item chain, adding in current state from ps.
2287 // Also, if tok is not nil, scan it for generic attributes and assign
2288 // the genattr field of the item accordingly.
2290 additem(Pstate* ps, Item* it, Token* tok)
2303 fprint(2, "warning: skipping item: %I\n", it);
2306 it->anchorid = ps->curanchor;
2307 it->state |= ps->curstate;
2315 for(a = tok->attr; a != nil; a = a->next) {
2337 assert(aid >= Aonblur && aid <= Aonunload);
2338 e = newscriptevent(scriptev[a->attid], a->value, e);
2345 it->genattr = newgenattr(i, c, s, t, e);
2347 ps->curstate &= ~(IFbrk|IFbrksp|IFnobrk|IFcleft|IFcright);
2348 ps->prelastit = ps->lastit;
2349 ps->lastit->next = it;
2353 // Make a text item out of s,
2354 // using current font, foreground, vertical offset and underline state.
2356 textit(Pstate* ps, Rune* s)
2359 return newitext(s, ps->curfont, ps->curfg, ps->curvoff + Voffbias, ps->curul);
2362 // Add text item or items for s, paying attention to
2363 // current font, foreground, baseline offset, underline state,
2364 // and literal mode. Unless we're in literal mode, compress
2365 // whitespace to single blank, and, if curstate has a break,
2366 // trim any leading whitespace. Whether in literal mode or not,
2367 // turn nonbreaking spaces into spacer items with IFnobrk set.
2369 // In literal mode, break up s at newlines and add breaks instead.
2370 // Also replace tabs appropriate number of spaces.
2371 // In nonliteral mode, break up the items every 100 or so characters
2372 // just to make the layout algorithm not go quadratic.
2374 // addtext assumes ownership of s.
2376 addtext(Pstate* ps, Rune* s)
2388 Rune buf[SMALLBUFSIZE];
2399 // trim trailing blanks from line
2400 for(k = i; k > j; k--)
2404 additem(ps, textit(ps, _Strndup(s+j, k-j)), nil);
2414 // make ss = s[j:i] + nsp spaces
2415 ss = _newstr(i-j+nsp);
2416 p = _Stradd(ss, s+j, i-j);
2417 p = _Stradd(p, L(Ltab2space), nsp);
2419 additem(ps, textit(ps, ss), nil);
2423 else if(s[i] == NBSP) {
2425 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2434 if(j == 0 && i == n) {
2435 // just transfer s over
2436 additem(ps, textit(ps, s), nil);
2439 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2444 else { // not literal mode
2445 if((ps->curstate&IFbrk) || ps->lastit == ps->items)
2448 if(c >= 256 || !isspace(c))
2453 for(j = i; i < n; i++) {
2454 assert(p+i-j < buf+SMALLBUFSIZE-1);
2458 p = _Stradd(p, s+j, i-j);
2460 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2466 if(c < 256 && isspace(c)) {
2468 p = _Stradd(p, s+j, i-j);
2472 if(c >= 256 || !isspace(c))
2479 p = _Stradd(p, s+j, i+1-j);
2483 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2487 if(i > j && j < n) {
2488 assert(p+i-j < buf+SMALLBUFSIZE-1);
2489 p = _Stradd(p, s+j, i-j);
2491 // don't add a space if previous item ended in a space
2492 if(p-buf == 1 && buf[0] == ' ' && ps->lastit != nil) {
2494 if(it->tag == Itexttag) {
2495 ss = ((Itext*)it)->s;
2497 if(k > 0 && ss[k] == ' ')
2502 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2507 // Add a break to ps->curstate, with extra space if sp is true.
2508 // If there was a previous break, combine this one's parameters
2509 // with that to make the amt be the max of the two and the clr
2510 // be the most general. (amt will be 0 or 1)
2511 // Also, if the immediately preceding item was a text item,
2512 // trim any whitespace from the end of it, if not in literal mode.
2513 // Finally, if this is at the very beginning of the item list
2514 // (the only thing there is a null spacer), then don't add the space.
2516 addbrk(Pstate* ps, int sp, int clr)
2526 state = ps->curstate;
2527 clr = clr|(state&(IFcleft|IFcright));
2528 if(sp && !(ps->lastit == ps->items))
2532 ps->curstate = IFbrk|sp|(state&~(IFcleft|IFcright))|clr;
2533 if(ps->lastit != ps->items) {
2534 if(!ps->literal && ps->lastit->tag == Itexttag) {
2535 t = (Itext*)ps->lastit;
2536 _splitr(t->s, _Strlen(t->s), notwhitespace, &l, &nl, &r, &nr);
2537 // try to avoid making empty items
2538 // but not crucial f the occasional one gets through
2539 if(nl == 0 && ps->prelastit != nil) {
2540 ps->lastit = ps->prelastit;
2541 ps->lastit->next = nil;
2542 ps->prelastit = nil;
2547 // need a non-nil pointer to empty string
2548 // (_Strdup(L(Lempty)) returns nil)
2549 t->s = emalloc(sizeof(Rune));
2553 t->s = _Strndup(l, nl);
2561 // Add break due to a <br> or a newline within a preformatted section.
2562 // We add a null item first, with current font's height and ascent, to make
2563 // sure that the current line takes up at least that amount of vertical space.
2564 // This ensures that <br>s on empty lines cause blank lines, and that
2565 // multiple <br>s in a row give multiple blank lines.
2566 // However don't add the spacer if the previous item was something that
2567 // takes up space itself.
2569 addlinebrk(Pstate* ps, int clr)
2575 // don't want break before our null item unless the previous item
2576 // was also a null item for the purposes of line breaking
2577 obrkstate = ps->curstate&(IFbrk|IFbrksp);
2580 if(ps->lastit != nil) {
2581 if(ps->lastit->tag == Ispacertag) {
2582 if(((Ispacer*)ps->lastit)->spkind == ISPvline)
2586 else if(ps->lastit->tag == Ifloattag)
2590 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|b;
2591 additem(ps, newispacer(ISPvline), nil);
2592 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|obrkstate;
2597 // Add a nonbreakable space
2601 // if nbsp comes right where a break was specified,
2602 // do the break anyway (nbsp is being used to generate undiscardable
2603 // space rather than to prevent a break)
2604 if((ps->curstate&IFbrk) == 0)
2605 ps->curstate |= IFnobrk;
2606 additem(ps, newispacer(ISPhspace), nil);
2607 // but definitely no break on next item
2608 ps->curstate |= IFnobrk;
2611 // Change hang in ps.curstate by delta.
2612 // The amount is in 1/10ths of tabs, and is the amount that
2613 // the current contiguous set of items with a hang value set
2614 // is to be shifted left from its normal (indented) place.
2616 changehang(Pstate* ps, int delta)
2620 amt = (ps->curstate&IFhangmask) + delta;
2623 fprint(2, "warning: hang went negative\n");
2626 ps->curstate = (ps->curstate&~IFhangmask)|amt;
2629 // Change indent in ps.curstate by delta.
2631 changeindent(Pstate* ps, int delta)
2635 amt = ((ps->curstate&IFindentmask) >> IFindentshift) + delta;
2638 fprint(2, "warning: indent went negative\n");
2641 ps->curstate = (ps->curstate&~IFindentmask)|(amt << IFindentshift);
2644 // Push val on top of stack, and also return value pushed
2646 push(Stack* stk, int val)
2648 if(stk->n == Nestmax) {
2650 fprint(2, "warning: build stack overflow\n");
2653 stk->slots[stk->n++] = val;
2665 //Return top of stack, using dflt if stack is empty
2667 top(Stack* stk, int dflt)
2671 return stk->slots[stk->n-1];
2674 // pop, then return new top, with dflt if empty
2676 popretnewtop(Stack* stk, int dflt)
2683 return stk->slots[stk->n-1];
2686 // Copy fromstk entries into tostk
2688 copystack(Stack* tostk, Stack* fromstk)
2694 memmove(tostk->slots, fromstk->slots, n*sizeof(int));
2698 popfontstyle(Pstate* ps)
2700 pop(&ps->fntstylestk);
2705 pushfontstyle(Pstate* ps, int sty)
2707 push(&ps->fntstylestk, sty);
2712 popfontsize(Pstate* ps)
2714 pop(&ps->fntsizestk);
2719 pushfontsize(Pstate* ps, int sz)
2721 push(&ps->fntsizestk, sz);
2726 setcurfont(Pstate* ps)
2731 sty = top(&ps->fntstylestk, FntR);
2732 sz = top(&ps->fntsizestk, Normal);
2737 ps->curfont = sty*NumSize + sz;
2748 pushjust(Pstate* ps, int j)
2750 push(&ps->juststk, j);
2755 setcurjust(Pstate* ps)
2760 j = top(&ps->juststk, ALleft);
2761 if(j != ps->curjust) {
2763 state = ps->curstate;
2764 state &= ~(IFrjust|IFcjust);
2767 else if(j == ALright)
2769 ps->curstate = state;
2773 // Do final rearrangement after table parsing is finished
2774 // and assign cells to grid points
2776 finish_table(Table* t)
2784 Tablecell** rowspancell;
2800 t->nrow = nrow = _listlen((List*)rl);
2801 t->rows = (Tablerow*)emalloc(nrow * sizeof(Tablerow));
2804 for(row = rl; row != nil; row = rownext) {
2805 // copy the data from the allocated Tablerow into the array slot
2807 rownext = row->next;
2813 // If rowspan is > 1 but this is the last row,
2814 // reset the rowspan
2815 if(c != nil && c->rowspan > 1 && r == nrow-2)
2818 // reverse row->cells list (along nextinrow pointers)
2821 cnext = c->nextinrow;
2822 c->nextinrow = row->cells;
2824 rcols += c->colspan;
2831 t->cols = (Tablecol*)emalloc(ncol * sizeof(Tablecol));
2833 // Reverse cells just so they are drawn in source order.
2834 // Also, trim their contents so they don't end in whitespace.
2835 t->cells = (Tablecell*)_revlist((List*)t->cells);
2836 for(c = t->cells; c != nil; c= c->next)
2838 t->grid = (Tablecell***)emalloc(nrow * sizeof(Tablecell**));
2839 for(i = 0; i < nrow; i++)
2840 t->grid[i] = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2842 // The following arrays keep track of cells that are spanning
2843 // multiple rows; rowspancnt[i] is the number of rows left
2844 // to be spanned in column i.
2845 // When done, cell's (row,col) is upper left grid point.
2846 rowspancnt = (int*)emalloc(ncol * sizeof(int));
2847 rowspancell = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2848 for(ri = 0; ri < nrow; ri++) {
2852 while(ci < ncol || cl != nil) {
2853 if(ci < ncol && rowspancnt[ci] > 0) {
2854 t->grid[ri][ci] = rowspancell[ci];
2867 if(ci + cspan > ncol) {
2868 // because of row spanning, we calculated
2869 // ncol incorrectly; adjust it
2870 newncol = ci + cspan;
2871 t->cols = (Tablecol*)erealloc(t->cols, newncol * sizeof(Tablecol));
2872 rowspancnt = (int*)erealloc(rowspancnt, newncol * sizeof(int));
2873 rowspancell = (Tablecell**)erealloc(rowspancell, newncol * sizeof(Tablecell*));
2875 memset(t->cols+ncol, 0, k*sizeof(Tablecol));
2876 memset(rowspancnt+ncol, 0, k*sizeof(int));
2877 memset(rowspancell+ncol, 0, k*sizeof(Tablecell*));
2878 for(j = 0; j < nrow; j++) {
2879 t->grid[j] = (Tablecell**)erealloc(t->grid[j], newncol * sizeof(Tablecell*));
2880 memset(t->grid[j], 0, k*sizeof(Tablecell*));
2882 t->ncol = ncol = newncol;
2886 for(i = 0; i < cspan; i++) {
2887 t->grid[ri][ci] = c;
2889 rowspancnt[ci] = rspan - 1;
2890 rowspancell[ci] = c;
2899 // Remove tail of cell content until it isn't whitespace.
2901 trim_cell(Tablecell* c)
2914 while(c->content != nil && dropping) {
2917 while(p->next != nil) {
2922 if(!(p->state&IFnobrk)) {
2923 if(p->tag == Itexttag) {
2926 _splitr(s, _Strlen(s), notwhitespace, &x, &nx, &y, &ny);
2927 if(nx != 0 && ny != 0) {
2928 q->s = _Strndup(x, nx);
2944 // Caller must free answer (eventually).
2946 listmark(uchar ty, int n)
2959 s[0] = (ty == LTdisc)? 0x2022 // bullet
2960 : ((ty == LTsquare)? 0x220e // filled square
2961 : 0x2218); // degree
2969 t = _Stradd(s, t, n2);
2980 s = _newstr((n <= 25)? 2 : 3);
2986 s[i++] = n2 + (ty == LTa)? 'a' : 'A';
2988 s[i++] = n + (ty == LTa)? 'a' : 'A';
2997 fprint(2, "warning: unimplemented roman number > %d\n", NROMAN);
3003 for(i = 0; i < n2; i++)
3004 s[i] = (ty == LTi)? tolower(t[i]) : t[i];
3012 // Find map with given name in di.maps.
3013 // If not there, add one, copying name.
3014 // Ownership of map remains with di->maps list.
3016 getmap(Docinfo* di, Rune* name)
3020 for(m = di->maps; m != nil; m = m->next) {
3021 if(!_Strcmp(name, m->name))
3024 m = (Map*)emalloc(sizeof(Map));
3025 m->name = _Strdup(name);
3032 // Transfers ownership of href to Area
3034 newarea(int shape, Rune* href, int target, Area* link)
3038 a = (Area*)emalloc(sizeof(Area));
3046 // Return string value associated with attid in tok, nil if none.
3047 // Caller must free the result (eventually).
3049 aval(Token* tok, int attid)
3053 _tokaval(tok, attid, &ans, 1); // transfers string ownership from token to ans
3057 // Like aval, but use dflt if there was no such attribute in tok.
3058 // Caller must free the result (eventually).
3060 astrval(Token* tok, int attid, Rune* dflt)
3064 if(_tokaval(tok, attid, &ans, 1))
3065 return ans; // transfers string ownership from token to ans
3067 return _Strdup(dflt);
3070 // Here we're supposed to convert to an int,
3071 // and have a default when not found
3073 aintval(Token* tok, int attid, int dflt)
3077 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
3083 // Like aintval, but result should be >= 0
3085 auintval(Token* tok, int attid, int dflt)
3090 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
3094 return v >= 0? v : 0;
3098 // int conversion, but with possible error check (if warning)
3105 ans = _Strtol(s, &eptr, 10);
3108 eptr = _Strclass(eptr, notwhitespace);
3110 fprint(2, "warning: expected integer, got %S\n", s);
3116 // Attribute value when need a table to convert strings to ints
3118 atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt)
3124 if(_tokaval(tok, attid, &aval, 0)) {
3125 if(!_lookup(tab, ntab, aval, _Strlen(aval), &ans)) {
3128 fprint(2, "warning: name not found in table lookup: %S\n", aval);
3134 // Attribute value when supposed to be a color
3136 acolorval(Token* tok, int attid, int dflt)
3142 if(_tokaval(tok, attid, &aval, 0))
3143 ans = color(aval, dflt);
3147 // Attribute value when supposed to be a target frame name
3149 atargval(Token* tok, int dflt)
3155 if(_tokaval(tok, Atarget, &aval, 0)){
3156 ans = targetid(aval);
3161 // special for list types, where "i" and "I" are different,
3162 // but "square" and "SQUARE" are the same
3164 listtyval(Token* tok, int dflt)
3171 if(_tokaval(tok, Atype, &aval, 0)) {
3191 fprint(2, "warning: unknown list element type %c\n", aval[0]);
3195 if(!_Strncmpci(aval, n, L(Lcircle)))
3197 else if(!_Strncmpci(aval, n, L(Ldisc)))
3199 else if(!_Strncmpci(aval, n, L(Lsquare)))
3203 fprint(2, "warning: unknown list element type %S\n", aval);
3210 // Attribute value when value is a URL, possibly relative to base.
3211 // FOR NOW: leave the url relative.
3212 // Caller must free the result (eventually).
3214 aurlval(Token* tok, int attid, Rune* dflt, Rune* base)
3221 if(_tokaval(tok, attid, &url, 0) && url != nil)
3222 ans = removeallwhite(url);
3224 ans = _Strdup(dflt);
3228 // Return copy of s but with all whitespace (even internal) removed.
3229 // This fixes some buggy URL specification strings.
3231 removeallwhite(Rune* s)
3241 for(i = 0; i < n; i++) {
3243 if(c >= 256 || !isspace(c))
3249 for(i = 0; i < n; i++) {
3251 if(c >= 256 || !isspace(c))
3261 // Attribute value when mere presence of attr implies value of 1,
3262 // but if there is an integer there, return it as the value.
3264 aflagval(Token* tok, int attid)
3270 if(_tokaval(tok, attid, &sval, 0)) {
3279 makealign(int halign, int valign)
3288 // Make an Align (two alignments, horizontal and vertical)
3293 atabval(tok, Aalign, align_tab, NALIGNTAB, ALnone),
3294 atabval(tok, Avalign, align_tab, NALIGNTAB, ALnone));
3297 // Make a Dimen, based on value of attid attr
3299 adimen(Token* tok, int attid)
3303 if(_tokaval(tok, attid, &wd, 0))
3304 return parsedim(wd, _Strlen(wd));
3306 return makedimen(Dnone, 0);
3309 // Parse s[0:n] as num[.[num]][unit][%|*]
3311 parsedim(Rune* s, int ns)
3328 _splitl(s, ns, L(Lnot0to9), &l, &nl, &r, &nr);
3330 spec = 1000*_Strtol(l, nil, 10);
3331 if(nr > 0 && r[0] == '.') {
3332 _splitl(r+1, nr-1, L(Lnot0to9), &f, &nf, &r, &nr);
3335 for(i = 0; i < nf; i++) {
3336 spec = spec + mul*(f[i]-'0');
3348 if(!_Strncmpci(units, 2, L(Lpt)))
3349 spec = (spec*Tkdpi)/72;
3350 else if(!_Strncmpci(units, 2, L(Lpi)))
3351 spec = (spec*12*Tkdpi)/72;
3352 else if(!_Strncmpci(units, 2, L(Lin)))
3354 else if(!_Strncmpci(units, 2, L(Lcm)))
3355 spec = (spec*100*Tkdpi)/254;
3356 else if(!_Strncmpci(units, 2, L(Lmm)))
3357 spec = (spec*10*Tkdpi)/254;
3358 else if(!_Strncmpci(units, 2, L(Lem)))
3362 fprint(2, "warning: unknown units %C%Cs\n", units[0], units[1]);
3368 else if(r[0] == '*')
3374 else if(nr == 1 && r[0] == '*') {
3378 return makedimen(kind, spec);
3382 setdimarray(Token* tok, int attid, Dimen** pans, int* panslen)
3388 Rune* a[SMALLBUFSIZE];
3389 int an[SMALLBUFSIZE];
3391 if(_tokaval(tok, attid, &s, 0)) {
3392 nc = _splitall(s, _Strlen(s), L(Lcommaspace), a, an, SMALLBUFSIZE);
3394 d = (Dimen*)emalloc(nc * sizeof(Dimen));
3395 for(k = 0; k < nc; k++) {
3396 d[k] = parsedim(a[k], an[k]);
3408 makebackground(Rune* imageurl, int color)
3412 bg.image = imageurl;
3418 newitext(Rune* s, int fnt, int fg, int voff, int ul)
3423 t = (Itext*)emalloc(sizeof(Itext));
3424 t->item.tag = Itexttag;
3434 newirule(int align, int size, int noshade, Dimen wspec)
3438 r = (Irule*)emalloc(sizeof(Irule));
3439 r->item.tag = Iruletag;
3442 r->noshade = noshade;
3447 // Map is owned elsewhere.
3449 newiimage(Rune* src, Rune* altrep, int align, int width, int height,
3450 int hspace, int vspace, int border, int ismap, Map* map)
3458 i = (Iimage*)emalloc(sizeof(Iimage));
3459 i->item.tag = Iimagetag;
3460 i->item.state = state;
3465 i->imheight = height;
3475 newiformfield(Formfield* ff)
3479 f = (Iformfield*)emalloc(sizeof(Iformfield));
3480 f->item.tag = Iformfieldtag;
3486 newitable(Table* tab)
3490 t = (Itable*)emalloc(sizeof(Itable));
3491 t->item.tag = Itabletag;
3497 newifloat(Item* it, int side)
3501 f = (Ifloat*)emalloc(sizeof(Ifloat));
3502 f->_item.tag = Ifloattag;
3503 f->_item.state = IFwrap;
3510 newispacer(int spkind)
3514 s = (Ispacer*)emalloc(sizeof(Ispacer));
3515 s->item.tag = Ispacertag;
3520 // Free one item (caller must deal with next pointer)
3532 free(((Itext*)it)->s);
3540 freeformfield(((Iformfield*)it)->formfield);
3543 freetable(((Itable*)it)->table);
3546 freeitem(((Ifloat*)it)->item);
3555 freescriptevents(ga->events);
3560 // Free list of items chained through next pointer
3562 freeitems(Item* ithead)
3576 freeformfield(Formfield* ff)
3586 for(o = ff->options; o != nil; o = onext) {
3604 // We'll find all the unique cells via t->cells and next pointers.
3605 // (Other pointers to cells in the table are duplicates of these)
3606 for(c = t->cells; c != nil; c = cnext) {
3608 freeitems(c->content);
3610 if(t->grid != nil) {
3611 for(i = 0; i < t->nrow; i++)
3617 freeitems(t->caption);
3629 // Form doesn't own its fields (Iformfield items do)
3634 freeforms(Form* fhead)
3639 for(f = fhead; f != nil; f = fnext) {
3646 freeanchor(Anchor* a)
3657 freeanchors(Anchor* ahead)
3662 for(a = ahead; a != nil; a = anext) {
3669 freedestanchor(DestAnchor* da)
3679 freedestanchors(DestAnchor* dahead)
3684 for(da = dahead; da != nil; da = danext) {
3699 static void freekidinfos(Kidinfo* khead);
3702 freekidinfo(Kidinfo* k)
3707 freekidinfos(k->kidinfos);
3717 freekidinfos(Kidinfo* khead)
3722 for(k = khead; k != nil; k = knext) {
3738 for(a = m->areas; a != nil; a = anext) {
3746 freemaps(Map* mhead)
3751 for(m = mhead; m != nil; m = mnext) {
3758 freedocinfo(Docinfo* d)
3764 freeitem((Item*)d->backgrounditem);
3766 freekidinfos(d->kidinfo);
3767 freeanchors(d->anchors);
3768 freedestanchors(d->dests);
3769 freeforms(d->forms);
3771 // tables, images, and formfields are freed when
3772 // the items pointing at them are freed
3776 // Currently, someone else owns all the memory
3777 // pointed to by things in a Pstate.
3779 freepstate(Pstate* p)
3785 freepstatestack(Pstate* pshead)
3790 for(p = pshead; p != nil; p = pnext) {
3815 char buf[BIGBUFSIZE];
3817 it = va_arg(f->args, Item*);
3823 cl = state&(IFcleft|IFcright);
3826 if(cl == (IFcleft|IFcright))
3828 else if(cl == IFcleft)
3833 bi = snprint(buf, nbuf, "brk(%d%s)", (state&IFbrksp)? 1 : 0, p);
3836 bi += snprint(buf+bi, nbuf-bi, " nobrk");
3838 bi += snprint(buf+bi, nbuf-bi, " nowrap");
3840 bi += snprint(buf+bi, nbuf-bi, " rjust");
3842 bi += snprint(buf+bi, nbuf-bi, " cjust");
3844 bi += snprint(buf+bi, nbuf-bi, " smap");
3845 indent = (state&IFindentmask) >> IFindentshift;
3847 bi += snprint(buf+bi, nbuf-bi, " indent=%d", indent);
3848 hang = state&IFhangmask;
3850 bi += snprint(buf+bi, nbuf-bi, " hang=%d", hang);
3855 bi += snprint(buf+bi, nbuf-bi, " Text '%S', fnt=%d, fg=%x", t->s, t->fnt, t->fg);
3860 bi += snprint(buf+bi, nbuf-bi, "Rule size=%d, al=%S, wspec=", r->size, stringalign(r->align));
3861 bi += dimprint(buf+bi, nbuf-bi, r->wspec);
3866 bi += snprint(buf+bi, nbuf-bi,
3867 "Image src=%S, alt=%S, al=%S, w=%d, h=%d hsp=%d, vsp=%d, bd=%d, map=%S",
3868 i->imsrc, i->altrep? i->altrep : L(Lempty), stringalign(i->align), i->imwidth, i->imheight,
3869 i->hspace, i->vspace, i->border, i->map?i->map->name : L(Lempty));
3873 ff = ((Iformfield*)it)->formfield;
3874 if(ff->ftype == Ftextarea)
3876 else if(ff->ftype == Fselect)
3879 ty = _revlookup(input_tab, NINPUTTAB, ff->ftype);
3883 bi += snprint(buf+bi, nbuf-bi, "Formfield %S, fieldid=%d, formid=%d, name=%S, value=%S",
3884 ty, ff->fieldid, ff->form->formid, ff->name? ff->name : L(Lempty),
3885 ff->value? ff->value : L(Lempty));
3889 tab = ((Itable*)it)->table;
3890 bi += snprint(buf+bi, nbuf-bi, "Table tableid=%d, width=", tab->tableid);
3891 bi += dimprint(buf+bi, nbuf-bi, tab->width);
3892 bi += snprint(buf+bi, nbuf-bi, ", nrow=%d, ncol=%d, ncell=%d, totw=%d, toth=%d\n",
3893 tab->nrow, tab->ncol, tab->ncell, tab->totw, tab->toth);
3894 for(c = tab->cells; c != nil; c = c->next)
3895 bi += snprint(buf+bi, nbuf-bi, "Cell %d.%d, at (%d,%d) ",
3896 tab->tableid, c->cellid, c->row, c->col);
3897 bi += snprint(buf+bi, nbuf-bi, "End of Table %d", tab->tableid);
3902 bi += snprint(buf+bi, nbuf-bi, "Float, x=%d y=%d, side=%S, it=%I",
3903 fl->x, fl->y, stringalign(fl->side), fl->item);
3904 bi += snprint(buf+bi, nbuf-bi, "\n\t");
3909 switch(((Ispacer*)it)->spkind) {
3920 bi += snprint(buf+bi, nbuf-bi, "Spacer %s ", p);
3923 bi += snprint(buf+bi, nbuf-bi, " w=%d, h=%d, a=%d, anchor=%d\n",
3924 it->width, it->height, it->ascent, it->anchorid);
3926 return fmtstrcpy(f, buf);
3929 // String version of alignment 'a'
3935 s = _revlookup(align_tab, NALIGNTAB, a);
3941 // Put at most nbuf chars of representation of d into buf,
3942 // and return number of characters put
3944 dimprint(char* buf, int nbuf, Dimen d)
3950 n += snprint(buf, nbuf, "%d", dimenspec(d));
3960 printitems(Item* items, char* msg)
3964 fprint(2, "%s\n", msg);
3967 fprint(2, "%I", il);
3973 newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, SEvent* events)
3977 g = (Genattr*)emalloc(sizeof(Genattr));
3987 newformfield(int ftype, int fieldid, Form* form, Rune* name,
3988 Rune* value, int size, int maxlength, Formfield* link)
3992 ff = (Formfield*)emalloc(sizeof(Formfield));
3994 ff->fieldid = fieldid;
3999 ff->maxlength = maxlength;
4005 // Transfers ownership of value and display to Option.
4007 newoption(int selected, Rune* value, Rune* display, Option* link)
4011 o = (Option*)emalloc(sizeof(Option));
4012 o->selected = selected;
4014 o->display = display;
4020 newform(int formid, Rune* name, Rune* action, int target, int method, Form* link)
4024 f = (Form*)emalloc(sizeof(Form));
4037 newtable(int tableid, Align align, Dimen width, int border,
4038 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link)
4042 t = (Table*)emalloc(sizeof(Table));
4043 t->tableid = tableid;
4047 t->cellspacing = cellspacing;
4048 t->cellpadding = cellpadding;
4050 t->caption_place = ALbottom;
4051 t->caption_lay = nil;
4059 newtablerow(Align align, Background bg, int flags, Tablerow* link)
4063 tr = (Tablerow*)emalloc(sizeof(Tablerow));
4065 tr->background = bg;
4072 newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec, int hspec,
4073 Background bg, int flags, Tablecell* link)
4077 c = (Tablecell*)emalloc(sizeof(Tablecell));
4080 c->rowspan = rowspan;
4081 c->colspan = colspan;
4092 newanchor(int index, Rune* name, Rune* href, int target, Anchor* link)
4096 a = (Anchor*)emalloc(sizeof(Anchor));
4106 newdestanchor(int index, Rune* name, Item* item, DestAnchor* link)
4110 d = (DestAnchor*)emalloc(sizeof(DestAnchor));
4119 newscriptevent(int type, Rune* script, SEvent* link)
4123 ans = (SEvent*)emalloc(sizeof(SEvent));
4125 ans->script = script;
4131 freescriptevents(SEvent* ehead)
4146 makedimen(int kind, int spec)
4150 if(spec&Dkindmask) {
4152 fprint(2, "warning: dimension spec too big: %d\n", spec);
4155 d.kindspec = kind|spec;
4162 return (d.kindspec&Dkindmask);
4168 return (d.kindspec&Dspecmask);
4172 newkidinfo(int isframeset, Kidinfo* link)
4176 ki = (Kidinfo*)emalloc(sizeof(Kidinfo));
4177 ki->isframeset = isframeset;
4179 ki->flags = FRhscrollauto|FRvscrollauto;
4180 ki->marginw = FRKIDMARGIN;
4181 ki->marginh = FRKIDMARGIN;
4193 d = (Docinfo*)emalloc(sizeof(Docinfo));
4199 resetdocinfo(Docinfo* d)
4201 memset(d, 0, sizeof(Docinfo));
4202 d->background = makebackground(nil, White);
4208 d->chset = ISO_8859_1;
4209 d->scripttype = TextJavascript;
4213 // Use targetmap array to keep track of name <-> targetid mapping.
4214 // Use real malloc(), and never free
4219 targetmap = (StringInt*)emalloc(targetmapsize*sizeof(StringInt));
4220 memset(targetmap, 0, targetmapsize*sizeof(StringInt));
4221 targetmap[0].key = _Strdup(L(L_top));
4222 targetmap[0].val = FTtop;
4223 targetmap[1].key = _Strdup(L(L_self));
4224 targetmap[1].val = FTself;
4225 targetmap[2].key = _Strdup(L(L_parent));
4226 targetmap[2].val = FTparent;
4227 targetmap[3].key = _Strdup(L(L_blank));
4228 targetmap[3].val = FTblank;
4241 for(i = 0; i < ntargets; i++)
4242 if(_Strcmp(s, targetmap[i].key) == 0)
4243 return targetmap[i].val;
4244 if(i >= targetmapsize) {
4245 targetmapsize += 10;
4246 targetmap = (StringInt*)erealloc(targetmap, targetmapsize*sizeof(StringInt));
4248 targetmap[i].key = (Rune*)emalloc((n+1)*sizeof(Rune));
4249 memmove(targetmap[i].key, s, (n+1)*sizeof(Rune));
4250 targetmap[i].val = i;
4256 targetname(int targid)
4260 for(i = 0; i < ntargets; i++)
4261 if(targetmap[i].val == targid)
4262 return targetmap[i].key;
4263 return L(Lquestion);
4266 // Convert HTML color spec to RGB value, returning dflt if can't.
4267 // Argument is supposed to be a valid HTML color, or "".
4268 // Return the RGB value of the color, using dflt if s
4269 // is nil or an invalid color.
4271 color(Rune* s, int dflt)
4278 if(_lookup(color_tab, NCOLORS, s, _Strlen(s), &v))
4282 v = _Strtol(s, &rest, 16);
4290 #define HUGEPIX 10000
4292 // A "shallow" validitem, that doesn't follow next links
4293 // or descend into tables.
4304 ok = (i->tag >= Itexttag && i->tag <= Ispacertag) &&
4305 (i->next == nil || validptr(i->next)) &&
4306 (i->width >= 0 && i->width < HUGEPIX) &&
4307 (i->height >= 0 && i->height < HUGEPIX) &&
4308 (i->ascent > -HUGEPIX && i->ascent < HUGEPIX) &&
4309 (i->anchorid >= 0) &&
4310 (i->genattr == nil || validptr(i->genattr));
4311 // also, could check state for ridiculous combinations
4312 // also, could check anchorid for within-doc-range
4317 ok = validStr(ti->s) &&
4318 (ti->fnt >= 0 && ti->fnt < NumStyle*NumSize) &&
4319 (ti->ul == ULnone || ti->ul == ULunder || ti->ul == ULmid);
4323 ok = (validvalign(ri->align) || validhalign(ri->align)) &&
4324 (ri->size >=0 && ri->size < HUGEPIX);
4328 ok = (ii->imsrc == nil || validptr(ii->imsrc)) &&
4329 (ii->item.width >= 0 && ii->item.width < HUGEPIX) &&
4330 (ii->item.height >= 0 && ii->item.height < HUGEPIX) &&
4331 (ii->imwidth >= 0 && ii->imwidth < HUGEPIX) &&
4332 (ii->imheight >= 0 && ii->imheight < HUGEPIX) &&
4333 (ii->altrep == nil || validStr(ii->altrep)) &&
4334 (ii->map == nil || validptr(ii->map)) &&
4335 (validvalign(ii->align) || validhalign(ii->align)) &&
4336 (ii->nextimage == nil || validptr(ii->nextimage));
4339 ok = validformfield(((Iformfield*)i)->formfield);
4342 ok = validptr((Itable*)i);
4346 ok = (fi->side == ALleft || fi->side == ALright) &&
4347 validitem(fi->item) &&
4348 (fi->item->tag == Iimagetag || fi->item->tag == Itabletag);
4351 a = ((Ispacer*)i)->spkind;
4352 ok = a==ISPnull || a==ISPvline || a==ISPhspace || a==ISPgeneral;
4360 // "deep" validation, that checks whole list of items,
4361 // and descends into tables and floated tables.
4362 // nil is ok for argument.
4370 while(i != nil && ok) {
4373 if(i->tag == Itabletag) {
4374 ok = validtable(((Itable*)i)->table);
4376 else if(i->tag == Ifloattag) {
4377 ii = ((Ifloat*)i)->item;
4378 if(ii->tag == Itabletag)
4379 ok = validtable(((Itable*)ii)->table);
4383 fprint(2, "invalid item: %I\n", i);
4391 validformfield(Formfield* f)
4395 ok = (f->next == nil || validptr(f->next)) &&
4396 (f->ftype >= 0 && f->ftype <= Ftextarea) &&
4398 (f->form == nil || validptr(f->form)) &&
4399 (f->name == nil || validStr(f->name)) &&
4400 (f->value == nil || validStr(f->value)) &&
4401 (f->options == nil || validptr(f->options)) &&
4402 (f->image == nil || validitem(f->image)) &&
4403 (f->events == nil || validptr(f->events));
4404 // when all built, should have f->fieldid < f->form->nfields,
4405 // but this may be called during build...
4409 // "deep" validation -- checks cell contents too
4411 validtable(Table* t)
4417 ok = (t->next == nil || validptr(t->next)) &&
4421 validalign(t->align) &&
4422 validdimen(t->width) &&
4423 (t->border >= 0 && t->border < HUGEPIX) &&
4424 (t->cellspacing >= 0 && t->cellspacing < HUGEPIX) &&
4425 (t->cellpadding >= 0 && t->cellpadding < HUGEPIX) &&
4426 validitems(t->caption) &&
4427 (t->caption_place == ALtop || t->caption_place == ALbottom) &&
4428 (t->totw >= 0 && t->totw < HUGEPIX) &&
4429 (t->toth >= 0 && t->toth < HUGEPIX) &&
4430 (t->tabletok == nil || validptr(t->tabletok));
4431 // during parsing, t->rows has list;
4432 // only when parsing is done is t->nrow set > 0
4433 if(ok && t->nrow > 0 && t->ncol > 0) {
4434 // table is "finished"
4435 for(i = 0; i < t->nrow && ok; i++)
4436 ok = validtablerow(t->rows+i);
4437 for(j = 0; j < t->ncol && ok; j++)
4438 ok = validtablecol(t->cols+j);
4439 for(c = t->cells; c != nil && ok; c = c->next)
4440 ok = validtablecell(c);
4441 for(i = 0; i < t->nrow && ok; i++)
4442 for(j = 0; j < t->ncol && ok; j++)
4443 ok = validptr(t->grid[i][j]);
4451 return a == ALnone || a == ALmiddle || a == ALbottom || a == ALtop || a == ALbaseline;
4457 return a == ALnone || a == ALleft || a == ALcenter || a == ALright ||
4458 a == ALjustify || a == ALchar;
4464 return validhalign(a.halign) && validvalign(a.valign);
4474 s = d.kindspec&Dspecmask;
4475 switch(d.kindspec&Dkindmask) {
4491 validtablerow(Tablerow* r)
4493 return (r->cells == nil || validptr(r->cells)) &&
4494 (r->height >= 0 && r->height < HUGEPIX) &&
4495 (r->ascent > -HUGEPIX && r->ascent < HUGEPIX) &&
4496 validalign(r->align);
4500 validtablecol(Tablecol* c)
4502 return c->width >= 0 && c->width < HUGEPIX
4503 && validalign(c->align);
4507 validtablecell(Tablecell* c)
4511 ok = (c->next == nil || validptr(c->next)) &&
4512 (c->nextinrow == nil || validptr(c->nextinrow)) &&
4513 (c->content == nil || validptr(c->content)) &&
4514 (c->lay == nil || validptr(c->lay)) &&
4517 validalign(c->align) &&
4518 validdimen(c->wspec) &&
4522 if(c->content != nil)
4523 ok = validitems(c->content);
4531 // TODO: a better job of this.
4532 // For now, just dereference, which cause a bomb
4543 return s != nil && validptr(s);