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