hlpfile.c 87.3 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3
/*
 * Help Viewer
 *
4
 * Copyright    1996 Ulrich Schmid
5
 *              2002, 2008 Eric Pouech
6
 *              2007 Kirill K. Smirnov
7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
Alexandre Julliard's avatar
Alexandre Julliard committed
21 22
 */

23
#include <stdarg.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
24
#include <stdio.h>
25
#include <string.h>
26 27

#include "windef.h"
28 29
#include "winbase.h"
#include "wingdi.h"
Eric Pouech's avatar
Eric Pouech committed
30
#include "winuser.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
31 32
#include "winhelp.h"

33 34 35
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(winhelp);
Alexandre Julliard's avatar
Alexandre Julliard committed
36

37 38 39 40 41 42 43 44 45 46 47 48 49 50
static inline unsigned short GET_USHORT(const BYTE* buffer, unsigned i)
{
    return (BYTE)buffer[i] + 0x100 * (BYTE)buffer[i + 1];
}

static inline short GET_SHORT(const BYTE* buffer, unsigned i)
{
    return (BYTE)buffer[i] + 0x100 * (signed char)buffer[i+1];
}

static inline unsigned GET_UINT(const BYTE* buffer, unsigned i)
{
    return GET_USHORT(buffer, i) + 0x10000 * GET_USHORT(buffer, i + 2);
}
Alexandre Julliard's avatar
Alexandre Julliard committed
51 52 53

static HLPFILE *first_hlpfile = 0;

54

55 56 57 58 59 60 61 62 63
/**************************************************************************
 * HLPFILE_BPTreeSearch
 *
 * Searches for an element in B+ tree
 *
 * PARAMS
 *     buf        [I] pointer to the embedded file structured as a B+ tree
 *     key        [I] pointer to data to find
 *     comp       [I] compare function
64
 *
65 66
 * RETURNS
 *     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 73 74 75 76 77 78
    unsigned magic;
    unsigned page_size;
    unsigned cur_page;
    unsigned level;
    BYTE *pages, *ptr, *newptr;
    int i, entries;
    int ret;
79

80 81
    magic = GET_USHORT(buf, 9);
    if (magic != 0x293B)
82
    {
83 84 85 86 87 88 89 90 91 92 93 94 95
        WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
        return NULL;
    }
    page_size = GET_USHORT(buf, 9+4);
    cur_page  = GET_USHORT(buf, 9+26);
    level     = GET_USHORT(buf, 9+32);
    pages     = buf + 9 + 38;
    while (--level > 0)
    {
        ptr = pages + cur_page*page_size;
        entries = GET_SHORT(ptr, 2);
        ptr += 6;
        for (i = 0; i < entries; i++)
96
        {
97 98
            if (comp(ptr, key, 0, (void **)&newptr) > 0) break;
            ptr = newptr;
99
        }
100
        cur_page = GET_USHORT(ptr-2, 0);
101
    }
102 103 104 105 106 107 108 109 110 111 112
    ptr = pages + cur_page*page_size;
    entries = GET_SHORT(ptr, 2);
    ptr += 8;
    for (i = 0; i < entries; i++)
    {
        ret = comp(ptr, key, 1, (void **)&newptr);
        if (ret == 0) return ptr;
        if (ret > 0) return NULL;
        ptr = newptr;
    }
    return NULL;
113 114
}

115
/**************************************************************************
116
 * HLPFILE_BPTreeEnum
117
 *
118
 * Enumerates elements in B+ tree.
119
 *
120 121 122 123
 * PARAMS
 *     buf        [I]  pointer to the embedded file structured as a B+ tree
 *     cb         [I]  compare function
 *     cookie     [IO] cookie for cb function
124
 */
125
void HLPFILE_BPTreeEnum(BYTE* buf, HLPFILE_BPTreeCallback cb, void* cookie)
126
{
127 128 129 130 131 132
    unsigned magic;
    unsigned page_size;
    unsigned cur_page;
    unsigned level;
    BYTE *pages, *ptr, *newptr;
    int i, entries;
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    magic = GET_USHORT(buf, 9);
    if (magic != 0x293B)
    {
        WINE_ERR("Invalid magic in B+ tree: 0x%x\n", magic);
        return;
    }
    page_size = GET_USHORT(buf, 9+4);
    cur_page  = GET_USHORT(buf, 9+26);
    level     = GET_USHORT(buf, 9+32);
    pages     = buf + 9 + 38;
    while (--level > 0)
    {
        ptr = pages + cur_page*page_size;
        cur_page = GET_USHORT(ptr, 4);
    }
    while (cur_page != 0xFFFF)
    {
        ptr = pages + cur_page*page_size;
        entries = GET_SHORT(ptr, 2);
        ptr += 8;
        for (i = 0; i < entries; i++)
        {
            cb(ptr, (void **)&newptr, cookie);
            ptr = newptr;
        }
        cur_page = GET_USHORT(pages+cur_page*page_size, 6);
    }
161 162
}

163

Alexandre Julliard's avatar
Alexandre Julliard committed
164 165
/***********************************************************************
 *
166
 *           HLPFILE_UncompressedLZ77_Size
Alexandre Julliard's avatar
Alexandre Julliard committed
167
 */
168
static INT HLPFILE_UncompressedLZ77_Size(const BYTE *ptr, const BYTE *end)
Alexandre Julliard's avatar
Alexandre Julliard committed
169
{
170
    int  i, newsize = 0;
171

172
    while (ptr < end)
Alexandre Julliard's avatar
Alexandre Julliard committed
173
    {
174 175 176 177 178 179 180 181 182 183 184 185
        int mask = *ptr++;
        for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
	{
            if (mask & 1)
	    {
                int code = GET_USHORT(ptr, 0);
                int len  = 3 + (code >> 12);
                newsize += len;
                ptr     += 2;
	    }
            else newsize++, ptr++;
	}
Alexandre Julliard's avatar
Alexandre Julliard committed
186
    }
187

188
    return newsize;
Alexandre Julliard's avatar
Alexandre Julliard committed
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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        int mask = *ptr++;
        for (i = 0; i < 8 && ptr < end; i++, mask >>= 1)
	{
            if (mask & 1)
	    {
                int code   = GET_USHORT(ptr, 0);
                int len    = 3 + (code >> 12);
                int offset = code & 0xfff;
                /*
                 * We must copy byte-by-byte here. We cannot use memcpy nor
                 * memmove here. Just example:
                 * a[]={1,2,3,4,5,6,7,8,9,10}
                 * newptr=a+2;
                 * offset=1;
                 * We expect:
                 * {1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 11, 12}
                 */
                for (; len>0; len--, newptr++) *newptr = *(newptr-offset-1);
                ptr    += 2;
	    }
            else *newptr++ = *ptr++;
	}
223 224
    }

225
    return newptr;
226 227
}

228 229
/***********************************************************************
 *
230
 *           HLPFILE_Uncompress2
231 232
 */

233 234 235 236 237
static void HLPFILE_Uncompress2(HLPFILE* hlpfile, const BYTE *ptr, const BYTE *end, BYTE *newptr, const BYTE *newend)
{
    BYTE *phptr, *phend;
    UINT code;
    UINT index;
238

239
    while (ptr < end && newptr < newend)
240
    {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        if (!*ptr || *ptr >= 0x10)
            *newptr++ = *ptr++;
        else
	{
            code  = 0x100 * ptr[0] + ptr[1];
            index = (code - 0x100) / 2;

            phptr = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index];
            phend = (BYTE*)hlpfile->phrases_buffer + hlpfile->phrases_offsets[index + 1];

            if (newptr + (phend - phptr) > newend)
            {
                WINE_FIXME("buffer overflow %p > %p for %lu bytes\n",
                           newptr, newend, (SIZE_T)(phend - phptr));
                return;
            }
            memcpy(newptr, phptr, phend - phptr);
            newptr += phend - phptr;
            if (code & 1) *newptr++ = ' ';

            ptr += 2;
	}
263
    }
264
    if (newptr > newend) WINE_FIXME("buffer overflow %p > %p\n", newptr, newend);
265 266
}

267 268 269
/******************************************************************
 *		HLPFILE_Uncompress3
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
270 271
 *
 */
272 273
static BOOL HLPFILE_Uncompress3(HLPFILE* hlpfile, char* dst, const char* dst_end,
                                const BYTE* src, const BYTE* src_end)
Alexandre Julliard's avatar
Alexandre Julliard committed
274
{
275
    unsigned int idx, len;
276

277
    for (; src < src_end; src++)
Alexandre Julliard's avatar
Alexandre Julliard committed
278
    {
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        if ((*src & 1) == 0)
        {
            idx = *src / 2;
            if (idx > hlpfile->num_phrases)
            {
                WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
                len = 0;
            }
            else
            {
                len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
                if (dst + len <= dst_end)
                    memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
            }
        }
        else if ((*src & 0x03) == 0x01)
        {
            idx = (*src + 1) * 64;
            idx += *++src;
            if (idx > hlpfile->num_phrases)
            {
                WINE_ERR("index in phrases %d/%d\n", idx, hlpfile->num_phrases);
                len = 0;
            }
            else
            {
                len = hlpfile->phrases_offsets[idx + 1] - hlpfile->phrases_offsets[idx];
                if (dst + len <= dst_end)
                    memcpy(dst, &hlpfile->phrases_buffer[hlpfile->phrases_offsets[idx]], len);
            }
        }
        else if ((*src & 0x07) == 0x03)
        {
            len = (*src / 8) + 1;
            if (dst + len <= dst_end)
                memcpy(dst, src + 1, len);
            src += len;
        }
        else
        {
            len = (*src / 16) + 1;
            if (dst + len <= dst_end)
                memset(dst, ((*src & 0x0F) == 0x07) ? ' ' : 0, len);
        }
        dst += len;
Alexandre Julliard's avatar
Alexandre Julliard committed
324
    }
325 326 327

    if (dst > dst_end) WINE_ERR("buffer overflow (%p > %p)\n", dst, dst_end);
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
328
}
329

330 331 332
/******************************************************************
 *		HLPFILE_UncompressRLE
 *
Alexandre Julliard's avatar
Alexandre Julliard committed
333 334
 *
 */
335
static void HLPFILE_UncompressRLE(const BYTE* src, const BYTE* end, BYTE* dst, unsigned dstsz)
Alexandre Julliard's avatar
Alexandre Julliard committed
336
{
337 338
    BYTE        ch;
    BYTE*       sdst = dst + dstsz;
339

340
    while (src < end)
341
    {
342 343
        ch = *src++;
        if (ch & 0x80)
344
        {
345 346 347 348
            ch &= 0x7F;
            if (dst + ch <= sdst)
                memcpy(dst, src, ch);
            src += ch;
349
        }
350 351 352 353 354 355 356
        else
        {
            if (dst + ch <= sdst)
                memset(dst, (char)*src, ch);
            src++;
        }
        dst += ch;
357
    }
358 359 360 361
    if (dst != sdst)
        WINE_WARN("Buffer X-flow: d(%lu) instead of d(%u)\n",
                  (SIZE_T)(dst - (sdst - dstsz)), dstsz);
}
362

Alexandre Julliard's avatar
Alexandre Julliard committed
363

364 365 366 367 368 369 370 371 372
/******************************************************************
 *		HLPFILE_PageByOffset
 *
 *
 */
HLPFILE_PAGE *HLPFILE_PageByOffset(HLPFILE* hlpfile, LONG offset, ULONG* relative)
{
    HLPFILE_PAGE*       page;
    HLPFILE_PAGE*       found;
Eric Pouech's avatar
Eric Pouech committed
373

374
    if (!hlpfile) return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
375

376
    WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, offset);
Alexandre Julliard's avatar
Alexandre Julliard committed
377

378 379 380 381
    if (offset == 0xFFFFFFFF) return NULL;
    page = NULL;

    for (found = NULL, page = hlpfile->first_page; page; page = page->next)
Alexandre Julliard's avatar
Alexandre Julliard committed
382
    {
383 384 385 386 387
        if (page->offset <= offset && (!found || found->offset < page->offset))
        {
            *relative = offset - page->offset;
            found = page;
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
388
    }
389 390 391 392
    if (!found)
        WINE_ERR("Page of offset %u not found in file %s\n",
                 offset, hlpfile->lpszPath);
    return found;
Alexandre Julliard's avatar
Alexandre Julliard committed
393 394 395 396
}

/***********************************************************************
 *
397
 *           HLPFILE_Contents
Alexandre Julliard's avatar
Alexandre Julliard committed
398
 */
399
static HLPFILE_PAGE* HLPFILE_Contents(HLPFILE *hlpfile, ULONG* relative)
Alexandre Julliard's avatar
Alexandre Julliard committed
400
{
401
    HLPFILE_PAGE*       page = NULL;
402

403
    if (!hlpfile) return NULL;
404

405 406 407 408 409 410 411 412
    page = HLPFILE_PageByOffset(hlpfile, hlpfile->contents_start, relative);
    if (!page)
    {
        page = hlpfile->first_page;
        *relative = 0;
    }
    return page;
}
413

414 415 416 417 418 419 420 421 422 423 424
/**************************************************************************
 * comp_PageByHash
 *
 * HLPFILE_BPTreeCompare function for '|CONTEXT' B+ tree file
 *
 */
static int comp_PageByHash(void *p, const void *key,
                           int leaf, void** next)
{
    LONG lKey = (LONG_PTR)key;
    LONG lTest = (INT)GET_UINT(p, 0);
Eric Pouech's avatar
Eric Pouech committed
425

426 427 428 429 430 431
    *next = (char *)p+(leaf?8:6);
    WINE_TRACE("Comparing '%d' with '%d'\n", lKey, lTest);
    if (lTest < lKey) return -1;
    if (lTest > lKey) return 1;
    return 0;
}
432

433 434 435 436 437 438 439
/***********************************************************************
 *
 *           HLPFILE_PageByHash
 */
