Use WIN_ReleasePtr not WIN_ReleaseWndPtr with WIN_GetPtr.
[wine] / windows / mdi.c
1 /* MDI.C
2  *
3  * Copyright 1994, Bob Amstadt
4  *           1995,1996 Alex Korobka
5  *
6  * This file contains routines to support MDI (Multiple Document
7  * Interface) features .
8  *
9  * Notes: Fairly complete implementation.
10  *        Also, Excel and WinWord do _not_ use MDI so if you're trying
11  *        to fix them look elsewhere. 
12  *
13  * Notes on how the "More Windows..." is implemented:
14  *
15  *      When we have more than 9 opened windows, a "More Windows..."
16  *      option appears in the "Windows" menu. Each child window has
17  *      a WND* associated with it, accesible via the children list of
18  *      the parent window. This WND* has a wIDmenu member, which reflects
19  *      the position of the child in the window list. For example, with
20  *      9 child windows, we could have the following pattern:
21  *
22  *
23  *
24  *                Name of the child window    pWndChild->wIDmenu
25  *                     Doc1                       5000
26  *                     Doc2                       5001
27  *                     Doc3                       5002
28  *                     Doc4                       5003
29  *                     Doc5                       5004
30  *                     Doc6                       5005
31  *                     Doc7                       5006
32  *                     Doc8                       5007
33  *                     Doc9                       5008
34  *
35  *
36  *       The "Windows" menu, as the "More windows..." dialog, are constructed
37  *       in this order. If we add a child, we would have the following list:
38  *
39  *
40  *               Name of the child window    pWndChild->wIDmenu
41  *                     Doc1                       5000
42  *                     Doc2                       5001
43  *                     Doc3                       5002
44  *                     Doc4                       5003
45  *                     Doc5                       5004
46  *                     Doc6                       5005
47  *                     Doc7                       5006
48  *                     Doc8                       5007
49  *                     Doc9                       5008
50  *                     Doc10                      5009
51  *
52  *       But only 5000 to 5008 would be displayed in the "Windows" menu. We want
53  *       the last created child to be in the menu, so we swap the last child with
54  *       the 9th... Doc9 will be accessible via the "More Windows..." option.
55  *
56  *                     Doc1                       5000
57  *                     Doc2                       5001
58  *                     Doc3                       5002
59  *                     Doc4                       5003
60  *                     Doc5                       5004
61  *                     Doc6                       5005
62  *                     Doc7                       5006
63  *                     Doc8                       5007
64  *                     Doc9                       5009
65  *                     Doc10                      5008
66  *
67  */
68
69 #include <stdlib.h>
70 #include <stdio.h>
71 #include <string.h>
72 #include <math.h>
73
74 #include "windef.h"
75 #include "winbase.h"
76 #include "wingdi.h"
77 #include "winuser.h"
78 #include "wine/unicode.h"
79 #include "win.h"
80 #include "heap.h"
81 #include "nonclient.h"
82 #include "controls.h"
83 #include "user.h"
84 #include "struct32.h"
85 #include "debugtools.h"
86 #include "dlgs.h"
87
88 DEFAULT_DEBUG_CHANNEL(mdi);
89
90 #define MDI_MAXLISTLENGTH       0x40
91 #define MDI_MAXTITLELENGTH      0xa1
92
93 #define MDI_NOFRAMEREPAINT      0
94 #define MDI_REPAINTFRAMENOW     1
95 #define MDI_REPAINTFRAME        2
96
97 #define WM_MDICALCCHILDSCROLL   0x10ac /* this is exactly what Windows uses */
98
99 /* "More Windows..." definitions */
100 #define MDI_MOREWINDOWSLIMIT    9       /* after this number of windows, a "More Windows..." 
101                                            option will appear under the Windows menu */
102 #define MDI_IDC_LISTBOX         100
103 #define MDI_IDS_MOREWINDOWS     13
104
105 #define MDIF_NEEDUPDATE         0x0001
106
107 typedef struct
108 {
109     UINT      nActiveChildren;
110     HWND      hwndChildMaximized;
111     HWND      hwndActiveChild;
112     HMENU     hWindowMenu;
113     UINT      idFirstChild;
114     LPWSTR    frameTitle;
115     UINT      nTotalCreated;
116     UINT      mdiFlags;
117     UINT      sbRecalc;   /* SB_xxx flags for scrollbar fixup */
118 } MDICLIENTINFO;
119
120 static HBITMAP hBmpClose   = 0;
121 static HBITMAP hBmpRestore = 0;
122
123 /* ----------------- declarations ----------------- */
124 static void MDI_UpdateFrameText( HWND, HWND, BOOL, LPCWSTR);
125 static BOOL MDI_AugmentFrameMenu( HWND, HWND );
126 static BOOL MDI_RestoreFrameMenu( HWND, HWND );
127 static LONG MDI_ChildActivate( HWND, HWND );
128
129 static HWND MDI_MoreWindowsDialog(HWND);
130 static void MDI_SwapMenuItems(HWND, UINT, UINT);
131 static LRESULT WINAPI MDIClientWndProcA( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );
132 static LRESULT WINAPI MDIClientWndProcW( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );
133
134 /* -------- Miscellaneous service functions ----------
135  *
136  *                      MDI_GetChildByID
137  */
138 static HWND MDI_GetChildByID(HWND hwnd, UINT id)
139 {
140     HWND ret;
141     HWND *win_array;
142     int i;
143
144     if (!(win_array = WIN_ListChildren( hwnd ))) return 0;
145     for (i = 0; win_array[i]; i++)
146     {
147         if (GetWindowLongA( win_array[i], GWL_ID ) == id) break;
148     }
149     ret = win_array[i];
150     HeapFree( GetProcessHeap(), 0, win_array );
151     return ret;
152 }
153
154 static void MDI_PostUpdate(HWND hwnd, MDICLIENTINFO* ci, WORD recalc)
155 {
156     if( !(ci->mdiFlags & MDIF_NEEDUPDATE) )
157     {
158         ci->mdiFlags |= MDIF_NEEDUPDATE;
159         PostMessageA( hwnd, WM_MDICALCCHILDSCROLL, 0, 0);
160     }
161     ci->sbRecalc = recalc;
162 }
163
164
165 /*********************************************************************
166  * MDIClient class descriptor
167  */
168 const struct builtin_class_descr MDICLIENT_builtin_class =
169 {
170     "MDIClient",            /* name */
171     CS_GLOBALCLASS,         /* style */
172     MDIClientWndProcA,      /* procA */
173     MDIClientWndProcW,      /* procW */
174     sizeof(MDICLIENTINFO),  /* extra */
175     IDC_ARROWA,             /* cursor */
176     COLOR_APPWORKSPACE+1    /* brush */
177 };
178
179
180 static MDICLIENTINFO *get_client_info( HWND client )
181 {
182     MDICLIENTINFO *ret = NULL;
183     WND *win = WIN_GetPtr( client );
184     if (win)
185     {
186         if (win == WND_OTHER_PROCESS)
187         {
188             ERR( "client %x belongs to other process\n", client );
189             return NULL;
190         }
191         if (win->cbWndExtra < sizeof(MDICLIENTINFO)) WARN( "%x is not an MDI client\n", client );
192         else ret = (MDICLIENTINFO *)win->wExtra;
193         WIN_ReleasePtr( win );
194     }
195     return ret;
196 }
197
198 /**********************************************************************
199  *                      MDI_MenuModifyItem
200  */
201 static void MDI_MenuModifyItem( HWND client, HWND hWndChild )
202 {
203     MDICLIENTINFO *clientInfo = get_client_info( client );
204     WCHAR buffer[128];
205     UINT n, id;
206
207     if (!clientInfo || !clientInfo->hWindowMenu) return;
208
209     id = GetWindowLongA( hWndChild, GWL_ID );
210     if (id >= clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT) return;
211     buffer[0] = '&';
212     buffer[1] = '1' + id - clientInfo->idFirstChild;
213     buffer[2] = ' ';
214     GetWindowTextW( hWndChild, buffer + 3, sizeof(buffer)/sizeof(WCHAR) - 3 );
215
216     n = GetMenuState(clientInfo->hWindowMenu, id, MF_BYCOMMAND);
217     ModifyMenuW(clientInfo->hWindowMenu, id, MF_BYCOMMAND | MF_STRING, id, buffer );
218     CheckMenuItem(clientInfo->hWindowMenu, id, n & MF_CHECKED);
219 }
220
221 /**********************************************************************
222  *                      MDI_MenuDeleteItem
223  */
224 static BOOL MDI_MenuDeleteItem( HWND client, HWND hWndChild )
225 {
226     WCHAR        buffer[128];
227     static const WCHAR format[] = {'&','%','d',' ',0};
228     MDICLIENTINFO *clientInfo = get_client_info( client );
229     UINT         index      = 0,id,n;
230
231     if( !clientInfo->nActiveChildren || !clientInfo->hWindowMenu )
232         return FALSE;
233
234     id = GetWindowLongA( hWndChild, GWL_ID );
235     DeleteMenu(clientInfo->hWindowMenu,id,MF_BYCOMMAND);
236
237  /* walk the rest of MDI children to prevent gaps in the id 
238   * sequence and in the menu child list */
239
240     for( index = id+1; index <= clientInfo->nActiveChildren + 
241                                 clientInfo->idFirstChild; index++ )
242     {
243         HWND hwnd = MDI_GetChildByID(client,index);
244         if (!hwnd)
245         {
246             TRACE("no window for id=%i\n",index);
247             continue;
248         }
249
250         /* set correct id */
251         SetWindowLongW( hwnd, GWL_ID, GetWindowLongW( hwnd, GWL_ID ) - 1 );
252
253         n = wsprintfW(buffer, format ,index - clientInfo->idFirstChild);
254         GetWindowTextW( hwnd, buffer + n, sizeof(buffer)/sizeof(WCHAR) - n );
255
256         /*  change menu if the current child is to be shown in the 
257          *  "Windows" menu
258          */
259         if (index <= clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT) 
260         ModifyMenuW(clientInfo->hWindowMenu ,index ,MF_BYCOMMAND | MF_STRING,
261                       index - 1 , buffer ); 
262     }
263
264     /*  We must restore the "More Windows..." option if there are enough children
265      */
266     if (clientInfo->nActiveChildren - 1 > MDI_MOREWINDOWSLIMIT)
267     {
268         WCHAR szTmp[50];
269         LoadStringW(GetModuleHandleA("USER32"), MDI_IDS_MOREWINDOWS, szTmp, sizeof(szTmp)/sizeof(szTmp[0]));
270         AppendMenuW(clientInfo->hWindowMenu, MF_STRING, clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT, szTmp);
271     }
272     return TRUE;
273 }
274
275 /**********************************************************************
276  *                      MDI_GetWindow
277  *
278  * returns "activateable" child different from the current or zero
279  */
280 static HWND MDI_GetWindow(MDICLIENTINFO *clientInfo, HWND hWnd, BOOL bNext,
281                             DWORD dwStyleMask )
282 {
283     int i;
284     HWND *list;
285     HWND last = 0;
286
287     dwStyleMask |= WS_DISABLED | WS_VISIBLE;
288     if( !hWnd ) hWnd = clientInfo->hwndActiveChild;
289
290     if (!(list = WIN_ListChildren( GetParent(hWnd) ))) return 0;
291     i = 0;
292     /* start from next after hWnd */
293     while (list[i] && list[i] != hWnd) i++;
294     if (list[i]) i++;
295
296     for ( ; list[i]; i++)
297     {
298         if (GetWindow( list[i], GW_OWNER )) continue;
299         if ((GetWindowLongW( list[i], GWL_STYLE ) & dwStyleMask) != WS_VISIBLE) continue;
300         last = list[i];
301         if (bNext) goto found;
302     }
303     /* now restart from the beginning */
304     for (i = 0; list[i] && list[i] != hWnd; i++)
305     {
306         if (GetWindow( list[i], GW_OWNER )) continue;
307         if ((GetWindowLongW( list[i], GWL_STYLE ) & dwStyleMask) != WS_VISIBLE) continue;
308         last = list[i];
309         if (bNext) goto found;
310     }
311  found:
312     HeapFree( GetProcessHeap(), 0, list );
313     return last;
314 }
315
316 /**********************************************************************
317  *                      MDI_CalcDefaultChildPos
318  *
319  *  It seems that the default height is about 2/3 of the client rect
320  */
321 static void MDI_CalcDefaultChildPos( HWND hwnd, WORD n, LPPOINT lpPos, INT delta)
322 {
323     INT  nstagger;
324     RECT rect;
325     INT  spacing = GetSystemMetrics(SM_CYCAPTION) +
326                      GetSystemMetrics(SM_CYFRAME) - 1; 
327
328     GetClientRect( hwnd, &rect );
329     if( rect.bottom - rect.top - delta >= spacing ) 
330         rect.bottom -= delta;
331
332     nstagger = (rect.bottom - rect.top)/(3 * spacing);
333     lpPos[1].x = (rect.right - rect.left - nstagger * spacing);
334     lpPos[1].y = (rect.bottom - rect.top - nstagger * spacing);
335     lpPos[0].x = lpPos[0].y = spacing * (n%(nstagger+1));
336 }
337
338 /**********************************************************************
339  *            MDISetMenu
340  */
341 static LRESULT MDISetMenu( HWND hwnd, HMENU hmenuFrame,
342                            HMENU hmenuWindow)
343 {
344     MDICLIENTINFO *ci;
345     HWND hwndFrame = GetParent(hwnd);
346     HMENU oldFrameMenu = GetMenu(hwndFrame);
347
348     TRACE("%04x %04x %04x\n",
349                 hwnd, hmenuFrame, hmenuWindow);
350
351     if (hmenuFrame && !IsMenu(hmenuFrame))
352     {
353         WARN("hmenuFrame is not a menu handle\n");
354         return 0L;
355     }
356         
357     if (hmenuWindow && !IsMenu(hmenuWindow))
358     {
359         WARN("hmenuWindow is not a menu handle\n");
360         return 0L;
361     }
362
363     if (!(ci = get_client_info( hwnd ))) return 0;
364
365     if( ci->hwndChildMaximized && hmenuFrame && hmenuFrame!=oldFrameMenu )
366         MDI_RestoreFrameMenu( GetParent(hwnd), ci->hwndChildMaximized );
367
368     if( hmenuWindow && ci->hWindowMenu && hmenuWindow!=ci->hWindowMenu )
369     {
370         /* delete menu items from ci->hWindowMenu 
371          * and add them to hmenuWindow */
372
373         INT i = GetMenuItemCount(ci->hWindowMenu) - 1;
374         INT pos = GetMenuItemCount(hmenuWindow) + 1;
375
376         AppendMenuA( hmenuWindow, MF_SEPARATOR, 0, NULL);
377
378         if( ci->nActiveChildren )
379         {
380             INT j;
381             LPWSTR buffer = NULL;
382             MENUITEMINFOW mii;
383             INT nbWindowsMenuItems; /* num of documents shown + "More Windows..." if present */
384
385             if (ci->nActiveChildren <= MDI_MOREWINDOWSLIMIT)
386                 nbWindowsMenuItems = ci->nActiveChildren;
387             else
388                 nbWindowsMenuItems = MDI_MOREWINDOWSLIMIT + 1;
389
390             j = i - nbWindowsMenuItems + 1;
391
392             for( ; i >= j ; i-- )
393             {
394                 memset(&mii, 0, sizeof(mii));
395                 mii.cbSize = sizeof(mii);
396                 mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE
397                   | MIIM_SUBMENU | MIIM_TYPE | MIIM_BITMAP;
398
399                 GetMenuItemInfoW(ci->hWindowMenu, i, TRUE, &mii);
400                 if(mii.cch) { /* Menu is MFT_STRING */
401                     mii.cch++; /* add room for '\0' */
402                     buffer = HeapAlloc(GetProcessHeap(), 0,
403                                        mii.cch * sizeof(WCHAR));
404                     mii.dwTypeData = buffer;
405                     GetMenuItemInfoW(ci->hWindowMenu, i, TRUE, &mii);
406                 }
407                 DeleteMenu(ci->hWindowMenu, i, MF_BYPOSITION);
408                 InsertMenuItemW(hmenuWindow, pos, TRUE, &mii);
409                 if(buffer) {
410                     HeapFree(GetProcessHeap(), 0, buffer);
411                     buffer = NULL;
412                 }
413             }
414         }
415
416         /* remove separator */
417         DeleteMenu(ci->hWindowMenu, i, MF_BYPOSITION); 
418
419         ci->hWindowMenu = hmenuWindow;
420     } 
421
422     if (hmenuFrame)
423     {
424         SetMenu(hwndFrame, hmenuFrame);
425         if( hmenuFrame!=oldFrameMenu )
426         {
427             if( ci->hwndChildMaximized )
428                 MDI_AugmentFrameMenu( GetParent(hwnd), ci->hwndChildMaximized );
429             return oldFrameMenu;
430         }
431     }
432     else
433     {
434         HMENU menu = GetMenu( GetParent(hwnd) );
435         INT nItems = GetMenuItemCount(menu) - 1;
436         UINT iId = GetMenuItemID(menu,nItems) ;
437
438         if( !(iId == SC_RESTORE || iId == SC_CLOSE) )
439         {
440             /* SetMenu() may already have been called, meaning that this window
441              * already has its menu. But they may have done a SetMenu() on
442              * an MDI window, and called MDISetMenu() after the fact, meaning
443              * that the "if" to this "else" wouldn't catch the need to
444              * augment the frame menu.
445              */
446             if( ci->hwndChildMaximized )
447                 MDI_AugmentFrameMenu( GetParent(hwnd), ci->hwndChildMaximized );
448         }
449     }
450     return 0;
451 }
452
453 /**********************************************************************
454  *            MDIRefreshMenu
455  */
456 static LRESULT MDIRefreshMenu( HWND hwnd, HMENU hmenuFrame,
457                            HMENU hmenuWindow)
458 {
459     HWND hwndFrame = GetParent(hwnd);
460     HMENU oldFrameMenu = GetMenu(hwndFrame);
461
462     TRACE("%04x %04x %04x\n",
463                 hwnd, hmenuFrame, hmenuWindow);
464
465     FIXME("partially function stub\n");
466
467     return oldFrameMenu;
468 }
469
470
471 /* ------------------ MDI child window functions ---------------------- */
472
473
474 /**********************************************************************
475  *                                      MDICreateChild
476  */
477 static HWND MDICreateChild( HWND parent, MDICLIENTINFO *ci,
478                             LPMDICREATESTRUCTA cs, BOOL unicode )
479 {
480     POINT          pos[2]; 
481     DWORD            style = cs->style | (WS_CHILD | WS_CLIPSIBLINGS);
482     HWND             hwnd, hwndMax = 0;
483     UINT wIDmenu = ci->idFirstChild + ci->nActiveChildren;
484     WND *wndParent;
485     static const WCHAR lpstrDef[] = {'j','u','n','k','!',0};
486
487     TRACE("origin %i,%i - dim %i,%i, style %08lx\n", 
488                 cs->x, cs->y, cs->cx, cs->cy, cs->style);
489     /* calculate placement */
490     MDI_CalcDefaultChildPos(parent, ci->nTotalCreated++, pos, 0);
491
492     if (cs->cx == CW_USEDEFAULT || cs->cx == CW_USEDEFAULT16 || !cs->cx) cs->cx = pos[1].x;
493     if (cs->cy == CW_USEDEFAULT || cs->cy == CW_USEDEFAULT16 || !cs->cy) cs->cy = pos[1].y;
494
495     if (cs->x == CW_USEDEFAULT || cs->x == CW_USEDEFAULT16)
496     {
497         cs->x = pos[0].x;
498         cs->y = pos[0].y;
499     }
500
501     /* restore current maximized child */
502     if( (style & WS_VISIBLE) && ci->hwndChildMaximized )
503     {
504         TRACE("Restoring current maximized child %04x\n", ci->hwndChildMaximized);
505         if( style & WS_MAXIMIZE )
506             SendMessageW(parent, WM_SETREDRAW, FALSE, 0L);
507         hwndMax = ci->hwndChildMaximized;
508         ShowWindow( hwndMax, SW_SHOWNOACTIVATE );
509         if( style & WS_MAXIMIZE )
510             SendMessageW(parent, WM_SETREDRAW, TRUE, 0L);
511     }
512
513     if (ci->nActiveChildren <= MDI_MOREWINDOWSLIMIT)
514     /* this menu is needed to set a check mark in MDI_ChildActivate */
515     if (ci->hWindowMenu != 0)
516         AppendMenuW(ci->hWindowMenu, MF_STRING, wIDmenu, lpstrDef);
517
518     ci->nActiveChildren++;
519
520     /* fix window style */
521     wndParent = WIN_FindWndPtr( parent );
522     if( !(wndParent->dwStyle & MDIS_ALLCHILDSTYLES) )
523     {
524         TRACE("MDIS_ALLCHILDSTYLES is missing, fixing window style\n");
525         style &= (WS_CHILD | WS_CLIPSIBLINGS | WS_MINIMIZE | WS_MAXIMIZE |
526                   WS_CLIPCHILDREN | WS_DISABLED | WS_VSCROLL | WS_HSCROLL );
527         style |= (WS_VISIBLE | WS_OVERLAPPEDWINDOW);
528     }
529
530     if( wndParent->flags & WIN_ISWIN32 )
531     {
532         WIN_ReleaseWndPtr( wndParent );
533         if(unicode)
534         {
535             MDICREATESTRUCTW *csW = (MDICREATESTRUCTW *)cs;
536             hwnd = CreateWindowW( csW->szClass, csW->szTitle, style, 
537                                 csW->x, csW->y, csW->cx, csW->cy, parent,
538                                 (HMENU)wIDmenu, csW->hOwner, csW );
539         }
540         else
541             hwnd = CreateWindowA( cs->szClass, cs->szTitle, style, 
542                                 cs->x, cs->y, cs->cx, cs->cy, parent,
543                                 (HMENU)wIDmenu, cs->hOwner, cs );
544     }
545     else
546     {
547         MDICREATESTRUCT16 *cs16;
548         LPSTR title, cls;
549
550         WIN_ReleaseWndPtr( wndParent );
551         cs16 = SEGPTR_NEW(MDICREATESTRUCT16);
552         STRUCT32_MDICREATESTRUCT32Ato16( cs, cs16 );
553         title = SEGPTR_STRDUP( cs->szTitle );
554         cls   = SEGPTR_STRDUP( cs->szClass );
555         cs16->szTitle = SEGPTR_GET(title);
556         cs16->szClass = SEGPTR_GET(cls);
557
558         hwnd = WIN_Handle32( CreateWindow16( cs->szClass, cs->szTitle, style,
559                                              cs16->x, cs16->y, cs16->cx, cs16->cy,
560                                              WIN_Handle16(parent), (HMENU)wIDmenu,
561                                              cs16->hOwner, (LPVOID)SEGPTR_GET(cs16) ));
562         SEGPTR_FREE( title );
563         SEGPTR_FREE( cls );
564         SEGPTR_FREE( cs16 );
565     }
566
567     /* MDI windows are WS_CHILD so they won't be activated by CreateWindow */
568
569     if (hwnd)
570     {
571         /* All MDI child windows have the WS_EX_MDICHILD style */
572         SetWindowLongW( hwnd, GWL_EXSTYLE, GetWindowLongW( hwnd, GWL_EXSTYLE ) | WS_EX_MDICHILD );
573
574         /*  If we have more than 9 windows, we must insert the new one at the
575          *  9th position in order to see it in the "Windows" menu
576          */
577         if (ci->nActiveChildren > MDI_MOREWINDOWSLIMIT)
578             MDI_SwapMenuItems( parent, GetWindowLongW( hwnd, GWL_ID ),
579                                ci->idFirstChild + MDI_MOREWINDOWSLIMIT - 1);
580
581         MDI_MenuModifyItem(parent, hwnd);
582
583         /* Have we hit the "More Windows..." limit? If so, we must 
584          * add a "More Windows..." option 
585          */
586         if (ci->nActiveChildren == MDI_MOREWINDOWSLIMIT + 1)
587         {
588             WCHAR szTmp[50];
589             LoadStringW(GetModuleHandleA("USER32"), MDI_IDS_MOREWINDOWS, szTmp, sizeof(szTmp)/sizeof(szTmp[0]));
590
591             ModifyMenuW(ci->hWindowMenu,
592                         ci->idFirstChild + MDI_MOREWINDOWSLIMIT, 
593                         MF_BYCOMMAND | MF_STRING, 
594                         ci->idFirstChild + MDI_MOREWINDOWSLIMIT, 
595                         szTmp);
596         }
597
598         if( IsIconic(hwnd) && ci->hwndActiveChild )
599         {
600             TRACE("Minimizing created MDI child %04x\n", hwnd);
601             ShowWindow( hwnd, SW_SHOWMINNOACTIVE );
602         }
603         else
604         {
605             /* WS_VISIBLE is clear if a) the MDI client has
606              * MDIS_ALLCHILDSTYLES style and 2) the flag is cleared in the
607              * MDICreateStruct. If so the created window is not shown nor 
608              * activated.
609              */
610             if (IsWindowVisible(hwnd)) ShowWindow(hwnd, SW_SHOW);
611         }
612         TRACE("created child - %04x\n",hwnd);
613     }
614     else
615     {
616         ci->nActiveChildren--;
617         DeleteMenu(ci->hWindowMenu,wIDmenu,MF_BYCOMMAND);
618         if( IsWindow(hwndMax) )
619             ShowWindow(hwndMax, SW_SHOWMAXIMIZED);
620     }
621         
622     return hwnd;
623 }
624
625 /**********************************************************************
626  *                      MDI_ChildGetMinMaxInfo
627  *
628  * Note: The rule here is that client rect of the maximized MDI child 
629  *       is equal to the client rect of the MDI client window.
630  */
631 static void MDI_ChildGetMinMaxInfo( HWND client, HWND hwnd, MINMAXINFO* lpMinMax )
632 {
633     RECT rect;
634
635     GetClientRect( client, &rect );
636     AdjustWindowRectEx( &rect, GetWindowLongW( hwnd, GWL_STYLE ),
637                         0, GetWindowLongW( hwnd, GWL_EXSTYLE ));
638
639     lpMinMax->ptMaxSize.x = rect.right -= rect.left;
640     lpMinMax->ptMaxSize.y = rect.bottom -= rect.top;
641
642     lpMinMax->ptMaxPosition.x = rect.left;
643     lpMinMax->ptMaxPosition.y = rect.top; 
644
645     TRACE("max rect (%i,%i - %i, %i)\n", 
646                         rect.left,rect.top,rect.right,rect.bottom);
647 }
648
649 /**********************************************************************
650  *                      MDI_SwitchActiveChild
651  * 
652  * Note: SetWindowPos sends WM_CHILDACTIVATE to the child window that is
653  *       being activated 
654  */
655 static void MDI_SwitchActiveChild( HWND clientHwnd, HWND childHwnd,
656                                    BOOL bNextWindow )
657 {
658     HWND           hwndTo    = 0;
659     HWND           hwndPrev  = 0;
660     MDICLIENTINFO *ci = get_client_info( clientHwnd );
661
662     hwndTo = MDI_GetWindow(ci, childHwnd, bNextWindow, 0);
663
664     TRACE("from %04x, to %04x\n",childHwnd,hwndTo);
665
666     if ( !hwndTo ) return; /* no window to switch to */
667
668     hwndPrev = ci->hwndActiveChild;
669
670     if ( hwndTo != hwndPrev )
671     {
672         SetWindowPos( hwndTo, HWND_TOP, 0, 0, 0, 0, 
673                       SWP_NOMOVE | SWP_NOSIZE );
674
675         if( bNextWindow && hwndPrev )
676             SetWindowPos( hwndPrev, HWND_BOTTOM, 0, 0, 0, 0, 
677                           SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE );
678     }
679 }
680
681
682 /**********************************************************************
683  *                                      MDIDestroyChild
684  */
685 static LRESULT MDIDestroyChild( HWND parent, MDICLIENTINFO *ci,
686                                 HWND child, BOOL flagDestroy )
687 {
688     if( child == ci->hwndActiveChild )
689     {
690         MDI_SwitchActiveChild(parent, child, TRUE);
691
692         if( child == ci->hwndActiveChild )
693         {
694             ShowWindow( child, SW_HIDE);
695             if( child == ci->hwndChildMaximized )
696             {
697                 HWND frame = GetParent(parent);
698                 MDI_RestoreFrameMenu( frame, child );
699                 ci->hwndChildMaximized = 0;
700                 MDI_UpdateFrameText( frame, parent, TRUE, NULL);
701             }
702
703             MDI_ChildActivate(parent, 0);
704         }
705     }
706
707     MDI_MenuDeleteItem(parent, child);
708
709     ci->nActiveChildren--;
710
711     TRACE("child destroyed - %04x\n",child);
712
713     if (flagDestroy)
714     {
715         MDI_PostUpdate(GetParent(child), ci, SB_BOTH+1);
716         DestroyWindow(child);
717     }
718     return 0;
719 }
720
721
722 /**********************************************************************
723  *                                      MDI_ChildActivate
724  *
725  * Note: hWndChild is NULL when last child is being destroyed
726  */
727 static LONG MDI_ChildActivate( HWND client, HWND child )
728 {
729     MDICLIENTINFO *clientInfo = get_client_info( client );
730     HWND prevActiveWnd = clientInfo->hwndActiveChild;
731     BOOL isActiveFrameWnd;
732
733     if (child && (!IsWindowEnabled( child ))) return 0;
734
735     /* Don't activate if it is already active. Might happen 
736        since ShowWindow DOES activate MDI children */
737     if (clientInfo->hwndActiveChild == child) return 0;
738
739     TRACE("%04x\n", child);
740
741     isActiveFrameWnd = (GetActiveWindow() == GetParent(client));
742
743     /* deactivate prev. active child */
744     if(prevActiveWnd)
745     {
746         SetWindowLongA( prevActiveWnd, GWL_STYLE,
747                         GetWindowLongA( prevActiveWnd, GWL_STYLE ) | WS_SYSMENU );
748         SendMessageA( prevActiveWnd, WM_NCACTIVATE, FALSE, 0L );
749         SendMessageA( prevActiveWnd, WM_MDIACTIVATE, (WPARAM)prevActiveWnd, (LPARAM)child);
750         /* uncheck menu item */
751         if( clientInfo->hWindowMenu )
752         {
753             UINT prevID = GetWindowLongA( prevActiveWnd, GWL_ID );
754
755             if (prevID - clientInfo->idFirstChild < MDI_MOREWINDOWSLIMIT)
756                 CheckMenuItem( clientInfo->hWindowMenu, prevID, 0);
757             else
758                 CheckMenuItem( clientInfo->hWindowMenu,
759                                clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT - 1, 0);
760         }
761     }
762
763     /* set appearance */
764     if (clientInfo->hwndChildMaximized && clientInfo->hwndChildMaximized != child)
765     {
766         if( child )
767         {
768             clientInfo->hwndActiveChild = child;
769             ShowWindow( child, SW_SHOWMAXIMIZED);
770         }
771         else ShowWindow( clientInfo->hwndActiveChild, SW_SHOWNORMAL );
772     }
773
774     clientInfo->hwndActiveChild = child;
775
776     /* check if we have any children left */
777     if( !child )
778     {
779         if( isActiveFrameWnd )
780             SetFocus( client );
781         return 0;
782     }
783
784     /* check menu item */
785     if( clientInfo->hWindowMenu )
786     {
787         UINT id = GetWindowLongA( child, GWL_ID );
788         /* The window to be activated must be displayed in the "Windows" menu */
789         if (id >= clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT)
790         {
791             MDI_SwapMenuItems( GetParent(child),
792                                id, clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT - 1);
793             id = clientInfo->idFirstChild + MDI_MOREWINDOWSLIMIT - 1;
794             MDI_MenuModifyItem( GetParent(child), child );
795         }
796
797         CheckMenuItem(clientInfo->hWindowMenu, id, MF_CHECKED);
798     }
799     /* bring active child to the top */
800     SetWindowPos( child, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
801
802     if( isActiveFrameWnd )
803     {
804             SendMessageA( child, WM_NCACTIVATE, TRUE, 0L);
805             if( GetFocus() == client )
806                 SendMessageA( client, WM_SETFOCUS, (WPARAM)client, 0L );
807             else
808                 SetFocus( client );
809     }
810     SendMessageA( child, WM_MDIACTIVATE, (WPARAM)prevActiveWnd, (LPARAM)child );
811     return TRUE;
812 }
813
814 /* -------------------- MDI client window functions ------------------- */
815
816 /**********************************************************************
817  *                              CreateMDIMenuBitmap
818  */
819 static HBITMAP CreateMDIMenuBitmap(void)
820 {
821  HDC            hDCSrc  = CreateCompatibleDC(0);
822  HDC            hDCDest = CreateCompatibleDC(hDCSrc);
823  HBITMAP        hbClose = LoadBitmapW(0, MAKEINTRESOURCEW(OBM_CLOSE) );
824  HBITMAP        hbCopy;
825  HBITMAP        hobjSrc, hobjDest;
826
827  hobjSrc = SelectObject(hDCSrc, hbClose);
828  hbCopy = CreateCompatibleBitmap(hDCSrc,GetSystemMetrics(SM_CXSIZE),GetSystemMetrics(SM_CYSIZE));
829  hobjDest = SelectObject(hDCDest, hbCopy);
830
831  BitBlt(hDCDest, 0, 0, GetSystemMetrics(SM_CXSIZE), GetSystemMetrics(SM_CYSIZE),
832           hDCSrc, GetSystemMetrics(SM_CXSIZE), 0, SRCCOPY);
833   
834  SelectObject(hDCSrc, hobjSrc);
835  DeleteObject(hbClose);
836  DeleteDC(hDCSrc);
837
838  hobjSrc = SelectObject( hDCDest, GetStockObject(BLACK_PEN) );
839
840  MoveToEx( hDCDest, GetSystemMetrics(SM_CXSIZE) - 1, 0, NULL );
841  LineTo( hDCDest, GetSystemMetrics(SM_CXSIZE) - 1, GetSystemMetrics(SM_CYSIZE) - 1);
842
843  SelectObject(hDCDest, hobjSrc );
844  SelectObject(hDCDest, hobjDest);
845  DeleteDC(hDCDest);
846
847  return hbCopy;
848 }
849
850 /**********************************************************************
851  *                              MDICascade
852  */
853 static LONG MDICascade( HWND client, MDICLIENTINFO *ci )
854 {
855     HWND *win_array;
856     BOOL has_icons = FALSE;
857     int i, total;
858
859     if (ci->hwndChildMaximized)
860         SendMessageA( client, WM_MDIRESTORE,
861                         (WPARAM)ci->hwndChildMaximized, 0);
862
863     if (ci->nActiveChildren == 0) return 0;
864
865     if (!(win_array = WIN_ListChildren( client ))) return 0;
866
867     /* remove all the windows we don't want */
868     for (i = total = 0; win_array[i]; i++)
869     {
870         if (!IsWindowVisible( win_array[i] )) continue;
871         if (GetWindow( win_array[i], GW_OWNER )) continue; /* skip owned windows */
872         if (IsIconic( win_array[i] ))
873         {
874             has_icons = TRUE;
875             continue;
876         }
877         win_array[total++] = win_array[i];
878     }
879     win_array[total] = 0;
880
881     if (total)
882     {
883         INT delta = 0, n = 0, i;
884         POINT pos[2];
885         if (has_icons) delta = GetSystemMetrics(SM_CYICONSPACING) + GetSystemMetrics(SM_CYICON);
886
887         /* walk the list (backwards) and move windows */
888         for (i = total - 1; i >= 0; i--)
889         {
890             TRACE("move %04x to (%ld,%ld) size [%ld,%ld]\n", 
891                   win_array[i], pos[0].x, pos[0].y, pos[1].x, pos[1].y);
892
893             MDI_CalcDefaultChildPos(client, n++, pos, delta);
894             SetWindowPos( win_array[i], 0, pos[0].x, pos[0].y, pos[1].x, pos[1].y,
895                           SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
896         }
897     }
898     HeapFree( GetProcessHeap(), 0, win_array );
899
900     if (has_icons) ArrangeIconicWindows( client );
901     return 0;
902 }
903
904 /**********************************************************************
905  *                                      MDITile
906  */
907 static void MDITile( HWND client, MDICLIENTINFO *ci, WPARAM wParam )
908 {
909     HWND *win_array;
910     int i, total;
911     BOOL has_icons = FALSE;
912
913     if (ci->hwndChildMaximized)
914         SendMessageA( client, WM_MDIRESTORE, (WPARAM)ci->hwndChildMaximized, 0);
915
916     if (ci->nActiveChildren == 0) return;
917
918     if (!(win_array = WIN_ListChildren( client ))) return;
919
920     /* remove all the windows we don't want */
921     for (i = total = 0; win_array[i]; i++)
922     {
923         if (!IsWindowVisible( win_array[i] )) continue;
924         if (GetWindow( win_array[i], GW_OWNER )) continue; /* skip owned windows (icon titles) */
925         if (IsIconic( win_array[i] ))
926         {
927             has_icons = TRUE;
928             continue;
929         }
930         if ((wParam & MDITILE_SKIPDISABLED) && !IsWindowEnabled( win_array[i] )) continue;
931         win_array[total++] = win_array[i];
932     }
933     win_array[total] = 0;
934
935     TRACE("%u windows to tile\n", total);
936
937     if (total)
938     {
939         HWND *pWnd = win_array;
940         RECT rect;
941         int x, y, xsize, ysize;
942         int rows, columns, r, c, i;
943
944         GetClientRect(client,&rect);
945         rows    = (int) sqrt((double)total);
946         columns = total / rows;
947
948         if( wParam & MDITILE_HORIZONTAL )  /* version >= 3.1 */
949         {
950             i = rows;
951             rows = columns;  /* exchange r and c */
952             columns = i;
953         }
954
955         if (has_icons)
956         {
957             y = rect.bottom - 2 * GetSystemMetrics(SM_CYICONSPACING) - GetSystemMetrics(SM_CYICON);
958             rect.bottom = ( y - GetSystemMetrics(SM_CYICON) < rect.top )? rect.bottom: y;
959         }
960
961         ysize   = rect.bottom / rows;
962         xsize   = rect.right  / columns;
963
964         for (x = i = 0, c = 1; c <= columns && *pWnd; c++)
965         {
966             if (c == columns)
967             {
968                 rows  = total - i;
969                 ysize = rect.bottom / rows;
970             }
971
972             y = 0;
973             for (r = 1; r <= rows && *pWnd; r++, i++)
974             {
975                 SetWindowPos(*pWnd, 0, x, y, xsize, ysize,
976                              SWP_DRAWFRAME | SWP_NOACTIVATE | SWP_NOZORDER);
977                 y += ysize;
978                 pWnd++;
979             }
980             x += xsize;
981         }
982     }
983     HeapFree( GetProcessHeap(), 0, win_array );
984     if (has_icons) ArrangeIconicWindows( client );
985 }
986
987 /* ----------------------- Frame window ---------------------------- */
988
989
990 /**********************************************************************
991  *                                      MDI_AugmentFrameMenu
992  */
993 static BOOL MDI_AugmentFrameMenu( HWND frame, HWND hChild )
994 {
995     HMENU menu = GetMenu( frame );
996     WND*        child = WIN_FindWndPtr(hChild);
997     HMENU       hSysPopup = 0;
998   HBITMAP hSysMenuBitmap = 0;
999
1000     TRACE("frame %04x,child %04x\n",frame,hChild);
1001
1002     if( !menu || !child->hSysMenu )
1003     {
1004         WIN_ReleaseWndPtr(child);
1005         return 0;
1006     }
1007     WIN_ReleaseWndPtr(child);
1008
1009     /* create a copy of sysmenu popup and insert it into frame menu bar */
1010
1011     if (!(hSysPopup = LoadMenuA(GetModuleHandleA("USER32"), "SYSMENU")))
1012         return 0;
1013
1014     AppendMenuA(menu,MF_HELP | MF_BITMAP,
1015                    SC_MINIMIZE, (LPSTR)(DWORD)HBMMENU_MBAR_MINIMIZE ) ;
1016     AppendMenuA(menu,MF_HELP | MF_BITMAP,
1017                    SC_RESTORE, (LPSTR)(DWORD)HBMMENU_MBAR_RESTORE );
1018
1019   /* In Win 95 look, the system menu is replaced by the child icon */
1020
1021   if(TWEAK_WineLook > WIN31_LOOK)
1022   {
1023     HICON hIcon = GetClassLongA(hChild, GCL_HICONSM);
1024     if (!hIcon)
1025       hIcon = GetClassLongA(hChild, GCL_HICON);
1026     if (hIcon)
1027     {
1028       HDC hMemDC;
1029       HBITMAP hBitmap, hOldBitmap;
1030       HBRUSH hBrush;
1031       HDC hdc = GetDC(hChild);
1032
1033       if (hdc)
1034       {
1035         int cx, cy;
1036         cx = GetSystemMetrics(SM_CXSMICON);
1037         cy = GetSystemMetrics(SM_CYSMICON);
1038         hMemDC = CreateCompatibleDC(hdc);
1039         hBitmap = CreateCompatibleBitmap(hdc, cx, cy);
1040         hOldBitmap = SelectObject(hMemDC, hBitmap);
1041         SetMapMode(hMemDC, MM_TEXT);
1042         hBrush = CreateSolidBrush(GetSysColor(COLOR_MENU));
1043         DrawIconEx(hMemDC, 0, 0, hIcon, cx, cy, 0, hBrush, DI_NORMAL);
1044         SelectObject (hMemDC, hOldBitmap);
1045         DeleteObject(hBrush);
1046         DeleteDC(hMemDC);
1047         ReleaseDC(hChild, hdc);
1048         hSysMenuBitmap = hBitmap;
1049       }
1050     }
1051   }
1052   else
1053     hSysMenuBitmap = hBmpClose;
1054
1055     if( !InsertMenuA(menu,0,MF_BYPOSITION | MF_BITMAP | MF_POPUP,
1056                     hSysPopup, (LPSTR)(DWORD)hSysMenuBitmap))
1057     {  
1058         TRACE("not inserted\n");
1059         DestroyMenu(hSysPopup); 
1060         return 0; 
1061     }
1062
1063     /* The close button is only present in Win 95 look */
1064     if(TWEAK_WineLook > WIN31_LOOK)
1065     {
1066         AppendMenuA(menu,MF_HELP | MF_BITMAP,
1067                        SC_CLOSE, (LPSTR)(DWORD)HBMMENU_MBAR_CLOSE );
1068     }
1069
1070     EnableMenuItem(hSysPopup, SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
1071     EnableMenuItem(hSysPopup, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
1072     EnableMenuItem(hSysPopup, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
1073     SetMenuDefaultItem(hSysPopup, SC_CLOSE, FALSE);
1074
1075     /* redraw menu */
1076     DrawMenuBar(frame);
1077
1078     return 1;
1079 }
1080
1081 /**********************************************************************
1082  *                                      MDI_RestoreFrameMenu
1083  */
1084 static BOOL MDI_RestoreFrameMenu( HWND frame, HWND hChild )
1085 {
1086     MENUITEMINFOW menuInfo;
1087     HMENU menu = GetMenu( frame );
1088     INT nItems = GetMenuItemCount(menu) - 1;
1089     UINT iId = GetMenuItemID(menu,nItems) ;
1090
1091     TRACE("frame %04x,child %04x,nIt=%d,iId=%d\n",frame,hChild,nItems,iId);
1092
1093     if(!(iId == SC_RESTORE || iId == SC_CLOSE) )
1094         return 0; 
1095
1096     /*
1097      * Remove the system menu, If that menu is the icon of the window
1098      * as it is in win95, we have to delete the bitmap.
1099      */
1100     memset(&menuInfo, 0, sizeof(menuInfo));
1101     menuInfo.cbSize = sizeof(menuInfo);
1102     menuInfo.fMask  = MIIM_DATA | MIIM_TYPE;
1103
1104     GetMenuItemInfoW(menu,
1105                      0, 
1106                      TRUE,
1107                      &menuInfo);
1108
1109     RemoveMenu(menu,0,MF_BYPOSITION);
1110
1111     if ( (menuInfo.fType & MFT_BITMAP)           &&
1112          (LOWORD(menuInfo.dwTypeData)!=0)        &&
1113          (LOWORD(menuInfo.dwTypeData)!=hBmpClose) )
1114     {
1115       DeleteObject((HBITMAP)LOWORD(menuInfo.dwTypeData));
1116     }
1117
1118     if(TWEAK_WineLook > WIN31_LOOK)
1119     {
1120         /* close */
1121         DeleteMenu(menu,GetMenuItemCount(menu) - 1,MF_BYPOSITION);
1122     }
1123     /* restore */
1124     DeleteMenu(menu,GetMenuItemCount(menu) - 1,MF_BYPOSITION);
1125     /* minimize */
1126     DeleteMenu(menu,GetMenuItemCount(menu) - 1,MF_BYPOSITION);
1127
1128     DrawMenuBar(frame);
1129
1130     return 1;
1131 }
1132
1133
1134 /**********************************************************************
1135  *                                      MDI_UpdateFrameText
1136  *
1137  * used when child window is maximized/restored 
1138  *
1139  * Note: lpTitle can be NULL
1140  */
1141 static void MDI_UpdateFrameText( HWND frame, HWND hClient,
1142                                  BOOL repaint, LPCWSTR lpTitle )
1143 {
1144     WCHAR   lpBuffer[MDI_MAXTITLELENGTH+1];
1145     MDICLIENTINFO *ci = get_client_info( hClient );
1146
1147     TRACE("repaint %i, frameText %s\n", repaint, debugstr_w(lpTitle));
1148
1149     if (!ci) return;
1150
1151     if (!lpTitle && !ci->frameTitle)  /* first time around, get title from the frame window */
1152     {
1153         GetWindowTextW( frame, lpBuffer, sizeof(lpBuffer)/sizeof(WCHAR) );
1154         lpTitle = lpBuffer;
1155     }
1156
1157     /* store new "default" title if lpTitle is not NULL */
1158     if (lpTitle) 
1159     {
1160         if (ci->frameTitle) HeapFree( GetProcessHeap(), 0, ci->frameTitle );
1161         if ((ci->frameTitle = HeapAlloc( GetProcessHeap(), 0, (strlenW(lpTitle)+1)*sizeof(WCHAR))))
1162             strcpyW( ci->frameTitle, lpTitle );
1163     }
1164
1165     if (ci->frameTitle)
1166     {
1167         if (ci->hwndChildMaximized)
1168         {
1169             /* combine frame title and child title if possible */
1170
1171             static const WCHAR lpBracket[]  = {' ','-',' ','[',0};
1172             static const WCHAR lpBracket2[]  = {']',0};
1173             int i_frame_text_length = strlenW(ci->frameTitle);
1174
1175             lstrcpynW( lpBuffer, ci->frameTitle, MDI_MAXTITLELENGTH);
1176
1177             if( i_frame_text_length + 6 < MDI_MAXTITLELENGTH )
1178             {
1179                 strcatW( lpBuffer, lpBracket );
1180                 if (GetWindowTextW( ci->hwndChildMaximized, lpBuffer + i_frame_text_length + 4,
1181                                     MDI_MAXTITLELENGTH - i_frame_text_length - 5 ))
1182                     strcatW( lpBuffer, lpBracket2 );
1183                 else
1184                     lpBuffer[i_frame_text_length] = 0;  /* remove bracket */
1185             }
1186         }
1187         else
1188         {
1189             lstrcpynW(lpBuffer, ci->frameTitle, MDI_MAXTITLELENGTH+1 );
1190         }
1191     }
1192     else
1193         lpBuffer[0] = '\0';
1194
1195     DefWindowProcW( frame, WM_SETTEXT, 0, (LPARAM)lpBuffer );
1196     if( repaint == MDI_REPAINTFRAME)
1197         SetWindowPos( frame, 0,0,0,0,0, SWP_FRAMECHANGED |
1198                       SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOZORDER );
1199 }
1200
1201
1202 /* ----------------------------- Interface ---------------------------- */
1203
1204
1205 /**********************************************************************
1206  *              MDIClientWndProc_common
1207  */
1208 static LRESULT MDIClientWndProc_common( HWND hwnd, UINT message,
1209                                         WPARAM wParam, LPARAM lParam, BOOL unicode )
1210 {
1211     MDICLIENTINFO *ci;
1212
1213     if (!(ci = get_client_info( hwnd ))) return 0;
1214
1215     switch (message)
1216     {
1217       case WM_CREATE:
1218       {
1219           RECT rect;
1220           /* Since we are using only cs->lpCreateParams, we can safely
1221            * cast to LPCREATESTRUCTA here */
1222           LPCREATESTRUCTA cs = (LPCREATESTRUCTA)lParam;
1223           WND *wndPtr = WIN_GetPtr( hwnd );
1224
1225         /* Translation layer doesn't know what's in the cs->lpCreateParams
1226          * so we have to keep track of what environment we're in. */
1227
1228         if( wndPtr->flags & WIN_ISWIN32 )
1229         {
1230 #define ccs ((LPCLIENTCREATESTRUCT)cs->lpCreateParams)
1231             ci->hWindowMenu     = ccs->hWindowMenu;
1232             ci->idFirstChild    = ccs->idFirstChild;
1233 #undef ccs
1234         }
1235         else    
1236         {
1237             LPCLIENTCREATESTRUCT16 ccs = MapSL((SEGPTR)cs->lpCreateParams);
1238             ci->hWindowMenu     = ccs->hWindowMenu;
1239             ci->idFirstChild    = ccs->idFirstChild;
1240         }
1241         WIN_ReleasePtr( wndPtr );
1242
1243         ci->hwndChildMaximized  = 0;
1244         ci->nActiveChildren     = 0;
1245         ci->nTotalCreated       = 0;
1246         ci->frameTitle          = NULL;
1247         ci->mdiFlags            = 0;
1248         SetWindowLongW( hwnd, GWL_STYLE, GetWindowLongW(hwnd,GWL_STYLE) | WS_CLIPCHILDREN );
1249
1250         if (!hBmpClose)
1251         {
1252             hBmpClose = CreateMDIMenuBitmap();
1253             hBmpRestore = LoadBitmapW( 0, MAKEINTRESOURCEW(OBM_RESTORE) );
1254         }
1255
1256         if (ci->hWindowMenu != 0)
1257             AppendMenuW( ci->hWindowMenu, MF_SEPARATOR, 0, NULL );
1258
1259         GetClientRect( GetParent(hwnd), &rect);
1260         MoveWindow( hwnd, 0, 0, rect.right, rect.bottom, FALSE );
1261
1262         MDI_UpdateFrameText( GetParent(hwnd), hwnd, MDI_NOFRAMEREPAINT, NULL);
1263
1264         TRACE("Client created - hwnd = %04x, idFirst = %u\n",
1265               hwnd, ci->idFirstChild );
1266         return 0;
1267       }
1268
1269       case WM_DESTROY:
1270       {
1271           INT nItems;
1272           if( ci->hwndChildMaximized )
1273               MDI_RestoreFrameMenu( GetParent(hwnd), ci->hwndChildMaximized);
1274           if((ci->hWindowMenu != 0) &&
1275              (nItems = GetMenuItemCount(ci->hWindowMenu)) > 0)
1276           {
1277               ci->idFirstChild = nItems - 1;
1278               ci->nActiveChildren++;  /* to delete a separator */
1279               while( ci->nActiveChildren-- )
1280                   DeleteMenu(ci->hWindowMenu,MF_BYPOSITION,ci->idFirstChild--);
1281           }
1282           if (ci->frameTitle) HeapFree( GetProcessHeap(), 0, ci->frameTitle );
1283           return 0;
1284       }
1285
1286       case WM_MDIACTIVATE:
1287         if( ci->hwndActiveChild != (HWND)wParam )
1288             SetWindowPos((HWND)wParam, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE);
1289         return 0;
1290
1291       case WM_MDICASCADE:
1292         return MDICascade(hwnd, ci);
1293
1294       case WM_MDICREATE:
1295         if (lParam)
1296             return (LRESULT)MDICreateChild( hwnd, ci, (MDICREATESTRUCTA *)lParam, unicode );
1297         return 0;
1298
1299       case WM_MDIDESTROY:
1300           return MDIDestroyChild( hwnd, ci, WIN_GetFullHandle( (HWND)wParam ), TRUE );
1301
1302       case WM_MDIGETACTIVE:
1303           if (lParam) *(BOOL *)lParam = (ci->hwndChildMaximized != 0);
1304           return (LRESULT)ci->hwndActiveChild;
1305
1306       case WM_MDIICONARRANGE:
1307         ci->mdiFlags |= MDIF_NEEDUPDATE;
1308         ArrangeIconicWindows( hwnd );
1309         ci->sbRecalc = SB_BOTH+1;
1310         SendMessageW( hwnd, WM_MDICALCCHILDSCROLL, 0, 0 );
1311         return 0;
1312
1313       case WM_MDIMAXIMIZE:
1314         ShowWindow( (HWND)wParam, SW_MAXIMIZE );
1315         return 0;
1316
1317       case WM_MDINEXT: /* lParam != 0 means previous window */
1318         MDI_SwitchActiveChild( hwnd, WIN_GetFullHandle( (HWND)wParam ), !lParam );
1319         break;
1320         
1321       case WM_MDIRESTORE:
1322         SendMessageW( (HWND)wParam, WM_SYSCOMMAND, SC_RESTORE, 0);
1323         return 0;
1324
1325       case WM_MDISETMENU:
1326           return MDISetMenu( hwnd, (HMENU)wParam, (HMENU)lParam );
1327
1328       case WM_MDIREFRESHMENU:
1329           return MDIRefreshMenu( hwnd, (HMENU)wParam, (HMENU)lParam );
1330
1331       case WM_MDITILE:
1332         ci->mdiFlags |= MDIF_NEEDUPDATE;
1333         ShowScrollBar( hwnd, SB_BOTH, FALSE );
1334         MDITile( hwnd, ci, wParam );
1335         ci->mdiFlags &= ~MDIF_NEEDUPDATE;
1336         return 0;
1337
1338       case WM_VSCROLL:
1339       case WM_HSCROLL:
1340         ci->mdiFlags |= MDIF_NEEDUPDATE;
1341         ScrollChildren( hwnd, message, wParam, lParam );
1342         ci->mdiFlags &= ~MDIF_NEEDUPDATE;
1343         return 0;
1344
1345       case WM_SETFOCUS:
1346           if (ci->hwndActiveChild && !IsIconic( ci->hwndActiveChild ))
1347               SetFocus( ci->hwndActiveChild );
1348           return 0;
1349
1350       case WM_NCACTIVATE:
1351         if( ci->hwndActiveChild )
1352             SendMessageW(ci->hwndActiveChild, message, wParam, lParam);
1353         break;
1354
1355       case WM_PARENTNOTIFY:
1356         if (LOWORD(wParam) == WM_LBUTTONDOWN)
1357         {
1358             HWND child;
1359             POINT pt;
1360             pt.x = SLOWORD(lParam);
1361             pt.y = SHIWORD(lParam);
1362             child = ChildWindowFromPoint(hwnd, pt);
1363
1364             TRACE("notification from %04x (%li,%li)\n",child,pt.x,pt.y);
1365
1366             if( child && child != hwnd && child != ci->hwndActiveChild )
1367                 SetWindowPos(child, 0,0,0,0,0, SWP_NOSIZE | SWP_NOMOVE );
1368         }
1369         return 0;
1370
1371       case WM_SIZE:
1372         if( IsWindow(ci->hwndChildMaximized) )
1373         {
1374             RECT        rect;
1375
1376             rect.left = 0;
1377             rect.top = 0;
1378             rect.right = LOWORD(lParam);
1379             rect.bottom = HIWORD(lParam);
1380
1381             AdjustWindowRectEx(&rect, GetWindowLongA(ci->hwndChildMaximized,GWL_STYLE),
1382                                0, GetWindowLongA(ci->hwndChildMaximized,GWL_EXSTYLE) );
1383             MoveWindow(ci->hwndChildMaximized, rect.left, rect.top,
1384                          rect.right - rect.left, rect.bottom - rect.top, 1);
1385         }
1386         else
1387             MDI_PostUpdate(hwnd, ci, SB_BOTH+1);
1388
1389         break;
1390
1391       case WM_MDICALCCHILDSCROLL:
1392         if( (ci->mdiFlags & MDIF_NEEDUPDATE) && ci->sbRecalc )
1393         {
1394             CalcChildScroll(hwnd, ci->sbRecalc-1);
1395             ci->sbRecalc = 0;
1396             ci->mdiFlags &= ~MDIF_NEEDUPDATE;
1397         }
1398         return 0;
1399     }
1400     return unicode ? DefWindowProcW( hwnd, message, wParam, lParam ) :
1401                      DefWindowProcA( hwnd, message, wParam, lParam );
1402 }
1403
1404 /***********************************************************************
1405  *              MDIClientWndProcA
1406  */
1407 static LRESULT WINAPI MDIClientWndProcA( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )
1408 {
1409     if (!IsWindow(hwnd)) return 0;
1410     return MDIClientWndProc_common( hwnd, message, wParam, lParam, FALSE );
1411 }
1412
1413 /***********************************************************************
1414  *              MDIClientWndProcW
1415  */
1416 static LRESULT WINAPI MDIClientWndProcW( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam )
1417 {
1418     if (!IsWindow(hwnd)) return 0;
1419     return MDIClientWndProc_common( hwnd, message, wParam, lParam, TRUE );
1420 }
1421
1422 /***********************************************************************
1423  *              DefFrameProc (USER.445)
1424  */
1425 LRESULT WINAPI DefFrameProc16( HWND16 hwnd, HWND16 hwndMDIClient,
1426                                UINT16 message, WPARAM16 wParam, LPARAM lParam )
1427 {
1428     switch (message)
1429     {
1430     case WM_SETTEXT:
1431         lParam = (LPARAM)MapSL(lParam);
1432         /* fall through */
1433     case WM_COMMAND:
1434     case WM_NCACTIVATE:
1435     case WM_SETFOCUS:
1436     case WM_SIZE:
1437         return DefFrameProcA( WIN_Handle32(hwnd), WIN_Handle32(hwndMDIClient),
1438                               message, wParam, lParam );
1439
1440     case WM_NEXTMENU:
1441         {
1442             MDINEXTMENU next_menu;
1443             DefFrameProcW( WIN_Handle32(hwnd), WIN_Handle32(hwndMDIClient),
1444                            message, wParam, (LPARAM)&next_menu );
1445             return MAKELONG( next_menu.hmenuNext, WIN_Handle16(next_menu.hwndNext) );
1446         }
1447     default:
1448         return DefWindowProc16(hwnd, message, wParam, lParam);
1449     }
1450 }
1451
1452
1453 /***********************************************************************
1454  *              DefFrameProcA (USER32.@)
1455  */
1456 LRESULT WINAPI DefFrameProcA( HWND hwnd, HWND hwndMDIClient,
1457                                 UINT message, WPARAM wParam, LPARAM lParam)
1458 {
1459     if (hwndMDIClient)
1460     {
1461         switch (message)
1462         {
1463         case WM_SETTEXT:
1464             {
1465                 LPWSTR text = HEAP_strdupAtoW( GetProcessHeap(), 0, (LPSTR)lParam );
1466                 MDI_UpdateFrameText(hwnd, hwndMDIClient, MDI_REPAINTFRAME, text );
1467                 HeapFree( GetProcessHeap(), 0, text );
1468             }
1469             return 1; /* success. FIXME: check text length */
1470
1471         case WM_COMMAND:
1472         case WM_NCACTIVATE:
1473         case WM_NEXTMENU:
1474         case WM_SETFOCUS:
1475         case WM_SIZE:
1476             return DefFrameProcW( hwnd, hwndMDIClient, message, wParam, lParam );
1477         }
1478     }
1479     return DefWindowProcA(hwnd, message, wParam, lParam);
1480 }
1481
1482
1483 /***********************************************************************
1484  *              DefFrameProcW (USER32.@)
1485  */
1486 LRESULT WINAPI DefFrameProcW( HWND hwnd, HWND hwndMDIClient,
1487                                 UINT message, WPARAM wParam, LPARAM lParam)
1488 {
1489     MDICLIENTINFO *ci = get_client_info( hwndMDIClient );
1490
1491     if (ci)
1492     {
1493         switch (message)
1494         {
1495         case WM_COMMAND:
1496             {
1497                 WORD id = LOWORD(wParam);
1498                 /* check for possible syscommands for maximized MDI child */
1499                 if (id <  ci->idFirstChild || id >= ci->idFirstChild + ci->nActiveChildren)
1500                 {
1501                     if( (id - 0xf000) & 0xf00f ) break;
1502                     if( !ci->hwndChildMaximized ) break;
1503                     switch( id )
1504                     {
1505                     case SC_SIZE:
1506                     case SC_MOVE:
1507                     case SC_MINIMIZE:
1508                     case SC_MAXIMIZE:
1509                     case SC_NEXTWINDOW:
1510                     case SC_PREVWINDOW:
1511                     case SC_CLOSE:
1512                     case SC_RESTORE:
1513                         return SendMessageW( ci->hwndChildMaximized, WM_SYSCOMMAND,
1514                                              wParam, lParam);
1515                     }
1516                 }
1517                 else
1518                 {
1519                     HWND childHwnd;
1520                     if (id - ci->idFirstChild == MDI_MOREWINDOWSLIMIT)
1521                         /* User chose "More Windows..." */
1522                         childHwnd = MDI_MoreWindowsDialog(hwndMDIClient);
1523                     else
1524                         /* User chose one of the windows listed in the "Windows" menu */
1525                         childHwnd = MDI_GetChildByID(hwndMDIClient,id);
1526
1527                     if( childHwnd )
1528                         SendMessageW( hwndMDIClient, WM_MDIACTIVATE, (WPARAM)childHwnd, 0 );
1529                 }
1530             }
1531             break;
1532
1533         case WM_NCACTIVATE:
1534             SendMessageW(hwndMDIClient, message, wParam, lParam);
1535             break;
1536
1537         case WM_SETTEXT: 
1538             MDI_UpdateFrameText(hwnd, hwndMDIClient, MDI_REPAINTFRAME, (LPWSTR)lParam );
1539             return 1; /* success. FIXME: check text length */
1540
1541         case WM_SETFOCUS:
1542             SetFocus(hwndMDIClient);
1543             break;
1544
1545         case WM_SIZE:
1546             MoveWindow(hwndMDIClient, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE);
1547             break;
1548
1549         case WM_NEXTMENU:
1550             {
1551                 MDINEXTMENU *next_menu = (MDINEXTMENU *)lParam;
1552
1553                 if (!IsIconic(hwnd) && ci->hwndActiveChild && !ci->hwndChildMaximized)
1554                 {
1555                     /* control menu is between the frame system menu and 
1556                      * the first entry of menu bar */
1557                     WND *wndPtr = WIN_GetPtr(hwnd);
1558
1559                     if( (wParam == VK_LEFT && GetMenu(hwnd) == next_menu->hmenuIn) ||
1560                         (wParam == VK_RIGHT && GetSubMenu(wndPtr->hSysMenu, 0) == next_menu->hmenuIn) )
1561                     {
1562                         WIN_ReleasePtr(wndPtr);
1563                         wndPtr = WIN_GetPtr(ci->hwndActiveChild);
1564                         next_menu->hmenuNext = GetSubMenu(wndPtr->hSysMenu, 0);
1565                         next_menu->hwndNext = ci->hwndActiveChild;
1566                     }
1567                     WIN_ReleasePtr(wndPtr);
1568                 }
1569                 return 0;
1570             }
1571         }
1572     }
1573
1574     return DefWindowProcW( hwnd, message, wParam, lParam );
1575 }
1576
1577
1578 /***********************************************************************
1579  *              DefMDIChildProc (USER.447)
1580  */
1581 LRESULT WINAPI DefMDIChildProc16( HWND16 hwnd, UINT16 message,
1582                                   WPARAM16 wParam, LPARAM lParam )
1583 {
1584     switch (message)
1585     {
1586     case WM_SETTEXT:
1587         return DefMDIChildProcA( WIN_Handle32(hwnd), message, wParam, (LPARAM)MapSL(lParam) );
1588     case WM_MENUCHAR:
1589     case WM_CLOSE:
1590     case WM_SETFOCUS:
1591     case WM_CHILDACTIVATE:
1592     case WM_SYSCOMMAND:
1593     case WM_SETVISIBLE:
1594     case WM_SIZE:
1595     case WM_SYSCHAR:
1596         return DefMDIChildProcW( WIN_Handle32(hwnd), message, wParam, lParam );
1597     case WM_GETMINMAXINFO:
1598         {
1599             MINMAXINFO16 *mmi16 = (MINMAXINFO16 *)MapSL(lParam);
1600             MINMAXINFO mmi;
1601             STRUCT32_MINMAXINFO16to32( mmi16, &mmi );
1602             DefMDIChildProcW( WIN_Handle32(hwnd), message, wParam, (LPARAM)&mmi );
1603             STRUCT32_MINMAXINFO32to16( &mmi, mmi16 );
1604             return 0;
1605         }
1606     case WM_NEXTMENU:
1607         {
1608             MDINEXTMENU next_menu;
1609             DefMDIChildProcW( WIN_Handle32(hwnd), message, wParam, (LPARAM)&next_menu );
1610             return MAKELONG( next_menu.hmenuNext, WIN_Handle16(next_menu.hwndNext) );
1611         }
1612     default:
1613         return DefWindowProc16(hwnd, message, wParam, lParam);
1614     }
1615 }
1616
1617
1618 /***********************************************************************
1619  *              DefMDIChildProcA (USER32.@)
1620  */
1621 LRESULT WINAPI DefMDIChildProcA( HWND hwnd, UINT message,
1622                                    WPARAM wParam, LPARAM lParam )
1623 {
1624     HWND client = GetParent(hwnd);
1625     MDICLIENTINFO *ci = get_client_info( client );
1626
1627     hwnd = WIN_GetFullHandle( hwnd );
1628     if (!ci) return DefWindowProcA( hwnd, message, wParam, lParam );
1629
1630     switch (message)
1631     {
1632     case WM_SETTEXT:
1633         DefWindowProcA(hwnd, message, wParam, lParam);
1634         MDI_MenuModifyItem( client, hwnd );
1635         if( ci->hwndChildMaximized == hwnd )
1636             MDI_UpdateFrameText( GetParent(client), client, MDI_REPAINTFRAME, NULL );
1637         return 1; /* success. FIXME: check text length */
1638
1639     case WM_GETMINMAXINFO:
1640     case WM_MENUCHAR:
1641     case WM_CLOSE:
1642     case WM_SETFOCUS:
1643     case WM_CHILDACTIVATE:
1644     case WM_SYSCOMMAND:
1645     case WM_SETVISIBLE:
1646     case WM_SIZE:
1647     case WM_NEXTMENU:
1648     case WM_SYSCHAR:
1649         return DefMDIChildProcW( hwnd, message, wParam, lParam );
1650     }
1651     return DefWindowProcA(hwnd, message, wParam, lParam);
1652 }
1653
1654
1655 /***********************************************************************
1656  *              DefMDIChildProcW (USER32.@)
1657  */
1658 LRESULT WINAPI DefMDIChildProcW( HWND hwnd, UINT message,
1659                                    WPARAM wParam, LPARAM lParam )
1660 {
1661     HWND client = GetParent(hwnd);
1662     MDICLIENTINFO *ci = get_client_info( client );
1663
1664     hwnd = WIN_GetFullHandle( hwnd );
1665     if (!ci) return DefWindowProcW( hwnd, message, wParam, lParam );
1666
1667     switch (message)
1668     {
1669     case WM_SETTEXT:
1670         DefWindowProcW(hwnd, message, wParam, lParam);
1671         MDI_MenuModifyItem( client, hwnd );
1672         if( ci->hwndChildMaximized == hwnd )
1673             MDI_UpdateFrameText( GetParent(client), client, MDI_REPAINTFRAME, NULL );
1674         return 1; /* success. FIXME: check text length */
1675
1676     case WM_GETMINMAXINFO:
1677         MDI_ChildGetMinMaxInfo( client, hwnd, (MINMAXINFO *)lParam );
1678         return 0;
1679
1680     case WM_MENUCHAR:
1681         return 0x00010000; /* MDI children don't have menu bars */
1682
1683     case WM_CLOSE:
1684         SendMessageW( client, WM_MDIDESTROY, (WPARAM)hwnd, 0 );
1685         return 0;
1686
1687     case WM_SETFOCUS:
1688         if (ci->hwndActiveChild != hwnd) MDI_ChildActivate( client, hwnd );
1689         break;
1690
1691     case WM_CHILDACTIVATE:
1692         MDI_ChildActivate( client, hwnd );
1693         return 0;
1694
1695     case WM_SYSCOMMAND:
1696         switch( wParam )
1697         {
1698         case SC_MOVE:
1699             if( ci->hwndChildMaximized == hwnd) return 0;
1700             break;
1701         case SC_RESTORE:
1702         case SC_MINIMIZE:
1703             SetWindowLongA( hwnd, GWL_STYLE,
1704                             GetWindowLongA( hwnd, GWL_STYLE ) | WS_SYSMENU );
1705             break;
1706         case SC_MAXIMIZE:
1707             if (ci->hwndChildMaximized == hwnd)
1708                 return SendMessageW( GetParent(client), message, wParam, lParam);
1709             SetWindowLongW( hwnd, GWL_STYLE,
1710                             GetWindowLongW( hwnd, GWL_STYLE ) & ~WS_SYSMENU );
1711             break;
1712         case SC_NEXTWINDOW:
1713             SendMessageW( client, WM_MDINEXT, 0, 0);
1714             return 0;
1715         case SC_PREVWINDOW:
1716             SendMessageW( client, WM_MDINEXT, 0, 1);
1717             return 0;
1718         }
1719         break;
1720
1721     case WM_SETVISIBLE:
1722         if( ci->hwndChildMaximized) ci->mdiFlags &= ~MDIF_NEEDUPDATE;
1723         else MDI_PostUpdate(client, ci, SB_BOTH+1);
1724         break;
1725
1726     case WM_SIZE:
1727         if( ci->hwndActiveChild == hwnd && wParam != SIZE_MAXIMIZED )
1728         {
1729             ci->hwndChildMaximized = 0;
1730             MDI_RestoreFrameMenu( GetParent(client), hwnd );
1731             MDI_UpdateFrameText( GetParent(client), client, MDI_REPAINTFRAME, NULL );
1732         }
1733
1734         if( wParam == SIZE_MAXIMIZED )
1735         {
1736             HWND hMaxChild = ci->hwndChildMaximized;
1737
1738             if( hMaxChild == hwnd ) break;
1739             if( hMaxChild)
1740             {
1741                 SendMessageW( hMaxChild, WM_SETREDRAW, FALSE, 0 );
1742                 MDI_RestoreFrameMenu( GetParent(client), hMaxChild );
1743                 ShowWindow( hMaxChild, SW_SHOWNOACTIVATE );
1744                 SendMessageW( hMaxChild, WM_SETREDRAW, TRUE, 0 );
1745             }
1746             TRACE("maximizing child %04x\n", hwnd );
1747
1748             /* keep track of the maximized window. */
1749             ci->hwndChildMaximized = hwnd; /* !!! */
1750
1751             /* The maximized window should also be the active window */
1752             MDI_ChildActivate( client, hwnd );
1753             MDI_AugmentFrameMenu( GetParent(client), hwnd );
1754             MDI_UpdateFrameText( GetParent(client), client, MDI_REPAINTFRAME, NULL );
1755         }
1756
1757         if( wParam == SIZE_MINIMIZED )
1758         {
1759             HWND switchTo = MDI_GetWindow(ci, hwnd, TRUE, WS_MINIMIZE);
1760
1761             if (switchTo) SendMessageW( switchTo, WM_CHILDACTIVATE, 0, 0);
1762         }
1763         MDI_PostUpdate(client, ci, SB_BOTH+1);
1764         break;
1765
1766     case WM_NEXTMENU:
1767         {
1768             MDINEXTMENU *next_menu = (MDINEXTMENU *)lParam;
1769             HWND parent = GetParent(client);
1770
1771             if( wParam == VK_LEFT )  /* switch to frame system menu */
1772             {
1773                 WND *wndPtr = WIN_GetPtr( parent );
1774                 next_menu->hmenuNext = GetSubMenu( wndPtr->hSysMenu, 0 );
1775                 WIN_ReleasePtr( wndPtr );
1776             }
1777             if( wParam == VK_RIGHT )  /* to frame menu bar */
1778             {
1779                 next_menu->hmenuNext = GetMenu(parent);
1780             }
1781             next_menu->hwndNext = parent;
1782             return 0;
1783         }
1784
1785     case WM_SYSCHAR:
1786         if (wParam == '-')
1787         {
1788             SendMessageW( hwnd, WM_SYSCOMMAND, (WPARAM)SC_KEYMENU, (DWORD)VK_SPACE);
1789             return 0;
1790         }
1791         break;
1792     }
1793     return DefWindowProcW(hwnd, message, wParam, lParam);
1794 }
1795
1796 /**********************************************************************
1797  *              CreateMDIWindowA (USER32.@) Creates a MDI child
1798  *
1799  * RETURNS
1800  *    Success: Handle to created window
1801  *    Failure: NULL
1802  */
1803 HWND WINAPI CreateMDIWindowA(
1804     LPCSTR lpClassName,    /* [in] Pointer to registered child class name */
1805     LPCSTR lpWindowName,   /* [in] Pointer to window name */
1806     DWORD dwStyle,         /* [in] Window style */
1807     INT X,               /* [in] Horizontal position of window */
1808     INT Y,               /* [in] Vertical position of window */
1809     INT nWidth,          /* [in] Width of window */
1810     INT nHeight,         /* [in] Height of window */
1811     HWND hWndParent,     /* [in] Handle to parent window */
1812     HINSTANCE hInstance, /* [in] Handle to application instance */
1813     LPARAM lParam)         /* [in] Application-defined value */
1814 {
1815     MDICLIENTINFO *pCi = get_client_info( hWndParent );
1816     MDICREATESTRUCTA cs;
1817
1818     TRACE("(%s,%s,%ld,%d,%d,%d,%d,%x,%d,%ld)\n",
1819           debugstr_a(lpClassName),debugstr_a(lpWindowName),dwStyle,X,Y,
1820           nWidth,nHeight,hWndParent,hInstance,lParam);
1821
1822     if (!pCi)
1823     {
1824         ERR("bad hwnd for MDI-client: %04x\n", hWndParent);
1825         return 0;
1826     }
1827     cs.szClass=lpClassName;
1828     cs.szTitle=lpWindowName;
1829     cs.hOwner=hInstance;
1830     cs.x=X;
1831     cs.y=Y;
1832     cs.cx=nWidth;
1833     cs.cy=nHeight;
1834     cs.style=dwStyle;
1835     cs.lParam=lParam;
1836
1837     return MDICreateChild(hWndParent, pCi, &cs, FALSE);
1838 }
1839
1840 /***********************************************************************
1841  *              CreateMDIWindowW (USER32.@) Creates a MDI child
1842  *
1843  * RETURNS
1844  *    Success: Handle to created window
1845  *    Failure: NULL
1846  */
1847 HWND WINAPI CreateMDIWindowW(
1848     LPCWSTR lpClassName,    /* [in] Pointer to registered child class name */
1849     LPCWSTR lpWindowName,   /* [in] Pointer to window name */
1850     DWORD dwStyle,         /* [in] Window style */
1851     INT X,               /* [in] Horizontal position of window */
1852     INT Y,               /* [in] Vertical position of window */
1853     INT nWidth,          /* [in] Width of window */
1854     INT nHeight,         /* [in] Height of window */
1855     HWND hWndParent,     /* [in] Handle to parent window */
1856     HINSTANCE hInstance, /* [in] Handle to application instance */
1857     LPARAM lParam)         /* [in] Application-defined value */
1858 {
1859     MDICLIENTINFO *pCi = get_client_info( hWndParent );
1860     MDICREATESTRUCTW cs;
1861
1862     TRACE("(%s,%s,%ld,%d,%d,%d,%d,%x,%d,%ld)\n",
1863           debugstr_w(lpClassName), debugstr_w(lpWindowName), dwStyle, X, Y,
1864           nWidth, nHeight, hWndParent, hInstance, lParam);
1865
1866     if (!pCi)
1867     {
1868         ERR("bad hwnd for MDI-client: %04x\n", hWndParent);
1869         return 0;
1870     }
1871     cs.szClass = lpClassName;
1872     cs.szTitle = lpWindowName;
1873     cs.hOwner = hInstance;
1874     cs.x = X;
1875     cs.y = Y;
1876     cs.cx = nWidth;
1877     cs.cy = nHeight;
1878     cs.style = dwStyle;
1879     cs.lParam = lParam;
1880
1881     return MDICreateChild(hWndParent, pCi, (MDICREATESTRUCTA *)&cs, TRUE);
1882 }
1883
1884 /**********************************************************************
1885  *              TranslateMDISysAccel (USER32.@)
1886  */
1887 BOOL WINAPI TranslateMDISysAccel( HWND hwndClient, LPMSG msg )
1888 {
1889     if (msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN)
1890     {
1891         MDICLIENTINFO *ci = get_client_info( hwndClient );
1892         WPARAM wParam = 0;
1893
1894         if (!ci || !IsWindowEnabled(ci->hwndActiveChild)) return 0;
1895
1896         /* translate if the Ctrl key is down and Alt not. */
1897
1898         if( (GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000))
1899         {
1900             switch( msg->wParam )
1901             {
1902             case VK_F6:
1903             case VK_TAB:
1904                 wParam = ( GetKeyState(VK_SHIFT) & 0x8000 ) ? SC_NEXTWINDOW : SC_PREVWINDOW;
1905                 break;
1906             case VK_F4:
1907             case VK_RBUTTON:
1908                 wParam = SC_CLOSE;
1909                 break;
1910             default:
1911                 return 0;
1912             }
1913             TRACE("wParam = %04x\n", wParam);
1914             SendMessageW(ci->hwndActiveChild, WM_SYSCOMMAND, wParam, (LPARAM)msg->wParam);
1915             return 1;
1916         }
1917     }
1918     return 0; /* failure */
1919 }
1920
1921 /***********************************************************************
1922  *              CalcChildScroll (USER32.@)
1923  */
1924 void WINAPI CalcChildScroll( HWND hwnd, INT scroll )
1925 {
1926     SCROLLINFO info;
1927     RECT childRect, clientRect;
1928     INT  vmin, vmax, hmin, hmax, vpos, hpos;
1929     HWND *list;
1930
1931     GetClientRect( hwnd, &clientRect );
1932     SetRectEmpty( &childRect );
1933
1934     if ((list = WIN_ListChildren( hwnd )))
1935     {
1936         int i;
1937         for (i = 0; list[i]; i++)
1938         {
1939             DWORD style = GetWindowLongW( list[i], GWL_STYLE );
1940             if (style & WS_MAXIMIZE)
1941             {
1942                 HeapFree( GetProcessHeap(), 0, list );
1943                 ShowScrollBar( hwnd, SB_BOTH, FALSE );
1944                 return;
1945             }
1946             if (style & WS_VISIBLE)
1947             {
1948                 WND *pWnd = WIN_FindWndPtr( list[i] );
1949                 UnionRect( &childRect, &pWnd->rectWindow, &childRect );
1950                 WIN_ReleaseWndPtr( pWnd );
1951             }
1952         }
1953         HeapFree( GetProcessHeap(), 0, list );
1954     }
1955     UnionRect( &childRect, &clientRect, &childRect );
1956
1957     hmin = childRect.left;
1958     hmax = childRect.right - clientRect.right;
1959     hpos = clientRect.left - childRect.left;
1960     vmin = childRect.top;
1961     vmax = childRect.bottom - clientRect.bottom;
1962     vpos = clientRect.top - childRect.top;
1963
1964     switch( scroll )
1965     {
1966         case SB_HORZ:
1967                         vpos = hpos; vmin = hmin; vmax = hmax;
1968         case SB_VERT:
1969                         info.cbSize = sizeof(info);
1970                         info.nMax = vmax; info.nMin = vmin; info.nPos = vpos;
1971                         info.fMask = SIF_POS | SIF_RANGE;
1972                         SetScrollInfo(hwnd, scroll, &info, TRUE);
1973                         break;
1974         case SB_BOTH:
1975                         SCROLL_SetNCSbState( hwnd, vmin, vmax, vpos,
1976                                              hmin, hmax, hpos);
1977     }    
1978 }
1979
1980
1981 /***********************************************************************
1982  *              ScrollChildren (USER32.@)
1983  */
1984 void WINAPI ScrollChildren(HWND hWnd, UINT uMsg, WPARAM wParam,
1985                              LPARAM lParam)
1986 {
1987     INT newPos = -1;
1988     INT curPos, length, minPos, maxPos, shift;
1989     RECT rect;
1990
1991     GetClientRect( hWnd, &rect );
1992
1993     switch(uMsg)
1994     {
1995     case WM_HSCROLL:
1996         GetScrollRange(hWnd,SB_HORZ,&minPos,&maxPos);
1997         curPos = GetScrollPos(hWnd,SB_HORZ);
1998         length = (rect.right - rect.left) / 2;
1999         shift = GetSystemMetrics(SM_CYHSCROLL);
2000         break;
2001     case WM_VSCROLL:
2002         GetScrollRange(hWnd,SB_VERT,&minPos,&maxPos);
2003         curPos = GetScrollPos(hWnd,SB_VERT);
2004         length = (rect.bottom - rect.top) / 2;
2005         shift = GetSystemMetrics(SM_CXVSCROLL);
2006         break;
2007     default:
2008         return;
2009     }
2010
2011     switch( wParam )
2012     {
2013         case SB_LINEUP: 
2014                         newPos = curPos - shift;
2015                         break;
2016         case SB_LINEDOWN:    
2017                         newPos = curPos + shift;
2018                         break;
2019         case SB_PAGEUP: 
2020                         newPos = curPos - length;
2021                         break;
2022         case SB_PAGEDOWN:    
2023                         newPos = curPos + length;
2024                         break;
2025
2026         case SB_THUMBPOSITION: 
2027                         newPos = LOWORD(lParam);
2028                         break;
2029
2030         case SB_THUMBTRACK:  
2031                         return;
2032
2033         case SB_TOP:            
2034                         newPos = minPos;
2035                         break;
2036         case SB_BOTTOM: 
2037                         newPos = maxPos;
2038                         break;
2039         case SB_ENDSCROLL:
2040                         CalcChildScroll(hWnd,(uMsg == WM_VSCROLL)?SB_VERT:SB_HORZ);
2041                         return;
2042     }
2043
2044     if( newPos > maxPos )
2045         newPos = maxPos;
2046     else 
2047         if( newPos < minPos )
2048             newPos = minPos;
2049
2050     SetScrollPos(hWnd, (uMsg == WM_VSCROLL)?SB_VERT:SB_HORZ , newPos, TRUE);
2051
2052     if( uMsg == WM_VSCROLL )
2053         ScrollWindowEx(hWnd ,0 ,curPos - newPos, NULL, NULL, 0, NULL, 
2054                         SW_INVALIDATE | SW_ERASE | SW_SCROLLCHILDREN );
2055     else
2056         ScrollWindowEx(hWnd ,curPos - newPos, 0, NULL, NULL, 0, NULL,
2057                         SW_INVALIDATE | SW_ERASE | SW_SCROLLCHILDREN );
2058 }
2059
2060
2061 /******************************************************************************
2062  *              CascadeWindows (USER32.@) Cascades MDI child windows
2063  *
2064  * RETURNS
2065  *    Success: Number of cascaded windows.
2066  *    Failure: 0
2067  */
2068 WORD WINAPI
2069 CascadeWindows (HWND hwndParent, UINT wFlags, const LPRECT lpRect,
2070                 UINT cKids, const HWND *lpKids)
2071 {
2072     FIXME("(0x%08x,0x%08x,...,%u,...): stub\n",
2073            hwndParent, wFlags, cKids);
2074
2075     return 0;
2076 }
2077
2078
2079 /******************************************************************************
2080  *              TileWindows (USER32.@) Tiles MDI child windows
2081  *
2082  * RETURNS
2083  *    Success: Number of tiled windows.
2084  *    Failure: 0
2085  */
2086 WORD WINAPI
2087 TileWindows (HWND hwndParent, UINT wFlags, const LPRECT lpRect,
2088              UINT cKids, const HWND *lpKids)
2089 {
2090     FIXME("(0x%08x,0x%08x,...,%u,...): stub\n",
2091            hwndParent, wFlags, cKids);
2092
2093     return 0;
2094 }
2095
2096 /************************************************************************
2097  *              "More Windows..." functionality
2098  */
2099
2100 /*              MDI_MoreWindowsDlgProc
2101  *
2102  *    This function will process the messages sent to the "More Windows..."
2103  *    dialog.
2104  *    Return values:  0    = cancel pressed
2105  *                    HWND = ok pressed or double-click in the list...
2106  *
2107  */
2108
2109 static BOOL WINAPI MDI_MoreWindowsDlgProc (HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam)
2110 {
2111     switch (iMsg)
2112     {
2113        case WM_INITDIALOG:
2114        {
2115            UINT widest       = 0;
2116            UINT length;
2117            UINT i;
2118            MDICLIENTINFO *ci = get_client_info( (HWND)lParam );
2119            HWND hListBox = GetDlgItem(hDlg, MDI_IDC_LISTBOX);
2120            HWND *list, *sorted_list;
2121
2122            if (!(list = WIN_ListChildren( (HWND)lParam ))) return TRUE;
2123            if (!(sorted_list = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
2124                                           sizeof(HWND) * ci->nActiveChildren )))
2125            {
2126                HeapFree( GetProcessHeap(), 0, list );
2127                return FALSE;
2128            }
2129
2130            /* Fill the list, sorted by id... */
2131            for (i = 0; list[i]; i++)
2132            {
2133                UINT id = GetWindowLongW( list[i], GWL_ID ) - ci->idFirstChild;
2134                if (id < ci->nActiveChildren) sorted_list[id] = list[i];
2135            }
2136            HeapFree( GetProcessHeap(), 0, list );
2137
2138            for (i = 0; i < ci->nActiveChildren; i++)
2139            {
2140                WCHAR buffer[128];
2141
2142                if (!GetWindowTextW( sorted_list[i], buffer, sizeof(buffer)/sizeof(WCHAR) ))
2143                    continue;
2144                SendMessageW(hListBox, LB_ADDSTRING, 0, (LPARAM)buffer );
2145                SendMessageW(hListBox, LB_SETITEMDATA, i, (LPARAM)sorted_list[i] );
2146                length = strlenW(buffer);  /* FIXME: should use GetTextExtentPoint */
2147                if (length > widest)
2148                    widest = length;
2149            }
2150            /* Make sure the horizontal scrollbar scrolls ok */
2151            SendMessageW(hListBox, LB_SETHORIZONTALEXTENT, widest * 6, 0);
2152
2153            /* Set the current selection */
2154            SendMessageW(hListBox, LB_SETCURSEL, MDI_MOREWINDOWSLIMIT, 0);
2155            return TRUE;
2156        }
2157
2158        case WM_COMMAND:
2159            switch (LOWORD(wParam))
2160            {
2161                 default:
2162                     if (HIWORD(wParam) != LBN_DBLCLK) break;
2163                     /* fall through */
2164                 case IDOK:
2165                 {
2166                     /*  windows are sorted by menu ID, so we must return the
2167                      *  window associated to the given id
2168                      */
2169                     HWND hListBox     = GetDlgItem(hDlg, MDI_IDC_LISTBOX);
2170                     UINT index        = SendMessageW(hListBox, LB_GETCURSEL, 0, 0);
2171                     LRESULT res = SendMessageW(hListBox, LB_GETITEMDATA, index, 0);
2172                     EndDialog(hDlg, res);
2173                     return TRUE;
2174                 }
2175                 case IDCANCEL:
2176                     EndDialog(hDlg, 0);
2177                     return TRUE;
2178            }
2179            break;
2180     }
2181     return FALSE;
2182 }
2183
2184 /*
2185  *
2186  *                      MDI_MoreWindowsDialog
2187  *
2188  *     Prompts the user with a listbox containing the opened
2189  *     documents. The user can then choose a windows and click
2190  *     on OK to set the current window to the one selected, or
2191  *     CANCEL to cancel. The function returns a handle to the
2192  *     selected window.
2193  */
2194
2195 static HWND MDI_MoreWindowsDialog(HWND hwnd)
2196 {
2197     LPCVOID template;
2198     HRSRC hRes;
2199     HANDLE hDlgTmpl;
2200
2201     hRes = FindResourceA(GetModuleHandleA("USER32"), "MDI_MOREWINDOWS", RT_DIALOGA);
2202
2203     if (hRes == 0)
2204         return 0;
2205
2206     hDlgTmpl = LoadResource(GetModuleHandleA("USER32"), hRes );
2207
2208     if (hDlgTmpl == 0)
2209         return 0;
2210
2211     template = LockResource( hDlgTmpl );
2212
2213     if (template == 0)
2214         return 0;
2215
2216     return (HWND) DialogBoxIndirectParamA(GetModuleHandleA("USER32"),
2217                                           (LPDLGTEMPLATEA) template,
2218                                           hwnd, MDI_MoreWindowsDlgProc, (LPARAM) hwnd);
2219 }
2220
2221 /*
2222  *
2223  *                      MDI_SwapMenuItems
2224  *
2225  *      Will swap the menu IDs for the given 2 positions.
2226  *      pos1 and pos2 are menu IDs
2227  *     
2228  *    
2229  */
2230
2231 static void MDI_SwapMenuItems(HWND parent, UINT pos1, UINT pos2)
2232 {
2233     HWND *list;
2234     int i;
2235
2236     if (!(list = WIN_ListChildren( parent ))) return;
2237     for (i = 0; list[i]; i++)
2238     {
2239         UINT id = GetWindowLongW( list[i], GWL_ID );
2240         if (id == pos1) SetWindowLongW( list[i], GWL_ID, pos2 );
2241         else if (id == pos2) SetWindowLongW( list[i], GWL_ID, pos1 );
2242     }
2243     HeapFree( GetProcessHeap(), 0, list );
2244 }
2245