dnsapi: Remove a dead assignment (clang).
[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, (const 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 static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
765                                              const char* str, unsigned len, LONG hash,
766                                              unsigned clrChange, unsigned bHotSpot, unsigned wnd);
767
768 /******************************************************************
769  *              HLPFILE_AddHotSpotLinks
770  *
771  */
772 static void HLPFILE_AddHotSpotLinks(struct RtfData* rd, HLPFILE* file,
773                                     const BYTE* start, ULONG hs_size, ULONG hs_offset)
774 {
775     unsigned    i, hs_num;
776     ULONG       hs_macro;
777     const char* str;
778
779     if (hs_size == 0 || hs_offset == 0) return;
780
781     start += hs_offset;
782     /* always 1 ?? */
783     hs_num = GET_USHORT(start, 1);
784     hs_macro = GET_UINT(start, 3);
785
786     str = (const char*)start + 7 + 15 * hs_num + hs_macro;
787     /* FIXME: should use hs_size to prevent out of bounds reads */
788     for (i = 0; i < hs_num; i++)
789     {
790         HLPFILE_HOTSPOTLINK*    hslink;
791
792         WINE_TRACE("%02x-%02x%02x {%s,%s}\n",
793                    start[7 + 15 * i + 0], start[7 + 15 * i + 1], start[7 + 15 * i + 2],
794                    str, str + strlen(str) + 1);
795         /* str points to two null terminated strings:
796          * hotspot name, then link name
797          */
798         str += strlen(str) + 1;     /* skip hotspot name */
799
800         hslink = NULL;
801         switch (start[7 + 15 * i + 0])
802         /* The next two chars always look like 0x04 0x00 ???
803          * What are they for ?
804          */
805         {
806         case 0xC8:
807             hslink = (HLPFILE_HOTSPOTLINK*)
808                 HLPFILE_AllocLink(rd, hlp_link_macro, str, -1, 0, 0, 1, -1);
809             break;
810
811         case 0xE6:
812         case 0xE7:
813             hslink = (HLPFILE_HOTSPOTLINK*)
814                 HLPFILE_AllocLink(rd, (start[7 + 15 * i + 0] & 1) ? hlp_link_link : hlp_link_popup,
815                                   file->lpszPath, -1, HLPFILE_Hash(str),
816                                   0, 1, -1);
817             break;
818
819         case 0xEE:
820         case 0xEF:
821             {
822                 const char* win = strchr(str, '>');
823                 int wnd = -1;
824                 char* tgt = NULL;
825
826                 if (win)
827                 {
828                     for (wnd = file->numWindows - 1; wnd >= 0; wnd--)
829                     {
830                         if (!strcmp(win + 1, file->windows[wnd].name)) break;
831                     }
832                     if (wnd == -1)
833                         WINE_WARN("Couldn't find window info for %s\n", win);
834                     if ((tgt = HeapAlloc(GetProcessHeap(), 0, win - str + 1)))
835                     {
836                         memcpy(tgt, str, win - str);
837                         tgt[win - str] = '\0';
838                     }
839                 }
840                 hslink = (HLPFILE_HOTSPOTLINK*)
841                     HLPFILE_AllocLink(rd, (start[7 + 15 * i + 0] & 1) ? hlp_link_link : hlp_link_popup,
842                                       file->lpszPath, -1, HLPFILE_Hash(tgt ? tgt : str), 0, 1, wnd);
843                 HeapFree(GetProcessHeap(), 0, tgt);
844                 break;
845             }
846         default:
847             WINE_FIXME("unknown hotsport target 0x%x\n", start[7 + 15 * i + 0]);
848         }
849         if (hslink)
850         {
851             hslink->x      = GET_USHORT(start, 7 + 15 * i + 3);
852             hslink->y      = GET_USHORT(start, 7 + 15 * i + 5);
853             hslink->width  = GET_USHORT(start, 7 + 15 * i + 7);
854             hslink->height = GET_USHORT(start, 7 + 15 * i + 9);
855             /* target = GET_UINT(start, 7 + 15 * i + 11); */
856         }
857         str += strlen(str) + 1;
858     }
859 }
860
861 /******************************************************************
862  *             HLPFILE_RtfAddTransparentBitmap
863  *
864  * We'll transform a transparent bitmap into an metafile that
865  * we then transform into RTF
866  */
867 static BOOL HLPFILE_RtfAddTransparentBitmap(struct RtfData* rd, const BITMAPINFO* bi,
868                                             const void* pict, unsigned nc)
869 {
870     HDC                 hdc, hdcMask, hdcMem, hdcEMF;
871     HBITMAP             hbm, hbmMask, hbmOldMask, hbmOldMem;
872     HENHMETAFILE        hEMF;
873     BOOL                ret = FALSE;
874     void*               data;
875     UINT                sz;
876
877     hbm = CreateDIBitmap(hdc = GetDC(0), &bi->bmiHeader,
878                          CBM_INIT, pict, bi, DIB_RGB_COLORS);
879
880     hdcMem = CreateCompatibleDC(hdc);
881     hbmOldMem = SelectObject(hdcMem, hbm);
882
883     /* create the mask bitmap from the main bitmap */
884     hdcMask = CreateCompatibleDC(hdc);
885     hbmMask = CreateBitmap(bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, 1, 1, NULL);
886     hbmOldMask = SelectObject(hdcMask, hbmMask);
887     SetBkColor(hdcMem,
888                RGB(bi->bmiColors[nc - 1].rgbRed,
889                    bi->bmiColors[nc - 1].rgbGreen,
890                    bi->bmiColors[nc - 1].rgbBlue));
891     BitBlt(hdcMask, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCCOPY);
892
893     /* sets to RGB(0,0,0) the transparent bits in main bitmap */
894     SetBkColor(hdcMem, RGB(0,0,0));
895     SetTextColor(hdcMem, RGB(255,255,255));
896     BitBlt(hdcMem, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMask, 0, 0, SRCAND);
897
898     SelectObject(hdcMask, hbmOldMask);
899     DeleteDC(hdcMask);
900
901     SelectObject(hdcMem, hbmOldMem);
902     DeleteDC(hdcMem);
903
904     /* we create the bitmap on the fly */
905     hdcEMF = CreateEnhMetaFileW(NULL, NULL, NULL, NULL);
906     hdcMem = CreateCompatibleDC(hdcEMF);
907
908     /* sets to RGB(0,0,0) the transparent bits in final bitmap */
909     hbmOldMem = SelectObject(hdcMem, hbmMask);
910     SetBkColor(hdcEMF, RGB(255, 255, 255));
911     SetTextColor(hdcEMF, RGB(0, 0, 0));
912     BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCAND);
913
914     /* and copy the remaining bits of main bitmap */
915     SelectObject(hdcMem, hbm);
916     BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCPAINT);
917     SelectObject(hdcMem, hbmOldMem);
918     DeleteDC(hdcMem);
919
920     /* do the cleanup */
921     ReleaseDC(0, hdc);
922     DeleteObject(hbmMask);
923     DeleteObject(hbm);
924
925     hEMF = CloseEnhMetaFile(hdcEMF);
926
927     /* generate rtf stream */
928     sz = GetEnhMetaFileBits(hEMF, 0, NULL);
929     if (sz && (data = HeapAlloc(GetProcessHeap(), 0, sz)))
930     {
931         if (sz == GetEnhMetaFileBits(hEMF, sz, data))
932         {
933             ret = HLPFILE_RtfAddControl(rd, "{\\pict\\emfblip") &&
934                 HLPFILE_RtfAddHexBytes(rd, data, sz) &&
935                 HLPFILE_RtfAddControl(rd, "}");
936         }
937         HeapFree(GetProcessHeap(), 0, data);
938     }
939     DeleteEnhMetaFile(hEMF);
940
941     return ret;
942 }
943
944 /******************************************************************
945  *              HLPFILE_RtfAddBitmap
946  *
947  */
948 static BOOL HLPFILE_RtfAddBitmap(struct RtfData* rd, HLPFILE* file, const BYTE* beg, BYTE type, BYTE pack)
949 {
950     const BYTE*         ptr;
951     const BYTE*         pict_beg;
952     BYTE*               alloc = NULL;
953     BITMAPINFO*         bi;
954     ULONG               off, csz;
955     unsigned            nc = 0;
956     BOOL                clrImportant = FALSE;
957     BOOL                ret = FALSE;
958     char                tmp[256];
959     unsigned            hs_size, hs_offset;
960
961     bi = HeapAlloc(GetProcessHeap(), 0, sizeof(*bi));
962     if (!bi) return FALSE;
963
964     ptr = beg + 2; /* for type and pack */
965
966     bi->bmiHeader.biSize          = sizeof(bi->bmiHeader);
967     bi->bmiHeader.biXPelsPerMeter = fetch_ulong(&ptr);
968     bi->bmiHeader.biYPelsPerMeter = fetch_ulong(&ptr);
969     bi->bmiHeader.biPlanes        = fetch_ushort(&ptr);
970     bi->bmiHeader.biBitCount      = fetch_ushort(&ptr);
971     bi->bmiHeader.biWidth         = fetch_ulong(&ptr);
972     bi->bmiHeader.biHeight        = fetch_ulong(&ptr);
973     bi->bmiHeader.biClrUsed       = fetch_ulong(&ptr);
974     clrImportant  = fetch_ulong(&ptr);
975     bi->bmiHeader.biClrImportant  = (clrImportant > 1) ? clrImportant : 0;
976     bi->bmiHeader.biCompression   = BI_RGB;
977     if (bi->bmiHeader.biBitCount > 32) WINE_FIXME("Unknown bit count %u\n", bi->bmiHeader.biBitCount);
978     if (bi->bmiHeader.biPlanes != 1) WINE_FIXME("Unsupported planes %u\n", bi->bmiHeader.biPlanes);
979     bi->bmiHeader.biSizeImage = (((bi->bmiHeader.biWidth * bi->bmiHeader.biBitCount + 31) & ~31) / 8) * bi->bmiHeader.biHeight;
980     WINE_TRACE("planes=%d bc=%d size=(%d,%d)\n",
981                bi->bmiHeader.biPlanes, bi->bmiHeader.biBitCount,
982                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
983
984     csz = fetch_ulong(&ptr);
985     hs_size = fetch_ulong(&ptr);
986
987     off = GET_UINT(ptr, 0); ptr += 4;
988     hs_offset = GET_UINT(ptr, 0); ptr += 4;
989     HLPFILE_AddHotSpotLinks(rd, file, beg, hs_size, hs_offset);
990
991     /* now read palette info */
992     if (type == 0x06)
993     {
994         unsigned i;
995
996         nc = bi->bmiHeader.biClrUsed;
997         /* not quite right, especially for bitfields type of compression */
998         if (!nc && bi->bmiHeader.biBitCount <= 8)
999             nc = 1 << bi->bmiHeader.biBitCount;
1000
1001         bi = HeapReAlloc(GetProcessHeap(), 0, bi, sizeof(*bi) + nc * sizeof(RGBQUAD));
1002         if (!bi) return FALSE;
1003         for (i = 0; i < nc; i++)
1004         {
1005             bi->bmiColors[i].rgbBlue     = ptr[0];
1006             bi->bmiColors[i].rgbGreen    = ptr[1];
1007             bi->bmiColors[i].rgbRed      = ptr[2];
1008             bi->bmiColors[i].rgbReserved = 0;
1009             ptr += 4;
1010         }
1011     }
1012     pict_beg = HLPFILE_DecompressGfx(beg + off, csz, bi->bmiHeader.biSizeImage, pack, &alloc);
1013
1014     if (clrImportant == 1 && nc > 0)
1015     {
1016         ret = HLPFILE_RtfAddTransparentBitmap(rd, bi, pict_beg, nc);
1017         goto done;
1018     }
1019     if (!HLPFILE_RtfAddControl(rd, "{\\pict")) goto done;
1020     if (type == 0x06)
1021     {
1022         sprintf(tmp, "\\dibitmap0\\picw%d\\pich%d",
1023                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
1024         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1025         if (!HLPFILE_RtfAddHexBytes(rd, bi, sizeof(*bi) + nc * sizeof(RGBQUAD))) goto done;
1026     }
1027     else
1028     {
1029         sprintf(tmp, "\\wbitmap0\\wbmbitspixel%d\\wbmplanes%d\\picw%d\\pich%d",
1030                 bi->bmiHeader.biBitCount, bi->bmiHeader.biPlanes,
1031                 bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
1032         if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1033     }
1034     if (!HLPFILE_RtfAddHexBytes(rd, pict_beg, bi->bmiHeader.biSizeImage)) goto done;
1035     if (!HLPFILE_RtfAddControl(rd, "}")) goto done;
1036
1037     ret = TRUE;
1038 done:
1039     HeapFree(GetProcessHeap(), 0, bi);
1040     HeapFree(GetProcessHeap(), 0, alloc);
1041
1042     return ret;
1043 }
1044
1045 /******************************************************************
1046  *              HLPFILE_RtfAddMetaFile
1047  *
1048  */
1049 static BOOL     HLPFILE_RtfAddMetaFile(struct RtfData* rd, HLPFILE* file, const BYTE* beg, BYTE pack)
1050 {
1051     ULONG               size, csize, off, hs_offset, hs_size;
1052     const BYTE*         ptr;
1053     const BYTE*         bits;
1054     BYTE*               alloc = NULL;
1055     char                tmp[256];
1056     unsigned            mm;
1057     BOOL                ret;
1058
1059     WINE_TRACE("Loading metafile\n");
1060
1061     ptr = beg + 2; /* for type and pack */
1062
1063     mm = fetch_ushort(&ptr); /* mapping mode */
1064     sprintf(tmp, "{\\pict\\wmetafile%d\\picw%d\\pich%d",
1065             mm, GET_USHORT(ptr, 0), GET_USHORT(ptr, 2));
1066     if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1067     ptr += 4;
1068
1069     size = fetch_ulong(&ptr); /* decompressed size */
1070     csize = fetch_ulong(&ptr); /* compressed size */
1071     hs_size = fetch_ulong(&ptr); /* hotspot size */
1072     off = GET_UINT(ptr, 0);
1073     hs_offset = GET_UINT(ptr, 4);
1074     ptr += 8;
1075
1076     HLPFILE_AddHotSpotLinks(rd, file, beg, hs_size, hs_offset);
1077
1078     WINE_TRACE("sz=%u csz=%u offs=%u/%u,%u/%u\n",
1079                size, csize, off, (ULONG)(ptr - beg), hs_size, hs_offset);
1080
1081     bits = HLPFILE_DecompressGfx(beg + off, csize, size, pack, &alloc);
1082     if (!bits) return FALSE;
1083
1084     ret = HLPFILE_RtfAddHexBytes(rd, bits, size) &&
1085         HLPFILE_RtfAddControl(rd, "}");
1086
1087     HeapFree(GetProcessHeap(), 0, alloc);
1088
1089     return ret;
1090 }
1091
1092 /******************************************************************
1093  *              HLPFILE_RtfAddGfxByAddr
1094  *
1095  */
1096 static  BOOL    HLPFILE_RtfAddGfxByAddr(struct RtfData* rd, HLPFILE *hlpfile,
1097                                         const BYTE* ref, ULONG size)
1098 {
1099     unsigned    i, numpict;
1100
1101     numpict = GET_USHORT(ref, 2);
1102     WINE_TRACE("Got picture magic=%04x #=%d\n", GET_USHORT(ref, 0), numpict);
1103
1104     for (i = 0; i < numpict; i++)
1105     {
1106         const BYTE*     beg;
1107         const BYTE*     ptr;
1108         BYTE            type, pack;
1109
1110         WINE_TRACE("Offset[%d] = %x\n", i, GET_UINT(ref, (1 + i) * 4));
1111         beg = ptr = ref + GET_UINT(ref, (1 + i) * 4);
1112
1113         type = *ptr++;
1114         pack = *ptr++;
1115
1116         switch (type)
1117         {
1118         case 5: /* device dependent bmp */
1119         case 6: /* device independent bmp */
1120             HLPFILE_RtfAddBitmap(rd, hlpfile, beg, type, pack);
1121             break;
1122         case 8:
1123             HLPFILE_RtfAddMetaFile(rd, hlpfile, beg, pack);
1124             break;
1125         default: WINE_FIXME("Unknown type %u\n", type); return FALSE;
1126         }
1127
1128         /* FIXME: hotspots */
1129
1130         /* FIXME: implement support for multiple picture format */
1131         if (numpict != 1) WINE_FIXME("Supporting only one bitmap format per logical bitmap (for now). Using first format\n");
1132         break;
1133     }
1134     return TRUE;
1135 }
1136
1137 /******************************************************************
1138  *              HLPFILE_RtfAddGfxByIndex
1139  *
1140  *
1141  */
1142 static  BOOL    HLPFILE_RtfAddGfxByIndex(struct RtfData* rd, HLPFILE *hlpfile,
1143                                          unsigned index)
1144 {
1145     char        tmp[16];
1146     BYTE        *ref, *end;
1147
1148     WINE_TRACE("Loading picture #%d\n", index);
1149
1150     sprintf(tmp, "|bm%u", index);
1151
1152     if (!HLPFILE_FindSubFile(hlpfile, tmp, &ref, &end)) {WINE_WARN("no sub file\n"); return FALSE;}
1153
1154     ref += 9;
1155     return HLPFILE_RtfAddGfxByAddr(rd, hlpfile, ref, end - ref);
1156 }
1157
1158 /******************************************************************
1159  *              HLPFILE_AllocLink
1160  *
1161  *
1162  */
1163 static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
1164                                              const char* str, unsigned len, LONG hash,
1165                                              unsigned clrChange, unsigned bHotSpot, unsigned wnd)
1166 {
1167     HLPFILE_LINK*  link;
1168     char*          link_str;
1169     unsigned       asz = bHotSpot ? sizeof(HLPFILE_HOTSPOTLINK) : sizeof(HLPFILE_LINK);
1170
1171     /* FIXME: should build a string table for the attributes.link.lpszPath
1172      * they are reallocated for each link
1173      */
1174     if (len == -1) len = strlen(str);
1175     link = HeapAlloc(GetProcessHeap(), 0, asz + len + 1);
1176     if (!link) return NULL;
1177
1178     link->cookie     = cookie;
1179     link->string     = link_str = (char*)link + asz;
1180     memcpy(link_str, str, len);
1181     link_str[len] = '\0';
1182     link->hash       = hash;
1183     link->bClrChange = clrChange ? 1 : 0;
1184     link->bHotSpot   = bHotSpot;
1185     link->window     = wnd;
1186     link->next       = rd->first_link;
1187     rd->first_link   = link;
1188     link->cpMin      = rd->char_pos;
1189     rd->force_color  = clrChange;
1190     if (rd->current_link) WINE_FIXME("Pending link\n");
1191     if (bHotSpot)
1192         link->cpMax = rd->char_pos;
1193     else
1194         rd->current_link = link;
1195
1196     WINE_TRACE("Link[%d] to %s@%08x:%d\n",
1197                link->cookie, link->string, link->hash, link->window);
1198     return link;
1199 }
1200
1201 static unsigned HLPFILE_HalfPointsToTwips(unsigned pts)
1202 {
1203     static unsigned logPxY;
1204     if (!logPxY)
1205     {
1206         HDC hdc = GetDC(NULL);
1207         logPxY = GetDeviceCaps(hdc, LOGPIXELSY);
1208         ReleaseDC(NULL, hdc);
1209     }
1210     return MulDiv(pts, 72 * 10, logPxY);
1211 }
1212
1213 /***********************************************************************
1214  *
1215  *           HLPFILE_BrowseParagraph
1216  */
1217 static BOOL HLPFILE_BrowseParagraph(HLPFILE_PAGE* page, struct RtfData* rd,
1218                                     BYTE *buf, BYTE* end, unsigned* parlen)
1219 {
1220     UINT               textsize;
1221     const BYTE        *format, *format_end;
1222     char              *text, *text_base, *text_end;
1223     LONG               size, blocksize, datalen;
1224     unsigned short     bits;
1225     unsigned           nc, ncol = 1;
1226     short              table_width;
1227     BOOL               in_table = FALSE;
1228     char               tmp[256];
1229     BOOL               ret = FALSE;
1230
1231     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
1232
1233     *parlen = 0;
1234     blocksize = GET_UINT(buf, 0);
1235     size = GET_UINT(buf, 0x4);
1236     datalen = GET_UINT(buf, 0x10);
1237     text = text_base = HeapAlloc(GetProcessHeap(), 0, size);
1238     if (!text) return FALSE;
1239     if (size > blocksize - datalen)
1240     {
1241         /* need to decompress */
1242         if (page->file->hasPhrases)
1243             HLPFILE_Uncompress2(page->file, buf + datalen, end, (BYTE*)text, (BYTE*)text + size);
1244         else if (page->file->hasPhrases40)
1245             HLPFILE_Uncompress3(page->file, text, text + size, buf + datalen, end);
1246         else
1247         {
1248             WINE_FIXME("Text size is too long, splitting\n");
1249             size = blocksize - datalen;
1250             memcpy(text, buf + datalen, size);
1251         }
1252     }
1253     else
1254         memcpy(text, buf + datalen, size);
1255
1256     text_end = text + size;
1257
1258     format = buf + 0x15;
1259     format_end = buf + GET_UINT(buf, 0x10);
1260
1261     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
1262     {
1263         fetch_long(&format);
1264         *parlen = fetch_ushort(&format);
1265     }
1266
1267     if (buf[0x14] == 0x23)
1268     {
1269         char    type;
1270
1271         in_table = TRUE;
1272         ncol = *format++;
1273
1274         if (!HLPFILE_RtfAddControl(rd, "\\trowd")) goto done;
1275         type = *format++;
1276         if (type == 0 || type == 2)
1277         {
1278             table_width = GET_SHORT(format, 0);
1279             format += 2;
1280         }
1281         else
1282             table_width = 32767;
1283         WINE_TRACE("New table: cols=%d type=%x width=%d\n",
1284                    ncol, type, table_width);
1285         if (ncol > 1)
1286         {
1287             int     pos;
1288             sprintf(tmp, "\\trgaph%d\\trleft%d",
1289                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6), table_width, 32767)),
1290                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)));
1291             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1292             pos = HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6) / 2, table_width, 32767));
1293             for (nc = 0; nc < ncol; nc++)
1294             {
1295                 WINE_TRACE("column(%d/%d) gap=%d width=%d\n",
1296                            nc, ncol, GET_SHORT(format, nc*4),
1297                            GET_SHORT(format, nc*4+2));
1298                 pos += GET_SHORT(format, nc * 4) + GET_SHORT(format, nc * 4 + 2);
1299                 sprintf(tmp, "\\cellx%d",
1300                         HLPFILE_HalfPointsToTwips(MulDiv(pos, table_width, 32767)));
1301                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1302             }
1303         }
1304         else
1305         {
1306             WINE_TRACE("column(0/%d) gap=%d width=%d\n",
1307                        ncol, GET_SHORT(format, 0), GET_SHORT(format, 2));
1308             sprintf(tmp, "\\trleft%d\\cellx%d ",
1309                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)),
1310                     HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0) + GET_SHORT(format, 2),
1311                                       table_width, 32767)));
1312             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1313         }
1314         format += ncol * 4;
1315     }
1316
1317     for (nc = 0; nc < ncol; /**/)
1318     {
1319         WINE_TRACE("looking for format at offset %lu in column %d\n", (SIZE_T)(format - (buf + 0x15)), nc);
1320         if (!HLPFILE_RtfAddControl(rd, "\\pard")) goto done;
1321         if (in_table)
1322         {
1323             nc = GET_SHORT(format, 0);
1324             if (nc == -1) break;
1325             format += 5;
1326             if (!HLPFILE_RtfAddControl(rd, "\\intbl")) goto done;
1327         }
1328         else nc++;
1329         if (buf[0x14] == 0x01)
1330             format += 6;
1331         else
1332             format += 4;
1333         bits = GET_USHORT(format, 0); format += 2;
1334         if (bits & 0x0001) fetch_long(&format);
1335         if (bits & 0x0002)
1336         {
1337             sprintf(tmp, "\\sb%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1338             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1339         }
1340         if (bits & 0x0004)
1341         {
1342             sprintf(tmp, "\\sa%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1343             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1344         }
1345         if (bits & 0x0008)
1346         {
1347             sprintf(tmp, "\\sl%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1348             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1349         }
1350         if (bits & 0x0010)
1351         {
1352             sprintf(tmp, "\\li%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1353             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1354         }
1355         if (bits & 0x0020)
1356         {
1357             sprintf(tmp, "\\ri%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1358             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1359         }
1360         if (bits & 0x0040)
1361         {
1362             sprintf(tmp, "\\fi%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
1363             if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1364         }
1365         if (bits & 0x0100)
1366         {
1367             BYTE        brdr = *format++;
1368             short       w;
1369
1370             if ((brdr & 0x01) && !HLPFILE_RtfAddControl(rd, "\\box")) goto done;
1371             if ((brdr & 0x02) && !HLPFILE_RtfAddControl(rd, "\\brdrt")) goto done;
1372             if ((brdr & 0x04) && !HLPFILE_RtfAddControl(rd, "\\brdrl")) goto done;
1373             if ((brdr & 0x08) && !HLPFILE_RtfAddControl(rd, "\\brdrb")) goto done;
1374             if ((brdr & 0x10) && !HLPFILE_RtfAddControl(rd, "\\brdrr")) goto done;
1375             if ((brdr & 0x20) && !HLPFILE_RtfAddControl(rd, "\\brdrth")) goto done;
1376             if (!(brdr & 0x20) && !HLPFILE_RtfAddControl(rd, "\\brdrs")) goto done;
1377             if ((brdr & 0x40) && !HLPFILE_RtfAddControl(rd, "\\brdrdb")) goto done;
1378             /* 0x80: unknown */
1379
1380             w = GET_SHORT(format, 0); format += 2;
1381             if (w)
1382             {
1383                 sprintf(tmp, "\\brdrw%d", HLPFILE_HalfPointsToTwips(w));
1384                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1385             }
1386         }
1387         if (bits & 0x0200)
1388         {
1389             int                 i, ntab = fetch_short(&format);
1390             unsigned            tab, ts;
1391             const char*         kind;
1392
1393             for (i = 0; i < ntab; i++)
1394             {
1395                 tab = fetch_ushort(&format);
1396                 ts = (tab & 0x4000) ? fetch_ushort(&format) : 0 /* left */;
1397                 switch (ts)
1398                 {
1399                 default: WINE_FIXME("Unknown tab style %x\n", ts);
1400                 /* fall through */
1401                 case 0: kind = ""; break;
1402                 case 1: kind = "\\tqr"; break;
1403                 case 2: kind = "\\tqc"; break;
1404                 }
1405                 /* FIXME: do kind */
1406                 sprintf(tmp, "%s\\tx%d",
1407                         kind, HLPFILE_HalfPointsToTwips(tab & 0x3FFF));
1408                 if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1409             }
1410         }
1411         switch (bits & 0xc00)
1412         {
1413         default: WINE_FIXME("Unsupported alignment 0xC00\n"); break;
1414         case 0: if (!HLPFILE_RtfAddControl(rd, "\\ql")) goto done; break;
1415         case 0x400: if (!HLPFILE_RtfAddControl(rd, "\\qr")) goto done; break;
1416         case 0x800: if (!HLPFILE_RtfAddControl(rd, "\\qc")) goto done; break;
1417         }
1418
1419         /* 0x1000 doesn't need space */
1420         if ((bits & 0x1000) && !HLPFILE_RtfAddControl(rd, "\\keep")) goto done;
1421         if ((bits & 0xE080) != 0) 
1422             WINE_FIXME("Unsupported bits %04x, potential trouble ahead\n", bits);
1423
1424         while (text < text_end && format < format_end)
1425         {
1426             WINE_TRACE("Got text: %s (%p/%p - %p/%p)\n", wine_dbgstr_a(text), text, text_end, format, format_end);
1427             textsize = strlen(text);
1428             if (textsize)
1429             {
1430                 if (rd->force_color)
1431                 {
1432                     if ((rd->current_link->cookie == hlp_link_popup) ?
1433                         !HLPFILE_RtfAddControl(rd, "{\\uld\\cf1") :
1434                         !HLPFILE_RtfAddControl(rd, "{\\ul\\cf1")) goto done;
1435                 }
1436                 if (!HLPFILE_RtfAddText(rd, text)) goto done;
1437                 if (rd->force_color && !HLPFILE_RtfAddControl(rd, "}")) goto done;
1438                 rd->char_pos += textsize;
1439             }
1440             /* else: null text, keep on storing attributes */
1441             text += textsize + 1;
1442
1443             if (*format == 0xff)
1444             {
1445                 format++;
1446                 break;
1447             }
1448
1449             WINE_TRACE("format=%02x\n", *format);
1450             switch (*format)
1451             {
1452             case 0x20:
1453                 WINE_FIXME("NIY20\n");
1454                 format += 5;
1455                 break;
1456
1457             case 0x21:
1458                 WINE_FIXME("NIY21\n");
1459                 format += 3;
1460                 break;
1461
1462             case 0x80:
1463                 {
1464                     unsigned    font = GET_USHORT(format, 1);
1465                     unsigned    fs;
1466
1467                     WINE_TRACE("Changing font to %d\n", font);
1468                     format += 3;
1469                     /* Font size in hlpfile is given in the same units as
1470                        rtf control word \fs uses (half-points). */
1471                     switch (rd->font_scale)
1472                     {
1473                     case 0: fs = page->file->fonts[font].LogFont.lfHeight - 4; break;
1474                     default:
1475                     case 1: fs = page->file->fonts[font].LogFont.lfHeight; break;
1476                     case 2: fs = page->file->fonts[font].LogFont.lfHeight + 4; break;
1477                     }
1478                     /* FIXME: missing at least colors, also bold attribute looses information */
1479
1480                     sprintf(tmp, "\\f%d\\cf%d\\fs%d%s%s%s%s",
1481                             font, font + 2, fs,
1482                             page->file->fonts[font].LogFont.lfWeight > 400 ? "\\b" : "\\b0",
1483                             page->file->fonts[font].LogFont.lfItalic ? "\\i" : "\\i0",
1484                             page->file->fonts[font].LogFont.lfUnderline ? "\\ul" : "\\ul0",
1485                             page->file->fonts[font].LogFont.lfStrikeOut ? "\\strike" : "\\strike0");
1486                     if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1487                 }
1488                break;
1489
1490             case 0x81:
1491                 if (!HLPFILE_RtfAddControl(rd, "\\line")) goto done;
1492                 format += 1;
1493                 rd->char_pos++;
1494                 break;
1495
1496             case 0x82:
1497                 if (in_table)
1498                 {
1499                     if (format[1] != 0xFF)
1500                     {
1501                         if (!HLPFILE_RtfAddControl(rd, "\\par\\intbl")) goto done;
1502                     }
1503                     else
1504                     {
1505                         if (!HLPFILE_RtfAddControl(rd, "\\cell\\pard\\intbl")) goto done;
1506                     }
1507                 }
1508                 else if (!HLPFILE_RtfAddControl(rd, "\\par")) goto done;
1509                 format += 1;
1510                 rd->char_pos++;
1511                 break;
1512
1513             case 0x83:
1514                 if (!HLPFILE_RtfAddControl(rd, "\\tab")) goto done;
1515                 format += 1;
1516                 rd->char_pos++;
1517                 break;
1518
1519 #if 0
1520             case 0x84:
1521                 format += 3;
1522                 break;
1523 #endif
1524
1525             case 0x86:
1526             case 0x87:
1527             case 0x88:
1528                 {
1529                     BYTE    type = format[1];
1530                     LONG    size;
1531
1532                     /* FIXME: we don't use 'BYTE    pos = (*format - 0x86);' for the image position */
1533                     format += 2;
1534                     size = fetch_long(&format);
1535
1536                     switch (type)
1537                     {
1538                     case 0x22:
1539                         fetch_ushort(&format); /* hot spot */
1540                         /* fall thru */
1541                     case 0x03:
1542                         switch (GET_SHORT(format, 0))
1543                         {
1544                         case 0:
1545                             HLPFILE_RtfAddGfxByIndex(rd, page->file, GET_SHORT(format, 2));
1546                             rd->char_pos++;
1547                             break;
1548                         case 1:
1549                             WINE_FIXME("does it work ??? %x<%u>#%u\n",
1550                                        GET_SHORT(format, 0),
1551                                        size, GET_SHORT(format, 2));
1552                             HLPFILE_RtfAddGfxByAddr(rd, page->file, format + 2, size - 4);
1553                             rd->char_pos++;
1554                            break;
1555                         default:
1556                             WINE_FIXME("??? %u\n", GET_SHORT(format, 0));
1557                             break;
1558                         }
1559                         break;
1560                     case 0x05:
1561                         WINE_FIXME("Got an embedded element %s\n", format + 6);
1562                         break;
1563                     default:
1564                         WINE_FIXME("Got a type %d picture\n", type);
1565                         break;
1566                     }
1567                     format += size;
1568                 }
1569                 break;
1570
1571             case 0x89:
1572                 format += 1;
1573                 if (!rd->current_link)
1574                     WINE_FIXME("No existing link\n");
1575                 rd->current_link->cpMax = rd->char_pos;
1576                 rd->current_link = NULL;
1577                 rd->force_color = FALSE;
1578                 break;
1579
1580             case 0x8B:
1581                 if (!HLPFILE_RtfAddControl(rd, "\\~")) goto done;
1582                 format += 1;
1583                 rd->char_pos++;
1584                 break;
1585
1586             case 0x8C:
1587                 if (!HLPFILE_RtfAddControl(rd, "\\_")) goto done;
1588                 /* FIXME: it could be that hyphen is also in input stream !! */
1589                 format += 1;
1590                 rd->char_pos++;
1591                 break;
1592
1593 #if 0
1594             case 0xA9:
1595                 format += 2;
1596                 break;
1597 #endif
1598
1599             case 0xC8:
1600             case 0xCC:
1601                 WINE_TRACE("macro => %s\n", format + 3);
1602                 HLPFILE_AllocLink(rd, hlp_link_macro, (const char*)format + 3,
1603                                   GET_USHORT(format, 1), 0, !(*format & 4), 0, -1);
1604                 format += 3 + GET_USHORT(format, 1);
1605                 break;
1606
1607             case 0xE0:
1608             case 0xE1:
1609                 WINE_WARN("jump topic 1 => %u\n", GET_UINT(format, 1));
1610                 HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1611                                   page->file->lpszPath, -1, GET_UINT(format, 1), 1, 0, -1);
1612
1613
1614                 format += 5;
1615                 break;
1616
1617             case 0xE2:
1618             case 0xE3:
1619             case 0xE6:
1620             case 0xE7:
1621                 HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1622                                   page->file->lpszPath, -1, GET_UINT(format, 1),
1623                                   !(*format & 4), 0, -1);
1624                 format += 5;
1625                 break;
1626
1627             case 0xEA:
1628             case 0xEB:
1629             case 0xEE:
1630             case 0xEF:
1631                 {
1632                     const char*       ptr = (const char*) format + 8;
1633                     BYTE        type = format[3];
1634                     int         wnd = -1;
1635
1636                     switch (type)
1637                     {
1638                     case 1:
1639                         wnd = *ptr;
1640                         /* fall through */
1641                     case 0:
1642                         ptr = page->file->lpszPath;
1643                         break;
1644                     case 6:
1645                         for (wnd = page->file->numWindows - 1; wnd >= 0; wnd--)
1646                         {
1647                             if (!strcmp(ptr, page->file->windows[wnd].name)) break;
1648                         }
1649                         if (wnd == -1)
1650                             WINE_WARN("Couldn't find window info for %s\n", ptr);
1651                         ptr += strlen(ptr) + 1;
1652                         /* fall through */
1653                     case 4:
1654                         break;
1655                     default:
1656                         WINE_WARN("Unknown link type %d\n", type);
1657                         break;
1658                     }
1659                     HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1660                                       ptr, -1, GET_UINT(format, 4), !(*format & 4), 0, wnd);
1661                 }
1662                 format += 3 + GET_USHORT(format, 1);
1663                 break;
1664
1665             default:
1666                 WINE_WARN("format %02x\n", *format);
1667                 format++;
1668             }
1669         }
1670     }
1671     if (in_table)
1672     {
1673         if (!HLPFILE_RtfAddControl(rd, "\\row\\par\\pard\\plain")) goto done;
1674         rd->char_pos += 2;
1675     }
1676     ret = TRUE;
1677 done:
1678
1679     HeapFree(GetProcessHeap(), 0, text_base);
1680     return ret;
1681 }
1682
1683 /******************************************************************
1684  *              HLPFILE_BrowsePage
1685  *
1686  */
1687 BOOL    HLPFILE_BrowsePage(HLPFILE_PAGE* page, struct RtfData* rd,
1688                            unsigned font_scale, unsigned relative)
1689 {
1690     HLPFILE     *hlpfile = page->file;
1691     BYTE        *buf, *end;
1692     DWORD       ref = page->reference;
1693     unsigned    index, old_index = -1, offset, count = 0, offs = 0;
1694     unsigned    cpg, parlen;
1695     char        tmp[1024];
1696     const char* ck = NULL;
1697
1698     rd->in_text = TRUE;
1699     rd->data = rd->ptr = HeapAlloc(GetProcessHeap(), 0, rd->allocated = 32768);
1700     rd->char_pos = 0;
1701     rd->first_link = rd->current_link = NULL;
1702     rd->force_color = FALSE;
1703     rd->font_scale = font_scale;
1704     rd->relative = relative;
1705     rd->char_pos_rel = 0;
1706
1707     switch (hlpfile->charset)
1708     {
1709     case DEFAULT_CHARSET:
1710     case ANSI_CHARSET:          cpg = 1252; break;
1711     case SHIFTJIS_CHARSET:      cpg = 932; break;
1712     case HANGEUL_CHARSET:       cpg = 949; break;
1713     case GB2312_CHARSET:        cpg = 936; break;
1714     case CHINESEBIG5_CHARSET:   cpg = 950; break;
1715     case GREEK_CHARSET:         cpg = 1253; break;
1716     case TURKISH_CHARSET:       cpg = 1254; break;
1717     case HEBREW_CHARSET:        cpg = 1255; break;
1718     case ARABIC_CHARSET:        cpg = 1256; break;
1719     case BALTIC_CHARSET:        cpg = 1257; break;
1720     case VIETNAMESE_CHARSET:    cpg = 1258; break;
1721     case RUSSIAN_CHARSET:       cpg = 1251; break;
1722     case EE_CHARSET:            cpg = 1250; break;
1723     case THAI_CHARSET:          cpg = 874; break;
1724     case JOHAB_CHARSET:         cpg = 1361; break;
1725     case MAC_CHARSET:           ck = "mac"; break;
1726     default:
1727         WINE_FIXME("Unsupported charset %u\n", hlpfile->charset);
1728         cpg = 1252;
1729     }
1730     if (ck)
1731     {
1732         sprintf(tmp, "{\\rtf1\\%s\\deff0", ck);
1733         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1734     }
1735     else
1736     {
1737         sprintf(tmp, "{\\rtf1\\ansi\\ansicpg%d\\deff0", cpg);
1738         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1739     }
1740
1741     /* generate font table */
1742     if (!HLPFILE_RtfAddControl(rd, "{\\fonttbl")) return FALSE;
1743     for (index = 0; index < hlpfile->numFonts; index++)
1744     {
1745         const char* family;
1746         switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
1747         {
1748         case FF_MODERN:     family = "modern";  break;
1749         case FF_ROMAN:      family = "roman";   break;
1750         case FF_SWISS:      family = "swiss";   break;
1751         case FF_SCRIPT:     family = "script";  break;
1752         case FF_DECORATIVE: family = "decor";   break;
1753         default:            family = "nil";     break;
1754         }
1755         sprintf(tmp, "{\\f%d\\f%s\\fprq%d\\fcharset%d %s;}",
1756                 index, family,
1757                 hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0x0F,
1758                 hlpfile->fonts[index].LogFont.lfCharSet,
1759                 hlpfile->fonts[index].LogFont.lfFaceName);
1760         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1761     }
1762     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1763     /* generate color table */
1764     if (!HLPFILE_RtfAddControl(rd, "{\\colortbl ;\\red0\\green128\\blue0;")) return FALSE;
1765     for (index = 0; index < hlpfile->numFonts; index++)
1766     {
1767         sprintf(tmp, "\\red%d\\green%d\\blue%d;",
1768                 GetRValue(hlpfile->fonts[index].color),
1769                 GetGValue(hlpfile->fonts[index].color),
1770                 GetBValue(hlpfile->fonts[index].color));
1771         if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
1772     }
1773     if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1774
1775     do
1776     {
1777         if (hlpfile->version <= 16)
1778         {
1779             index  = (ref - 0x0C) / hlpfile->dsize;
1780             offset = (ref - 0x0C) % hlpfile->dsize;
1781         }
1782         else
1783         {
1784             index  = (ref - 0x0C) >> 14;
1785             offset = (ref - 0x0C) & 0x3FFF;
1786         }
1787
1788         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
1789         {
1790             /* we jumped to the next block, adjust pointers */
1791             ref -= 12;
1792             offset -= 12;
1793         }
1794
1795         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
1796         buf = hlpfile->topic_map[index] + offset;
1797         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
1798         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
1799         if (index != old_index) {offs = 0; old_index = index;}
1800
1801         switch (buf[0x14])
1802         {
1803         case 0x02:
1804             if (count++) goto done;
1805             break;
1806         case 0x01:
1807         case 0x20:
1808         case 0x23:
1809             if (!HLPFILE_BrowseParagraph(page, rd, buf, end, &parlen)) return FALSE;
1810             if (relative > index * 0x8000 + offs)
1811                 rd->char_pos_rel = rd->char_pos;
1812             offs += parlen;
1813             break;
1814         default:
1815             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
1816         }
1817         if (hlpfile->version <= 16)
1818         {
1819             ref += GET_UINT(buf, 0xc);
1820             if (GET_UINT(buf, 0xc) == 0)
1821                 break;
1822         }
1823         else
1824             ref = GET_UINT(buf, 0xc);
1825     } while (ref != 0xffffffff);
1826 done:
1827     page->first_link = rd->first_link;
1828     return HLPFILE_RtfAddControl(rd, "}");
1829 }
1830
1831 /******************************************************************
1832  *              HLPFILE_ReadFont
1833  *
1834  *
1835  */
1836 static BOOL HLPFILE_ReadFont(HLPFILE* hlpfile)
1837 {
1838     BYTE        *ref, *end;
1839     unsigned    i, len, idx;
1840     unsigned    face_num, dscr_num, face_offset, dscr_offset;
1841     BYTE        flag, family;
1842
1843     if (!HLPFILE_FindSubFile(hlpfile, "|FONT", &ref, &end))
1844     {
1845         WINE_WARN("no subfile FONT\n");
1846         hlpfile->numFonts = 0;
1847         hlpfile->fonts = NULL;
1848         return FALSE;
1849     }
1850
1851     ref += 9;
1852
1853     face_num    = GET_USHORT(ref, 0);
1854     dscr_num    = GET_USHORT(ref, 2);
1855     face_offset = GET_USHORT(ref, 4);
1856     dscr_offset = GET_USHORT(ref, 6);
1857
1858     WINE_TRACE("Got NumFacenames=%u@%u NumDesc=%u@%u\n",
1859                face_num, face_offset, dscr_num, dscr_offset);
1860
1861     hlpfile->numFonts = dscr_num;
1862     hlpfile->fonts = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_FONT) * dscr_num);
1863
1864     len = (dscr_offset - face_offset) / face_num;
1865 /* EPP     for (i = face_offset; i < dscr_offset; i += len) */
1866 /* EPP         WINE_FIXME("[%d]: %*s\n", i / len, len, ref + i); */
1867     for (i = 0; i < dscr_num; i++)
1868     {
1869         flag = ref[dscr_offset + i * 11 + 0];
1870         family = ref[dscr_offset + i * 11 + 2];
1871
1872         hlpfile->fonts[i].LogFont.lfHeight = ref[dscr_offset + i * 11 + 1];
1873         hlpfile->fonts[i].LogFont.lfWidth = 0;
1874         hlpfile->fonts[i].LogFont.lfEscapement = 0;
1875         hlpfile->fonts[i].LogFont.lfOrientation = 0;
1876         hlpfile->fonts[i].LogFont.lfWeight = (flag & 1) ? 700 : 400;
1877         hlpfile->fonts[i].LogFont.lfItalic = (flag & 2) ? TRUE : FALSE;
1878         hlpfile->fonts[i].LogFont.lfUnderline = (flag & 4) ? TRUE : FALSE;
1879         hlpfile->fonts[i].LogFont.lfStrikeOut = (flag & 8) ? TRUE : FALSE;
1880         hlpfile->fonts[i].LogFont.lfCharSet = hlpfile->charset;
1881         hlpfile->fonts[i].LogFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1882         hlpfile->fonts[i].LogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1883         hlpfile->fonts[i].LogFont.lfQuality = DEFAULT_QUALITY;
1884         hlpfile->fonts[i].LogFont.lfPitchAndFamily = DEFAULT_PITCH;
1885
1886         switch (family)
1887         {
1888         case 0x01: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_MODERN;     break;
1889         case 0x02: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_ROMAN;      break;
1890         case 0x03: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SWISS;      break;
1891         case 0x04: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SCRIPT;     break;
1892         case 0x05: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_DECORATIVE; break;
1893         default: WINE_FIXME("Unknown family %u\n", family);
1894         }
1895         idx = GET_USHORT(ref, dscr_offset + i * 11 + 3);
1896
1897         if (idx < face_num)
1898         {
1899             memcpy(hlpfile->fonts[i].LogFont.lfFaceName, ref + face_offset + idx * len, min(len, LF_FACESIZE - 1));
1900             hlpfile->fonts[i].LogFont.lfFaceName[min(len, LF_FACESIZE - 1)] = '\0';
1901         }
1902         else
1903         {
1904             WINE_FIXME("Too high face ref (%u/%u)\n", idx, face_num);
1905             strcpy(hlpfile->fonts[i].LogFont.lfFaceName, "Helv");
1906         }
1907         hlpfile->fonts[i].hFont = 0;
1908         hlpfile->fonts[i].color = RGB(ref[dscr_offset + i * 11 + 5],
1909                                       ref[dscr_offset + i * 11 + 6],
1910                                       ref[dscr_offset + i * 11 + 7]);
1911 #define X(b,s) ((flag & (1 << b)) ? "-"s: "")
1912         WINE_TRACE("Font[%d]: flags=%02x%s%s%s%s%s%s pSize=%u family=%u face=%s[%u] color=%08x\n",
1913                    i, flag,
1914                    X(0, "bold"),
1915                    X(1, "italic"),
1916                    X(2, "underline"),
1917                    X(3, "strikeOut"),
1918                    X(4, "dblUnderline"),
1919                    X(5, "smallCaps"),
1920                    ref[dscr_offset + i * 11 + 1],
1921                    family,
1922                    hlpfile->fonts[i].LogFont.lfFaceName, idx,
1923                    GET_UINT(ref, dscr_offset + i * 11 + 5) & 0x00FFFFFF);
1924     }
1925     return TRUE;
1926 }
1927
1928 /***********************************************************************
1929  *
1930  *           HLPFILE_ReadFileToBuffer
1931  */
1932 static BOOL HLPFILE_ReadFileToBuffer(HLPFILE* hlpfile, HFILE hFile)
1933 {
1934     BYTE  header[16], dummy[1];
1935
1936     if (_hread(hFile, header, 16) != 16) {WINE_WARN("header\n"); return FALSE;};
1937
1938     /* sanity checks */
1939     if (GET_UINT(header, 0) != 0x00035F3F)
1940     {WINE_WARN("wrong header\n"); return FALSE;};
1941
1942     hlpfile->file_buffer_size = GET_UINT(header, 12);
1943     hlpfile->file_buffer = HeapAlloc(GetProcessHeap(), 0, hlpfile->file_buffer_size + 1);
1944     if (!hlpfile->file_buffer) return FALSE;
1945
1946     memcpy(hlpfile->file_buffer, header, 16);
1947     if (_hread(hFile, hlpfile->file_buffer + 16, hlpfile->file_buffer_size - 16) !=hlpfile->file_buffer_size - 16)
1948     {WINE_WARN("filesize1\n"); return FALSE;};
1949
1950     if (_hread(hFile, dummy, 1) != 0) WINE_WARN("filesize2\n");
1951
1952     hlpfile->file_buffer[hlpfile->file_buffer_size] = '\0'; /* FIXME: was '0', sounds backwards to me */
1953
1954     return TRUE;
1955 }
1956
1957 /***********************************************************************
1958  *
1959  *           HLPFILE_SystemCommands
1960  */
1961 static BOOL HLPFILE_SystemCommands(HLPFILE* hlpfile)
1962 {
1963     BYTE *buf, *ptr, *end;
1964     HLPFILE_MACRO *macro, **m;
1965     LPSTR p;
1966     unsigned short magic, minor, major, flags;
1967
1968     hlpfile->lpszTitle = NULL;
1969
1970     if (!HLPFILE_FindSubFile(hlpfile, "|SYSTEM", &buf, &end)) return FALSE;
1971
1972     magic = GET_USHORT(buf + 9, 0);
1973     minor = GET_USHORT(buf + 9, 2);
1974     major = GET_USHORT(buf + 9, 4);
1975     /* gen date on 4 bytes */
1976     flags = GET_USHORT(buf + 9, 10);
1977     WINE_TRACE("Got system header: magic=%04x version=%d.%d flags=%04x\n",
1978                magic, major, minor, flags);
1979     if (magic != 0x036C || major != 1)
1980     {WINE_WARN("Wrong system header\n"); return FALSE;}
1981     if (minor <= 16)
1982     {
1983         hlpfile->tbsize = 0x800;
1984         hlpfile->compressed = 0;
1985     }
1986     else if (flags == 0)
1987     {
1988         hlpfile->tbsize = 0x1000;
1989         hlpfile->compressed = 0;
1990     }
1991     else if (flags == 4)
1992     {
1993         hlpfile->tbsize = 0x1000;
1994         hlpfile->compressed = 1;
1995     }
1996     else
1997     {
1998         hlpfile->tbsize = 0x800;
1999         hlpfile->compressed = 1;
2000     }
2001
2002     if (hlpfile->compressed)
2003         hlpfile->dsize = 0x4000;
2004     else
2005         hlpfile->dsize = hlpfile->tbsize - 0x0C;
2006
2007     hlpfile->version = minor;
2008     hlpfile->flags = flags;
2009     hlpfile->charset = DEFAULT_CHARSET;
2010
2011     if (hlpfile->version <= 16)
2012     {
2013         char *str = (char*)buf + 0x15;
2014
2015         hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2016         if (!hlpfile->lpszTitle) return FALSE;
2017         strcpy(hlpfile->lpszTitle, str);
2018         WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
2019         /* Nothing more to parse */
2020         return TRUE;
2021     }
2022     for (ptr = buf + 0x15; ptr + 4 <= end; ptr += GET_USHORT(ptr, 2) + 4)
2023     {
2024         char *str = (char*) ptr + 4;
2025         switch (GET_USHORT(ptr, 0))
2026         {
2027         case 1:
2028             if (hlpfile->lpszTitle) {WINE_WARN("title\n"); break;}
2029             hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2030             if (!hlpfile->lpszTitle) return FALSE;
2031             strcpy(hlpfile->lpszTitle, str);
2032             WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
2033             break;
2034
2035         case 2:
2036             if (hlpfile->lpszCopyright) {WINE_WARN("copyright\n"); break;}
2037             hlpfile->lpszCopyright = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2038             if (!hlpfile->lpszCopyright) return FALSE;
2039             strcpy(hlpfile->lpszCopyright, str);
2040             WINE_TRACE("Copyright: %s\n", hlpfile->lpszCopyright);
2041             break;
2042
2043         case 3:
2044             if (GET_USHORT(ptr, 2) != 4) {WINE_WARN("system3\n");break;}
2045             hlpfile->contents_start = GET_UINT(ptr, 4);
2046             WINE_TRACE("Setting contents start at %08lx\n", hlpfile->contents_start);
2047             break;
2048
2049         case 4:
2050             macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + strlen(str) + 1);
2051             if (!macro) break;
2052             p = (char*)macro + sizeof(HLPFILE_MACRO);
2053             strcpy(p, str);
2054             macro->lpszMacro = p;
2055             macro->next = 0;
2056             for (m = &hlpfile->first_macro; *m; m = &(*m)->next);
2057             *m = macro;
2058             break;
2059
2060         case 5:
2061             if (GET_USHORT(ptr, 4 + 4) != 1)
2062                 WINE_FIXME("More than one icon, picking up first\n");
2063             /* 0x16 is sizeof(CURSORICONDIR), see user32/user_private.h */
2064             hlpfile->hIcon = CreateIconFromResourceEx(ptr + 4 + 0x16,
2065                                                       GET_USHORT(ptr, 2) - 0x16, TRUE,
2066                                                       0x30000, 0, 0, 0);
2067             break;
2068
2069         case 6:
2070             if (GET_USHORT(ptr, 2) != 90) {WINE_WARN("system6\n");break;}
2071
2072             if (hlpfile->windows) 
2073                 hlpfile->windows = HeapReAlloc(GetProcessHeap(), 0, hlpfile->windows, 
2074                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
2075             else 
2076                 hlpfile->windows = HeapAlloc(GetProcessHeap(), 0, 
2077                                            sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
2078             
2079             if (hlpfile->windows)
2080             {
2081                 unsigned flags = GET_USHORT(ptr, 4);
2082                 HLPFILE_WINDOWINFO* wi = &hlpfile->windows[hlpfile->numWindows - 1];
2083
2084                 if (flags & 0x0001) strcpy(wi->type, &str[2]);
2085                 else wi->type[0] = '\0';
2086                 if (flags & 0x0002) strcpy(wi->name, &str[12]);
2087                 else wi->name[0] = '\0';
2088                 if (flags & 0x0004) strcpy(wi->caption, &str[21]);
2089                 else lstrcpynA(wi->caption, hlpfile->lpszTitle, sizeof(wi->caption));
2090                 wi->origin.x = (flags & 0x0008) ? GET_USHORT(ptr, 76) : CW_USEDEFAULT;
2091                 wi->origin.y = (flags & 0x0010) ? GET_USHORT(ptr, 78) : CW_USEDEFAULT;
2092                 wi->size.cx = (flags & 0x0020) ? GET_USHORT(ptr, 80) : CW_USEDEFAULT;
2093                 wi->size.cy = (flags & 0x0040) ? GET_USHORT(ptr, 82) : CW_USEDEFAULT;
2094                 wi->style = (flags & 0x0080) ? GET_USHORT(ptr, 84) : SW_SHOW;
2095                 wi->win_style = WS_OVERLAPPEDWINDOW;
2096                 wi->sr_color = (flags & 0x0100) ? GET_UINT(ptr, 86) : 0xFFFFFF;
2097                 wi->nsr_color = (flags & 0x0200) ? GET_UINT(ptr, 90) : 0xFFFFFF;
2098                 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",
2099                            flags & 0x0001 ? 'T' : 't',
2100                            flags & 0x0002 ? 'N' : 'n',
2101                            flags & 0x0004 ? 'C' : 'c',
2102                            flags & 0x0008 ? 'X' : 'x',
2103                            flags & 0x0010 ? 'Y' : 'y',
2104                            flags & 0x0020 ? 'W' : 'w',
2105                            flags & 0x0040 ? 'H' : 'h',
2106                            flags & 0x0080 ? 'S' : 's',
2107                            wi->type, wi->name, wi->caption, wi->origin.x, wi->origin.y,
2108                            wi->size.cx, wi->size.cy);
2109             }
2110             break;
2111         case 8:
2112             WINE_WARN("Citation: '%s'\n", ptr + 4);
2113             break;
2114         case 11:
2115             hlpfile->charset = ptr[4];
2116             WINE_TRACE("Charset: %d\n", hlpfile->charset);
2117             break;
2118         default:
2119             WINE_WARN("Unsupported SystemRecord[%d]\n", GET_USHORT(ptr, 0));
2120         }
2121     }
2122     if (!hlpfile->lpszTitle)
2123         hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1);
2124     return TRUE;
2125 }
2126
2127 /***********************************************************************
2128  *
2129  *           HLPFILE_GetContext
2130  */
2131 static BOOL HLPFILE_GetContext(HLPFILE *hlpfile)
2132 {
2133     BYTE                *cbuf, *cend;
2134     unsigned            clen;
2135
2136     if (!HLPFILE_FindSubFile(hlpfile, "|CONTEXT",  &cbuf, &cend))
2137     {WINE_WARN("context0\n"); return FALSE;}
2138
2139     clen = cend - cbuf;
2140     hlpfile->Context = HeapAlloc(GetProcessHeap(), 0, clen);
2141     if (!hlpfile->Context) return FALSE;
2142     memcpy(hlpfile->Context, cbuf, clen);
2143
2144     return TRUE;
2145 }
2146
2147 /***********************************************************************
2148  *
2149  *           HLPFILE_GetKeywords
2150  */
2151 static BOOL HLPFILE_GetKeywords(HLPFILE *hlpfile)
2152 {
2153     BYTE                *cbuf, *cend;
2154     unsigned            clen;
2155
2156     if (!HLPFILE_FindSubFile(hlpfile, "|KWBTREE", &cbuf, &cend)) return FALSE;
2157     clen = cend - cbuf;
2158     hlpfile->kwbtree = HeapAlloc(GetProcessHeap(), 0, clen);
2159     if (!hlpfile->kwbtree) return FALSE;
2160     memcpy(hlpfile->kwbtree, cbuf, clen);
2161
2162     if (!HLPFILE_FindSubFile(hlpfile, "|KWDATA", &cbuf, &cend))
2163     {
2164         WINE_ERR("corrupted help file: kwbtree present but kwdata absent\n");
2165         HeapFree(GetProcessHeap(), 0, hlpfile->kwbtree);
2166         return FALSE;
2167     }
2168     clen = cend - cbuf;
2169     hlpfile->kwdata = HeapAlloc(GetProcessHeap(), 0, clen);
2170     if (!hlpfile->kwdata)
2171     {
2172         HeapFree(GetProcessHeap(), 0, hlpfile->kwdata);
2173         return FALSE;
2174     }
2175     memcpy(hlpfile->kwdata, cbuf, clen);
2176
2177     return TRUE;
2178 }
2179
2180 /***********************************************************************
2181  *
2182  *           HLPFILE_GetMap
2183  */
2184 static BOOL HLPFILE_GetMap(HLPFILE *hlpfile)
2185 {
2186     BYTE                *cbuf, *cend;
2187     unsigned            entries, i;
2188
2189     if (!HLPFILE_FindSubFile(hlpfile, "|CTXOMAP",  &cbuf, &cend))
2190     {WINE_WARN("no map section\n"); return FALSE;}
2191
2192     entries = GET_USHORT(cbuf, 9);
2193     hlpfile->Map = HeapAlloc(GetProcessHeap(), 0, entries * sizeof(HLPFILE_MAP));
2194     if (!hlpfile->Map) return FALSE;
2195     hlpfile->wMapLen = entries;
2196     for (i = 0; i < entries; i++)
2197     {
2198         hlpfile->Map[i].lMap = GET_UINT(cbuf+11,i*8);
2199         hlpfile->Map[i].offset = GET_UINT(cbuf+11,i*8+4);
2200     }
2201     return TRUE;
2202 }
2203
2204 /***********************************************************************
2205  *
2206  *           HLPFILE_GetTOMap
2207  */
2208 static BOOL HLPFILE_GetTOMap(HLPFILE *hlpfile)
2209 {
2210     BYTE                *cbuf, *cend;
2211     unsigned            clen;
2212
2213     if (!HLPFILE_FindSubFile(hlpfile, "|TOMAP",  &cbuf, &cend))
2214     {WINE_WARN("no tomap section\n"); return FALSE;}
2215
2216     clen = cend - cbuf - 9;
2217     hlpfile->TOMap = HeapAlloc(GetProcessHeap(), 0, clen);
2218     if (!hlpfile->TOMap) return FALSE;
2219     memcpy(hlpfile->TOMap, cbuf+9, clen);
2220     hlpfile->wTOMapLen = clen/4;
2221     return TRUE;
2222 }
2223
2224 /***********************************************************************
2225  *
2226  *           DeleteMacro
2227  */
2228 static void HLPFILE_DeleteMacro(HLPFILE_MACRO* macro)
2229 {
2230     HLPFILE_MACRO*      next;
2231
2232     while (macro)
2233     {
2234         next = macro->next;
2235         HeapFree(GetProcessHeap(), 0, macro);
2236         macro = next;
2237     }
2238 }
2239
2240 /***********************************************************************
2241  *
2242  *           DeletePage
2243  */
2244 static void HLPFILE_DeletePage(HLPFILE_PAGE* page)
2245 {
2246     HLPFILE_PAGE* next;
2247
2248     while (page)
2249     {
2250         next = page->next;
2251         HLPFILE_DeleteMacro(page->first_macro);
2252         HeapFree(GetProcessHeap(), 0, page);
2253         page = next;
2254     }
2255 }
2256
2257 /***********************************************************************
2258  *
2259  *           HLPFILE_FreeHlpFile
2260  */
2261 void HLPFILE_FreeHlpFile(HLPFILE* hlpfile)
2262 {
2263     unsigned i;
2264
2265     if (!hlpfile || --hlpfile->wRefCount > 0) return;
2266
2267     if (hlpfile->next) hlpfile->next->prev = hlpfile->prev;
2268     if (hlpfile->prev) hlpfile->prev->next = hlpfile->next;
2269     else first_hlpfile = hlpfile->next;
2270
2271     if (hlpfile->numFonts)
2272     {
2273         for (i = 0; i < hlpfile->numFonts; i++)
2274         {
2275             DeleteObject(hlpfile->fonts[i].hFont);
2276         }
2277         HeapFree(GetProcessHeap(), 0, hlpfile->fonts);
2278     }
2279
2280     if (hlpfile->numBmps)
2281     {
2282         for (i = 0; i < hlpfile->numBmps; i++)
2283         {
2284             DeleteObject(hlpfile->bmps[i]);
2285         }
2286         HeapFree(GetProcessHeap(), 0, hlpfile->bmps);
2287     }
2288
2289     HLPFILE_DeletePage(hlpfile->first_page);
2290     HLPFILE_DeleteMacro(hlpfile->first_macro);
2291
2292     DestroyIcon(hlpfile->hIcon);
2293     if (hlpfile->numWindows)    HeapFree(GetProcessHeap(), 0, hlpfile->windows);
2294     HeapFree(GetProcessHeap(), 0, hlpfile->Context);
2295     HeapFree(GetProcessHeap(), 0, hlpfile->Map);
2296     HeapFree(GetProcessHeap(), 0, hlpfile->lpszTitle);
2297     HeapFree(GetProcessHeap(), 0, hlpfile->lpszCopyright);
2298     HeapFree(GetProcessHeap(), 0, hlpfile->file_buffer);
2299     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2300     HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2301     HeapFree(GetProcessHeap(), 0, hlpfile->topic_map);
2302     HeapFree(GetProcessHeap(), 0, hlpfile->help_on_file);
2303     HeapFree(GetProcessHeap(), 0, hlpfile);
2304 }
2305
2306 /***********************************************************************
2307  *
2308  *           HLPFILE_UncompressLZ77_Phrases
2309  */
2310 static BOOL HLPFILE_UncompressLZ77_Phrases(HLPFILE* hlpfile)
2311 {
2312     UINT i, num, dec_size, head_size;
2313     BYTE *buf, *end;
2314
2315     if (!HLPFILE_FindSubFile(hlpfile, "|Phrases", &buf, &end)) return FALSE;
2316
2317     if (hlpfile->version <= 16)
2318         head_size = 13;
2319     else
2320         head_size = 17;
2321
2322     num = hlpfile->num_phrases = GET_USHORT(buf, 9);
2323     if (buf + 2 * num + 0x13 >= end) {WINE_WARN("1a\n"); return FALSE;};
2324
2325     if (hlpfile->version <= 16)
2326         dec_size = end - buf - 15 - 2 * num;
2327     else
2328         dec_size = HLPFILE_UncompressedLZ77_Size(buf + 0x13 + 2 * num, end);
2329
2330     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2331     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2332     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2333     {
2334         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2335         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2336         return FALSE;
2337     }
2338
2339     for (i = 0; i <= num; i++)
2340         hlpfile->phrases_offsets[i] = GET_USHORT(buf, head_size + 2 * i) - 2 * num - 2;
2341
2342     if (hlpfile->version <= 16)
2343         memcpy(hlpfile->phrases_buffer, buf + 15 + 2*num, dec_size);
2344     else
2345         HLPFILE_UncompressLZ77(buf + 0x13 + 2 * num, end, (BYTE*)hlpfile->phrases_buffer);
2346
2347     hlpfile->hasPhrases = TRUE;
2348     return TRUE;
2349 }
2350
2351 /***********************************************************************
2352  *
2353  *           HLPFILE_Uncompress_Phrases40
2354  */
2355 static BOOL HLPFILE_Uncompress_Phrases40(HLPFILE* hlpfile)
2356 {
2357     UINT num;
2358     INT dec_size, cpr_size;
2359     BYTE *buf_idx, *end_idx;
2360     BYTE *buf_phs, *end_phs;
2361     ULONG* ptr, mask = 0;
2362     unsigned int i;
2363     unsigned short bc, n;
2364
2365     if (!HLPFILE_FindSubFile(hlpfile, "|PhrIndex", &buf_idx, &end_idx) ||
2366         !HLPFILE_FindSubFile(hlpfile, "|PhrImage", &buf_phs, &end_phs)) return FALSE;
2367
2368     ptr = (ULONG*)(buf_idx + 9 + 28);
2369     bc = GET_USHORT(buf_idx, 9 + 24) & 0x0F;
2370     num = hlpfile->num_phrases = GET_USHORT(buf_idx, 9 + 4);
2371
2372     WINE_TRACE("Index: Magic=%08x #entries=%u CpsdSize=%u PhrImgSize=%u\n"
2373                "\tPhrImgCprsdSize=%u 0=%u bc=%x ukn=%x\n",
2374                GET_UINT(buf_idx, 9 + 0),
2375                GET_UINT(buf_idx, 9 + 4),
2376                GET_UINT(buf_idx, 9 + 8),
2377                GET_UINT(buf_idx, 9 + 12),
2378                GET_UINT(buf_idx, 9 + 16),
2379                GET_UINT(buf_idx, 9 + 20),
2380                GET_USHORT(buf_idx, 9 + 24),
2381                GET_USHORT(buf_idx, 9 + 26));
2382
2383     dec_size = GET_UINT(buf_idx, 9 + 12);
2384     cpr_size = GET_UINT(buf_idx, 9 + 16);
2385
2386     if (dec_size != cpr_size &&
2387         dec_size != HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs))
2388     {
2389         WINE_WARN("size mismatch %u %u\n",
2390                   dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2391         dec_size = max(dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2392     }
2393
2394     hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
2395     hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
2396     if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2397     {
2398         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
2399         HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2400         return FALSE;
2401     }
2402
2403 #define getbit() ((mask <<= 1) ? (*ptr & mask) != 0: (*++ptr & (mask=1)) != 0)
2404
2405     hlpfile->phrases_offsets[0] = 0;
2406     ptr--; /* as we'll first increment ptr because mask is 0 on first getbit() call */
2407     for (i = 0; i < num; i++)
2408     {
2409         for (n = 1; getbit(); n += 1 << bc);
2410         if (getbit()) n++;
2411         if (bc > 1 && getbit()) n += 2;
2412         if (bc > 2 && getbit()) n += 4;
2413         if (bc > 3 && getbit()) n += 8;
2414         if (bc > 4 && getbit()) n += 16;
2415         hlpfile->phrases_offsets[i + 1] = hlpfile->phrases_offsets[i] + n;
2416     }
2417 #undef getbit
2418
2419     if (dec_size == cpr_size)
2420         memcpy(hlpfile->phrases_buffer, buf_phs + 9, dec_size);
2421     else
2422         HLPFILE_UncompressLZ77(buf_phs + 9, end_phs, (BYTE*)hlpfile->phrases_buffer);
2423
2424     hlpfile->hasPhrases40 = TRUE;
2425     return TRUE;
2426 }
2427
2428 /***********************************************************************
2429  *
2430  *           HLPFILE_Uncompress_Topic
2431  */
2432 static BOOL HLPFILE_Uncompress_Topic(HLPFILE* hlpfile)
2433 {
2434     BYTE *buf, *ptr, *end, *newptr;
2435     unsigned int i, newsize = 0;
2436     unsigned int topic_size;
2437
2438     if (!HLPFILE_FindSubFile(hlpfile, "|TOPIC", &buf, &end))
2439     {WINE_WARN("topic0\n"); return FALSE;}
2440
2441     buf += 9; /* Skip file header */
2442     topic_size = end - buf;
2443     if (hlpfile->compressed)
2444     {
2445         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2446
2447         for (i = 0; i < hlpfile->topic_maplen; i++)
2448         {
2449             ptr = buf + i * hlpfile->tbsize;
2450
2451             /* I don't know why, it's necessary for printman.hlp */
2452             if (ptr + 0x44 > end) ptr = end - 0x44;
2453
2454             newsize += HLPFILE_UncompressedLZ77_Size(ptr + 0xc, min(end, ptr + hlpfile->tbsize));
2455         }
2456
2457         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2458                                        hlpfile->topic_maplen * sizeof(hlpfile->topic_map[0]) + newsize);
2459         if (!hlpfile->topic_map) return FALSE;
2460         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2461         hlpfile->topic_end = newptr + newsize;
2462
2463         for (i = 0; i < hlpfile->topic_maplen; i++)
2464         {
2465             ptr = buf + i * hlpfile->tbsize;
2466             if (ptr + 0x44 > end) ptr = end - 0x44;
2467
2468             hlpfile->topic_map[i] = newptr;
2469             newptr = HLPFILE_UncompressLZ77(ptr + 0xc, min(end, ptr + hlpfile->tbsize), newptr);
2470         }
2471     }
2472     else
2473     {
2474         /* basically, we need to copy the TopicBlockSize byte pages
2475          * (removing the first 0x0C) in one single area in memory
2476          */
2477         hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2478         hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
2479                                        hlpfile->topic_maplen * (sizeof(hlpfile->topic_map[0]) + hlpfile->dsize));
2480         if (!hlpfile->topic_map) return FALSE;
2481         newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
2482         hlpfile->topic_end = newptr + topic_size;
2483
2484         for (i = 0; i < hlpfile->topic_maplen; i++)
2485         {
2486             hlpfile->topic_map[i] = newptr + i * hlpfile->dsize;
2487             memcpy(hlpfile->topic_map[i], buf + i * hlpfile->tbsize + 0x0C, hlpfile->dsize);
2488         }
2489     }
2490     return TRUE;
2491 }
2492
2493 /***********************************************************************
2494  *
2495  *           HLPFILE_AddPage
2496  */
2497 static BOOL HLPFILE_AddPage(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned ref, unsigned offset)
2498 {
2499     HLPFILE_PAGE* page;
2500     const BYTE*   title;
2501     UINT          titlesize, blocksize, datalen;
2502     char*         ptr;
2503     HLPFILE_MACRO*macro;
2504
2505     blocksize = GET_UINT(buf, 0);
2506     datalen = GET_UINT(buf, 0x10);
2507     title = buf + datalen;
2508     if (title > end) {WINE_WARN("page2\n"); return FALSE;};
2509
2510     titlesize = GET_UINT(buf, 4);
2511     page = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_PAGE) + titlesize + 1);
2512     if (!page) return FALSE;
2513     page->lpszTitle = (char*)page + sizeof(HLPFILE_PAGE);
2514
2515     if (titlesize > blocksize - datalen)
2516     {
2517         /* need to decompress */
2518         if (hlpfile->hasPhrases)
2519             HLPFILE_Uncompress2(hlpfile, title, end, (BYTE*)page->lpszTitle, (BYTE*)page->lpszTitle + titlesize);
2520         else if (hlpfile->hasPhrases40)
2521             HLPFILE_Uncompress3(hlpfile, page->lpszTitle, page->lpszTitle + titlesize, title, end);
2522         else
2523         {
2524             WINE_FIXME("Text size is too long, splitting\n");
2525             titlesize = blocksize - datalen;
2526             memcpy(page->lpszTitle, title, titlesize);
2527         }
2528     }
2529     else
2530         memcpy(page->lpszTitle, title, titlesize);
2531
2532     page->lpszTitle[titlesize] = '\0';
2533
2534     if (hlpfile->first_page)
2535     {
2536         hlpfile->last_page->next = page;
2537         page->prev = hlpfile->last_page;
2538         hlpfile->last_page = page;
2539     }
2540     else
2541     {
2542         hlpfile->first_page = page;
2543         hlpfile->last_page = page;
2544         page->prev = NULL;
2545     }
2546
2547     page->file            = hlpfile;
2548     page->next            = NULL;
2549     page->first_macro     = NULL;
2550     page->first_link      = NULL;
2551     page->wNumber         = GET_UINT(buf, 0x21);
2552     page->offset          = offset;
2553     page->reference       = ref;
2554
2555     page->browse_bwd = GET_UINT(buf, 0x19);
2556     page->browse_fwd = GET_UINT(buf, 0x1D);
2557
2558     if (hlpfile->version <= 16)
2559     {
2560         if (page->browse_bwd == 0xFFFF || page->browse_bwd == 0xFFFFFFFF)
2561             page->browse_bwd = 0xFFFFFFFF;
2562         else
2563             page->browse_bwd = hlpfile->TOMap[page->browse_bwd];
2564
2565         if (page->browse_fwd == 0xFFFF || page->browse_fwd == 0xFFFFFFFF)
2566             page->browse_fwd = 0xFFFFFFFF;
2567         else
2568             page->browse_fwd = hlpfile->TOMap[page->browse_fwd];
2569     }
2570
2571     WINE_TRACE("Added page[%d]: title='%s' %08x << %08x >> %08x\n",
2572                page->wNumber, page->lpszTitle,
2573                page->browse_bwd, page->offset, page->browse_fwd);
2574
2575     /* now load macros */
2576     ptr = page->lpszTitle + strlen(page->lpszTitle) + 1;
2577     while (ptr < page->lpszTitle + titlesize)
2578     {
2579         unsigned len = strlen(ptr);
2580         char*    macro_str;
2581
2582         WINE_TRACE("macro: %s\n", ptr);
2583         macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + len + 1);
2584         macro->lpszMacro = macro_str = (char*)(macro + 1);
2585         memcpy(macro_str, ptr, len + 1);
2586         /* FIXME: shall we really link macro in reverse order ??
2587          * may produce strange results when played at page opening
2588          */
2589         macro->next = page->first_macro;
2590         page->first_macro = macro;
2591         ptr += len + 1;
2592     }
2593
2594     return TRUE;
2595 }
2596
2597 /***********************************************************************
2598  *
2599  *           HLPFILE_SkipParagraph
2600  */
2601 static BOOL HLPFILE_SkipParagraph(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned* len)
2602 {
2603     const BYTE  *tmp;
2604
2605     if (!hlpfile->first_page) {WINE_WARN("no page\n"); return FALSE;};
2606     if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
2607
2608     tmp = buf + 0x15;
2609     if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
2610     {
2611         fetch_long(&tmp);
2612         *len = fetch_ushort(&tmp);
2613     }
2614     else *len = end-buf-15;
2615
2616     return TRUE;
2617 }
2618
2619 /***********************************************************************
2620  *
2621  *           HLPFILE_DoReadHlpFile
2622  */
2623 static BOOL HLPFILE_DoReadHlpFile(HLPFILE *hlpfile, LPCSTR lpszPath)
2624 {
2625     BOOL        ret;
2626     HFILE       hFile;
2627     OFSTRUCT    ofs;
2628     BYTE*       buf;
2629     DWORD       ref = 0x0C;
2630     unsigned    index, old_index, offset, len, offs, topicoffset;
2631
2632     hFile = OpenFile(lpszPath, &ofs, OF_READ);
2633     if (hFile == HFILE_ERROR) return FALSE;
2634
2635     ret = HLPFILE_ReadFileToBuffer(hlpfile, hFile);
2636     _lclose(hFile);
2637     if (!ret) return FALSE;
2638
2639     if (!HLPFILE_SystemCommands(hlpfile)) return FALSE;
2640
2641     if (hlpfile->version <= 16 && !HLPFILE_GetTOMap(hlpfile)) return FALSE;
2642
2643     /* load phrases support */
2644     if (!HLPFILE_UncompressLZ77_Phrases(hlpfile))
2645         HLPFILE_Uncompress_Phrases40(hlpfile);
2646
2647     if (!HLPFILE_Uncompress_Topic(hlpfile)) return FALSE;
2648     if (!HLPFILE_ReadFont(hlpfile)) return FALSE;
2649
2650     old_index = -1;
2651     offs = 0;
2652     do
2653     {
2654         BYTE*   end;
2655
2656         if (hlpfile->version <= 16)
2657         {
2658             index  = (ref - 0x0C) / hlpfile->dsize;
2659             offset = (ref - 0x0C) % hlpfile->dsize;
2660         }
2661         else
2662         {
2663             index  = (ref - 0x0C) >> 14;
2664             offset = (ref - 0x0C) & 0x3FFF;
2665         }
2666
2667         if (hlpfile->version <= 16 && index != old_index && old_index != -1)
2668         {
2669             /* we jumped to the next block, adjust pointers */
2670             ref -= 12;
2671             offset -= 12;
2672         }
2673
2674         WINE_TRACE("ref=%08x => [%u/%u]\n", ref, index, offset);
2675
2676         if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
2677         buf = hlpfile->topic_map[index] + offset;
2678         if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
2679         end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
2680         if (index != old_index) {offs = 0; old_index = index;}
2681
2682         switch (buf[0x14])
2683         {
2684         case 0x02:
2685             if (hlpfile->version <= 16)
2686                 topicoffset = ref + index * 12;
2687             else
2688                 topicoffset = index * 0x8000 + offs;
2689             if (!HLPFILE_AddPage(hlpfile, buf, end, ref, topicoffset)) return FALSE;
2690             break;
2691
2692         case 0x01:
2693         case 0x20:
2694         case 0x23:
2695             if (!HLPFILE_SkipParagraph(hlpfile, buf, end, &len)) return FALSE;
2696             offs += len;
2697             break;
2698
2699         default:
2700             WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
2701         }
2702
2703         if (hlpfile->version <= 16)
2704         {
2705             ref += GET_UINT(buf, 0xc);
2706             if (GET_UINT(buf, 0xc) == 0)
2707                 break;
2708         }
2709         else
2710             ref = GET_UINT(buf, 0xc);
2711     } while (ref != 0xffffffff);
2712
2713     HLPFILE_GetKeywords(hlpfile);
2714     HLPFILE_GetMap(hlpfile);
2715     if (hlpfile->version <= 16) return TRUE;
2716     return HLPFILE_GetContext(hlpfile);
2717 }
2718
2719 /***********************************************************************
2720  *
2721  *           HLPFILE_ReadHlpFile
2722  */
2723 HLPFILE *HLPFILE_ReadHlpFile(LPCSTR lpszPath)
2724 {
2725     HLPFILE*      hlpfile;
2726
2727     for (hlpfile = first_hlpfile; hlpfile; hlpfile = hlpfile->next)
2728     {
2729         if (!strcmp(lpszPath, hlpfile->lpszPath))
2730         {
2731             hlpfile->wRefCount++;
2732             return hlpfile;
2733         }
2734     }
2735
2736     hlpfile = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2737                         sizeof(HLPFILE) + strlen(lpszPath) + 1);
2738     if (!hlpfile) return 0;
2739
2740     hlpfile->lpszPath           = (char*)hlpfile + sizeof(HLPFILE);
2741     hlpfile->contents_start     = 0xFFFFFFFF;
2742     hlpfile->next               = first_hlpfile;
2743     hlpfile->wRefCount          = 1;
2744
2745     strcpy(hlpfile->lpszPath, lpszPath);
2746
2747     first_hlpfile = hlpfile;
2748     if (hlpfile->next) hlpfile->next->prev = hlpfile;
2749
2750     if (!HLPFILE_DoReadHlpFile(hlpfile, lpszPath))
2751     {
2752         HLPFILE_FreeHlpFile(hlpfile);
2753         hlpfile = 0;
2754     }
2755
2756     return hlpfile;
2757 }