HLPFILE_PAGE *HLPFILE_PageByHash(HLPFILE* hlpfile, LONG lHash, ULONG* relative)
{
    BYTE *ptr;
Eric Pouech's avatar
Eric Pouech committed
440

441 442
    if (!hlpfile) return NULL;
    if (!lHash) return HLPFILE_Contents(hlpfile, relative);
443

444
    WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lHash);
Alexandre Julliard's avatar
Alexandre Julliard committed
445

446 447 448 449 450 451
    /* For win 3.0 files hash values are really page numbers */
    if (hlpfile->version <= 16)
    {
        if (lHash >= hlpfile->wTOMapLen) return NULL;
        return HLPFILE_PageByOffset(hlpfile, hlpfile->TOMap[lHash], relative);
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
452

453 454 455 456 457 458
    ptr = HLPFILE_BPTreeSearch(hlpfile->Context, LongToPtr(lHash), comp_PageByHash);
    if (!ptr)
    {
        WINE_ERR("Page of hash %x not found in file %s\n", lHash, hlpfile->lpszPath);
        return NULL;
    }
459

460 461
    return HLPFILE_PageByOffset(hlpfile, GET_UINT(ptr, 4), relative);
}
Alexandre Julliard's avatar
Alexandre Julliard committed
462

463 464 465 466 467 468 469
/***********************************************************************
 *
 *           HLPFILE_PageByMap
 */
