/* * winhelp.c a module to generate Windows .HLP files * * Documentation of the .HLP file format comes from the excellent * HELPFILE.TXT, published alongside the Help decompiler HELPDECO * by Manfred Winterhoff. This code would not have been possible * without his efforts. Many thanks. */ /* * Potential future features: * * - perhaps LZ77 compression? This appears to cause a phase order * problem: it's hard to do the compression until the data to be * compressed is finalised, and yet you can't finalise the data * to be compressed until you know how much of it is going into * which TOPICBLOCK in order to work out the offsets in the * topic headers - for which you have to have already done the * compression. Perhaps the thing to do is to implement an LZ77 * compressor that can guarantee to leave particular bytes in * the stream as literals, and then go back and fix the offsets * up later. Not pleasant. * * - It would be good to find out what relation (if any) the LCID * record in the |SYSTEM section bears to the codepage used in * the actual help text, so as to be able to vary that if the * user needs it. For the moment I suspect we're stuck with * Win1252. * * - tables might be nice. * * Unlikely future features: * * - Phrase compression sounds harder. It's reasonably easy * (though space-costly) to analyse all the text in the file to * determine the one key phrase which would save most space if * replaced by a reference everywhere it appears; but finding * the _1024_ most effective phrases seems much harder since a * naive analysis might find lots of phrases that all overlap * (so you wouldn't get the saving you expected, as after taking * out the first phrase the rest would never crop up). In * addition, MS hold US patent number 4955066 which may cover * phrase compression, so perhaps it's best just to leave it. * * Cleanup work: * * - sort out begin_topic. Ideally we should have a separate * topic_macro function that adds to the existing linkdata for * the topic, because that's more flexible than a variadic * function. This will be fiddly, though: if it's called before * whlp_begin_topic then we must buffer macros, and if it's * called afterwards then we must be able to go back and modify * the linkdata2 of the topic start block. Foo. * * - find out what should happen if a single topiclink crosses * _two_ topicblock boundaries. * * - What is the BlockSize in a topic header (first 4 bytes of * LinkData1 in a type 2 record) supposed to mean? How on earth * is it measured? The help file doesn't become perceptibly * corrupt if I frob it randomly; and on some occasions taking a * bit _out_ of the help file _increases_ that value. I have a * feeling it's completely made up and/or vestigial, so for the * moment I'm just making up a plausible value as I go along. */ #include #include #include #include #include #include #include "halibut.h" #include "winhelp.h" #include "tree234.h" #ifdef TESTMODE /* * This lot is useful for testing. Something like it will also be * needed to use this module standalone. */ #define smalloc malloc #define srealloc realloc #define sfree free #define snew(type) ( (type *) smalloc (sizeof (type)) ) #define snewn(number, type) ( (type *) smalloc ((number) * sizeof (type)) ) #define sresize(array, len, type) \ ( (type *) srealloc ((array), (len) * sizeof (type)) ) #define lenof(array) ( sizeof(array) / sizeof(*(array)) ) char *dupstr(char *s) { char *r = snewn(1+strlen(s), char); strcpy(r,s); return r; } #endif #define UNUSEDARG(x) ( (x) = (x) ) #define GET_32BIT_LSB_FIRST(cp) \ (((unsigned long)(unsigned char)(cp)[0]) | \ ((unsigned long)(unsigned char)(cp)[1] << 8) | \ ((unsigned long)(unsigned char)(cp)[2] << 16) | \ ((unsigned long)(unsigned char)(cp)[3] << 24)) #define PUT_32BIT_LSB_FIRST(cp, value) do { \ (cp)[0] = 0xFF & (value); \ (cp)[1] = 0xFF & ((value) >> 8); \ (cp)[2] = 0xFF & ((value) >> 16); \ (cp)[3] = 0xFF & ((value) >> 24); } while (0) #define GET_16BIT_LSB_FIRST(cp) \ (((unsigned long)(unsigned char)(cp)[0]) | \ ((unsigned long)(unsigned char)(cp)[1] << 8)) #define PUT_16BIT_LSB_FIRST(cp, value) do { \ (cp)[0] = 0xFF & (value); \ (cp)[1] = 0xFF & ((value) >> 8); } while (0) #define MAX_PAGE_SIZE 0x800 /* max page size in any B-tree */ #define TOPIC_BLKSIZE 4096 /* implied by version/flags combo */ typedef struct WHLP_TOPIC_tag context; struct file { char *name; /* file name, will need freeing */ unsigned char *data; /* file data, will need freeing */ int pos; /* position for adding data */ int len; /* # of meaningful bytes in data */ int size; /* # of allocated bytes in data */ int fileoffset; /* offset in the real .HLP file */ }; struct indexrec { char *term; /* index term, will need freeing */ context *topic; /* topic it links to */ int count, offset; /* used when building |KWDATA */ }; struct topiclink { int topicoffset, topicpos; /* for referencing from elsewhere */ int recordtype; int len1, len2; unsigned char *data1, *data2; context *context; struct topiclink *nonscroll, *scroll, *nexttopic; int block_size; /* for the topic header - *boggle* */ }; struct WHLP_TOPIC_tag { char *name; /* needs freeing */ unsigned long hash; struct topiclink *link; /* this provides TOPICOFFSET */ context *browse_next, *browse_prev; char *title; /* needs freeing */ int index; /* arbitrary number */ }; struct fontdesc { char *font; int family, rendition, halfpoints; int r, g, b; }; struct WHLP_tag { tree234 *files; /* stores `struct file' */ tree234 *pre_contexts; /* stores `context' */ tree234 *contexts; /* also stores `context' */ tree234 *titles; /* _also_ stores `context' */ tree234 *text; /* stores `struct topiclink' */ tree234 *index; /* stores `struct indexrec' */ tree234 *tabstops; /* stores `int' */ tree234 *fontnames; /* stores `char *' */ tree234 *fontdescs; /* stores `struct fontdesc' */ struct file *systemfile; /* the |SYSTEM internal file */ context *ptopic; /* primary topic */ struct topiclink *prevtopic; /* to link type-2 records together */ struct topiclink *link; /* while building a topiclink */ unsigned char linkdata1[TOPIC_BLKSIZE]; /* while building a topiclink */ unsigned char linkdata2[TOPIC_BLKSIZE]; /* while building a topiclink */ int topicblock_remaining; /* while building |TOPIC section */ int lasttopiclink; /* while building |TOPIC section */ int firsttopiclink_offset; /* while building |TOPIC section */ int lasttopicstart; /* while building |TOPIC section */ int para_flags; int para_attrs[7]; int ncontexts; }; /* Functions to return the index and leaf data for B-tree contents. */ typedef int (*bt_index_fn)(const void *item, unsigned char *outbuf); typedef int (*bt_leaf_fn)(const void *item, unsigned char *outbuf); /* Forward references. */ static void whlp_para_reset(WHLP h); static struct file *whlp_new_file(WHLP h, char *name); static void whlp_file_add(struct file *f, const void *data, int len); static void whlp_file_add_char(struct file *f, int data); static void whlp_file_add_short(struct file *f, int data); static void whlp_file_add_long(struct file *f, int data); static void whlp_file_fill(struct file *f, int len); static void whlp_file_seek(struct file *f, int pos, int whence); static int whlp_file_offset(struct file *f); /* ---------------------------------------------------------------------- * Fiddly little functions: B-tree compare, index and leaf functions. */ /* The master index maps file names to help-file offsets. */ static int filecmp(void *av, void *bv) { const struct file *a = (const struct file *)av; const struct file *b = (const struct file *)bv; return strcmp(a->name, b->name); } static int fileindex(const void *av, unsigned char *outbuf) { const struct file *a = (const struct file *)av; int len = 1+strlen(a->name); memcpy(outbuf, a->name, len); return len; } static int fileleaf(const void *av, unsigned char *outbuf) { const struct file *a = (const struct file *)av; int len = 1+strlen(a->name); memcpy(outbuf, a->name, len); PUT_32BIT_LSB_FIRST(outbuf+len, a->fileoffset); return len+4; } /* The |CONTEXT internal file maps help context hashes to TOPICOFFSETs. */ static int ctxcmp(void *av, void *bv) { const context *a = (const context *)av; const context *b = (const context *)bv; if ((signed long)a->hash < (signed long)b->hash) return -1; if ((signed long)a->hash > (signed long)b->hash) return +1; return 0; } static int ctxindex(const void *av, unsigned char *outbuf) { const context *a = (const context *)av; PUT_32BIT_LSB_FIRST(outbuf, a->hash); return 4; } static int ctxleaf(const void *av, unsigned char *outbuf) { const context *a = (const context *)av; PUT_32BIT_LSB_FIRST(outbuf, a->hash); PUT_32BIT_LSB_FIRST(outbuf+4, a->link->topicoffset); return 8; } /* The |TTLBTREE internal file maps TOPICOFFSETs to title strings. */ static int ttlcmp(void *av, void *bv) { const context *a = (const context *)av; const context *b = (const context *)bv; if (a->link->topicoffset < b->link->topicoffset) return -1; if (a->link->topicoffset > b->link->topicoffset) return +1; return 0; } static int ttlindex(const void *av, unsigned char *outbuf) { const context *a = (const context *)av; PUT_32BIT_LSB_FIRST(outbuf, a->link->topicoffset); return 4; } static int ttlleaf(const void *av, unsigned char *outbuf) { const context *a = (const context *)av; int slen; PUT_32BIT_LSB_FIRST(outbuf, a->link->topicoffset); slen = 1+strlen(a->title); memcpy(outbuf+4, a->title, slen); return 4+slen; } /* The |KWBTREE internal file maps index strings to TOPICOFFSETs. */ static int idxcmp(void *av, void *bv) { const struct indexrec *a = (const struct indexrec *)av; const struct indexrec *b = (const struct indexrec *)bv; int cmp; if ( (cmp = strcmp(a->term, b->term)) != 0) return cmp; /* Now sort on the index field of the topics. */ if (a->topic->index < b->topic->index) return -1; if (a->topic->index > b->topic->index) return +1; return 0; } static int idxindex(const void *av, unsigned char *outbuf) { const struct indexrec *a = (const struct indexrec *)av; int len = 1+strlen(a->term); memcpy(outbuf, a->term, len); return len; } static int idxleaf(const void *av, unsigned char *outbuf) { const struct indexrec *a = (const struct indexrec *)av; int len = 1+strlen(a->term); memcpy(outbuf, a->term, len); PUT_16BIT_LSB_FIRST(outbuf+len, a->count); PUT_32BIT_LSB_FIRST(outbuf+len+2, a->offset); return len+6; } /* * The internal `tabstops' B-tree stores pointers-to-int. Sorting * is by the low 16 bits of the number (above that is flags). */ static int tabcmp(void *av, void *bv) { const int *a = (const int *)av; const int *b = (const int *)bv; if ((*a & 0xFFFF) < (*b & 0xFFFF)) return -1; if ((*a & 0xFFFF) > (*b & 0xFFFF)) return +1; return 0; } /* The internal `fontnames' B-tree stores strings. */ static int fontcmp(void *av, void *bv) { const char *a = (const char *)av; const char *b = (const char *)bv; return strcmp(a,b); } /* ---------------------------------------------------------------------- * Manage help contexts and topics. */ /* * This is the code to compute the hash of a context name. Copied * straight from Winterhoff's documentation. */ static unsigned long context_hash(char *context) { signed char bytemapping[256] = "\x00\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF" "\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF" "\xF0\x0B\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\x0C\xFF" "\x0A\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x0B\x0C\x0D\x0E\x0D" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" "\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F" "\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F" "\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F" "\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F" "\x80\x81\x82\x83\x0B\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F" "\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F" "\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF" "\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF" "\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF"; unsigned long hash; /* * The hash algorithm starts the hash at 0 and updates it with * each character. Therefore, logically, the hash of an empty * string should be 0 (it starts at 0 and is never updated); * but Winterhoff says it is in fact 1. Shouldn't matter, since * I never plan to use empty context names, but I'll stick the * special case in here anyway. */ if (!*context) return 1; /* * Now compute the hash in the normal way. */ hash = 0; while (*context) { /* * Be careful of overflowing `unsigned long', for maximum * portability. */ /* * Multiply `hash' by 43. */ { unsigned long bottom, top; bottom = (hash & 0xFFFFUL) * 43; top = ((hash >> 16) & 0xFFFFUL) * 43; top += (bottom >> 16); bottom &= 0xFFFFUL; top &= 0xFFFFUL; hash = (top << 16) | bottom; } /* * Add the mapping value for this byte to `hash'. */ { int val = bytemapping[(unsigned char)*context]; if (val > 0 && hash > (0xFFFFFFFFUL - val)) { hash -= (0xFFFFFFFFUL - val) + 1; } else if (val < 0 && hash < (unsigned long)-val) { hash += (0xFFFFFFFFUL + val) + 1; } else hash += val; } context++; } return hash; } WHLP_TOPIC whlp_register_topic(WHLP h, char *context_name, char **clash) { context *ctx = snew(context); context *otherctx; /* * Index contexts in order of creation, just so there's some * sort of non-arbitrary ordering in the index B-tree. Call me * fussy, but I don't like indexing on pointer values because I * prefer the code to be deterministic when run under different * C libraries. */ ctx->index = h->ncontexts++; ctx->browse_prev = ctx->browse_next = NULL; if (context_name) { /* * We have a context name, which means we can put this * context straight into the `contexts' tree. */ ctx->name = dupstr(context_name); ctx->hash = context_hash(context_name); otherctx = add234(h->contexts, ctx); if (otherctx != ctx) { /* * Hash clash. Destroy the new context and return NULL, * providing the clashing string. */ sfree(ctx->name); sfree(ctx); if (clash) *clash = otherctx->name; return NULL; } } else { /* * We have no context name yet. Enter this into the * pre_contexts tree of anonymous topics, which we will go * through later and allocate unique context names and hash * values. */ ctx->name = NULL; addpos234(h->pre_contexts, ctx, count234(h->pre_contexts)); } return ctx; } void whlp_prepare(WHLP h) { /* * We must go through pre_contexts and allocate a context ID to * each anonymous context, making sure it doesn't clash with * the existing contexts. * * Our own context IDs will just be of the form `t00000001', * and we'll increment the number each time and skip over any * IDs that clash with existing context names. */ int ctx_num = 0; context *ctx, *otherctx; while ( (ctx = index234(h->pre_contexts, 0)) != NULL ) { delpos234(h->pre_contexts, 0); ctx->name = snewn(20, char); do { sprintf(ctx->name, "t%08d", ctx_num++); ctx->hash = context_hash(ctx->name); otherctx = add234(h->contexts, ctx); } while (otherctx != ctx); } /* * Ensure paragraph attributes are clear for the start of text * output. */ whlp_para_reset(h); } char *whlp_topic_id(WHLP_TOPIC topic) { return topic->name; } void whlp_begin_topic(WHLP h, WHLP_TOPIC topic, char *title, ...) { struct topiclink *link = snew(struct topiclink); int len, slen; char *macro; va_list ap; link->nexttopic = NULL; if (h->prevtopic) h->prevtopic->nexttopic = link; h->prevtopic = link; link->nonscroll = link->scroll = NULL; link->context = topic; link->block_size = 0; link->recordtype = 2; /* topic header */ link->len1 = 4*7; /* standard linkdata1 size */ link->data1 = snewn(link->len1, unsigned char); slen = strlen(title); assert(slen+1 <= TOPIC_BLKSIZE); memcpy(h->linkdata2, title, slen+1); len = slen+1; va_start(ap, title); while ( (macro = va_arg(ap, char *)) != NULL) { slen = strlen(macro); assert(len+slen+1 <= TOPIC_BLKSIZE); memcpy(h->linkdata2+len, macro, slen+1); len += slen+1; } va_end(ap); len--; /* lose the last \0 on the last macro */ link->len2 = len; link->data2 = snewn(link->len2, unsigned char); memcpy(link->data2, h->linkdata2, link->len2); topic->title = dupstr(title); topic->link = link; addpos234(h->text, link, count234(h->text)); } void whlp_browse_link(WHLP h, WHLP_TOPIC before, WHLP_TOPIC after) { UNUSEDARG(h); /* * See if the `before' topic is already linked to another one, * and break the link to that if so. Likewise the `after' * topic. */ if (before->browse_next) before->browse_next->browse_prev = NULL; if (after->browse_prev) after->browse_prev->browse_next = NULL; before->browse_next = after; after->browse_prev = before; } /* ---------------------------------------------------------------------- * Manage the actual generation of paragraph and text records. */ static void whlp_linkdata(WHLP h, int which, int c) { int *len = (which == 1 ? &h->link->len1 : &h->link->len2); char *data = (which == 1 ? h->linkdata1 : h->linkdata2); assert(*len < TOPIC_BLKSIZE); data[(*len)++] = c; } static void whlp_linkdata_short(WHLP h, int which, int data) { whlp_linkdata(h, which, data & 0xFF); whlp_linkdata(h, which, (data >> 8) & 0xFF); } static void whlp_linkdata_long(WHLP h, int which, int data) { whlp_linkdata(h, which, data & 0xFF); whlp_linkdata(h, which, (data >> 8) & 0xFF); whlp_linkdata(h, which, (data >> 16) & 0xFF); whlp_linkdata(h, which, (data >> 24) & 0xFF); } static void whlp_linkdata_cushort(WHLP h, int which, int data) { if (data <= 0x7F) { whlp_linkdata(h, which, data*2); } else { whlp_linkdata(h, which, 1 + (data%128 * 2)); whlp_linkdata(h, which, data/128); } } static void whlp_linkdata_csshort(WHLP h, int which, int data) { if (data >= -0x40 && data <= 0x3F) whlp_linkdata_cushort(h, which, data+64); else whlp_linkdata_cushort(h, which, data+16384); } static void whlp_linkdata_culong(WHLP h, int which, int data) { if (data <= 0x7FFF) { whlp_linkdata_short(h, which, data*2); } else { whlp_linkdata_short(h, which, 1 + (data%32768 * 2)); whlp_linkdata_short(h, which, data/32768); } } static void whlp_linkdata_cslong(WHLP h, int which, int data) { if (data >= -0x4000 && data <= 0x3FFF) whlp_linkdata_culong(h, which, data+16384); else whlp_linkdata_culong(h, which, data+67108864); } static void whlp_para_reset(WHLP h) { int *p; h->para_flags = 0; while ( (p = index234(h->tabstops, 0)) != NULL) { delpos234(h->tabstops, 0); sfree(p); } } void whlp_para_attr(WHLP h, int attr_id, int attr_param) { if (attr_id >= WHLP_PARA_SPACEABOVE && attr_id <= WHLP_PARA_FIRSTLINEINDENT) { h->para_flags |= 1 << attr_id; h->para_attrs[attr_id] = attr_param; } else if (attr_id == WHLP_PARA_ALIGNMENT) { h->para_flags &= ~0xC00; if (attr_param == WHLP_ALIGN_RIGHT) h->para_flags |= 0x400; else if (attr_param == WHLP_ALIGN_CENTRE) h->para_flags |= 0x800; } } void whlp_set_tabstop(WHLP h, int tabstop, int alignment) { int *p; if (alignment == WHLP_ALIGN_CENTRE) tabstop |= 0x20000; if (alignment == WHLP_ALIGN_RIGHT) tabstop |= 0x10000; p = snew(int); *p = tabstop; add234(h->tabstops, p); h->para_flags |= 0x0200; } void whlp_begin_para(WHLP h, int para_type) { struct topiclink *link = snew(struct topiclink); int i; /* * Clear these to NULL out of paranoia, although in records * that aren't type 2 they should never actually be needed. */ link->nexttopic = NULL; link->context = NULL; link->nonscroll = link->scroll = NULL; link->recordtype = 32; /* text record */ h->link = link; link->len1 = link->len2 = 0; link->data1 = h->linkdata1; link->data2 = h->linkdata2; if (para_type == WHLP_PARA_NONSCROLL && h->prevtopic && !h->prevtopic->nonscroll) h->prevtopic->nonscroll = link; if (para_type == WHLP_PARA_SCROLL && h->prevtopic && !h->prevtopic->scroll) h->prevtopic->scroll = link; /* * Now we're ready to start accumulating stuff in linkdata1 and * linkdata2. Next we build up the paragraph info. Note that * the TopicSize (cslong: size of LinkData1 minus the topicsize * and topiclength fields) and TopicLength (cushort: size of * LinkData2) fields are missing; we will put those on when we * end the paragraph. */ whlp_linkdata(h, 1, 0); /* must-be-0x00 */ whlp_linkdata(h, 1, 0x80); /* must-be-0x80 */ whlp_linkdata_short(h, 1, 0); /* Winterhoff says `id'; always 0 AFAICT */ whlp_linkdata_short(h, 1, h->para_flags); for (i = WHLP_PARA_SPACEABOVE; i <= WHLP_PARA_FIRSTLINEINDENT; i++) { if (h->para_flags & (1<para_attrs[i]); } if (h->para_flags & 0x0200) { int ntabs; /* * Write out tab stop data. */ ntabs = count234(h->tabstops); whlp_linkdata_csshort(h, 1, ntabs); for (i = 0; i < ntabs; i++) { int tab, *tabp; tabp = index234(h->tabstops, i); tab = *tabp; if (tab & 0x30000) tab |= 0x4000; whlp_linkdata_cushort(h, 1, tab & 0xFFFF); if (tab & 0x4000) whlp_linkdata_cushort(h, 1, tab >> 16); } } /* * Fine. Now we're ready to start writing actual text and * formatting commands. */ } void whlp_set_font(WHLP h, int font_id) { /* * Write a NUL into linkdata2 to cause the reader to flip over * to linkdata1 to see the formatting command. */ whlp_linkdata(h, 2, 0); /* * Now the formatting command is 0x80 followed by a short. */ whlp_linkdata(h, 1, 0x80); whlp_linkdata_short(h, 1, font_id); } void whlp_start_hyperlink(WHLP h, WHLP_TOPIC target) { /* * Write a NUL into linkdata2. */ whlp_linkdata(h, 2, 0); /* * Now the formatting command is 0xE3 followed by the context * hash. */ whlp_linkdata(h, 1, 0xE3); whlp_linkdata_long(h, 1, target->hash); } void whlp_end_hyperlink(WHLP h) { /* * Write a NUL into linkdata2. */ whlp_linkdata(h, 2, 0); /* * Now the formatting command is 0x89. */ whlp_linkdata(h, 1, 0x89); } void whlp_tab(WHLP h) { /* * Write a NUL into linkdata2. */ whlp_linkdata(h, 2, 0); /* * Now the formatting command is 0x83. */ whlp_linkdata(h, 1, 0x83); } void whlp_text(WHLP h, char *text) { while (*text) { whlp_linkdata(h, 2, *text++); } } void whlp_end_para(WHLP h) { int data1cut; /* * Round off the paragraph with 0x82 and 0xFF formatting * commands. Each requires a NUL in linkdata2. */ whlp_linkdata(h, 2, 0); whlp_linkdata(h, 1, 0x82); whlp_linkdata(h, 2, 0); whlp_linkdata(h, 1, 0xFF); /* * Now finish up: create the header of linkdata1 (TopicLength * and TopicSize fields), allocate the real linkdata1 and * linkdata2 fields, and copy them out of the buffers in h. * Then insert the finished topiclink into the `text' tree, and * clean up. */ data1cut = h->link->len1; whlp_linkdata_cslong(h, 1, data1cut); whlp_linkdata_cushort(h, 1, h->link->len2); h->link->data1 = snewn(h->link->len1, unsigned char); memcpy(h->link->data1, h->linkdata1 + data1cut, h->link->len1 - data1cut); memcpy(h->link->data1 + h->link->len1 - data1cut, h->linkdata1, data1cut); h->link->data2 = snewn(h->link->len2, unsigned char); memcpy(h->link->data2, h->linkdata2, h->link->len2); addpos234(h->text, h->link, count234(h->text)); /* Hack: accumulate the `blocksize' parameter in the topic header. */ if (h->prevtopic) h->prevtopic->block_size += 21 + h->link->len1 + h->link->len2; h->link = NULL; /* this is now in the tree */ whlp_para_reset(h); } /* ---------------------------------------------------------------------- * Manage the layout and generation of the |TOPIC section. */ static void whlp_topicsect_write(WHLP h, struct file *f, void *data, int len, int can_break) { unsigned char *p = (unsigned char *)data; if (h->topicblock_remaining <= 0 || h->topicblock_remaining < can_break) { /* * Start a new block. */ if (h->topicblock_remaining > 0) whlp_file_fill(f, h->topicblock_remaining); whlp_file_add_long(f, h->lasttopiclink); h->firsttopiclink_offset = whlp_file_offset(f); whlp_file_add_long(f, -1L); /* this will be filled in later */ whlp_file_add_long(f, h->lasttopicstart); h->topicblock_remaining = TOPIC_BLKSIZE - 12; } while (len > 0) { int thislen = (h->topicblock_remaining < len ? h->topicblock_remaining : len); whlp_file_add(f, p, thislen); p += thislen; len -= thislen; h->topicblock_remaining -= thislen; if (len > 0 && h->topicblock_remaining <= 0) { /* * Start a new block. */ whlp_file_add_long(f, h->lasttopiclink); h->firsttopiclink_offset = whlp_file_offset(f); whlp_file_add_long(f, -1L); /* this will be filled in later */ whlp_file_add_long(f, h->lasttopicstart); h->topicblock_remaining = TOPIC_BLKSIZE - 12; } } } static void whlp_topic_layout(WHLP h) { int block, offset, pos; int i, nlinks, size; int topicnum; struct topiclink *link; struct file *f; /* * Create a final TOPICLINK containing no usable data. */ link = snew(struct topiclink); link->nexttopic = NULL; if (h->prevtopic) h->prevtopic->nexttopic = link; h->prevtopic = link; link->data1 = snewn(0x1c, unsigned char); link->block_size = 0; link->data2 = NULL; link->len1 = 0x1c; link->len2 = 0; link->nexttopic = NULL; link->recordtype = 2; link->nonscroll = link->scroll = NULL; link->context = NULL; addpos234(h->text, link, count234(h->text)); /* * Each TOPICBLOCK has space for TOPIC_BLKSIZE-12 bytes. The * size of each TOPICLINK is 21 bytes plus the combined lengths * of LinkData1 and LinkData2. So we can now go through and * break up the TOPICLINKs into TOPICBLOCKs, and also set up * the TOPICOFFSET and TOPICPOS of each one while we do so. */ block = 0; offset = 0; pos = 12; nlinks = count234(h->text); for (i = 0; i < nlinks; i++) { link = index234(h->text, i); size = 21 + link->len1 + link->len2; /* * We can't split within the topicblock header or within * linkdata1. So if the split would fall in that area, * start a new block _now_. */ if (TOPIC_BLKSIZE - pos < 21 + link->len1) { block++; offset = 0; pos = 12; } link->topicoffset = block * 0x8000 + offset; link->topicpos = block * 0x4000 + pos; pos += size; if (link->recordtype != 2) /* TOPICOFFSET doesn't count titles */ offset += link->len2; while (pos > TOPIC_BLKSIZE) { block++; offset = 0; pos -= TOPIC_BLKSIZE - 12; } } /* * Now we have laid out the TOPICLINKs into blocks, and * determined the final TOPICOFFSET and TOPICPOS of each one. * So now we can go through and write the headers of the type-2 * records. */ topicnum = 0; for (i = 0; i < nlinks; i++) { link = index234(h->text, i); if (link->recordtype != 2) continue; PUT_32BIT_LSB_FIRST(link->data1 + 0, link->block_size); if (link->context && link->context->browse_prev) PUT_32BIT_LSB_FIRST(link->data1 + 4, link->context->browse_prev->link->topicoffset); else PUT_32BIT_LSB_FIRST(link->data1 + 4, 0xFFFFFFFFL); if (link->context && link->context->browse_next) PUT_32BIT_LSB_FIRST(link->data1 + 8, link->context->browse_next->link->topicoffset); else PUT_32BIT_LSB_FIRST(link->data1 + 8, 0xFFFFFFFFL); PUT_32BIT_LSB_FIRST(link->data1 + 12, topicnum); topicnum++; if (link->nonscroll) PUT_32BIT_LSB_FIRST(link->data1 + 16, link->nonscroll->topicpos); else PUT_32BIT_LSB_FIRST(link->data1 + 16, 0xFFFFFFFFL); if (link->scroll) PUT_32BIT_LSB_FIRST(link->data1 + 20, link->scroll->topicpos); else PUT_32BIT_LSB_FIRST(link->data1 + 20, 0xFFFFFFFFL); if (link->nexttopic) PUT_32BIT_LSB_FIRST(link->data1 + 24, link->nexttopic->topicpos); else PUT_32BIT_LSB_FIRST(link->data1 + 24, 0xFFFFFFFFL); } /* * Having done all _that_, we're now finally ready to go * through and create the |TOPIC section in its final form. */ h->lasttopiclink = -1L; h->lasttopicstart = 0L; f = whlp_new_file(h, "|TOPIC"); h->topicblock_remaining = -1; whlp_topicsect_write(h, f, NULL, 0, 0); /* start the first block */ for (i = 0; i < nlinks; i++) { unsigned char header[21]; struct topiclink *otherlink; link = index234(h->text, i); /* * Create and output the TOPICLINK header. */ PUT_32BIT_LSB_FIRST(header + 0, 21 + link->len1 + link->len2); PUT_32BIT_LSB_FIRST(header + 4, link->len2); if (i == 0) { PUT_32BIT_LSB_FIRST(header + 8, 0xFFFFFFFFL); } else { otherlink = index234(h->text, i-1); PUT_32BIT_LSB_FIRST(header + 8, otherlink->topicpos); } if (i+1 >= nlinks) { PUT_32BIT_LSB_FIRST(header + 12, 0xFFFFFFFFL); } else { otherlink = index234(h->text, i+1); PUT_32BIT_LSB_FIRST(header + 12, otherlink->topicpos); } PUT_32BIT_LSB_FIRST(header + 16, 21 + link->len1); header[20] = link->recordtype; whlp_topicsect_write(h, f, header, 21, 21 + link->len1); /* * Fill in the `first topiclink' pointer in the block * header if appropriate. (We do this _after_ outputting * the header because then we can be sure we'll be in the * same block as we think we are.) */ if (h->firsttopiclink_offset > 0) { whlp_file_seek(f, h->firsttopiclink_offset, 0); whlp_file_add_long(f, link->topicpos); h->firsttopiclink_offset = 0; whlp_file_seek(f, 0, 2); } /* * Update the `last topiclink', and possibly `last * topicstart', pointers. */ h->lasttopiclink = link->topicpos; if (link->recordtype == 2) h->lasttopicstart = link->topicpos; /* * Output LinkData1 and LinkData2. */ whlp_topicsect_write(h, f, link->data1, link->len1, link->len1); whlp_topicsect_write(h, f, link->data2, link->len2, 0); /* * Output the block header. */ link = index234(h->text, i); } } /* ---------------------------------------------------------------------- * Manage the index sections (|KWDATA, |KWMAP, |KWBTREE). */ void whlp_index_term(WHLP h, char *index, WHLP_TOPIC topic) { struct indexrec *idx = snew(struct indexrec); idx->term = dupstr(index); idx->topic = topic; /* * If this reference is already in the tree, just silently drop * the duplicate. */ if (add234(h->index, idx) != idx) { sfree(idx->term); sfree(idx); } } static void whlp_build_kwdata(WHLP h) { struct file *f; int i; struct indexrec *first, *next; f = whlp_new_file(h, "|KWDATA"); /* * Go through the index B-tree, condensing all sequences of * records with the same term into a single one with a valid * (count,offset) pair, and building up the KWDATA section. */ i = 0; while ( (first = index234(h->index, i)) != NULL) { first->count = 1; first->offset = whlp_file_offset(f); whlp_file_add_long(f, first->topic->link->topicoffset); i++; while ( (next = index234(h->index, i)) != NULL && !strcmp(first->term, next->term)) { /* * The next index record has the same term. Fold it * into this one and remove from the tree. */ whlp_file_add_long(f, next->topic->link->topicoffset); first->count++; delpos234(h->index, i); sfree(next->term); sfree(next); } } /* * Now we should have `index' in a form that's ready to * construct |KWBTREE. So we can return. */ } /* ---------------------------------------------------------------------- * Standard chunks of data for the |SYSTEM and |FONT sections. */ static void whlp_system_record(struct file *f, int id, const void *data, int length) { whlp_file_add_short(f, id); whlp_file_add_short(f, length); whlp_file_add(f, data, length); } static void whlp_standard_systemsection(struct file *f) { const char lcid[] = { 0, 0, 0, 0, 0, 0, 0, 0, 9, 4 }; const char charset[] = { 0, 0, 0, 2, 0 }; whlp_file_add_short(f, 0x36C); /* magic number */ whlp_file_add_short(f, 33); /* minor version: HCW 4.00 Win95+ */ whlp_file_add_short(f, 1); /* major version */ whlp_file_add_long(f, time(NULL)); /* generation date */ whlp_file_add_short(f, 0); /* flags=0 means no compression */ /* * Add some magic locale identifier information. (We ought to * find out something about what all this means; see the TODO * list at the top of the file.) */ whlp_system_record(f, 9, lcid, sizeof(lcid)); whlp_system_record(f, 11, charset, sizeof(charset)); } void whlp_title(WHLP h, char *title) { whlp_system_record(h->systemfile, 1, title, 1+strlen(title)); } void whlp_copyright(WHLP h, char *copyright) { whlp_system_record(h->systemfile, 2, copyright, 1+strlen(copyright)); } void whlp_start_macro(WHLP h, char *macro) { whlp_system_record(h->systemfile, 4, macro, 1+strlen(macro)); } void whlp_primary_topic(WHLP h, WHLP_TOPIC t) { h->ptopic = t; } static void whlp_do_primary_topic(WHLP h) { unsigned char firsttopic[4]; PUT_32BIT_LSB_FIRST(firsttopic, h->ptopic->link->topicoffset); whlp_system_record(h->systemfile, 3, firsttopic, sizeof(firsttopic)); } int whlp_create_font(WHLP h, char *font, int family, int halfpoints, int rendition, int r, int g, int b) { char *fontname = dupstr(font); struct fontdesc *fontdesc; int index; font = add234(h->fontnames, fontname); if (font != fontname) { /* The font name was already present. Free the new copy. */ sfree(fontname); } fontdesc = snew(struct fontdesc); fontdesc->font = font; fontdesc->family = family; fontdesc->halfpoints = halfpoints; fontdesc->rendition = rendition; fontdesc->r = r; fontdesc->g = g; fontdesc->b = b; index = count234(h->fontdescs); addpos234(h->fontdescs, fontdesc, index); return index; } static void whlp_make_fontsection(WHLP h, struct file *f) { int i; char *fontname; struct fontdesc *fontdesc; /* * Header block: number of font names, number of font * descriptors, offset to font names, and offset to font * descriptors. */ whlp_file_add_short(f, count234(h->fontnames)); whlp_file_add_short(f, count234(h->fontdescs)); whlp_file_add_short(f, 8); whlp_file_add_short(f, 8 + 32 * count234(h->fontnames)); /* * Font names. */ for (i = 0; (fontname = index234(h->fontnames, i)) != NULL; i++) { char data[32]; memset(data, i, sizeof(data)); strncpy(data, fontname, sizeof(data)); whlp_file_add(f, data, sizeof(data)); } /* * Font descriptors. */ for (i = 0; (fontdesc = index234(h->fontdescs, i)) != NULL; i++) { int fontpos; void *ret; ret = findpos234(h->fontnames, fontdesc->font, NULL, &fontpos); assert(ret != NULL); whlp_file_add_char(f, fontdesc->rendition); whlp_file_add_char(f, fontdesc->halfpoints); whlp_file_add_char(f, fontdesc->family); whlp_file_add_short(f, fontpos); /* Foreground RGB */ whlp_file_add_char(f, fontdesc->r); whlp_file_add_char(f, fontdesc->g); whlp_file_add_char(f, fontdesc->b); /* Background RGB is apparently unused and always set to zero */ whlp_file_add_char(f, 0); whlp_file_add_char(f, 0); whlp_file_add_char(f, 0); } } /* ---------------------------------------------------------------------- * Routines to manage a B-tree type file. */ static void whlp_make_btree(struct file *f, int flags, int pagesize, char *dataformat, tree234 *tree, struct file *map, bt_index_fn indexfn, bt_leaf_fn leaffn) { void **page_elements = NULL; int npages = 0, pagessize = 0; int npages_this_level, nentries, nlevels; int total_leaf_entries; char btdata[MAX_PAGE_SIZE]; int btlen; int page_start, fixups_offset, unused_bytes; void *element; int index; assert(pagesize <= MAX_PAGE_SIZE); /* * Start with the B-tree header. We'll have to come back and * fill in a few bits later. */ whlp_file_add_short(f, 0x293B); /* magic number */ whlp_file_add_short(f, flags); whlp_file_add_short(f, pagesize); { char data[16]; memset(data, 0, sizeof(data)); assert(strlen(dataformat) <= sizeof(data)); memcpy(data, dataformat, strlen(dataformat)); whlp_file_add(f, data, sizeof(data)); } whlp_file_add_short(f, 0); /* must-be-zero */ fixups_offset = whlp_file_offset(f); whlp_file_add_short(f, 0); /* page splits; fix up later */ whlp_file_add_short(f, 0); /* root page index; fix up later */ whlp_file_add_short(f, -1); /* must-be-minus-one */ whlp_file_add_short(f, 0); /* total number of pages; fix later */ whlp_file_add_short(f, 0); /* number of levels; fix later */ whlp_file_add_long(f, count234(tree));/* total B-tree entries */ /* * If we have a map section, leave space at the start for its * element count. */ if (map) { whlp_file_add_short(map, 0); } /* * Now create the leaf pages. */ index = 0; npages_this_level = 0; total_leaf_entries = 0; element = index234(tree, index); while (element) { /* * Make a new leaf page. */ npages_this_level++; if (npages >= pagessize) { pagessize = npages + 32; page_elements = sresize(page_elements, pagessize, void *); } page_elements[npages++] = element; /* * Leave space in the leaf page for the header. We'll * come back and add it later. */ page_start = whlp_file_offset(f); whlp_file_add(f, "12345678", 8); unused_bytes = pagesize - 8; nentries = 0; /* * Now add leaf entries until we run out of room, or out of * elements. */ while (element) { btlen = leaffn(element, btdata); if (btlen > unused_bytes) break; whlp_file_add(f, btdata, btlen); unused_bytes -= btlen; nentries++; index++; element = index234(tree, index); } /* * Now add the unused bytes, and then go back and put * in the header. */ whlp_file_fill(f, unused_bytes); whlp_file_seek(f, page_start, 0); whlp_file_add_short(f, unused_bytes); whlp_file_add_short(f, nentries); /* Previous-page indicator will automatically go to -1 when * absent. */ whlp_file_add_short(f, npages-2); /* Next-page indicator must be -1 if we're at the end. */ if (!element) whlp_file_add_short(f, -1); else whlp_file_add_short(f, npages); whlp_file_seek(f, 0, 2); /* * If we have a map section, add a map entry. */ if (map) { whlp_file_add_long(map, total_leaf_entries); whlp_file_add_short(map, npages_this_level-1); } total_leaf_entries += nentries; } /* * If we have a map section, write the total number of map * entries into it. */ if (map) { whlp_file_seek(map, 0, 0); whlp_file_add_short(map, npages_this_level); whlp_file_seek(map, 0, 2); } /* * Now create further levels until we're down to one page. */ nlevels = 1; while (npages_this_level > 1) { int first = npages - npages_this_level; int last = npages - 1; int current; nlevels++; npages_this_level = 0; current = first; while (current <= last) { /* * Make a new index page. */ npages_this_level++; if (npages >= pagessize) { pagessize = npages + 32; page_elements = sresize(page_elements, pagessize, void *); } page_elements[npages++] = page_elements[current]; /* * Leave space for some of the header, but we can put * in the PreviousPage link already. */ page_start = whlp_file_offset(f); whlp_file_add(f, "1234", 4); whlp_file_add_short(f, current); unused_bytes = pagesize - 6; /* * Now add index entries until we run out of either * space or pages. */ current++; nentries = 0; while (current <= last) { btlen = indexfn(page_elements[current], btdata); if (btlen + 2 > unused_bytes) break; whlp_file_add(f, btdata, btlen); whlp_file_add_short(f, current); unused_bytes -= btlen+2; nentries++; current++; } /* * Now add the unused bytes, and then go back and put * in the header. */ whlp_file_fill(f, unused_bytes); whlp_file_seek(f, page_start, 0); whlp_file_add_short(f, unused_bytes); whlp_file_add_short(f, nentries); whlp_file_seek(f, 0, 2); } } /* * Now we have all our pages ready, and we know where our root * page is. Fix up the main B-tree header. */ whlp_file_seek(f, fixups_offset, 0); /* Creation of every page requires a split unless it's the first in * a new level. Hence, page splits equals pages minus levels. */ whlp_file_add_short(f, npages - nlevels); whlp_file_add_short(f, npages-1); /* root page index */ whlp_file_add_short(f, -1); /* must-be-minus-one */ whlp_file_add_short(f, npages); /* total number of pages */ whlp_file_add_short(f, nlevels); /* number of levels */ /* Just for tidiness, seek to the end of the file :-) */ whlp_file_seek(f, 0, 2); /* Clean up. */ sfree(page_elements); } /* ---------------------------------------------------------------------- * Routines to manage the `internal file' structure. */ static struct file *whlp_new_file(WHLP h, char *name) { struct file *f; f = snew(struct file); f->data = NULL; f->pos = f->len = f->size = 0; if (name) { f->name = dupstr(name); add234(h->files, f); } else { f->name = NULL; } return f; } static void whlp_free_file(struct file *f) { sfree(f->data); sfree(f->name); /* may be NULL */ sfree(f); } static void whlp_file_add(struct file *f, const void *data, int len) { if (f->pos + len > f->size) { f->size = f->pos + len + 1024; f->data = sresize(f->data, f->size, unsigned char); } memcpy(f->data + f->pos, data, len); f->pos += len; if (f->len < f->pos) f->len = f->pos; } static void whlp_file_add_char(struct file *f, int data) { unsigned char s; s = data & 0xFF; whlp_file_add(f, &s, 1); } static void whlp_file_add_short(struct file *f, int data) { unsigned char s[2]; PUT_16BIT_LSB_FIRST(s, data); whlp_file_add(f, s, 2); } static void whlp_file_add_long(struct file *f, int data) { unsigned char s[4]; PUT_32BIT_LSB_FIRST(s, data); whlp_file_add(f, s, 4); } static void whlp_file_fill(struct file *f, int len) { if (f->pos + len > f->size) { f->size = f->pos + len + 1024; f->data = sresize(f->data, f->size, unsigned char); } memset(f->data + f->pos, 0, len); f->pos += len; if (f->len < f->pos) f->len = f->pos; } static void whlp_file_seek(struct file *f, int pos, int whence) { f->pos = (whence == 0 ? 0 : whence == 1 ? f->pos : f->len) + pos; } static int whlp_file_offset(struct file *f) { return f->pos; } /* ---------------------------------------------------------------------- * Open and close routines; final wrapper around everything. */ WHLP whlp_new(void) { WHLP ret; struct file *f; ret = snew(struct WHLP_tag); /* * Internal B-trees. */ ret->files = newtree234(filecmp); ret->pre_contexts = newtree234(NULL); ret->contexts = newtree234(ctxcmp); ret->titles = newtree234(ttlcmp); ret->text = newtree234(NULL); ret->index = newtree234(idxcmp); ret->tabstops = newtree234(tabcmp); ret->fontnames = newtree234(fontcmp); ret->fontdescs = newtree234(NULL); /* * Some standard files. */ f = whlp_new_file(ret, "|CTXOMAP"); whlp_file_add_short(f, 0); /* dummy section */ f = whlp_new_file(ret, "|SYSTEM"); whlp_standard_systemsection(f); ret->systemfile = f; /* * Other variables. */ ret->prevtopic = NULL; ret->ncontexts = 0; ret->link = NULL; return ret; } void whlp_close(WHLP h, char *filename) { FILE *fp; int filecount, offset, index, filelen; struct file *file, *map, *md; context *ctx; int has_index; /* * Lay out the topic section. */ whlp_topic_layout(h); /* * Finish off the system section. */ whlp_do_primary_topic(h); /* * Assemble the font section. */ file = whlp_new_file(h, "|FONT"); whlp_make_fontsection(h, file); /* * Set up the index. */ has_index = (count234(h->index) != 0); if (has_index) whlp_build_kwdata(h); /* * Set up the `titles' B-tree for the |TTLBTREE section. */ for (index = 0; (ctx = index234(h->contexts, index)) != NULL; index++) add234(h->titles, ctx); /* * Construct the various B-trees. */ file = whlp_new_file(h, "|CONTEXT"); whlp_make_btree(file, 0x0002, 0x0800, "L4", h->contexts, NULL, ctxindex, ctxleaf); file = whlp_new_file(h, "|TTLBTREE"); whlp_make_btree(file, 0x0002, 0x0800, "Lz", h->titles, NULL, ttlindex, ttlleaf); if (has_index) { file = whlp_new_file(h, "|KWBTREE"); map = whlp_new_file(h, "|KWMAP"); whlp_make_btree(file, 0x0002, 0x0800, "F24", h->index, map, idxindex, idxleaf); } /* * Open the output file. */ fp = fopen(filename, "wb"); if (!fp) { whlp_abandon(h); return; } /* * Work out all the file offsets. */ filecount = count234(h->files); offset = 16; /* just after header */ for (index = 0; index < filecount; index++) { file = index234(h->files, index); file->fileoffset = offset; offset += 9 + file->len; /* 9 is size of file header */ } /* Now `offset' holds what will be the offset of the master directory. */ md = whlp_new_file(h, NULL); /* master directory file */ whlp_make_btree(md, 0x0402, 0x0400, "z4", h->files, NULL, fileindex, fileleaf); filelen = offset + 9 + md->len; /* * Write out the file header. */ { unsigned char header[16]; PUT_32BIT_LSB_FIRST(header+0, 0x00035F3FL); /* magic */ PUT_32BIT_LSB_FIRST(header+4, offset); /* offset to directory */ PUT_32BIT_LSB_FIRST(header+8, 0xFFFFFFFFL); /* first free block */ PUT_32BIT_LSB_FIRST(header+12, filelen); /* total file length */ fwrite(header, 1, 16, fp); } /* * Now write out each file. */ for (index = 0; index <= filecount; index++) { int used, reserved; unsigned char header[9]; if (index == filecount) file = md; /* master directory comes last */ else file = index234(h->files, index); used = file->len; reserved = used + 9; /* File header. */ PUT_32BIT_LSB_FIRST(header+0, reserved); PUT_32BIT_LSB_FIRST(header+4, used); header[8] = 0; /* flags */ fwrite(header, 1, 9, fp); /* File data. */ fwrite(file->data, 1, file->len, fp); } fclose(fp); whlp_free_file(md); whlp_abandon(h); /* now free everything */ } void whlp_abandon(WHLP h) { struct file *f; struct indexrec *idx; struct topiclink *link; struct fontdesc *fontdesc; char *fontname; context *ctx; /* Get rid of any lingering tab stops. */ whlp_para_reset(h); /* Delete the (now empty) tabstops tree. */ freetree234(h->tabstops); /* Delete the index tree and all its entries. */ while ( (idx = index234(h->index, 0)) != NULL) { delpos234(h->index, 0); sfree(idx->term); sfree(idx); } freetree234(h->index); /* Delete the text tree and all its topiclinks. */ while ( (link = index234(h->text, 0)) != NULL) { delpos234(h->text, 0); sfree(link->data1); /* may be NULL */ sfree(link->data2); /* may be NULL */ sfree(link); } freetree234(h->text); /* Delete the fontdescs tree and all its entries. */ while ( (fontdesc = index234(h->fontdescs, 0)) != NULL) { delpos234(h->fontdescs, 0); sfree(fontdesc); } freetree234(h->fontdescs); /* Delete the fontnames tree and all its entries. */ while ( (fontname = index234(h->fontnames, 0)) != NULL) { delpos234(h->fontnames, 0); sfree(fontname); } freetree234(h->fontnames); /* There might be an unclosed paragraph in h->link. */ if (h->link) sfree(h->link); /* if so it won't have data1 or data2 */ /* * `titles' contains copies of the `contexts' entries, so we * don't need to free them here. */ freetree234(h->titles); /* * `contexts' and `pre_contexts' _both_ contain contexts that * need freeing. (pre_contexts shouldn't contain any, unless * the help generation was abandoned half-way through.) */ while ( (ctx = index234(h->pre_contexts, 0)) != NULL) { delpos234(h->index, 0); sfree(ctx->name); sfree(ctx->title); sfree(ctx); } freetree234(h->pre_contexts); while ( (ctx = index234(h->contexts, 0)) != NULL) { delpos234(h->contexts, 0); sfree(ctx->name); sfree(ctx->title); sfree(ctx); } freetree234(h->contexts); /* * Free all the internal files. */ while ( (f = index234(h->files, 0)) != NULL ) { delpos234(h->files, 0); whlp_free_file(f); } freetree234(h->files); sfree(h); } #ifdef TESTMODE int main(void) { WHLP h; WHLP_TOPIC t1, t2, t3; char *e; char mymacro[100]; h = whlp_new(); whlp_title(h, "Test Help File"); whlp_copyright(h, "This manual is copyright \251 2001 Simon Tatham." " All rights reversed."); whlp_start_macro(h, "CB(\"btn_about\",\"&About\",\"About()\")"); whlp_start_macro(h, "CB(\"btn_up\",\"&Up\",\"Contents()\")"); whlp_start_macro(h, "BrowseButtons()"); whlp_create_font(h, "Arial", WHLP_FONTFAM_SANS, 30, 0, 0, 0, 0); whlp_create_font(h, "Times New Roman", WHLP_FONTFAM_SERIF, 24, WHLP_FONT_STRIKEOUT, 0, 0, 0); whlp_create_font(h, "Times New Roman", WHLP_FONTFAM_SERIF, 24, WHLP_FONT_ITALIC, 0, 0, 0); whlp_create_font(h, "Courier New", WHLP_FONTFAM_FIXED, 24, 0, 0, 0, 0); t1 = whlp_register_topic(h, "foobar", &e); assert(t1 != NULL); t2 = whlp_register_topic(h, "M359HPEHGW", &e); assert(t2 != NULL); t3 = whlp_register_topic(h, "Y5VQEXZQVJ", &e); assert(t3 == NULL && !strcmp(e, "M359HPEHGW")); t3 = whlp_register_topic(h, NULL, NULL); assert(t3 != NULL); whlp_primary_topic(h, t2); whlp_prepare(h); whlp_begin_topic(h, t1, "First Topic", "DB(\"btn_up\")", NULL); whlp_begin_para(h, WHLP_PARA_NONSCROLL); whlp_set_font(h, 0); whlp_text(h, "Foobar"); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "This is a silly paragraph with "); whlp_set_font(h, 3); whlp_text(h, "code"); whlp_set_font(h, 1); whlp_text(h, " in it."); whlp_end_para(h); whlp_para_attr(h, WHLP_PARA_SPACEABOVE, 12); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "This second, equally silly, paragraph has "); whlp_set_font(h, 2); whlp_text(h, "emphasis"); whlp_set_font(h, 1); whlp_text(h, " just to prove we can do it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Now I'm going to waffle on indefinitely, in a vague attempt" " to make some wrapping happen, and also to make the topicblock" " go across its boundaries. This is going to take a fair amount" " of text, so I'll just have to cheat and c'n'p a lot of it."); whlp_end_para(h); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Have a "); whlp_start_hyperlink(h, t2); whlp_text(h, "hyperlink"); whlp_end_hyperlink(h); whlp_text(h, " to another topic."); whlp_end_para(h); sprintf(mymacro, "CBB(\"btn_up\",\"JI(`',`%s')\");EB(\"btn_up\")", whlp_topic_id(t3)); whlp_begin_topic(h, t2, "Second Topic", mymacro, NULL); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "This topic contains no non-scrolling region. I would" " illustrate this with a ludicrously long paragraph, but that" " would get very tedious very quickly. Instead I'll just waffle" " on pointlessly for a little bit and then shut up."); whlp_end_para(h); whlp_set_tabstop(h, 36, WHLP_ALIGN_LEFT); whlp_para_attr(h, WHLP_PARA_LEFTINDENT, 36); whlp_para_attr(h, WHLP_PARA_FIRSTLINEINDENT, -36); whlp_para_attr(h, WHLP_PARA_SPACEABOVE, 12); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "\225"); /* bullet */ whlp_tab(h); whlp_text(h, "This is a paragraph with a bullet. With any luck it should" " work exactly like it used to in the old NASM help file."); whlp_end_para(h); whlp_set_tabstop(h, 128, WHLP_ALIGN_RIGHT); whlp_set_tabstop(h, 256, WHLP_ALIGN_CENTRE); whlp_set_tabstop(h, 384, WHLP_ALIGN_LEFT); whlp_para_attr(h, WHLP_PARA_SPACEABOVE, 12); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Ooh:"); whlp_tab(h); whlp_text(h, "Right?"); whlp_tab(h); whlp_text(h, "Centre?"); whlp_tab(h); whlp_text(h, "Left?"); whlp_end_para(h); whlp_set_tabstop(h, 128, WHLP_ALIGN_RIGHT); whlp_set_tabstop(h, 256, WHLP_ALIGN_CENTRE); whlp_set_tabstop(h, 384, WHLP_ALIGN_LEFT); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "Aah:"); whlp_tab(h); whlp_text(h, "R?"); whlp_tab(h); whlp_text(h, "C?"); whlp_tab(h); whlp_text(h, "L?"); whlp_end_para(h); sprintf(mymacro, "CBB(\"btn_up\",\"JI(`',`%s')\");EB(\"btn_up\")", whlp_topic_id(t1)); whlp_begin_topic(h, t3, "Third Topic", mymacro, NULL); whlp_begin_para(h, WHLP_PARA_SCROLL); whlp_set_font(h, 1); whlp_text(h, "This third topic is almost as boring as the first. Woo!"); whlp_end_para(h); /* * Browse sequence. */ whlp_browse_link(h, t1, t2); whlp_browse_link(h, t2, t3); /* * Index terms. */ whlp_index_term(h, "foobarbaz", t1); whlp_index_term(h, "foobarbaz", t2); whlp_index_term(h, "foobarbaz", t3); whlp_index_term(h, "foobar", t1); whlp_index_term(h, "foobar", t2); whlp_index_term(h, "foobaz", t1); whlp_index_term(h, "foobaz", t3); whlp_index_term(h, "barbaz", t2); whlp_index_term(h, "barbaz", t3); whlp_index_term(h, "foo", t1); whlp_index_term(h, "bar", t2); whlp_index_term(h, "baz", t3); whlp_close(h, "test.hlp"); return 0; } #endif 779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2008-2009 Teruaki Kawashima
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "plugin.h"
#include "lib/playback_control.h"
#include "lib/configfile.h"
#include "lib/helper.h"
#include <ctype.h>



