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]= {
169 [Taddress] BLBA, [Tblockquote] BLBA, [Tcenter] BL,
170 [Tdir] BLBA, [Tdiv] BL, [Tdd] BL, [Tdl] BLBA,
171 [Tdt] BL, [Tform] BLBA,
172 // headings and tables get breaks added manually
173 [Th1] BL, [Th2] BL, [Th3] BL,
174 [Th4] BL, [Th5] BL, [Th6] BL,
175 [Thr] BL, [Tisindex] BLBA, [Tli] BL, [Tmenu] BLBA,
176 [Tol] BLBA, [Tp] BLBA, [Tpre] BLBA,
184 // attrinfo is information about attributes.
185 // The AGEN value means that the attribute is generic (applies to almost all elements)
186 static uchar attrinfo[Numattrs]= {
187 [Aid] AGEN, [Aclass] AGEN, [Astyle] AGEN, [Atitle] AGEN,
188 [Aonblur] AGEN, [Aonchange] AGEN, [Aonclick] AGEN,
189 [Aondblclick] AGEN, [Aonfocus] AGEN, [Aonkeypress] AGEN,
190 [Aonkeyup] AGEN, [Aonload] AGEN, [Aonmousedown] AGEN,
191 [Aonmousemove] AGEN, [Aonmouseout] AGEN, [Aonmouseover] AGEN,
192 [Aonmouseup] AGEN, [Aonreset] AGEN, [Aonselect] AGEN,
193 [Aonsubmit] AGEN, [Aonunload] AGEN
196 static uchar scriptev[Numattrs]= {
197 [Aonblur] SEonblur, [Aonchange] SEonchange, [Aonclick] SEonclick,
198 [Aondblclick] SEondblclick, [Aonfocus] SEonfocus, [Aonkeypress] SEonkeypress,
199 [Aonkeyup] SEonkeyup, [Aonload] SEonload, [Aonmousedown] SEonmousedown,
200 [Aonmousemove] SEonmousemove, [Aonmouseout] SEonmouseout, [Aonmouseover] SEonmouseover,
201 [Aonmouseup] SEonmouseup, [Aonreset] SEonreset, [Aonselect] SEonselect,
202 [Aonsubmit] SEonsubmit, [Aonunload] SEonunload
205 // Color lookup table
206 static StringInt *color_tab;
207 static AsciiInt _color_tab[] = {
211 {"fuchsia", 0xFF00FF},
215 {"maroon", 0x800000},
218 {"purple", 0x800080},
220 {"silver", 0xC0C0C0},
225 #define NCOLORS (sizeof(color_tab)/sizeof(StringInt))
227 static StringInt *targetmap;
228 static int targetmapsize;
231 static int buildinited = 0;
233 #define SMALLBUFSIZE 240
234 #define BIGBUFSIZE 2000
239 static Align aalign(Token* tok);
240 static int acolorval(Token* tok, int attid, int dflt);
241 static void addbrk(Pstate* ps, int sp, int clr);
242 static void additem(Pstate* ps, Item* it, Token* tok);
243 static void addlinebrk(Pstate* ps, int clr);
244 static void addnbsp(Pstate* ps);
245 static void addtext(Pstate* ps, Rune* s);
246 static Dimen adimen(Token* tok, int attid);
247 static int aflagval(Token* tok, int attid);
248 static int aintval(Token* tok, int attid, int dflt);
249 static Rune* astrval(Token* tok, int attid, Rune* dflt);
250 static int atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt);
251 static int atargval(Token* tok, int dflt);
252 static int auintval(Token* tok, int attid, int dflt);
253 static Rune* aurlval(Token* tok, int attid, Rune* dflt, Rune* base);
254 static Rune* aval(Token* tok, int attid);
255 static void buildinit(void);
256 static Pstate* cell_pstate(Pstate* oldps, int ishead);
257 static void changehang(Pstate* ps, int delta);
258 static void changeindent(Pstate* ps, int delta);
259 static int color(Rune* s, int dflt);
260 static void copystack(Stack* tostk, Stack* fromstk);
261 static int dimprint(char* buf, int nbuf, Dimen d);
262 static Pstate* finishcell(Table* curtab, Pstate* psstk);
263 static void finish_table(Table* t);
264 static void freeanchor(Anchor* a);
265 static void freedestanchor(DestAnchor* da);
266 static void freeform(Form* f);
267 static void freeformfield(Formfield* ff);
268 static void freeitem(Item* it);
269 static void freepstate(Pstate* p);
270 static void freepstatestack(Pstate* pshead);
271 static void freescriptevents(SEvent* ehead);
272 static void freetable(Table* t);
273 static Map* getmap(Docinfo* di, Rune* name);
274 static Rune* getpcdata(Token* toks, int tokslen, int* ptoki);
275 static Pstate* lastps(Pstate* psl);
276 static Rune* listmark(uchar ty, int n);
277 static int listtyval(Token* tok, int dflt);
278 static Align makealign(int halign, int valign);
279 static Background makebackground(Rune* imgurl, int color);
280 static Dimen makedimen(int kind, int spec);
281 static Anchor* newanchor(int index, Rune* name, Rune* href, int target, Anchor* link);
282 static Area* newarea(int shape, Rune* href, int target, Area* link);
283 static DestAnchor* newdestanchor(int index, Rune* name, Item* item, DestAnchor* link);
284 static Docinfo* newdocinfo(void);
285 static Genattr* newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, SEvent* events);
286 static Form* newform(int formid, Rune* name, Rune* action,
287 int target, int method, Form* link);
288 static Formfield* newformfield(int ftype, int fieldid, Form* form, Rune* name,
289 Rune* value, int size, int maxlength, Formfield* link);
290 static Item* newifloat(Item* it, int side);
291 static Item* newiformfield(Formfield* ff);
292 static Item* newiimage(Rune* src, Rune* altrep, int align, int width, int height,
293 int hspace, int vspace, int border, int ismap, Map* map);
294 static Item* newirule(int align, int size, int noshade, Dimen wspec);
295 static Item* newispacer(int spkind);
296 static Item* newitable(Table* t);
297 static ItemSource* newitemsource(Docinfo* di);
298 static Item* newitext(Rune* s, int fnt, int fg, int voff, int ul);
299 static Kidinfo* newkidinfo(int isframeset, Kidinfo* link);
300 static Option* newoption(int selected, Rune* value, Rune* display, Option* link);
301 static Pstate* newpstate(Pstate* link);
302 static SEvent* newscriptevent(int type, Rune* script, SEvent* link);
303 static Table* newtable(int tableid, Align align, Dimen width, int border,
304 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link);
305 static Tablecell* newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec,
306 int hspec, Background bg, int flags, Tablecell* link);
307 static Tablerow* newtablerow(Align align, Background bg, int flags, Tablerow* link);
308 static Dimen parsedim(Rune* s, int ns);
309 static void pop(Stack* stk);
310 static void popfontsize(Pstate* ps);
311 static void popfontstyle(Pstate* ps);
312 static void popjust(Pstate* ps);
313 static int popretnewtop(Stack* stk, int dflt);
314 static int push(Stack* stk, int val);
315 static void pushfontsize(Pstate* ps, int sz);
316 static void pushfontstyle(Pstate* ps, int sty);
317 static void pushjust(Pstate* ps, int j);
318 static Item* textit(Pstate* ps, Rune* s);
319 static Rune* removeallwhite(Rune* s);
320 static void resetdocinfo(Docinfo* d);
321 static void setcurfont(Pstate* ps);
322 static void setcurjust(Pstate* ps);
323 static void setdimarray(Token* tok, int attid, Dimen** pans, int* panslen);
324 static Rune* stringalign(int a);
325 static void targetmapinit(void);
326 static int toint(Rune* s);
327 static int top(Stack* stk, int dflt);
328 static void trim_cell(Tablecell* c);
329 static int validalign(Align a);
330 static int validdimen(Dimen d);
331 static int validformfield(Formfield* f);
332 static int validhalign(int a);
333 static int validptr(void* p);
334 static int validStr(Rune* s);
335 static int validtable(Table* t);
336 static int validtablerow(Tablerow* r);
337 static int validtablecol(Tablecol* c);
338 static int validtablecell(Tablecell* c);
339 static int validvalign(int a);
340 static int Iconv(Fmt *f);
346 roman = cvtstringtab(_roman, nelem(_roman));
347 color_tab = cvtstringinttab(_color_tab, nelem(_color_tab));
348 method_tab = cvtstringinttab(_method_tab, nelem(_method_tab));
349 shape_tab = cvtstringinttab(_shape_tab, nelem(_shape_tab));
350 fscroll_tab = cvtstringinttab(_fscroll_tab, nelem(_fscroll_tab));
351 clear_tab = cvtstringinttab(_clear_tab, nelem(_clear_tab));
352 input_tab = cvtstringinttab(_input_tab, nelem(_input_tab));
353 align_tab = cvtstringinttab(_align_tab, nelem(_align_tab));
355 fmtinstall('I', Iconv);
361 newitemsource(Docinfo* di)
367 if(di->mediatype != TextHtml) {
368 ps->curstate &= ~IFwrap;
370 pushfontstyle(ps, FntT);
372 is = (ItemSource*)emalloc(sizeof(ItemSource));
386 static Item *getitems(ItemSource* is, uchar* data, int datalen);
388 // Parse an html document and create a list of layout items.
389 // Allocate and return document info in *pdi.
390 // When caller is done with the items, it should call
391 // freeitems on the returned result, and then
392 // freedocinfo(*pdi).
394 parsehtml(uchar* data, int datalen, Rune* pagesrc, int mtype, int chset, Docinfo** pdi)
401 di->src = _Strdup(pagesrc);
402 di->base = _Strdup(pagesrc);
403 di->mediatype = mtype;
406 is = newitemsource(di);
407 it = getitems(is, data, datalen);
408 freepstatestack(is->psstk);
413 // Get a group of tokens for lexer, parse them, and create
414 // a list of layout items.
415 // When caller is done with the items, it should call
416 // freeitems on the returned result.
418 getitems(ItemSource* is, uchar* data, int datalen)
493 doscripts = 0; // for now
497 toks = _gettoks(data, datalen, di->chset, di->mediatype, &tokslen);
499 for(; toki < tokslen; toki++) {
502 fprint(2, "build: curstate %ux, token %T\n", ps->curstate, tok);
511 else if(tag < Numtags + RBRA) {
512 brk = blockbrk[tag - RBRA];
517 addbrk(ps, brksp, 0);
523 // check common case first (Data), then switch statement on tag
525 // Lexing didn't pay attention to SGML record boundary rules:
526 // \n after start tag or before end tag to be discarded.
527 // (Lex has already discarded all \r's).
528 // Some pages assume this doesn't happen in <PRE> text,
529 // so we won't do it if literal is true.
530 // BUG: won't discard \n before a start tag that begins
531 // the next bufferful of tokens.
538 pt = toks[toki - 1].tag;
539 // IE and Netscape both ignore this rule (contrary to spec)
540 // if previous tag was img
541 if(pt < Numtags && pt != Timg && j > 0 && s[0] == '\n')
544 if(toki < tokslen - 1) {
545 nt = toks[toki + 1].tag;
546 if(nt >= RBRA && nt < Numtags + RBRA && j > i && s[j - 1] == '\n')
551 s = _Strsubstr(s, i, j);
557 _trimwhite(s, n, &t, &nt);
570 tok->text = nil; // token doesn't own string anymore
576 // Some abbrevs used in following DTD comments
578 // | TT | I | B | U | STRIKE | BIG | SMALL | SUB | SUP
579 // | EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE
580 // | A | IMG | APPLET | FONT | BASEFONT | BR | SCRIPT | MAP
581 // | INPUT | SELECT | TEXTAREA
582 // %block = P | UL | OL | DIR | MENU | DL | PRE | DL | DIV | CENTER
583 // | BLOCKQUOTE | FORM | ISINDEX | HR | TABLE
584 // %flow = (%text | %block)*
585 // %body.content = (%heading | %text | %block | ADDRESS)*
587 // <!ELEMENT A - - (%text) -(A)>
588 // Anchors are not supposed to be nested, but you sometimes see
589 // href anchors inside destination anchors.
591 if(ps->curanchor != 0) {
593 fprint(2, "warning: nested <A> or missing </A>\n");
596 name = aval(tok, Aname);
597 href = aurlval(tok, Ahref, nil, di->base);
598 // ignore rel, rev, and title attrs
600 target = atargval(tok, di->target);
601 di->anchors = newanchor(++is->nanchors, name, href, target, di->anchors);
603 name = _Strdup(name); // for DestAnchor construction, below
604 ps->curanchor = is->nanchors;
605 ps->curfg = push(&ps->fgstk, di->link);
606 ps->curul = push(&ps->ulstk, ULunder);
609 // add a null item to be destination
610 additem(ps, newispacer(ISPnull), tok);
611 di->dests = newdestanchor(++is->nanchors, name, ps->lastit, di->dests);
616 if(ps->curanchor != 0) {
617 ps->curfg = popretnewtop(&ps->fgstk, di->text);
618 ps->curul = popretnewtop(&ps->ulstk, ULnone);
623 // <!ELEMENT APPLET - - (PARAM | %text)* >
624 // We can't do applets, so ignore PARAMS, and let
625 // the %text contents appear for the alternative rep
628 if(warn && tag == Tapplet)
629 fprint(2, "warning: <APPLET> ignored\n");
632 // <!ELEMENT AREA - O EMPTY>
637 fprint(2, "warning: <AREA> not inside <MAP>\n");
640 map->areas = newarea(atabval(tok, Ashape, shape_tab, NSHAPETAB, SHrect),
641 aurlval(tok, Ahref, nil, di->base),
642 atargval(tok, di->target),
644 setdimarray(tok, Acoords, &map->areas->coords, &map->areas->ncoords);
647 // <!ELEMENT (B|STRONG) - - (%text)*>
650 pushfontstyle(ps, FntB);
668 // <!ELEMENT BASE - O EMPTY>
671 di->base = aurlval(tok, Ahref, di->base, di->base);
674 di->target = atargval(tok, di->target);
677 // <!ELEMENT BASEFONT - O EMPTY>
679 ps->adjsize = aintval(tok, Asize, 3) - 3;
682 // <!ELEMENT (BIG|SMALL) - - (%text)*>
690 pushfontsize(ps, sz);
698 // <!ELEMENT BLOCKQUOTE - - %body.content>
700 changeindent(ps, BQTAB);
703 case Tblockquote+RBRA:
704 changeindent(ps, -BQTAB);
707 // <!ELEMENT BODY O O %body.content>
710 bg = makebackground(nil, acolorval(tok, Abgcolor, di->background.color));
711 bgurl = aurlval(tok, Abackground, nil, di->base);
713 if(di->backgrounditem != nil)
714 freeitem((Item*)di->backgrounditem);
715 // really should remove old item from di->images list,
716 // but there should only be one BODY element ...
717 di->backgrounditem = (Iimage*)newiimage(bgurl, nil, ALnone, 0, 0, 0, 0, 0, 0, nil);
718 di->backgrounditem->nextimage = di->images;
719 di->images = di->backgrounditem;
723 di->text = acolorval(tok, Atext, di->text);
724 di->link = acolorval(tok, Alink, di->link);
725 di->vlink = acolorval(tok, Avlink, di->vlink);
726 di->alink = acolorval(tok, Aalink, di->alink);
727 if(di->text != ps->curfg) {
728 ps->curfg = di->text;
734 // HTML spec says ignore things after </body>,
735 // but IE and Netscape don't
739 // <!ELEMENT BR - O EMPTY>
741 addlinebrk(ps, atabval(tok, Aclear, clear_tab, NCLEARTAB, 0));
744 // <!ELEMENT CAPTION - - (%text;)*>
748 fprint(2, "warning: <CAPTION> outside <TABLE>\n");
751 if(curtab->caption != nil) {
753 fprint(2, "warning: more than one <CAPTION> in <TABLE>\n");
757 curtab->caption_place = atabval(tok, Aalign, align_tab, NALIGNTAB, ALtop);
762 if(curtab == nil || nextps == nil) {
764 fprint(2, "warning: unexpected </CAPTION>\n");
767 curtab->caption = ps->items->next;
777 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust);
786 // <!ELEMENT DD - O %flow >
788 if(ps->hangstk.n == 0) {
790 fprint(2, "warning: <DD> not inside <DL\n");
793 h = top(&ps->hangstk, 0);
795 changehang(ps, -10*LISTTAB);
798 push(&ps->hangstk, 0);
801 //<!ELEMENT (DIR|MENU) - - (LI)+ -(%block) >
802 //<!ELEMENT (OL|UL) - - (LI)+>
807 changeindent(ps, LISTTAB);
808 push(&ps->listtypestk, listtyval(tok, (tag==Tol)? LT1 : LTdisc));
809 push(&ps->listcntstk, aintval(tok, Astart, 1));
816 if(ps->listtypestk.n == 0) {
818 fprint(2, "warning: %T ended no list\n", tok);
822 pop(&ps->listtypestk);
823 pop(&ps->listcntstk);
824 changeindent(ps, -LISTTAB);
827 // <!ELEMENT DL - - (DT|DD)+ >
829 changeindent(ps, LISTTAB);
830 push(&ps->hangstk, 0);
834 if(ps->hangstk.n == 0) {
836 fprint(2, "warning: unexpected </DL>\n");
839 changeindent(ps, -LISTTAB);
840 if(top(&ps->hangstk, 0) != 0)
841 changehang(ps, -10*LISTTAB);
845 // <!ELEMENT DT - O (%text)* >
847 if(ps->hangstk.n == 0) {
849 fprint(2, "warning: <DT> not inside <DL>\n");
852 h = top(&ps->hangstk, 0);
855 changehang(ps, -10*LISTTAB);
856 changehang(ps, 10*LISTTAB);
857 push(&ps->hangstk, 1);
860 // <!ELEMENT FONT - - (%text)*>
862 sz = top(&ps->fntsizestk, Normal);
863 if(_tokaval(tok, Asize, &nsz, 0)) {
864 if(_prefix(L(Lplus), nsz))
865 sz = Normal + _Strtol(nsz+1, nil, 10) + ps->adjsize;
866 else if(_prefix(L(Lminus), nsz))
867 sz = Normal - _Strtol(nsz+1, nil, 10) + ps->adjsize;
869 sz = Normal + (_Strtol(nsz, nil, 10) - 3);
871 ps->curfg = push(&ps->fgstk, acolorval(tok, Acolor, ps->curfg));
872 pushfontsize(ps, sz);
876 if(ps->fgstk.n == 0) {
878 fprint(2, "warning: unexpected </FONT>\n");
881 ps->curfg = popretnewtop(&ps->fgstk, di->text);
885 // <!ELEMENT FORM - - %body.content -(FORM) >
887 if(is->curform != nil) {
889 fprint(2, "warning: <FORM> nested inside another\n");
892 action = aurlval(tok, Aaction, di->base, di->base);
894 name = astrval(tok, Aname, s);
897 target = atargval(tok, di->target);
898 method = atabval(tok, Amethod, method_tab, NMETHODTAB, HGet);
899 if(warn && _tokaval(tok, Aenctype, &enctype, 0) &&
900 _Strcmp(enctype, L(Lappl_form)))
901 fprint(2, "form enctype %S not handled\n", enctype);
902 frm = newform(++is->nforms, name, action, target, method, di->forms);
908 if(is->curform == nil) {
910 fprint(2, "warning: unexpected </FORM>\n");
913 // put fields back in input order
914 is->curform->fields = (Formfield*)_revlist((List*)is->curform->fields);
918 // <!ELEMENT FRAME - O EMPTY>
923 fprint(2, "warning: <FRAME> not in <FRAMESET>\n");
926 ks->kidinfos = kd = newkidinfo(0, ks->kidinfos);
927 kd->src = aurlval(tok, Asrc, nil, di->base);
928 kd->name = aval(tok, Aname);
929 if(kd->name == nil) {
930 s = _ltoStr(++is->nframes);
931 kd->name = _Strdup2(L(Lfr), s);
934 kd->marginw = auintval(tok, Amarginwidth, 0);
935 kd->marginh = auintval(tok, Amarginheight, 0);
936 kd->framebd = auintval(tok, Aframeborder, 1);
937 kd->flags = atabval(tok, Ascrolling, fscroll_tab, NFSCROLLTAB, kd->flags);
938 norsz = aflagval(tok, Anoresize);
940 kd->flags |= FRnoresize;
943 // <!ELEMENT FRAMESET - - (FRAME|FRAMESET)+>
945 ks = newkidinfo(1, nil);
950 ks->next = pks->kidinfos;
953 ks->nextframeset = pks;
955 setdimarray(tok, Arows, &ks->rows, &ks->nrows);
957 ks->rows = (Dimen*)emalloc(sizeof(Dimen));
959 ks->rows[0] = makedimen(Dpercent, 100);
961 setdimarray(tok, Acols, &ks->cols, &ks->ncols);
963 ks->cols = (Dimen*)emalloc(sizeof(Dimen));
965 ks->cols[0] = makedimen(Dpercent, 100);
970 if(is->kidstk == nil) {
972 fprint(2, "warning: unexpected </FRAMESET>\n");
976 // put kids back in original order
977 // and add blank frames to fill out cells
978 n = ks->nrows*ks->ncols;
979 nblank = n - _listlen((List*)ks->kidinfos);
981 ks->kidinfos = newkidinfo(0, ks->kidinfos);
982 ks->kidinfos = (Kidinfo*)_revlist((List*)ks->kidinfos);
983 is->kidstk = is->kidstk->nextframeset;
984 if(is->kidstk == nil) {
991 // <!ELEMENT H1 - - (%text;)*>, etc.
999 if(ps->items == ps->lastit)
1001 addbrk(ps, bramt, IFcleft|IFcright);
1002 sz = Verylarge - (tag - Th1);
1005 pushfontsize(ps, sz);
1006 sty = top(&ps->fntstylestk, FntR);
1009 pushfontstyle(ps, sty);
1010 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1020 addbrk(ps, 1, IFcleft|IFcright);
1027 // HTML spec says ignore regular markup in head,
1028 // but Netscape and IE don't
1036 // <!ELEMENT HR - O EMPTY>
1038 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ALcenter);
1039 sz = auintval(tok, Asize, HRSZ);
1040 wd = adimen(tok, Awidth);
1041 if(dimenkind(wd) == Dnone)
1042 wd = makedimen(Dpercent, 100);
1043 nosh = aflagval(tok, Anoshade);
1044 additem(ps, newirule(al, sz, nosh, wd), tok);
1054 pushfontstyle(ps, FntI);
1057 // <!ELEMENT IMG - O EMPTY>
1060 oldcuranchor = ps->curanchor;
1061 if(_tokaval(tok, Ausemap, &usemap, 0)) {
1062 if(!_prefix(L(Lhash), usemap)) {
1064 fprint(2, "warning: can't handle non-local map %S\n", usemap);
1067 map = getmap(di, usemap+1);
1068 if(ps->curanchor == 0) {
1069 di->anchors = newanchor(++is->nanchors, nil, nil, di->target, di->anchors);
1070 ps->curanchor = is->nanchors;
1074 align = atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom);
1076 if(ps->curanchor != 0)
1078 src = aurlval(tok, Asrc, nil, di->base);
1081 fprint(2, "warning: <img> has no src attribute\n");
1082 ps->curanchor = oldcuranchor;
1085 img = newiimage(src,
1088 auintval(tok, Awidth, 0),
1089 auintval(tok, Aheight, 0),
1090 auintval(tok, Ahspace, IMGHSPACE),
1091 auintval(tok, Avspace, IMGVSPACE),
1092 auintval(tok, Aborder, dfltbd),
1093 aflagval(tok, Aismap),
1095 if(align == ALleft || align == ALright) {
1096 additem(ps, newifloat(img, align), tok);
1097 // if no hspace specified, use FLTIMGHSPACE
1098 if(!_tokaval(tok, Ahspace, &val, 0))
1099 ((Iimage*)img)->hspace = FLTIMGHSPACE;
1103 additem(ps, img, tok);
1106 ((Iimage*)img)->nextimage = di->images;
1107 di->images = (Iimage*)img;
1109 ps->curanchor = oldcuranchor;
1112 // <!ELEMENT INPUT - O EMPTY>
1115 if(is->curform == nil) {
1117 fprint(2, "<INPUT> not inside <FORM>\n");
1120 is->curform->fields = field = newformfield(
1121 atabval(tok, Atype, input_tab, NINPUTTAB, Ftext),
1122 ++is->curform->nfields,
1126 auintval(tok, Asize, 0),
1127 auintval(tok, Amaxlength, 1000),
1128 is->curform->fields);
1129 if(aflagval(tok, Achecked))
1130 field->flags = FFchecked;
1132 switch(field->ftype) {
1136 if(field->size == 0)
1141 if(field->name == nil) {
1143 fprint(2, "warning: checkbox form field missing name\n");
1146 if(field->value == nil)
1147 field->value = _Strdup(L(Lone));
1151 if(field->name == nil || field->value == nil) {
1153 fprint(2, "warning: radio form field missing name or value\n");
1159 if(field->value == nil)
1160 field->value = _Strdup(L(Lsubmit));
1161 if(field->name == nil)
1162 field->name = _Strdup(L(Lnoname));
1166 src = aurlval(tok, Asrc, nil, di->base);
1169 fprint(2, "warning: image form field missing src\n");
1172 // width and height attrs aren't specified in HTML 3.2,
1173 // but some people provide them and they help avoid
1175 field->image = newiimage(src,
1176 astrval(tok, Aalt, L(Lsubmit)),
1177 atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom),
1178 auintval(tok, Awidth, 0), auintval(tok, Aheight, 0),
1180 ii = (Iimage*)field->image;
1181 ii->nextimage = di->images;
1186 if(field->value == nil)
1187 field->value = _Strdup(L(Lreset));
1191 if(field->value == nil)
1192 field->value = _Strdup(L(Lspace));
1195 ffit = newiformfield(field);
1196 additem(ps, ffit, tok);
1197 if(ffit->genattr != nil)
1198 field->events = ffit->genattr->events;
1201 // <!ENTITY ISINDEX - O EMPTY>
1204 prompt = astrval(tok, Aprompt, L(Lindex));
1205 target = atargval(tok, di->target);
1206 additem(ps, textit(ps, prompt), tok);
1207 frm = newform(++is->nforms,
1214 ff = newformfield(Ftext,
1217 _Strdup(L(Lisindex)),
1224 additem(ps, newiformfield(ff), tok);
1228 // <!ELEMENT LI - O %flow>
1230 if(ps->listtypestk.n == 0) {
1232 fprint(2, "<LI> not in list\n");
1235 ty = top(&ps->listtypestk, 0);
1236 ty2 = listtyval(tok, ty);
1239 push(&ps->listtypestk, ty2);
1241 v = aintval(tok, Avalue, top(&ps->listcntstk, 1));
1242 if(ty == LTdisc || ty == LTsquare || ty == LTcircle)
1243 hang = 10*LISTTAB - 3;
1245 hang = 10*LISTTAB - 1;
1246 changehang(ps, hang);
1247 addtext(ps, listmark(ty, v));
1248 push(&ps->listcntstk, v + 1);
1249 changehang(ps, -hang);
1253 // <!ELEMENT MAP - - (AREA)+>
1255 if(_tokaval(tok, Aname, &name, 0))
1256 is->curmap = getmap(di, name);
1263 fprint(2, "warning: unexpected </MAP>\n");
1266 map->areas = (Area*)_revlist((List*)map->areas);
1272 if(_tokaval(tok, Ahttp_equiv, &equiv, 0)) {
1273 val = aval(tok, Acontent);
1275 if(!_Strncmpci(equiv, n, L(Lrefresh)))
1277 else if(!_Strncmpci(equiv, n, L(Lcontent))) {
1279 if(!_Strncmpci(val, n, L(Ljavascript))
1280 || !_Strncmpci(val, n, L(Ljscript1))
1281 || !_Strncmpci(val, n, L(Ljscript)))
1282 di->scripttype = TextJavascript;
1285 fprint(2, "unimplemented script type %S\n", val);
1286 di->scripttype = UnknownType;
1292 // Nobr is NOT in HMTL 4.0, but it is ubiquitous on the web
1295 ps->curstate &= ~IFwrap;
1299 ps->curstate |= IFwrap;
1302 // We do frames, so skip stuff in noframes
1307 case Tnoframes+RBRA:
1311 // We do scripts (if enabled), so skip stuff in noscripts
1317 case Tnoscript+RBRA:
1322 // <!ELEMENT OPTION - O ( //PCDATA)>
1324 if(is->curform == nil || is->curform->fields == nil) {
1326 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1329 field = is->curform->fields;
1330 if(field->ftype != Fselect) {
1332 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1335 val = aval(tok, Avalue);
1336 option = newoption(aflagval(tok, Aselected), val, nil, field->options);
1337 field->options = option;
1338 option->display = getpcdata(toks, tokslen, &toki);
1340 option->value = _Strdup(option->display);
1343 // <!ELEMENT P - O (%text)* >
1345 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1353 // <!ELEMENT PARAM - O EMPTY>
1354 // Do something when we do applets...
1358 // <!ELEMENT PRE - - (%text)* -(IMG|BIG|SMALL|SUB|SUP|FONT) >
1360 ps->curstate &= ~IFwrap;
1363 pushfontstyle(ps, FntT);
1367 ps->curstate |= IFwrap;
1374 // <!ELEMENT SCRIPT - - CDATA>
1377 if(!di->hasscripts) {
1378 if(di->scripttype == TextJavascript) {
1379 // TODO: initialize script if nec.
1385 if(!di->hasscripts) {
1387 fprint(2, "warning: <SCRIPT> ignored\n");
1391 scriptsrc = aurlval(tok, Asrc, nil, di->base);
1393 if(scriptsrc != nil) {
1395 fprint(2, "warning: non-local <SCRIPT> ignored\n");
1399 script = getpcdata(toks, tokslen, &toki);
1403 fprint(2, "script ignored\n");
1413 // <!ELEMENT SELECT - - (OPTION+)>
1415 if(is->curform == nil) {
1417 fprint(2, "<SELECT> not inside <FORM>\n");
1420 field = newformfield(Fselect,
1421 ++is->curform->nfields,
1425 auintval(tok, Asize, 0),
1427 is->curform->fields);
1428 is->curform->fields = field;
1429 if(aflagval(tok, Amultiple))
1430 field->flags = FFmultiple;
1431 ffit = newiformfield(field);
1432 additem(ps, ffit, tok);
1433 if(ffit->genattr != nil)
1434 field->events = ffit->genattr->events;
1435 // throw away stuff until next tag (should be <OPTION>)
1436 s = getpcdata(toks, tokslen, &toki);
1442 if(is->curform == nil || is->curform->fields == nil) {
1444 fprint(2, "warning: unexpected </SELECT>\n");
1447 field = is->curform->fields;
1448 if(field->ftype != Fselect)
1450 // put options back in input order
1451 field->options = (Option*)_revlist((List*)field->options);
1454 // <!ELEMENT (STRIKE|U) - - (%text)*>
1457 ps->curul = push(&ps->ulstk, (tag==Tstrike)? ULmid : ULunder);
1462 if(ps->ulstk.n == 0) {
1464 fprint(2, "warning: unexpected %T\n", tok);
1467 ps->curul = popretnewtop(&ps->ulstk, ULnone);
1470 // <!ELEMENT STYLE - - CDATA>
1473 fprint(2, "warning: unimplemented <STYLE>\n");
1481 // <!ELEMENT (SUB|SUP) - - (%text)*>
1485 ps->curvoff += SUBOFF;
1487 ps->curvoff -= SUPOFF;
1488 push(&ps->voffstk, ps->curvoff);
1489 sz = top(&ps->fntsizestk, Normal);
1490 pushfontsize(ps, sz - 1);
1495 if(ps->voffstk.n == 0) {
1497 fprint(2, "warning: unexpected %T\n", tok);
1500 ps->curvoff = popretnewtop(&ps->voffstk, 0);
1504 // <!ELEMENT TABLE - - (CAPTION?, TR+)>
1507 tab = newtable(++is->ntables,
1509 adimen(tok, Awidth),
1510 aflagval(tok, Aborder),
1511 auintval(tok, Acellspacing, TABSP),
1512 auintval(tok, Acellpadding, TABPAD),
1513 makebackground(nil, acolorval(tok, Abgcolor, ps->curbg.color)),
1523 fprint(2, "warning: unexpected </TABLE>\n");
1526 isempty = (curtab->cells == nil);
1529 fprint(2, "warning: <TABLE> has no cells\n");
1532 ps = finishcell(curtab, ps);
1533 if(curtab->rows != nil)
1534 curtab->rows->flags = 0;
1535 finish_table(curtab);
1539 tabitem = newitable(curtab);
1540 al = curtab->align.halign;
1544 additem(ps, newifloat(tabitem, al), tok);
1548 pushjust(ps, ALcenter);
1554 additem(ps, tabitem, curtab->tabletok);
1560 if(is->tabstk == nil) {
1562 fprint(2, "warning: table stack is wrong\n");
1565 is->tabstk = is->tabstk->next;
1566 curtab->next = di->tables;
1567 di->tables = curtab;
1568 curtab = is->tabstk;
1573 // <!ELEMENT (TH|TD) - O %body.content>
1574 // Cells for a row are accumulated in reverse order.
1575 // We push ps on a stack, and use a new one to accumulate
1576 // the contents of the cell.
1581 fprint(2, "%T outside <TABLE>\n", tok);
1588 ps = finishcell(curtab, ps);
1590 if(curtab->rows != nil)
1592 if(tr == nil || !tr->flags) {
1594 fprint(2, "%T outside row\n", tok);
1595 tr = newtablerow(makealign(ALnone, ALnone),
1596 makebackground(nil, curtab->background.color),
1601 ps = cell_pstate(ps, tag == Tth);
1603 if(aflagval(tok, Anowrap)) {
1605 ps->curstate &= ~IFwrap;
1609 c = newtablecell(curtab->cells==nil? 1 : curtab->cells->cellid+1,
1610 auintval(tok, Arowspan, 1),
1611 auintval(tok, Acolspan, 1),
1613 adimen(tok, Awidth),
1614 auintval(tok, Aheight, 0),
1615 makebackground(nil, acolorval(tok, Abgcolor, tr->background.color)),
1619 ps->curbg = c->background;
1620 if(c->align.halign == ALnone) {
1621 if(tr->align.halign != ALnone)
1622 c->align.halign = tr->align.halign;
1624 c->align.halign = ALcenter;
1626 c->align.halign = ALleft;
1628 if(c->align.valign == ALnone) {
1629 if(tr->align.valign != ALnone)
1630 c->align.valign = tr->align.valign;
1632 c->align.valign = ALmiddle;
1634 c->nextinrow = tr->cells;
1640 if(curtab == nil || curtab->cells == nil) {
1642 fprint(2, "unexpected %T\n", tok);
1645 ps = finishcell(curtab, ps);
1648 // <!ELEMENT TEXTAREA - - ( //PCDATA)>
1650 if(is->curform == nil) {
1652 fprint(2, "<TEXTAREA> not inside <FORM>\n");
1655 field = newformfield(Ftextarea,
1656 ++is->curform->nfields,
1662 is->curform->fields);
1663 is->curform->fields = field;
1664 field->rows = auintval(tok, Arows, 3);
1665 field->cols = auintval(tok, Acols, 50);
1666 field->value = getpcdata(toks, tokslen, &toki);
1667 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttextarea + RBRA)
1668 fprint(2, "warning: <TEXTAREA> data ended by %T\n", &toks[toki + 1]);
1669 ffit = newiformfield(field);
1670 additem(ps, ffit, tok);
1671 if(ffit->genattr != nil)
1672 field->events = ffit->genattr->events;
1675 // <!ELEMENT TITLE - - ( //PCDATA)* -(%head.misc)>
1677 di->doctitle = getpcdata(toks, tokslen, &toki);
1678 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttitle + RBRA)
1679 fprint(2, "warning: <TITLE> data ended by %T\n", &toks[toki + 1]);
1682 // <!ELEMENT TR - O (TH|TD)+>
1683 // rows are accumulated in reverse order in curtab->rows
1687 fprint(2, "warning: <TR> outside <TABLE>\n");
1694 ps = finishcell(curtab, ps);
1695 if(curtab->rows != nil)
1696 curtab->rows->flags = 0;
1697 curtab->rows = newtablerow(aalign(tok),
1698 makebackground(nil, acolorval(tok, Abgcolor, curtab->background.color)),
1704 if(curtab == nil || curtab->rows == nil) {
1706 fprint(2, "warning: unexpected </TR>\n");
1709 ps = finishcell(curtab, ps);
1711 if(tr->cells == nil) {
1713 fprint(2, "warning: empty row\n");
1714 curtab->rows = tr->next;
1721 // <!ELEMENT (TT|CODE|KBD|SAMP) - - (%text)*>
1726 pushfontstyle(ps, FntT);
1729 // Tags that have empty action
1736 case Tbasefont+RBRA:
1753 case Ttextarea+RBRA:
1758 // Tags not implemented
1766 case Tfieldset+RBRA:
1778 case Toptgroup+RBRA:
1784 fprint(2, "warning: unimplemented HTML tag: %S\n", tagnames[tag]);
1790 fprint(2, "warning: unknown HTML tag: %S\n", tok->text);
1794 // some pages omit trailing </table>
1795 while(curtab != nil) {
1797 fprint(2, "warning: <TABLE> not closed\n");
1798 if(curtab->cells != nil) {
1799 ps = finishcell(curtab, ps);
1800 if(curtab->cells == nil) {
1802 fprint(2, "warning: empty table\n");
1805 if(curtab->rows != nil)
1806 curtab->rows->flags = 0;
1807 finish_table(curtab);
1809 additem(ps, newitable(curtab), curtab->tabletok);
1813 if(is->tabstk != nil)
1814 is->tabstk = is->tabstk->next;
1815 curtab->next = di->tables;
1816 di->tables = curtab;
1817 curtab = is->tabstk;
1819 outerps = lastps(ps);
1820 ans = outerps->items->next;
1821 // note: ans may be nil and di->kids not nil, if there's a frameset!
1822 outerps->items = newispacer(ISPnull);
1823 outerps->lastit = outerps->items;
1825 if(ans != nil && di->hasscripts) {
1826 // TODO evalscript(nil);
1832 assert(validitems(ans));
1834 fprint(2, "getitems returning nil\n");
1836 printitems(ans, "getitems returning:");
1841 // Concatenate together maximal set of Data tokens, starting at toks[toki+1].
1842 // Lexer has ensured that there will either be a following non-data token or
1843 // we will be at eof.
1844 // Return emallocd trimmed concatenation, and update *ptoki to last used toki
1846 getpcdata(Token* toks, int tokslen, int* ptoki)
1858 // first find length of answer
1859 toki = (*ptoki) + 1;
1860 while(toki < tokslen) {
1862 if(tok->tag == Data) {
1864 anslen += _Strlen(tok->text);
1869 // now make up the initial answer
1871 ans = _newstr(anslen);
1873 toki = (*ptoki) + 1;
1874 while(toki < tokslen) {
1876 if(tok->tag == Data) {
1878 p = _Stradd(p, tok->text, _Strlen(tok->text));
1884 _trimwhite(ans, anslen, &trimans, &trimanslen);
1885 if(trimanslen != anslen) {
1887 ans = _Strndup(trimans, trimanslen);
1895 // If still parsing head of curtab->cells list, finish it off
1896 // by transferring the items on the head of psstk to the cell.
1897 // Then pop the psstk and return the new psstk.
1899 finishcell(Table* curtab, Pstate* psstk)
1906 if((c->flags&TFparsing)) {
1907 psstknext = psstk->next;
1908 if(psstknext == nil) {
1910 fprint(2, "warning: parse state stack is wrong\n");
1913 c->content = psstk->items->next;
1914 c->flags &= ~TFparsing;
1923 // Make a new Pstate for a cell, based on the old pstate, oldps.
1924 // Also, put the new ps on the head of the oldps stack.
1926 cell_pstate(Pstate* oldps, int ishead)
1931 ps = newpstate(oldps);
1933 ps->curanchor = oldps->curanchor;
1934 copystack(&ps->fntstylestk, &oldps->fntstylestk);
1935 copystack(&ps->fntsizestk, &oldps->fntsizestk);
1936 ps->curfont = oldps->curfont;
1937 ps->curfg = oldps->curfg;
1938 ps->curbg = oldps->curbg;
1939 copystack(&ps->fgstk, &oldps->fgstk);
1940 ps->adjsize = oldps->adjsize;
1942 sty = ps->curfont%NumSize;
1943 ps->curfont = FntB*NumSize + sty;
1948 // Return a new Pstate with default starting state.
1949 // Use link to add it to head of a list, if any.
1951 newpstate(Pstate* link)
1955 ps = (Pstate*)emalloc(sizeof(Pstate));
1956 ps->curfont = DefFnt;
1958 ps->curbg.image = nil;
1959 ps->curbg.color = White;
1961 ps->curjust = ALleft;
1962 ps->curstate = IFwrap;
1963 ps->items = newispacer(ISPnull);
1964 ps->lastit = ps->items;
1965 ps->prelastit = nil;
1970 // Return last Pstate on psl list
1975 while(psl->next != nil)
1980 // Add it to end of ps item chain, adding in current state from ps.
1981 // Also, if tok is not nil, scan it for generic attributes and assign
1982 // the genattr field of the item accordingly.
1984 additem(Pstate* ps, Item* it, Token* tok)
1997 fprint(2, "warning: skipping item: %I\n", it);
2000 it->anchorid = ps->curanchor;
2001 it->state |= ps->curstate;
2009 for(a = tok->attr; a != nil; a = a->next) {
2031 assert(aid >= Aonblur && aid <= Aonunload);
2032 e = newscriptevent(scriptev[a->attid], a->value, e);
2039 it->genattr = newgenattr(i, c, s, t, e);
2041 ps->curstate &= ~(IFbrk|IFbrksp|IFnobrk|IFcleft|IFcright);
2042 ps->prelastit = ps->lastit;
2043 ps->lastit->next = it;
2047 // Make a text item out of s,
2048 // using current font, foreground, vertical offset and underline state.
2050 textit(Pstate* ps, Rune* s)
2053 return newitext(s, ps->curfont, ps->curfg, ps->curvoff + Voffbias, ps->curul);
2056 // Add text item or items for s, paying attention to
2057 // current font, foreground, baseline offset, underline state,
2058 // and literal mode. Unless we're in literal mode, compress
2059 // whitespace to single blank, and, if curstate has a break,
2060 // trim any leading whitespace. Whether in literal mode or not,
2061 // turn nonbreaking spaces into spacer items with IFnobrk set.
2063 // In literal mode, break up s at newlines and add breaks instead.
2064 // Also replace tabs appropriate number of spaces.
2065 // In nonliteral mode, break up the items every 100 or so characters
2066 // just to make the layout algorithm not go quadratic.
2068 // addtext assumes ownership of s.
2070 addtext(Pstate* ps, Rune* s)
2082 Rune buf[SMALLBUFSIZE];
2093 // trim trailing blanks from line
2094 for(k = i; k > j; k--)
2098 additem(ps, textit(ps, _Strndup(s+j, k-j)), nil);
2108 // make ss = s[j:i] + nsp spaces
2109 ss = _newstr(i-j+nsp);
2110 p = _Stradd(ss, s+j, i-j);
2111 p = _Stradd(p, L(Ltab2space), nsp);
2113 additem(ps, textit(ps, ss), nil);
2117 else if(s[i] == NBSP) {
2119 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2128 if(j == 0 && i == n) {
2129 // just transfer s over
2130 additem(ps, textit(ps, s), nil);
2133 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2138 else { // not literal mode
2139 if((ps->curstate&IFbrk) || ps->lastit == ps->items)
2142 if(c >= 256 || !isspace(c))
2147 for(j = i; i < n; i++) {
2148 assert(p+i-j < buf+SMALLBUFSIZE-1);
2152 p = _Stradd(p, s+j, i-j);
2154 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2160 if(c < 256 && isspace(c)) {
2162 p = _Stradd(p, s+j, i-j);
2166 if(c >= 256 || !isspace(c))
2173 p = _Stradd(p, s+j, i+1-j);
2177 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2181 if(i > j && j < n) {
2182 assert(p+i-j < buf+SMALLBUFSIZE-1);
2183 p = _Stradd(p, s+j, i-j);
2185 // don't add a space if previous item ended in a space
2186 if(p-buf == 1 && buf[0] == ' ' && ps->lastit != nil) {
2188 if(it->tag == Itexttag) {
2189 ss = ((Itext*)it)->s;
2191 if(k > 0 && ss[k] == ' ')
2196 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2201 // Add a break to ps->curstate, with extra space if sp is true.
2202 // If there was a previous break, combine this one's parameters
2203 // with that to make the amt be the max of the two and the clr
2204 // be the most general. (amt will be 0 or 1)
2205 // Also, if the immediately preceding item was a text item,
2206 // trim any whitespace from the end of it, if not in literal mode.
2207 // Finally, if this is at the very beginning of the item list
2208 // (the only thing there is a null spacer), then don't add the space.
2210 addbrk(Pstate* ps, int sp, int clr)
2220 state = ps->curstate;
2221 clr = clr|(state&(IFcleft|IFcright));
2222 if(sp && !(ps->lastit == ps->items))
2226 ps->curstate = IFbrk|sp|(state&~(IFcleft|IFcright))|clr;
2227 if(ps->lastit != ps->items) {
2228 if(!ps->literal && ps->lastit->tag == Itexttag) {
2229 t = (Itext*)ps->lastit;
2230 _splitr(t->s, _Strlen(t->s), notwhitespace, &l, &nl, &r, &nr);
2231 // try to avoid making empty items
2232 // but not crucial f the occasional one gets through
2233 if(nl == 0 && ps->prelastit != nil) {
2234 ps->lastit = ps->prelastit;
2235 ps->lastit->next = nil;
2236 ps->prelastit = nil;
2241 // need a non-nil pointer to empty string
2242 // (_Strdup(L(Lempty)) returns nil)
2243 t->s = emalloc(sizeof(Rune));
2247 t->s = _Strndup(l, nl);
2255 // Add break due to a <br> or a newline within a preformatted section.
2256 // We add a null item first, with current font's height and ascent, to make
2257 // sure that the current line takes up at least that amount of vertical space.
2258 // This ensures that <br>s on empty lines cause blank lines, and that
2259 // multiple <br>s in a row give multiple blank lines.
2260 // However don't add the spacer if the previous item was something that
2261 // takes up space itself.
2263 addlinebrk(Pstate* ps, int clr)
2269 // don't want break before our null item unless the previous item
2270 // was also a null item for the purposes of line breaking
2271 obrkstate = ps->curstate&(IFbrk|IFbrksp);
2274 if(ps->lastit != nil) {
2275 if(ps->lastit->tag == Ispacertag) {
2276 if(((Ispacer*)ps->lastit)->spkind == ISPvline)
2280 else if(ps->lastit->tag == Ifloattag)
2284 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|b;
2285 additem(ps, newispacer(ISPvline), nil);
2286 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|obrkstate;
2291 // Add a nonbreakable space
2295 // if nbsp comes right where a break was specified,
2296 // do the break anyway (nbsp is being used to generate undiscardable
2297 // space rather than to prevent a break)
2298 if((ps->curstate&IFbrk) == 0)
2299 ps->curstate |= IFnobrk;
2300 additem(ps, newispacer(ISPhspace), nil);
2301 // but definitely no break on next item
2302 ps->curstate |= IFnobrk;
2305 // Change hang in ps.curstate by delta.
2306 // The amount is in 1/10ths of tabs, and is the amount that
2307 // the current contiguous set of items with a hang value set
2308 // is to be shifted left from its normal (indented) place.
2310 changehang(Pstate* ps, int delta)
2314 amt = (ps->curstate&IFhangmask) + delta;
2317 fprint(2, "warning: hang went negative\n");
2320 ps->curstate = (ps->curstate&~IFhangmask)|amt;
2323 // Change indent in ps.curstate by delta.
2325 changeindent(Pstate* ps, int delta)
2329 amt = ((ps->curstate&IFindentmask) >> IFindentshift) + delta;
2332 fprint(2, "warning: indent went negative\n");
2335 ps->curstate = (ps->curstate&~IFindentmask)|(amt << IFindentshift);
2338 // Push val on top of stack, and also return value pushed
2340 push(Stack* stk, int val)
2342 if(stk->n == Nestmax) {
2344 fprint(2, "warning: build stack overflow\n");
2347 stk->slots[stk->n++] = val;
2359 //Return top of stack, using dflt if stack is empty
2361 top(Stack* stk, int dflt)
2365 return stk->slots[stk->n-1];
2368 // pop, then return new top, with dflt if empty
2370 popretnewtop(Stack* stk, int dflt)
2377 return stk->slots[stk->n-1];
2380 // Copy fromstk entries into tostk
2382 copystack(Stack* tostk, Stack* fromstk)
2388 memmove(tostk->slots, fromstk->slots, n*sizeof(int));
2392 popfontstyle(Pstate* ps)
2394 pop(&ps->fntstylestk);
2399 pushfontstyle(Pstate* ps, int sty)
2401 push(&ps->fntstylestk, sty);
2406 popfontsize(Pstate* ps)
2408 pop(&ps->fntsizestk);
2413 pushfontsize(Pstate* ps, int sz)
2415 push(&ps->fntsizestk, sz);
2420 setcurfont(Pstate* ps)
2425 sty = top(&ps->fntstylestk, FntR);
2426 sz = top(&ps->fntsizestk, Normal);
2431 ps->curfont = sty*NumSize + sz;
2442 pushjust(Pstate* ps, int j)
2444 push(&ps->juststk, j);
2449 setcurjust(Pstate* ps)
2454 j = top(&ps->juststk, ALleft);
2455 if(j != ps->curjust) {
2457 state = ps->curstate;
2458 state &= ~(IFrjust|IFcjust);
2461 else if(j == ALright)
2463 ps->curstate = state;
2467 // Do final rearrangement after table parsing is finished
2468 // and assign cells to grid points
2470 finish_table(Table* t)
2478 Tablecell** rowspancell;
2494 t->nrow = nrow = _listlen((List*)rl);
2495 t->rows = (Tablerow*)emalloc(nrow * sizeof(Tablerow));
2498 for(row = rl; row != nil; row = rownext) {
2499 // copy the data from the allocated Tablerow into the array slot
2501 rownext = row->next;
2507 // If rowspan is > 1 but this is the last row,
2508 // reset the rowspan
2509 if(c != nil && c->rowspan > 1 && r == nrow-2)
2512 // reverse row->cells list (along nextinrow pointers)
2515 cnext = c->nextinrow;
2516 c->nextinrow = row->cells;
2518 rcols += c->colspan;
2525 t->cols = (Tablecol*)emalloc(ncol * sizeof(Tablecol));
2527 // Reverse cells just so they are drawn in source order.
2528 // Also, trim their contents so they don't end in whitespace.
2529 t->cells = (Tablecell*)_revlist((List*)t->cells);
2530 for(c = t->cells; c != nil; c= c->next)
2532 t->grid = (Tablecell***)emalloc(nrow * sizeof(Tablecell**));
2533 for(i = 0; i < nrow; i++)
2534 t->grid[i] = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2536 // The following arrays keep track of cells that are spanning
2537 // multiple rows; rowspancnt[i] is the number of rows left
2538 // to be spanned in column i.
2539 // When done, cell's (row,col) is upper left grid point.
2540 rowspancnt = (int*)emalloc(ncol * sizeof(int));
2541 rowspancell = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2542 for(ri = 0; ri < nrow; ri++) {
2546 while(ci < ncol || cl != nil) {
2547 if(ci < ncol && rowspancnt[ci] > 0) {
2548 t->grid[ri][ci] = rowspancell[ci];
2561 if(ci + cspan > ncol) {
2562 // because of row spanning, we calculated
2563 // ncol incorrectly; adjust it
2564 newncol = ci + cspan;
2565 t->cols = (Tablecol*)erealloc(t->cols, newncol * sizeof(Tablecol));
2566 rowspancnt = (int*)erealloc(rowspancnt, newncol * sizeof(int));
2567 rowspancell = (Tablecell**)erealloc(rowspancell, newncol * sizeof(Tablecell*));
2569 memset(t->cols+ncol, 0, k*sizeof(Tablecol));
2570 memset(rowspancnt+ncol, 0, k*sizeof(int));
2571 memset(rowspancell+ncol, 0, k*sizeof(Tablecell*));
2572 for(j = 0; j < nrow; j++) {
2573 t->grid[j] = (Tablecell**)erealloc(t->grid[j], newncol * sizeof(Tablecell*));
2574 memset(t->grid[j], 0, k*sizeof(Tablecell*));
2576 t->ncol = ncol = newncol;
2580 for(i = 0; i < cspan; i++) {
2581 t->grid[ri][ci] = c;
2583 rowspancnt[ci] = rspan - 1;
2584 rowspancell[ci] = c;
2593 // Remove tail of cell content until it isn't whitespace.
2595 trim_cell(Tablecell* c)
2608 while(c->content != nil && dropping) {
2611 while(p->next != nil) {
2616 if(!(p->state&IFnobrk)) {
2617 if(p->tag == Itexttag) {
2620 _splitr(s, _Strlen(s), notwhitespace, &x, &nx, &y, &ny);
2621 if(nx != 0 && ny != 0) {
2622 q->s = _Strndup(x, nx);
2638 // Caller must free answer (eventually).
2640 listmark(uchar ty, int n)
2653 s[0] = (ty == LTdisc)? 0x2022 // bullet
2654 : ((ty == LTsquare)? 0x220e // filled square
2655 : 0x2218); // degree
2663 t = _Stradd(s, t, n2);
2674 s = _newstr((n <= 25)? 2 : 3);
2680 s[i++] = n2 + (ty == LTa)? 'a' : 'A';
2682 s[i++] = n + (ty == LTa)? 'a' : 'A';
2691 fprint(2, "warning: unimplemented roman number > %d\n", NROMAN);
2697 for(i = 0; i < n2; i++)
2698 s[i] = (ty == LTi)? tolower(t[i]) : t[i];
2706 // Find map with given name in di.maps.
2707 // If not there, add one, copying name.
2708 // Ownership of map remains with di->maps list.
2710 getmap(Docinfo* di, Rune* name)
2714 for(m = di->maps; m != nil; m = m->next) {
2715 if(!_Strcmp(name, m->name))
2718 m = (Map*)emalloc(sizeof(Map));
2719 m->name = _Strdup(name);
2726 // Transfers ownership of href to Area
2728 newarea(int shape, Rune* href, int target, Area* link)
2732 a = (Area*)emalloc(sizeof(Area));
2740 // Return string value associated with attid in tok, nil if none.
2741 // Caller must free the result (eventually).
2743 aval(Token* tok, int attid)
2747 _tokaval(tok, attid, &ans, 1); // transfers string ownership from token to ans
2751 // Like aval, but use dflt if there was no such attribute in tok.
2752 // Caller must free the result (eventually).
2754 astrval(Token* tok, int attid, Rune* dflt)
2758 if(_tokaval(tok, attid, &ans, 1))
2759 return ans; // transfers string ownership from token to ans
2761 return _Strdup(dflt);
2764 // Here we're supposed to convert to an int,
2765 // and have a default when not found
2767 aintval(Token* tok, int attid, int dflt)
2771 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
2777 // Like aintval, but result should be >= 0
2779 auintval(Token* tok, int attid, int dflt)
2784 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
2788 return v >= 0? v : 0;
2792 // int conversion, but with possible error check (if warning)
2799 ans = _Strtol(s, &eptr, 10);
2802 eptr = _Strclass(eptr, notwhitespace);
2804 fprint(2, "warning: expected integer, got %S\n", s);
2810 // Attribute value when need a table to convert strings to ints
2812 atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt)
2818 if(_tokaval(tok, attid, &aval, 0)) {
2819 if(!_lookup(tab, ntab, aval, _Strlen(aval), &ans)) {
2822 fprint(2, "warning: name not found in table lookup: %S\n", aval);
2828 // Attribute value when supposed to be a color
2830 acolorval(Token* tok, int attid, int dflt)
2836 if(_tokaval(tok, attid, &aval, 0))
2837 ans = color(aval, dflt);
2841 // Attribute value when supposed to be a target frame name
2843 atargval(Token* tok, int dflt)
2849 if(_tokaval(tok, Atarget, &aval, 0)){
2850 ans = targetid(aval);
2855 // special for list types, where "i" and "I" are different,
2856 // but "square" and "SQUARE" are the same
2858 listtyval(Token* tok, int dflt)
2865 if(_tokaval(tok, Atype, &aval, 0)) {
2885 fprint(2, "warning: unknown list element type %c\n", aval[0]);
2889 if(!_Strncmpci(aval, n, L(Lcircle)))
2891 else if(!_Strncmpci(aval, n, L(Ldisc)))
2893 else if(!_Strncmpci(aval, n, L(Lsquare)))
2897 fprint(2, "warning: unknown list element type %S\n", aval);
2904 // Attribute value when value is a URL, possibly relative to base.
2905 // FOR NOW: leave the url relative.
2906 // Caller must free the result (eventually).
2908 aurlval(Token* tok, int attid, Rune* dflt, Rune* base)
2915 if(_tokaval(tok, attid, &url, 0) && url != nil)
2916 ans = removeallwhite(url);
2918 ans = _Strdup(dflt);
2922 // Return copy of s but with all whitespace (even internal) removed.
2923 // This fixes some buggy URL specification strings.
2925 removeallwhite(Rune* s)
2935 for(i = 0; i < n; i++) {
2937 if(c >= 256 || !isspace(c))
2943 for(i = 0; i < n; i++) {
2945 if(c >= 256 || !isspace(c))
2955 // Attribute value when mere presence of attr implies value of 1,
2956 // but if there is an integer there, return it as the value.
2958 aflagval(Token* tok, int attid)
2964 if(_tokaval(tok, attid, &sval, 0)) {
2973 makealign(int halign, int valign)
2982 // Make an Align (two alignments, horizontal and vertical)
2987 atabval(tok, Aalign, align_tab, NALIGNTAB, ALnone),
2988 atabval(tok, Avalign, align_tab, NALIGNTAB, ALnone));
2991 // Make a Dimen, based on value of attid attr
2993 adimen(Token* tok, int attid)
2997 if(_tokaval(tok, attid, &wd, 0))
2998 return parsedim(wd, _Strlen(wd));
3000 return makedimen(Dnone, 0);
3003 // Parse s[0:n] as num[.[num]][unit][%|*]
3005 parsedim(Rune* s, int ns)
3022 _splitl(s, ns, L(Lnot0to9), &l, &nl, &r, &nr);
3024 spec = 1000*_Strtol(l, nil, 10);
3025 if(nr > 0 && r[0] == '.') {
3026 _splitl(r+1, nr-1, L(Lnot0to9), &f, &nf, &r, &nr);
3029 for(i = 0; i < nf; i++) {
3030 spec = spec + mul*(f[i]-'0');
3042 if(!_Strncmpci(units, 2, L(Lpt)))
3043 spec = (spec*Tkdpi)/72;
3044 else if(!_Strncmpci(units, 2, L(Lpi)))
3045 spec = (spec*12*Tkdpi)/72;
3046 else if(!_Strncmpci(units, 2, L(Lin)))
3048 else if(!_Strncmpci(units, 2, L(Lcm)))
3049 spec = (spec*100*Tkdpi)/254;
3050 else if(!_Strncmpci(units, 2, L(Lmm)))
3051 spec = (spec*10*Tkdpi)/254;
3052 else if(!_Strncmpci(units, 2, L(Lem)))
3056 fprint(2, "warning: unknown units %C%Cs\n", units[0], units[1]);
3062 else if(r[0] == '*')
3068 else if(nr == 1 && r[0] == '*') {
3072 return makedimen(kind, spec);
3076 setdimarray(Token* tok, int attid, Dimen** pans, int* panslen)
3082 Rune* a[SMALLBUFSIZE];
3083 int an[SMALLBUFSIZE];
3085 if(_tokaval(tok, attid, &s, 0)) {
3086 nc = _splitall(s, _Strlen(s), L(Lcommaspace), a, an, SMALLBUFSIZE);
3088 d = (Dimen*)emalloc(nc * sizeof(Dimen));
3089 for(k = 0; k < nc; k++) {
3090 d[k] = parsedim(a[k], an[k]);
3102 makebackground(Rune* imageurl, int color)
3106 bg.image = imageurl;
3112 newitext(Rune* s, int fnt, int fg, int voff, int ul)
3117 t = (Itext*)emalloc(sizeof(Itext));
3118 t->item.tag = Itexttag;
3128 newirule(int align, int size, int noshade, Dimen wspec)
3132 r = (Irule*)emalloc(sizeof(Irule));
3133 r->item.tag = Iruletag;
3136 r->noshade = noshade;
3141 // Map is owned elsewhere.
3143 newiimage(Rune* src, Rune* altrep, int align, int width, int height,
3144 int hspace, int vspace, int border, int ismap, Map* map)
3152 i = (Iimage*)emalloc(sizeof(Iimage));
3153 i->item.tag = Iimagetag;
3154 i->item.state = state;
3159 i->imheight = height;
3169 newiformfield(Formfield* ff)
3173 f = (Iformfield*)emalloc(sizeof(Iformfield));
3174 f->item.tag = Iformfieldtag;
3180 newitable(Table* tab)
3184 t = (Itable*)emalloc(sizeof(Itable));
3185 t->item.tag = Itabletag;
3191 newifloat(Item* it, int side)
3195 f = (Ifloat*)emalloc(sizeof(Ifloat));
3196 f->_item.tag = Ifloattag;
3197 f->_item.state = IFwrap;
3204 newispacer(int spkind)
3208 s = (Ispacer*)emalloc(sizeof(Ispacer));
3209 s->item.tag = Ispacertag;
3214 // Free one item (caller must deal with next pointer)
3226 free(((Itext*)it)->s);
3234 freeformfield(((Iformfield*)it)->formfield);
3237 freetable(((Itable*)it)->table);
3240 freeitem(((Ifloat*)it)->item);
3249 freescriptevents(ga->events);
3254 // Free list of items chained through next pointer
3256 freeitems(Item* ithead)
3270 freeformfield(Formfield* ff)
3280 for(o = ff->options; o != nil; o = onext) {
3298 // We'll find all the unique cells via t->cells and next pointers.
3299 // (Other pointers to cells in the table are duplicates of these)
3300 for(c = t->cells; c != nil; c = cnext) {
3302 freeitems(c->content);
3304 if(t->grid != nil) {
3305 for(i = 0; i < t->nrow; i++)
3311 freeitems(t->caption);
3323 // Form doesn't own its fields (Iformfield items do)
3328 freeforms(Form* fhead)
3333 for(f = fhead; f != nil; f = fnext) {
3340 freeanchor(Anchor* a)
3351 freeanchors(Anchor* ahead)
3356 for(a = ahead; a != nil; a = anext) {
3363 freedestanchor(DestAnchor* da)
3373 freedestanchors(DestAnchor* dahead)
3378 for(da = dahead; da != nil; da = danext) {
3393 static void freekidinfos(Kidinfo* khead);
3396 freekidinfo(Kidinfo* k)
3401 freekidinfos(k->kidinfos);
3411 freekidinfos(Kidinfo* khead)
3416 for(k = khead; k != nil; k = knext) {
3432 for(a = m->areas; a != nil; a = anext) {
3440 freemaps(Map* mhead)
3445 for(m = mhead; m != nil; m = mnext) {
3452 freedocinfo(Docinfo* d)
3458 freeitem((Item*)d->backgrounditem);
3460 freekidinfos(d->kidinfo);
3461 freeanchors(d->anchors);
3462 freedestanchors(d->dests);
3463 freeforms(d->forms);
3465 // tables, images, and formfields are freed when
3466 // the items pointing at them are freed
3470 // Currently, someone else owns all the memory
3471 // pointed to by things in a Pstate.
3473 freepstate(Pstate* p)
3479 freepstatestack(Pstate* pshead)
3484 for(p = pshead; p != nil; p = pnext) {
3509 char buf[BIGBUFSIZE];
3511 it = va_arg(f->args, Item*);
3517 cl = state&(IFcleft|IFcright);
3520 if(cl == (IFcleft|IFcright))
3522 else if(cl == IFcleft)
3527 bi = snprint(buf, nbuf, "brk(%d%s)", (state&IFbrksp)? 1 : 0, p);
3530 bi += snprint(buf+bi, nbuf-bi, " nobrk");
3532 bi += snprint(buf+bi, nbuf-bi, " nowrap");
3534 bi += snprint(buf+bi, nbuf-bi, " rjust");
3536 bi += snprint(buf+bi, nbuf-bi, " cjust");
3538 bi += snprint(buf+bi, nbuf-bi, " smap");
3539 indent = (state&IFindentmask) >> IFindentshift;
3541 bi += snprint(buf+bi, nbuf-bi, " indent=%d", indent);
3542 hang = state&IFhangmask;
3544 bi += snprint(buf+bi, nbuf-bi, " hang=%d", hang);
3549 bi += snprint(buf+bi, nbuf-bi, " Text '%S', fnt=%d, fg=%x", t->s, t->fnt, t->fg);
3554 bi += snprint(buf+bi, nbuf-bi, "Rule size=%d, al=%S, wspec=", r->size, stringalign(r->align));
3555 bi += dimprint(buf+bi, nbuf-bi, r->wspec);
3560 bi += snprint(buf+bi, nbuf-bi,
3561 "Image src=%S, alt=%S, al=%S, w=%d, h=%d hsp=%d, vsp=%d, bd=%d, map=%S",
3562 i->imsrc, i->altrep? i->altrep : L(Lempty), stringalign(i->align), i->imwidth, i->imheight,
3563 i->hspace, i->vspace, i->border, i->map?i->map->name : L(Lempty));
3567 ff = ((Iformfield*)it)->formfield;
3568 if(ff->ftype == Ftextarea)
3570 else if(ff->ftype == Fselect)
3573 ty = _revlookup(input_tab, NINPUTTAB, ff->ftype);
3577 bi += snprint(buf+bi, nbuf-bi, "Formfield %S, fieldid=%d, formid=%d, name=%S, value=%S",
3578 ty, ff->fieldid, ff->form->formid, ff->name? ff->name : L(Lempty),
3579 ff->value? ff->value : L(Lempty));
3583 tab = ((Itable*)it)->table;
3584 bi += snprint(buf+bi, nbuf-bi, "Table tableid=%d, width=", tab->tableid);
3585 bi += dimprint(buf+bi, nbuf-bi, tab->width);
3586 bi += snprint(buf+bi, nbuf-bi, ", nrow=%d, ncol=%d, ncell=%d, totw=%d, toth=%d\n",
3587 tab->nrow, tab->ncol, tab->ncell, tab->totw, tab->toth);
3588 for(c = tab->cells; c != nil; c = c->next)
3589 bi += snprint(buf+bi, nbuf-bi, "Cell %d.%d, at (%d,%d) ",
3590 tab->tableid, c->cellid, c->row, c->col);
3591 bi += snprint(buf+bi, nbuf-bi, "End of Table %d", tab->tableid);
3596 bi += snprint(buf+bi, nbuf-bi, "Float, x=%d y=%d, side=%S, it=%I",
3597 fl->x, fl->y, stringalign(fl->side), fl->item);
3598 bi += snprint(buf+bi, nbuf-bi, "\n\t");
3603 switch(((Ispacer*)it)->spkind) {
3614 bi += snprint(buf+bi, nbuf-bi, "Spacer %s ", p);
3617 bi += snprint(buf+bi, nbuf-bi, " w=%d, h=%d, a=%d, anchor=%d\n",
3618 it->width, it->height, it->ascent, it->anchorid);
3620 return fmtstrcpy(f, buf);
3623 // String version of alignment 'a'
3629 s = _revlookup(align_tab, NALIGNTAB, a);
3635 // Put at most nbuf chars of representation of d into buf,
3636 // and return number of characters put
3638 dimprint(char* buf, int nbuf, Dimen d)
3644 n += snprint(buf, nbuf, "%d", dimenspec(d));
3654 printitems(Item* items, char* msg)
3658 fprint(2, "%s\n", msg);
3661 fprint(2, "%I", il);
3667 newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, SEvent* events)
3671 g = (Genattr*)emalloc(sizeof(Genattr));
3681 newformfield(int ftype, int fieldid, Form* form, Rune* name,
3682 Rune* value, int size, int maxlength, Formfield* link)
3686 ff = (Formfield*)emalloc(sizeof(Formfield));
3688 ff->fieldid = fieldid;
3693 ff->maxlength = maxlength;
3699 // Transfers ownership of value and display to Option.
3701 newoption(int selected, Rune* value, Rune* display, Option* link)
3705 o = (Option*)emalloc(sizeof(Option));
3706 o->selected = selected;
3708 o->display = display;
3714 newform(int formid, Rune* name, Rune* action, int target, int method, Form* link)
3718 f = (Form*)emalloc(sizeof(Form));
3731 newtable(int tableid, Align align, Dimen width, int border,
3732 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link)
3736 t = (Table*)emalloc(sizeof(Table));
3737 t->tableid = tableid;
3741 t->cellspacing = cellspacing;
3742 t->cellpadding = cellpadding;
3744 t->caption_place = ALbottom;
3745 t->caption_lay = nil;
3753 newtablerow(Align align, Background bg, int flags, Tablerow* link)
3757 tr = (Tablerow*)emalloc(sizeof(Tablerow));
3759 tr->background = bg;
3766 newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec, int hspec,
3767 Background bg, int flags, Tablecell* link)
3771 c = (Tablecell*)emalloc(sizeof(Tablecell));
3774 c->rowspan = rowspan;
3775 c->colspan = colspan;
3786 newanchor(int index, Rune* name, Rune* href, int target, Anchor* link)
3790 a = (Anchor*)emalloc(sizeof(Anchor));
3800 newdestanchor(int index, Rune* name, Item* item, DestAnchor* link)
3804 d = (DestAnchor*)emalloc(sizeof(DestAnchor));
3813 newscriptevent(int type, Rune* script, SEvent* link)
3817 ans = (SEvent*)emalloc(sizeof(SEvent));
3819 ans->script = script;
3825 freescriptevents(SEvent* ehead)
3840 makedimen(int kind, int spec)
3844 if(spec&Dkindmask) {
3846 fprint(2, "warning: dimension spec too big: %d\n", spec);
3849 d.kindspec = kind|spec;
3856 return (d.kindspec&Dkindmask);
3862 return (d.kindspec&Dspecmask);
3866 newkidinfo(int isframeset, Kidinfo* link)
3870 ki = (Kidinfo*)emalloc(sizeof(Kidinfo));
3871 ki->isframeset = isframeset;
3873 ki->flags = FRhscrollauto|FRvscrollauto;
3874 ki->marginw = FRKIDMARGIN;
3875 ki->marginh = FRKIDMARGIN;
3887 d = (Docinfo*)emalloc(sizeof(Docinfo));
3893 resetdocinfo(Docinfo* d)
3895 memset(d, 0, sizeof(Docinfo));
3896 d->background = makebackground(nil, White);
3902 d->chset = ISO_8859_1;
3903 d->scripttype = TextJavascript;
3907 // Use targetmap array to keep track of name <-> targetid mapping.
3908 // Use real malloc(), and never free
3913 targetmap = (StringInt*)emalloc(targetmapsize*sizeof(StringInt));
3914 memset(targetmap, 0, targetmapsize*sizeof(StringInt));
3915 targetmap[0].key = _Strdup(L(L_top));
3916 targetmap[0].val = FTtop;
3917 targetmap[1].key = _Strdup(L(L_self));
3918 targetmap[1].val = FTself;
3919 targetmap[2].key = _Strdup(L(L_parent));
3920 targetmap[2].val = FTparent;
3921 targetmap[3].key = _Strdup(L(L_blank));
3922 targetmap[3].val = FTblank;
3935 for(i = 0; i < ntargets; i++)
3936 if(_Strcmp(s, targetmap[i].key) == 0)
3937 return targetmap[i].val;
3938 if(i >= targetmapsize) {
3939 targetmapsize += 10;
3940 targetmap = (StringInt*)erealloc(targetmap, targetmapsize*sizeof(StringInt));
3942 targetmap[i].key = (Rune*)emalloc((n+1)*sizeof(Rune));
3943 memmove(targetmap[i].key, s, (n+1)*sizeof(Rune));
3944 targetmap[i].val = i;
3950 targetname(int targid)
3954 for(i = 0; i < ntargets; i++)
3955 if(targetmap[i].val == targid)
3956 return targetmap[i].key;
3957 return L(Lquestion);
3960 // Convert HTML color spec to RGB value, returning dflt if can't.
3961 // Argument is supposed to be a valid HTML color, or "".
3962 // Return the RGB value of the color, using dflt if s
3963 // is nil or an invalid color.
3965 color(Rune* s, int dflt)
3972 if(_lookup(color_tab, NCOLORS, s, _Strlen(s), &v))
3976 v = _Strtol(s, &rest, 16);
3984 #define HUGEPIX 10000
3986 // A "shallow" validitem, that doesn't follow next links
3987 // or descend into tables.
3998 ok = (i->tag >= Itexttag && i->tag <= Ispacertag) &&
3999 (i->next == nil || validptr(i->next)) &&
4000 (i->width >= 0 && i->width < HUGEPIX) &&
4001 (i->height >= 0 && i->height < HUGEPIX) &&
4002 (i->ascent > -HUGEPIX && i->ascent < HUGEPIX) &&
4003 (i->anchorid >= 0) &&
4004 (i->genattr == nil || validptr(i->genattr));
4005 // also, could check state for ridiculous combinations
4006 // also, could check anchorid for within-doc-range
4011 ok = validStr(ti->s) &&
4012 (ti->fnt >= 0 && ti->fnt < NumStyle*NumSize) &&
4013 (ti->ul == ULnone || ti->ul == ULunder || ti->ul == ULmid);
4017 ok = (validvalign(ri->align) || validhalign(ri->align)) &&
4018 (ri->size >=0 && ri->size < HUGEPIX);
4022 ok = (ii->imsrc == nil || validptr(ii->imsrc)) &&
4023 (ii->item.width >= 0 && ii->item.width < HUGEPIX) &&
4024 (ii->item.height >= 0 && ii->item.height < HUGEPIX) &&
4025 (ii->imwidth >= 0 && ii->imwidth < HUGEPIX) &&
4026 (ii->imheight >= 0 && ii->imheight < HUGEPIX) &&
4027 (ii->altrep == nil || validStr(ii->altrep)) &&
4028 (ii->map == nil || validptr(ii->map)) &&
4029 (validvalign(ii->align) || validhalign(ii->align)) &&
4030 (ii->nextimage == nil || validptr(ii->nextimage));
4033 ok = validformfield(((Iformfield*)i)->formfield);
4036 ok = validptr((Itable*)i);
4040 ok = (fi->side == ALleft || fi->side == ALright) &&
4041 validitem(fi->item) &&
4042 (fi->item->tag == Iimagetag || fi->item->tag == Itabletag);
4045 a = ((Ispacer*)i)->spkind;
4046 ok = a==ISPnull || a==ISPvline || a==ISPhspace || a==ISPgeneral;
4054 // "deep" validation, that checks whole list of items,
4055 // and descends into tables and floated tables.
4056 // nil is ok for argument.
4064 while(i != nil && ok) {
4067 if(i->tag == Itabletag) {
4068 ok = validtable(((Itable*)i)->table);
4070 else if(i->tag == Ifloattag) {
4071 ii = ((Ifloat*)i)->item;
4072 if(ii->tag == Itabletag)
4073 ok = validtable(((Itable*)ii)->table);
4077 fprint(2, "invalid item: %I\n", i);
4085 validformfield(Formfield* f)
4089 ok = (f->next == nil || validptr(f->next)) &&
4090 (f->ftype >= 0 && f->ftype <= Ftextarea) &&
4092 (f->form == nil || validptr(f->form)) &&
4093 (f->name == nil || validStr(f->name)) &&
4094 (f->value == nil || validStr(f->value)) &&
4095 (f->options == nil || validptr(f->options)) &&
4096 (f->image == nil || validitem(f->image)) &&
4097 (f->events == nil || validptr(f->events));
4098 // when all built, should have f->fieldid < f->form->nfields,
4099 // but this may be called during build...
4103 // "deep" validation -- checks cell contents too
4105 validtable(Table* t)
4111 ok = (t->next == nil || validptr(t->next)) &&
4115 validalign(t->align) &&
4116 validdimen(t->width) &&
4117 (t->border >= 0 && t->border < HUGEPIX) &&
4118 (t->cellspacing >= 0 && t->cellspacing < HUGEPIX) &&
4119 (t->cellpadding >= 0 && t->cellpadding < HUGEPIX) &&
4120 validitems(t->caption) &&
4121 (t->caption_place == ALtop || t->caption_place == ALbottom) &&
4122 (t->totw >= 0 && t->totw < HUGEPIX) &&
4123 (t->toth >= 0 && t->toth < HUGEPIX) &&
4124 (t->tabletok == nil || validptr(t->tabletok));
4125 // during parsing, t->rows has list;
4126 // only when parsing is done is t->nrow set > 0
4127 if(ok && t->nrow > 0 && t->ncol > 0) {
4128 // table is "finished"
4129 for(i = 0; i < t->nrow && ok; i++)
4130 ok = validtablerow(t->rows+i);
4131 for(j = 0; j < t->ncol && ok; j++)
4132 ok = validtablecol(t->cols+j);
4133 for(c = t->cells; c != nil && ok; c = c->next)
4134 ok = validtablecell(c);
4135 for(i = 0; i < t->nrow && ok; i++)
4136 for(j = 0; j < t->ncol && ok; j++)
4137 ok = validptr(t->grid[i][j]);
4145 return a == ALnone || a == ALmiddle || a == ALbottom || a == ALtop || a == ALbaseline;
4151 return a == ALnone || a == ALleft || a == ALcenter || a == ALright ||
4152 a == ALjustify || a == ALchar;
4158 return validhalign(a.halign) && validvalign(a.valign);
4168 s = d.kindspec&Dspecmask;
4169 switch(d.kindspec&Dkindmask) {
4185 validtablerow(Tablerow* r)
4187 return (r->cells == nil || validptr(r->cells)) &&
4188 (r->height >= 0 && r->height < HUGEPIX) &&
4189 (r->ascent > -HUGEPIX && r->ascent < HUGEPIX) &&
4190 validalign(r->align);
4194 validtablecol(Tablecol* c)
4196 return c->width >= 0 && c->width < HUGEPIX
4197 && validalign(c->align);
4201 validtablecell(Tablecell* c)
4205 ok = (c->next == nil || validptr(c->next)) &&
4206 (c->nextinrow == nil || validptr(c->nextinrow)) &&
4207 (c->content == nil || validptr(c->content)) &&
4208 (c->lay == nil || validptr(c->lay)) &&
4211 validalign(c->align) &&
4212 validdimen(c->wspec) &&
4216 if(c->content != nil)
4217 ok = validitems(c->content);
4225 // TODO: a better job of this.
4226 // For now, just dereference, which cause a bomb
4237 return s != nil && validptr(s);