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