HLPFILE_PAGE *HLPFILE_PageByMap(HLPFILE* hlpfile, LONG lMap, ULONG* relative)
{
    unsigned int i;
Alexandre Julliard's avatar
Alexandre Julliard committed
470

471
    if (!hlpfile) return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
472

473
    WINE_TRACE("<%s>[%x]\n", hlpfile->lpszPath, lMap);
Alexandre Julliard's avatar
Alexandre Julliard committed
474

475 476 477 478 479
    for (i = 0; i < hlpfile->wMapLen; i++)
    {
        if (hlpfile->Map[i].lMap == lMap)
            return HLPFILE_PageByOffset(hlpfile, hlpfile->Map[i].offset, relative);
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
480

481 482 483
    WINE_ERR("Page of Map %x not found in file %s\n", lMap, hlpfile->lpszPath);
    return NULL;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
484

485 486 487 488 489 490 491 492 493 494
/**************************************************************************
 * comp_FindSubFile
 *
 * HLPFILE_BPTreeCompare function for HLPFILE directory.
 *
 */
static int comp_FindSubFile(void *p, const void *key,
                            int leaf, void** next)
{
    *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);
Alexandre Julliard's avatar
Alexandre Julliard committed
497 498 499 500
}

/***********************************************************************
 *
501
 *           HLPFILE_FindSubFile
Alexandre Julliard's avatar
Alexandre Julliard committed
502
 */
503
static BOOL HLPFILE_FindSubFile(HLPFILE* hlpfile, LPCSTR name, BYTE **subbuf, BYTE **subend)
504
{
505
    BYTE *ptr;
506

507 508 509 510 511 512
    WINE_TRACE("looking for file '%s'\n", name);
    ptr = HLPFILE_BPTreeSearch(hlpfile->file_buffer + GET_UINT(hlpfile->file_buffer, 4),
                               name, comp_FindSubFile);
    if (!ptr) return FALSE;
    *subbuf = hlpfile->file_buffer + GET_UINT(ptr, strlen(name)+1);
    if (*subbuf >= hlpfile->file_buffer + hlpfile->file_buffer_size)
513
    {
514 515
        WINE_ERR("internal file %s does not fit\n", name);
        return FALSE;
516
    }
517 518
    *subend = *subbuf + GET_UINT(*subbuf, 0);
    if (*subend > hlpfile->file_buffer + hlpfile->file_buffer_size)
519
    {
520 521
        WINE_ERR("internal file %s does not fit\n", name);
        return FALSE;
522
    }
523
    if (GET_UINT(*subbuf, 0) < GET_UINT(*subbuf, 4) + 9)
524
    {
525 526
        WINE_ERR("invalid size provided for internal file %s\n", name);
        return FALSE;
527
    }
528 529
    return TRUE;
}
530

531 532 533 534 535 536 537 538
/***********************************************************************
 *
 *           HLPFILE_Hash
 */
LONG HLPFILE_Hash(LPCSTR lpszContext)
{
    LONG lHash = 0;
    CHAR c;
539

540
    while ((c = *lpszContext++))
541
    {
542 543 544 545 546 547 548 549
        CHAR x = 0;
        if (c >= 'A' && c <= 'Z') x = c - 'A' + 17;
        if (c >= 'a' && c <= 'z') x = c - 'a' + 17;
        if (c >= '1' && c <= '9') x = c - '0';
        if (c == '0') x = 10;
        if (c == '.') x = 12;
        if (c == '_') x = 13;
        if (x) lHash = lHash * 43 + x;
550
    }
551
    return lHash;
552 553
}

554
static LONG fetch_long(const BYTE** ptr)
Alexandre Julliard's avatar
Alexandre Julliard committed
555
{
556
    LONG        ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
557

558 559
    if (*(*ptr) & 1)
    {
560
        ret = (*(const ULONG*)(*ptr) - 0x80000000) / 2;
561 562 563 564
        (*ptr) += 4;
    }
    else
    {
565
        ret = (*(const USHORT*)(*ptr) - 0x8000) / 2;
566 567
        (*ptr) += 2;
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
568

569 570
    return ret;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
571

572
static ULONG fetch_ulong(const BYTE** ptr)
573
{
574
    ULONG        ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
575

576 577
    if (*(*ptr) & 1)
    {
578
        ret = *(const ULONG*)(*ptr) / 2;
579 580 581 582
        (*ptr) += 4;
    }
    else
    {
583
        ret = *(const USHORT*)(*ptr) / 2;
584 585 586
        (*ptr) += 2;
    }
    return ret;
587
}    
Alexandre Julliard's avatar
Alexandre Julliard committed
588

589
static short fetch_short(const BYTE** ptr)
590 591 592 593 594
{
    short       ret;

    if (*(*ptr) & 1)
    {
595
        ret = (*(const unsigned short*)(*ptr) - 0x8000) / 2;
596 597 598 599
        (*ptr) += 2;
    }
    else
    {
600
        ret = (*(const unsigned char*)(*ptr) - 0x80) / 2;
601 602 603 604
        (*ptr)++;
    }
    return ret;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
605

606
static unsigned short fetch_ushort(const BYTE** ptr)
607 608
{
    unsigned short ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
609

610 611
    if (*(*ptr) & 1)
    {
612
        ret = *(const unsigned short*)(*ptr) / 2;
613 614 615 616
        (*ptr) += 2;
    }
    else
    {
617
        ret = *(const unsigned char*)(*ptr) / 2;
618 619 620
        (*ptr)++;
    }
    return ret;
Alexandre Julliard's avatar
Alexandre Julliard committed
621 622
}

623
/******************************************************************
624 625 626 627
 *		HLPFILE_DecompressGfx
 *
 * Decompress the data part of a bitmap or a metafile
 */
628 629
static const BYTE*      HLPFILE_DecompressGfx(const BYTE* src, unsigned csz, unsigned sz, BYTE packing,
                                              BYTE** alloc)
630
{
631
    const BYTE* dst;
632 633 634 635 636 637 638 639 640
    BYTE*       tmp;
    unsigned    sz77;

    WINE_TRACE("Unpacking (%d) from %u bytes to %u bytes\n", packing, csz, sz);

    switch (packing)
    {
    case 0: /* uncompressed */
        if (sz != csz)
641
            WINE_WARN("Bogus gfx sizes (uncompressed): %u / %u\n", sz, csz);
642
        dst = src;
643
        *alloc = NULL;
644 645
        break;
    case 1: /* RunLen */
646
        dst = *alloc = HeapAlloc(GetProcessHeap(), 0, sz);
647
        if (!dst) return NULL;
648
        HLPFILE_UncompressRLE(src, src + csz, *alloc, sz);
649 650 651
        break;
    case 2: /* LZ77 */
        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 658 659
        break;
    case 3: /* LZ77 then RLE */
        sz77 = HLPFILE_UncompressedLZ77_Size(src, src + csz);
660
        tmp = HeapAlloc(GetProcessHeap(), 0, sz77);
661 662
        if (!tmp) return FALSE;
        HLPFILE_UncompressLZ77(src, src + csz, tmp);
663
        dst = *alloc = HeapAlloc(GetProcessHeap(), 0, sz);
664 665 666 667 668
        if (!dst)
        {
            HeapFree(GetProcessHeap(), 0, tmp);
            return FALSE;
        }
669
        HLPFILE_UncompressRLE(tmp, tmp + sz77, *alloc, sz);
670 671 672 673 674 675 676 677 678
        HeapFree(GetProcessHeap(), 0, tmp);
        break;
    default:
        WINE_FIXME("Unsupported packing %u\n", packing);
        return NULL;
    }
    return dst;
}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
static BOOL HLPFILE_RtfAddRawString(struct RtfData* rd, const char* str, size_t sz)
{
    if (rd->ptr + sz >= rd->data + rd->allocated)
    {
        char*   new = HeapReAlloc(GetProcessHeap(), 0, rd->data, rd->allocated *= 2);
        if (!new) return FALSE;
        rd->ptr = new + (rd->ptr - rd->data);
        rd->data = new;
    }
    memcpy(rd->ptr, str, sz);
    rd->ptr += sz;

    return TRUE;
}

static BOOL HLPFILE_RtfAddControl(struct RtfData* rd, const char* str)
{
    if (*str == '\\' || *str == '{') rd->in_text = FALSE;
    else if (*str == '}') rd->in_text = TRUE;
    return HLPFILE_RtfAddRawString(rd, str, strlen(str));
}

static BOOL HLPFILE_RtfAddText(struct RtfData* rd, const char* str)
{
    const char* p;
    const char* last;
    const char* replace;
706
    unsigned    rlen;
707 708 709 710 711 712 713 714

    if (!rd->in_text)
    {
        if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
        rd->in_text = TRUE;
    }
    for (last = p = str; *p; p++)
    {
715
        if (*p & 0x80) /* escape non-ASCII chars */
716
        {
717 718 719 720 721 722 723 724 725
            static char         xx[8];
            rlen = sprintf(xx, "\\'%x", *(const BYTE*)p);
            replace = xx;
        }
        else switch (*p)
        {
        case '{':  rlen = 2; replace = "\\{";  break;
        case '}':  rlen = 2; replace = "\\}";  break;
        case '\\': rlen = 2; replace = "\\\\"; break;
726 727 728
        default:   continue;
        }
        if ((p != last && !HLPFILE_RtfAddRawString(rd, last, p - last)) ||
729
            !HLPFILE_RtfAddRawString(rd, replace, rlen)) return FALSE;
730 731 732 733 734
        last = p + 1;
    }
    return HLPFILE_RtfAddRawString(rd, last, p - last);
}

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
/******************************************************************
 *		RtfAddHexBytes
 *
 */
static BOOL HLPFILE_RtfAddHexBytes(struct RtfData* rd, const void* _ptr, unsigned sz)
{
    char        tmp[512];
    unsigned    i, step;
    const BYTE* ptr = _ptr;
    static const char* _2hex = "0123456789abcdef";

    if (!rd->in_text)
    {
        if (!HLPFILE_RtfAddRawString(rd, " ", 1)) return FALSE;
        rd->in_text = TRUE;
    }
    for (; sz; sz -= step)
    {
        step = min(256, sz);
        for (i = 0; i < step; i++)
        {
            tmp[2 * i + 0] = _2hex[*ptr >> 4];
            tmp[2 * i + 1] = _2hex[*ptr++ & 0xF];
        }
        if (!HLPFILE_RtfAddRawString(rd, tmp, 2 * step)) return FALSE;
    }
    return TRUE;
}

764 765
static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
                                             const char* str, unsigned len, LONG hash,
766
                                             BOOL clrChange, BOOL bHotSpot, unsigned wnd);
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

/******************************************************************
 *		HLPFILE_AddHotSpotLinks
 *
 */
static void HLPFILE_AddHotSpotLinks(struct RtfData* rd, HLPFILE* file,
                                    const BYTE* start, ULONG hs_size, ULONG hs_offset)
{
    unsigned    i, hs_num;
    ULONG       hs_macro;
    const char* str;

    if (hs_size == 0 || hs_offset == 0) return;

    start += hs_offset;
    /* always 1 ?? */
    hs_num = GET_USHORT(start, 1);
    hs_macro = GET_UINT(start, 3);

    str = (const char*)start + 7 + 15 * hs_num + hs_macro;
    /* FIXME: should use hs_size to prevent out of bounds reads */
    for (i = 0; i < hs_num; i++)
    {
        HLPFILE_HOTSPOTLINK*    hslink;

        WINE_TRACE("%02x-%02x%02x {%s,%s}\n",
                   start[7 + 15 * i + 0], start[7 + 15 * i + 1], start[7 + 15 * i + 2],
                   str, str + strlen(str) + 1);
        /* str points to two null terminated strings:
         * hotspot name, then link name
         */
        str += strlen(str) + 1;     /* skip hotspot name */

800
        hslink = NULL;
801 802 803 804 805
        switch (start[7 + 15 * i + 0])
        /* The next two chars always look like 0x04 0x00 ???
         * What are they for ?
         */
        {
806 807
        case 0xC8:
            hslink = (HLPFILE_HOTSPOTLINK*)
808
                HLPFILE_AllocLink(rd, hlp_link_macro, str, -1, 0, FALSE, TRUE, -1);
809 810
            break;

811 812 813 814 815
        case 0xE6:
        case 0xE7:
            hslink = (HLPFILE_HOTSPOTLINK*)
                HLPFILE_AllocLink(rd, (start[7 + 15 * i + 0] & 1) ? hlp_link_link : hlp_link_popup,
                                  file->lpszPath, -1, HLPFILE_Hash(str),
816
                                  FALSE, TRUE, -1);
817
            break;
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

        case 0xEE:
        case 0xEF:
            {
                const char* win = strchr(str, '>');
                int wnd = -1;
                char* tgt = NULL;

                if (win)
                {
                    for (wnd = file->numWindows - 1; wnd >= 0; wnd--)
                    {
                        if (!strcmp(win + 1, file->windows[wnd].name)) break;
                    }
                    if (wnd == -1)
                        WINE_WARN("Couldn't find window info for %s\n", win);
                    if ((tgt = HeapAlloc(GetProcessHeap(), 0, win - str + 1)))
                    {
                        memcpy(tgt, str, win - str);
                        tgt[win - str] = '\0';
                    }
                }
                hslink = (HLPFILE_HOTSPOTLINK*)
                    HLPFILE_AllocLink(rd, (start[7 + 15 * i + 0] & 1) ? hlp_link_link : hlp_link_popup,
842
                                      file->lpszPath, -1, HLPFILE_Hash(tgt ? tgt : str), FALSE, TRUE, wnd);
843 844 845
                HeapFree(GetProcessHeap(), 0, tgt);
                break;
            }
846 847 848
        default:
            WINE_FIXME("unknown hotsport target 0x%x\n", start[7 + 15 * i + 0]);
        }
849 850 851 852 853 854 855 856
        if (hslink)
        {
            hslink->x      = GET_USHORT(start, 7 + 15 * i + 3);
            hslink->y      = GET_USHORT(start, 7 + 15 * i + 5);
            hslink->width  = GET_USHORT(start, 7 + 15 * i + 7);
            hslink->height = GET_USHORT(start, 7 + 15 * i + 9);
            /* target = GET_UINT(start, 7 + 15 * i + 11); */
        }
857 858 859 860
        str += strlen(str) + 1;
    }
}

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
/******************************************************************
 *             HLPFILE_RtfAddTransparentBitmap
 *
 * We'll transform a transparent bitmap into an metafile that
 * we then transform into RTF
 */
static BOOL HLPFILE_RtfAddTransparentBitmap(struct RtfData* rd, const BITMAPINFO* bi,
                                            const void* pict, unsigned nc)
{
    HDC                 hdc, hdcMask, hdcMem, hdcEMF;
    HBITMAP             hbm, hbmMask, hbmOldMask, hbmOldMem;
    HENHMETAFILE        hEMF;
    BOOL                ret = FALSE;
    void*               data;
    UINT                sz;

    hbm = CreateDIBitmap(hdc = GetDC(0), &bi->bmiHeader,
                         CBM_INIT, pict, bi, DIB_RGB_COLORS);

    hdcMem = CreateCompatibleDC(hdc);
    hbmOldMem = SelectObject(hdcMem, hbm);

    /* create the mask bitmap from the main bitmap */
    hdcMask = CreateCompatibleDC(hdc);
    hbmMask = CreateBitmap(bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, 1, 1, NULL);
    hbmOldMask = SelectObject(hdcMask, hbmMask);
    SetBkColor(hdcMem,
               RGB(bi->bmiColors[nc - 1].rgbRed,
                   bi->bmiColors[nc - 1].rgbGreen,
                   bi->bmiColors[nc - 1].rgbBlue));
    BitBlt(hdcMask, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCCOPY);

    /* sets to RGB(0,0,0) the transparent bits in main bitmap */
    SetBkColor(hdcMem, RGB(0,0,0));
    SetTextColor(hdcMem, RGB(255,255,255));
    BitBlt(hdcMem, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMask, 0, 0, SRCAND);

    SelectObject(hdcMask, hbmOldMask);
    DeleteDC(hdcMask);

    SelectObject(hdcMem, hbmOldMem);
    DeleteDC(hdcMem);

    /* we create the bitmap on the fly */
905
    hdcEMF = CreateEnhMetaFileW(NULL, NULL, NULL, NULL);
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    hdcMem = CreateCompatibleDC(hdcEMF);

    /* sets to RGB(0,0,0) the transparent bits in final bitmap */
    hbmOldMem = SelectObject(hdcMem, hbmMask);
    SetBkColor(hdcEMF, RGB(255, 255, 255));
    SetTextColor(hdcEMF, RGB(0, 0, 0));
    BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCAND);

    /* and copy the remaining bits of main bitmap */
    SelectObject(hdcMem, hbm);
    BitBlt(hdcEMF, 0, 0, bi->bmiHeader.biWidth, bi->bmiHeader.biHeight, hdcMem, 0, 0, SRCPAINT);
    SelectObject(hdcMem, hbmOldMem);
    DeleteDC(hdcMem);

    /* do the cleanup */
    ReleaseDC(0, hdc);
    DeleteObject(hbmMask);
    DeleteObject(hbm);

    hEMF = CloseEnhMetaFile(hdcEMF);

    /* generate rtf stream */
    sz = GetEnhMetaFileBits(hEMF, 0, NULL);
    if (sz && (data = HeapAlloc(GetProcessHeap(), 0, sz)))
    {
        if (sz == GetEnhMetaFileBits(hEMF, sz, data))
        {
            ret = HLPFILE_RtfAddControl(rd, "{\\pict\\emfblip") &&
                HLPFILE_RtfAddHexBytes(rd, data, sz) &&
                HLPFILE_RtfAddControl(rd, "}");
        }
        HeapFree(GetProcessHeap(), 0, data);
    }
    DeleteEnhMetaFile(hEMF);

    return ret;
}

944 945 946 947
/******************************************************************
 *		HLPFILE_RtfAddBitmap
 *
 */
948
static BOOL HLPFILE_RtfAddBitmap(struct RtfData* rd, HLPFILE* file, const BYTE* beg, BYTE type, BYTE pack)
949
{
950 951 952
    const BYTE*         ptr;
    const BYTE*         pict_beg;
    BYTE*               alloc = NULL;
953
    BITMAPINFO*         bi;
954
    ULONG               off, csz;
955
    unsigned            nc = 0;
956
    BOOL                clrImportant = FALSE;
957 958
    BOOL                ret = FALSE;
    char                tmp[256];
959
    unsigned            hs_size, hs_offset;
960 961 962 963 964 965 966 967 968 969 970 971 972 973

    bi = HeapAlloc(GetProcessHeap(), 0, sizeof(*bi));
    if (!bi) return FALSE;

    ptr = beg + 2; /* for type and pack */

    bi->bmiHeader.biSize          = sizeof(bi->bmiHeader);
    bi->bmiHeader.biXPelsPerMeter = fetch_ulong(&ptr);
    bi->bmiHeader.biYPelsPerMeter = fetch_ulong(&ptr);
    bi->bmiHeader.biPlanes        = fetch_ushort(&ptr);
    bi->bmiHeader.biBitCount      = fetch_ushort(&ptr);
    bi->bmiHeader.biWidth         = fetch_ulong(&ptr);
    bi->bmiHeader.biHeight        = fetch_ulong(&ptr);
    bi->bmiHeader.biClrUsed       = fetch_ulong(&ptr);
974 975
    clrImportant  = fetch_ulong(&ptr);
    bi->bmiHeader.biClrImportant  = (clrImportant > 1) ? clrImportant : 0;
976 977 978 979 980 981 982 983 984
    bi->bmiHeader.biCompression   = BI_RGB;
    if (bi->bmiHeader.biBitCount > 32) WINE_FIXME("Unknown bit count %u\n", bi->bmiHeader.biBitCount);
    if (bi->bmiHeader.biPlanes != 1) WINE_FIXME("Unsupported planes %u\n", bi->bmiHeader.biPlanes);
    bi->bmiHeader.biSizeImage = (((bi->bmiHeader.biWidth * bi->bmiHeader.biBitCount + 31) & ~31) / 8) * bi->bmiHeader.biHeight;
    WINE_TRACE("planes=%d bc=%d size=(%d,%d)\n",
               bi->bmiHeader.biPlanes, bi->bmiHeader.biBitCount,
               bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);

    csz = fetch_ulong(&ptr);
985
    hs_size = fetch_ulong(&ptr);
986

987 988 989
    off = GET_UINT(ptr, 0); ptr += 4;
    hs_offset = GET_UINT(ptr, 0); ptr += 4;
    HLPFILE_AddHotSpotLinks(rd, file, beg, hs_size, hs_offset);
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

    /* now read palette info */
    if (type == 0x06)
    {
        unsigned i;

        nc = bi->bmiHeader.biClrUsed;
        /* not quite right, especially for bitfields type of compression */
        if (!nc && bi->bmiHeader.biBitCount <= 8)
            nc = 1 << bi->bmiHeader.biBitCount;

        bi = HeapReAlloc(GetProcessHeap(), 0, bi, sizeof(*bi) + nc * sizeof(RGBQUAD));
        if (!bi) return FALSE;
        for (i = 0; i < nc; i++)
        {
            bi->bmiColors[i].rgbBlue     = ptr[0];
            bi->bmiColors[i].rgbGreen    = ptr[1];
            bi->bmiColors[i].rgbRed      = ptr[2];
            bi->bmiColors[i].rgbReserved = 0;
            ptr += 4;
        }
    }
1012
    pict_beg = HLPFILE_DecompressGfx(beg + off, csz, bi->bmiHeader.biSizeImage, pack, &alloc);
1013

1014 1015 1016 1017 1018
    if (clrImportant == 1 && nc > 0)
    {
        ret = HLPFILE_RtfAddTransparentBitmap(rd, bi, pict_beg, nc);
        goto done;
    }
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    if (!HLPFILE_RtfAddControl(rd, "{\\pict")) goto done;
    if (type == 0x06)
    {
        sprintf(tmp, "\\dibitmap0\\picw%d\\pich%d",
                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
        if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        if (!HLPFILE_RtfAddHexBytes(rd, bi, sizeof(*bi) + nc * sizeof(RGBQUAD))) goto done;
    }
    else
    {
        sprintf(tmp, "\\wbitmap0\\wbmbitspixel%d\\wbmplanes%d\\picw%d\\pich%d",
                bi->bmiHeader.biBitCount, bi->bmiHeader.biPlanes,
                bi->bmiHeader.biWidth, bi->bmiHeader.biHeight);
        if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
    }
    if (!HLPFILE_RtfAddHexBytes(rd, pict_beg, bi->bmiHeader.biSizeImage)) goto done;
    if (!HLPFILE_RtfAddControl(rd, "}")) goto done;

    ret = TRUE;
done:
    HeapFree(GetProcessHeap(), 0, bi);
1040
    HeapFree(GetProcessHeap(), 0, alloc);
1041 1042 1043 1044 1045 1046 1047 1048

    return ret;
}

/******************************************************************
 *		HLPFILE_RtfAddMetaFile
 *
 */
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 1053 1054
    const BYTE*         ptr;
    const BYTE*         bits;
    BYTE*               alloc = NULL;
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    char                tmp[256];
    unsigned            mm;
    BOOL                ret;

    WINE_TRACE("Loading metafile\n");

    ptr = beg + 2; /* for type and pack */

    mm = fetch_ushort(&ptr); /* mapping mode */
    sprintf(tmp, "{\\pict\\wmetafile%d\\picw%d\\pich%d",
            mm, GET_USHORT(ptr, 0), GET_USHORT(ptr, 2));
    if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
    ptr += 4;

    size = fetch_ulong(&ptr); /* decompressed size */
    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 1075
    ptr += 8;

1076 1077 1078 1079
    HLPFILE_AddHotSpotLinks(rd, file, beg, hs_size, hs_offset);

    WINE_TRACE("sz=%u csz=%u offs=%u/%u,%u/%u\n",
               size, csize, off, (ULONG)(ptr - beg), hs_size, hs_offset);
1080

1081
    bits = HLPFILE_DecompressGfx(beg + off, csize, size, pack, &alloc);
1082 1083 1084 1085 1086
    if (!bits) return FALSE;

    ret = HLPFILE_RtfAddHexBytes(rd, bits, size) &&
        HLPFILE_RtfAddControl(rd, "}");

1087
    HeapFree(GetProcessHeap(), 0, alloc);
1088 1089

    return ret;
1090 1091 1092 1093 1094 1095 1096
}

/******************************************************************
 *		HLPFILE_RtfAddGfxByAddr
 *
 */
static  BOOL    HLPFILE_RtfAddGfxByAddr(struct RtfData* rd, HLPFILE *hlpfile,
1097
                                        const BYTE* ref, ULONG size)
1098 1099 1100 1101 1102 1103 1104 1105
{
    unsigned    i, numpict;

    numpict = GET_USHORT(ref, 2);
    WINE_TRACE("Got picture magic=%04x #=%d\n", GET_USHORT(ref, 0), numpict);

    for (i = 0; i < numpict; i++)
    {
1106 1107 1108
        const BYTE*     beg;
        const BYTE*     ptr;
        BYTE            type, pack;
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119

        WINE_TRACE("Offset[%d] = %x\n", i, GET_UINT(ref, (1 + i) * 4));
        beg = ptr = ref + GET_UINT(ref, (1 + i) * 4);

        type = *ptr++;
        pack = *ptr++;

        switch (type)
        {
        case 5: /* device dependent bmp */
        case 6: /* device independent bmp */
1120
            HLPFILE_RtfAddBitmap(rd, hlpfile, beg, type, pack);
1121 1122
            break;
        case 8:
1123
            HLPFILE_RtfAddMetaFile(rd, hlpfile, beg, pack);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
            break;
        default: WINE_FIXME("Unknown type %u\n", type); return FALSE;
        }

        /* FIXME: hotspots */

        /* FIXME: implement support for multiple picture format */
        if (numpict != 1) WINE_FIXME("Supporting only one bitmap format per logical bitmap (for now). Using first format\n");
        break;
    }
    return TRUE;
}

/******************************************************************
 *		HLPFILE_RtfAddGfxByIndex
 *
 *
 */
static  BOOL    HLPFILE_RtfAddGfxByIndex(struct RtfData* rd, HLPFILE *hlpfile,
                                         unsigned index)
{
    char        tmp[16];
    BYTE        *ref, *end;

    WINE_TRACE("Loading picture #%d\n", index);

    sprintf(tmp, "|bm%u", index);

    if (!HLPFILE_FindSubFile(hlpfile, tmp, &ref, &end)) {WINE_WARN("no sub file\n"); return FALSE;}

    ref += 9;
    return HLPFILE_RtfAddGfxByAddr(rd, hlpfile, ref, end - ref);
}

1158 1159 1160 1161 1162
/******************************************************************
 *		HLPFILE_AllocLink
 *
 *
 */
1163 1164
static HLPFILE_LINK*       HLPFILE_AllocLink(struct RtfData* rd, int cookie,
                                             const char* str, unsigned len, LONG hash,
1165
                                             BOOL clrChange, BOOL bHotSpot, unsigned wnd)
1166 1167
{
    HLPFILE_LINK*  link;
1168
    char*          link_str;
1169
    unsigned       asz = bHotSpot ? sizeof(HLPFILE_HOTSPOTLINK) : sizeof(HLPFILE_LINK);
1170 1171 1172 1173

    /* FIXME: should build a string table for the attributes.link.lpszPath
     * they are reallocated for each link
     */
1174
    if (len == -1) len = strlen(str);
1175
    link = HeapAlloc(GetProcessHeap(), 0, asz + len + 1);
1176 1177 1178
    if (!link) return NULL;

    link->cookie     = cookie;
1179
    link->string     = link_str = (char*)link + asz;
1180 1181 1182
    memcpy(link_str, str, len);
    link_str[len] = '\0';
    link->hash       = hash;
1183
    link->bClrChange = clrChange;
1184
    link->bHotSpot   = bHotSpot;
1185
    link->window     = wnd;
1186 1187 1188 1189 1190
    link->next       = rd->first_link;
    rd->first_link   = link;
    link->cpMin      = rd->char_pos;
    rd->force_color  = clrChange;
    if (rd->current_link) WINE_FIXME("Pending link\n");
1191 1192 1193 1194
    if (bHotSpot)
        link->cpMax = rd->char_pos;
    else
        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 1199 1200
    return link;
}

1201
static unsigned HLPFILE_HalfPointsToTwips(unsigned pts)
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
{
    static unsigned logPxY;
    if (!logPxY)
    {
        HDC hdc = GetDC(NULL);
        logPxY = GetDeviceCaps(hdc, LOGPIXELSY);
        ReleaseDC(NULL, hdc);
    }
    return MulDiv(pts, 72 * 10, logPxY);
}

1213 1214
/***********************************************************************
 *
1215
 *           HLPFILE_BrowseParagraph
1216
 */
1217 1218
static BOOL HLPFILE_BrowseParagraph(HLPFILE_PAGE* page, struct RtfData* rd,
                                    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 1225
    unsigned short     bits;
    unsigned           nc, ncol = 1;
1226
    short              table_width;
1227
    BOOL               in_table = FALSE;
1228 1229
    char               tmp[256];
    BOOL               ret = FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1230

1231 1232
    if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};

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);
Eric Pouech's avatar
Eric Pouech committed
1238
    if (!text) return FALSE;
1239
    if (size > blocksize - datalen)
1240
    {
1241
        /* need to decompress */
1242 1243 1244 1245
        if (page->file->hasPhrases)
            HLPFILE_Uncompress2(page->file, buf + datalen, end, (BYTE*)text, (BYTE*)text + size);
        else if (page->file->hasPhrases40)
            HLPFILE_Uncompress3(page->file, text, text + size, buf + datalen, end);
1246 1247
        else
        {
1248 1249 1250
            WINE_FIXME("Text size is too long, splitting\n");
            size = blocksize - datalen;
            memcpy(text, buf + datalen, size);
1251
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
1252
    }
1253 1254 1255
    else
        memcpy(text, buf + datalen, size);

1256 1257 1258 1259
    text_end = text + size;

    format = buf + 0x15;
    format_end = buf + GET_UINT(buf, 0x10);
Alexandre Julliard's avatar
Alexandre Julliard committed
1260

1261 1262 1263
    if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
    {
        fetch_long(&format);
1264
        *parlen = fetch_ushort(&format);
1265
    }
Eric Pouech's avatar
Eric Pouech committed
1266

1267
    if (buf[0x14] == 0x23)
Alexandre Julliard's avatar
Alexandre Julliard committed
1268
    {
1269
        char    type;
Alexandre Julliard's avatar
Alexandre Julliard committed
1270

1271
        in_table = TRUE;
1272
        ncol = *format++;
Alexandre Julliard's avatar
Alexandre Julliard committed
1273

1274
        if (!HLPFILE_RtfAddControl(rd, "\\trowd")) goto done;
1275 1276
        type = *format++;
        if (type == 0 || type == 2)
1277 1278
        {
            table_width = GET_SHORT(format, 0);
1279
            format += 2;
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
        }
        else
            table_width = 32767;
        WINE_TRACE("New table: cols=%d type=%x width=%d\n",
                   ncol, type, table_width);
        if (ncol > 1)
        {
            int     pos;
            sprintf(tmp, "\\trgaph%d\\trleft%d",
                    HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6), table_width, 32767)),
                    HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
            pos = HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 6) / 2, table_width, 32767));
            for (nc = 0; nc < ncol; nc++)
            {
                WINE_TRACE("column(%d/%d) gap=%d width=%d\n",
                           nc, ncol, GET_SHORT(format, nc*4),
                           GET_SHORT(format, nc*4+2));
                pos += GET_SHORT(format, nc * 4) + GET_SHORT(format, nc * 4 + 2);
                sprintf(tmp, "\\cellx%d",
                        HLPFILE_HalfPointsToTwips(MulDiv(pos, table_width, 32767)));
                if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
            }
        }
        else
        {
            WINE_TRACE("column(0/%d) gap=%d width=%d\n",
                       ncol, GET_SHORT(format, 0), GET_SHORT(format, 2));
            sprintf(tmp, "\\trleft%d\\cellx%d ",
                    HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0), table_width, 32767)),
                    HLPFILE_HalfPointsToTwips(MulDiv(GET_SHORT(format, 0) + GET_SHORT(format, 2),
                                      table_width, 32767)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
1314 1315 1316
        format += ncol * 4;
    }

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 1322 1323 1324
        if (in_table)
        {
            nc = GET_SHORT(format, 0);
            if (nc == -1) break;
1325
            format += 5;
1326
            if (!HLPFILE_RtfAddControl(rd, "\\intbl")) goto done;
1327 1328
        }
        else nc++;
