oleaut32: Dump MSFT format typeinfos upon loading.
[wine] / programs / winhlp32 / hlpfile.c
1 /*
2  * Help Viewer
3  *
4  * Copyright    1996 Ulrich Schmid
5  *              2002, 2008 Eric Pouech
6  *              2007 Kirill K. Smirnov
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "windef.h"
28 #include "winbase.h"
29 #include "wingdi.h"
30 #include "winuser.h"
31 #include "winhelp.h"
32
33 #include "wine/debug.h"
34
35 WINE_DEFAULT_DEBUG_CHANNEL(winhelp);
36
37 static inline unsigned short GET_USHORT(const BYTE* buffer, unsigned i)
38 {
39     return (BYTE)buffer[i] + 0x100 * (BYTE)buffer[i + 1];
40 }
41
42 static inline short GET_SHORT(const BYTE* buffer, unsigned i)
43 {
44     return (BYTE)buffer[i] + 0x100 * (signed char)buffer[i+1];
45 }
46
47 static inline unsigned GET_UINT(const BYTE* buffer, unsigned i)
48 {
49     return GET_USHORT(buffer, i) + 0x10000 * GET_USHORT(buffer, i + 2);
50 }
51
52 static HLPFILE *first_hlpfile = 0;
53
54 static BOOL  HLPFILE_DoReadHlpFile(HLPFILE*, LPCSTR);
55 static BOOL  HLPFILE_ReadFileToBuffer(HLPFILE*, HFILE);
56 static BOOL  HLPFILE_FindSubFile(HLPFILE*, LPCSTR, BYTE**, BYTE**);
57 static BOOL  HLPFILE_SystemCommands(HLPFILE*);
58 static INT   HLPFILE_UncompressedLZ77_Size(const BYTE *ptr, const BYTE *end);
59 static BYTE* HLPFILE_UncompressLZ77(const BYTE *ptr, const BYTE *end, BYTE *newptr);
60 static BOOL  HLPFILE_UncompressLZ77_Phrases(HLPFILE*);
61 static BOOL  HLPFILE_Uncompress_Phrases40(HLPFILE*);
62 static BOOL  HLPFILE_Uncompress_Topic(HLPFILE*);
63 static BOOL  HLPFILE_GetContext(HLPFILE*);
64 static BOOL  HLPFILE_GetKeywords(HLPFILE*);
65 static BOOL  HLPFILE_GetMap(HLPFILE*);
66 static BOOL  HLPFILE_GetTOMap(HLPFILE*);
67 static BOOL  HLPFILE_AddPage(HLPFILE*, const BYTE*, const BYTE*, unsigned, unsigned);
68 static BOOL  HLPFILE_SkipParagraph(HLPFILE*, const BYTE*, const BYTE*, unsigned*);
69 static void  HLPFILE_Uncompress2(HLPFILE*, const BYTE*, const BYTE*, BYTE*, const BYTE*);
70 static BOOL  HLPFILE_Uncompress3(HLPFILE*, char*, const char*, const BYTE*, const BYTE*);
71 static void  HLPFILE_UncompressRLE(const BYTE* src, const BYTE* end, BYTE* dst, unsigned dstsz);
72 static BOOL  HLPFILE_ReadFont(HLPFILE* hlpfile);
73
74 /******************************************************************
75  *              HLPFILE_PageByOffset
76  *
77  *
78  */
79 HLPFILE_PAGE *HLPFILE_PageByOffset(HLPFILE* hlpfile, LONG offset, ULONG* relative)
80 {
81     HLPFILE_PAGE*       page;
82     HLPFILE_PAGE*       found;
83
84     if (!hlpfile) return 0;
85
86     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, offset);
87
88     if (offset == 0xFFFFFFFF) return NULL;
89     page = NULL;
90
91     for (found = NULL, page = hlpfile->first_page; page; page = page->next)
92     {
93         if (page->offset <= offset && (!found || found->offset < page->offset))
94         {
95             *relative = offset - page->offset;
96             found = page;
97         }
98     }
99     if (!found)
100         WINE_ERR("Page of offset %u not found in file %s\n",
101                  offset, hlpfile->lpszPath);
102     return found;
103 }
104
105 /**************************************************************************
106  * comp_PageByHash
107  *
108  * HLPFILE_BPTreeCompare function for '|CONTEXT' B+ tree file
109  *
110  */
111 static int comp_PageByHash(void *p, const void *key,
112                            int leaf, void** next)
113 {
114     LONG lKey = (LONG_PTR)key;
115     LONG lTest = (INT)GET_UINT(p, 0);
116
117     *next = (char *)p+(leaf?8:6);
118     WINE_TRACE("Comparing '%d' with '%d'\n", lKey, lTest);
119     if (lTest < lKey) return -1;
120     if (lTest > lKey) return 1;
121     return 0;
122 }
123
124 /***********************************************************************
125  *
126  *           HLPFILE_PageByHash
127  */
128 HLPFILE_PAGE *HLPFILE_PageByHash(HLPFILE* hlpfile, LONG lHash, ULONG* relative)
129 {
130     BYTE *ptr;
131
132     if (!hlpfile) return NULL;
133     if (!lHash) return HLPFILE_Contents(hlpfile, relative);
134
135     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lHash);
136
137     /* For win 3.0 files hash values are really page numbers */
138     if (hlpfile->version <= 16)
139     {
140         if (lHash >= hlpfile->wTOMapLen) return NULL;
141         return HLPFILE_PageByOffset(hlpfile, hlpfile->TOMap[lHash], relative);
142     }
143
144     ptr = HLPFILE_BPTreeSearch(hlpfile->Context, LongToPtr(lHash), comp_PageByHash);
145     if (!ptr)
146     {
147         WINE_ERR("Page of hash %x not found in file %s\n", lHash, hlpfile->lpszPath);
148         return NULL;
149     }
150
151     return HLPFILE_PageByOffset(hlpfile, GET_UINT(ptr, 4), relative);
152 }
153
154 /***********************************************************************
155  *
156  *           HLPFILE_PageByMap
157  */
158 HLPFILE_PAGE *HLPFILE_PageByMap(HLPFILE* hlpfile, LONG lMap, ULONG* relative)
159 {
160     unsigned int i;
161
162     if (!hlpfile) return 0;
163
164     WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lMap);
165
166     for (i = 0; i < hlpfile->wMapLen; i++)
167     {
168         if (hlpfile->Map[i].lMap == lMap)
169             return HLPFILE_PageByOffset(hlpfile, hlpfile->Map[i].offset, relative);
170     }
171
172     WINE_ERR("Page of Map %x not found in file %s\n", lMap, hlpfile->lpszPath);
173     return NULL;
174 }
175
176 /***********************************************************************
177  *
178  *           HLPFILE_Contents
179  */
180 HLPFILE_PAGE* HLPFILE_Contents(HLPFILE *hlpfile, ULONG* relative)
181 {
182     HLPFILE_PAGE*       page = NULL;
183
184     if (!hlpfile) return NULL;
185
186     page = HLPFILE_PageByOffset(hlpfile, hlpfile->contents_start, relative);
187     if (!page)
188     {
189         page = hlpfile->first_page;
190         *relative = 0;
191     }
192     return page;
193 }
194
195 /***********************************************************************
196  *
197  *           HLPFILE_Hash
198  */
199 LONG HLPFILE_Hash(LPCSTR lpszContext)
200 {
201     LONG lHash = 0;
202     CHAR c;
203
204     while ((c = *lpszContext++))
205     {
206         CHAR x = 0;
207         if (c >= 'A' && c <= 'Z') x = c - 'A' + 17;
208         if (c >= 'a' && c <= 'z') x = c - 'a' + 17;
209         if (c >= '1' && c <= '9') x = c - '0';
210         if (c == '0') x = 10;
211         if (c == '.') x = 12;
212         if (c == '_') x = 13;
213         if (x) lHash = lHash * 43 + x;
214     }
215     return lHash;
216 }
217
218 /***********************************************************************
219  *
220  *           HLPFILE_ReadHlpFile
221  */
222 HLPFILE *HLPFILE_ReadHlpFile(LPCSTR lpszPath)
223 {
224     HLPFILE*      hlpfile;
225
226     for (hlpfile = first_hlpfile; hlpfile; hlpfile = hlpfile->next)
227     {
228         if (!strcmp(lpszPath, hlpfile->lpszPath))
229         {
230             hlpfile->wRefCount++;
231             return hlpfile;
232         }
233     }
234
235     hlpfile = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
236                         sizeof(HLPFILE) + lstrlen(lpszPath) + 1);
237     if (!hlpfile) return 0;
238
239     hlpfile->lpszPath           = (char*)hlpfile + sizeof(HLPFILE);
240     hlpfile->contents_start     = 0xFFFFFFFF;
241     hlpfile->next               = first_hlpfile;
242     hlpfile->wRefCount          = 1;
243
244     strcpy(hlpfile->lpszPath, lpszPath);
245
246     first_hlpfile = hlpfile;
247     if (hlpfile->next) hlpfile->next->prev = hlpfile;
248
249     if (!HLPFILE_DoReadHlpFile(hlpfile, lpszPath))
250     {
251         HLPFILE_FreeHlpFile(hlpfile);
252         hlpfile = 0;
253     }
254
255     return hlpfile;
256 }
257
258 /***********************************************************************
259  *
260  *           HLPFILE_DoReadHlpFile
261  */
262 static BOOL HLPFILE_DoReadHlpFile(HLPFILE *hlpfile, LPCSTR lpszPath)
263 {
264     BOOL        ret;
265     HFILE       hFile;
266     OFSTRUCT    ofs;
267     BYTE*       buf;
268     DWORD       ref = 0x0C;
269     unsigned    index, old_index, offset, len, offs, topicoffset;
270
271     hFile = OpenFile(lpszPath, &ofs, OF_READ);
272     if (hFile == HFILE_ERROR) return FALSE;
273
274     ret = HLPFILE_ReadFileToBuffer(hlpfile, hFile);
275     _lclose(hFile);
276     if (!ret) return FALSE;
277
278     if (!HLPFILE_SystemCommands(hlpfile)) return FALSE;
279
280     if (hlpfile->version <= 16 && !HLPFILE_GetTOMap(hlpfile)) return FALSE;
281
282     /* load phrases support */
283     if (!HLPFILE_UncompressLZ77_Phrases(hlpfile))
284         HLPFILE_Uncompress_Phrases40(hlpfile);
285
286     if (!HLPFILE_Uncompress_Topic(hlpfile)) return FALSE;
287     if (!HLPFILE_ReadFont(hlpfile)) return FALSE;
288
289     buf = hlpfile->topic_map[0];
290     old_index = -1;
291     offs = 0;
292     do
293     {
294         BYTE*   end;
295
296         if (hlpfile->version <= 16)
297         {
298             index  = (ref - 0x0C) / hlpfile->dsize;
299             offset = (ref - 0x0C) % hlpfile->dsize;
300         }
301         else
302         {
303             index  = (ref - 0x0C) >> 14;
304             offset = (ref - 0x0C) & 0x3FFF;
305         }
306
307         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
308         {
309             /* we jumped to the next block, adjust pointers */
310             ref -= 12;
311             offset -= 12;
312         }
313
314         WINE_TRACE("ref=%08x => [%u/%u]\n", ref, index, offset);
315
316         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
317         buf = hlpfile->topic_map[index] + offset;
318         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
319         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
320         if (index != old_index) {offs = 0; old_index = index;}
321
322         switch (buf[0x14])
323         {
324         case 0x02:
325             if (hlpfile->version <= 16)
326                 topicoffset = ref + index * 12;
327             else
328                 topicoffset = index * 0x8000 + offs;
329             if (!HLPFILE_AddPage(hlpfile, buf, end, ref, topicoffset)) return FALSE;
330             break;
331
332         case 0x01:
333         case 0x20:
334         case 0x23:
335             if (!HLPFILE_SkipParagraph(hlpfile, buf, end, &len)) return FALSE;
336             offs += len;
337             break;
338
339         default:
340             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
341         }
342
343         if (hlpfile->version <= 16)
344         {
345             ref += GET_UINT(buf, 0xc);
346             if (GET_UINT(buf, 0xc) == 0)
347                 break;
348         }
349         else
350             ref = GET_UINT(buf, 0xc);
351     } while (ref != 0xffffffff);
352
353     HLPFILE_GetKeywords(hlpfile);
354     HLPFILE_GetMap(hlpfile);
355     if (hlpfile->version <= 16) return TRUE;
356     return HLPFILE_GetContext(hlpfile);
357 }
358
359 /***********************************************************************
360  *
361  *           HLPFILE_AddPage
362  */
363 static BOOL HLPFILE_AddPage(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned ref, unsigned offset)
364 {
365     HLPFILE_PAGE* page;
366     const BYTE*   title;
367     UINT          titlesize, blocksize, datalen;
368     char*         ptr;
369     HLPFILE_MACRO*macro;
370
371     blocksize = GET_UINT(buf, 0);
372     datalen = GET_UINT(buf, 0x10);
373     title = buf + datalen;
374     if (title > end) {WINE_WARN("page2\n"); return FALSE;};
375
376     titlesize = GET_UINT(buf, 4);
377     page = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_PAGE) + titlesize + 1);
378     if (!page) return FALSE;
379     page->lpszTitle = (char*)page + sizeof(HLPFILE_PAGE);
380
381     if (titlesize > blocksize - datalen)
382     {
383         /* need to decompress */
384         if (hlpfile->hasPhrases)
385             HLPFILE_Uncompress2(hlpfile, title, end, (BYTE*)page->lpszTitle, (BYTE*)page->lpszTitle + titlesize);
386         else if (hlpfile->hasPhrases40)
387             HLPFILE_Uncompress3(hlpfile, page->lpszTitle, page->lpszTitle + titlesize, title, end);
388         else
389         {
390             WINE_FIXME("Text size is too long, splitting\n");
391             titlesize = blocksize - datalen;
392             memcpy(page->lpszTitle, title, titlesize);
393         }
394     }
395     else
396         memcpy(page->lpszTitle, title, titlesize);
397
398     page->lpszTitle[titlesize] = '\0';
399
400     if (hlpfile->first_page)
401     {
402         hlpfile->last_page->next = page;
403         page->prev = hlpfile->last_page;
404         hlpfile->last_page = page;
405     }
406     else
407     {
408         hlpfile->first_page = page;
409         hlpfile->last_page = page;
410         page->prev = NULL;
411     }
412
413     page->file            = hlpfile;
414     page->next            = NULL;
415     page->first_macro     = NULL;
416     page->first_link      = NULL;
417     page->wNumber         = GET_UINT(buf, 0x21);
418     page->offset          = offset;
419     page->reference       = ref;
420
421     page->browse_bwd = GET_UINT(buf, 0x19);
422     page->browse_fwd = GET_UINT(buf, 0x1D);
423
424     if (hlpfile->version <= 16)
425     {
426         if (page->browse_bwd == 0xFFFF || page->browse_bwd == 0xFFFFFFFF)
427             page->browse_bwd = 0xFFFFFFFF;
428         else
429             page->browse_bwd = hlpfile->TOMap[page->browse_bwd];
430
431         if (page->browse_fwd == 0xFFFF || page->browse_fwd == 0xFFFFFFFF)
432             page->browse_fwd = 0xFFFFFFFF;
433         else
434             page->browse_fwd = hlpfile->TOMap[page->browse_fwd];
435     }
436
437     WINE_TRACE("Added page[%d]: title='%s' %08x << %08x >> %08x\n",
438                page->wNumber, page->lpszTitle, 
439                page->browse_bwd, page->offset, page->browse_fwd);
440
441     /* now load macros */
442     ptr = page->lpszTitle + strlen(page->lpszTitle) + 1;
443     while (ptr < page->lpszTitle + titlesize)
444     {
445         unsigned len = strlen(ptr);
446         char*    macro_str;
447
448         WINE_TRACE("macro: %s\n", ptr);
449         macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + len + 1);
450         macro->lpszMacro = macro_str = (char*)(macro + 1);
451         memcpy(macro_str, ptr, len + 1);
452         /* FIXME: shall we really link macro in reverse order ??
453          * may produce strange results when played at page opening
454          */
455         macro->next = page->first_macro;
456         page->first_macro = macro;
457         ptr += len + 1;
458     }
459
460     return TRUE;
461 }
462
463 static LONG fetch_long(const BYTE** ptr)
464 {
465     LONG        ret;
466
467     if (*(*ptr) & 1)
468     {
469         ret = (*(const ULONG*)(*ptr) - 0x80000000) / 2;
470         (*ptr) += 4;
471     }
472     else
473     {
474         ret = (*(const USHORT*)(*ptr) - 0x8000) / 2;
475         (*ptr) += 2;
476     }
477
478     return ret;
479 }
480
481 static ULONG fetch_ulong(const BYTE** ptr)
482 {
483     ULONG        ret;
484
485     if (*(*ptr) & 1)
486     {
487         ret = *(const ULONG*)(*ptr) / 2;
488         (*ptr) += 4;
489     }
490     else
491     {
492         ret = *(const USHORT*)(*ptr) / 2;
493         (*ptr) += 2;
494     }
495     return ret;
496 }    
497
498 static short fetch_short(const BYTE** ptr)
499 {
500     short       ret;
501
502     if (*(*ptr) & 1)
503     {
504         ret = (*(const unsigned short*)(*ptr) - 0x8000) / 2;
505         (*ptr) += 2;
506     }
507     else
508     {
509         ret = (*(const unsigned char*)(*ptr) - 0x80) / 2;
510         (*ptr)++;
511     }
512     return ret;
513 }
514
515 static unsigned short fetch_ushort(const BYTE** ptr)
516 {
517     unsigned short ret;
518
519     if (*(*ptr) & 1)
520     {
521         ret = *(const unsigned short*)(*ptr) / 2;
522         (*ptr) += 2;
523     }
524     else
525     {
526         ret = *(const unsigned char*)(*ptr) / 2;
527         (*ptr)++;
528     }
529     return ret;
530 }
531
532 /***********************************************************************
533  *
534  *           HLPFILE_SkipParagraph
535  */
536 static BOOL HLPFILE_SkipParagraph(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned* len)
537 {
538     const BYTE  *tmp;
539
540     if (!hlpfile->first_page) {WINE_WARN("no page\n"); return FALSE;};
541     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
542
543     tmp = buf + 0x15;
544     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
545     {
546         fetch_long(&tmp);
547         *len = fetch_ushort(&tmp);
548     }
549     else *len = end-buf-15;
550
551     return TRUE;
552 }
553
554 /******************************************************************
555  *              HLPFILE_DecompressGfx
556  *
557  * Decompress the data part of a bitmap or a metafile
558  */
559 static const BYTE*      HLPFILE_DecompressGfx(const BYTE* src, unsigned csz, unsigned sz, BYTE packing,
560                                               BYTE** alloc)
561 {
562     const BYTE* dst;
563     BYTE*       tmp;
564     unsigned    sz77;
565
566     WINE_TRACE("Unpacking (%d) from %u bytes to %u bytes\n", packing, csz, sz);
567
568     switch (packing)
569     {
570     case 0: /* uncompressed */
571         if (sz != csz)
572             WINE_WARN("Bogus gfx sizes (uncompressed): %u / %u\n", sz, csz);
573         dst = src;
574         *alloc = NULL;
575         break;
576     case 1: /* RunLen */
577         dst = *alloc = HeapAlloc(GetProcessHeap(), 0, sz);
578         if (!dst) return NULL;
579         HLPFILE_UncompressRLE(src, src + csz, *alloc, sz);
580         break;
581     case 2: /* LZ77 */
582         sz77 = HLPFILE_UncompressedLZ77_Size(src, src + csz);
583         dst = *alloc = HeapAlloc(GetProcessHeap(), 0, sz77);
584         if (!dst) return NULL;
585         HLPFILE_UncompressLZ77(src, src + csz, *alloc);
586         if (sz77 != sz)
587             WINE_WARN("Bogus gfx sizes (LZ77): %u / %u\n", sz77, sz);
588         break;
589     case 3: /* LZ77 then RLE */
590         sz77 = HLPFILE_UncompressedLZ77_Size(src, src + csz);
591         tmp = HeapAlloc(GetProcessHeap(), 0, sz77);
592         if (!tmp) return FALSE;
593         HLPFILE_UncompressLZ77(src, src + csz, tmp);
594         dst = *alloc = HeapAlloc(GetProcessHeap(), 0, sz);
595         if (!dst)
596         {
597             HeapFree(GetProcessHeap(), 0, tmp);
598             return FALSE;
599         }
600         HLPFILE_UncompressRLE(tmp, tmp + sz77, *alloc, sz);
601         HeapFree(GetProcessHeap(), 0, tmp);
602         break;
603     default:
604         WINE_FIXME("Unsupported packing %u\n", packing);
605         return NULL;
606     }
607     return dst;
608 }
609
610 static BOOL HLPFILE_RtfAddRawString(struct RtfData* rd, const char* str, size_t sz)
611 {
612     if (rd->ptr + sz >= rd->data + rd->allocated)
613     {
614         char*   new = HeapReAlloc(GetProcessHeap(), 0, rd->data, rd->allocated *= 2);
615         if (!new) return FALSE;
616         rd->ptr = new + (rd->ptr - rd->data);
617         rd->data = new;
618     }
619     memcpy(rd->ptr, str, sz);
620     rd->ptr += sz;
621
622     return TRUE;
623 }
624
625 static BOOL HLPFILE_RtfAddControl(struct RtfData* rd, const char* str)
626 {
627     if (*str == '\\' || *str == '{') rd->in_text = FALSE;
628     else if (*str == '}') rd->in_text = TRUE;
629     return HLPFILE_RtfAddRawString(rd, str, strlen(str));
630 }
631
632 static BOOL HLPFILE_RtfAddText(struct RtfData* rd, const char* str)
633 {
634     const char* p;
635     const char* last;
636     const char* replace;
637     unsigned    rlen;
638
639     if (!rd->in_text)
640     {
641         if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
642         rd->in_text = TRUE;
643     }
644     for (last = p = str; *p; p++)
645     {
646         if (*p < 0) /* escape non ASCII chars */
647         {
648             static char         xx[8];
649             rlen = sprintf(xx, "\\'%x", *(const BYTE*)p);
650             replace = xx;
651         }
652         else switch (*p)
653         {
654         case '{':  rlen = 2; replace = "\\{";  break;
655         case '}':  rlen = 2; replace = "\\}";  break;
656         case '\\': rlen = 2; replace = "\\\\"; break;
657         default:   continue;
658         }
659         if ((p != last && !HLPFILE_RtfAddRawString(rd, last, p - last)) ||
660             !HLPFILE_RtfAddRawString(rd, replace, rlen)) return FALSE;
661         last = p + 1;
662     }
663     return HLPFILE_RtfAddRawString(rd, last, p - last);
664 }
665
666 /******************************************************************
667  *              RtfAddHexBytes
668  *
669  */
670 static BOOL HLPFILE_RtfAddHexBytes(struct RtfData* rd, const void* _ptr, unsigned sz)
671 {
672     char        tmp[512];
673     unsigned    i, step;
674     const BYTE* ptr = _ptr;
675     static const char* _2hex = "0123456789abcdef";
676
677     if (!rd->in_text)
678     {
679         if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
680         rd->in_text = TRUE;
681     }
682     for (; sz; sz -= step)
683     {
684         step = min(256, sz);
685         for (i = 0; i < step; i++)
686         {
687             tmp[2 * i + 0] = _2hex[*ptr >> 4];
688             tmp[2 * i + 1] = _2hex[*ptr++ & 0xF];
689         }
690         if (!HLPFILE_RtfAddRawString(rd, tmp, 2 * step)) return FALSE;
691     }
692     return TRUE;
693 }
694
695 /******************************************************************
696  *             HLPFILE_RtfAddTransparentBitmap
697  *
698  * We'll transform a transparent bitmap into an metafile that
699  * we then transform into RTF
700  */
701 static BOOL HLPFILE_RtfAddTransparentBitmap(struct RtfData* rd, const BITMAPINFO* bi,
702                                             const void* pict, unsigned nc)
703 {
704     HDC                 hdc, hdcMask, hdcMem, hdcEMF;
705     HBITMAP             hbm, hbmMask, hbmOldMask, hbmOldMem;
706     HENHMETAFILE        hEMF;
707     BOOL                ret = FALSE;
708     void*               data;
709     UINT                sz;
710
711     hbm = CreateDIBitmap(hdc = GetDC(0), &bi->bmiHeader,
712                          CBM_INIT, pict, bi, DIB_RGB_COLORS);
713
714     hdcMem = CreateCompatibleDC(hdc);
715     hbmOldMem = SelectObject(hdcMem, hbm);
716
717     /* create the mask bitmap from the main bitmap */
718     hdcMask = CreateCompatibleDC(hdc);
719     hbmMask = CreateBitmap(bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, 1, 1, NULL);
720     hbmOldMask = SelectObject(hdcMask, hbmMask);
721     SetBkColor(hdcMem,
722                RGB(bi->bmiColors[nc - 1].rgbRed,
723                    bi->bmiColors[nc - 1].rgbGreen,
724                    bi->bmiColors[nc - 1].rgbBlue));
725     BitBlt(hdcMask, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCCOPY);
726
727     /* sets to RGB(0,0,0) the transparent bits in main bitmap */
728     SetBkColor(hdcMem, RGB(0,0,0));
729     SetTextColor(hdcMem, RGB(255,255,255));
730     BitBlt(hdcMem, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMask, 0, 0, SRCAND);
731
732     SelectObject(hdcMask, hbmOldMask);
733     DeleteDC(hdcMask);
734
735     SelectObject(hdcMem, hbmOldMem);
736     DeleteDC(hdcMem);
737
738     /* we create the bitmap on the fly */
739     hdcEMF = CreateEnhMetaFile(NULL, NULL, NULL, NULL);
740     hdcMem = CreateCompatibleDC(hdcEMF);
741
742     /* sets to RGB(0,0,0) the transparent bits in final bitmap */
743     hbmOldMem = SelectObject(hdcMem, hbmMask);
744     SetBkColor(hdcEMF, RGB(255, 255, 255));
745     SetTextColor(hdcEMF, RGB(0, 0, 0));
746     BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCAND);
747
748     /* and copy the remaining bits of main bitmap */
749     SelectObject(hdcMem, hbm);
750     BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCPAINT);
751     SelectObject(hdcMem, hbmOldMem);
752     DeleteDC(hdcMem);
753
754     /* do the cleanup */
755     ReleaseDC(0, hdc);
756     DeleteObject(hbmMask);
757     DeleteObject(hbm);
758
759     hEMF = CloseEnhMetaFile(hdcEMF);
760
761     /* generate rtf stream */
762     sz = GetEnhMetaFileBits(hEMF, 0, NULL);
763     if (sz && (data = HeapAlloc(GetProcessHeap(), 0, sz)))
764     {
765         if (sz == GetEnhMetaFileBits(hEMF, sz, data))
766         {
767             ret = HLPFILE_RtfAddControl(rd, "{\\pict\\emfblip") &&
768                 HLPFILE_RtfAddHexBytes(rd, data, sz) &&
769                 HLPFILE_RtfAddControl(rd, "}");
770         }
771         HeapFree(GetProcessHeap(), 0, data);
772     }
773     DeleteEnhMetaFile(hEMF);
774
775     return ret;
776 }
777
778 /******************************************************************
779  *              HLPFILE_RtfAddBitmap
780  *
781  */
782 static BOOL HLPFILE_RtfAddBitmap(struct RtfData* rd, const BYTE* beg, BYTE type, BYTE pack)
783 {
784     const BYTE*         ptr;
785     const BYTE*         pict_beg;
786     BYTE*               alloc = NULL;
787     BITMAPINFO*         bi;
788     ULONG               off, csz;
789     unsigned            nc = 0;
790     BOOL                clrImportant = FALSE;
791     BOOL                ret = FALSE;
792     char                tmp[256];
793
794     bi = HeapAlloc(GetProcessHeap(), 0, sizeof(*bi));
795     if (!bi) return FALSE;
796
797     ptr = beg + 2; /* for type and pack */
798
799     bi->bmiHeader.biSize          = sizeof(bi->bmiHeader);
800     bi->bmiHeader.biXPelsPerMeter = fetch_ulong(&ptr);
801     bi->bmiHeader.biYPelsPerMeter = fetch_ulong(&ptr);
802     bi->bmiHeader.biPlanes        = fetch_ushort(&ptr);
803     bi->bmiHeader.biBitCount      = fetch_ushort(&ptr);
804     bi->bmiHeader.biWidth         = fetch_ulong(&ptr);
805     bi->bmiHeader.biHeight        = fetch_ulong(&ptr);
806     bi->bmiHeader.biClrUsed       = fetch_ulong(&ptr);
807     clrImportant  = fetch_ulong(&ptr);
808     bi->bmiHeader.biClrImportant  = (clrImportant > 1) ? clrImportant : 0;
809     bi->bmiHeader.biCompression   = BI_RGB;
810     if (bi->bmiHeader.biBitCount > 32) WINE_FIXME("Unknown bit count %u\n", bi->bmiHeader.biBitCount);
811     if (bi->bmiHeader.biPlanes != 1) WINE_FIXME("Unsupported planes %u\n", bi->bmiHeader.biPlanes);
812     bi->bmiHeader.biSizeImage = (((bi->bmiHeader.biWidth * bi->bmiHeader.biBitCount + 31) & ~31) / 8) * bi->bmiHeader.biHeight;
813     WINE_TRACE("planes=%d bc=%d size=(%d,%d)\n",
814                bi->bmiHeader.biPlanes, bi->bmiHeader.biBitCount,
815                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
816
817     csz = fetch_ulong(&ptr);
818     fetch_ulong(&ptr); /* hotspot size */
819
820     off = GET_UINT(ptr, 0);     ptr += 4;
821     /* GET_UINT(ptr, 0); hotspot offset */ ptr += 4;
822
823     /* now read palette info */
824     if (type == 0x06)
825     {
826         unsigned i;
827
828         nc = bi->bmiHeader.biClrUsed;
829         /* not quite right, especially for bitfields type of compression */
830         if (!nc && bi->bmiHeader.biBitCount <= 8)
831             nc = 1 << bi->bmiHeader.biBitCount;
832
833         bi = HeapReAlloc(GetProcessHeap(), 0, bi, sizeof(*bi) + nc * sizeof(RGBQUAD));
834         if (!bi) return FALSE;
835         for (i = 0; i < nc; i++)
836         {
837             bi->bmiColors[i].rgbBlue     = ptr[0];
838             bi->bmiColors[i].rgbGreen    = ptr[1];
839             bi->bmiColors[i].rgbRed      = ptr[2];
840             bi->bmiColors[i].rgbReserved = 0;
841             ptr += 4;
842         }
843     }
844     pict_beg = HLPFILE_DecompressGfx(beg + off, csz, bi->bmiHeader.biSizeImage, pack, &alloc);
845
846     if (clrImportant == 1 && nc > 0)
847     {
848         ret = HLPFILE_RtfAddTransparentBitmap(rd, bi, pict_beg, nc);
849         goto done;
850     }
851     if (!HLPFILE_RtfAddControl(rd, "{\\pict")) goto done;
852     if (type == 0x06)
853     {
854         sprintf(tmp, "\\dibitmap0\\picw%d\\pich%d",
855                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
856         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
857         if (!HLPFILE_RtfAddHexBytes(rd, bi, sizeof(*bi) + nc * sizeof(RGBQUAD))) goto done;
858     }
859     else
860     {
861         sprintf(tmp, "\\wbitmap0\\wbmbitspixel%d\\wbmplanes%d\\picw%d\\pich%d",
862                 bi->bmiHeader.biBitCount, bi->bmiHeader.biPlanes,
863                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
864         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
865     }
866     if (!HLPFILE_RtfAddHexBytes(rd, pict_beg, bi->bmiHeader.biSizeImage)) goto done;
867     if (!HLPFILE_RtfAddControl(rd, "}")) goto done;
868
869     ret = TRUE;
870 done:
871     HeapFree(GetProcessHeap(), 0, bi);
872     HeapFree(GetProcessHeap(), 0, alloc);
873
874     return ret;
875 }
876
877 /******************************************************************
878  *              HLPFILE_RtfAddMetaFile
879  *
880  */
881 static BOOL     HLPFILE_RtfAddMetaFile(struct RtfData* rd, const BYTE* beg, BYTE pack)
882 {
883     ULONG size, csize, off, hsoff;
884     const BYTE*         ptr;
885     const BYTE*         bits;
886     BYTE*               alloc = NULL;
887     char                tmp[256];
888     unsigned            mm;
889     BOOL                ret;
890
891     WINE_TRACE("Loading metafile\n");
892
893     ptr = beg + 2; /* for type and pack */
894
895     mm = fetch_ushort(&ptr); /* mapping mode */
896     sprintf(tmp, "{\\pict\\wmetafile%d\\picw%d\\pich%d",
897             mm, GET_USHORT(ptr, 0), GET_USHORT(ptr, 2));
898     if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
899     ptr += 4;
900
901     size = fetch_ulong(&ptr); /* decompressed size */
902     csize = fetch_ulong(&ptr); /* compressed size */
903     fetch_ulong(&ptr); /* hotspot size */
904     off = GET_UINT(ptr, 0);
905     hsoff = GET_UINT(ptr, 4);
906     ptr += 8;
907
908     WINE_TRACE("sz=%u csz=%u offs=%u/%u,%u\n",
909                size, csize, off, (ULONG)(ptr - beg), hsoff);
910
911     bits = HLPFILE_DecompressGfx(beg + off, csize, size, pack, &alloc);
912     if (!bits) return FALSE;
913
914     ret = HLPFILE_RtfAddHexBytes(rd, bits, size) &&
915         HLPFILE_RtfAddControl(rd, "}");
916
917     HeapFree(GetProcessHeap(), 0, alloc);
918
919     return ret;
920 }
921
922 /******************************************************************
923  *              HLPFILE_RtfAddGfxByAddr
924  *
925  */
926 static  BOOL    HLPFILE_RtfAddGfxByAddr(struct RtfData* rd, HLPFILE *hlpfile,
927                                         const BYTE* ref, ULONG size)
928 {
929     unsigned    i, numpict;
930
931     numpict = GET_USHORT(ref, 2);
932     WINE_TRACE("Got picture magic=%04x #=%d\n", GET_USHORT(ref, 0), numpict);
933
934     for (i = 0; i < numpict; i++)
935     {
936         const BYTE*     beg;
937         const BYTE*     ptr;
938         BYTE            type, pack;
939
940         WINE_TRACE("Offset[%d] = %x\n", i, GET_UINT(ref, (1 + i) * 4));
941         beg = ptr = ref + GET_UINT(ref, (1 + i) * 4);
942
943         type = *ptr++;
944         pack = *ptr++;
945
946         switch (type)
947         {
948         case 5: /* device dependent bmp */
949         case 6: /* device independent bmp */
950             HLPFILE_RtfAddBitmap(rd, beg, type, pack);
951             break;
952         case 8:
953             HLPFILE_RtfAddMetaFile(rd, beg, pack);
954             break;
955         default: WINE_FIXME("Unknown type %u\n", type); return FALSE;
956         }
957
958         /* FIXME: hotspots */
959
960         /* FIXME: implement support for multiple picture format */
961         if (numpict != 1) WINE_FIXME("Supporting only one bitmap format per logical bitmap (for now). Using first format\n");
962         break;
963     }
964     return TRUE;
965 }
966
967 /******************************************************************
968  *              HLPFILE_RtfAddGfxByIndex
969  *
970  *
971  */
972 static  BOOL    HLPFILE_RtfAddGfxByIndex(struct RtfData* rd, HLPFILE *hlpfile,
973                                          unsigned index)
974 {
975     char        tmp[16];
976     BYTE        *ref, *end;
977
978     WINE_TRACE("Loading picture #%d\n", index);
979
980     sprintf(tmp, "|bm%u", index);
981
982     if (!HLPFILE_FindSubFile(hlpfile, tmp, &ref, &end)) {WINE_WARN("no sub file\n"); return FALSE;}
983
984     ref += 9;
985     return HLPFILE_RtfAddGfxByAddr(rd, hlpfile, ref, end - ref);
986 }
987
988 /******************************************************************
989  *              HLPFILE_AllocLink
990  *
991  *
992  */
993 static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
994                                              const char* str, unsigned len, LONG hash,
995                                              unsigned clrChange, unsigned wnd)
996 {
997     HLPFILE_LINK*  link;
998     char*          link_str;
999
1000     /* FIXME: should build a string table for the attributes.link.lpszPath
1001      * they are reallocated for each link
1002      */
1003     if (len == -1) len = strlen(str);
1004     link = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_LINK) + len + 1);
1005     if (!link) return NULL;
1006
1007     link->cookie     = cookie;
1008     link->string     = link_str = (char*)(link + 1);
1009     memcpy(link_str, str, len);
1010     link_str[len] = '\0';
1011     link->hash       = hash;
1012     link->bClrChange = clrChange ? 1 : 0;
1013     link->window     = wnd;
1014     link->next       = rd->first_link;
1015     rd->first_link   = link;
1016     link->cpMin      = rd->char_pos;
1017     link->cpMax      = 0;
1018     rd->force_color  = clrChange;
1019     if (rd->current_link) WINE_FIXME("Pending link\n");
1020     rd->current_link = link;
1021
1022     WINE_TRACE("Link[%d] to %s@%08x:%d\n",
1023                link->cookie, link->string, link->hash, link->window);
1024     return link;
1025 }
1026
1027 unsigned HLPFILE_HalfPointsToTwips(unsigned pts)
1028 {
1029     static unsigned logPxY;
1030     if (!logPxY)
1031     {
1032         HDC hdc = GetDC(NULL);
1033         logPxY = GetDeviceCaps(hdc, LOGPIXELSY);
1034         ReleaseDC(NULL, hdc);
1035     }
1036     return MulDiv(pts, 72 * 10, logPxY);
1037 }
1038
1039 /***********************************************************************
1040  *
1041  *           HLPFILE_BrowseParagraph
1042  */
1043 static BOOL HLPFILE_BrowseParagraph(HLPFILE_PAGE* page, struct RtfData* rd,
1044                                     BYTE *buf, BYTE* end, unsigned* parlen)
1045 {
1046     UINT               textsize;
1047     const BYTE        *format, *format_end;
1048     char              *text, *text_base, *text_end;
1049     LONG               size, blocksize, datalen;
1050     unsigned short     bits;
1051     unsigned           nc, ncol = 1;
1052     short              table_width;
1053     BOOL               in_table = FALSE;
1054     char               tmp[256];
1055     BOOL               ret = FALSE;
1056
1057     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
1058
1059     *parlen = 0;
1060     blocksize = GET_UINT(buf, 0);
1061     size = GET_UINT(buf, 0x4);
1062     datalen = GET_UINT(buf, 0x10);
1063     text = text_base = HeapAlloc(GetProcessHeap(), 0, size);
1064     if (!text) return FALSE;
1065     if (size > blocksize - datalen)
1066     {
1067         /* need to decompress */
1068         if (page->file->hasPhrases)
1069             HLPFILE_Uncompress2(page->file, buf + datalen, end, (BYTE*)text, (BYTE*)text + size);
1070         else if (page->file->hasPhrases40)
1071             HLPFILE_Uncompress3(page->file, text, text + size, buf + datalen, end);
1072         else
1073         {
1074             WINE_FIXME("Text size is too long, splitting\n");
1075             size = blocksize - datalen;
1076             memcpy(text, buf + datalen, size);
1077         }
1078     }
1079     else
1080         memcpy(text, buf + datalen, size);
1081
1082     text_end = text + size;
1083
1084     format = buf + 0x15;
1085     format_end = buf + GET_UINT(buf, 0x10);
1086
1087     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
1088     {
1089         fetch_long(&format);
1090         *parlen = fetch_ushort(&format);
1091     }
1092
1093     if (buf[0x14] == 0x23)
1094     {
1095         char    type;
1096
1097         in_table = TRUE;
1098         ncol = *format++;
1099
1100         if (!HLPFILE_RtfAddControl(rd, "\\trowd")) goto done;
1101         type = *format++;
1102         if (type == 0 || type == 2)
1103         {
1104             table_width = GET_SHORT(format, 0);
1105             format += 2;
1106         }
1107         else
1108             table_width = 32767;
1109         WINE_TRACE("New table: cols=%d type=%x width=%d\n",
1110                    ncol, type, table_width);
1111         if (ncol > 1)
1112         {
1113             int     pos;
1114             sprintf(tmp, "\\trgaph%d\\trleft%d",
1115                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6), table_width, 32767)),
1116                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)));
1117             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1118             pos = HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6) / 2, table_width, 32767));
1119             for (nc = 0; nc < ncol; nc++)
1120             {
1121                 WINE_TRACE("column(%d/%d) gap=%d width=%d\n",
1122                            nc, ncol, GET_SHORT(format, nc*4),
1123                            GET_SHORT(format, nc*4+2));
1124                 pos += GET_SHORT(format, nc * 4) + GET_SHORT(format, nc * 4 + 2);
1125                 sprintf(tmp, "\\cellx%d",
1126                         HLPFILE_HalfPointsToTwips(MulDiv(pos, table_width, 32767)));
1127                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1128             }
1129         }
1130         else
1131         {
1132             WINE_TRACE("column(0/%d) gap=%d width=%d\n",
1133                        ncol, GET_SHORT(format, 0), GET_SHORT(format, 2));
1134             sprintf(tmp, "\\trleft%d\\cellx%d ",
1135                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)),
1136                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0) + GET_SHORT(format, 2),
1137                                       table_width, 32767)));
1138             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1139         }
1140         format += ncol * 4;
1141     }
1142
1143     for (nc = 0; nc < ncol; /**/)
1144     {
1145         WINE_TRACE("looking for format at offset %lu in column %d\n", (SIZE_T)(format - (buf + 0x15)), nc);
1146         if (!HLPFILE_RtfAddControl(rd, "\\pard")) goto done;
1147         if (in_table)
1148         {
1149             nc = GET_SHORT(format, 0);
1150             if (nc == -1) break;
1151             format += 5;
1152             if (!HLPFILE_RtfAddControl(rd, "\\intbl")) goto done;
1153         }
1154         else nc++;
1155         if (buf[0x14] == 0x01)
1156             format += 6;
1157         else
1158             format += 4;
1159         bits = GET_USHORT(format, 0); format += 2;
1160         if (bits & 0x0001) fetch_long(&format);
1161         if (bits & 0x0002)
1162         {
1163             sprintf(tmp, "\\sb%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1164             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1165         }
1166         if (bits & 0x0004)
1167         {
1168             sprintf(tmp, "\\sa%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1169             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1170         }
1171         if (bits & 0x0008)
1172         {
1173             sprintf(tmp, "\\sl%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1174             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1175         }
1176         if (bits & 0x0010)
1177         {
1178             sprintf(tmp, "\\li%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1179             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1180         }
1181         if (bits & 0x0020)
1182         {
1183             sprintf(tmp, "\\ri%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1184             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1185         }
1186         if (bits & 0x0040)
1187         {
1188             sprintf(tmp, "\\fi%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1189             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1190         }
1191         if (bits & 0x0100)
1192         {
1193             BYTE        brdr = *format++;
1194             short       w;
1195
1196             if (brdr & 0x01 && !HLPFILE_RtfAddControl(rd, "\\box")) goto done;
1197             if (brdr & 0x02 && !HLPFILE_RtfAddControl(rd, "\\brdrt")) goto done;
1198             if (brdr & 0x04 && !HLPFILE_RtfAddControl(rd, "\\brdrl")) goto done;
1199             if (brdr & 0x08 && !HLPFILE_RtfAddControl(rd, "\\brdrb")) goto done;
1200             if (brdr & 0x10 && !HLPFILE_RtfAddControl(rd, "\\brdrr")) goto done;
1201             if (brdr & 0x20 && !HLPFILE_RtfAddControl(rd, "\\brdrth")) goto done;
1202             if (!(brdr & 0x20) && !HLPFILE_RtfAddControl(rd, "\\brdrs")) goto done;
1203             if (brdr & 0x40 && !HLPFILE_RtfAddControl(rd, "\\brdrdb")) goto done;
1204             /* 0x80: unknown */
1205
1206             w = GET_SHORT(format, 0); format += 2;
1207             if (w)
1208             {
1209                 sprintf(tmp, "\\brdrw%d", HLPFILE_HalfPointsToTwips(w));
1210                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1211             }
1212         }
1213         if (bits & 0x0200)
1214         {
1215             int                 i, ntab = fetch_short(&format);
1216             unsigned            tab, ts;
1217             const char*         kind;
1218
1219             for (i = 0; i < ntab; i++)
1220             {
1221                 tab = fetch_ushort(&format);
1222                 ts = (tab & 0x4000) ? fetch_ushort(&format) : 0 /* left */;
1223                 switch (ts)
1224                 {
1225                 default: WINE_FIXME("Unknown tab style %x\n", ts);
1226                 /* fall through */
1227                 case 0: kind = ""; break;
1228                 case 1: kind = "\\tqr"; break;
1229                 case 2: kind = "\\tqc"; break;
1230                 }
1231                 /* FIXME: do kind */
1232                 sprintf(tmp, "%s\\tx%d",
1233                         kind, HLPFILE_HalfPointsToTwips(tab & 0x3FFF));
1234                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1235             }
1236         }
1237         switch (bits & 0xc00)
1238         {
1239         default: WINE_FIXME("Unsupported alignment 0xC00\n"); break;
1240         case 0: if (!HLPFILE_RtfAddControl(rd, "\\ql")) goto done; break;
1241         case 0x400: if (!HLPFILE_RtfAddControl(rd, "\\qr")) goto done; break;
1242         case 0x800: if (!HLPFILE_RtfAddControl(rd, "\\qc")) goto done; break;
1243         }
1244
1245         /* 0x1000 doesn't need space */
1246         if ((bits & 0x1000) && !HLPFILE_RtfAddControl(rd, "\\keep")) goto done;
1247         if ((bits & 0xE080) != 0) 
1248             WINE_FIXME("Unsupported bits %04x, potential trouble ahead\n", bits);
1249
1250         while (text < text_end && format < format_end)
1251         {
1252             WINE_TRACE("Got text: %s (%p/%p - %p/%p)\n", wine_dbgstr_a(text), text, text_end, format, format_end);
1253             textsize = strlen(text);
1254             if (textsize)
1255             {
1256                 if (rd->force_color)
1257                 {
1258                     if ((rd->current_link->cookie == hlp_link_popup) ?
1259                         !HLPFILE_RtfAddControl(rd, "{\\uld\\cf1") :
1260                         !HLPFILE_RtfAddControl(rd, "{\\ul\\cf1")) goto done;
1261                 }
1262                 if (!HLPFILE_RtfAddText(rd, text)) goto done;
1263                 if (rd->force_color && !HLPFILE_RtfAddControl(rd, "}")) goto done;
1264                 rd->char_pos += textsize;
1265             }
1266             /* else: null text, keep on storing attributes */
1267             text += textsize + 1;
1268
1269             if (*format == 0xff)
1270             {
1271                 format++;
1272                 break;
1273             }
1274
1275             WINE_TRACE("format=%02x\n", *format);
1276             switch (*format)
1277             {
1278             case 0x20:
1279                 WINE_FIXME("NIY20\n");
1280                 format += 5;
1281                 break;
1282
1283             case 0x21:
1284                 WINE_FIXME("NIY21\n");
1285                 format += 3;
1286                 break;
1287
1288             case 0x80:
1289                 {
1290                     unsigned    font = GET_USHORT(format, 1);
1291                     unsigned    fs;
1292
1293                     WINE_TRACE("Changing font to %d\n", font);
1294                     format += 3;
1295                     /* Font size in hlpfile is given in the same units as
1296                        rtf control word \fs uses (half-points). */
1297                     switch (rd->font_scale)
1298                     {
1299                     case 0: fs = page->file->fonts[font].LogFont.lfHeight - 4; break;
1300                     default:
1301                     case 1: fs = page->file->fonts[font].LogFont.lfHeight; break;
1302                     case 2: fs = page->file->fonts[font].LogFont.lfHeight + 4; break;
1303                     }
1304                     /* FIXME: missing at least colors, also bold attribute looses information */
1305
1306                     sprintf(tmp, "\\f%d\\cf%d\\fs%d%s%s%s%s",
1307                             font, font + 2, fs,
1308                             page->file->fonts[font].LogFont.lfWeight > 400 ? "\\b" : "\\b0",
1309                             page->file->fonts[font].LogFont.lfItalic ? "\\i" : "\\i0",
1310                             page->file->fonts[font].LogFont.lfUnderline ? "\\ul" : "\\ul0",
1311                             page->file->fonts[font].LogFont.lfStrikeOut ? "\\strike" : "\\strike0");
1312                     if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1313                 }
1314                break;
1315
1316             case 0x81:
1317                 if (!HLPFILE_RtfAddControl(rd, "\\line")) goto done;
1318                 format += 1;
1319                 rd->char_pos++;
1320                 break;
1321
1322             case 0x82:
1323                 if (in_table)
1324                 {
1325                     if (format[1] != 0xFF)
1326                     {
1327                         if (!HLPFILE_RtfAddControl(rd, "\\par\\intbl")) goto done;
1328                     }
1329                     else
1330                     {
1331                         if (!HLPFILE_RtfAddControl(rd, "\\cell\\pard\\intbl")) goto done;
1332                     }
1333                 }
1334                 else if (!HLPFILE_RtfAddControl(rd, "\\par")) goto done;
1335                 format += 1;
1336                 rd->char_pos++;
1337                 break;
1338
1339             case 0x83:
1340                 if (!HLPFILE_RtfAddControl(rd, "\\tab")) goto done;
1341                 format += 1;
1342                 rd->char_pos++;
1343                 break;
1344
1345 #if 0
1346             case 0x84:
1347                 format += 3;
1348                 break;
1349 #endif
1350
1351             case 0x86:
1352             case 0x87:
1353             case 0x88:
1354                 {
1355                     BYTE    type = format[1];
1356                     LONG    size;
1357
1358                     /* FIXME: we don't use 'BYTE    pos = (*format - 0x86);' for the image position */
1359                     format += 2;
1360                     size = fetch_long(&format);
1361
1362                     switch (type)
1363                     {
1364                     case 0x22:
1365                         fetch_ushort(&format); /* hot spot */
1366                         /* fall thru */
1367                     case 0x03:
1368                         switch (GET_SHORT(format, 0))
1369                         {
1370                         case 0:
1371                             HLPFILE_RtfAddGfxByIndex(rd, page->file, GET_SHORT(format, 2));
1372                             rd->char_pos++;
1373                             break;
1374                         case 1:
1375                             WINE_FIXME("does it work ??? %x<%u>#%u\n",
1376                                        GET_SHORT(format, 0),
1377                                        size, GET_SHORT(format, 2));
1378                             HLPFILE_RtfAddGfxByAddr(rd, page->file, format + 2, size - 4);
1379                             rd->char_pos++;
1380                            break;
1381                         default:
1382                             WINE_FIXME("??? %u\n", GET_SHORT(format, 0));
1383                             break;
1384                         }
1385                         break;
1386                     case 0x05:
1387                         WINE_FIXME("Got an embedded element %s\n", format + 6);
1388                         break;
1389                     default:
1390                         WINE_FIXME("Got a type %d picture\n", type);
1391                         break;
1392                     }
1393                     format += size;
1394                 }
1395                 break;
1396
1397             case 0x89:
1398                 format += 1;
1399                 if (!rd->current_link)
1400                     WINE_FIXME("No existing link\n");
1401                 rd->current_link->cpMax = rd->char_pos;
1402                 rd->current_link = NULL;
1403                 rd->force_color = FALSE;
1404                 break;
1405
1406             case 0x8B:
1407                 if (!HLPFILE_RtfAddControl(rd, "\\~")) goto done;
1408                 format += 1;
1409                 rd->char_pos++;
1410                 break;
1411
1412             case 0x8C:
1413                 if (!HLPFILE_RtfAddControl(rd, "\\_")) goto done;
1414                 /* FIXME: it could be that hypen is also in input stream !! */
1415                 format += 1;
1416                 rd->char_pos++;
1417                 break;
1418
1419 #if 0
1420             case 0xA9:
1421                 format += 2;
1422                 break;
1423 #endif
1424
1425             case 0xC8:
1426             case 0xCC:
1427                 WINE_TRACE("macro => %s\n", format + 3);
1428                 HLPFILE_AllocLink(rd, hlp_link_macro, (const char*)format + 3,
1429                                   GET_USHORT(format, 1), 0, !(*format & 4), -1);
1430                 format += 3 + GET_USHORT(format, 1);
1431                 break;
1432
1433             case 0xE0:
1434             case 0xE1:
1435                 WINE_WARN("jump topic 1 => %u\n", GET_UINT(format, 1));
1436                 HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1437                                   page->file->lpszPath, -1, GET_UINT(format, 1), 1, -1);
1438
1439
1440                 format += 5;
1441                 break;
1442
1443             case 0xE2:
1444             case 0xE3:
1445             case 0xE6:
1446             case 0xE7:
1447                 HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1448                                   page->file->lpszPath, -1, GET_UINT(format, 1),
1449                                   !(*format & 4), -1);
1450                 format += 5;
1451                 break;
1452
1453             case 0xEA:
1454             case 0xEB:
1455             case 0xEE:
1456             case 0xEF:
1457                 {
1458                     char*       ptr = (char*) format + 8;
1459                     BYTE        type = format[3];
1460                     int         wnd = -1;
1461
1462                     switch (type)
1463                     {
1464                     case 1:
1465                         wnd = *ptr;
1466                         /* fall through */
1467                     case 0:
1468                         ptr = page->file->lpszPath;
1469                         break;
1470                     case 6:
1471                         for (wnd = page->file->numWindows - 1; wnd >= 0; wnd--)
1472                         {
1473                             if (!strcmp(ptr, page->file->windows[wnd].name)) break;
1474                         }
1475                         if (wnd == -1)
1476                             WINE_WARN("Couldn't find window info for %s\n", ptr);
1477                         ptr += strlen(ptr) + 1;
1478                         /* fall through */
1479                     case 4:
1480                         break;
1481                     default:
1482                         WINE_WARN("Unknown link type %d\n", type);
1483                         break;
1484                     }
1485                     HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1486                                       ptr, -1, GET_UINT(format, 4), !(*format & 4), wnd);
1487                 }
1488                 format += 3 + GET_USHORT(format, 1);
1489                 break;
1490
1491             default:
1492                 WINE_WARN("format %02x\n", *format);
1493                 format++;
1494             }
1495         }
1496     }
1497     if (in_table)
1498     {
1499         if (!HLPFILE_RtfAddControl(rd, "\\row\\par\\pard\\plain")) goto done;
1500         rd->char_pos += 2;
1501     }
1502     ret = TRUE;
1503 done:
1504
1505     HeapFree(GetProcessHeap(), 0, text_base);
1506     return ret;
1507 }
1508
1509 /******************************************************************
1510  *              HLPFILE_BrowsePage
1511  *
1512  */
1513 BOOL    HLPFILE_BrowsePage(HLPFILE_PAGE* page, struct RtfData* rd,
1514                            unsigned font_scale, unsigned relative)
1515 {
1516     HLPFILE     *hlpfile = page->file;
1517     BYTE        *buf, *end;
1518     DWORD       ref = page->reference;
1519     unsigned    index, old_index = -1, offset, count = 0, offs = 0;
1520     unsigned    cpg, parlen;
1521     char        tmp[1024];
1522     const char* ck = NULL;
1523
1524     rd->in_text = TRUE;
1525     rd->data = rd->ptr = HeapAlloc(GetProcessHeap(), 0, rd->allocated = 32768);
1526     rd->char_pos = 0;
1527     rd->first_link = rd->current_link = NULL;
1528     rd->force_color = FALSE;
1529     rd->font_scale = font_scale;
1530     rd->relative = relative;
1531     rd->char_pos_rel = 0;
1532
1533     switch (hlpfile->charset)
1534     {
1535     case DEFAULT_CHARSET:
1536     case ANSI_CHARSET:          cpg = 1252; break;
1537     case SHIFTJIS_CHARSET:      cpg = 932; break;
1538     case HANGEUL_CHARSET:       cpg = 949; break;
1539     case GB2312_CHARSET:        cpg = 936; break;
1540     case CHINESEBIG5_CHARSET:   cpg = 950; break;
1541     case GREEK_CHARSET:         cpg = 1253; break;
1542     case TURKISH_CHARSET:       cpg = 1254; break;
1543     case HEBREW_CHARSET:        cpg = 1255; break;
1544     case ARABIC_CHARSET:        cpg = 1256; break;
1545     case BALTIC_CHARSET:        cpg = 1257; break;
1546     case VIETNAMESE_CHARSET:    cpg = 1258; break;
1547     case RUSSIAN_CHARSET:       cpg = 1251; break;
1548     case EE_CHARSET:            cpg = 1250; break;
1549     case THAI_CHARSET:          cpg = 874; break;
1550     case JOHAB_CHARSET:         cpg = 1361; break;
1551     case MAC_CHARSET:           ck = "mac"; break;
1552     default:
1553         WINE_FIXME("Unsupported charset %u\n", hlpfile->charset);
1554         cpg = 1252;
1555     }
1556     if (ck)
1557     {
1558         sprintf(tmp, "{\\rtf1\\%s\\deff0", ck);
1559         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1560     }
1561     else
1562     {
1563         sprintf(tmp, "{\\rtf1\\ansi\\ansicpg%d\\deff0", cpg);
1564         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1565     }
1566
1567     /* generate font table */
1568     if (!HLPFILE_RtfAddControl(rd, "{\\fonttbl")) return FALSE;
1569     for (index = 0; index < hlpfile->numFonts; index++)
1570     {
1571         const char* family;
1572         switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
1573         {
1574         case FF_MODERN:     family = "modern";  break;
1575         case FF_ROMAN:      family = "roman";   break;
1576         case FF_SWISS:      family = "swiss";   break;
1577         case FF_SCRIPT:     family = "script";  break;
1578         case FF_DECORATIVE: family = "decor";   break;
1579         default:            family = "nil";     break;
1580         }
1581         sprintf(tmp, "{\\f%d\\f%s\\fprq%d\\fcharset%d %s;}",
1582                 index, family,
1583                 hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0x0F,
1584                 hlpfile->fonts[index].LogFont.lfCharSet,
1585                 hlpfile->fonts[index].LogFont.lfFaceName);
1586         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1587     }
1588     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1589     /* generate color table */
1590     if (!HLPFILE_RtfAddControl(rd, "{\\colortbl ;\\red0\\green128\\blue0;")) return FALSE;
1591     for (index = 0; index < hlpfile->numFonts; index++)
1592     {
1593         const char* family;
1594         switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
1595         {
1596         case FF_MODERN:     family = "modern";  break;
1597         case FF_ROMAN:      family = "roman";   break;
1598         case FF_SWISS:      family = "swiss";   break;
1599         case FF_SCRIPT:     family = "script";  break;
1600         case FF_DECORATIVE: family = "decor";   break;
1601         default:            family = "nil";     break;
1602         }
1603         sprintf(tmp, "\\red%d\\green%d\\blue%d;",
1604                 GetRValue(hlpfile->fonts[index].color),
1605                 GetGValue(hlpfile->fonts[index].color),
1606                 GetBValue(hlpfile->fonts[index].color));
1607         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1608     }
1609     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1610
1611     do
1612     {
1613         if (hlpfile->version <= 16)
1614         {
1615             index  = (ref - 0x0C) / hlpfile->dsize;
1616             offset = (ref - 0x0C) % hlpfile->dsize;
1617         }
1618         else
1619         {
1620             index  = (ref - 0x0C) >> 14;
1621             offset = (ref - 0x0C) & 0x3FFF;
1622         }
1623
1624         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
1625         {
1626             /* we jumped to the next block, adjust pointers */
1627             ref -= 12;
1628             offset -= 12;
1629         }
1630
1631         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
1632         buf = hlpfile->topic_map[index] + offset;
1633         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
1634         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
1635         if (index != old_index) {offs = 0; old_index = index;}
1636
1637         switch (buf[0x14])
1638         {
1639         case 0x02:
1640             if (count++) goto done;
1641             break;
1642         case 0x01:
1643         case 0x20:
1644         case 0x23:
1645             if (!HLPFILE_BrowseParagraph(page, rd, buf, end, &parlen)) return FALSE;
1646             if (relative > index * 0x8000 + offs)
1647                 rd->char_pos_rel = rd->char_pos;
1648             offs += parlen;
1649             break;
1650         default:
1651             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
1652         }
1653         if (hlpfile->version <= 16)
1654         {
1655             ref += GET_UINT(buf, 0xc);
1656             if (GET_UINT(buf, 0xc) == 0)
1657                 break;
1658         }
1659         else
1660             ref = GET_UINT(buf, 0xc);
1661     } while (ref != 0xffffffff);
1662 done:
1663     page->first_link = rd->first_link;
1664     return HLPFILE_RtfAddControl(rd, "}");
1665 }
1666
1667 /******************************************************************
1668  *              HLPFILE_ReadFont
1669  *
1670  *
1671  */
1672 static BOOL HLPFILE_ReadFont(HLPFILE* hlpfile)
1673 {
1674     BYTE        *ref, *end;
1675     unsigned    i, len, idx;
1676     unsigned    face_num, dscr_num, face_offset, dscr_offset;
1677     BYTE        flag, family;
1678
1679     if (!HLPFILE_FindSubFile(hlpfile, "|FONT", &ref, &end))
1680     {
1681         WINE_WARN("no subfile FONT\n");
1682         hlpfile->numFonts = 0;
1683         hlpfile->fonts = NULL;
1684         return FALSE;
1685     }
1686
1687     ref += 9;
1688
1689     face_num    = GET_USHORT(ref, 0);
1690     dscr_num    = GET_USHORT(ref, 2);
1691     face_offset = GET_USHORT(ref, 4);
1692     dscr_offset = GET_USHORT(ref, 6);
1693
1694     WINE_TRACE("Got NumFacenames=%u@%u NumDesc=%u@%u\n",
1695                face_num, face_offset, dscr_num, dscr_offset);
1696
1697     hlpfile->numFonts = dscr_num;
1698     hlpfile->fonts = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_FONT) * dscr_num);
1699
1700     len = (dscr_offset - face_offset) / face_num;
1701 /* EPP     for (i = face_offset; i < dscr_offset; i += len) */
1702 /* EPP         WINE_FIXME("[%d]: %*s\n", i / len, len, ref + i); */
1703     for (i = 0; i < dscr_num; i++)
1704     {
1705         flag = ref[dscr_offset + i * 11 + 0];
1706         family = ref[dscr_offset + i * 11 + 2];
1707
1708         hlpfile->fonts[i].LogFont.lfHeight = ref[dscr_offset + i * 11 + 1];
1709         hlpfile->fonts[i].LogFont.lfWidth = 0;
1710         hlpfile->fonts[i].LogFont.lfEscapement = 0;
1711         hlpfile->fonts[i].LogFont.lfOrientation = 0;
1712         hlpfile->fonts[i].LogFont.lfWeight = (flag & 1) ? 700 : 400;
1713         hlpfile->fonts[i].LogFont.lfItalic = (flag & 2) ? TRUE : FALSE;
1714         hlpfile->fonts[i].LogFont.lfUnderline = (flag & 4) ? TRUE : FALSE;
1715         hlpfile->fonts[i].LogFont.lfStrikeOut = (flag & 8) ? TRUE : FALSE;
1716         hlpfile->fonts[i].LogFont.lfCharSet = hlpfile->charset;
1717         hlpfile->fonts[i].LogFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1718         hlpfile->fonts[i].LogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1719         hlpfile->fonts[i].LogFont.lfQuality = DEFAULT_QUALITY;
1720         hlpfile->fonts[i].LogFont.lfPitchAndFamily = DEFAULT_PITCH;
1721
1722         switch (family)
1723         {
1724         case 0x01: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_MODERN;     break;
1725         case 0x02: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_ROMAN;      break;
1726         case 0x03: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SWISS;      break;
1727         case 0x04: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SCRIPT;     break;
1728         case 0x05: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_DECORATIVE; break;
1729         default: WINE_FIXME("Unknown family %u\n", family);
1730         }
1731         idx = GET_USHORT(ref, dscr_offset + i * 11 + 3);
1732
1733         if (idx < face_num)
1734         {
1735             memcpy(hlpfile->fonts[i].LogFont.lfFaceName, ref + face_offset + idx * len, min(len, LF_FACESIZE - 1));
1736             hlpfile->fonts[i].LogFont.lfFaceName[min(len, LF_FACESIZE - 1)] = '\0';
1737         }
1738         else
1739         {
1740             WINE_FIXME("Too high face ref (%u/%u)\n", idx, face_num);
1741             strcpy(hlpfile->fonts[i].LogFont.lfFaceName, "Helv");
1742         }
1743         hlpfile->fonts[i].hFont = 0;
1744         hlpfile->fonts[i].color = RGB(ref[dscr_offset + i * 11 + 5],
1745                                       ref[dscr_offset + i * 11 + 6],
1746                                       ref[dscr_offset + i * 11 + 7]);
1747 #define X(b,s) ((flag & (1 << b)) ? "-"s: "")
1748         WINE_TRACE("Font[%d]: flags=%02x%s%s%s%s%s%s pSize=%u family=%u face=%s[%u] color=%08x\n",
1749                    i, flag,
1750                    X(0, "bold"),
1751                    X(1, "italic"),
1752                    X(2, "underline"),
1753                    X(3, "strikeOut"),
1754                    X(4, "dblUnderline"),
1755                    X(5, "smallCaps"),
1756                    ref[dscr_offset + i * 11 + 1],
1757                    family,
1758                    hlpfile->fonts[i].LogFont.lfFaceName, idx,
1759                    GET_UINT(ref, dscr_offset + i * 11 + 5) & 0x00FFFFFF);
1760     }
1761     return TRUE;
1762 }
1763
1764 /***********************************************************************
1765  *
1766  *           HLPFILE_ReadFileToBuffer
1767  */
1768 static BOOL HLPFILE_ReadFileToBuffer(HLPFILE* hlpfile, HFILE hFile)
1769 {
1770     BYTE  header[16], dummy[1];
1771
1772     if (_hread(hFile, header, 16) != 16) {WINE_WARN("header\n"); return FALSE;};
1773
1774     /* sanity checks */
1775     if (GET_UINT(header, 0) != 0x00035F3F)
1776     {WINE_WARN("wrong header\n"); return FALSE;};
1777
1778     hlpfile->file_buffer_size = GET_UINT(header, 12);
1779     hlpfile->file_buffer = HeapAlloc(GetProcessHeap(), 0, hlpfile->file_buffer_size + 1);
1780     if (!hlpfile->file_buffer) return FALSE;
1781
1782     memcpy(hlpfile->file_buffer, header, 16);
1783     if (_hread(hFile, hlpfile->file_buffer + 16, hlpfile->file_buffer_size - 16) !=hlpfile->file_buffer_size - 16)
1784     {WINE_WARN("filesize1\n"); return FALSE;};
1785
1786     if (_hread(hFile, dummy, 1) != 0) WINE_WARN("filesize2\n");
1787
1788     hlpfile->file_buffer[hlpfile->file_buffer_size] = '\0'; /* FIXME: was '0', sounds backwards to me */
1789
1790     return TRUE;
1791 }
1792
1793 /**************************************************************************
1794  * comp_FindSubFile
1795  *
1796  * HLPFILE_BPTreeCompare function for HLPFILE directory.
1797  *
1798  */
1799 static int comp_FindSubFile(void *p, const void *key,
1800                             int leaf, void** next)
1801 {
1802     *next = (char *)p+strlen(p)+(leaf?5:3);
1803     WINE_TRACE("Comparing '%s' with '%s'\n", (char *)p, (char *)key);
1804     return strcmp(p, key);
1805 }
1806
1807 /***********************************************************************
1808  *
1809  *           HLPFILE_FindSubFile
1810  */
1811 static BOOL HLPFILE_FindSubFile(HLPFILE* hlpfile, LPCSTR name, BYTE **subbuf, BYTE **subend)
1812 {
1813     BYTE *ptr;
1814
1815     WINE_TRACE("looking for file '%s'\n", name);
1816     ptr = HLPFILE_BPTreeSearch(hlpfile->file_buffer + GET_UINT(hlpfile->file_buffer, 4),
1817                                name, comp_FindSubFile);
1818     if (!ptr) return FALSE;
1819     *subbuf = hlpfile->file_buffer + GET_UINT(ptr, strlen(name)+1);
1820     if (*subbuf >= hlpfile->file_buffer + hlpfile->file_buffer_size)
1821     {
1822         WINE_ERR("internal file %s does not fit\n", name);
1823         return FALSE;
1824     }
1825     *subend = *subbuf + GET_UINT(*subbuf, 0);
1826     if (*subend > hlpfile->file_buffer + hlpfile->file_buffer_size)
1827     {
1828         WINE_ERR("internal file %s does not fit\n", name);
1829         return FALSE;
1830     }
1831     if (GET_UINT(*subbuf, 0) < GET_UINT(*subbuf, 4) + 9)
1832     {
1833         WINE_ERR("invalid size provided for internal file %s\n", name);
1834         return FALSE;
1835     }
1836     return TRUE;
1837 }
1838
1839 /***********************************************************************
1840  *
1841  *           HLPFILE_SystemCommands
1842  */
1843 static BOOL HLPFILE_SystemCommands(HLPFILE* hlpfile)
1844 {
1845     BYTE *buf, *ptr, *end;
1846     HLPFILE_MACRO *macro, **m;
1847     LPSTR p;
1848     unsigned short magic, minor, major, flags;
1849
1850     hlpfile->lpszTitle = NULL;
1851
1852     if (!HLPFILE_FindSubFile(hlpfile, "|SYSTEM", &buf, &end)) return FALSE;
1853
1854     magic = GET_USHORT(buf + 9, 0);
1855     minor = GET_USHORT(buf + 9, 2);
1856     major = GET_USHORT(buf + 9, 4);
1857     /* gen date on 4 bytes */
1858     flags = GET_USHORT(buf + 9, 10);
1859     WINE_TRACE("Got system header: magic=%04x version=%d.%d flags=%04x\n",
1860                magic, major, minor, flags);
1861     if (magic != 0x036C || major != 1)
1862     {WINE_WARN("Wrong system header\n"); return FALSE;}
1863     if (minor <= 16)
1864     {
1865         hlpfile->tbsize = 0x800;
1866         hlpfile->compressed = 0;
1867     }
1868     else if (flags == 0)
1869     {
1870         hlpfile->tbsize = 0x1000;
1871         hlpfile->compressed = 0;
1872     }
1873     else if (flags == 4)
1874     {
1875         hlpfile->tbsize = 0x1000;
1876         hlpfile->compressed = 1;
1877     }
1878     else
1879     {
1880         hlpfile->tbsize = 0x800;
1881         hlpfile->compressed = 1;
1882     }
1883
1884     if (hlpfile->compressed)
1885         hlpfile->dsize = 0x4000;
1886     else
1887         hlpfile->dsize = hlpfile->tbsize - 0x0C;
1888
1889     hlpfile->version = minor;
1890     hlpfile->flags = flags;
1891     hlpfile->charset = DEFAULT_CHARSET;
1892
1893     if (hlpfile->version <= 16)
1894     {
1895         char *str = (char*)buf + 0x15;
1896
1897         hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
1898         if (!hlpfile->lpszTitle) return FALSE;
1899         lstrcpy(hlpfile->lpszTitle, str);
1900         WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
1901         /* Nothing more to parse */
1902         return TRUE;
1903     }
1904     for (ptr = buf + 0x15; ptr + 4 <= end; ptr += GET_USHORT(ptr, 2) + 4)
1905     {
1906         char *str = (char*) ptr + 4;
1907         switch (GET_USHORT(ptr, 0))
1908         {
1909         case 1:
1910             if (hlpfile->lpszTitle) {WINE_WARN("title\n"); break;}
1911             hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
1912             if (!hlpfile->lpszTitle) return FALSE;
1913             lstrcpy(hlpfile->lpszTitle, str);
1914             WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
1915             break;
1916
1917         case 2:
1918             if (hlpfile->lpszCopyright) {WINE_WARN("copyright\n"); break;}
1919             hlpfile->lpszCopyright = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
1920             if (!hlpfile->lpszCopyright) return FALSE;
1921             lstrcpy(hlpfile->lpszCopyright, str);
1922             WINE_TRACE("Copyright: %s\n", hlpfile->lpszCopyright);
1923             break;
1924
1925         case 3:
1926             if (GET_USHORT(ptr, 2) != 4) {WINE_WARN("system3\n");break;}
1927             hlpfile->contents_start = GET_UINT(ptr, 4);
1928             WINE_TRACE("Setting contents start at %08lx\n", hlpfile->contents_start);
1929             break;
1930
1931         case 4:
1932             macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + lstrlen(str) + 1);
1933             if (!macro) break;
1934             p = (char*)macro + sizeof(HLPFILE_MACRO);
1935             lstrcpy(p, str);
1936             macro->lpszMacro = p;
1937             macro->next = 0;
1938             for (m = &hlpfile->first_macro; *m; m = &(*m)->next);
1939             *m = macro;
1940             break;
1941
1942         case 5:
1943             if (GET_USHORT(ptr, 4 + 4) != 1)
1944                 WINE_FIXME("More than one icon, picking up first\n");
1945             /* 0x16 is sizeof(CURSORICONDIR), see user32/user_private.h */
1946             hlpfile->hIcon = CreateIconFromResourceEx(ptr + 4 + 0x16,
1947                                                       GET_USHORT(ptr, 2) - 0x16, TRUE,
1948                                                       0x30000, 0, 0, 0);
1949             break;
1950
1951         case 6:
1952             if (GET_USHORT(ptr, 2) != 90) {WINE_WARN("system6\n");break;}
1953
1954             if (hlpfile->windows) 
1955                 hlpfile->windows = HeapReAlloc(GetProcessHeap(), 0, hlpfile->windows, 
1956                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
1957             else 
1958                 hlpfile->windows = HeapAlloc(GetProcessHeap(), 0, 
1959                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
1960             
1961             if (hlpfile->windows)
1962             {
1963                 unsigned flags = GET_USHORT(ptr, 4);
1964                 HLPFILE_WINDOWINFO* wi = &hlpfile->windows[hlpfile->numWindows - 1];
1965
1966                 if (flags & 0x0001) strcpy(wi->type, &str[2]);
1967                 else wi->type[0] = '\0';
1968                 if (flags & 0x0002) strcpy(wi->name, &str[12]);
1969                 else wi->name[0] = '\0';
1970                 if (flags & 0x0004) strcpy(wi->caption, &str[21]);
1971                 else lstrcpynA(wi->caption, hlpfile->lpszTitle, sizeof(wi->caption));
1972                 wi->origin.x = (flags & 0x0008) ? GET_USHORT(ptr, 76) : CW_USEDEFAULT;
1973                 wi->origin.y = (flags & 0x0010) ? GET_USHORT(ptr, 78) : CW_USEDEFAULT;
1974                 wi->size.cx = (flags & 0x0020) ? GET_USHORT(ptr, 80) : CW_USEDEFAULT;
1975                 wi->size.cy = (flags & 0x0040) ? GET_USHORT(ptr, 82) : CW_USEDEFAULT;
1976                 wi->style = (flags & 0x0080) ? GET_USHORT(ptr, 84) : SW_SHOW;
1977                 wi->win_style = WS_OVERLAPPEDWINDOW;
1978                 wi->sr_color = (flags & 0x0100) ? GET_UINT(ptr, 86) : 0xFFFFFF;
1979                 wi->nsr_color = (flags & 0x0200) ? GET_UINT(ptr, 90) : 0xFFFFFF;
1980                 WINE_TRACE("System-Window: flags=%c%c%c%c%c%c%c%c type=%s name=%s caption=%s (%d,%d)x(%d,%d)\n",
1981                            flags & 0x0001 ? 'T' : 't',
1982                            flags & 0x0002 ? 'N' : 'n',
1983                            flags & 0x0004 ? 'C' : 'c',
1984                            flags & 0x0008 ? 'X' : 'x',
1985                            flags & 0x0010 ? 'Y' : 'y',
1986                            flags & 0x0020 ? 'W' : 'w',
1987                            flags & 0x0040 ? 'H' : 'h',
1988                            flags & 0x0080 ? 'S' : 's',
1989                            wi->type, wi->name, wi->caption, wi->origin.x, wi->origin.y,
1990                            wi->size.cx, wi->size.cy);
1991             }
1992             break;
1993         case 8:
1994             WINE_WARN("Citation: '%s'\n", ptr + 4);
1995             break;
1996         case 11:
1997             hlpfile->charset = ptr[4];
1998             WINE_TRACE("Charset: %d\n", hlpfile->charset);
1999             break;
2000         default:
2001             WINE_WARN("Unsupported SystemRecord[%d]\n", GET_USHORT(ptr, 0));
2002         }
2003     }
2004     if (!hlpfile->lpszTitle)
2005         hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1);
2006     return TRUE;
2007 }
2008
2009 /***********************************************************************
2010  *
2011  *           HLPFILE_UncompressedLZ77_Size
2012  */
2013 static INT HLPFILE_UncompressedLZ77_Size(const BYTE *ptr, const BYTE *end)
2014 {
2015     int  i, newsize = 0;
2016
2017     while (ptr < end)
2018     {
2019         int mask = *ptr++;
2020         for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
2021         {
2022             if (mask & 1)
2023             {
2024                 int code = GET_USHORT(ptr, 0);
2025                 int len  = 3 + (code >> 12);
2026                 newsize += len;
2027                 ptr     += 2;
2028             }
2029             else newsize++, ptr++;
2030         }
2031     }
2032
2033     return newsize;
2034 }
2035
2036 /***********************************************************************
2037  *
2038  *           HLPFILE_UncompressLZ77
2039  */
2040 static BYTE *HLPFILE_UncompressLZ77(const BYTE *ptr, const BYTE *end, BYTE *newptr)
2041 {
2042     int i;
2043
2044     while (ptr < end)
2045     {
2046         int mask = *ptr++;
2047         for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
2048         {
2049             if (mask & 1)
2050             {
2051                 int code   = GET_USHORT(ptr, 0);
2052                 int len    = 3 + (code >> 12);
2053                 int offset = code & 0xfff;
2054                 /*
2055                  * We must copy byte-by-byte here. We cannot use memcpy nor
2056                  * memmove here. Just example:
2057                  * a[]={1,2,3,4,5,6,7,8,9,10}
2058                  * newptr=a+2;
2059                  * offset=1;
2060                  * We expect:
2061                  * {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 11, 12}
2062                  */
2063                 for (; len>0; len--, newptr++) *newptr = *(newptr-offset-1);
2064                 ptr    += 2;
2065             }
2066             else *newptr++ = *ptr++;
2067         }
2068     }
2069
2070     return newptr;
2071 }
2072
2073 /***********************************************************************
2074  *
2075  *           HLPFILE_UncompressLZ77_Phrases
2076  */
2077 static BOOL HLPFILE_UncompressLZ77_Phrases(HLPFILE* hlpfile)
2078 {
2079     UINT i, num, dec_size, head_size;
2080     BYTE *buf, *end;
2081
2082     if (!HLPFILE_FindSubFile(hlpfile, "|Phrases", &buf, &end)) return FALSE;
2083
2084     if (hlpfile->version <= 16)
2085         head_size = 13;
2086     else
2087         head_size = 17;
2088
2089     num = hlpfile->num_phrases = GET_USHORT(buf, 9);
2090     if (buf + 2 * num + 0x13 >= end) {WINE_WARN("1a\n"); return FALSE;};
2091
2092     if (hlpfile->version <= 16)
2093         dec_size = end - buf - 15 - 2 * num;
2094     else
2095         dec_size = HLPFILE_UncompressedLZ77_Size(buf + 0x13 + 2 * num, end);
2096
2097     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2098     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2099     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2100     {
2101         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2102         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2103         return FALSE;
2104     }
2105
2106     for (i = 0; i <= num; i++)
2107         hlpfile->phrases_offsets[i] = GET_USHORT(buf, head_size + 2 * i) - 2 * num - 2;
2108
2109     if (hlpfile->version <= 16)
2110         memcpy(hlpfile->phrases_buffer, buf + 15 + 2*num, dec_size);
2111     else
2112         HLPFILE_UncompressLZ77(buf + 0x13 + 2 * num, end, (BYTE*)hlpfile->phrases_buffer);
2113
2114     hlpfile->hasPhrases = TRUE;
2115     return TRUE;
2116 }
2117
2118 /***********************************************************************
2119  *
2120  *           HLPFILE_Uncompress_Phrases40
2121  */
2122 static BOOL HLPFILE_Uncompress_Phrases40(HLPFILE* hlpfile)
2123 {
2124     UINT num;
2125     INT dec_size, cpr_size;
2126     BYTE *buf_idx, *end_idx;
2127     BYTE *buf_phs, *end_phs;
2128     LONG* ptr, mask = 0;
2129     unsigned int i;
2130     unsigned short bc, n;
2131
2132     if (!HLPFILE_FindSubFile(hlpfile, "|PhrIndex", &buf_idx, &end_idx) ||
2133         !HLPFILE_FindSubFile(hlpfile, "|PhrImage", &buf_phs, &end_phs)) return FALSE;
2134
2135     ptr = (LONG*)(buf_idx + 9 + 28);
2136     bc = GET_USHORT(buf_idx, 9 + 24) & 0x0F;
2137     num = hlpfile->num_phrases = GET_USHORT(buf_idx, 9 + 4);
2138
2139     WINE_TRACE("Index: Magic=%08x #entries=%u CpsdSize=%u PhrImgSize=%u\n"
2140                "\tPhrImgCprsdSize=%u 0=%u bc=%x ukn=%x\n",
2141                GET_UINT(buf_idx, 9 + 0),
2142                GET_UINT(buf_idx, 9 + 4),
2143                GET_UINT(buf_idx, 9 + 8),
2144                GET_UINT(buf_idx, 9 + 12),
2145                GET_UINT(buf_idx, 9 + 16),
2146                GET_UINT(buf_idx, 9 + 20),
2147                GET_USHORT(buf_idx, 9 + 24),
2148                GET_USHORT(buf_idx, 9 + 26));
2149
2150     dec_size = GET_UINT(buf_idx, 9 + 12);
2151     cpr_size = GET_UINT(buf_idx, 9 + 16);
2152
2153     if (dec_size != cpr_size &&
2154         dec_size != HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs))
2155     {
2156         WINE_WARN("size mismatch %u %u\n",
2157                   dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2158         dec_size = max(dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2159     }
2160
2161     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2162     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2163     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2164     {
2165         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2166         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2167         return FALSE;
2168     }
2169
2170 #define getbit() (ptr += (mask < 0), mask = mask*2 + (mask<=0), (*ptr & mask) != 0)
2171
2172     hlpfile->phrases_offsets[0] = 0;
2173     for (i = 0; i < num; i++)
2174     {
2175         for (n = 1; getbit(); n += 1 << bc);
2176         if (getbit()) n++;
2177         if (bc > 1 && getbit()) n += 2;
2178         if (bc > 2 && getbit()) n += 4;
2179         if (bc > 3 && getbit()) n += 8;
2180         if (bc > 4 && getbit()) n += 16;
2181         hlpfile->phrases_offsets[i + 1] = hlpfile->phrases_offsets[i] + n;
2182     }
2183 #undef getbit
2184
2185     if (dec_size == cpr_size)
2186         memcpy(hlpfile->phrases_buffer, buf_phs + 9, dec_size);
2187     else
2188         HLPFILE_UncompressLZ77(buf_phs + 9, end_phs, (BYTE*)hlpfile->phrases_buffer);
2189
2190     hlpfile->hasPhrases40 = TRUE;
2191     return TRUE;
2192 }
2193
2194 /***********************************************************************
2195  *
2196  *           HLPFILE_Uncompress_Topic
2197  */
2198 static BOOL HLPFILE_Uncompress_Topic(HLPFILE* hlpfile)
2199 {
2200     BYTE *buf, *ptr, *end, *newptr;
2201     unsigned int i, newsize = 0;
2202     unsigned int topic_size;
2203
2204     if (!HLPFILE_FindSubFile(hlpfile, "|TOPIC", &buf, &end))
2205     {WINE_WARN("topic0\n"); return FALSE;}
2206
2207     buf += 9; /* Skip file header */
2208     topic_size = end - buf;
2209     if (hlpfile->compressed)
2210     {
2211         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2212
2213         for (i = 0; i < hlpfile->topic_maplen; i++)
2214         {
2215             ptr = buf + i * hlpfile->tbsize;
2216
2217             /* I don't know why, it's necessary for printman.hlp */
2218             if (ptr + 0x44 > end) ptr = end - 0x44;
2219
2220             newsize += HLPFILE_UncompressedLZ77_Size(ptr + 0xc, min(end, ptr + hlpfile->tbsize));
2221         }
2222
2223         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2224                                        hlpfile->topic_maplen * sizeof(hlpfile->topic_map[0]) + newsize);
2225         if (!hlpfile->topic_map) return FALSE;
2226         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2227         hlpfile->topic_end = newptr + newsize;
2228
2229         for (i = 0; i < hlpfile->topic_maplen; i++)
2230         {
2231             ptr = buf + i * hlpfile->tbsize;
2232             if (ptr + 0x44 > end) ptr = end - 0x44;
2233
2234             hlpfile->topic_map[i] = newptr;
2235             newptr = HLPFILE_UncompressLZ77(ptr + 0xc, min(end, ptr + hlpfile->tbsize), newptr);
2236         }
2237     }
2238     else
2239     {
2240         /* basically, we need to copy the TopicBlockSize byte pages
2241          * (removing the first 0x0C) in one single area in memory
2242          */
2243         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2244         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2245                                        hlpfile->topic_maplen * (sizeof(hlpfile->topic_map[0]) + hlpfile->dsize));
2246         if (!hlpfile->topic_map) return FALSE;
2247         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2248         hlpfile->topic_end = newptr + topic_size;
2249
2250         for (i = 0; i < hlpfile->topic_maplen; i++)
2251         {
2252             hlpfile->topic_map[i] = newptr + i * hlpfile->dsize;
2253             memcpy(hlpfile->topic_map[i], buf + i * hlpfile->tbsize + 0x0C, hlpfile->dsize);
2254         }
2255     }
2256     return TRUE;
2257 }
2258
2259 /***********************************************************************
2260  *
2261  *           HLPFILE_Uncompress2
2262  */
2263
2264 static void HLPFILE_Uncompress2(HLPFILE* hlpfile, const BYTE *ptr, const BYTE *end, BYTE *newptr, const BYTE *newend)
2265 {
2266     BYTE *phptr, *phend;
2267     UINT code;
2268     UINT index;
2269
2270     while (ptr < end && newptr < newend)
2271     {
2272         if (!*ptr || *ptr >= 0x10)
2273             *newptr++ = *ptr++;
2274         else
2275         {
2276             code  = 0x100 * ptr[0] + ptr[1];
2277             index = (code - 0x100) / 2;
2278
2279             phptr = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index];
2280             phend = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index + 1];
2281
2282             if (newptr + (phend - phptr) > newend)
2283             {
2284                 WINE_FIXME("buffer overflow %p > %p for %lu bytes\n",
2285                            newptr, newend, (SIZE_T)(phend - phptr));
2286                 return;
2287             }
2288             memcpy(newptr, phptr, phend - phptr);
2289             newptr += phend - phptr;
2290             if (code & 1) *newptr++ = ' ';
2291
2292             ptr += 2;
2293         }
2294     }
2295     if (newptr > newend) WINE_FIXME("buffer overflow %p > %p\n", newptr, newend);
2296 }
2297
2298 /******************************************************************
2299  *              HLPFILE_Uncompress3
2300  *
2301  *
2302  */
2303 static BOOL HLPFILE_Uncompress3(HLPFILE* hlpfile, char* dst, const char* dst_end,
2304                                 const BYTE* src, const BYTE* src_end)
2305 {
2306     unsigned int idx, len;
2307
2308     for (; src < src_end; src++)
2309     {
2310         if ((*src & 1) == 0)
2311         {
2312             idx = *src / 2;
2313             if (idx > hlpfile->num_phrases)
2314             {
2315                 WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
2316                 len = 0;
2317             }
2318             else 
2319             {
2320                 len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
2321                 if (dst + len <= dst_end)
2322                     memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
2323             }
2324         }
2325         else if ((*src & 0x03) == 0x01)
2326         {
2327             idx = (*src + 1) * 64;
2328             idx += *++src;
2329             if (idx > hlpfile->num_phrases)
2330             {
2331                 WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
2332                 len = 0;
2333             }
2334             else
2335             {
2336                 len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
2337                 if (dst + len <= dst_end)
2338                     memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
2339             }
2340         }
2341         else if ((*src & 0x07) == 0x03)
2342         {
2343             len = (*src / 8) + 1;
2344             if (dst + len <= dst_end)
2345                 memcpy(dst, src + 1, len);
2346             src += len;
2347         }
2348         else
2349         {
2350             len = (*src / 16) + 1;
2351             if (dst + len <= dst_end)
2352                 memset(dst, ((*src & 0x0F) == 0x07) ? ' ' : 0, len);
2353         }
2354         dst += len;
2355     }
2356
2357     if (dst > dst_end) WINE_ERR("buffer overflow (%p > %p)\n", dst, dst_end);
2358     return TRUE;
2359 }
2360
2361 /******************************************************************
2362  *              HLPFILE_UncompressRLE
2363  *
2364  *
2365  */
2366 static void HLPFILE_UncompressRLE(const BYTE* src, const BYTE* end, BYTE* dst, unsigned dstsz)
2367 {
2368     BYTE        ch;
2369     BYTE*       sdst = dst + dstsz;
2370
2371     while (src < end)
2372     {
2373         ch = *src++;
2374         if (ch & 0x80)
2375         {
2376             ch &= 0x7F;
2377             if (dst + ch <= sdst)
2378                 memcpy(dst, src, ch);
2379             src += ch;
2380         }
2381         else
2382         {
2383             if (dst + ch <= sdst)
2384                 memset(dst, (char)*src, ch);
2385             src++;
2386         }
2387         dst += ch;
2388     }
2389     if (dst != sdst)
2390         WINE_WARN("Buffer X-flow: d(%lu) instead of d(%u)\n",
2391                   (SIZE_T)(dst - (sdst - dstsz)), dstsz);
2392 }
2393
2394 /**************************************************************************
2395  * HLPFILE_BPTreeSearch
2396  *
2397  * Searches for an element in B+ tree
2398  *
2399  * PARAMS
2400  *     buf        [I] pointer to the embedded file structured as a B+ tree
2401  *     key        [I] pointer to data to find
2402  *     comp       [I] compare function
2403  *
2404  * RETURNS
2405  *     Pointer to block identified by key, or NULL if failure.
2406  *
2407  */
2408 void* HLPFILE_BPTreeSearch(BYTE* buf, const void* key,
2409                            HLPFILE_BPTreeCompare comp)
2410 {
2411     unsigned magic;
2412     unsigned page_size;
2413     unsigned cur_page;
2414     unsigned level;
2415     BYTE *pages, *ptr, *newptr;
2416     int i, entries;
2417     int ret;
2418
2419     magic = GET_USHORT(buf, 9);
2420     if (magic != 0x293B)
2421     {
2422         WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
2423         return NULL;
2424     }
2425     page_size = GET_USHORT(buf, 9+4);
2426     cur_page  = GET_USHORT(buf, 9+26);
2427     level     = GET_USHORT(buf, 9+32);
2428     pages     = buf + 9 + 38;
2429     while (--level > 0)
2430     {
2431         ptr = pages + cur_page*page_size;
2432         entries = GET_SHORT(ptr, 2);
2433         ptr += 6;
2434         for (i = 0; i < entries; i++)
2435         {
2436             if (comp(ptr, key, 0, (void **)&newptr) > 0) break;
2437             ptr = newptr;
2438         }
2439         cur_page = GET_USHORT(ptr-2, 0);
2440     }
2441     ptr = pages + cur_page*page_size;
2442     entries = GET_SHORT(ptr, 2);
2443     ptr += 8;
2444     for (i = 0; i < entries; i++)
2445     {
2446         ret = comp(ptr, key, 1, (void **)&newptr);
2447         if (ret == 0) return ptr;
2448         if (ret > 0) return NULL;
2449         ptr = newptr;
2450     }
2451     return NULL;
2452 }
2453
2454 /**************************************************************************
2455  * HLPFILE_BPTreeEnum
2456  *
2457  * Enumerates elements in B+ tree.
2458  *
2459  * PARAMS
2460  *     buf        [I]  pointer to the embedded file structured as a B+ tree
2461  *     cb         [I]  compare function
2462  *     cookie     [IO] cookie for cb function
2463  */
2464 void HLPFILE_BPTreeEnum(BYTE* buf, HLPFILE_BPTreeCallback cb, void* cookie)
2465 {
2466     unsigned magic;
2467     unsigned page_size;
2468     unsigned cur_page;
2469     unsigned level;
2470     BYTE *pages, *ptr, *newptr;
2471     int i, entries;
2472
2473     magic = GET_USHORT(buf, 9);
2474     if (magic != 0x293B)
2475     {
2476         WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
2477         return;
2478     }
2479     page_size = GET_USHORT(buf, 9+4);
2480     cur_page  = GET_USHORT(buf, 9+26);
2481     level     = GET_USHORT(buf, 9+32);
2482     pages     = buf + 9 + 38;
2483     while (--level > 0)
2484     {
2485         ptr = pages + cur_page*page_size;
2486         cur_page = GET_USHORT(ptr, 4);
2487     }
2488     while (cur_page != 0xFFFF)
2489     {
2490         ptr = pages + cur_page*page_size;
2491         entries = GET_SHORT(ptr, 2);
2492         ptr += 8;
2493         for (i = 0; i < entries; i++)
2494         {
2495             cb(ptr, (void **)&newptr, cookie);
2496             ptr = newptr;
2497         }
2498         cur_page = GET_USHORT(pages+cur_page*page_size, 6);
2499     }
2500 }
2501
2502
2503 /***********************************************************************
2504  *
2505  *           HLPFILE_GetContext
2506  */
2507 static BOOL HLPFILE_GetContext(HLPFILE *hlpfile)
2508 {
2509     BYTE                *cbuf, *cend;
2510     unsigned            clen;
2511
2512     if (!HLPFILE_FindSubFile(hlpfile, "|CONTEXT",  &cbuf, &cend))
2513     {WINE_WARN("context0\n"); return FALSE;}
2514
2515     clen = cend - cbuf;
2516     hlpfile->Context = HeapAlloc(GetProcessHeap(), 0, clen);
2517     if (!hlpfile->Context) return FALSE;
2518     memcpy(hlpfile->Context, cbuf, clen);
2519
2520     return TRUE;
2521 }
2522
2523 /***********************************************************************
2524  *
2525  *           HLPFILE_GetKeywords
2526  */
2527 static BOOL HLPFILE_GetKeywords(HLPFILE *hlpfile)
2528 {
2529     BYTE                *cbuf, *cend;
2530     unsigned            clen;
2531
2532     if (!HLPFILE_FindSubFile(hlpfile, "|KWBTREE", &cbuf, &cend)) return FALSE;
2533     clen = cend - cbuf;
2534     hlpfile->kwbtree = HeapAlloc(GetProcessHeap(), 0, clen);
2535     if (!hlpfile->kwbtree) return FALSE;
2536     memcpy(hlpfile->kwbtree, cbuf, clen);
2537
2538     if (!HLPFILE_FindSubFile(hlpfile, "|KWDATA", &cbuf, &cend))
2539     {
2540         WINE_ERR("corrupted help file: kwbtree present but kwdata absent\n");
2541         HeapFree(GetProcessHeap(), 0, hlpfile->kwbtree);
2542         return FALSE;
2543     }
2544     clen = cend - cbuf;
2545     hlpfile->kwdata = HeapAlloc(GetProcessHeap(), 0, clen);
2546     if (!hlpfile->kwdata)
2547     {
2548         HeapFree(GetProcessHeap(), 0, hlpfile->kwdata);
2549         return FALSE;
2550     }
2551     memcpy(hlpfile->kwdata, cbuf, clen);
2552
2553     return TRUE;
2554 }
2555
2556 /***********************************************************************
2557  *
2558  *           HLPFILE_GetMap
2559  */
2560 static BOOL HLPFILE_GetMap(HLPFILE *hlpfile)
2561 {
2562     BYTE                *cbuf, *cend;
2563     unsigned            entries, i;
2564
2565     if (!HLPFILE_FindSubFile(hlpfile, "|CTXOMAP",  &cbuf, &cend))
2566     {WINE_WARN("no map section\n"); return FALSE;}
2567
2568     entries = GET_USHORT(cbuf, 9);
2569     hlpfile->Map = HeapAlloc(GetProcessHeap(), 0, entries * sizeof(HLPFILE_MAP));
2570     if (!hlpfile->Map) return FALSE;
2571     hlpfile->wMapLen = entries;
2572     for (i = 0; i < entries; i++)
2573     {
2574         hlpfile->Map[i].lMap = GET_UINT(cbuf+11,i*8);
2575         hlpfile->Map[i].offset = GET_UINT(cbuf+11,i*8+4);
2576     }
2577     return TRUE;
2578 }
2579
2580 /***********************************************************************
2581  *
2582  *           HLPFILE_GetTOMap
2583  */
2584 static BOOL HLPFILE_GetTOMap(HLPFILE *hlpfile)
2585 {
2586     BYTE                *cbuf, *cend;
2587     unsigned            clen;
2588
2589     if (!HLPFILE_FindSubFile(hlpfile, "|TOMAP",  &cbuf, &cend))
2590     {WINE_WARN("no tomap section\n"); return FALSE;}
2591
2592     clen = cend - cbuf - 9;
2593     hlpfile->TOMap = HeapAlloc(GetProcessHeap(), 0, clen);
2594     if (!hlpfile->TOMap) return FALSE;
2595     memcpy(hlpfile->TOMap, cbuf+9, clen);
2596     hlpfile->wTOMapLen = clen/4;
2597     return TRUE;
2598 }
2599
2600 /***********************************************************************
2601  *
2602  *           DeleteMacro
2603  */
2604 static void HLPFILE_DeleteMacro(HLPFILE_MACRO* macro)
2605 {
2606     HLPFILE_MACRO*      next;
2607
2608     while (macro)
2609     {
2610         next = macro->next;
2611         HeapFree(GetProcessHeap(), 0, macro);
2612         macro = next;
2613     }
2614 }
2615
2616 /***********************************************************************
2617  *
2618  *           DeletePage
2619  */
2620 static void HLPFILE_DeletePage(HLPFILE_PAGE* page)
2621 {
2622     HLPFILE_PAGE* next;
2623
2624     while (page)
2625     {
2626         next = page->next;
2627         HLPFILE_DeleteMacro(page->first_macro);
2628         HeapFree(GetProcessHeap(), 0, page);
2629         page = next;
2630     }
2631 }
2632
2633 /***********************************************************************
2634  *
2635  *           HLPFILE_FreeHlpFile
2636  */
2637 void HLPFILE_FreeHlpFile(HLPFILE* hlpfile)
2638 {
2639     unsigned i;
2640
2641     if (!hlpfile || --hlpfile->wRefCount > 0) return;
2642
2643     if (hlpfile->next) hlpfile->next->prev = hlpfile->prev;
2644     if (hlpfile->prev) hlpfile->prev->next = hlpfile->next;
2645     else first_hlpfile = hlpfile->next;
2646
2647     if (hlpfile->numFonts)
2648     {
2649         for (i = 0; i < hlpfile->numFonts; i++)
2650         {
2651             DeleteObject(hlpfile->fonts[i].hFont);
2652         }
2653         HeapFree(GetProcessHeap(), 0, hlpfile->fonts);
2654     }
2655
2656     if (hlpfile->numBmps)
2657     {
2658         for (i = 0; i < hlpfile->numBmps; i++)
2659         {
2660             DeleteObject(hlpfile->bmps[i]);
2661         }
2662         HeapFree(GetProcessHeap(), 0, hlpfile->bmps);
2663     }
2664
2665     HLPFILE_DeletePage(hlpfile->first_page);
2666     HLPFILE_DeleteMacro(hlpfile->first_macro);
2667
2668     DestroyIcon(hlpfile->hIcon);
2669     if (hlpfile->numWindows)    HeapFree(GetProcessHeap(), 0, hlpfile->windows);
2670     HeapFree(GetProcessHeap(), 0, hlpfile->Context);
2671     HeapFree(GetProcessHeap(), 0, hlpfile->Map);
2672     HeapFree(GetProcessHeap(), 0, hlpfile->lpszTitle);
2673     HeapFree(GetProcessHeap(), 0, hlpfile->lpszCopyright);
2674     HeapFree(GetProcessHeap(), 0, hlpfile->file_buffer);
2675     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2676     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2677     HeapFree(GetProcessHeap(), 0, hlpfile->topic_map);
2678     HeapFree(GetProcessHeap(), 0, hlpfile->help_on_file);
2679     HeapFree(GetProcessHeap(), 0, hlpfile);
2680 }