#define MAX_LINE_LEN    256
#define LRC_BUFFER_SIZE 0x3000 /* 12 kiB */
#if PLUGIN_BUFFER_SIZE >= 0x10000 /* no id3 support for low mem targets */
/* define this to read lyrics in id3 tag */
#define LRC_SUPPORT_ID3
#endif
/* define this to show debug info in menu */
/* #define LRC_DEBUG */

enum lrc_screen {
    PLUGIN_OTHER = 0x200,
    LRC_GOTO_MAIN,
    LRC_GOTO_MENU,
    LRC_GOTO_EDITOR,
};

struct lrc_word {
    long time_start;
    short count;
    short width;
    unsigned char *word;
};

struct lrc_brpos {
    short count;
    short width;
};

struct lrc_line {
    long time_start;
    long old_time_start;
    off_t file_offset; /* offset of time tag in file */
    short nword;
    short width;
    short nline[NB_SCREENS];
    struct lrc_line *next;
    struct lrc_word *words;
};

struct preferences {
    /* display settings */
#if LCD_DEPTH > 1
    unsigned active_color;
    unsigned inactive_color;
#endif
#ifdef HAVE_LCD_BITMAP
    bool wrap;
    bool wipe;
    bool active_one_line;
    int  align; /* 0: left, 1: center, 2: right */
    bool statusbar_on;
    bool display_title;
#endif
    bool display_time;
    bool backlight_on;

