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 {L"baseline", ALbaseline},
82 {L"bottom", ALbottom},
83 {L"center", ALcenter},
85 {L"justify", ALjustify},
87 {L"middle", ALmiddle},
91 #define NALIGNTAB (sizeof(align_tab)/sizeof(StringInt))
93 static StringInt input_tab[] = {
95 {L"checkbox", Fcheckbox},
99 {L"password", Fpassword},
102 {L"submit", Fsubmit},
105 #define NINPUTTAB (sizeof(input_tab)/sizeof(StringInt))
107 static StringInt clear_tab[] = {
108 {L"all", IFcleft|IFcright},
112 #define NCLEARTAB (sizeof(clear_tab)/sizeof(StringInt))
114 static StringInt fscroll_tab[] = {
115 {L"auto", FRhscrollauto|FRvscrollauto},
117 {L"yes", FRhscroll|FRvscroll},
119 #define NFSCROLLTAB (sizeof(fscroll_tab)/sizeof(StringInt))
121 static StringInt shape_tab[] = {
123 {L"circle", SHcircle},
125 {L"polygon", SHpoly},
127 {L"rectangle", SHrect}
129 #define NSHAPETAB (sizeof(shape_tab)/sizeof(StringInt))
131 static StringInt method_tab[] = {
135 #define NMETHODTAB (sizeof(method_tab)/sizeof(StringInt))
137 static Rune* roman[15]= {
138 L"I", L"II", L"III", L"IV", L"V", L"VI", L"VII", L"VIII", L"IX", L"X",
139 L"XI", L"XII", L"XIII", L"XIV", L"XV"
145 LTdisc, LTsquare, LTcircle, LT1, LTa, LTA, LTi, LTI
152 BLBA = (BL|SPBefore|SPAfter)
155 // blockbrk[tag] is break info for a block level element, or one
156 // of a few others that get the same treatment re ending open paragraphs
157 // and requiring a line break / vertical space before them.
158 // If we want a line of space before the given element, SPBefore is OR'd in.
159 // If we want a line of space after the given element, SPAfter is OR'd in.
161 static uchar blockbrk[Numtags]= {
162 [Taddress] BLBA, [Tblockquote] BLBA, [Tcenter] BL,
163 [Tdir] BLBA, [Tdiv] BL, [Tdd] BL, [Tdl] BLBA,
164 [Tdt] BL, [Tform] BLBA,
165 // headings and tables get breaks added manually
166 [Th1] BL, [Th2] BL, [Th3] BL,
167 [Th4] BL, [Th5] BL, [Th6] BL,
168 [Thr] BL, [Tisindex] BLBA, [Tli] BL, [Tmenu] BLBA,
169 [Tol] BLBA, [Tp] BLBA, [Tpre] BLBA,
177 // attrinfo is information about attributes.
178 // The AGEN value means that the attribute is generic (applies to almost all elements)
179 static uchar attrinfo[Numattrs]= {
180 [Aid] AGEN, [Aclass] AGEN, [Astyle] AGEN, [Atitle] AGEN,
181 [Aonblur] AGEN, [Aonchange] AGEN, [Aonclick] AGEN,
182 [Aondblclick] AGEN, [Aonfocus] AGEN, [Aonkeypress] AGEN,
183 [Aonkeyup] AGEN, [Aonload] AGEN, [Aonmousedown] AGEN,
184 [Aonmousemove] AGEN, [Aonmouseout] AGEN, [Aonmouseover] AGEN,
185 [Aonmouseup] AGEN, [Aonreset] AGEN, [Aonselect] AGEN,
186 [Aonsubmit] AGEN, [Aonunload] AGEN
189 static uchar scriptev[Numattrs]= {
190 [Aonblur] SEonblur, [Aonchange] SEonchange, [Aonclick] SEonclick,
191 [Aondblclick] SEondblclick, [Aonfocus] SEonfocus, [Aonkeypress] SEonkeypress,
192 [Aonkeyup] SEonkeyup, [Aonload] SEonload, [Aonmousedown] SEonmousedown,
193 [Aonmousemove] SEonmousemove, [Aonmouseout] SEonmouseout, [Aonmouseover] SEonmouseover,
194 [Aonmouseup] SEonmouseup, [Aonreset] SEonreset, [Aonselect] SEonselect,
195 [Aonsubmit] SEonsubmit, [Aonunload] SEonunload
198 // Color lookup table
199 static StringInt color_tab[] = {
201 {L"black", 0x000000},
203 {L"fuchsia", 0xFF00FF},
205 {L"green", 0x008000},
207 {L"maroon", 0x800000},
208 {L"navy", 0x000080,},
209 {L"olive", 0x808000},
210 {L"purple", 0x800080},
212 {L"silver", 0xC0C0C0},
214 {L"white", 0xFFFFFF},
215 {L"yellow", 0xFFFF00}
217 #define NCOLORS (sizeof(color_tab)/sizeof(StringInt))
219 static StringInt *targetmap;
220 static int targetmapsize;
223 static int buildinited = 0;
225 #define SMALLBUFSIZE 240
226 #define BIGBUFSIZE 2000
231 static Align aalign(Token* tok);
232 static int acolorval(Token* tok, int attid, int dflt);
233 static void addbrk(Pstate* ps, int sp, int clr);
234 static void additem(Pstate* ps, Item* it, Token* tok);
235 static void addlinebrk(Pstate* ps, int clr);
236 static void addnbsp(Pstate* ps);
237 static void addtext(Pstate* ps, Rune* s);
238 static Dimen adimen(Token* tok, int attid);
239 static int aflagval(Token* tok, int attid);
240 static int aintval(Token* tok, int attid, int dflt);
241 static Rune* astrval(Token* tok, int attid, Rune* dflt);
242 static int atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt);
243 static int atargval(Token* tok, int dflt);
244 static int auintval(Token* tok, int attid, int dflt);
245 static Rune* aurlval(Token* tok, int attid, Rune* dflt, Rune* base);
246 static Rune* aval(Token* tok, int attid);
247 static void buildinit(void);
248 static Pstate* cell_pstate(Pstate* oldps, int ishead);
249 static void changehang(Pstate* ps, int delta);
250 static void changeindent(Pstate* ps, int delta);
251 static int color(Rune* s, int dflt);
252 static void copystack(Stack* tostk, Stack* fromstk);
253 static int dimprint(char* buf, int nbuf, Dimen d);
254 static Pstate* finishcell(Table* curtab, Pstate* psstk);
255 static void finish_table(Table* t);
256 static void freeanchor(Anchor* a);
257 static void freedestanchor(DestAnchor* da);
258 static void freeform(Form* f);
259 static void freeformfield(Formfield* ff);
260 static void freeitem(Item* it);
261 static void freepstate(Pstate* p);
262 static void freepstatestack(Pstate* pshead);
263 static void freescriptevents(SEvent* ehead);
264 static void freetable(Table* t);
265 static Map* getmap(Docinfo* di, Rune* name);
266 static Rune* getpcdata(Token* toks, int tokslen, int* ptoki);
267 static Pstate* lastps(Pstate* psl);
268 static Rune* listmark(uchar ty, int n);
269 static int listtyval(Token* tok, int dflt);
270 static Align makealign(int halign, int valign);
271 static Background makebackground(Rune* imgurl, int color);
272 static Dimen makedimen(int kind, int spec);
273 static Anchor* newanchor(int index, Rune* name, Rune* href, int target, Anchor* link);
274 static Area* newarea(int shape, Rune* href, int target, Area* link);
275 static DestAnchor* newdestanchor(int index, Rune* name, Item* item, DestAnchor* link);
276 static Docinfo* newdocinfo(void);
277 static Genattr* newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, Attr* events);
278 static Form* newform(int formid, Rune* name, Rune* action,
279 int target, int method, Form* link);
280 static Formfield* newformfield(int ftype, int fieldid, Form* form, Rune* name,
281 Rune* value, int size, int maxlength, Formfield* link);
282 static Item* newifloat(Item* it, int side);
283 static Item* newiformfield(Formfield* ff);
284 static Item* newiimage(Rune* src, Rune* altrep, int align, int width, int height,
285 int hspace, int vspace, int border, int ismap, Map* map);
286 static Item* newirule(int align, int size, int noshade, int color, Dimen wspec);
287 static Item* newispacer(int spkind);
288 static Item* newitable(Table* t);
289 static ItemSource* newitemsource(Docinfo* di);
290 static Item* newitext(Rune* s, int fnt, int fg, int voff, int ul);
291 static Kidinfo* newkidinfo(int isframeset, Kidinfo* link);
292 static Option* newoption(int selected, Rune* value, Rune* display, Option* link);
293 static Pstate* newpstate(Pstate* link);
294 static SEvent* newscriptevent(int type, Rune* script, SEvent* link);
295 static Table* newtable(int tableid, Align align, Dimen width, int border,
296 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link);
297 static Tablecell* newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec,
298 int hspec, Background bg, int flags, Tablecell* link);
299 static Tablerow* newtablerow(Align align, Background bg, int flags, Tablerow* link);
300 static Dimen parsedim(Rune* s, int ns);
301 static void pop(Stack* stk);
302 static void popfontsize(Pstate* ps);
303 static void popfontstyle(Pstate* ps);
304 static void popjust(Pstate* ps);
305 static int popretnewtop(Stack* stk, int dflt);
306 static int push(Stack* stk, int val);
307 static void pushfontsize(Pstate* ps, int sz);
308 static void pushfontstyle(Pstate* ps, int sty);
309 static void pushjust(Pstate* ps, int j);
310 static Item* textit(Pstate* ps, Rune* s);
311 static Rune* removeallwhite(Rune* s);
312 static void resetdocinfo(Docinfo* d);
313 static void setcurfont(Pstate* ps);
314 static void setcurjust(Pstate* ps);
315 static void setdimarray(Token* tok, int attid, Dimen** pans, int* panslen);
316 static Rune* stringalign(int a);
317 static void targetmapinit(void);
318 static int toint(Rune* s);
319 static int top(Stack* stk, int dflt);
320 static void trim_cell(Tablecell* c);
321 static int validalign(Align a);
322 static int validdimen(Dimen d);
323 static int validformfield(Formfield* f);
324 static int validhalign(int a);
325 static int validptr(void* p);
326 static int validStr(Rune* s);
327 static int validtable(Table* t);
328 static int validtablerow(Tablerow* r);
329 static int validtablecol(Tablecol* c);
330 static int validtablecell(Tablecell* c);
331 static int validvalign(int a);
332 static int Iconv(Fmt *f);
337 fmtinstall('I', Iconv);
343 newitemsource(Docinfo* di)
349 if(di->mediatype != TextHtml) {
350 ps->curstate &= ~IFwrap;
352 pushfontstyle(ps, FntT);
354 is = (ItemSource*)emalloc(sizeof(ItemSource));
368 static Item *getitems(ItemSource* is, uchar* data, int datalen);
370 // Parse an html document and create a list of layout items.
371 // Allocate and return document info in *pdi.
372 // When caller is done with the items, it should call
373 // freeitems on the returned result, and then
374 // freedocinfo(*pdi).
376 parsehtml(uchar* data, int datalen, Rune* pagesrc, int mtype, int chset, Docinfo** pdi)
383 di->src = _Strdup(pagesrc);
384 di->base = _Strdup(pagesrc);
385 di->mediatype = mtype;
388 is = newitemsource(di);
389 it = getitems(is, data, datalen);
390 freepstatestack(is->psstk);
395 // Get a group of tokens for lexer, parse them, and create
396 // a list of layout items.
397 // When caller is done with the items, it should call
398 // freeitems on the returned result.
400 getitems(ItemSource* is, uchar* data, int datalen)
476 doscripts = 0; // for now
480 toks = _gettoks(data, datalen, di->chset, di->mediatype, &tokslen);
482 for(; toki < tokslen; toki++) {
485 fprint(2, "build: curstate %ux, token %T\n", ps->curstate, tok);
494 else if(tag < Numtags + RBRA) {
495 brk = blockbrk[tag - RBRA];
500 addbrk(ps, brksp, 0);
506 // check common case first (Data), then switch statement on tag
508 // Lexing didn't pay attention to SGML record boundary rules:
509 // \n after start tag or before end tag to be discarded.
510 // (Lex has already discarded all \r's).
511 // Some pages assume this doesn't happen in <PRE> text,
512 // so we won't do it if literal is true.
513 // BUG: won't discard \n before a start tag that begins
514 // the next bufferful of tokens.
521 pt = toks[toki - 1].tag;
522 // IE and Netscape both ignore this rule (contrary to spec)
523 // if previous tag was img
524 if(pt < Numtags && pt != Timg && j > 0 && s[0] == '\n')
527 if(toki < tokslen - 1) {
528 nt = toks[toki + 1].tag;
529 if(nt >= RBRA && nt < Numtags + RBRA && j > i && s[j - 1] == '\n')
534 s = _Strsubstr(s, i, j);
540 _trimwhite(s, n, &t, &nt);
553 tok->text = nil; // token doesn't own string anymore
559 // Some abbrevs used in following DTD comments
561 // | TT | I | B | U | STRIKE | BIG | SMALL | SUB | SUP
562 // | EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE
563 // | A | IMG | APPLET | FONT | BASEFONT | BR | SCRIPT | MAP
564 // | INPUT | SELECT | TEXTAREA
565 // %block = P | UL | OL | DIR | MENU | DL | PRE | DL | DIV | CENTER
566 // | BLOCKQUOTE | FORM | ISINDEX | HR | TABLE
567 // %flow = (%text | %block)*
568 // %body.content = (%heading | %text | %block | ADDRESS)*
570 // <!ELEMENT A - - (%text) -(A)>
571 // Anchors are not supposed to be nested, but you sometimes see
572 // href anchors inside destination anchors.
574 if(ps->curanchor != 0) {
576 fprint(2, "warning: nested <A> or missing </A>\n");
579 name = aval(tok, Aname);
580 href = aurlval(tok, Ahref, nil, di->base);
581 // ignore rel, rev, and title attrs
583 target = atargval(tok, di->target);
584 di->anchors = newanchor(++is->nanchors, name, href, target, di->anchors);
586 name = _Strdup(name); // for DestAnchor construction, below
587 ps->curanchor = is->nanchors;
588 ps->curfg = push(&ps->fgstk, di->link);
589 ps->curul = push(&ps->ulstk, ULunder);
592 // add a null item to be destination
593 additem(ps, newispacer(ISPnull), tok);
594 di->dests = newdestanchor(++is->nanchors, name, ps->lastit, di->dests);
599 if(ps->curanchor != 0) {
600 ps->curfg = popretnewtop(&ps->fgstk, di->text);
601 ps->curul = popretnewtop(&ps->ulstk, ULnone);
606 // <!ELEMENT APPLET - - (PARAM | %text)* >
607 // We can't do applets, so ignore PARAMS, and let
608 // the %text contents appear for the alternative rep
611 if(warn && tag == Tapplet)
612 fprint(2, "warning: <APPLET> ignored\n");
615 // <!ELEMENT AREA - O EMPTY>
620 fprint(2, "warning: <AREA> not inside <MAP>\n");
623 map->areas = newarea(atabval(tok, Ashape, shape_tab, NSHAPETAB, SHrect),
624 aurlval(tok, Ahref, nil, di->base),
625 atargval(tok, di->target),
627 setdimarray(tok, Acoords, &map->areas->coords, &map->areas->ncoords);
630 // <!ELEMENT (B|STRONG) - - (%text)*>
633 pushfontstyle(ps, FntB);
651 // <!ELEMENT BASE - O EMPTY>
654 di->base = aurlval(tok, Ahref, di->base, di->base);
657 di->target = atargval(tok, di->target);
660 // <!ELEMENT BASEFONT - O EMPTY>
662 ps->adjsize = aintval(tok, Asize, 3) - 3;
665 // <!ELEMENT (BIG|SMALL) - - (%text)*>
673 pushfontsize(ps, sz);
681 // <!ELEMENT BLOCKQUOTE - - %body.content>
683 changeindent(ps, BQTAB);
686 case Tblockquote+RBRA:
687 changeindent(ps, -BQTAB);
690 // <!ELEMENT BODY O O %body.content>
693 bg = makebackground(nil, acolorval(tok, Abgcolor, di->background.color));
694 bgurl = aurlval(tok, Abackground, nil, di->base);
696 if(di->backgrounditem != nil)
697 freeitem((Item*)di->backgrounditem);
698 // really should remove old item from di->images list,
699 // but there should only be one BODY element ...
700 di->backgrounditem = (Iimage*)newiimage(bgurl, nil, ALnone, 0, 0, 0, 0, 0, 0, nil);
701 di->backgrounditem->nextimage = di->images;
702 di->images = di->backgrounditem;
706 di->text = acolorval(tok, Atext, di->text);
707 di->link = acolorval(tok, Alink, di->link);
708 di->vlink = acolorval(tok, Avlink, di->vlink);
709 di->alink = acolorval(tok, Aalink, di->alink);
710 if(di->text != ps->curfg) {
711 ps->curfg = di->text;
717 // HTML spec says ignore things after </body>,
718 // but IE and Netscape don't
722 // <!ELEMENT BR - O EMPTY>
724 addlinebrk(ps, atabval(tok, Aclear, clear_tab, NCLEARTAB, 0));
727 // <!ELEMENT CAPTION - - (%text;)*>
731 fprint(2, "warning: <CAPTION> outside <TABLE>\n");
734 if(curtab->caption != nil) {
736 fprint(2, "warning: more than one <CAPTION> in <TABLE>\n");
740 curtab->caption_place = atabval(tok, Aalign, align_tab, NALIGNTAB, ALtop);
745 if(curtab == nil || nextps == nil) {
747 fprint(2, "warning: unexpected </CAPTION>\n");
750 curtab->caption = ps->items->next;
760 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust);
769 // <!ELEMENT DD - O %flow >
771 if(ps->hangstk.n == 0) {
773 fprint(2, "warning: <DD> not inside <DL\n");
776 h = top(&ps->hangstk, 0);
778 changehang(ps, -10*LISTTAB);
781 push(&ps->hangstk, 0);
784 //<!ELEMENT (DIR|MENU) - - (LI)+ -(%block) >
785 //<!ELEMENT (OL|UL) - - (LI)+>
790 changeindent(ps, LISTTAB);
791 push(&ps->listtypestk, listtyval(tok, (tag==Tol)? LT1 : LTdisc));
792 push(&ps->listcntstk, aintval(tok, Astart, 1));
799 if(ps->listtypestk.n == 0) {
801 fprint(2, "warning: %T ended no list\n", tok);
805 pop(&ps->listtypestk);
806 pop(&ps->listcntstk);
807 changeindent(ps, -LISTTAB);
810 // <!ELEMENT DL - - (DT|DD)+ >
812 changeindent(ps, LISTTAB);
813 push(&ps->hangstk, 0);
817 if(ps->hangstk.n == 0) {
819 fprint(2, "warning: unexpected </DL>\n");
822 changeindent(ps, -LISTTAB);
823 if(top(&ps->hangstk, 0) != 0)
824 changehang(ps, -10*LISTTAB);
828 // <!ELEMENT DT - O (%text)* >
830 if(ps->hangstk.n == 0) {
832 fprint(2, "warning: <DT> not inside <DL>\n");
835 h = top(&ps->hangstk, 0);
838 changehang(ps, -10*LISTTAB);
839 changehang(ps, 10*LISTTAB);
840 push(&ps->hangstk, 1);
843 // <!ELEMENT FONT - - (%text)*>
845 sz = top(&ps->fntsizestk, Normal);
846 if(_tokaval(tok, Asize, &nsz, 0)) {
847 if(_prefix(L"+", nsz))
848 sz = Normal + _Strtol(nsz+1, nil, 10) + ps->adjsize;
849 else if(_prefix(L"-", nsz))
850 sz = Normal - _Strtol(nsz+1, nil, 10) + ps->adjsize;
852 sz = Normal + (_Strtol(nsz, nil, 10) - 3);
854 ps->curfg = push(&ps->fgstk, acolorval(tok, Acolor, ps->curfg));
855 pushfontsize(ps, sz);
859 if(ps->fgstk.n == 0) {
861 fprint(2, "warning: unexpected </FONT>\n");
864 ps->curfg = popretnewtop(&ps->fgstk, di->text);
868 // <!ELEMENT FORM - - %body.content -(FORM) >
870 if(is->curform != nil) {
872 fprint(2, "warning: <FORM> nested inside another\n");
875 action = aurlval(tok, Aaction, di->base, di->base);
877 name = astrval(tok, Aname, s);
880 target = atargval(tok, di->target);
881 method = atabval(tok, Amethod, method_tab, NMETHODTAB, HGet);
882 if(warn && _tokaval(tok, Aenctype, &enctype, 0) &&
883 _Strcmp(enctype, L"application/x-www-form-urlencoded"))
884 fprint(2, "form enctype %S not handled\n", enctype);
885 frm = newform(++is->nforms, name, action, target, method, di->forms);
891 if(is->curform == nil) {
893 fprint(2, "warning: unexpected </FORM>\n");
896 // put fields back in input order
897 is->curform->fields = (Formfield*)_revlist((List*)is->curform->fields);
901 // <!ELEMENT FRAME - O EMPTY>
906 fprint(2, "warning: <FRAME> not in <FRAMESET>\n");
909 ks->kidinfos = kd = newkidinfo(0, ks->kidinfos);
910 kd->src = aurlval(tok, Asrc, nil, di->base);
911 kd->name = aval(tok, Aname);
913 kd->name = runesmprint("_fr%d", ++is->nframes);
914 kd->marginw = auintval(tok, Amarginwidth, 0);
915 kd->marginh = auintval(tok, Amarginheight, 0);
916 kd->framebd = auintval(tok, Aframeborder, 1);
917 kd->flags = atabval(tok, Ascrolling, fscroll_tab, NFSCROLLTAB, kd->flags);
918 norsz = aflagval(tok, Anoresize);
920 kd->flags |= FRnoresize;
923 // <!ELEMENT FRAMESET - - (FRAME|FRAMESET)+>
925 ks = newkidinfo(1, nil);
930 ks->next = pks->kidinfos;
933 ks->nextframeset = pks;
935 setdimarray(tok, Arows, &ks->rows, &ks->nrows);
937 ks->rows = (Dimen*)emalloc(sizeof(Dimen));
939 ks->rows[0] = makedimen(Dpercent, 100);
941 setdimarray(tok, Acols, &ks->cols, &ks->ncols);
943 ks->cols = (Dimen*)emalloc(sizeof(Dimen));
945 ks->cols[0] = makedimen(Dpercent, 100);
950 if(is->kidstk == nil) {
952 fprint(2, "warning: unexpected </FRAMESET>\n");
956 // put kids back in original order
957 // and add blank frames to fill out cells
958 n = ks->nrows*ks->ncols;
959 nblank = n - _listlen((List*)ks->kidinfos);
961 ks->kidinfos = newkidinfo(0, ks->kidinfos);
962 ks->kidinfos = (Kidinfo*)_revlist((List*)ks->kidinfos);
963 is->kidstk = is->kidstk->nextframeset;
964 if(is->kidstk == nil) {
971 // <!ELEMENT H1 - - (%text;)*>, etc.
979 if(ps->items == ps->lastit)
981 addbrk(ps, bramt, IFcleft|IFcright);
982 sz = Verylarge - (tag - Th1);
985 pushfontsize(ps, sz);
986 sty = top(&ps->fntstylestk, FntR);
989 pushfontstyle(ps, sty);
990 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1000 addbrk(ps, 1, IFcleft|IFcright);
1007 // HTML spec says ignore regular markup in head,
1008 // but Netscape and IE don't
1016 // <!ELEMENT HR - O EMPTY>
1018 al = atabval(tok, Aalign, align_tab, NALIGNTAB, ALcenter);
1019 sz = auintval(tok, Asize, HRSZ);
1020 wd = adimen(tok, Awidth);
1021 if(dimenkind(wd) == Dnone)
1022 wd = makedimen(Dpercent, 100);
1023 nosh = aflagval(tok, Anoshade);
1024 color = acolorval(tok, Acolor, 0);
1025 additem(ps, newirule(al, sz, nosh, color, wd), tok);
1035 pushfontstyle(ps, FntI);
1038 // <!ELEMENT IMG - O EMPTY>
1041 oldcuranchor = ps->curanchor;
1042 if(_tokaval(tok, Ausemap, &usemap, 0)) {
1043 if(!_prefix(L"#", usemap)) {
1045 fprint(2, "warning: can't handle non-local map %S\n", usemap);
1048 map = getmap(di, usemap+1);
1049 if(ps->curanchor == 0) {
1050 di->anchors = newanchor(++is->nanchors, nil, nil, di->target, di->anchors);
1051 ps->curanchor = is->nanchors;
1055 align = atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom);
1057 if(ps->curanchor != 0)
1059 src = aurlval(tok, Asrc, nil, di->base);
1062 fprint(2, "warning: <img> has no src attribute\n");
1063 ps->curanchor = oldcuranchor;
1066 img = newiimage(src,
1069 auintval(tok, Awidth, 0),
1070 auintval(tok, Aheight, 0),
1071 auintval(tok, Ahspace, IMGHSPACE),
1072 auintval(tok, Avspace, IMGVSPACE),
1073 auintval(tok, Aborder, dfltbd),
1074 aflagval(tok, Aismap),
1076 if(align == ALleft || align == ALright) {
1077 additem(ps, newifloat(img, align), tok);
1078 // if no hspace specified, use FLTIMGHSPACE
1079 if(!_tokaval(tok, Ahspace, &val, 0))
1080 ((Iimage*)img)->hspace = FLTIMGHSPACE;
1084 additem(ps, img, tok);
1087 ((Iimage*)img)->nextimage = di->images;
1088 di->images = (Iimage*)img;
1090 ps->curanchor = oldcuranchor;
1093 // <!ELEMENT INPUT - O EMPTY>
1096 if(is->curform == nil) {
1098 fprint(2, "<INPUT> not inside <FORM>\n");
1101 is->curform->fields = field = newformfield(
1102 atabval(tok, Atype, input_tab, NINPUTTAB, Ftext),
1103 ++is->curform->nfields,
1107 auintval(tok, Asize, 0),
1108 auintval(tok, Amaxlength, 1000),
1109 is->curform->fields);
1110 if(aflagval(tok, Achecked))
1111 field->flags = FFchecked;
1113 switch(field->ftype) {
1117 if(field->size == 0)
1122 if(field->name == nil) {
1124 fprint(2, "warning: checkbox form field missing name\n");
1127 if(field->value == nil)
1128 field->value = _Strdup(L"1");
1132 if(field->name == nil || field->value == nil) {
1134 fprint(2, "warning: radio form field missing name or value\n");
1140 if(field->value == nil)
1141 field->value = _Strdup(L"Submit");
1142 if(field->name == nil)
1143 field->name = _Strdup(L"_no_name_submit_");
1147 src = aurlval(tok, Asrc, nil, di->base);
1150 fprint(2, "warning: image form field missing src\n");
1153 // width and height attrs aren't specified in HTML 3.2,
1154 // but some people provide them and they help avoid
1156 field->image = newiimage(src,
1157 astrval(tok, Aalt, L"Submit"),
1158 atabval(tok, Aalign, align_tab, NALIGNTAB, ALbottom),
1159 auintval(tok, Awidth, 0), auintval(tok, Aheight, 0),
1161 ii = (Iimage*)field->image;
1162 ii->nextimage = di->images;
1167 if(field->value == nil)
1168 field->value = _Strdup(L"Reset");
1172 if(field->value == nil)
1173 field->value = _Strdup(L" ");
1176 ffit = newiformfield(field);
1177 additem(ps, ffit, tok);
1178 if(ffit->genattr != nil)
1179 field->events = ffit->genattr->events;
1182 // <!ENTITY ISINDEX - O EMPTY>
1185 prompt = astrval(tok, Aprompt, L"Index search terms:");
1186 target = atargval(tok, di->target);
1187 additem(ps, textit(ps, prompt), tok);
1188 frm = newform(++is->nforms,
1195 ff = newformfield(Ftext,
1198 _Strdup(L"_ISINDEX_"),
1205 additem(ps, newiformfield(ff), tok);
1209 // <!ELEMENT LI - O %flow>
1211 if(ps->listtypestk.n == 0) {
1213 fprint(2, "<LI> not in list\n");
1216 ty = top(&ps->listtypestk, 0);
1217 ty2 = listtyval(tok, ty);
1220 push(&ps->listtypestk, ty2);
1222 v = aintval(tok, Avalue, top(&ps->listcntstk, 1));
1223 if(ty == LTdisc || ty == LTsquare || ty == LTcircle)
1224 hang = 10*LISTTAB - 3;
1226 hang = 10*LISTTAB - 1;
1227 changehang(ps, hang);
1228 addtext(ps, listmark(ty, v));
1229 push(&ps->listcntstk, v + 1);
1230 changehang(ps, -hang);
1234 // <!ELEMENT MAP - - (AREA)+>
1236 if(_tokaval(tok, Aname, &name, 0))
1237 is->curmap = getmap(di, name);
1244 fprint(2, "warning: unexpected </MAP>\n");
1247 map->areas = (Area*)_revlist((List*)map->areas);
1253 if(_tokaval(tok, Ahttp_equiv, &equiv, 0)) {
1254 val = aval(tok, Acontent);
1256 if(!_Strncmpci(equiv, n, L"refresh"))
1258 else if(!_Strncmpci(equiv, n, L"content-script-type")) {
1260 if(!_Strncmpci(val, n, L"javascript")
1261 || !_Strncmpci(val, n, L"jscript1.1")
1262 || !_Strncmpci(val, n, L"jscript"))
1263 di->scripttype = TextJavascript;
1266 fprint(2, "unimplemented script type %S\n", val);
1267 di->scripttype = UnknownType;
1273 // Nobr is NOT in HMTL 4.0, but it is ubiquitous on the web
1276 ps->curstate &= ~IFwrap;
1280 ps->curstate |= IFwrap;
1283 // We do frames, so skip stuff in noframes
1288 case Tnoframes+RBRA:
1292 // We do scripts (if enabled), so skip stuff in noscripts
1298 case Tnoscript+RBRA:
1303 // <!ELEMENT OPTION - O ( //PCDATA)>
1305 if(is->curform == nil || is->curform->fields == nil) {
1307 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1310 field = is->curform->fields;
1311 if(field->ftype != Fselect) {
1313 fprint(2, "warning: <OPTION> not in <SELECT>\n");
1316 val = aval(tok, Avalue);
1317 option = newoption(aflagval(tok, Aselected), val, nil, field->options);
1318 field->options = option;
1319 option->display = getpcdata(toks, tokslen, &toki);
1321 option->value = _Strdup(option->display);
1324 // <!ELEMENT P - O (%text)* >
1326 pushjust(ps, atabval(tok, Aalign, align_tab, NALIGNTAB, ps->curjust));
1334 // <!ELEMENT PARAM - O EMPTY>
1335 // Do something when we do applets...
1339 // <!ELEMENT PRE - - (%text)* -(IMG|BIG|SMALL|SUB|SUP|FONT) >
1341 ps->curstate &= ~IFwrap;
1344 pushfontstyle(ps, FntT);
1348 ps->curstate |= IFwrap;
1355 // <!ELEMENT SCRIPT - - CDATA>
1358 if(!di->hasscripts) {
1359 if(di->scripttype == TextJavascript) {
1360 // TODO: initialize script if nec.
1366 if(!di->hasscripts) {
1368 fprint(2, "warning: <SCRIPT> ignored\n");
1372 scriptsrc = aurlval(tok, Asrc, nil, di->base);
1374 if(scriptsrc != nil) {
1376 fprint(2, "warning: non-local <SCRIPT> ignored\n");
1380 script = getpcdata(toks, tokslen, &toki);
1384 fprint(2, "script ignored\n");
1394 // <!ELEMENT SELECT - - (OPTION+)>
1396 if(is->curform == nil) {
1398 fprint(2, "<SELECT> not inside <FORM>\n");
1401 field = newformfield(Fselect,
1402 ++is->curform->nfields,
1406 auintval(tok, Asize, 0),
1408 is->curform->fields);
1409 is->curform->fields = field;
1410 if(aflagval(tok, Amultiple))
1411 field->flags = FFmultiple;
1412 ffit = newiformfield(field);
1413 additem(ps, ffit, tok);
1414 if(ffit->genattr != nil)
1415 field->events = ffit->genattr->events;
1416 // throw away stuff until next tag (should be <OPTION>)
1417 s = getpcdata(toks, tokslen, &toki);
1423 if(is->curform == nil || is->curform->fields == nil) {
1425 fprint(2, "warning: unexpected </SELECT>\n");
1428 field = is->curform->fields;
1429 if(field->ftype != Fselect)
1431 // put options back in input order
1432 field->options = (Option*)_revlist((List*)field->options);
1435 // <!ELEMENT (STRIKE|U) - - (%text)*>
1438 ps->curul = push(&ps->ulstk, (tag==Tstrike)? ULmid : ULunder);
1443 if(ps->ulstk.n == 0) {
1445 fprint(2, "warning: unexpected %T\n", tok);
1448 ps->curul = popretnewtop(&ps->ulstk, ULnone);
1451 // <!ELEMENT STYLE - - CDATA>
1454 fprint(2, "warning: unimplemented <STYLE>\n");
1462 // <!ELEMENT (SUB|SUP) - - (%text)*>
1466 ps->curvoff += SUBOFF;
1468 ps->curvoff -= SUPOFF;
1469 push(&ps->voffstk, ps->curvoff);
1470 sz = top(&ps->fntsizestk, Normal);
1471 pushfontsize(ps, sz - 1);
1476 if(ps->voffstk.n == 0) {
1478 fprint(2, "warning: unexpected %T\n", tok);
1481 ps->curvoff = popretnewtop(&ps->voffstk, 0);
1485 // <!ELEMENT TABLE - - (CAPTION?, TR+)>
1488 tab = newtable(++is->ntables,
1490 adimen(tok, Awidth),
1491 aflagval(tok, Aborder),
1492 auintval(tok, Acellspacing, TABSP),
1493 auintval(tok, Acellpadding, TABPAD),
1494 makebackground(nil, acolorval(tok, Abgcolor, ps->curbg.color)),
1504 fprint(2, "warning: unexpected </TABLE>\n");
1507 isempty = (curtab->cells == nil);
1510 fprint(2, "warning: <TABLE> has no cells\n");
1513 ps = finishcell(curtab, ps);
1514 if(curtab->rows != nil)
1515 curtab->rows->flags = 0;
1516 finish_table(curtab);
1520 tabitem = newitable(curtab);
1521 al = curtab->align.halign;
1525 additem(ps, newifloat(tabitem, al), tok);
1529 pushjust(ps, ALcenter);
1535 additem(ps, tabitem, curtab->tabletok);
1541 if(is->tabstk == nil) {
1543 fprint(2, "warning: table stack is wrong\n");
1546 is->tabstk = is->tabstk->next;
1547 curtab->next = di->tables;
1548 di->tables = curtab;
1549 curtab = is->tabstk;
1554 // <!ELEMENT (TH|TD) - O %body.content>
1555 // Cells for a row are accumulated in reverse order.
1556 // We push ps on a stack, and use a new one to accumulate
1557 // the contents of the cell.
1562 fprint(2, "%T outside <TABLE>\n", tok);
1569 ps = finishcell(curtab, ps);
1571 if(curtab->rows != nil)
1573 if(tr == nil || !tr->flags) {
1575 fprint(2, "%T outside row\n", tok);
1576 tr = newtablerow(makealign(ALnone, ALnone),
1577 makebackground(nil, curtab->background.color),
1582 ps = cell_pstate(ps, tag == Tth);
1584 if(aflagval(tok, Anowrap)) {
1586 ps->curstate &= ~IFwrap;
1590 c = newtablecell(curtab->cells==nil? 1 : curtab->cells->cellid+1,
1591 auintval(tok, Arowspan, 1),
1592 auintval(tok, Acolspan, 1),
1594 adimen(tok, Awidth),
1595 auintval(tok, Aheight, 0),
1596 makebackground(nil, acolorval(tok, Abgcolor, tr->background.color)),
1600 ps->curbg = c->background;
1601 if(c->align.halign == ALnone) {
1602 if(tr->align.halign != ALnone)
1603 c->align.halign = tr->align.halign;
1605 c->align.halign = ALcenter;
1607 c->align.halign = ALleft;
1609 if(c->align.valign == ALnone) {
1610 if(tr->align.valign != ALnone)
1611 c->align.valign = tr->align.valign;
1613 c->align.valign = ALmiddle;
1615 c->nextinrow = tr->cells;
1621 if(curtab == nil || curtab->cells == nil) {
1623 fprint(2, "unexpected %T\n", tok);
1626 ps = finishcell(curtab, ps);
1629 // <!ELEMENT TEXTAREA - - ( //PCDATA)>
1631 if(is->curform == nil) {
1633 fprint(2, "<TEXTAREA> not inside <FORM>\n");
1636 field = newformfield(Ftextarea,
1637 ++is->curform->nfields,
1643 is->curform->fields);
1644 is->curform->fields = field;
1645 field->rows = auintval(tok, Arows, 3);
1646 field->cols = auintval(tok, Acols, 50);
1647 field->value = getpcdata(toks, tokslen, &toki);
1648 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttextarea + RBRA)
1649 fprint(2, "warning: <TEXTAREA> data ended by %T\n", &toks[toki + 1]);
1650 ffit = newiformfield(field);
1651 additem(ps, ffit, tok);
1652 if(ffit->genattr != nil)
1653 field->events = ffit->genattr->events;
1656 // <!ELEMENT TITLE - - ( //PCDATA)* -(%head.misc)>
1658 di->doctitle = getpcdata(toks, tokslen, &toki);
1659 if(warn && toki < tokslen - 1 && toks[toki + 1].tag != Ttitle + RBRA)
1660 fprint(2, "warning: <TITLE> data ended by %T\n", &toks[toki + 1]);
1663 // <!ELEMENT TR - O (TH|TD)+>
1664 // rows are accumulated in reverse order in curtab->rows
1668 fprint(2, "warning: <TR> outside <TABLE>\n");
1675 ps = finishcell(curtab, ps);
1676 if(curtab->rows != nil)
1677 curtab->rows->flags = 0;
1678 curtab->rows = newtablerow(aalign(tok),
1679 makebackground(nil, acolorval(tok, Abgcolor, curtab->background.color)),
1685 if(curtab == nil || curtab->rows == nil) {
1687 fprint(2, "warning: unexpected </TR>\n");
1690 ps = finishcell(curtab, ps);
1692 if(tr->cells == nil) {
1694 fprint(2, "warning: empty row\n");
1695 curtab->rows = tr->next;
1702 // <!ELEMENT (TT|CODE|KBD|SAMP) - - (%text)*>
1707 pushfontstyle(ps, FntT);
1710 // Tags that have empty action
1717 case Tbasefont+RBRA:
1734 case Ttextarea+RBRA:
1739 // Tags not implemented
1747 case Tfieldset+RBRA:
1759 case Toptgroup+RBRA:
1765 fprint(2, "warning: unimplemented HTML tag: %S\n", tagnames[tag]);
1771 fprint(2, "warning: unknown HTML tag: %S\n", tok->text);
1775 // some pages omit trailing </table>
1776 while(curtab != nil) {
1778 fprint(2, "warning: <TABLE> not closed\n");
1779 if(curtab->cells != nil) {
1780 ps = finishcell(curtab, ps);
1781 if(curtab->cells == nil) {
1783 fprint(2, "warning: empty table\n");
1786 if(curtab->rows != nil)
1787 curtab->rows->flags = 0;
1788 finish_table(curtab);
1790 additem(ps, newitable(curtab), curtab->tabletok);
1794 if(is->tabstk != nil)
1795 is->tabstk = is->tabstk->next;
1796 curtab->next = di->tables;
1797 di->tables = curtab;
1798 curtab = is->tabstk;
1800 outerps = lastps(ps);
1801 ans = outerps->items->next;
1802 freeitem(outerps->items);
1803 // note: ans may be nil and di->kids not nil, if there's a frameset!
1804 outerps->items = newispacer(ISPnull);
1805 outerps->lastit = outerps->items;
1807 if(ans != nil && di->hasscripts) {
1808 // TODO evalscript(nil);
1814 assert(validitems(ans));
1816 fprint(2, "getitems returning nil\n");
1818 printitems(ans, "getitems returning:");
1823 // Concatenate together maximal set of Data tokens, starting at toks[toki+1].
1824 // Lexer has ensured that there will either be a following non-data token or
1825 // we will be at eof.
1826 // Return emallocd trimmed concatenation, and update *ptoki to last used toki
1828 getpcdata(Token* toks, int tokslen, int* ptoki)
1840 // first find length of answer
1841 toki = (*ptoki) + 1;
1842 while(toki < tokslen) {
1844 if(tok->tag == Data) {
1846 anslen += _Strlen(tok->text);
1851 // now make up the initial answer
1853 ans = _newstr(anslen);
1855 toki = (*ptoki) + 1;
1856 while(toki < tokslen) {
1858 if(tok->tag == Data) {
1860 p = _Stradd(p, tok->text, _Strlen(tok->text));
1866 _trimwhite(ans, anslen, &trimans, &trimanslen);
1867 if(trimanslen != anslen) {
1869 ans = _Strndup(trimans, trimanslen);
1877 // If still parsing head of curtab->cells list, finish it off
1878 // by transferring the items on the head of psstk to the cell.
1879 // Then pop the psstk and return the new psstk.
1881 finishcell(Table* curtab, Pstate* psstk)
1888 if((c->flags&TFparsing)) {
1889 psstknext = psstk->next;
1890 if(psstknext == nil) {
1892 fprint(2, "warning: parse state stack is wrong\n");
1895 c->content = psstk->items->next;
1896 c->flags &= ~TFparsing;
1905 // Make a new Pstate for a cell, based on the old pstate, oldps.
1906 // Also, put the new ps on the head of the oldps stack.
1908 cell_pstate(Pstate* oldps, int ishead)
1913 ps = newpstate(oldps);
1915 ps->curanchor = oldps->curanchor;
1916 copystack(&ps->fntstylestk, &oldps->fntstylestk);
1917 copystack(&ps->fntsizestk, &oldps->fntsizestk);
1918 ps->curfont = oldps->curfont;
1919 ps->curfg = oldps->curfg;
1920 ps->curbg = oldps->curbg;
1921 copystack(&ps->fgstk, &oldps->fgstk);
1922 ps->adjsize = oldps->adjsize;
1924 sty = ps->curfont%NumSize;
1925 ps->curfont = FntB*NumSize + sty;
1930 // Return a new Pstate with default starting state.
1931 // Use link to add it to head of a list, if any.
1933 newpstate(Pstate* link)
1937 ps = (Pstate*)emalloc(sizeof(Pstate));
1938 ps->curfont = DefFnt;
1940 ps->curbg.image = nil;
1941 ps->curbg.color = White;
1943 ps->curjust = ALleft;
1944 ps->curstate = IFwrap;
1945 ps->items = newispacer(ISPnull);
1946 ps->lastit = ps->items;
1947 ps->prelastit = nil;
1952 // Return last Pstate on psl list
1957 while(psl->next != nil)
1962 // Add it to end of ps item chain, adding in current state from ps.
1963 // Also, if tok is not nil, scan it for generic attributes and assign
1964 // the genattr field of the item accordingly.
1966 additem(Pstate* ps, Item* it, Token* tok)
1979 fprint(2, "warning: skipping item: %I\n", it);
1982 it->anchorid = ps->curanchor;
1983 it->state |= ps->curstate;
1991 for(a = tok->attr; a != nil; a = a->next) {
2013 assert(aid >= Aonblur && aid <= Aonunload);
2014 e = newscriptevent(scriptev[a->attid], a->value, e);
2021 it->genattr = newgenattr(i, c, s, t, e);
2023 ps->curstate &= ~(IFbrk|IFbrksp|IFnobrk|IFcleft|IFcright);
2024 ps->prelastit = ps->lastit;
2025 ps->lastit->next = it;
2029 // Make a text item out of s,
2030 // using current font, foreground, vertical offset and underline state.
2032 textit(Pstate* ps, Rune* s)
2035 return newitext(s, ps->curfont, ps->curfg, ps->curvoff + Voffbias, ps->curul);
2038 // Add text item or items for s, paying attention to
2039 // current font, foreground, baseline offset, underline state,
2040 // and literal mode. Unless we're in literal mode, compress
2041 // whitespace to single blank, and, if curstate has a break,
2042 // trim any leading whitespace. Whether in literal mode or not,
2043 // turn nonbreaking spaces into spacer items with IFnobrk set.
2045 // In literal mode, break up s at newlines and add breaks instead.
2046 // Also replace tabs appropriate number of spaces.
2047 // In nonliteral mode, break up the items every 100 or so characters
2048 // just to make the layout algorithm not go quadratic.
2050 // addtext assumes ownership of s.
2052 addtext(Pstate* ps, Rune* s)
2064 Rune buf[SMALLBUFSIZE];
2075 // trim trailing blanks from line
2076 for(k = i; k > j; k--)
2080 additem(ps, textit(ps, _Strndup(s+j, k-j)), nil);
2090 // make ss = s[j:i] + nsp spaces
2091 ss = _newstr(i-j+nsp);
2092 p = _Stradd(ss, s+j, i-j);
2093 p = _Stradd(p, L" ", nsp);
2095 additem(ps, textit(ps, ss), nil);
2099 else if(s[i] == NBSP) {
2101 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2110 if(j == 0 && i == n) {
2111 // just transfer s over
2112 additem(ps, textit(ps, s), nil);
2115 additem(ps, textit(ps, _Strndup(s+j, i-j)), nil);
2120 else { // not literal mode
2121 if((ps->curstate&IFbrk) || ps->lastit == ps->items)
2124 if(c >= 256 || !isspace(c))
2129 for(j = i; i < n; i++) {
2130 assert(p+i-j < buf+SMALLBUFSIZE-1);
2134 p = _Stradd(p, s+j, i-j);
2136 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2142 if(c < 256 && isspace(c)) {
2144 p = _Stradd(p, s+j, i-j);
2148 if(c >= 256 || !isspace(c))
2155 p = _Stradd(p, s+j, i+1-j);
2159 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2163 if(i > j && j < n) {
2164 assert(p+i-j < buf+SMALLBUFSIZE-1);
2165 p = _Stradd(p, s+j, i-j);
2167 // don't add a space if previous item ended in a space
2168 if(p-buf == 1 && buf[0] == ' ' && ps->lastit != nil) {
2170 if(it->tag == Itexttag) {
2171 ss = ((Itext*)it)->s;
2173 if(k > 0 && ss[k] == ' ')
2178 additem(ps, textit(ps, _Strndup(buf, p-buf)), nil);
2183 // Add a break to ps->curstate, with extra space if sp is true.
2184 // If there was a previous break, combine this one's parameters
2185 // with that to make the amt be the max of the two and the clr
2186 // be the most general. (amt will be 0 or 1)
2187 // Also, if the immediately preceding item was a text item,
2188 // trim any whitespace from the end of it, if not in literal mode.
2189 // Finally, if this is at the very beginning of the item list
2190 // (the only thing there is a null spacer), then don't add the space.
2192 addbrk(Pstate* ps, int sp, int clr)
2202 state = ps->curstate;
2203 clr = clr|(state&(IFcleft|IFcright));
2204 if(sp && !(ps->lastit == ps->items))
2208 ps->curstate = IFbrk|sp|(state&~(IFcleft|IFcright))|clr;
2209 if(ps->lastit != ps->items) {
2210 if(!ps->literal && ps->lastit->tag == Itexttag) {
2211 t = (Itext*)ps->lastit;
2212 _splitr(t->s, _Strlen(t->s), notwhitespace, &l, &nl, &r, &nr);
2213 // try to avoid making empty items
2214 // but not crucial f the occasional one gets through
2215 if(nl == 0 && ps->prelastit != nil) {
2216 ps->lastit = ps->prelastit;
2217 ps->lastit->next = nil;
2218 ps->prelastit = nil;
2223 // need a non-nil pointer to empty string
2224 // (_Strdup(L"") returns nil)
2225 t->s = emalloc(sizeof(Rune));
2229 t->s = _Strndup(l, nl);
2237 // Add break due to a <br> or a newline within a preformatted section.
2238 // We add a null item first, with current font's height and ascent, to make
2239 // sure that the current line takes up at least that amount of vertical space.
2240 // This ensures that <br>s on empty lines cause blank lines, and that
2241 // multiple <br>s in a row give multiple blank lines.
2242 // However don't add the spacer if the previous item was something that
2243 // takes up space itself.
2245 addlinebrk(Pstate* ps, int clr)
2250 // don't want break before our null item unless the previous item
2251 // was also a null item for the purposes of line breaking
2252 obrkstate = ps->curstate&(IFbrk|IFbrksp);
2254 if(ps->lastit != nil) {
2255 if(ps->lastit->tag == Ispacertag) {
2256 if(((Ispacer*)ps->lastit)->spkind == ISPvline)
2260 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|b;
2261 additem(ps, newispacer(ISPvline), nil);
2262 ps->curstate = (ps->curstate&~(IFbrk|IFbrksp))|obrkstate;
2266 // Add a nonbreakable space
2270 // if nbsp comes right where a break was specified,
2271 // do the break anyway (nbsp is being used to generate undiscardable
2272 // space rather than to prevent a break)
2273 if((ps->curstate&IFbrk) == 0)
2274 ps->curstate |= IFnobrk;
2275 additem(ps, newispacer(ISPhspace), nil);
2276 // but definitely no break on next item
2277 ps->curstate |= IFnobrk;
2280 // Change hang in ps.curstate by delta.
2281 // The amount is in 1/10ths of tabs, and is the amount that
2282 // the current contiguous set of items with a hang value set
2283 // is to be shifted left from its normal (indented) place.
2285 changehang(Pstate* ps, int delta)
2289 amt = (ps->curstate&IFhangmask) + delta;
2292 fprint(2, "warning: hang went negative\n");
2295 ps->curstate = (ps->curstate&~IFhangmask)|amt;
2298 // Change indent in ps.curstate by delta.
2300 changeindent(Pstate* ps, int delta)
2304 amt = ((ps->curstate&IFindentmask) >> IFindentshift) + delta;
2307 fprint(2, "warning: indent went negative\n");
2310 ps->curstate = (ps->curstate&~IFindentmask)|(amt << IFindentshift);
2313 // Push val on top of stack, and also return value pushed
2315 push(Stack* stk, int val)
2317 if(stk->n == Nestmax) {
2319 fprint(2, "warning: build stack overflow\n");
2322 stk->slots[stk->n++] = val;
2334 //Return top of stack, using dflt if stack is empty
2336 top(Stack* stk, int dflt)
2340 return stk->slots[stk->n-1];
2343 // pop, then return new top, with dflt if empty
2345 popretnewtop(Stack* stk, int dflt)
2352 return stk->slots[stk->n-1];
2355 // Copy fromstk entries into tostk
2357 copystack(Stack* tostk, Stack* fromstk)
2363 memmove(tostk->slots, fromstk->slots, n*sizeof(int));
2367 popfontstyle(Pstate* ps)
2369 pop(&ps->fntstylestk);
2374 pushfontstyle(Pstate* ps, int sty)
2376 push(&ps->fntstylestk, sty);
2381 popfontsize(Pstate* ps)
2383 pop(&ps->fntsizestk);
2388 pushfontsize(Pstate* ps, int sz)
2390 push(&ps->fntsizestk, sz);
2395 setcurfont(Pstate* ps)
2400 sty = top(&ps->fntstylestk, FntR);
2401 sz = top(&ps->fntsizestk, Normal);
2406 ps->curfont = sty*NumSize + sz;
2417 pushjust(Pstate* ps, int j)
2419 push(&ps->juststk, j);
2424 setcurjust(Pstate* ps)
2429 j = top(&ps->juststk, ALleft);
2430 if(j != ps->curjust) {
2432 state = ps->curstate;
2433 state &= ~(IFrjust|IFcjust);
2436 else if(j == ALright)
2438 ps->curstate = state;
2442 // Do final rearrangement after table parsing is finished
2443 // and assign cells to grid points
2445 finish_table(Table* t)
2453 Tablecell** rowspancell;
2469 t->nrow = nrow = _listlen((List*)rl);
2470 t->rows = (Tablerow*)emalloc(nrow * sizeof(Tablerow));
2473 for(row = rl; row != nil; row = rownext) {
2474 // copy the data from the allocated Tablerow into the array slot
2476 rownext = row->next;
2482 // If rowspan is > 1 but this is the last row,
2483 // reset the rowspan
2484 if(c != nil && c->rowspan > 1 && r == nrow-2)
2487 // reverse row->cells list (along nextinrow pointers)
2490 cnext = c->nextinrow;
2491 c->nextinrow = row->cells;
2493 rcols += c->colspan;
2500 t->cols = (Tablecol*)emalloc(ncol * sizeof(Tablecol));
2502 // Reverse cells just so they are drawn in source order.
2503 // Also, trim their contents so they don't end in whitespace.
2504 t->cells = (Tablecell*)_revlist((List*)t->cells);
2505 for(c = t->cells; c != nil; c= c->next)
2507 t->grid = (Tablecell***)emalloc(nrow * sizeof(Tablecell**));
2508 for(i = 0; i < nrow; i++)
2509 t->grid[i] = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2511 // The following arrays keep track of cells that are spanning
2512 // multiple rows; rowspancnt[i] is the number of rows left
2513 // to be spanned in column i.
2514 // When done, cell's (row,col) is upper left grid point.
2515 rowspancnt = (int*)emalloc(ncol * sizeof(int));
2516 rowspancell = (Tablecell**)emalloc(ncol * sizeof(Tablecell*));
2517 for(ri = 0; ri < nrow; ri++) {
2521 while(ci < ncol || cl != nil) {
2522 if(ci < ncol && rowspancnt[ci] > 0) {
2523 t->grid[ri][ci] = rowspancell[ci];
2536 if(ci + cspan > ncol) {
2537 // because of row spanning, we calculated
2538 // ncol incorrectly; adjust it
2539 newncol = ci + cspan;
2540 t->cols = (Tablecol*)erealloc(t->cols, newncol * sizeof(Tablecol));
2541 rowspancnt = (int*)erealloc(rowspancnt, newncol * sizeof(int));
2542 rowspancell = (Tablecell**)erealloc(rowspancell, newncol * sizeof(Tablecell*));
2544 memset(t->cols+ncol, 0, k*sizeof(Tablecol));
2545 memset(rowspancnt+ncol, 0, k*sizeof(int));
2546 memset(rowspancell+ncol, 0, k*sizeof(Tablecell*));
2547 for(j = 0; j < nrow; j++) {
2548 t->grid[j] = (Tablecell**)erealloc(t->grid[j], newncol * sizeof(Tablecell*));
2549 memset(t->grid[j], 0, k*sizeof(Tablecell*));
2551 t->ncol = ncol = newncol;
2555 for(i = 0; i < cspan; i++) {
2556 t->grid[ri][ci] = c;
2558 rowspancnt[ci] = rspan - 1;
2559 rowspancell[ci] = c;
2570 // Remove tail of cell content until it isn't whitespace.
2572 trim_cell(Tablecell* c)
2585 while(c->content != nil && dropping) {
2588 while(p->next != nil) {
2593 if(!(p->state&IFnobrk)) {
2594 if(p->tag == Itexttag) {
2597 _splitr(s, _Strlen(s), notwhitespace, &x, &nx, &y, &ny);
2598 if(nx != 0 && ny != 0) {
2599 q->s = _Strndup(x, nx);
2615 // Caller must free answer (eventually).
2617 listmark(uchar ty, int n)
2630 s[0] = (ty == LTdisc)? 0x2022 // bullet
2631 : ((ty == LTsquare)? 0x220e // filled square
2632 : 0x2218); // degree
2637 s = runesmprint("%d.", n);
2646 s = _newstr((n <= 25)? 2 : 3);
2652 s[i++] = n2 + (ty == LTa)? 'a' : 'A';
2654 s[i++] = n + (ty == LTa)? 'a' : 'A';
2663 fprint(2, "warning: unimplemented roman number > %d\n", NROMAN);
2669 for(i = 0; i < n2; i++)
2670 s[i] = (ty == LTi)? tolower(t[i]) : t[i];
2678 // Find map with given name in di.maps.
2679 // If not there, add one, copying name.
2680 // Ownership of map remains with di->maps list.
2682 getmap(Docinfo* di, Rune* name)
2686 for(m = di->maps; m != nil; m = m->next) {
2687 if(!_Strcmp(name, m->name))
2690 m = (Map*)emalloc(sizeof(Map));
2691 m->name = _Strdup(name);
2698 // Transfers ownership of href to Area
2700 newarea(int shape, Rune* href, int target, Area* link)
2704 a = (Area*)emalloc(sizeof(Area));
2712 // Return string value associated with attid in tok, nil if none.
2713 // Caller must free the result (eventually).
2715 aval(Token* tok, int attid)
2719 _tokaval(tok, attid, &ans, 1); // transfers string ownership from token to ans
2723 // Like aval, but use dflt if there was no such attribute in tok.
2724 // Caller must free the result (eventually).
2726 astrval(Token* tok, int attid, Rune* dflt)
2730 if(_tokaval(tok, attid, &ans, 1))
2731 return ans; // transfers string ownership from token to ans
2733 return _Strdup(dflt);
2736 // Here we're supposed to convert to an int,
2737 // and have a default when not found
2739 aintval(Token* tok, int attid, int dflt)
2743 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
2749 // Like aintval, but result should be >= 0
2751 auintval(Token* tok, int attid, int dflt)
2756 if(!_tokaval(tok, attid, &ans, 0) || ans == nil)
2760 return v >= 0? v : 0;
2764 // int conversion, but with possible error check (if warning)
2771 ans = _Strtol(s, &eptr, 10);
2774 eptr = _Strclass(eptr, notwhitespace);
2776 fprint(2, "warning: expected integer, got %S\n", s);
2782 // Attribute value when need a table to convert strings to ints
2784 atabval(Token* tok, int attid, StringInt* tab, int ntab, int dflt)
2790 if(_tokaval(tok, attid, &aval, 0)) {
2791 if(!_lookup(tab, ntab, aval, _Strlen(aval), &ans)) {
2794 fprint(2, "warning: name not found in table lookup: %S\n", aval);
2800 // Attribute value when supposed to be a color
2802 acolorval(Token* tok, int attid, int dflt)
2808 if(_tokaval(tok, attid, &aval, 0))
2809 ans = color(aval, dflt);
2813 // Attribute value when supposed to be a target frame name
2815 atargval(Token* tok, int dflt)
2821 if(_tokaval(tok, Atarget, &aval, 0)){
2822 ans = targetid(aval);
2827 // special for list types, where "i" and "I" are different,
2828 // but "square" and "SQUARE" are the same
2830 listtyval(Token* tok, int dflt)
2837 if(_tokaval(tok, Atype, &aval, 0)) {
2857 fprint(2, "warning: unknown list element type %c\n", aval[0]);
2861 if(!_Strncmpci(aval, n, L"circle"))
2863 else if(!_Strncmpci(aval, n, L"disc"))
2865 else if(!_Strncmpci(aval, n, L"square"))
2869 fprint(2, "warning: unknown list element type %S\n", aval);
2876 // Attribute value when value is a URL, possibly relative to base.
2877 // FOR NOW: leave the url relative.
2878 // Caller must free the result (eventually).
2880 aurlval(Token* tok, int attid, Rune* dflt, Rune* base)
2887 if(_tokaval(tok, attid, &url, 0) && url != nil)
2888 ans = removeallwhite(url);
2890 ans = _Strdup(dflt);
2894 // Return copy of s but with all whitespace (even internal) removed.
2895 // This fixes some buggy URL specification strings.
2897 removeallwhite(Rune* s)
2907 for(i = 0; i < n; i++) {
2909 if(c >= 256 || !isspace(c))
2915 for(i = 0; i < n; i++) {
2917 if(c >= 256 || !isspace(c))
2927 // Attribute value when mere presence of attr implies value of 1,
2928 // but if there is an integer there, return it as the value.
2930 aflagval(Token* tok, int attid)
2936 if(_tokaval(tok, attid, &sval, 0)) {
2945 makealign(int halign, int valign)
2954 // Make an Align (two alignments, horizontal and vertical)
2959 atabval(tok, Aalign, align_tab, NALIGNTAB, ALnone),
2960 atabval(tok, Avalign, align_tab, NALIGNTAB, ALnone));
2963 // Make a Dimen, based on value of attid attr
2965 adimen(Token* tok, int attid)
2969 if(_tokaval(tok, attid, &wd, 0))
2970 return parsedim(wd, _Strlen(wd));
2972 return makedimen(Dnone, 0);
2975 // Parse s[0:n] as num[.[num]][unit][%|*]
2977 parsedim(Rune* s, int ns)
2994 _splitl(s, ns, L"^0-9", &l, &nl, &r, &nr);
2996 spec = 1000*_Strtol(l, nil, 10);
2997 if(nr > 0 && r[0] == '.') {
2998 _splitl(r+1, nr-1, L"^0-9", &f, &nf, &r, &nr);
3001 for(i = 0; i < nf; i++) {
3002 spec = spec + mul*(f[i]-'0');
3014 if(!_Strncmpci(units, 2, L"pt"))
3015 spec = (spec*Tkdpi)/72;
3016 else if(!_Strncmpci(units, 2, L"pi"))
3017 spec = (spec*12*Tkdpi)/72;
3018 else if(!_Strncmpci(units, 2, L"in"))
3020 else if(!_Strncmpci(units, 2, L"cm"))
3021 spec = (spec*100*Tkdpi)/254;
3022 else if(!_Strncmpci(units, 2, L"mm"))
3023 spec = (spec*10*Tkdpi)/254;
3024 else if(!_Strncmpci(units, 2, L"em"))
3028 fprint(2, "warning: unknown units %C%Cs\n", units[0], units[1]);
3034 else if(r[0] == '*')
3040 else if(nr == 1 && r[0] == '*') {
3044 return makedimen(kind, spec);
3048 setdimarray(Token* tok, int attid, Dimen** pans, int* panslen)
3054 Rune* a[SMALLBUFSIZE];
3055 int an[SMALLBUFSIZE];
3057 if(_tokaval(tok, attid, &s, 0)) {
3058 nc = _splitall(s, _Strlen(s), L", ", a, an, SMALLBUFSIZE);
3060 d = (Dimen*)emalloc(nc * sizeof(Dimen));
3061 for(k = 0; k < nc; k++) {
3062 d[k] = parsedim(a[k], an[k]);
3074 makebackground(Rune* imageurl, int color)
3078 bg.image = imageurl;
3084 newitext(Rune* s, int fnt, int fg, int voff, int ul)
3089 t = (Itext*)emalloc(sizeof(Itext));
3100 newirule(int align, int size, int noshade, int color, Dimen wspec)
3104 r = (Irule*)emalloc(sizeof(Irule));
3108 r->noshade = noshade;
3114 // Map is owned elsewhere.
3116 newiimage(Rune* src, Rune* altrep, int align, int width, int height,
3117 int hspace, int vspace, int border, int ismap, Map* map)
3125 i = (Iimage*)emalloc(sizeof(Iimage));
3132 i->imheight = height;
3142 newiformfield(Formfield* ff)
3146 f = (Iformfield*)emalloc(sizeof(Iformfield));
3147 f->tag = Iformfieldtag;
3153 newitable(Table* tab)
3157 t = (Itable*)emalloc(sizeof(Itable));
3164 newifloat(Item* it, int side)
3168 f = (Ifloat*)emalloc(sizeof(Ifloat));
3177 newispacer(int spkind)
3181 s = (Ispacer*)emalloc(sizeof(Ispacer));
3182 s->tag = Ispacertag;
3187 // Free one item (caller must deal with next pointer)
3199 free(((Itext*)it)->s);
3207 freeformfield(((Iformfield*)it)->formfield);
3210 freetable(((Itable*)it)->table);
3213 freeitem(((Ifloat*)it)->item);
3222 freescriptevents(ga->events);
3227 // Free list of items chained through next pointer
3229 freeitems(Item* ithead)
3243 freeformfield(Formfield* ff)
3253 for(o = ff->options; o != nil; o = onext) {
3271 // We'll find all the unique cells via t->cells and next pointers.
3272 // (Other pointers to cells in the table are duplicates of these)
3273 for(c = t->cells; c != nil; c = cnext) {
3275 freeitems(c->content);
3277 if(t->grid != nil) {
3278 for(i = 0; i < t->nrow; i++)
3284 freeitems(t->caption);
3296 // Form doesn't own its fields (Iformfield items do)
3301 freeforms(Form* fhead)
3306 for(f = fhead; f != nil; f = fnext) {
3313 freeanchor(Anchor* a)
3324 freeanchors(Anchor* ahead)
3329 for(a = ahead; a != nil; a = anext) {
3336 freedestanchor(DestAnchor* da)
3346 freedestanchors(DestAnchor* dahead)
3351 for(da = dahead; da != nil; da = danext) {
3366 static void freekidinfos(Kidinfo* khead);
3369 freekidinfo(Kidinfo* k)
3374 freekidinfos(k->kidinfos);
3384 freekidinfos(Kidinfo* khead)
3389 for(k = khead; k != nil; k = knext) {
3405 for(a = m->areas; a != nil; a = anext) {
3413 freemaps(Map* mhead)
3418 for(m = mhead; m != nil; m = mnext) {
3425 freedocinfo(Docinfo* d)
3431 freeitem((Item*)d->backgrounditem);
3433 freekidinfos(d->kidinfo);
3434 freeanchors(d->anchors);
3435 freedestanchors(d->dests);
3436 freeforms(d->forms);
3438 // tables, images, and formfields are freed when
3439 // the items pointing at them are freed
3443 // Currently, someone else owns all the memory
3444 // pointed to by things in a Pstate.
3446 freepstate(Pstate* p)
3452 freepstatestack(Pstate* pshead)
3457 for(p = pshead; p != nil; p = pnext) {
3482 char buf[BIGBUFSIZE];
3484 it = va_arg(f->args, Item*);
3490 cl = state&(IFcleft|IFcright);
3493 if(cl == (IFcleft|IFcright))
3495 else if(cl == IFcleft)
3500 bi = snprint(buf, nbuf, "brk(%d%s)", (state&IFbrksp)? 1 : 0, p);
3503 bi += snprint(buf+bi, nbuf-bi, " nobrk");
3505 bi += snprint(buf+bi, nbuf-bi, " nowrap");
3507 bi += snprint(buf+bi, nbuf-bi, " rjust");
3509 bi += snprint(buf+bi, nbuf-bi, " cjust");
3511 bi += snprint(buf+bi, nbuf-bi, " smap");
3512 indent = (state&IFindentmask) >> IFindentshift;
3514 bi += snprint(buf+bi, nbuf-bi, " indent=%d", indent);
3515 hang = state&IFhangmask;
3517 bi += snprint(buf+bi, nbuf-bi, " hang=%d", hang);
3522 bi += snprint(buf+bi, nbuf-bi, " Text '%S', fnt=%d, fg=%x", t->s, t->fnt, t->fg);
3527 bi += snprint(buf+bi, nbuf-bi, "Rule size=%d, al=%S, wspec=", r->size, stringalign(r->align));
3528 bi += dimprint(buf+bi, nbuf-bi, r->wspec);
3533 bi += snprint(buf+bi, nbuf-bi,
3534 "Image src=%S, alt=%S, al=%S, w=%d, h=%d hsp=%d, vsp=%d, bd=%d, map=%S",
3535 i->imsrc, i->altrep? i->altrep : L"", stringalign(i->align), i->imwidth, i->imheight,
3536 i->hspace, i->vspace, i->border, i->map? i->map->name : L"");
3540 ff = ((Iformfield*)it)->formfield;
3541 if(ff->ftype == Ftextarea)
3543 else if(ff->ftype == Fselect)
3546 ty = _revlookup(input_tab, NINPUTTAB, ff->ftype);
3550 bi += snprint(buf+bi, nbuf-bi, "Formfield %S, fieldid=%d, formid=%d, name=%S, value=%S",
3551 ty, ff->fieldid, ff->form->formid, ff->name? ff->name : L"",
3552 ff->value? ff->value : L"");
3556 tab = ((Itable*)it)->table;
3557 bi += snprint(buf+bi, nbuf-bi, "Table tableid=%d, width=", tab->tableid);
3558 bi += dimprint(buf+bi, nbuf-bi, tab->width);
3559 bi += snprint(buf+bi, nbuf-bi, ", nrow=%d, ncol=%d, ncell=%d, totw=%d, toth=%d\n",
3560 tab->nrow, tab->ncol, tab->ncell, tab->totw, tab->toth);
3561 for(c = tab->cells; c != nil; c = c->next)
3562 bi += snprint(buf+bi, nbuf-bi, "Cell %d.%d, at (%d,%d) ",
3563 tab->tableid, c->cellid, c->row, c->col);
3564 bi += snprint(buf+bi, nbuf-bi, "End of Table %d", tab->tableid);
3569 bi += snprint(buf+bi, nbuf-bi, "Float, x=%d y=%d, side=%S, it=%I",
3570 fl->x, fl->y, stringalign(fl->side), fl->item);
3571 bi += snprint(buf+bi, nbuf-bi, "\n\t");
3576 switch(((Ispacer*)it)->spkind) {
3587 bi += snprint(buf+bi, nbuf-bi, "Spacer %s ", p);
3590 bi += snprint(buf+bi, nbuf-bi, " w=%d, h=%d, a=%d, anchor=%d\n",
3591 it->width, it->height, it->ascent, it->anchorid);
3593 return fmtstrcpy(f, buf);
3596 // String version of alignment 'a'
3602 s = _revlookup(align_tab, NALIGNTAB, a);
3608 // Put at most nbuf chars of representation of d into buf,
3609 // and return number of characters put
3611 dimprint(char* buf, int nbuf, Dimen d)
3617 n += snprint(buf, nbuf, "%d", dimenspec(d));
3627 printitems(Item* items, char* msg)
3631 fprint(2, "%s\n", msg);
3634 fprint(2, "%I", il);
3640 newgenattr(Rune* id, Rune* class, Rune* style, Rune* title, SEvent* events)
3644 g = (Genattr*)emalloc(sizeof(Genattr));
3654 newformfield(int ftype, int fieldid, Form* form, Rune* name,
3655 Rune* value, int size, int maxlength, Formfield* link)
3659 ff = (Formfield*)emalloc(sizeof(Formfield));
3661 ff->fieldid = fieldid;
3666 ff->maxlength = maxlength;
3672 // Transfers ownership of value and display to Option.
3674 newoption(int selected, Rune* value, Rune* display, Option* link)
3678 o = (Option*)emalloc(sizeof(Option));
3679 o->selected = selected;
3681 o->display = display;
3687 newform(int formid, Rune* name, Rune* action, int target, int method, Form* link)
3691 f = (Form*)emalloc(sizeof(Form));
3704 newtable(int tableid, Align align, Dimen width, int border,
3705 int cellspacing, int cellpadding, Background bg, Token* tok, Table* link)
3709 t = (Table*)emalloc(sizeof(Table));
3710 t->tableid = tableid;
3714 t->cellspacing = cellspacing;
3715 t->cellpadding = cellpadding;
3717 t->caption_place = ALbottom;
3718 t->caption_lay = nil;
3726 newtablerow(Align align, Background bg, int flags, Tablerow* link)
3730 tr = (Tablerow*)emalloc(sizeof(Tablerow));
3732 tr->background = bg;
3739 newtablecell(int cellid, int rowspan, int colspan, Align align, Dimen wspec, int hspec,
3740 Background bg, int flags, Tablecell* link)
3744 c = (Tablecell*)emalloc(sizeof(Tablecell));
3747 c->rowspan = rowspan;
3748 c->colspan = colspan;
3759 newanchor(int index, Rune* name, Rune* href, int target, Anchor* link)
3763 a = (Anchor*)emalloc(sizeof(Anchor));
3773 newdestanchor(int index, Rune* name, Item* item, DestAnchor* link)
3777 d = (DestAnchor*)emalloc(sizeof(DestAnchor));
3786 newscriptevent(int type, Rune* script, SEvent* link)
3790 ans = (SEvent*)emalloc(sizeof(SEvent));
3792 ans->script = script;
3798 freescriptevents(SEvent* ehead)
3813 makedimen(int kind, int spec)
3817 if(spec&Dkindmask) {
3819 fprint(2, "warning: dimension spec too big: %d\n", spec);
3822 d.kindspec = kind|spec;
3829 return (d.kindspec&Dkindmask);
3835 return (d.kindspec&Dspecmask);
3839 newkidinfo(int isframeset, Kidinfo* link)
3843 ki = (Kidinfo*)emalloc(sizeof(Kidinfo));
3844 ki->isframeset = isframeset;
3846 ki->flags = FRhscrollauto|FRvscrollauto;
3847 ki->marginw = FRKIDMARGIN;
3848 ki->marginh = FRKIDMARGIN;
3860 d = (Docinfo*)emalloc(sizeof(Docinfo));
3866 resetdocinfo(Docinfo* d)
3868 memset(d, 0, sizeof(Docinfo));
3869 d->background = makebackground(nil, White);
3875 d->chset = ISO_8859_1;
3876 d->scripttype = TextJavascript;
3880 // Use targetmap array to keep track of name <-> targetid mapping.
3881 // Use real malloc(), and never free
3888 l = targetmapsize*sizeof *targetmap;
3889 targetmap = emalloc(l);
3890 memset(targetmap, 0, l);
3891 targetmap[0].key = _Strdup(L"_top");
3892 targetmap[0].val = FTtop;
3893 targetmap[1].key = _Strdup(L"_self");
3894 targetmap[1].val = FTself;
3895 targetmap[2].key = _Strdup(L"_parent");
3896 targetmap[2].val = FTparent;
3897 targetmap[3].key = _Strdup(L"_blank");
3898 targetmap[3].val = FTblank;
3911 for(i = 0; i < ntargets; i++)
3912 if(_Strcmp(s, targetmap[i].key) == 0)
3913 return targetmap[i].val;
3914 if(i == targetmapsize) {
3915 targetmapsize += 10;
3916 targetmap = erealloc(targetmap, targetmapsize*sizeof(StringInt));
3918 targetmap[i].key = _Strdup(s);
3919 targetmap[i].val = i;
3925 targetname(int targid)
3929 for(i = 0; i < ntargets; i++)
3930 if(targetmap[i].val == targid)
3931 return targetmap[i].key;
3935 // Convert HTML color spec to RGB value, returning dflt if can't.
3936 // Argument is supposed to be a valid HTML color, or "".
3937 // Return the RGB value of the color, using dflt if s
3938 // is nil or an invalid color.
3940 color(Rune* s, int dflt)
3947 if(_lookup(color_tab, NCOLORS, s, _Strlen(s), &v))
3951 v = _Strtol(s, &rest, 16);
3959 #define HUGEPIX 10000
3961 // A "shallow" validitem, that doesn't follow next links
3962 // or descend into tables.
3973 ok = (i->tag >= Itexttag && i->tag <= Ispacertag) &&
3974 (i->next == nil || validptr(i->next)) &&
3975 (i->width >= 0 && i->width < HUGEPIX) &&
3976 (i->height >= 0 && i->height < HUGEPIX) &&
3977 (i->ascent > -HUGEPIX && i->ascent < HUGEPIX) &&
3978 (i->anchorid >= 0) &&
3979 (i->genattr == nil || validptr(i->genattr));
3980 // also, could check state for ridiculous combinations
3981 // also, could check anchorid for within-doc-range
3986 ok = validStr(ti->s) &&
3987 (ti->fnt >= 0 && ti->fnt < NumStyle*NumSize) &&
3988 (ti->ul == ULnone || ti->ul == ULunder || ti->ul == ULmid);
3992 ok = (validvalign(ri->align) || validhalign(ri->align)) &&
3993 (ri->size >=0 && ri->size < HUGEPIX);
3997 ok = (ii->imsrc == nil || validptr(ii->imsrc)) &&
3998 (ii->width >= 0 && ii->width < HUGEPIX) &&
3999 (ii->height >= 0 && ii->height < HUGEPIX) &&
4000 (ii->imwidth >= 0 && ii->imwidth < HUGEPIX) &&
4001 (ii->imheight >= 0 && ii->imheight < HUGEPIX) &&
4002 (ii->altrep == nil || validStr(ii->altrep)) &&
4003 (ii->map == nil || validptr(ii->map)) &&
4004 (validvalign(ii->align) || validhalign(ii->align)) &&
4005 (ii->nextimage == nil || validptr(ii->nextimage));
4008 ok = validformfield(((Iformfield*)i)->formfield);
4011 ok = validptr((Itable*)i);
4015 ok = (fi->side == ALleft || fi->side == ALright) &&
4016 validitem(fi->item) &&
4017 (fi->item->tag == Iimagetag || fi->item->tag == Itabletag);
4020 a = ((Ispacer*)i)->spkind;
4021 ok = a==ISPnull || a==ISPvline || a==ISPhspace || a==ISPgeneral;
4029 // "deep" validation, that checks whole list of items,
4030 // and descends into tables and floated tables.
4031 // nil is ok for argument.
4039 while(i != nil && ok) {
4042 if(i->tag == Itabletag) {
4043 ok = validtable(((Itable*)i)->table);
4045 else if(i->tag == Ifloattag) {
4046 ii = ((Ifloat*)i)->item;
4047 if(ii->tag == Itabletag)
4048 ok = validtable(((Itable*)ii)->table);
4052 fprint(2, "invalid item: %I\n", i);
4060 validformfield(Formfield* f)
4064 ok = (f->next == nil || validptr(f->next)) &&
4065 (f->ftype >= 0 && f->ftype <= Ftextarea) &&
4067 (f->form == nil || validptr(f->form)) &&
4068 (f->name == nil || validStr(f->name)) &&
4069 (f->value == nil || validStr(f->value)) &&
4070 (f->options == nil || validptr(f->options)) &&
4071 (f->image == nil || validitem(f->image)) &&
4072 (f->events == nil || validptr(f->events));
4073 // when all built, should have f->fieldid < f->form->nfields,
4074 // but this may be called during build...
4078 // "deep" validation -- checks cell contents too
4080 validtable(Table* t)
4086 ok = (t->next == nil || validptr(t->next)) &&
4090 validalign(t->align) &&
4091 validdimen(t->width) &&
4092 (t->border >= 0 && t->border < HUGEPIX) &&
4093 (t->cellspacing >= 0 && t->cellspacing < HUGEPIX) &&
4094 (t->cellpadding >= 0 && t->cellpadding < HUGEPIX) &&
4095 validitems(t->caption) &&
4096 (t->caption_place == ALtop || t->caption_place == ALbottom) &&
4097 (t->totw >= 0 && t->totw < HUGEPIX) &&
4098 (t->toth >= 0 && t->toth < HUGEPIX) &&
4099 (t->tabletok == nil || validptr(t->tabletok));
4100 // during parsing, t->rows has list;
4101 // only when parsing is done is t->nrow set > 0
4102 if(ok && t->nrow > 0 && t->ncol > 0) {
4103 // table is "finished"
4104 for(i = 0; i < t->nrow && ok; i++)
4105 ok = validtablerow(t->rows+i);
4106 for(j = 0; j < t->ncol && ok; j++)
4107 ok = validtablecol(t->cols+j);
4108 for(c = t->cells; c != nil && ok; c = c->next)
4109 ok = validtablecell(c);
4110 for(i = 0; i < t->nrow && ok; i++)
4111 for(j = 0; j < t->ncol && ok; j++)
4112 ok = validptr(t->grid[i][j]);
4120 return a == ALnone || a == ALmiddle || a == ALbottom || a == ALtop || a == ALbaseline;
4126 return a == ALnone || a == ALleft || a == ALcenter || a == ALright ||
4127 a == ALjustify || a == ALchar;
4133 return validhalign(a.halign) && validvalign(a.valign);
4143 s = d.kindspec&Dspecmask;
4144 switch(d.kindspec&Dkindmask) {
4160 validtablerow(Tablerow* r)
4162 return (r->cells == nil || validptr(r->cells)) &&
4163 (r->height >= 0 && r->height < HUGEPIX) &&
4164 (r->ascent > -HUGEPIX && r->ascent < HUGEPIX) &&
4165 validalign(r->align);
4169 validtablecol(Tablecol* c)
4171 return c->width >= 0 && c->width < HUGEPIX
4172 && validalign(c->align);
4176 validtablecell(Tablecell* c)
4180 ok = (c->next == nil || validptr(c->next)) &&
4181 (c->nextinrow == nil || validptr(c->nextinrow)) &&
4182 (c->content == nil || validptr(c->content)) &&
4183 (c->lay == nil || validptr(c->lay)) &&
4186 validalign(c->align) &&
4187 validdimen(c->wspec) &&
4191 if(c->content != nil)
4192 ok = validitems(c->content);
4200 // TODO: a better job of this.
4201 // For now, just dereference, which cause a bomb
4212 return s != nil && validptr(s);