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