    /* file settings */
    char lrc_directory[64];
    int encoding;
#ifdef LRC_SUPPORT_ID3
    bool read_id3;
#endif
};

static struct preferences prefs, old_prefs;
static unsigned char *lrc_buffer;
static size_t lrc_buffer_size;
static size_t lrc_buffer_used, lrc_buffer_end;
enum extention_types {LRC, LRC8, SNC, TXT, NUM_TYPES, ID3_SYLT, ID3_USLT};
static const char *extentions[NUM_TYPES] = {
    ".lrc", ".lrc8", ".snc", ".txt",
};
static struct lrc_info {
    struct mp3entry *id3;
    long elapsed;
    long length;
    long ff_rewind;
    int  audio_status;
    char mp3_file[MAX_PATH];
    char lrc_file[MAX_PATH];
    char *title;  /* use lrc_buffer */
    char *artist; /* use lrc_buffer */
    enum extention_types type;
    long offset; /* msec */
    off_t offset_file_offset; /* offset of offset tag in file */
    int  nlrcbrpos;
    int  nlrcline;
    struct lrc_line *ll_head, **ll_tail;
    bool found_lrc;
    bool loaded_lrc;
    bool changed_lrc;
    bool too_many_lines; /* true if nlrcline >= max_lrclines after calc pos */
#ifdef HAVE_LCD_BITMAP
    bool wipe; /* false if lyrics is unsynched */
#endif
} current;
static char temp_buf[MAX(MAX_LINE_LEN,MAX_PATH)];
#ifdef HAVE_LCD_BITMAP
static int font_ui_height = 1;
static struct viewport vp_info[NB_SCREENS];
#endif
static struct viewport vp_lyrics[NB_SCREENS];