1329 1330 1331 1332
        if (buf[0x14] == 0x01)
            format += 6;
        else
            format += 4;
1333
        bits = GET_USHORT(format, 0); format += 2;
1334
        if (bits & 0x0001) fetch_long(&format);
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
        if (bits & 0x0002)
        {
            sprintf(tmp, "\\sb%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
        if (bits & 0x0004)
        {
            sprintf(tmp, "\\sa%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
        if (bits & 0x0008)
        {
            sprintf(tmp, "\\sl%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
        if (bits & 0x0010)
        {
            sprintf(tmp, "\\li%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
        if (bits & 0x0020)
        {
            sprintf(tmp, "\\ri%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
        if (bits & 0x0040)
        {
            sprintf(tmp, "\\fi%d", HLPFILE_HalfPointsToTwips(fetch_short(&format)));
            if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
        }
1365 1366 1367 1368 1369
        if (bits & 0x0100)
        {
            BYTE        brdr = *format++;
            short       w;

1370 1371 1372 1373 1374 1375
            if ((brdr & 0x01) && !HLPFILE_RtfAddControl(rd, "\\box")) goto done;
            if ((brdr & 0x02) && !HLPFILE_RtfAddControl(rd, "\\brdrt")) goto done;
            if ((brdr & 0x04) && !HLPFILE_RtfAddControl(rd, "\\brdrl")) goto done;
            if ((brdr & 0x08) && !HLPFILE_RtfAddControl(rd, "\\brdrb")) goto done;
            if ((brdr & 0x10) && !HLPFILE_RtfAddControl(rd, "\\brdrr")) goto done;
            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 1379 1380 1381 1382 1383 1384 1385 1386
            /* 0x80: unknown */

            w = GET_SHORT(format, 0); format += 2;
            if (w)
            {
                sprintf(tmp, "\\brdrw%d", HLPFILE_HalfPointsToTwips(w));
                if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
            }
        }
1387 1388
        if (bits & 0x0200)
        {
1389 1390 1391
            int                 i, ntab = fetch_short(&format);
            unsigned            tab, ts;
            const char*         kind;
1392

1393
            for (i = 0; i < ntab; i++)
1394
            {
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
                tab = fetch_ushort(&format);
                ts = (tab & 0x4000) ? fetch_ushort(&format) : 0 /* left */;
                switch (ts)
                {
                default: WINE_FIXME("Unknown tab style %x\n", ts);
                /* fall through */
                case 0: kind = ""; break;
                case 1: kind = "\\tqr"; break;
                case 2: kind = "\\tqc"; break;
                }
                /* FIXME: do kind */
                sprintf(tmp, "%s\\tx%d",
                        kind, HLPFILE_HalfPointsToTwips(tab & 0x3FFF));
                if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
1409 1410
            }
        }
1411 1412 1413 1414 1415 1416 1417 1418 1419
        switch (bits & 0xc00)
        {
        default: WINE_FIXME("Unsupported alignment 0xC00\n"); break;
        case 0: if (!HLPFILE_RtfAddControl(rd, "\\ql")) goto done; break;
        case 0x400: if (!HLPFILE_RtfAddControl(rd, "\\qr")) goto done; break;
        case 0x800: if (!HLPFILE_RtfAddControl(rd, "\\qc")) goto done; break;
        }

        /* 0x1000 doesn't need space */
1420
        if ((bits & 0x1000) && !HLPFILE_RtfAddControl(rd, "\\keep")) goto done;
Eric Pouech's avatar
Eric Pouech committed
1421 1422
        if ((bits & 0xE080) != 0) 
            WINE_FIXME("Unsupported bits %04x, potential trouble ahead\n", bits);
1423 1424 1425

        while (text < text_end && format < format_end)
        {
1426
            WINE_TRACE("Got text: %s (%p/%p - %p/%p)\n", wine_dbgstr_a(text), text, text_end, format, format_end);
1427 1428
            textsize = strlen(text);
            if (textsize)
1429
            {
1430 1431 1432 1433 1434 1435
                if (rd->force_color)
                {
                    if ((rd->current_link->cookie == hlp_link_popup) ?
                        !HLPFILE_RtfAddControl(rd, "{\\uld\\cf1") :
                        !HLPFILE_RtfAddControl(rd, "{\\ul\\cf1")) goto done;
                }
1436 1437 1438
                if (!HLPFILE_RtfAddText(rd, text)) goto done;
                if (rd->force_color && !HLPFILE_RtfAddControl(rd, "}")) goto done;
                rd->char_pos += textsize;
1439 1440
            }
            /* else: null text, keep on storing attributes */
1441
            text += textsize + 1;
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452

	    if (*format == 0xff)
            {
                format++;
                break;
            }

            WINE_TRACE("format=%02x\n", *format);
            switch (*format)
            {
            case 0x20:
Eric Pouech's avatar
Eric Pouech committed
1453
                WINE_FIXME("NIY20\n");
1454 1455 1456 1457
                format += 5;
                break;

            case 0x21:
Eric Pouech's avatar
Eric Pouech committed
1458
                WINE_FIXME("NIY21\n");
1459 1460
                format += 3;
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
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 1470
                    /* Font size in hlpfile is given in the same units as
                       rtf control word \fs uses (half-points). */
1471 1472
                    switch (rd->font_scale)
                    {
1473
                    case 0: fs = page->file->fonts[font].LogFont.lfHeight - 4; break;
1474
                    default:
1475 1476
                    case 1: fs = page->file->fonts[font].LogFont.lfHeight; break;
                    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 1483 1484 1485 1486 1487 1488
                            page->file->fonts[font].LogFont.lfWeight > 400 ? "\\b" : "\\b0",
                            page->file->fonts[font].LogFont.lfItalic ? "\\i" : "\\i0",
                            page->file->fonts[font].LogFont.lfUnderline ? "\\ul" : "\\ul0",
                            page->file->fonts[font].LogFont.lfStrikeOut ? "\\strike" : "\\strike0");
                    if (!HLPFILE_RtfAddControl(rd, tmp)) goto done;
                }
               break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1489 1490

	    case 0x81:
1491
                if (!HLPFILE_RtfAddControl(rd, "\\line")) goto done;
1492
                format += 1;
1493
                rd->char_pos++;
1494
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1495 1496

	    case 0x82:
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
                if (in_table)
                {
                    if (format[1] != 0xFF)
                    {
                        if (!HLPFILE_RtfAddControl(rd, "\\par\\intbl")) goto done;
                    }
                    else
                    {
                        if (!HLPFILE_RtfAddControl(rd, "\\cell\\pard\\intbl")) goto done;
                    }
                }
                else if (!HLPFILE_RtfAddControl(rd, "\\par")) goto done;
1509
                format += 1;
1510
                rd->char_pos++;
1511
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1512 1513

	    case 0x83:
1514
                if (!HLPFILE_RtfAddControl(rd, "\\tab")) goto done;
1515
                format += 1;
1516
                rd->char_pos++;
1517
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1518

1519
#if 0
Alexandre Julliard's avatar
Alexandre Julliard committed
1520
	    case 0x84:
1521 1522 1523
                format += 3;
                break;
#endif
Alexandre Julliard's avatar
Alexandre Julliard committed
1524 1525 1526 1527

	    case 0x86:
	    case 0x87:
	    case 0x88:
1528 1529 1530
                {
                    BYTE    type = format[1];

1531
                    /* FIXME: we don't use 'BYTE    pos = (*format - 0x86);' for the image position */
1532 1533
                    format += 2;
                    size = fetch_long(&format);
Eric Pouech's avatar
Eric Pouech committed
1534

1535 1536 1537 1538
                    switch (type)
                    {
                    case 0x22:
                        fetch_ushort(&format); /* hot spot */
1539
                        /* fall through */
1540
                    case 0x03:
1541
                        switch (GET_SHORT(format, 0))
1542
                        {
Eric Pouech's avatar
Eric Pouech committed
1543
                        case 0:
1544 1545
                            HLPFILE_RtfAddGfxByIndex(rd, page->file, GET_SHORT(format, 2));
                            rd->char_pos++;
Eric Pouech's avatar
Eric Pouech committed
1546 1547
                            break;
                        case 1:
1548
                            WINE_FIXME("does it work ??? %x<%u>#%u\n",
1549
                                       GET_SHORT(format, 0),
1550
                                       size, GET_SHORT(format, 2));
1551 1552 1553
                            HLPFILE_RtfAddGfxByAddr(rd, page->file, format + 2, size - 4);
                            rd->char_pos++;
                           break;
Eric Pouech's avatar
Eric Pouech committed
1554
                        default:
1555
                            WINE_FIXME("??? %u\n", GET_SHORT(format, 0));
Eric Pouech's avatar
Eric Pouech committed
1556
                            break;
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
                        }
                        break;
                    case 0x05:
                        WINE_FIXME("Got an embedded element %s\n", format + 6);
                        break;
                    default:
                        WINE_FIXME("Got a type %d picture\n", type);
                        break;
                    }
                    format += size;
                }
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1569 1570

	    case 0x89:
1571
                format += 1;
1572 1573 1574 1575 1576
                if (!rd->current_link)
                    WINE_FIXME("No existing link\n");
                rd->current_link->cpMax = rd->char_pos;
                rd->current_link = NULL;
                rd->force_color = FALSE;
1577
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1578

1579
            case 0x8B:
1580 1581
                if (!HLPFILE_RtfAddControl(rd, "\\~")) goto done;
                format += 1;
1582
                rd->char_pos++;
1583 1584
                break;

1585
            case 0x8C:
1586
                if (!HLPFILE_RtfAddControl(rd, "\\_")) goto done;
1587
                /* FIXME: it could be that hyphen is also in input stream !! */
1588
                format += 1;
1589
                rd->char_pos++;
1590 1591 1592
                break;

#if 0
1593
	    case 0xA9:
1594 1595 1596 1597
                format += 2;
                break;
#endif

1598 1599 1600
            case 0xC8:
            case 0xCC:
                WINE_TRACE("macro => %s\n", format + 3);
1601
                HLPFILE_AllocLink(rd, hlp_link_macro, (const char*)format + 3,
1602
                                  GET_USHORT(format, 1), 0, !(*format & 4), FALSE, -1);
1603
                format += 3 + GET_USHORT(format, 1);
1604 1605
                break;

1606 1607
            case 0xE0:
            case 0xE1:
1608
                WINE_WARN("jump topic 1 => %u\n", GET_UINT(format, 1));
1609
                HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1610
                                  page->file->lpszPath, -1, GET_UINT(format, 1), TRUE, FALSE, -1);
1611 1612


1613 1614
                format += 5;
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1615

1616 1617 1618 1619
	    case 0xE2:
	    case 0xE3:
            case 0xE6:
            case 0xE7:
1620 1621
                HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
                                  page->file->lpszPath, -1, GET_UINT(format, 1),
1622
                                  !(*format & 4), FALSE, -1);
1623 1624
                format += 5;
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1625

1626 1627 1628 1629 1630
	    case 0xEA:
            case 0xEB:
            case 0xEE:
            case 0xEF:
                {
1631
                    const char*       ptr = (const char*) format + 8;
1632 1633 1634
                    BYTE        type = format[3];
                    int         wnd = -1;

1635
                    switch (type)
1636
                    {
1637 1638 1639 1640
                    case 1:
                        wnd = *ptr;
                        /* fall through */
                    case 0:
1641
                        ptr = page->file->lpszPath;
1642 1643
                        break;
                    case 6:
1644
                        for (wnd = page->file->numWindows - 1; wnd >= 0; wnd--)
1645
                        {
1646
                            if (!strcmp(ptr, page->file->windows[wnd].name)) break;
1647
                        }
1648
                        if (wnd == -1)
1649
                            WINE_WARN("Couldn't find window info for %s\n", ptr);
1650 1651 1652 1653 1654 1655 1656
                        ptr += strlen(ptr) + 1;
                        /* fall through */
                    case 4:
                        break;
                    default:
                        WINE_WARN("Unknown link type %d\n", type);
                        break;
1657
                    }
1658
                    HLPFILE_AllocLink(rd, (*format & 1) ? hlp_link_link : hlp_link_popup,
1659
                                      ptr, -1, GET_UINT(format, 4), !(*format & 4), FALSE, wnd);
1660
                }
1661 1662
                format += 3 + GET_USHORT(format, 1);
                break;
Alexandre Julliard's avatar
Alexandre Julliard committed
1663 1664

	    default:
1665 1666
                WINE_WARN("format %02x\n", *format);
                format++;
Alexandre Julliard's avatar
Alexandre Julliard committed
1667 1668
	    }
	}
1669
    }
1670 1671 1672 1673 1674
    if (in_table)
    {
        if (!HLPFILE_RtfAddControl(rd, "\\row\\par\\pard\\plain")) goto done;
        rd->char_pos += 2;
    }
1675 1676
    ret = TRUE;
done:
1677

1678
    HeapFree(GetProcessHeap(), 0, text_base);
1679
    return ret;
1680
}
Alexandre Julliard's avatar
Alexandre Julliard committed
1681

1682 1683 1684 1685
/******************************************************************
 *		HLPFILE_BrowsePage
 *
 */
1686 1687
BOOL    HLPFILE_BrowsePage(HLPFILE_PAGE* page, struct RtfData* rd,
                           unsigned font_scale, unsigned relative)
1688 1689 1690 1691
{
    HLPFILE     *hlpfile = page->file;
    BYTE        *buf, *end;
    DWORD       ref = page->reference;
1692 1693
    unsigned    index, old_index = -1, offset, count = 0, offs = 0;
    unsigned    cpg, parlen;
1694
    char        tmp[1024];
1695
    const char* ck = NULL;
1696 1697 1698 1699

    rd->in_text = TRUE;
    rd->data = rd->ptr = HeapAlloc(GetProcessHeap(), 0, rd->allocated = 32768);
    rd->char_pos = 0;
1700
    rd->first_link = rd->current_link = NULL;
1701
    rd->force_color = FALSE;
1702
    rd->font_scale = font_scale;
1703 1704
    rd->relative = relative;
    rd->char_pos_rel = 0;
1705

1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    switch (hlpfile->charset)
    {
    case DEFAULT_CHARSET:
    case ANSI_CHARSET:          cpg = 1252; break;
    case SHIFTJIS_CHARSET:      cpg = 932; break;
    case HANGEUL_CHARSET:       cpg = 949; break;
    case GB2312_CHARSET:        cpg = 936; break;
    case CHINESEBIG5_CHARSET:   cpg = 950; break;
    case GREEK_CHARSET:         cpg = 1253; break;
    case TURKISH_CHARSET:       cpg = 1254; break;
    case HEBREW_CHARSET:        cpg = 1255; break;
    case ARABIC_CHARSET:        cpg = 1256; break;
    case BALTIC_CHARSET:        cpg = 1257; break;
    case VIETNAMESE_CHARSET:    cpg = 1258; break;
    case RUSSIAN_CHARSET:       cpg = 1251; break;
    case EE_CHARSET:            cpg = 1250; break;
    case THAI_CHARSET:          cpg = 874; break;
    case JOHAB_CHARSET:         cpg = 1361; break;
    case MAC_CHARSET:           ck = "mac"; break;
    default:
        WINE_FIXME("Unsupported charset %u\n", hlpfile->charset);
        cpg = 1252;
    }
    if (ck)
    {
        sprintf(tmp, "{\\rtf1\\%s\\deff0", ck);
        if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
    }
    else
    {
        sprintf(tmp, "{\\rtf1\\ansi\\ansicpg%d\\deff0", cpg);
        if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
    }

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
    /* generate font table */
    if (!HLPFILE_RtfAddControl(rd, "{\\fonttbl")) return FALSE;
    for (index = 0; index < hlpfile->numFonts; index++)
    {
        const char* family;
        switch (hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0xF0)
        {
        case FF_MODERN:     family = "modern";  break;
        case FF_ROMAN:      family = "roman";   break;
        case FF_SWISS:      family = "swiss";   break;
        case FF_SCRIPT:     family = "script";  break;
        case FF_DECORATIVE: family = "decor";   break;
        default:            family = "nil";     break;
        }
1754
        sprintf(tmp, "{\\f%d\\f%s\\fprq%d\\fcharset%d %s;}",
1755 1756
                index, family,
                hlpfile->fonts[index].LogFont.lfPitchAndFamily & 0x0F,
1757
                hlpfile->fonts[index].LogFont.lfCharSet,
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
                hlpfile->fonts[index].LogFont.lfFaceName);
        if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
    }
    if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
    /* generate color table */
    if (!HLPFILE_RtfAddControl(rd, "{\\colortbl ;\\red0\\green128\\blue0;")) return FALSE;
    for (index = 0; index < hlpfile->numFonts; index++)
    {
        sprintf(tmp, "\\red%d\\green%d\\blue%d;",
                GetRValue(hlpfile->fonts[index].color),
                GetGValue(hlpfile->fonts[index].color),
                GetBValue(hlpfile->fonts[index].color));
        if (!HLPFILE_RtfAddControl(rd, tmp)) return FALSE;
    }
    if (!HLPFILE_RtfAddControl(rd, "}")) return FALSE;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786

    do
    {
        if (hlpfile->version <= 16)
        {
            index  = (ref - 0x0C) / hlpfile->dsize;
            offset = (ref - 0x0C) % hlpfile->dsize;
        }
        else
        {
            index  = (ref - 0x0C) >> 14;
            offset = (ref - 0x0C) & 0x3FFF;
        }

1787
        if (hlpfile->version <= 16 && index != old_index && old_index != -1)
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
        {
            /* we jumped to the next block, adjust pointers */
            ref -= 12;
            offset -= 12;
        }

        if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
        buf = hlpfile->topic_map[index] + offset;
        if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
        end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
1798
        if (index != old_index) {offs = 0; old_index = index;}
1799 1800 1801 1802 1803 1804 1805 1806 1807

        switch (buf[0x14])
        {
        case 0x02:
            if (count++) goto done;
            break;
        case 0x01:
        case 0x20:
        case 0x23:
1808
            if (!HLPFILE_BrowseParagraph(page, rd, buf, end, &parlen)) return FALSE;
1809
            if (relative > index * 0x8000 + offs)
1810 1811
                rd->char_pos_rel = rd->char_pos;
            offs += parlen;
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
            break;
        default:
            WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
        }
        if (hlpfile->version <= 16)
        {
            ref += GET_UINT(buf, 0xc);
            if (GET_UINT(buf, 0xc) == 0)
                break;
        }
        else
            ref = GET_UINT(buf, 0xc);
    } while (ref != 0xffffffff);
done:
1826
    page->first_link = rd->first_link;
1827
    return HLPFILE_RtfAddControl(rd, "}");
1828 1829
}

1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
/******************************************************************
 *		HLPFILE_ReadFont
 *
 *
 */
static BOOL HLPFILE_ReadFont(HLPFILE* hlpfile)
{
    BYTE        *ref, *end;
    unsigned    i, len, idx;
    unsigned    face_num, dscr_num, face_offset, dscr_offset;
    BYTE        flag, family;
Alexandre Julliard's avatar
Alexandre Julliard committed
1841

1842
    if (!HLPFILE_FindSubFile(hlpfile, "|FONT", &ref, &end))
1843 1844 1845 1846 1847
    {
        WINE_WARN("no subfile FONT\n");
        hlpfile->numFonts = 0;
        hlpfile->fonts = NULL;
        return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1848 1849
    }

1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
    ref += 9;

    face_num    = GET_USHORT(ref, 0);
    dscr_num    = GET_USHORT(ref, 2);
    face_offset = GET_USHORT(ref, 4);
    dscr_offset = GET_USHORT(ref, 6);

    WINE_TRACE("Got NumFacenames=%u@%u NumDesc=%u@%u\n",
               face_num, face_offset, dscr_num, dscr_offset);

    hlpfile->numFonts = dscr_num;
    hlpfile->fonts = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_FONT) * dscr_num);

    len = (dscr_offset - face_offset) / face_num;
/* EPP     for (i = face_offset; i < dscr_offset; i += len) */
/* EPP         WINE_FIXME("[%d]: %*s\n", i / len, len, ref + i); */
    for (i = 0; i < dscr_num; i++)
    {
        flag = ref[dscr_offset + i * 11 + 0];
        family = ref[dscr_offset + i * 11 + 2];

1871
        hlpfile->fonts[i].LogFont.lfHeight = ref[dscr_offset + i * 11 + 1];
1872 1873 1874 1875
        hlpfile->fonts[i].LogFont.lfWidth = 0;
        hlpfile->fonts[i].LogFont.lfEscapement = 0;
        hlpfile->fonts[i].LogFont.lfOrientation = 0;
        hlpfile->fonts[i].LogFont.lfWeight = (flag & 1) ? 700 : 400;
1876 1877 1878
        hlpfile->fonts[i].LogFont.lfItalic = (flag & 2) != 0;
        hlpfile->fonts[i].LogFont.lfUnderline = (flag & 4) != 0;
        hlpfile->fonts[i].LogFont.lfStrikeOut = (flag & 8) != 0;
1879
        hlpfile->fonts[i].LogFont.lfCharSet = hlpfile->charset;
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
        hlpfile->fonts[i].LogFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
        hlpfile->fonts[i].LogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
        hlpfile->fonts[i].LogFont.lfQuality = DEFAULT_QUALITY;
        hlpfile->fonts[i].LogFont.lfPitchAndFamily = DEFAULT_PITCH;

        switch (family)
        {
        case 0x01: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_MODERN;     break;
        case 0x02: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_ROMAN;      break;
        case 0x03: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SWISS;      break;
        case 0x04: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_SCRIPT;     break;
        case 0x05: hlpfile->fonts[i].LogFont.lfPitchAndFamily |= FF_DECORATIVE; break;
        default: WINE_FIXME("Unknown family %u\n", family);
        }
1894
        idx = GET_USHORT(ref, dscr_offset + i * 11 + 3);
1895 1896 1897

        if (idx < face_num)
        {
1898 1899
            memcpy(hlpfile->fonts[i].LogFont.lfFaceName, ref + face_offset + idx * len, min(len, LF_FACESIZE - 1));
            hlpfile->fonts[i].LogFont.lfFaceName[min(len, LF_FACESIZE - 1)] = '\0';
1900 1901 1902 1903 1904 1905
        }
        else
        {
            WINE_FIXME("Too high face ref (%u/%u)\n", idx, face_num);
            strcpy(hlpfile->fonts[i].LogFont.lfFaceName, "Helv");
        }
1906
        hlpfile->fonts[i].hFont = 0;
1907 1908 1909 1910
        hlpfile->fonts[i].color = RGB(ref[dscr_offset + i * 11 + 5],
                                      ref[dscr_offset + i * 11 + 6],
                                      ref[dscr_offset + i * 11 + 7]);
#define X(b,s) ((flag & (1 << b)) ? "-"s: "")
1911
        WINE_TRACE("Font[%d]: flags=%02x%s%s%s%s%s%s pSize=%u family=%u face=%s[%u] color=%08x\n",
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
                   i, flag,
                   X(0, "bold"),
                   X(1, "italic"),
                   X(2, "underline"),
                   X(3, "strikeOut"),
                   X(4, "dblUnderline"),
                   X(5, "smallCaps"),
                   ref[dscr_offset + i * 11 + 1],
                   family,
                   hlpfile->fonts[i].LogFont.lfFaceName, idx,
1922
                   GET_UINT(ref, dscr_offset + i * 11 + 5) & 0x00FFFFFF);
1923 1924
    }
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1925 1926 1927 1928 1929 1930
}

/***********************************************************************
 *
 *           HLPFILE_ReadFileToBuffer
 */
1931
static BOOL HLPFILE_ReadFileToBuffer(HLPFILE* hlpfile, HFILE hFile)
Alexandre Julliard's avatar
Alexandre Julliard committed
1932
{
1933
    BYTE  header[16], dummy[1];
Alexandre Julliard's avatar
Alexandre Julliard committed
1934

1935
    if (_hread(hFile, header, 16) != 16) {WINE_WARN("header\n"); return FALSE;};
Alexandre Julliard's avatar
Alexandre Julliard committed
1936

1937 1938 1939 1940
    /* sanity checks */
    if (GET_UINT(header, 0) != 0x00035F3F)
    {WINE_WARN("wrong header\n"); return FALSE;};

1941 1942 1943
    hlpfile->file_buffer_size = GET_UINT(header, 12);
    hlpfile->file_buffer = HeapAlloc(GetProcessHeap(), 0, hlpfile->file_buffer_size + 1);
    if (!hlpfile->file_buffer) return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1944

1945 1946
    memcpy(hlpfile->file_buffer, header, 16);
    if (_hread(hFile, hlpfile->file_buffer + 16, hlpfile->file_buffer_size - 16) !=hlpfile->file_buffer_size - 16)
1947
    {WINE_WARN("filesize1\n"); return FALSE;};
Alexandre Julliard's avatar
Alexandre Julliard committed
1948

1949
    if (_hread(hFile, dummy, 1) != 0) WINE_WARN("filesize2\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
1950

Austin English's avatar
Austin English committed
1951
    hlpfile->file_buffer[hlpfile->file_buffer_size] = '\0'; /* FIXME: was '0', sounds backwards to me */
Alexandre Julliard's avatar
Alexandre Julliard committed
1952

1953
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
1954 1955 1956 1957 1958 1959
}

/***********************************************************************
 *
 *           HLPFILE_SystemCommands
 */
1960
static BOOL HLPFILE_SystemCommands(HLPFILE* hlpfile)
Alexandre Julliard's avatar
Alexandre Julliard committed
1961
{
1962 1963 1964 1965 1966 1967 1968
    BYTE *buf, *ptr, *end;
    HLPFILE_MACRO *macro, **m;
    LPSTR p;
    unsigned short magic, minor, major, flags;

    hlpfile->lpszTitle = NULL;

1969
    if (!HLPFILE_FindSubFile(hlpfile, "|SYSTEM", &buf, &end)) return FALSE;
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979

    magic = GET_USHORT(buf + 9, 0);
    minor = GET_USHORT(buf + 9, 2);
    major = GET_USHORT(buf + 9, 4);
    /* gen date on 4 bytes */
    flags = GET_USHORT(buf + 9, 10);
    WINE_TRACE("Got system header: magic=%04x version=%d.%d flags=%04x\n",
               magic, major, minor, flags);
    if (magic != 0x036C || major != 1)
    {WINE_WARN("Wrong system header\n"); return FALSE;}
1980 1981 1982
    if (minor <= 16)
    {
        hlpfile->tbsize = 0x800;
1983
        hlpfile->compressed = FALSE;
1984 1985 1986 1987
    }
    else if (flags == 0)
    {
        hlpfile->tbsize = 0x1000;
1988
        hlpfile->compressed = FALSE;
1989 1990 1991 1992
    }
    else if (flags == 4)
    {
        hlpfile->tbsize = 0x1000;
1993
        hlpfile->compressed = TRUE;
1994 1995 1996 1997
    }
    else
    {
        hlpfile->tbsize = 0x800;
1998
        hlpfile->compressed = TRUE;
1999 2000 2001 2002 2003 2004
    }

    if (hlpfile->compressed)
        hlpfile->dsize = 0x4000;
    else
        hlpfile->dsize = hlpfile->tbsize - 0x0C;
2005 2006 2007

    hlpfile->version = minor;
    hlpfile->flags = flags;
2008
    hlpfile->charset = DEFAULT_CHARSET;
2009

2010 2011 2012 2013 2014 2015
    if (hlpfile->version <= 16)
    {
        char *str = (char*)buf + 0x15;

        hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
        if (!hlpfile->lpszTitle) return FALSE;
2016
        strcpy(hlpfile->lpszTitle, str);
2017 2018 2019 2020
        WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
        /* Nothing more to parse */
        return TRUE;
    }
2021
    for (ptr = buf + 0x15; ptr + 4 <= end; ptr += GET_USHORT(ptr, 2) + 4)
Alexandre Julliard's avatar
Alexandre Julliard committed
2022
    {
Mike McCormack's avatar
Mike McCormack committed
2023
        char *str = (char*) ptr + 4;
2024
        switch (GET_USHORT(ptr, 0))
Alexandre Julliard's avatar
Alexandre Julliard committed
2025 2026
	{
	case 1:
2027
            if (hlpfile->lpszTitle) {WINE_WARN("title\n"); break;}
Mike McCormack's avatar
Mike McCormack committed
2028
            hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
2029
            if (!hlpfile->lpszTitle) return FALSE;
2030
            strcpy(hlpfile->lpszTitle, str);
2031 2032
            WINE_TRACE("Title: %s\n", hlpfile->lpszTitle);
            break;
Alexandre Julliard's avatar
Alexandre Julliard committed
2033 2034

	case 2:
Eric Pouech's avatar
Eric Pouech committed
2035
            if (hlpfile->lpszCopyright) {WINE_WARN("copyright\n"); break;}
Mike McCormack's avatar
Mike McCormack committed
2036
            hlpfile->lpszCopyright = HeapAlloc(GetProcessHeap(), 0, strlen(str) + 1);
Eric Pouech's avatar
Eric Pouech committed
2037
            if (!hlpfile->lpszCopyright) return FALSE;
2038
            strcpy(hlpfile->lpszCopyright, str);
Eric Pouech's avatar
Eric Pouech committed
2039
            WINE_TRACE("Copyright: %s\n", hlpfile->lpszCopyright);
2040
            break;
Alexandre Julliard's avatar
Alexandre Julliard committed
2041 2042

	case 3:
Eric Pouech's avatar
Eric Pouech committed
2043 2044 2045
            if (GET_USHORT(ptr, 2) != 4) {WINE_WARN("system3\n");break;}
            hlpfile->contents_start = GET_UINT(ptr, 4);
            WINE_TRACE("Setting contents start at %08lx\n", hlpfile->contents_start);
2046
            break;
Alexandre Julliard's avatar
Alexandre Julliard committed
2047 2048

	case 4:
2049
            macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + strlen(str) + 1);
2050 2051
            if (!macro) break;
            p = (char*)macro + sizeof(HLPFILE_MACRO);
2052
            strcpy(p, str);
2053 2054 2055 2056 2057
            macro->lpszMacro = p;
            macro->next = 0;
            for (m = &hlpfile->first_macro; *m; m = &(*m)->next);
            *m = macro;
            break;
Alexandre Julliard's avatar
Alexandre Julliard committed
2058

2059 2060 2061 2062 2063 2064 2065 2066 2067
        case 5:
            if (GET_USHORT(ptr, 4 + 4) != 1)
                WINE_FIXME("More than one icon, picking up first\n");
            /* 0x16 is sizeof(CURSORICONDIR), see user32/user_private.h */
            hlpfile->hIcon = CreateIconFromResourceEx(ptr + 4 + 0x16,
                                                      GET_USHORT(ptr, 2) - 0x16, TRUE,
                                                      0x30000, 0, 0, 0);
            break;

Eric Pouech's avatar
Eric Pouech committed
2068 2069
        case 6:
            if (GET_USHORT(ptr, 2) != 90) {WINE_WARN("system6\n");break;}
2070 2071 2072 2073 2074 2075

	    if (hlpfile->windows) 
        	hlpfile->windows = HeapReAlloc(GetProcessHeap(), 0, hlpfile->windows, 
                                           sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
	    else 
        	hlpfile->windows = HeapAlloc(GetProcessHeap(), 0, 
2076
                                           sizeof(HLPFILE_WINDOWINFO) * ++hlpfile->numWindows);
2077
	    
2078 2079 2080 2081
            if (hlpfile->windows)
            {
                HLPFILE_WINDOWINFO* wi = &hlpfile->windows[hlpfile->numWindows - 1];

2082
                flags = GET_USHORT(ptr, 4);
Mike McCormack's avatar
Mike McCormack committed
2083
                if (flags & 0x0001) strcpy(wi->type, &str[2]);
2084
                else wi->type[0] = '\0';
Mike McCormack's avatar
Mike McCormack committed
2085
                if (flags & 0x0002) strcpy(wi->name, &str[12]);
2086
                else wi->name[0] = '\0';
2087
                if (flags & 0x0004) strcpy(wi->caption, &str[21]);
2088
                else lstrcpynA(wi->caption, hlpfile->lpszTitle, sizeof(wi->caption));
2089 2090 2091 2092 2093
                wi->origin.x = (flags & 0x0008) ? GET_USHORT(ptr, 76) : CW_USEDEFAULT;
                wi->origin.y = (flags & 0x0010) ? GET_USHORT(ptr, 78) : CW_USEDEFAULT;
                wi->size.cx = (flags & 0x0020) ? GET_USHORT(ptr, 80) : CW_USEDEFAULT;
                wi->size.cy = (flags & 0x0040) ? GET_USHORT(ptr, 82) : CW_USEDEFAULT;
                wi->style = (flags & 0x0080) ? GET_USHORT(ptr, 84) : SW_SHOW;
2094
                wi->win_style = WS_OVERLAPPEDWINDOW;
2095 2096
                wi->sr_color = (flags & 0x0100) ? GET_UINT(ptr, 86) : 0xFFFFFF;
                wi->nsr_color = (flags & 0x0200) ? GET_UINT(ptr, 90) : 0xFFFFFF;
2097
                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",
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
                           flags & 0x0001 ? 'T' : 't',
                           flags & 0x0002 ? 'N' : 'n',
                           flags & 0x0004 ? 'C' : 'c',
                           flags & 0x0008 ? 'X' : 'x',
                           flags & 0x0010 ? 'Y' : 'y',
                           flags & 0x0020 ? 'W' : 'w',
                           flags & 0x0040 ? 'H' : 'h',
                           flags & 0x0080 ? 'S' : 's',
                           wi->type, wi->name, wi->caption, wi->origin.x, wi->origin.y,
                           wi->size.cx, wi->size.cy);
            }
Eric Pouech's avatar
Eric Pouech committed
2109
            break;
2110 2111 2112
        case 8:
            WINE_WARN("Citation: '%s'\n", ptr + 4);
            break;
2113 2114 2115 2116
        case 11:
            hlpfile->charset = ptr[4];
            WINE_TRACE("Charset: %d\n", hlpfile->charset);
            break;
Alexandre Julliard's avatar
Alexandre Julliard committed
2117
	default:
Eric Pouech's avatar
Eric Pouech committed
2118
            WINE_WARN("Unsupported SystemRecord[%d]\n", GET_USHORT(ptr, 0));
Alexandre Julliard's avatar
Alexandre Julliard committed
2119 2120
	}
    }
2121 2122
    if (!hlpfile->lpszTitle)
        hlpfile->lpszTitle = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1);
2123
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2124 2125 2126 2127
}

/***********************************************************************
 *
2128
 *           HLPFILE_GetContext
Alexandre Julliard's avatar
Alexandre Julliard committed
2129
 */
2130
static BOOL HLPFILE_GetContext(HLPFILE *hlpfile)
Alexandre Julliard's avatar
Alexandre Julliard committed
2131
{
2132 2133
    BYTE                *cbuf, *cend;
    unsigned            clen;
Alexandre Julliard's avatar
Alexandre Julliard committed
2134

2135 2136
    if (!HLPFILE_FindSubFile(hlpfile, "|CONTEXT",  &cbuf, &cend))
    {WINE_WARN("context0\n"); return FALSE;}
Alexandre Julliard's avatar
Alexandre Julliard committed
2137

2138 2139 2140 2141 2142 2143
    clen = cend - cbuf;
    hlpfile->Context = HeapAlloc(GetProcessHeap(), 0, clen);
    if (!hlpfile->Context) return FALSE;
    memcpy(hlpfile->Context, cbuf, clen);

    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2144 2145 2146 2147
}

/***********************************************************************
 *
2148
 *           HLPFILE_GetKeywords
Alexandre Julliard's avatar
Alexandre Julliard committed
2149
 */
2150
static BOOL HLPFILE_GetKeywords(HLPFILE *hlpfile)
Alexandre Julliard's avatar
Alexandre Julliard committed
2151
{
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
    BYTE                *cbuf, *cend;
    unsigned            clen;

    if (!HLPFILE_FindSubFile(hlpfile, "|KWBTREE", &cbuf, &cend)) return FALSE;
    clen = cend - cbuf;
    hlpfile->kwbtree = HeapAlloc(GetProcessHeap(), 0, clen);
    if (!hlpfile->kwbtree) return FALSE;
    memcpy(hlpfile->kwbtree, cbuf, clen);

    if (!HLPFILE_FindSubFile(hlpfile, "|KWDATA", &cbuf, &cend))
Alexandre Julliard's avatar
Alexandre Julliard committed
2162
    {
2163 2164 2165
        WINE_ERR("corrupted help file: kwbtree present but kwdata absent\n");
        HeapFree(GetProcessHeap(), 0, hlpfile->kwbtree);
        return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2166
    }
2167 2168 2169 2170 2171 2172 2173 2174
    clen = cend - cbuf;
    hlpfile->kwdata = HeapAlloc(GetProcessHeap(), 0, clen);
    if (!hlpfile->kwdata)
    {
        HeapFree(GetProcessHeap(), 0, hlpfile->kwdata);
        return FALSE;
    }
    memcpy(hlpfile->kwdata, cbuf, clen);
Alexandre Julliard's avatar
Alexandre Julliard committed
2175

2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
    return TRUE;
}

/***********************************************************************
 *
 *           HLPFILE_GetMap
 */
static BOOL HLPFILE_GetMap(HLPFILE *hlpfile)
{
    BYTE                *cbuf, *cend;
    unsigned            entries, i;

    if (!HLPFILE_FindSubFile(hlpfile, "|CTXOMAP",  &cbuf, &cend))
    {WINE_WARN("no map section\n"); return FALSE;}

    entries = GET_USHORT(cbuf, 9);
    hlpfile->Map = HeapAlloc(GetProcessHeap(), 0, entries * sizeof(HLPFILE_MAP));
    if (!hlpfile->Map) return FALSE;
    hlpfile->wMapLen = entries;
    for (i = 0; i < entries; i++)
    {
        hlpfile->Map[i].lMap = GET_UINT(cbuf+11,i*8);
        hlpfile->Map[i].offset = GET_UINT(cbuf+11,i*8+4);
    }
    return TRUE;
}

/***********************************************************************
 *
 *           HLPFILE_GetTOMap
 */
static BOOL HLPFILE_GetTOMap(HLPFILE *hlpfile)
{
    BYTE                *cbuf, *cend;
    unsigned            clen;

    if (!HLPFILE_FindSubFile(hlpfile, "|TOMAP",  &cbuf, &cend))
    {WINE_WARN("no tomap section\n"); return FALSE;}

    clen = cend - cbuf - 9;
    hlpfile->TOMap = HeapAlloc(GetProcessHeap(), 0, clen);
    if (!hlpfile->TOMap) return FALSE;
    memcpy(hlpfile->TOMap, cbuf+9, clen);
    hlpfile->wTOMapLen = clen/4;
    return TRUE;
}

/***********************************************************************
 *
 *           DeleteMacro
 */
static void HLPFILE_DeleteMacro(HLPFILE_MACRO* macro)
{
    HLPFILE_MACRO*      next;

    while (macro)
    {
        next = macro->next;
        HeapFree(GetProcessHeap(), 0, macro);
        macro = next;
    }
}

/***********************************************************************
 *
 *           DeletePage
 */
static void HLPFILE_DeletePage(HLPFILE_PAGE* page)
{
    HLPFILE_PAGE* next;

    while (page)
    {
        next = page->next;
        HLPFILE_DeleteMacro(page->first_macro);
        HeapFree(GetProcessHeap(), 0, page);
        page = next;
    }
}

/***********************************************************************
 *
 *           HLPFILE_FreeHlpFile
 */
void HLPFILE_FreeHlpFile(HLPFILE* hlpfile)
{
    unsigned i;

    if (!hlpfile || --hlpfile->wRefCount > 0) return;

    if (hlpfile->next) hlpfile->next->prev = hlpfile->prev;
    if (hlpfile->prev) hlpfile->prev->next = hlpfile->next;
    else first_hlpfile = hlpfile->next;

    if (hlpfile->numFonts)
    {
        for (i = 0; i < hlpfile->numFonts; i++)
        {
            DeleteObject(hlpfile->fonts[i].hFont);
        }
        HeapFree(GetProcessHeap(), 0, hlpfile->fonts);
    }

    if (hlpfile->numBmps)
    {
        for (i = 0; i < hlpfile->numBmps; i++)
        {
            DeleteObject(hlpfile->bmps[i]);
        }
        HeapFree(GetProcessHeap(), 0, hlpfile->bmps);
    }

    HLPFILE_DeletePage(hlpfile->first_page);
    HLPFILE_DeleteMacro(hlpfile->first_macro);

    DestroyIcon(hlpfile->hIcon);
    if (hlpfile->numWindows)    HeapFree(GetProcessHeap(), 0, hlpfile->windows);
    HeapFree(GetProcessHeap(), 0, hlpfile->Context);
    HeapFree(GetProcessHeap(), 0, hlpfile->Map);
    HeapFree(GetProcessHeap(), 0, hlpfile->lpszTitle);
    HeapFree(GetProcessHeap(), 0, hlpfile->lpszCopyright);
    HeapFree(GetProcessHeap(), 0, hlpfile->file_buffer);
    HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
    HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
    HeapFree(GetProcessHeap(), 0, hlpfile->topic_map);
    HeapFree(GetProcessHeap(), 0, hlpfile->help_on_file);
    HeapFree(GetProcessHeap(), 0, hlpfile);
Alexandre Julliard's avatar
Alexandre Julliard committed
2303 2304 2305 2306
}

/***********************************************************************
 *
2307
 *           HLPFILE_UncompressLZ77_Phrases
Alexandre Julliard's avatar
Alexandre Julliard committed
2308
 */
2309
static BOOL HLPFILE_UncompressLZ77_Phrases(HLPFILE* hlpfile)
Alexandre Julliard's avatar
Alexandre Julliard committed
2310
{
2311
    UINT i, num, dec_size, head_size;
2312 2313
    BYTE *buf, *end;

2314
    if (!HLPFILE_FindSubFile(hlpfile, "|Phrases", &buf, &end)) return FALSE;
2315

2316 2317 2318 2319 2320
    if (hlpfile->version <= 16)
        head_size = 13;
    else
        head_size = 17;

2321
    num = hlpfile->num_phrases = GET_USHORT(buf, 9);
2322 2323
    if (buf + 2 * num + 0x13 >= end) {WINE_WARN("1a\n"); return FALSE;};

2324 2325 2326 2327
    if (hlpfile->version <= 16)
        dec_size = end - buf - 15 - 2 * num;
    else
        dec_size = HLPFILE_UncompressedLZ77_Size(buf + 0x13 + 2 * num, end);
2328

2329 2330 2331
    hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
    hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
    if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2332
    {
2333 2334
        HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
        HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2335 2336
        return FALSE;
    }
2337 2338

    for (i = 0; i <= num; i++)
2339
        hlpfile->phrases_offsets[i] = GET_USHORT(buf, head_size + 2 * i) - 2 * num - 2;
Alexandre Julliard's avatar
Alexandre Julliard committed
2340

2341
    if (hlpfile->version <= 16)
2342
        memcpy(hlpfile->phrases_buffer, buf + 15 + 2*num, dec_size);
2343
    else
2344
        HLPFILE_UncompressLZ77(buf + 0x13 + 2 * num, end, (BYTE*)hlpfile->phrases_buffer);
Alexandre Julliard's avatar
Alexandre Julliard committed
2345

2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
    hlpfile->hasPhrases = TRUE;
    return TRUE;
}

/***********************************************************************
 *
 *           HLPFILE_Uncompress_Phrases40
 */
static BOOL HLPFILE_Uncompress_Phrases40(HLPFILE* hlpfile)
{
2356 2357
    UINT num;
    INT dec_size, cpr_size;
2358 2359
    BYTE *buf_idx, *end_idx;
    BYTE *buf_phs, *end_phs;
2360
    ULONG* ptr, mask = 0;
2361 2362
    unsigned int i;
    unsigned short bc, n;
2363

2364 2365
    if (!HLPFILE_FindSubFile(hlpfile, "|PhrIndex", &buf_idx, &end_idx) ||
        !HLPFILE_FindSubFile(hlpfile, "|PhrImage", &buf_phs, &end_phs)) return FALSE;
2366

2367
    ptr = (ULONG*)(buf_idx + 9 + 28);
2368
    bc = GET_USHORT(buf_idx, 9 + 24) & 0x0F;
2369
    num = hlpfile->num_phrases = GET_USHORT(buf_idx, 9 + 4);
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382

    WINE_TRACE("Index: Magic=%08x #entries=%u CpsdSize=%u PhrImgSize=%u\n"
               "\tPhrImgCprsdSize=%u 0=%u bc=%x ukn=%x\n",
               GET_UINT(buf_idx, 9 + 0),
               GET_UINT(buf_idx, 9 + 4),
               GET_UINT(buf_idx, 9 + 8),
               GET_UINT(buf_idx, 9 + 12),
               GET_UINT(buf_idx, 9 + 16),
               GET_UINT(buf_idx, 9 + 20),
               GET_USHORT(buf_idx, 9 + 24),
               GET_USHORT(buf_idx, 9 + 26));

    dec_size = GET_UINT(buf_idx, 9 + 12);
2383 2384 2385 2386
    cpr_size = GET_UINT(buf_idx, 9 + 16);

    if (dec_size != cpr_size &&
        dec_size != HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs))
2387 2388
    {
        WINE_WARN("size mismatch %u %u\n",
2389 2390
                  dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
        dec_size = max(dec_size, HLPFILE_UncompressedLZ77_Size(buf_phs + 9, end_phs));
2391
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
2392

2393 2394 2395
    hlpfile->phrases_offsets = HeapAlloc(GetProcessHeap(), 0, sizeof(unsigned) * (num + 1));
    hlpfile->phrases_buffer  = HeapAlloc(GetProcessHeap(), 0, dec_size);
    if (!hlpfile->phrases_offsets || !hlpfile->phrases_buffer)
2396
    {
2397 2398
        HeapFree(GetProcessHeap(), 0, hlpfile->phrases_offsets);
        HeapFree(GetProcessHeap(), 0, hlpfile->phrases_buffer);
2399 2400
        return FALSE;
    }
Alexandre Julliard's avatar
Alexandre Julliard committed
2401

2402
#define getbit() ((mask <<= 1) ? (*ptr & mask) != 0: (*++ptr & (mask=1)) != 0)
Alexandre Julliard's avatar
Alexandre Julliard committed
2403

2404
    hlpfile->phrases_offsets[0] = 0;
2405
    ptr--; /* as we'll first increment ptr because mask is 0 on first getbit() call */
2406
    for (i = 0; i < num; i++)
Alexandre Julliard's avatar
Alexandre Julliard committed
2407
    {
2408 2409 2410 2411 2412 2413
        for (n = 1; getbit(); n += 1 << bc);
        if (getbit()) n++;
        if (bc > 1 && getbit()) n += 2;
        if (bc > 2 && getbit()) n += 4;
        if (bc > 3 && getbit()) n += 8;
        if (bc > 4 && getbit()) n += 16;
2414
        hlpfile->phrases_offsets[i + 1] = hlpfile->phrases_offsets[i] + n;
Alexandre Julliard's avatar
Alexandre Julliard committed
2415
    }
2416 2417
#undef getbit

2418
    if (dec_size == cpr_size)
2419
        memcpy(hlpfile->phrases_buffer, buf_phs + 9, dec_size);
2420
    else
2421
        HLPFILE_UncompressLZ77(buf_phs + 9, end_phs, (BYTE*)hlpfile->phrases_buffer);
2422

2423
    hlpfile->hasPhrases40 = TRUE;
2424
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2425 2426 2427 2428
}

/***********************************************************************
 *
Eric Pouech's avatar
Eric Pouech committed
2429
 *           HLPFILE_Uncompress_Topic
Alexandre Julliard's avatar
Alexandre Julliard committed
2430
 */
Eric Pouech's avatar
Eric Pouech committed
2431
static BOOL HLPFILE_Uncompress_Topic(HLPFILE* hlpfile)
Alexandre Julliard's avatar
Alexandre Julliard committed
2432
{
2433
    BYTE *buf, *ptr, *end, *newptr;
2434
    unsigned int i, newsize = 0;
2435
    unsigned int topic_size;
2436

2437
    if (!HLPFILE_FindSubFile(hlpfile, "|TOPIC", &buf, &end))
2438
    {WINE_WARN("topic0\n"); return FALSE;}
Alexandre Julliard's avatar
Alexandre Julliard committed
2439

2440 2441 2442
    buf += 9; /* Skip file header */
    topic_size = end - buf;
    if (hlpfile->compressed)
Alexandre Julliard's avatar
Alexandre Julliard committed
2443
    {
2444
        hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
2445

2446
        for (i = 0; i < hlpfile->topic_maplen; i++)
Eric Pouech's avatar
Eric Pouech committed
2447
        {
2448 2449
            ptr = buf + i * hlpfile->tbsize;

Eric Pouech's avatar
Eric Pouech committed
2450 2451
            /* I don't know why, it's necessary for printman.hlp */
            if (ptr + 0x44 > end) ptr = end - 0x44;
Alexandre Julliard's avatar
Alexandre Julliard committed
2452

2453
            newsize += HLPFILE_UncompressedLZ77_Size(ptr + 0xc, min(end, ptr + hlpfile->tbsize));
Eric Pouech's avatar
Eric Pouech committed
2454
        }
2455

2456 2457 2458 2459 2460
        hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
                                       hlpfile->topic_maplen * sizeof(hlpfile->topic_map[0]) + newsize);
        if (!hlpfile->topic_map) return FALSE;
        newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
        hlpfile->topic_end = newptr + newsize;
Eric Pouech's avatar
Eric Pouech committed
2461

2462
        for (i = 0; i < hlpfile->topic_maplen; i++)
Eric Pouech's avatar
Eric Pouech committed
2463
        {
2464
            ptr = buf + i * hlpfile->tbsize;
Eric Pouech's avatar
Eric Pouech committed
2465
            if (ptr + 0x44 > end) ptr = end - 0x44;
Alexandre Julliard's avatar
Alexandre Julliard committed
2466

2467
            hlpfile->topic_map[i] = newptr;
2468
            newptr = HLPFILE_UncompressLZ77(ptr + 0xc, min(end, ptr + hlpfile->tbsize), newptr);
Eric Pouech's avatar
Eric Pouech committed
2469
        }
2470 2471 2472 2473 2474
    }
    else
    {
        /* basically, we need to copy the TopicBlockSize byte pages
         * (removing the first 0x0C) in one single area in memory
Eric Pouech's avatar
Eric Pouech committed
2475
         */
2476 2477 2478 2479 2480 2481 2482 2483
        hlpfile->topic_maplen = (topic_size - 1) / hlpfile->tbsize + 1;
        hlpfile->topic_map = HeapAlloc(GetProcessHeap(), 0,
                                       hlpfile->topic_maplen * (sizeof(hlpfile->topic_map[0]) + hlpfile->dsize));
        if (!hlpfile->topic_map) return FALSE;
        newptr = (BYTE*)(hlpfile->topic_map + hlpfile->topic_maplen);
        hlpfile->topic_end = newptr + topic_size;

        for (i = 0; i < hlpfile->topic_maplen; i++)
Eric Pouech's avatar
Eric Pouech committed
2484
        {
2485 2486
            hlpfile->topic_map[i] = newptr + i * hlpfile->dsize;
            memcpy(hlpfile->topic_map[i], buf + i * hlpfile->tbsize + 0x0C, hlpfile->dsize);
Eric Pouech's avatar
Eric Pouech committed
2487
        }
Alexandre Julliard's avatar
Alexandre Julliard committed
2488
    }
2489
    return TRUE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2490 2491 2492 2493
}

/***********************************************************************
 *
2494
 *           HLPFILE_AddPage
Alexandre Julliard's avatar
Alexandre Julliard committed
2495
 */
2496
static BOOL HLPFILE_AddPage(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned ref, unsigned offset)
2497
{
2498 2499 2500 2501 2502
    HLPFILE_PAGE* page;
    const BYTE*   title;
    UINT          titlesize, blocksize, datalen;
    char*         ptr;
    HLPFILE_MACRO*macro;
2503

2504 2505 2506 2507
    blocksize = GET_UINT(buf, 0);
    datalen = GET_UINT(buf, 0x10);
    title = buf + datalen;
    if (title > end) {WINE_WARN("page2\n"); return FALSE;};
2508

2509 2510 2511 2512
    titlesize = GET_UINT(buf, 4);
    page = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_PAGE) + titlesize + 1);
    if (!page) return FALSE;
    page->lpszTitle = (char*)page + sizeof(HLPFILE_PAGE);
Alexandre Julliard's avatar
Alexandre Julliard committed
2513

2514
    if (titlesize > blocksize - datalen)
2515
    {
2516 2517 2518 2519 2520
        /* need to decompress */
        if (hlpfile->hasPhrases)
            HLPFILE_Uncompress2(hlpfile, title, end, (BYTE*)page->lpszTitle, (BYTE*)page->lpszTitle + titlesize);
        else if (hlpfile->hasPhrases40)
            HLPFILE_Uncompress3(hlpfile, page->lpszTitle, page->lpszTitle + titlesize, title, end);
2521 2522
        else
        {
2523 2524 2525
            WINE_FIXME("Text size is too long, splitting\n");
            titlesize = blocksize - datalen;
            memcpy(page->lpszTitle, title, titlesize);
2526 2527
        }
    }
2528 2529
    else
        memcpy(page->lpszTitle, title, titlesize);
2530

2531
    page->lpszTitle[titlesize] = '\0';
2532

2533
    if (hlpfile->first_page)
2534
    {
2535 2536 2537
        hlpfile->last_page->next = page;
        page->prev = hlpfile->last_page;
        hlpfile->last_page = page;
2538
    }
2539
    else
2540
    {
2541 2542 2543
        hlpfile->first_page = page;
        hlpfile->last_page = page;
        page->prev = NULL;
2544
    }
2545

2546 2547 2548 2549 2550 2551 2552
    page->file            = hlpfile;
    page->next            = NULL;
    page->first_macro     = NULL;
    page->first_link      = NULL;
    page->wNumber         = GET_UINT(buf, 0x21);
    page->offset          = offset;
    page->reference       = ref;
2553

2554 2555 2556 2557
    page->browse_bwd = GET_UINT(buf, 0x19);
    page->browse_fwd = GET_UINT(buf, 0x1D);

    if (hlpfile->version <= 16)
2558
    {
2559 2560 2561 2562 2563 2564 2565 2566 2567
        if (page->browse_bwd == 0xFFFF || page->browse_bwd == 0xFFFFFFFF)
            page->browse_bwd = 0xFFFFFFFF;
        else
            page->browse_bwd = hlpfile->TOMap[page->browse_bwd];

        if (page->browse_fwd == 0xFFFF || page->browse_fwd == 0xFFFFFFFF)
            page->browse_fwd = 0xFFFFFFFF;
        else
            page->browse_fwd = hlpfile->TOMap[page->browse_fwd];
2568
    }
2569 2570 2571 2572 2573 2574 2575 2576

    WINE_TRACE("Added page[%d]: title='%s' %08x << %08x >> %08x\n",
               page->wNumber, page->lpszTitle,
               page->browse_bwd, page->offset, page->browse_fwd);

    /* now load macros */
    ptr = page->lpszTitle + strlen(page->lpszTitle) + 1;
    while (ptr < page->lpszTitle + titlesize)
2577
    {
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
        unsigned len = strlen(ptr);
        char*    macro_str;

        WINE_TRACE("macro: %s\n", ptr);
        macro = HeapAlloc(GetProcessHeap(), 0, sizeof(HLPFILE_MACRO) + len + 1);
        macro->lpszMacro = macro_str = (char*)(macro + 1);
        memcpy(macro_str, ptr, len + 1);
        /* FIXME: shall we really link macro in reverse order ??
         * may produce strange results when played at page opening
         */
        macro->next = page->first_macro;
        page->first_macro = macro;
        ptr += len + 1;
2591 2592 2593 2594 2595
    }

    return TRUE;
}

