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