#define AUDIO_PAUSE (current.audio_status & AUDIO_STATUS_PAUSE)
#define AUDIO_PLAY  (current.audio_status & AUDIO_STATUS_PLAY)
#define AUDIO_STOP  (!(current.audio_status & AUDIO_STATUS_PLAY))

/*******************************
 * lrc_set_time
 *******************************/
#define LST_SET_MSEC    0x00010000
#define LST_SET_SEC     0x00020000
#define LST_SET_MIN     0x00040000
#define LST_SET_HOUR    0x00080000

#include "lib/pluginlib_actions.h"
#define LST_SET_TIME    (LST_SET_MSEC|LST_SET_SEC|LST_SET_MIN|LST_SET_HOUR)
#ifdef HAVE_LCD_CHARCELLS
#define LST_OFF_Y 0
#else /* HAVE_LCD_BITMAP */
#define LST_OFF_Y 1
#endif
int lrc_set_time(const char *title, const char *unit, long *pval,
                 int step, int min, int max, int flags)
{
    const struct button_mapping *lst_contexts[] = {
        pla_main_ctx,
#ifdef HAVE_REMOTE_LCD
        pla_remote_ctx,
#endif
    };
    /* how many */
    const unsigned char formats[4][8] = {"%03ld.", "%02ld.", "%02ld:", "%02ld:"};
    const unsigned int maxs[4] = {1000, 60, 60, 24};
    const unsigned int scls[4] = {1, 1000, 60*1000, 60*60*1000};
    char buffer[32];
    long value = *pval, scl_step = step, i = 0;
    int pos = 0, last_pos = 0, pos_min = 3, pos_max = 0;
    int x = 0, y = 0, p_start = 0, p_end = 0;
    int ret = 10;

    if (!(flags&LST_SET_TIME))
        return -1;

    for (i = 0; i < 4; i++)
    {
        if (flags&(LST_SET_MSEC<<i))
        {
            if (pos_min > i) pos_min = i;
            if (pos_max < i) pos_max = i;
        }
    }
    pos = pos_min;

    rb->button_clear_queue();
    rb->lcd_clear_display();
    rb->lcd_puts_scroll(0, LST_OFF_Y, title);
    while (ret == 10)
    {
        int len = 0;
        long abs_val = value;
        long segvals[4] = {-1, -1, -1, -1};
        /* show negative value like -00:01 but 00:-1 */
        if (value < 0)
        {
            buffer[len++] = '-';
            abs_val = -value;
        }
        buffer[len] = 0;
        /* calc value of each segments */
        for (i = pos_min; i <= pos_max; i++)
        {
            segvals[i] = abs_val % maxs[i];
            abs_val /= maxs[i];
        }
        segvals[i-1] += abs_val * maxs[i-1];
        for (i = pos_max; i >= pos_min; i--)
        {
            if (pos == i)
            {
                rb->lcd_getstringsize(buffer, &x, &y);
                p_start = len;
            }
            rb->snprintf(&buffer[len], 32-len, formats[i], segvals[i]);
            len += rb->strlen(&buffer[len]);
            if (pos == i)
                p_end = len;
        }
        buffer[len-1] = 0; /* remove last separater */
        if (unit != NULL)
        {
            rb->snprintf(&buffer[len], 32-len, " (%s)", unit);
        }
        rb->lcd_puts(0, LST_OFF_Y+1, buffer);
        if (pos_min != pos_max)
        {
            /* draw cursor */