2596 2597
/***********************************************************************
 *
2598
 *           HLPFILE_SkipParagraph
2599
 */
2600
static BOOL HLPFILE_SkipParagraph(HLPFILE *hlpfile, const BYTE *buf, const BYTE *end, unsigned* len)
2601
{
2602
    const BYTE  *tmp;
2603

2604 2605
    if (!hlpfile->first_page) {WINE_WARN("no page\n"); return FALSE;};
    if (buf + 0x19 > end) {WINE_WARN("header too small\n"); return FALSE;};
2606

2607 2608
    tmp = buf + 0x15;
    if (buf[0x14] == 0x20 || buf[0x14] == 0x23)
2609
    {
2610 2611
        fetch_long(&tmp);
        *len = fetch_ushort(&tmp);
2612
    }
2613 2614
    else *len = end-buf-15;

2615 2616 2617
    return TRUE;
}

2618 2619
/***********************************************************************
 *
2620
 *           HLPFILE_DoReadHlpFile
2621
 */
2622
static BOOL HLPFILE_DoReadHlpFile(HLPFILE *hlpfile, LPCSTR lpszPath)
2623
{
2624 2625 2626 2627 2628 2629
    BOOL        ret;
    HFILE       hFile;
    OFSTRUCT    ofs;
    BYTE*       buf;
    DWORD       ref = 0x0C;
    unsigned    index, old_index, offset, len, offs, topicoffset;
2630

2631 2632
    hFile = OpenFile(lpszPath, &ofs, OF_READ);
    if (hFile == HFILE_ERROR) return FALSE;
2633

2634 2635 2636
    ret = HLPFILE_ReadFileToBuffer(hlpfile, hFile);
    _lclose(hFile);
    if (!ret) return FALSE;
2637

2638
    if (!HLPFILE_SystemCommands(hlpfile)) return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2639

2640
    if (hlpfile->version <= 16 && !HLPFILE_GetTOMap(hlpfile)) return FALSE;
Alexandre Julliard's avatar
Alexandre Julliard committed
2641

2642 2643 2644
    /* load phrases support */
    if (!HLPFILE_UncompressLZ77_Phrases(hlpfile))
        HLPFILE_Uncompress_Phrases40(hlpfile);
Alexandre Julliard's avatar
Alexandre Julliard committed
2645

2646 2647 2648 2649 2650 2651
    if (!HLPFILE_Uncompress_Topic(hlpfile)) return FALSE;
    if (!HLPFILE_ReadFont(hlpfile)) return FALSE;

    old_index = -1;
    offs = 0;
    do
2652
    {
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
        BYTE*   end;

        if (hlpfile->version <= 16)
        {
            index  = (ref - 0x0C) / hlpfile->dsize;
            offset = (ref - 0x0C) % hlpfile->dsize;
        }
        else
        {
            index  = (ref - 0x0C) >> 14;
            offset = (ref - 0x0C) & 0x3FFF;
        }

        if (hlpfile->version <= 16 && index != old_index && old_index != -1)
        {
            /* we jumped to the next block, adjust pointers */
            ref -= 12;
            offset -= 12;
        }

        WINE_TRACE("ref=%08x => [%u/%u]\n", ref, index, offset);

        if (index >= hlpfile->topic_maplen) {WINE_WARN("maplen\n"); break;}
        buf = hlpfile->topic_map[index] + offset;
        if (buf + 0x15 >= hlpfile->topic_end) {WINE_WARN("extra\n"); break;}
        end = min(buf + GET_UINT(buf, 0), hlpfile->topic_end);
        if (index != old_index) {offs = 0; old_index = index;}

        switch (buf[0x14])
	{
	case 0x02:
            if (hlpfile->version <= 16)
                topicoffset = ref + index * 12;
            else
                topicoffset = index * 0x8000 + offs;
            if (!HLPFILE_AddPage(hlpfile, buf, end, ref, topicoffset)) return FALSE;
            break;

	case 0x01:
	case 0x20:
	case 0x23:
            if (!HLPFILE_SkipParagraph(hlpfile, buf, end, &len)) return FALSE;
            offs += len;
            break;

	default:
            WINE_ERR("buf[0x14] = %x\n", buf[0x14]);
	}

        if (hlpfile->version <= 16)
        {
            ref += GET_UINT(buf, 0xc);
            if (GET_UINT(buf, 0xc) == 0)
                break;
        }
        else
            ref = GET_UINT(buf, 0xc);
    } while (ref != 0xffffffff);

    HLPFILE_GetKeywords(hlpfile);
    HLPFILE_GetMap(hlpfile);
    if (hlpfile->version <= 16) return TRUE;
    return HLPFILE_GetContext(hlpfile);
Alexandre Julliard's avatar
Alexandre Julliard committed
2716 2717 2718 2719
}

