winedbg: Enforce 64bit modules address on 64bit platforms.
[wine] / programs / winhlp32 / winhelp.c
1 /*
2  * Help Viewer
3  *
4  * Copyright    1996 Ulrich Schmid <uschmid@mail.hh.provi.de>
5  *              2002 Sylvain Petreolle <spetreolle@yahoo.fr>
6  *              2002, 2008 Eric Pouech <eric.pouech@wanadoo.fr>
7  *              2004 Ken Belleau <jamez@ivic.qc.ca>
8  *              2008 Kirill K. Smirnov <lich@math.spbu.ru>
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include <assert.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "wingdi.h"
37 #include "winuser.h"
38 #include "commdlg.h"
39 #include "winhelp.h"
40 #include "winhelp_res.h"
41 #include "shellapi.h"
42 #include "richedit.h"
43 #include "commctrl.h"
44
45 #include "wine/debug.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(winhelp);
48
49 WINHELP_GLOBALS Globals = {3, NULL, TRUE, NULL, NULL, NULL, NULL, NULL, {{{NULL,NULL}},0}, NULL};
50
51 #define CTL_ID_BUTTON   0x700
52 #define CTL_ID_TEXT     0x701
53
54
55 /***********************************************************************
56  *
57  *           WINHELP_InitFonts
58  */
59 static void WINHELP_InitFonts(HWND hWnd)
60 {
61     WINHELP_WINDOW *win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
62     LOGFONT logfontlist[] = {
63         {-10, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
64         {-12, 0, 0, 0, 700, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
65         {-12, 0, 0, 0, 700, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
66         {-12, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
67         {-12, 0, 0, 0, 700, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
68         {-10, 0, 0, 0, 700, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"},
69         { -8, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, 0, 0, 0, 32, "Helv"}};
70 #define FONTS_LEN (sizeof(logfontlist)/sizeof(*logfontlist))
71
72     static HFONT fonts[FONTS_LEN];
73     static BOOL init = 0;
74
75     win->fonts_len = FONTS_LEN;
76     win->fonts = fonts;
77
78     if (!init)
79     {
80         UINT i;
81
82         for (i = 0; i < FONTS_LEN; i++)
83         {
84             fonts[i] = CreateFontIndirect(&logfontlist[i]);
85         }
86
87         init = 1;
88     }
89 }
90
91 static DWORD CALLBACK WINHELP_RtfStreamIn(DWORD_PTR cookie, BYTE* buff,
92                                           LONG cb, LONG* pcb)
93 {
94     struct RtfData*     rd = (struct RtfData*)cookie;
95
96     if (rd->where >= rd->ptr) return 1;
97     if (rd->where + cb > rd->ptr)
98         cb = rd->ptr - rd->where;
99     memcpy(buff, rd->where, cb);
100     rd->where += cb;
101     *pcb = cb;
102     return 0;
103 }
104
105 static void WINHELP_SetupText(HWND hTextWnd, WINHELP_WINDOW* win, ULONG relative)
106 {
107     /* At first clear area - needed by EM_POSFROMCHAR/EM_SETSCROLLPOS */
108     SendMessage(hTextWnd, WM_SETTEXT, 0, (LPARAM)"");
109     SendMessage(hTextWnd, WM_SETREDRAW, FALSE, 0);
110     SendMessage(hTextWnd, EM_SETBKGNDCOLOR, 0, (LPARAM)win->info->sr_color);
111     /* set word-wrap to window size (undocumented) */
112     SendMessage(hTextWnd, EM_SETTARGETDEVICE, 0, 0);
113     if (win->page)
114     {
115         struct RtfData  rd;
116         EDITSTREAM      es;
117         unsigned        cp = 0;
118         POINTL          ptl;
119         POINT           pt;
120
121
122         if (HLPFILE_BrowsePage(win->page, &rd, win->font_scale, relative))
123         {
124             rd.where = rd.data;
125             es.dwCookie = (DWORD_PTR)&rd;
126             es.dwError = 0;
127             es.pfnCallback = WINHELP_RtfStreamIn;
128
129             SendMessageW(hTextWnd, EM_STREAMIN, SF_RTF, (LPARAM)&es);
130             cp = rd.char_pos_rel;
131         }
132         /* FIXME: else leaking potentially the rd.first_link chain */
133         HeapFree(GetProcessHeap(), 0, rd.data);
134         SendMessage(hTextWnd, EM_POSFROMCHAR, (WPARAM)&ptl, cp ? cp - 1 : 0);
135         pt.x = 0; pt.y = ptl.y;
136         SendMessage(hTextWnd, EM_SETSCROLLPOS, 0, (LPARAM)&pt);
137     }
138     SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0);
139     RedrawWindow(hTextWnd, NULL, NULL, RDW_FRAME|RDW_INVALIDATE);
140 }
141
142 /***********************************************************************
143  *
144  *           WINHELP_GetOpenFileName
145  */
146 BOOL WINHELP_GetOpenFileName(LPSTR lpszFile, int len)
147 {
148     OPENFILENAME openfilename;
149     CHAR szDir[MAX_PATH];
150     CHAR szzFilter[2 * MAX_STRING_LEN + 100];
151     LPSTR p = szzFilter;
152
153     WINE_TRACE("()\n");
154
155     LoadString(Globals.hInstance, STID_HELP_FILES_HLP, p, MAX_STRING_LEN);
156     p += strlen(p) + 1;
157     lstrcpy(p, "*.hlp");
158     p += strlen(p) + 1;
159     LoadString(Globals.hInstance, STID_ALL_FILES, p, MAX_STRING_LEN);
160     p += strlen(p) + 1;
161     lstrcpy(p, "*.*");
162     p += strlen(p) + 1;
163     *p = '\0';
164
165     GetCurrentDirectory(sizeof(szDir), szDir);
166
167     lpszFile[0]='\0';
168
169     openfilename.lStructSize       = sizeof(OPENFILENAME);
170     openfilename.hwndOwner         = (Globals.active_win ? Globals.active_win->hMainWnd : 0);
171     openfilename.hInstance         = Globals.hInstance;
172     openfilename.lpstrFilter       = szzFilter;
173     openfilename.lpstrCustomFilter = 0;
174     openfilename.nMaxCustFilter    = 0;
175     openfilename.nFilterIndex      = 1;
176     openfilename.lpstrFile         = lpszFile;
177     openfilename.nMaxFile          = len;
178     openfilename.lpstrFileTitle    = 0;
179     openfilename.nMaxFileTitle     = 0;
180     openfilename.lpstrInitialDir   = szDir;
181     openfilename.lpstrTitle        = 0;
182     openfilename.Flags             = OFN_ENABLESIZING;
183     openfilename.nFileOffset       = 0;
184     openfilename.nFileExtension    = 0;
185     openfilename.lpstrDefExt       = 0;
186     openfilename.lCustData         = 0;
187     openfilename.lpfnHook          = 0;
188     openfilename.lpTemplateName    = 0;
189
190     return GetOpenFileName(&openfilename);
191 }
192
193 /***********************************************************************
194  *
195  *           WINHELP_MessageBoxIDS_s
196  */
197 static INT WINHELP_MessageBoxIDS_s(UINT ids_text, LPCSTR str, UINT ids_title, WORD type)
198 {
199     CHAR text[MAX_STRING_LEN];
200     CHAR newtext[MAX_STRING_LEN + MAX_PATH];
201
202     LoadString(Globals.hInstance, ids_text, text, sizeof(text));
203     wsprintf(newtext, text, str);
204
205     return MessageBox(0, newtext, MAKEINTRESOURCE(ids_title), type);
206 }
207
208 /***********************************************************************
209  *
210  *           WINHELP_LookupHelpFile
211  */
212 HLPFILE* WINHELP_LookupHelpFile(LPCSTR lpszFile)
213 {
214     HLPFILE*        hlpfile;
215     char szFullName[MAX_PATH];
216     char szAddPath[MAX_PATH];
217     char *p;
218
219     /*
220      * NOTE: This is needed by popup windows only.
221      * In other cases it's not needed but does not hurt though.
222      */
223     if (Globals.active_win && Globals.active_win->page && Globals.active_win->page->file)
224     {
225         strcpy(szAddPath, Globals.active_win->page->file->lpszPath);
226         p = strrchr(szAddPath, '\\');
227         if (p) *p = 0;
228     }
229
230     /*
231      * FIXME: Should we swap conditions?
232      */
233     if (!SearchPath(NULL, lpszFile, ".hlp", MAX_PATH, szFullName, NULL) &&
234         !SearchPath(szAddPath, lpszFile, ".hlp", MAX_PATH, szFullName, NULL))
235     {
236         if (WINHELP_MessageBoxIDS_s(STID_FILE_NOT_FOUND_s, lpszFile, STID_WHERROR,
237                                     MB_YESNO|MB_ICONQUESTION) != IDYES)
238             return NULL;
239         if (!WINHELP_GetOpenFileName(szFullName, MAX_PATH))
240             return NULL;
241     }
242     hlpfile = HLPFILE_ReadHlpFile(szFullName);
243     if (!hlpfile)
244         WINHELP_MessageBoxIDS_s(STID_HLPFILE_ERROR_s, lpszFile,
245                                 STID_WHERROR, MB_OK|MB_ICONSTOP);
246     return hlpfile;
247 }
248
249 /******************************************************************
250  *              WINHELP_GetWindowInfo
251  *
252  *
253  */
254 HLPFILE_WINDOWINFO*     WINHELP_GetWindowInfo(HLPFILE* hlpfile, LPCSTR name)
255 {
256     static      HLPFILE_WINDOWINFO      mwi;
257     unsigned int     i;
258
259     if (!name || !name[0])
260         name = Globals.active_win->info->name;
261
262     if (hlpfile)
263         for (i = 0; i < hlpfile->numWindows; i++)
264             if (!lstrcmpi(hlpfile->windows[i].name, name))
265                 return &hlpfile->windows[i];
266
267     if (strcmp(name, "main") != 0)
268     {
269         WINE_FIXME("Couldn't find window info for %s\n", name);
270         assert(0);
271         return NULL;
272     }
273     if (!mwi.name[0])
274     {
275         strcpy(mwi.type, "primary");
276         strcpy(mwi.name, "main");
277         if (hlpfile && hlpfile->lpszTitle[0])
278         {
279             char        tmp[128];
280             LoadString(Globals.hInstance, STID_WINE_HELP, tmp, sizeof(tmp));
281             snprintf(mwi.caption, sizeof(mwi.caption), "%s %s - %s",
282                      hlpfile->lpszTitle, tmp, hlpfile->lpszPath);
283         }
284         else
285             LoadString(Globals.hInstance, STID_WINE_HELP, mwi.caption, sizeof(mwi.caption));
286         mwi.origin.x = mwi.origin.y = mwi.size.cx = mwi.size.cy = CW_USEDEFAULT;
287         mwi.style = SW_SHOW;
288         mwi.win_style = WS_OVERLAPPEDWINDOW;
289         mwi.sr_color = mwi.nsr_color = 0xFFFFFF;
290     }
291     return &mwi;
292 }
293
294 /******************************************************************
295  *              HLPFILE_GetPopupWindowInfo
296  *
297  *
298  */
299 static HLPFILE_WINDOWINFO*     WINHELP_GetPopupWindowInfo(HLPFILE* hlpfile,
300                                                           WINHELP_WINDOW* parent, LPARAM mouse)
301 {
302     static      HLPFILE_WINDOWINFO      wi;
303
304     RECT parent_rect;
305     
306     wi.type[0] = wi.name[0] = wi.caption[0] = '\0';
307
308     /* Calculate horizontal size and position of a popup window */
309     GetWindowRect(parent->hMainWnd, &parent_rect);
310     wi.size.cx = (parent_rect.right  - parent_rect.left) / 2;
311     wi.size.cy = 10; /* need a non null value, so that border are taken into account while computing */
312
313     wi.origin.x = (short)LOWORD(mouse);
314     wi.origin.y = (short)HIWORD(mouse);
315     ClientToScreen(parent->hMainWnd, &wi.origin);
316     wi.origin.x -= wi.size.cx / 2;
317     wi.origin.x  = min(wi.origin.x, GetSystemMetrics(SM_CXSCREEN) - wi.size.cx);
318     wi.origin.x  = max(wi.origin.x, 0);
319
320     wi.style = SW_SHOW;
321     wi.win_style = WS_POPUP | WS_BORDER;
322     if (parent->page->file->has_popup_color)
323         wi.sr_color = parent->page->file->popup_color;
324     else
325         wi.sr_color = parent->info->sr_color;
326     wi.nsr_color = 0xFFFFFF;
327
328     return &wi;
329 }
330
331 typedef struct
332 {
333     WORD size;
334     WORD command;
335     LONG data;
336     LONG reserved;
337     WORD ofsFilename;
338     WORD ofsData;
339 } WINHELP,*LPWINHELP;
340
341 static BOOL WINHELP_HasWorkingWindow(void)
342 {
343     if (!Globals.active_win) return FALSE;
344     if (Globals.active_win->next || Globals.win_list != Globals.active_win) return TRUE;
345     return Globals.active_win->page != NULL && Globals.active_win->page->file != NULL;
346 }
347
348 /******************************************************************
349  *              WINHELP_HandleCommand
350  *
351  *
352  */
353 static LRESULT  WINHELP_HandleCommand(HWND hSrcWnd, LPARAM lParam)
354 {
355     COPYDATASTRUCT*     cds = (COPYDATASTRUCT*)lParam;
356     WINHELP*            wh;
357
358     if (cds->dwData != 0xA1DE505)
359     {
360         WINE_FIXME("Wrong magic number (%08lx)\n", cds->dwData);
361         return 0;
362     }
363
364     wh = cds->lpData;
365
366     if (wh)
367     {
368         char*   ptr = (wh->ofsFilename) ? (LPSTR)wh + wh->ofsFilename : NULL;
369
370         WINE_TRACE("Got[%u]: cmd=%u data=%08x fn=%s\n",
371                    wh->size, wh->command, wh->data, ptr);
372         switch (wh->command)
373         {
374         case HELP_CONTEXT:
375             if (ptr)
376             {
377                 MACRO_JumpContext(ptr, "main", wh->data);
378             }
379             if (!WINHELP_HasWorkingWindow()) MACRO_Exit();
380             break;
381         case HELP_QUIT:
382             MACRO_Exit();
383             break;
384         case HELP_CONTENTS:
385             if (ptr)
386             {
387                 MACRO_JumpContents(ptr, "main");
388             }
389             if (!WINHELP_HasWorkingWindow()) MACRO_Exit();
390             break;
391         case HELP_HELPONHELP:
392             MACRO_HelpOn();
393             if (!WINHELP_HasWorkingWindow()) MACRO_Exit();
394             break;
395         /* case HELP_SETINDEX: */
396         case HELP_SETCONTENTS:
397             if (ptr)
398             {
399                 MACRO_SetContents(ptr, wh->data);
400             }
401             break;
402         case HELP_CONTEXTPOPUP:
403             if (ptr)
404             {
405                 MACRO_PopupContext(ptr, wh->data);
406             }
407             break;
408         /* case HELP_FORCEFILE:*/
409         /* case HELP_CONTEXTMENU: */
410         case HELP_FINDER:
411             /* in fact, should be the topic dialog box */
412             WINE_FIXME("HELP_FINDER: stub\n");
413             if (ptr)
414             {
415                 MACRO_JumpHash(ptr, "main", 0);
416             }
417             break;
418         /* case HELP_WM_HELP: */
419         /* case HELP_SETPOPUP_POS: */
420         /* case HELP_KEY: */
421         /* case HELP_COMMAND: */
422         /* case HELP_PARTIALKEY: */
423         /* case HELP_MULTIKEY: */
424         /* case HELP_SETWINPOS: */
425         default:
426             WINE_FIXME("Unhandled command (%x) for remote winhelp control\n", wh->command);
427             break;
428         }
429     }
430     /* Always return success for now */
431     return 1;
432 }
433
434 void            WINHELP_LayoutMainWindow(WINHELP_WINDOW* win)
435 {
436     RECT        rect, button_box_rect;
437     INT         text_top = 0;
438     HWND        hButtonBoxWnd = GetDlgItem(win->hMainWnd, CTL_ID_BUTTON);
439     HWND        hTextWnd = GetDlgItem(win->hMainWnd, CTL_ID_TEXT);
440
441     GetClientRect(win->hMainWnd, &rect);
442
443     /* Update button box and text Window */
444     SetWindowPos(hButtonBoxWnd, HWND_TOP,
445                  rect.left, rect.top,
446                  rect.right - rect.left,
447                  rect.bottom - rect.top, 0);
448
449     if (GetWindowRect(hButtonBoxWnd, &button_box_rect))
450         text_top = rect.top + button_box_rect.bottom - button_box_rect.top;
451
452     SetWindowPos(hTextWnd, HWND_TOP,
453                  rect.left, text_top,
454                  rect.right - rect.left,
455                  rect.bottom - text_top, 0);
456
457 }
458
459 /******************************************************************
460  *              WINHELP_DeleteButtons
461  *
462  */
463 static void WINHELP_DeleteButtons(WINHELP_WINDOW* win)
464 {
465     WINHELP_BUTTON*     b;
466     WINHELP_BUTTON*     bp;
467
468     for (b = win->first_button; b; b = bp)
469     {
470         DestroyWindow(b->hWnd);
471         bp = b->next;
472         HeapFree(GetProcessHeap(), 0, b);
473     }
474     win->first_button = NULL;
475 }
476
477 /******************************************************************
478  *              WINHELP_DeleteBackSet
479  *
480  */
481 void WINHELP_DeleteBackSet(WINHELP_WINDOW* win)
482 {
483     unsigned int i;
484
485     for (i = 0; i < win->back.index; i++)
486     {
487         HLPFILE_FreeHlpFile(win->back.set[i].page->file);
488         win->back.set[i].page = NULL;
489     }
490     win->back.index = 0;
491 }
492
493 /******************************************************************
494  *             WINHELP_DeletePageLinks
495  *
496  */
497 static void WINHELP_DeletePageLinks(HLPFILE_PAGE* page)
498 {
499     HLPFILE_LINK*       curr;
500     HLPFILE_LINK*       next;
501
502     for (curr = page->first_link; curr; curr = next)
503     {
504         next = curr->next;
505         HeapFree(GetProcessHeap(), 0, curr);
506     }
507 }
508
509 /***********************************************************************
510  *
511  *           WINHELP_GrabWindow
512  */
513 WINHELP_WINDOW* WINHELP_GrabWindow(WINHELP_WINDOW* win)
514 {
515     WINE_TRACE("Grab %p#%d++\n", win, win->ref_count);
516     win->ref_count++;
517     return win;
518 }
519
520 /***********************************************************************
521  *
522  *           WINHELP_RelaseWindow
523  */
524 BOOL WINHELP_ReleaseWindow(WINHELP_WINDOW* win)
525 {
526     WINE_TRACE("Release %p#%d--\n", win, win->ref_count);
527
528     if (!--win->ref_count)
529     {
530         DestroyWindow(win->hMainWnd);
531         return FALSE;
532     }
533     return TRUE;
534 }
535
536 /***********************************************************************
537  *
538  *           WINHELP_DeleteWindow
539  */
540 static void WINHELP_DeleteWindow(WINHELP_WINDOW* win)
541 {
542     WINHELP_WINDOW**    w;
543     BOOL bExit;
544     HWND hTextWnd;
545
546     for (w = &Globals.win_list; *w; w = &(*w)->next)
547     {
548         if (*w == win)
549         {
550             *w = win->next;
551             break;
552         }
553     }
554     bExit = (Globals.wVersion >= 4 && !lstrcmpi(win->info->name, "main"));
555
556     if (Globals.active_win == win)
557     {
558         Globals.active_win = Globals.win_list;
559         if (Globals.win_list)
560             SetActiveWindow(Globals.win_list->hMainWnd);
561     }
562
563     if (win == Globals.active_popup)
564         Globals.active_popup = NULL;
565
566     hTextWnd = GetDlgItem(win->hMainWnd, CTL_ID_TEXT);
567     SetWindowLongPtr(hTextWnd, GWLP_WNDPROC,
568                      (LONG_PTR)win->origRicheditWndProc);
569
570     WINHELP_DeleteButtons(win);
571
572     if (win->page) WINHELP_DeletePageLinks(win->page);
573     if (win->hShadowWnd) DestroyWindow(win->hShadowWnd);
574     if (win->hHistoryWnd) DestroyWindow(win->hHistoryWnd);
575
576     DeleteObject(win->hBrush);
577
578     WINHELP_DeleteBackSet(win);
579
580     if (win->page) HLPFILE_FreeHlpFile(win->page->file);
581     HeapFree(GetProcessHeap(), 0, win);
582
583     if (bExit) MACRO_Exit();
584     if (!Globals.win_list)
585         PostQuitMessage(0);
586 }
587
588 static char* WINHELP_GetCaption(WINHELP_WNDPAGE* wpage)
589 {
590     if (wpage->wininfo->caption[0]) return wpage->wininfo->caption;
591     return wpage->page->file->lpszTitle;
592 }
593
594 static void WINHELP_RememberPage(WINHELP_WINDOW* win, WINHELP_WNDPAGE* wpage)
595 {
596     unsigned        num;
597
598     if (!Globals.history.index || Globals.history.set[0].page != wpage->page)
599     {
600         num = sizeof(Globals.history.set) / sizeof(Globals.history.set[0]);
601         /* we're full, remove latest entry */
602         if (Globals.history.index == num)
603         {
604             HLPFILE_FreeHlpFile(Globals.history.set[num - 1].page->file);
605             Globals.history.index--;
606         }
607         memmove(&Globals.history.set[1], &Globals.history.set[0],
608                 Globals.history.index * sizeof(Globals.history.set[0]));
609         Globals.history.set[0] = *wpage;
610         Globals.history.index++;
611         wpage->page->file->wRefCount++;
612     }
613     if (win->hHistoryWnd) InvalidateRect(win->hHistoryWnd, NULL, TRUE);
614
615     num = sizeof(win->back.set) / sizeof(win->back.set[0]);
616     if (win->back.index == num)
617     {
618         /* we're full, remove latest entry */
619         HLPFILE_FreeHlpFile(win->back.set[0].page->file);
620         memmove(&win->back.set[0], &win->back.set[1],
621                 (num - 1) * sizeof(win->back.set[0]));
622         win->back.index--;
623     }
624     win->back.set[win->back.index++] = *wpage;
625     wpage->page->file->wRefCount++;
626 }
627
628 /***********************************************************************
629  *
630  *           WINHELP_FindLink
631  */
632 static HLPFILE_LINK* WINHELP_FindLink(WINHELP_WINDOW* win, LPARAM pos)
633 {
634     HLPFILE_LINK*           link;
635     POINTL                  mouse_ptl, char_ptl, char_next_ptl;
636     DWORD                   cp;
637
638     if (!win->page) return NULL;
639
640     mouse_ptl.x = (short)LOWORD(pos);
641     mouse_ptl.y = (short)HIWORD(pos);
642     cp = SendMessageW(GetDlgItem(win->hMainWnd, CTL_ID_TEXT), EM_CHARFROMPOS,
643                       0, (LPARAM)&mouse_ptl);
644
645     for (link = win->page->first_link; link; link = link->next)
646     {
647         if (link->cpMin <= cp && cp <= link->cpMax)
648         {
649             /* check whether we're at end of line */
650             SendMessageW(GetDlgItem(win->hMainWnd, CTL_ID_TEXT), EM_POSFROMCHAR,
651                          (LPARAM)&char_ptl, cp);
652             SendMessageW(GetDlgItem(win->hMainWnd, CTL_ID_TEXT), EM_POSFROMCHAR,
653                          (LPARAM)&char_next_ptl, cp + 1);
654             if (link->bHotSpot)
655             {
656                 HLPFILE_HOTSPOTLINK*    hslink = (HLPFILE_HOTSPOTLINK*)link;
657                 if ((mouse_ptl.x < char_ptl.x + hslink->x) ||
658                     (mouse_ptl.x >= char_ptl.x + hslink->x + hslink->width) ||
659                     (mouse_ptl.y < char_ptl.y + hslink->y) ||
660                     (mouse_ptl.y >= char_ptl.y + hslink->y + hslink->height))
661                     continue;
662                 break;
663             }
664             if (char_next_ptl.y != char_ptl.y || mouse_ptl.x >= char_next_ptl.x)
665                 link = NULL;
666             break;
667         }
668     }
669     return link;
670 }
671
672 static LRESULT CALLBACK WINHELP_RicheditWndProc(HWND hWnd, UINT msg,
673                                                 WPARAM wParam, LPARAM lParam)
674 {
675     WINHELP_WINDOW *win = (WINHELP_WINDOW*) GetWindowLongPtr(GetParent(hWnd), 0);
676     DWORD messagePos;
677     POINT pt;
678     switch(msg)
679     {
680         case WM_SETCURSOR:
681             messagePos = GetMessagePos();
682             pt.x = (short)LOWORD(messagePos);
683             pt.y = (short)HIWORD(messagePos);
684             ScreenToClient(hWnd, &pt);
685             if (win->page && WINHELP_FindLink(win, MAKELPARAM(pt.x, pt.y)))
686             {
687                 SetCursor(win->hHandCur);
688                 return 0;
689             }
690             /* fall through */
691         default:
692             return CallWindowProcA(win->origRicheditWndProc, hWnd, msg, wParam, lParam);
693     }
694 }
695
696 /***********************************************************************
697  *
698  *           WINHELP_CreateHelpWindow
699  */
700 BOOL WINHELP_CreateHelpWindow(WINHELP_WNDPAGE* wpage, int nCmdShow, BOOL remember)
701 {
702     WINHELP_WINDOW*     win = NULL;
703     BOOL                bPrimary, bPopup, bReUsed = FALSE;
704     HICON               hIcon;
705     HWND                hTextWnd = NULL;
706
707     bPrimary = !lstrcmpi(wpage->wininfo->name, "main");
708     bPopup = !bPrimary && (wpage->wininfo->win_style & WS_POPUP);
709
710     if (!bPopup)
711     {
712         for (win = Globals.win_list; win; win = win->next)
713         {
714             if (!lstrcmpi(win->info->name, wpage->wininfo->name))
715             {
716                 POINT   pt = {0, 0};
717                 SIZE    sz = {0, 0};
718                 DWORD   flags = SWP_NOSIZE | SWP_NOMOVE;
719
720                 WINHELP_DeleteButtons(win);
721                 bReUsed = TRUE;
722                 SetWindowText(win->hMainWnd, WINHELP_GetCaption(wpage));
723                 if (wpage->wininfo->origin.x != CW_USEDEFAULT &&
724                     wpage->wininfo->origin.y != CW_USEDEFAULT)
725                 {
726                     pt = wpage->wininfo->origin;
727                     flags &= ~SWP_NOSIZE;
728                 }
729                 if (wpage->wininfo->size.cx != CW_USEDEFAULT &&
730                     wpage->wininfo->size.cy != CW_USEDEFAULT)
731                 {
732                     sz = wpage->wininfo->size;
733                     flags &= ~SWP_NOMOVE;
734                 }
735                 SetWindowPos(win->hMainWnd, HWND_TOP, pt.x, pt.y, sz.cx, sz.cy, flags);
736
737                 if (wpage->page && win->page && wpage->page->file != win->page->file)
738                     WINHELP_DeleteBackSet(win);
739                 WINHELP_InitFonts(win->hMainWnd);
740
741                 win->page = wpage->page;
742                 win->info = wpage->wininfo;
743                 hTextWnd = GetDlgItem(win->hMainWnd, CTL_ID_TEXT);
744                 WINHELP_SetupText(hTextWnd, win, wpage->relative);
745
746                 InvalidateRect(win->hMainWnd, NULL, TRUE);
747                 if (win->hHistoryWnd) InvalidateRect(win->hHistoryWnd, NULL, TRUE);
748
749                 break;
750             }
751         }
752     }
753
754     if (!win)
755     {
756         /* Initialize WINHELP_WINDOW struct */
757         win = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WINHELP_WINDOW));
758         if (!win) return FALSE;
759         win->next = Globals.win_list;
760         Globals.win_list = win;
761
762         win->hHandCur = LoadCursorW(0, (LPWSTR)IDC_HAND);
763         win->back.index = 0;
764         win->font_scale = 1;
765         WINHELP_GrabWindow(win);
766     }
767     win->page = wpage->page;
768     win->info = wpage->wininfo;
769     WINHELP_GrabWindow(win);
770
771     if (!bPopup && wpage->page && remember)
772     {
773         WINHELP_RememberPage(win, wpage);
774     }
775
776     if (bPopup)
777         Globals.active_popup = win;
778     else
779         Globals.active_win = win;
780
781     /* Initialize default pushbuttons */
782     if (bPrimary && wpage->page)
783     {
784         CHAR    buffer[MAX_STRING_LEN];
785
786         LoadString(Globals.hInstance, STID_CONTENTS, buffer, sizeof(buffer));
787         MACRO_CreateButton("BTN_CONTENTS", buffer, "Contents()");
788         LoadString(Globals.hInstance, STID_INDEX, buffer, sizeof(buffer));
789         MACRO_CreateButton("BTN_INDEX", buffer, "Finder()");
790         LoadString(Globals.hInstance, STID_BACK, buffer, sizeof(buffer));
791         MACRO_CreateButton("BTN_BACK", buffer, "Back()");
792         if (win->back.index <= 1) MACRO_DisableButton("BTN_BACK");
793     }
794
795     if (!bReUsed)
796     {
797         win->hMainWnd = CreateWindowEx((bPopup) ? WS_EX_TOOLWINDOW : 0, MAIN_WIN_CLASS_NAME,
798                                        WINHELP_GetCaption(wpage),
799                                        bPrimary ? WS_OVERLAPPEDWINDOW : wpage->wininfo->win_style,
800                                        wpage->wininfo->origin.x, wpage->wininfo->origin.y,
801                                        wpage->wininfo->size.cx, wpage->wininfo->size.cy,
802                                        bPopup ? Globals.active_win->hMainWnd : NULL,
803                                        bPrimary ? LoadMenu(Globals.hInstance, MAKEINTRESOURCE(MAIN_MENU)) : 0,
804                                        Globals.hInstance, win);
805         if (!bPopup)
806             /* Create button box and text Window */
807             CreateWindow(BUTTON_BOX_WIN_CLASS_NAME, "", WS_CHILD | WS_VISIBLE,
808                          0, 0, 0, 0, win->hMainWnd, (HMENU)CTL_ID_BUTTON, Globals.hInstance, NULL);
809
810         hTextWnd = CreateWindow(RICHEDIT_CLASS, NULL,
811                                 ES_MULTILINE | ES_READONLY | WS_CHILD | WS_HSCROLL | WS_VSCROLL | WS_VISIBLE,
812                                 0, 0, 0, 0, win->hMainWnd, (HMENU)CTL_ID_TEXT, Globals.hInstance, NULL);
813         SendMessage(hTextWnd, EM_SETEVENTMASK, 0,
814                     SendMessage(hTextWnd, EM_GETEVENTMASK, 0, 0) | ENM_MOUSEEVENTS);
815         win->origRicheditWndProc = (WNDPROC)SetWindowLongPtr(hTextWnd, GWLP_WNDPROC,
816                                                              (LONG_PTR)WINHELP_RicheditWndProc);
817     }
818
819     hIcon = (wpage->page) ? wpage->page->file->hIcon : NULL;
820     if (!hIcon) hIcon = LoadIcon(Globals.hInstance, MAKEINTRESOURCE(IDI_WINHELP));
821     SendMessage(win->hMainWnd, WM_SETICON, ICON_SMALL, (DWORD_PTR)hIcon);
822
823     /* Initialize file specific pushbuttons */
824     if (!(wpage->wininfo->win_style & WS_POPUP) && wpage->page)
825     {
826         HLPFILE_MACRO  *macro;
827         for (macro = wpage->page->file->first_macro; macro; macro = macro->next)
828             MACRO_ExecuteMacro(win, macro->lpszMacro);
829
830         for (macro = wpage->page->first_macro; macro; macro = macro->next)
831             MACRO_ExecuteMacro(win, macro->lpszMacro);
832     }
833     /* See #17681, in some cases, the newly created window is closed by the macros it contains
834      * (braindead), so deal with this case
835      */
836     for (win = Globals.win_list; win; win = win->next)
837     {
838         if (!lstrcmpi(win->info->name, wpage->wininfo->name)) break;
839     }
840     if (!win || !WINHELP_ReleaseWindow(win)) return TRUE;
841
842     if (bPopup)
843     {
844         DWORD   mask = SendMessage(hTextWnd, EM_GETEVENTMASK, 0, 0);
845         RECT    rect;
846
847         win->font_scale = Globals.active_win->font_scale;
848         WINHELP_SetupText(hTextWnd, win, wpage->relative);
849
850         /* we need the window to be shown for richedit to compute the size */
851         ShowWindow(win->hMainWnd, nCmdShow);
852         SendMessage(hTextWnd, EM_SETEVENTMASK, 0, mask | ENM_REQUESTRESIZE);
853         SendMessage(hTextWnd, EM_REQUESTRESIZE, 0, 0);
854         SendMessage(hTextWnd, EM_SETEVENTMASK, 0, mask);
855
856         GetWindowRect(win->hMainWnd, &rect);
857         win->hShadowWnd = CreateWindowEx(WS_EX_TOOLWINDOW, SHADOW_WIN_CLASS_NAME,
858                                          "", WS_POPUP | WS_VISIBLE,
859                                          rect.left + SHADOW_DX, rect.top + SHADOW_DY,
860                                          rect.right - rect.left,
861                                          rect.bottom - rect.top,
862                                          Globals.active_win->hMainWnd, 0,
863                                          Globals.hInstance, NULL);
864         SetWindowPos(win->hMainWnd, win->hShadowWnd, 0, 0, 0, 0,
865                      SWP_NOSIZE | SWP_NOMOVE);
866     }
867     else
868     {
869         WINHELP_SetupText(hTextWnd, win, wpage->relative);
870         WINHELP_LayoutMainWindow(win);
871         ShowWindow(win->hMainWnd, nCmdShow);
872     }
873
874     return TRUE;
875 }
876
877 /******************************************************************
878  *             WINHELP_OpenHelpWindow
879  * Main function to search for a page and display it in a window
880  */
881 BOOL WINHELP_OpenHelpWindow(HLPFILE_PAGE* (*lookup)(HLPFILE*, LONG, ULONG*),
882                             HLPFILE* hlpfile, LONG val, HLPFILE_WINDOWINFO* wi,
883                             int nCmdShow)
884 {
885     WINHELP_WNDPAGE     wpage;
886
887     wpage.page = lookup(hlpfile, val, &wpage.relative);
888     if (wpage.page) wpage.page->file->wRefCount++;
889     wpage.wininfo = wi;
890     return WINHELP_CreateHelpWindow(&wpage, nCmdShow, TRUE);
891 }
892
893 /******************************************************************
894  *             WINHELP_HandleTextMouse
895  *
896  */
897 static BOOL WINHELP_HandleTextMouse(WINHELP_WINDOW* win, UINT msg, LPARAM lParam)
898 {
899     HLPFILE*                hlpfile;
900     HLPFILE_LINK*           link;
901     BOOL                    ret = FALSE;
902
903     switch (msg)
904     {
905     case WM_LBUTTONDOWN:
906         if ((link = WINHELP_FindLink(win, lParam)))
907         {
908             HLPFILE_WINDOWINFO*     wi;
909
910             switch (link->cookie)
911             {
912             case hlp_link_link:
913                 if ((hlpfile = WINHELP_LookupHelpFile(link->string)))
914                 {
915                     if (link->window == -1)
916                         wi = win->info;
917                     else if (link->window < hlpfile->numWindows)
918                         wi = &hlpfile->windows[link->window];
919                     else
920                     {
921                         WINE_WARN("link to window %d/%d\n", link->window, hlpfile->numWindows);
922                         break;
923                     }
924                     WINHELP_OpenHelpWindow(HLPFILE_PageByHash, hlpfile, link->hash, wi, SW_NORMAL);
925                 }
926                 break;
927             case hlp_link_popup:
928                 if ((hlpfile = WINHELP_LookupHelpFile(link->string)))
929                     WINHELP_OpenHelpWindow(HLPFILE_PageByHash, hlpfile, link->hash,
930                                            WINHELP_GetPopupWindowInfo(hlpfile, win, lParam),
931                                            SW_NORMAL);
932                 break;
933             case hlp_link_macro:
934                 MACRO_ExecuteMacro(win, link->string);
935                 break;
936             default:
937                 WINE_FIXME("Unknown link cookie %d\n", link->cookie);
938             }
939             ret = TRUE;
940         }
941         break;
942     }
943     return ret;
944 }
945
946 /***********************************************************************
947  *
948  *           WINHELP_CheckPopup
949  */
950 static BOOL WINHELP_CheckPopup(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT* lret)
951 {
952     WINHELP_WINDOW*     popup;
953
954     if (!Globals.active_popup) return FALSE;
955
956     switch (msg)
957     {
958     case WM_NOTIFY:
959         {
960             MSGFILTER*  msgf = (MSGFILTER*)lParam;
961             if (msgf->nmhdr.code == EN_MSGFILTER)
962             {
963                 if (!WINHELP_CheckPopup(hWnd, msgf->msg, msgf->wParam, msgf->lParam, NULL))
964                     return FALSE;
965                 if (lret) *lret = 1;
966                 return TRUE;
967             }
968         }
969         break;
970     case WM_ACTIVATE:
971         if (wParam != WA_INACTIVE || (HWND)lParam == Globals.active_win->hMainWnd ||
972             (HWND)lParam == Globals.active_popup->hMainWnd ||
973             GetWindow((HWND)lParam, GW_OWNER) == Globals.active_win->hMainWnd)
974             break;
975     case WM_LBUTTONDOWN:
976         if (WINHELP_HandleTextMouse(Globals.active_popup, msg, lParam))
977             return FALSE;
978         /* fall through */
979     case WM_LBUTTONUP:
980     case WM_MBUTTONDOWN:
981     case WM_RBUTTONDOWN:
982     case WM_NCLBUTTONDOWN:
983     case WM_NCMBUTTONDOWN:
984     case WM_NCRBUTTONDOWN:
985         popup = Globals.active_popup;
986         Globals.active_popup = NULL;
987         WINHELP_ReleaseWindow(popup);
988         return TRUE;
989     }
990     return FALSE;
991 }
992
993 /***********************************************************************
994  *
995  *           WINHELP_ButtonWndProc
996  */
997 static LRESULT CALLBACK WINHELP_ButtonWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
998 {
999     if (WINHELP_CheckPopup(hWnd, msg, wParam, lParam, NULL)) return 0;
1000
1001     if (msg == WM_KEYDOWN)
1002     {
1003         switch (wParam)
1004         {
1005         case VK_UP:
1006         case VK_DOWN:
1007         case VK_PRIOR:
1008         case VK_NEXT:
1009         case VK_ESCAPE:
1010             return SendMessage(GetParent(hWnd), msg, wParam, lParam);
1011         }
1012     }
1013
1014     return CallWindowProc(Globals.button_proc, hWnd, msg, wParam, lParam);
1015 }
1016
1017 /***********************************************************************
1018  *
1019  *           WINHELP_ButtonBoxWndProc
1020  */
1021 static LRESULT CALLBACK WINHELP_ButtonBoxWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1022 {
1023     WINDOWPOS      *winpos;
1024     WINHELP_WINDOW *win;
1025     WINHELP_BUTTON *button;
1026     SIZE button_size;
1027     INT  x, y;
1028
1029     if (WINHELP_CheckPopup(hWnd, msg, wParam, lParam, NULL)) return 0L;
1030
1031     switch (msg)
1032     {
1033     case WM_WINDOWPOSCHANGING:
1034         winpos = (WINDOWPOS*) lParam;
1035         win = (WINHELP_WINDOW*) GetWindowLongPtr(GetParent(hWnd), 0);
1036
1037         /* Update buttons */
1038         button_size.cx = 0;
1039         button_size.cy = 0;
1040         for (button = win->first_button; button; button = button->next)
1041         {
1042             HDC  hDc;
1043             SIZE textsize;
1044             if (!button->hWnd)
1045             {
1046                 button->hWnd = CreateWindow(STRING_BUTTON, button->lpszName,
1047                                             WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
1048                                             0, 0, 0, 0,
1049                                             hWnd, (HMENU) button->wParam,
1050                                             Globals.hInstance, 0);
1051                 if (button->hWnd)
1052                 {
1053                     if (Globals.button_proc == NULL)
1054                     {
1055                         NONCLIENTMETRICSW ncm;
1056                         Globals.button_proc = (WNDPROC) GetWindowLongPtr(button->hWnd, GWLP_WNDPROC);
1057
1058                         ncm.cbSize = sizeof(NONCLIENTMETRICSW);
1059                         SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,
1060                                               sizeof(NONCLIENTMETRICSW), &ncm, 0);
1061                         Globals.hButtonFont = CreateFontIndirectW(&ncm.lfMenuFont);
1062                     }
1063                     SetWindowLongPtr(button->hWnd, GWLP_WNDPROC, (LONG_PTR) WINHELP_ButtonWndProc);
1064                     if (Globals.hButtonFont)
1065                         SendMessage(button->hWnd, WM_SETFONT, (WPARAM)Globals.hButtonFont, TRUE);
1066                 }
1067             }
1068             hDc = GetDC(button->hWnd);
1069             GetTextExtentPoint(hDc, button->lpszName,
1070                                lstrlen(button->lpszName), &textsize);
1071             ReleaseDC(button->hWnd, hDc);
1072
1073             button_size.cx = max(button_size.cx, textsize.cx + BUTTON_CX);
1074             button_size.cy = max(button_size.cy, textsize.cy + BUTTON_CY);
1075         }
1076
1077         x = 0;
1078         y = 0;
1079         for (button = win->first_button; button; button = button->next)
1080         {
1081             SetWindowPos(button->hWnd, HWND_TOP, x, y, button_size.cx, button_size.cy, 0);
1082
1083             if (x + 2 * button_size.cx <= winpos->cx)
1084                 x += button_size.cx;
1085             else
1086                 x = 0, y += button_size.cy;
1087         }
1088         winpos->cy = y + (x ? button_size.cy : 0);
1089         break;
1090
1091     case WM_COMMAND:
1092         SendMessage(GetParent(hWnd), msg, wParam, lParam);
1093         break;
1094
1095     case WM_KEYDOWN:
1096         switch (wParam)
1097         {
1098         case VK_UP:
1099         case VK_DOWN:
1100         case VK_PRIOR:
1101         case VK_NEXT:
1102         case VK_ESCAPE:
1103             return SendMessage(GetParent(hWnd), msg, wParam, lParam);
1104         }
1105         break;
1106     }
1107
1108     return DefWindowProc(hWnd, msg, wParam, lParam);
1109 }
1110
1111 /******************************************************************
1112  *              WINHELP_HistoryWndProc
1113  *
1114  *
1115  */
1116 static LRESULT CALLBACK WINHELP_HistoryWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1117 {
1118     WINHELP_WINDOW*     win;
1119     PAINTSTRUCT         ps;
1120     HDC                 hDc;
1121     TEXTMETRIC          tm;
1122     unsigned int        i;
1123     RECT                r;
1124
1125     switch (msg)
1126     {
1127     case WM_NCCREATE:
1128         win = (WINHELP_WINDOW*)((LPCREATESTRUCT)lParam)->lpCreateParams;
1129         SetWindowLongPtr(hWnd, 0, (ULONG_PTR)win);
1130         win->hHistoryWnd = hWnd;
1131         break;
1132     case WM_CREATE:
1133         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1134         hDc = GetDC(hWnd);
1135         GetTextMetrics(hDc, &tm);
1136         GetWindowRect(hWnd, &r);
1137
1138         r.right = r.left + 30 * tm.tmAveCharWidth;
1139         r.bottom = r.top + (sizeof(Globals.history.set) / sizeof(Globals.history.set[0])) * tm.tmHeight;
1140         AdjustWindowRect(&r, GetWindowLong(hWnd, GWL_STYLE), FALSE);
1141         if (r.left < 0) {r.right -= r.left; r.left = 0;}
1142         if (r.top < 0) {r.bottom -= r.top; r.top = 0;}
1143
1144         MoveWindow(hWnd, r.left, r.top, r.right, r.bottom, TRUE);
1145         ReleaseDC(hWnd, hDc);
1146         break;
1147     case WM_LBUTTONDOWN:
1148         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1149         hDc = GetDC(hWnd);
1150         GetTextMetrics(hDc, &tm);
1151         i = HIWORD(lParam) / tm.tmHeight;
1152         if (i < Globals.history.index)
1153             WINHELP_CreateHelpWindow(&Globals.history.set[i], SW_SHOW, TRUE);
1154         ReleaseDC(hWnd, hDc);
1155         break;
1156     case WM_PAINT:
1157         hDc = BeginPaint(hWnd, &ps);
1158         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1159         GetTextMetrics(hDc, &tm);
1160
1161         for (i = 0; i < Globals.history.index; i++)
1162         {
1163             if (Globals.history.set[i].page->file == Globals.active_win->page->file)
1164             {
1165                 TextOut(hDc, 0, i * tm.tmHeight,
1166                         Globals.history.set[i].page->lpszTitle,
1167                         strlen(Globals.history.set[i].page->lpszTitle));
1168             }
1169             else
1170             {
1171                 char        buffer[1024];
1172                 const char* ptr1;
1173                 const char* ptr2;
1174                 unsigned    len;
1175
1176                 ptr1 = strrchr(Globals.history.set[i].page->file->lpszPath, '\\');
1177                 if (!ptr1) ptr1 = Globals.history.set[i].page->file->lpszPath;
1178                 else ptr1++;
1179                 ptr2 = strrchr(ptr1, '.');
1180                 len = ptr2 ? ptr2 - ptr1 : strlen(ptr1);
1181                 if (len > sizeof(buffer)) len = sizeof(buffer);
1182                 memcpy(buffer, ptr1, len);
1183                 if (len < sizeof(buffer)) buffer[len++] = ':';
1184                 strncpy(&buffer[len], Globals.history.set[i].page->lpszTitle, sizeof(buffer) - len);
1185                 buffer[sizeof(buffer) - 1] = '\0';
1186                 TextOut(hDc, 0, i * tm.tmHeight, buffer, strlen(buffer));
1187             }
1188         }
1189         EndPaint(hWnd, &ps);
1190         break;
1191     case WM_DESTROY:
1192         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1193         if (hWnd == win->hHistoryWnd)
1194             win->hHistoryWnd = 0;
1195         break;
1196     }
1197     return DefWindowProc(hWnd, msg, wParam, lParam);
1198 }
1199
1200 /***********************************************************************
1201  *
1202  *           WINHELP_ShadowWndProc
1203  */
1204 static LRESULT CALLBACK WINHELP_ShadowWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1205 {
1206     if (WINHELP_CheckPopup(hWnd, msg, wParam, lParam, NULL)) return 0;
1207     return WINHELP_CheckPopup(hWnd, msg, wParam, lParam, NULL) ? 0L : DefWindowProc(hWnd, msg, wParam, lParam);
1208 }
1209
1210 /**************************************************************************
1211  * cb_KWBTree
1212  *
1213  * HLPFILE_BPTreeCallback enumeration function for '|KWBTREE' internal file.
1214  *
1215  */
1216 static void cb_KWBTree(void *p, void **next, void *cookie)
1217 {
1218     HWND hListWnd = cookie;
1219     int count;
1220
1221     WINE_TRACE("Adding '%s' to search list\n", (char *)p);
1222     SendMessage(hListWnd, LB_INSERTSTRING, -1, (LPARAM)p);
1223     count = SendMessage(hListWnd, LB_GETCOUNT, 0, 0);
1224     SendMessage(hListWnd, LB_SETITEMDATA, count-1, (LPARAM)p);
1225     *next = (char*)p + strlen((char*)p) + 7;
1226 }
1227
1228 struct index_data
1229 {
1230     HLPFILE*    hlpfile;
1231     BOOL        jump;
1232     ULONG       offset;
1233 };
1234
1235 /**************************************************************************
1236  * WINHELP_IndexDlgProc
1237  *
1238  */
1239 static INT_PTR CALLBACK WINHELP_IndexDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1240 {
1241     static struct index_data* id;
1242     int sel;
1243
1244     switch (msg)
1245     {
1246     case WM_INITDIALOG:
1247         id = (struct index_data*)((PROPSHEETPAGE*)lParam)->lParam;
1248         HLPFILE_BPTreeEnum(id->hlpfile->kwbtree, cb_KWBTree,
1249                            GetDlgItem(hWnd, IDC_INDEXLIST));
1250         id->jump = FALSE;
1251         id->offset = 1;
1252         return TRUE;
1253     case WM_COMMAND:
1254         switch (HIWORD(wParam))
1255         {
1256         case LBN_DBLCLK:
1257             if (LOWORD(wParam) == IDC_INDEXLIST)
1258                 SendMessage(GetParent(hWnd), PSM_PRESSBUTTON, PSBTN_OK, 0);
1259             break;
1260         }
1261         break;
1262     case WM_NOTIFY:
1263         switch (((NMHDR*)lParam)->code)
1264         {
1265         case PSN_APPLY:
1266             sel = SendDlgItemMessage(hWnd, IDC_INDEXLIST, LB_GETCURSEL, 0, 0);
1267             if (sel != LB_ERR)
1268             {
1269                 BYTE *p;
1270                 int count;
1271
1272                 p = (BYTE*)SendDlgItemMessage(hWnd, IDC_INDEXLIST,
1273                                               LB_GETITEMDATA, sel, 0);
1274                 count = *(short*)((char *)p + strlen((char *)p) + 1);
1275                 if (count > 1)
1276                 {
1277                     MessageBox(hWnd, "count > 1 not supported yet", "Error", MB_OK | MB_ICONSTOP);
1278                     SetWindowLongPtr(hWnd, DWLP_MSGRESULT, PSNRET_INVALID);
1279                     return TRUE;
1280                 }
1281                 id->offset = *(ULONG*)((char *)p + strlen((char *)p) + 3);
1282                 id->offset = *(long*)(id->hlpfile->kwdata + id->offset + 9);
1283                 if (id->offset == 0xFFFFFFFF)
1284                 {
1285                     MessageBox(hWnd, "macro keywords not supported yet", "Error", MB_OK | MB_ICONSTOP);
1286                     SetWindowLongPtr(hWnd, DWLP_MSGRESULT, PSNRET_INVALID);
1287                     return TRUE;
1288                 }
1289                 id->jump = TRUE;
1290                 SetWindowLongPtr(hWnd, DWLP_MSGRESULT, PSNRET_NOERROR);
1291             }
1292             return TRUE;
1293         default:
1294             return FALSE;
1295         }
1296         break;
1297     default:
1298         break;
1299     }
1300     return FALSE;
1301 }
1302
1303 /**************************************************************************
1304  * WINHELP_SearchDlgProc
1305  *
1306  */
1307 static INT_PTR CALLBACK WINHELP_SearchDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1308 {
1309     static struct index_data* id;
1310
1311     switch (msg)
1312     {
1313     case WM_INITDIALOG:
1314         id = (struct index_data*)((PROPSHEETPAGE*)lParam)->lParam;
1315         return TRUE;
1316     case WM_NOTIFY:
1317         switch (((NMHDR*)lParam)->code)
1318         {
1319         case PSN_APPLY:
1320             SetWindowLongPtr(hWnd, DWLP_MSGRESULT, PSNRET_NOERROR);
1321             return TRUE;
1322         default:
1323             return FALSE;
1324         }
1325         break;
1326     default:
1327         break;
1328     }
1329     return FALSE;
1330 }
1331
1332 /***********************************************************************
1333  *
1334  *           WINHELP_MainWndProc
1335  */
1336 static LRESULT CALLBACK WINHELP_MainWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1337 {
1338     WINHELP_WINDOW *win;
1339     WINHELP_BUTTON *button;
1340     INT  keyDelta;
1341     HWND hTextWnd;
1342     LRESULT ret;
1343
1344     if (WINHELP_CheckPopup(hWnd, msg, wParam, lParam, &ret)) return ret;
1345
1346     switch (msg)
1347     {
1348     case WM_NCCREATE:
1349         win = (WINHELP_WINDOW*) ((LPCREATESTRUCT) lParam)->lpCreateParams;
1350         SetWindowLongPtr(hWnd, 0, (ULONG_PTR) win);
1351         if (!win->page && Globals.isBook)
1352             PostMessage(hWnd, WM_COMMAND, MNID_FILE_OPEN, 0);
1353         win->hMainWnd = hWnd;
1354         break;
1355
1356     case WM_WINDOWPOSCHANGED:
1357         WINHELP_LayoutMainWindow((WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0));
1358         break;
1359
1360     case WM_COMMAND:
1361         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1362         switch (wParam)
1363         {
1364             /* Menu FILE */
1365         case MNID_FILE_OPEN:    MACRO_FileOpen();       break;
1366         case MNID_FILE_PRINT:   MACRO_Print();          break;
1367         case MNID_FILE_SETUP:   MACRO_PrinterSetup();   break;
1368         case MNID_FILE_EXIT:    MACRO_Exit();           break;
1369
1370             /* Menu EDIT */
1371         case MNID_EDIT_COPYDLG:
1372             SendMessage(GetDlgItem(hWnd, CTL_ID_TEXT), WM_COPY, 0, 0);
1373             break;
1374         case MNID_EDIT_ANNOTATE:MACRO_Annotate();       break;
1375
1376             /* Menu Bookmark */
1377         case MNID_BKMK_DEFINE:  MACRO_BookmarkDefine(); break;
1378
1379             /* Menu Help */
1380         case MNID_HELP_HELPON:  MACRO_HelpOn();         break;
1381         case MNID_HELP_HELPTOP: MACRO_HelpOnTop();      break;
1382         case MNID_HELP_ABOUT:   MACRO_About();          break;
1383         case MNID_HELP_WINE:    ShellAbout(hWnd, "WINE", "Help", 0); break;
1384
1385             /* Context help */
1386         case MNID_CTXT_ANNOTATE:MACRO_Annotate();       break;
1387         case MNID_CTXT_COPY:    MACRO_CopyDialog();     break;
1388         case MNID_CTXT_PRINT:   MACRO_Print();          break;
1389         case MNID_OPTS_HISTORY: MACRO_History();        break;
1390         case MNID_OPTS_FONTS_SMALL:
1391         case MNID_CTXT_FONTS_SMALL:
1392             win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1393             if (win->font_scale != 0)
1394             {
1395                 win->font_scale = 0;
1396                 WINHELP_SetupText(GetDlgItem(hWnd, CTL_ID_TEXT), win, 0 /* FIXME */);
1397             }
1398             break;
1399         case MNID_OPTS_FONTS_NORMAL:
1400         case MNID_CTXT_FONTS_NORMAL:
1401             win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1402             if (win->font_scale != 1)
1403             {
1404                 win->font_scale = 1;
1405                 WINHELP_SetupText(GetDlgItem(hWnd, CTL_ID_TEXT), win, 0 /* FIXME */);
1406             }
1407             break;
1408         case MNID_OPTS_FONTS_LARGE:
1409         case MNID_CTXT_FONTS_LARGE:
1410             win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1411             if (win->font_scale != 2)
1412             {
1413                 win->font_scale = 2;
1414                 WINHELP_SetupText(GetDlgItem(hWnd, CTL_ID_TEXT), win, 0 /* FIXME */);
1415             }
1416             break;
1417         case MNID_OPTS_HELP_DEFAULT:
1418         case MNID_OPTS_HELP_VISIBLE:
1419         case MNID_OPTS_HELP_NONVISIBLE:
1420         case MNID_OPTS_SYSTEM_COLORS:
1421         case MNID_CTXT_HELP_DEFAULT:
1422         case MNID_CTXT_HELP_VISIBLE:
1423         case MNID_CTXT_HELP_NONVISIBLE:
1424         case MNID_CTXT_SYSTEM_COLORS:
1425             /* FIXME: NIY */
1426
1427         default:
1428             /* Buttons */
1429             for (button = win->first_button; button; button = button->next)
1430                 if (wParam == button->wParam) break;
1431             if (button)
1432                 MACRO_ExecuteMacro(win, button->lpszMacro);
1433             else if (!HIWORD(wParam))
1434                 MessageBox(0, MAKEINTRESOURCE(STID_NOT_IMPLEMENTED),
1435                            MAKEINTRESOURCE(STID_WHERROR), MB_OK);
1436             break;
1437         }
1438         break;
1439 /* EPP     case WM_DESTROY: */
1440 /* EPP         if (Globals.hPopupWnd) DestroyWindow(Globals.hPopupWnd); */
1441 /* EPP         break; */
1442     case WM_COPYDATA:
1443         return WINHELP_HandleCommand((HWND)wParam, lParam);
1444
1445     case WM_CHAR:
1446         if (wParam == 3)
1447         {
1448             SendMessage(GetDlgItem(hWnd, CTL_ID_TEXT), WM_COPY, 0, 0);
1449             return 0;
1450         }
1451         break;
1452
1453     case WM_KEYDOWN:
1454         keyDelta = 0;
1455         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1456         hTextWnd = GetDlgItem(win->hMainWnd, CTL_ID_TEXT);
1457
1458         switch (wParam)
1459         {
1460         case VK_UP:
1461             SendMessage(hTextWnd, EM_SCROLL, SB_LINEUP, 0);
1462             return 0;
1463         case VK_DOWN:
1464             SendMessage(hTextWnd, EM_SCROLL, SB_LINEDOWN, 0);
1465             return 0;
1466         case VK_PRIOR:
1467             SendMessage(hTextWnd, EM_SCROLL, SB_PAGEUP, 0);
1468             return 0;
1469         case VK_NEXT:
1470             SendMessage(hTextWnd, EM_SCROLL, SB_PAGEDOWN, 0);
1471             return 0;
1472         case VK_ESCAPE:
1473             MACRO_Exit();
1474             return 0;
1475         }
1476         break;
1477
1478     case WM_NOTIFY:
1479         if (wParam == CTL_ID_TEXT)
1480         {
1481             RECT        rc;
1482
1483             switch (((NMHDR*)lParam)->code)
1484             {
1485             case EN_MSGFILTER:
1486                 {
1487                     const MSGFILTER*    msgf = (const MSGFILTER*)lParam;
1488                     switch (msgf->msg)
1489                     {
1490                     case WM_KEYUP:
1491                         if (msgf->wParam == VK_ESCAPE)
1492                             WINHELP_ReleaseWindow((WINHELP_WINDOW*)GetWindowLongPtr(hWnd, 0));
1493                         break;
1494                     case WM_RBUTTONDOWN:
1495                     {
1496                         HMENU       hMenu;
1497                         POINT       pt;
1498
1499                         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1500                         hMenu = LoadMenu(Globals.hInstance, (LPSTR)CONTEXT_MENU);
1501                         switch (win->font_scale)
1502                         {
1503                         case 0:
1504                             CheckMenuItem(hMenu, MNID_CTXT_FONTS_SMALL,
1505                                           MF_BYCOMMAND|MF_CHECKED);
1506                             break;
1507                         default:
1508                             WINE_FIXME("Unsupported %d\n", win->font_scale);
1509                         case 1:
1510                             CheckMenuItem(hMenu, MNID_CTXT_FONTS_NORMAL,
1511                                           MF_BYCOMMAND|MF_CHECKED);
1512                             break;
1513                         case 2:
1514                             CheckMenuItem(hMenu, MNID_CTXT_FONTS_LARGE,
1515                                           MF_BYCOMMAND|MF_CHECKED);
1516                             break;
1517                         }
1518                         pt.x = (int)(short)LOWORD(msgf->lParam);
1519                         pt.y = (int)(short)HIWORD(msgf->lParam);
1520                         ClientToScreen(msgf->nmhdr.hwndFrom, &pt);
1521                         TrackPopupMenu(GetSubMenu(hMenu, 0), TPM_LEFTALIGN|TPM_TOPALIGN,
1522                                        pt.x, pt.y, 0, hWnd, NULL);
1523                         DestroyMenu(hMenu);
1524                     }
1525                     break;
1526                     default:
1527                         return WINHELP_HandleTextMouse((WINHELP_WINDOW*)GetWindowLongPtr(hWnd, 0),
1528                                                        msgf->msg, msgf->lParam);
1529                     }
1530                 }
1531                 break;
1532
1533             case EN_REQUESTRESIZE:
1534                 rc = ((REQRESIZE*)lParam)->rc;
1535                 win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1536                 AdjustWindowRect(&rc, GetWindowLong(win->hMainWnd, GWL_STYLE),
1537                                  FALSE);
1538                 SetWindowPos(win->hMainWnd, HWND_TOP, 0, 0,
1539                              rc.right - rc.left, rc.bottom - rc.top,
1540                              SWP_NOMOVE | SWP_NOZORDER);
1541                 WINHELP_LayoutMainWindow(win);
1542                 break;
1543             }
1544         }
1545         break;
1546
1547     case WM_INITMENUPOPUP:
1548         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1549         CheckMenuItem((HMENU)wParam, MNID_OPTS_FONTS_SMALL,
1550                       MF_BYCOMMAND | (win->font_scale == 0) ? MF_CHECKED : 0);
1551         CheckMenuItem((HMENU)wParam, MNID_OPTS_FONTS_NORMAL,
1552                       MF_BYCOMMAND | (win->font_scale == 1) ? MF_CHECKED : 0);
1553         CheckMenuItem((HMENU)wParam, MNID_OPTS_FONTS_LARGE,
1554                       MF_BYCOMMAND | (win->font_scale == 2) ? MF_CHECKED : 0);
1555         break;
1556     case WM_DESTROY:
1557         win = (WINHELP_WINDOW*) GetWindowLongPtr(hWnd, 0);
1558         WINHELP_DeleteWindow(win);
1559         break;
1560     }
1561     return DefWindowProc(hWnd, msg, wParam, lParam);
1562 }
1563
1564 /**************************************************************************
1565  * WINHELP_CreateIndexWindow
1566  *
1567  * Displays a dialog with keywords of current help file.
1568  *
1569  */
1570 BOOL WINHELP_CreateIndexWindow(BOOL is_search)
1571 {
1572     HPROPSHEETPAGE      psPage[3];
1573     PROPSHEETPAGE       psp;
1574     PROPSHEETHEADER     psHead;
1575     struct index_data   id;
1576     char                buf[256];
1577
1578     if (Globals.active_win && Globals.active_win->page && Globals.active_win->page->file)
1579         id.hlpfile = Globals.active_win->page->file;
1580     else
1581         return FALSE;
1582
1583     if (id.hlpfile->kwbtree == NULL)
1584     {
1585         WINE_TRACE("No index provided\n");
1586         return FALSE;
1587     }
1588
1589     InitCommonControls();
1590
1591     id.jump = FALSE;
1592     memset(&psp, 0, sizeof(psp));
1593     psp.dwSize = sizeof(psp);
1594     psp.dwFlags = 0;
1595     psp.hInstance = Globals.hInstance;
1596
1597     psp.u.pszTemplate = MAKEINTRESOURCE(IDD_INDEX);
1598     psp.lParam = (LPARAM)&id;
1599     psp.pfnDlgProc = WINHELP_IndexDlgProc;
1600     psPage[0] = CreatePropertySheetPage(&psp);
1601
1602     psp.u.pszTemplate = MAKEINTRESOURCE(IDD_SEARCH);
1603     psp.lParam = (LPARAM)&id;
1604     psp.pfnDlgProc = WINHELP_SearchDlgProc;
1605     psPage[1] = CreatePropertySheetPage(&psp);
1606
1607     memset(&psHead, 0, sizeof(psHead));
1608     psHead.dwSize = sizeof(psHead);
1609
1610     LoadString(Globals.hInstance, STID_PSH_INDEX, buf, sizeof(buf));
1611     strcat(buf, Globals.active_win->info->caption);
1612
1613     psHead.pszCaption = buf;
1614     psHead.nPages = 2;
1615     psHead.u2.nStartPage = is_search ? 1 : 0;
1616     psHead.hwndParent = Globals.active_win->hMainWnd;
1617     psHead.u3.phpage = psPage;
1618     psHead.dwFlags = PSH_NOAPPLYNOW;
1619
1620     PropertySheet(&psHead);
1621     if (id.jump)
1622     {
1623         WINE_TRACE("got %d as an offset\n", id.offset);
1624         WINHELP_OpenHelpWindow(HLPFILE_PageByOffset, id.hlpfile, id.offset,
1625                                Globals.active_win->info, SW_NORMAL);
1626     }
1627     return TRUE;
1628 }
1629
1630 /***********************************************************************
1631  *
1632  *           RegisterWinClasses
1633  */
1634 static BOOL WINHELP_RegisterWinClasses(void)
1635 {
1636     WNDCLASS class_main, class_button_box, class_shadow, class_history;
1637
1638     class_main.style               = CS_HREDRAW | CS_VREDRAW;
1639     class_main.lpfnWndProc         = WINHELP_MainWndProc;
1640     class_main.cbClsExtra          = 0;
1641     class_main.cbWndExtra          = sizeof(WINHELP_WINDOW *);
1642     class_main.hInstance           = Globals.hInstance;
1643     class_main.hIcon               = LoadIcon(Globals.hInstance, MAKEINTRESOURCE(IDI_WINHELP));
1644     class_main.hCursor             = LoadCursor(0, IDC_ARROW);
1645     class_main.hbrBackground       = (HBRUSH)(COLOR_WINDOW+1);
1646     class_main.lpszMenuName        = 0;
1647     class_main.lpszClassName       = MAIN_WIN_CLASS_NAME;
1648
1649     class_button_box               = class_main;
1650     class_button_box.lpfnWndProc   = WINHELP_ButtonBoxWndProc;
1651     class_button_box.cbWndExtra    = 0;
1652     class_button_box.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1);
1653     class_button_box.lpszClassName = BUTTON_BOX_WIN_CLASS_NAME;
1654
1655     class_shadow                   = class_main;
1656     class_shadow.lpfnWndProc       = WINHELP_ShadowWndProc;
1657     class_shadow.cbWndExtra        = 0;
1658     class_shadow.hbrBackground     = (HBRUSH)(COLOR_3DDKSHADOW+1);
1659     class_shadow.lpszClassName     = SHADOW_WIN_CLASS_NAME;
1660
1661     class_history                  = class_main;
1662     class_history.lpfnWndProc      = WINHELP_HistoryWndProc;
1663     class_history.lpszClassName    = HISTORY_WIN_CLASS_NAME;
1664
1665     return (RegisterClass(&class_main) &&
1666             RegisterClass(&class_button_box) &&
1667             RegisterClass(&class_shadow) &&
1668             RegisterClass(&class_history));
1669 }
1670
1671 /***********************************************************************
1672  *
1673  *           WinMain
1674  */
1675 int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
1676 {
1677     MSG                 msg;
1678     LONG                lHash = 0;
1679     HLPFILE*            hlpfile;
1680     static CHAR         default_wndname[] = "main";
1681     LPSTR               wndname = default_wndname;
1682     WINHELP_DLL*        dll;
1683
1684     Globals.hInstance = hInstance;
1685
1686     if (LoadLibrary("riched20.dll") == NULL)
1687         return MessageBox(0, MAKEINTRESOURCE(STID_NO_RICHEDIT),
1688                           MAKEINTRESOURCE(STID_WHERROR), MB_OK);
1689
1690     /* Get options */
1691     while (*cmdline && (*cmdline == ' ' || *cmdline == '-'))
1692     {
1693         CHAR   option;
1694         LPCSTR topic_id;
1695         if (*cmdline++ == ' ') continue;
1696
1697         option = *cmdline;
1698         if (option) cmdline++;
1699         while (*cmdline && *cmdline == ' ') cmdline++;
1700         switch (option)
1701         {
1702         case 'i':
1703         case 'I':
1704             topic_id = cmdline;
1705             while (*cmdline && *cmdline != ' ') cmdline++;
1706             if (*cmdline) *cmdline++ = '\0';
1707             lHash = HLPFILE_Hash(topic_id);
1708             break;
1709
1710         case '3':
1711         case '4':
1712             Globals.wVersion = option - '0';
1713             break;
1714
1715         case 'x':
1716             show = SW_HIDE;
1717             Globals.isBook = FALSE;
1718             break;
1719
1720         default:
1721             WINE_FIXME("Unsupported cmd line: %s\n", cmdline);
1722             break;
1723         }
1724     }
1725
1726     /* Create primary window */
1727     if (!WINHELP_RegisterWinClasses())
1728     {
1729         WINE_FIXME("Couldn't register classes\n");
1730         return 0;
1731     }
1732
1733     if (*cmdline)
1734     {
1735         char*   ptr;
1736         if ((*cmdline == '"') && (ptr = strchr(cmdline+1, '"')))
1737         {
1738             cmdline++;
1739             *ptr = '\0';
1740         }
1741         if ((ptr = strchr(cmdline, '>')))
1742         {
1743             *ptr = '\0';
1744             wndname = ptr + 1;
1745         }
1746         hlpfile = WINHELP_LookupHelpFile(cmdline);
1747         if (!hlpfile) return 0;
1748     }
1749     else hlpfile = NULL;
1750     WINHELP_OpenHelpWindow(HLPFILE_PageByHash, hlpfile, lHash,
1751                            WINHELP_GetWindowInfo(hlpfile, wndname), show);
1752
1753     /* Message loop */
1754     while ((Globals.win_list || Globals.active_popup) && GetMessage(&msg, 0, 0, 0))
1755     {
1756         TranslateMessage(&msg);
1757         DispatchMessage(&msg);
1758     }
1759     for (dll = Globals.dlls; dll; dll = dll->next)
1760     {
1761         if (dll->class & DC_INITTERM) dll->handler(DW_TERM, 0, 0);
1762     }
1763     return 0;
1764 }