/***********************************************************************
 *
2720
 *           HLPFILE_ReadHlpFile
Alexandre Julliard's avatar
Alexandre Julliard committed
2721
 */
2722
HLPFILE *HLPFILE_ReadHlpFile(LPCSTR lpszPath)
Alexandre Julliard's avatar
Alexandre Julliard committed
2723
{
2724
    HLPFILE*      hlpfile;
Alexandre Julliard's avatar
Alexandre Julliard committed
2725

2726
    for (hlpfile = first_hlpfile; hlpfile; hlpfile = hlpfile->next)
2727
    {
2728
        if (!strcmp(lpszPath, hlpfile->lpszPath))
2729
        {
2730 2731
            hlpfile->wRefCount++;
            return hlpfile;
2732 2733 2734
        }
    }

2735
    hlpfile = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2736
                        sizeof(HLPFILE) + strlen(lpszPath) + 1);
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
    if (!hlpfile) return 0;

    hlpfile->lpszPath           = (char*)hlpfile + sizeof(HLPFILE);
    hlpfile->contents_start     = 0xFFFFFFFF;
    hlpfile->next               = first_hlpfile;
    hlpfile->wRefCount          = 1;

    strcpy(hlpfile->lpszPath, lpszPath);

    first_hlpfile = hlpfile;
    if (hlpfile->next) hlpfile->next->prev = hlpfile;

    if (!HLPFILE_DoReadHlpFile(hlpfile, lpszPath))
Eric Pouech's avatar
Eric Pouech committed
2750
    {
2751 2752
        HLPFILE_FreeHlpFile(hlpfile);
        hlpfile = 0;
Eric Pouech's avatar
Eric Pouech committed
2753 2754
    }

2755
    return hlpfile;
Alexandre Julliard's avatar
Alexandre Julliard committed
2756
}