msxml3/xmldoc: Fix IPersistStreamInit::GetClassID() for IXMLDocument.
[wine] / dlls / shell32 / brsfolder.c
1 /*
2  * Copyright 1999 Juergen Schmied
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  * FIXME:
19  *  - many memory leaks
20  *  - many flags unimplemented
21  *    - implement new dialog style "make new folder" button
22  *    - implement editbox
23  */
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #define COBJMACROS
29 #define NONAMELESSUNION
30 #define NONAMELESSSTRUCT
31
32 #include "wine/debug.h"
33 #include "undocshell.h"
34 #include "pidl.h"
35 #include "shell32_main.h"
36 #include "shellapi.h"
37 #include "shresdef.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(shell);
40
41 /* original margins and control size */
42 typedef struct tagLAYOUT_DATA
43 {
44     LONG left, width, right;
45     LONG top, height, bottom;
46 } LAYOUT_DATA;
47
48 typedef struct tagbrowse_info
49 {
50     HWND          hWnd;
51     HWND          hwndTreeView;
52     LPBROWSEINFOW lpBrowseInfo;
53     LPITEMIDLIST  pidlRet;
54     LAYOUT_DATA  *layout;  /* filled by LayoutInit, used by LayoutUpdate */
55     SIZE          szMin;
56 } browse_info;
57
58 typedef struct tagTV_ITEMDATA
59 {
60    LPSHELLFOLDER lpsfParent; /* IShellFolder of the parent */
61    LPITEMIDLIST  lpi;        /* PIDL relative to parent */
62    LPITEMIDLIST  lpifq;      /* Fully qualified PIDL */
63    IEnumIDList*  pEnumIL;    /* Children iterator */ 
64 } TV_ITEMDATA, *LPTV_ITEMDATA;
65
66 typedef struct tagLAYOUT_INFO
67 {
68     int iItemId;          /* control id */
69     DWORD dwAnchor;       /* BF_* flags specifying which margins should remain constant */
70 } LAYOUT_INFO;
71
72 static const LAYOUT_INFO g_layout_info[] =
73 {
74     {IDD_TITLE,         BF_TOP|BF_LEFT|BF_RIGHT},
75     {IDD_STATUS,        BF_TOP|BF_LEFT|BF_RIGHT},
76     {IDD_FOLDER,        BF_TOP|BF_LEFT|BF_RIGHT},
77     {IDD_TREEVIEW,      BF_TOP|BF_BOTTOM|BF_LEFT|BF_RIGHT},
78     {IDD_FOLDER,        BF_BOTTOM|BF_LEFT},
79     {IDD_FOLDERTEXT,    BF_BOTTOM|BF_LEFT|BF_RIGHT},
80     {IDD_MAKENEWFOLDER, BF_BOTTOM|BF_LEFT},
81     {IDOK,              BF_BOTTOM|BF_RIGHT},
82     {IDCANCEL,          BF_BOTTOM|BF_RIGHT}
83 };
84
85 #define LAYOUT_INFO_COUNT (sizeof(g_layout_info)/sizeof(g_layout_info[0]))
86
87 #define SUPPORTEDFLAGS (BIF_STATUSTEXT | \
88                         BIF_BROWSEFORCOMPUTER | \
89                         BIF_RETURNFSANCESTORS | \
90                         BIF_RETURNONLYFSDIRS | \
91                         BIF_NONEWFOLDERBUTTON | \
92                         BIF_NEWDIALOGSTYLE | \
93                         BIF_BROWSEINCLUDEFILES)
94
95 static void FillTreeView(browse_info*, LPSHELLFOLDER,
96                LPITEMIDLIST, HTREEITEM, IEnumIDList*);
97 static HTREEITEM InsertTreeViewItem( browse_info*, IShellFolder *,
98                LPCITEMIDLIST, LPCITEMIDLIST, IEnumIDList*, HTREEITEM);
99
100 static const WCHAR szBrowseFolderInfo[] = {
101     '_','_','W','I','N','E','_',
102     'B','R','S','F','O','L','D','E','R','D','L','G','_',
103     'I','N','F','O',0
104 };
105
106 static inline DWORD BrowseFlagsToSHCONTF(UINT ulFlags)
107 {
108     return SHCONTF_FOLDERS | (ulFlags & BIF_BROWSEINCLUDEFILES ? SHCONTF_NONFOLDERS : 0);
109 }
110
111 static void browsefolder_callback( LPBROWSEINFOW lpBrowseInfo, HWND hWnd,
112                                    UINT msg, LPARAM param )
113 {
114     if (!lpBrowseInfo->lpfn)
115         return;
116     lpBrowseInfo->lpfn( hWnd, msg, param, lpBrowseInfo->lParam );
117 }
118
119 static LAYOUT_DATA *LayoutInit(HWND hwnd, const LAYOUT_INFO *layout_info, int layout_count)
120 {
121     LAYOUT_DATA *data;
122     RECT rcWnd;
123     int i;
124
125     GetClientRect(hwnd, &rcWnd);
126     data = SHAlloc(sizeof(LAYOUT_DATA)*layout_count);
127     for (i = 0; i < layout_count; i++)
128     {
129         RECT r;
130         HWND hItem = GetDlgItem(hwnd, layout_info[i].iItemId);
131
132         if (hItem == NULL)
133             ERR("Item %d not found\n", i);
134         GetWindowRect(hItem, &r);
135         MapWindowPoints(HWND_DESKTOP, hwnd, (LPPOINT)&r, 2);
136
137         data[i].left = r.left;
138         data[i].right = rcWnd.right - r.right;
139         data[i].width = r.right - r.left;
140
141         data[i].top = r.top;
142         data[i].bottom = rcWnd.bottom - r.bottom;
143         data[i].height = r.bottom - r.top;
144     }
145     return data;
146 }
147
148 static void LayoutUpdate(HWND hwnd, LAYOUT_DATA *data, const LAYOUT_INFO *layout_info, int layout_count)
149 {
150     RECT rcWnd;
151     int i;
152
153     GetClientRect(hwnd, &rcWnd);
154     for (i = 0; i < layout_count; i++)
155     {
156         RECT r;
157         HWND hItem = GetDlgItem(hwnd, layout_info[i].iItemId);
158
159         GetWindowRect(hItem, &r);
160         MapWindowPoints(HWND_DESKTOP, hwnd, (LPPOINT)&r, 2);
161
162         if (layout_info[i].dwAnchor & BF_RIGHT)
163         {
164             r.right = rcWnd.right - data[i].right;
165             if (!(layout_info[i].dwAnchor & BF_LEFT))
166                 r.left = r.right - data[i].width;
167         }
168
169         if (layout_info[i].dwAnchor & BF_BOTTOM)
170         {
171             r.bottom = rcWnd.bottom - data[i].bottom;
172             if (!(layout_info[i].dwAnchor & BF_TOP))
173                 r.top = r.bottom - data[i].height;
174         }
175
176         SetWindowPos(hItem, NULL, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER);
177     }
178 }
179
180
181 /******************************************************************************
182  * InitializeTreeView [Internal]
183  *
184  * Called from WM_INITDIALOG handler.
185  * 
186  * PARAMS
187  *  hwndParent [I] The BrowseForFolder dialog
188  *  root       [I] ITEMIDLIST of the root shell folder
189  */
190 static void InitializeTreeView( browse_info *info )
191 {
192     LPITEMIDLIST pidlParent, pidlChild;
193     HIMAGELIST hImageList;
194     HRESULT hr;
195     IShellFolder *lpsfParent, *lpsfRoot;
196     IEnumIDList * pEnumChildren = NULL;
197     HTREEITEM item;
198     DWORD flags;
199     LPCITEMIDLIST root = info->lpBrowseInfo->pidlRoot;
200
201     TRACE("%p\n", info );
202     
203     Shell_GetImageList(NULL, &hImageList);
204
205     if (hImageList)
206         SendMessageW( info->hwndTreeView, TVM_SETIMAGELIST, 0, (LPARAM)hImageList );
207
208     /* We want to call InsertTreeViewItem down the code, in order to insert
209      * the root item of the treeview. Due to InsertTreeViewItem's signature, 
210      * we need the following to do this:
211      *
212      * + An ITEMIDLIST corresponding to _the parent_ of root. 
213      * + An ITEMIDLIST, which is a relative path from root's parent to root 
214      *   (containing a single SHITEMID).
215      * + An IShellFolder interface pointer of root's parent folder.
216      *
217      * If root is 'Desktop', then root's parent is also 'Desktop'.
218      */
219
220     pidlParent = ILClone(root);
221     ILRemoveLastID(pidlParent);
222     pidlChild = ILClone(ILFindLastID(root));
223     
224     if (_ILIsDesktop(pidlParent)) {
225         hr = SHGetDesktopFolder(&lpsfParent);
226     } else {
227         IShellFolder *lpsfDesktop;
228         hr = SHGetDesktopFolder(&lpsfDesktop);
229         if (FAILED(hr)) {
230             WARN("SHGetDesktopFolder failed! hr = %08x\n", hr);
231             return;
232         }
233         hr = IShellFolder_BindToObject(lpsfDesktop, pidlParent, 0, &IID_IShellFolder, (LPVOID*)&lpsfParent);
234         IShellFolder_Release(lpsfDesktop);
235     }
236
237     if (FAILED(hr)) {
238         WARN("Could not bind to parent shell folder! hr = %08x\n", hr);
239         return;
240     }
241
242     if (pidlChild && pidlChild->mkid.cb) {
243         hr = IShellFolder_BindToObject(lpsfParent, pidlChild, 0, &IID_IShellFolder, (LPVOID*)&lpsfRoot);
244     } else {
245         lpsfRoot = lpsfParent;
246         hr = IShellFolder_AddRef(lpsfParent);
247     }
248
249     if (FAILED(hr)) {
250         WARN("Could not bind to root shell folder! hr = %08x\n", hr);
251         IShellFolder_Release(lpsfParent);
252         return;
253     }
254
255     flags = BrowseFlagsToSHCONTF( info->lpBrowseInfo->ulFlags );
256     hr = IShellFolder_EnumObjects( lpsfRoot, info->hWnd, flags, &pEnumChildren );
257     if (FAILED(hr)) {
258         WARN("Could not get child iterator! hr = %08x\n", hr);
259         IShellFolder_Release(lpsfParent);
260         IShellFolder_Release(lpsfRoot);
261         return;
262     }
263
264     SendMessageW( info->hwndTreeView, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT );
265     item = InsertTreeViewItem( info, lpsfParent, pidlChild,
266                                pidlParent, pEnumChildren, TVI_ROOT );
267     SendMessageW( info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item );
268
269     IShellFolder_Release(lpsfRoot);
270     IShellFolder_Release(lpsfParent);
271 }
272
273 static int GetIcon(LPCITEMIDLIST lpi, UINT uFlags)
274 {
275     SHFILEINFOW sfi;
276     SHGetFileInfoW((LPCWSTR)lpi, 0 ,&sfi, sizeof(SHFILEINFOW), uFlags);
277     return sfi.iIcon;
278 }
279
280 static void GetNormalAndSelectedIcons(LPITEMIDLIST lpifq, LPTVITEMW lpTV_ITEM)
281 {
282     LPITEMIDLIST pidlDesktop = NULL;
283     DWORD flags;
284
285     TRACE("%p %p\n",lpifq, lpTV_ITEM);
286
287     if (!lpifq)
288     {
289         pidlDesktop = _ILCreateDesktop();
290         lpifq = pidlDesktop;
291     }
292
293     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON;
294     lpTV_ITEM->iImage = GetIcon( lpifq, flags );
295
296     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_OPENICON;
297     lpTV_ITEM->iSelectedImage = GetIcon( lpifq, flags );
298
299     if (pidlDesktop)
300         ILFree( pidlDesktop );
301 }
302
303 /******************************************************************************
304  * GetName [Internal]
305  *
306  * Query a shell folder for the display name of one of it's children
307  *
308  * PARAMS
309  *  lpsf           [I] IShellFolder interface of the folder to be queried.
310  *  lpi            [I] ITEMIDLIST of the child, relative to parent
311  *  dwFlags        [I] as in IShellFolder::GetDisplayNameOf
312  *  lpFriendlyName [O] The desired display name in unicode
313  *
314  * RETURNS
315  *  Success: TRUE
316  *  Failure: FALSE
317  */
318 static BOOL GetName(LPSHELLFOLDER lpsf, LPCITEMIDLIST lpi, DWORD dwFlags, LPWSTR lpFriendlyName)
319 {
320         BOOL   bSuccess=TRUE;
321         STRRET str;
322
323         TRACE("%p %p %x %p\n", lpsf, lpi, dwFlags, lpFriendlyName);
324         if (SUCCEEDED(IShellFolder_GetDisplayNameOf(lpsf, lpi, dwFlags, &str)))
325           bSuccess = StrRetToStrNW(lpFriendlyName, MAX_PATH, &str, lpi);
326         else
327           bSuccess = FALSE;
328
329         TRACE("-- %s\n", debugstr_w(lpFriendlyName));
330         return bSuccess;
331 }
332
333 /******************************************************************************
334  * InsertTreeViewItem [Internal]
335  *
336  * PARAMS
337  *  info       [I] data for the dialog
338  *  lpsf       [I] IShellFolder interface of the item's parent shell folder 
339  *  pidl       [I] ITEMIDLIST of the child to insert, relative to parent
340  *  pidlParent [I] ITEMIDLIST of the parent shell folder
341  *  pEnumIL    [I] Iterator for the children of the item to be inserted
342  *  hParent    [I] The treeview-item that represents the parent shell folder
343  *
344  * RETURNS
345  *  Success: Handle to the created and inserted treeview-item
346  *  Failure: NULL
347  */
348 static HTREEITEM InsertTreeViewItem( browse_info *info, IShellFolder * lpsf,
349     LPCITEMIDLIST pidl, LPCITEMIDLIST pidlParent, IEnumIDList* pEnumIL,
350     HTREEITEM hParent)
351 {
352         TVITEMW         tvi;
353         TVINSERTSTRUCTW tvins;
354         WCHAR           szBuff[MAX_PATH];
355         LPTV_ITEMDATA   lptvid=0;
356
357         tvi.mask  = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
358
359         tvi.cChildren= pEnumIL ? 1 : 0;
360         tvi.mask |= TVIF_CHILDREN;
361
362         lptvid = SHAlloc( sizeof(TV_ITEMDATA) );
363         if (!lptvid)
364             return NULL;
365
366         if (!GetName(lpsf, pidl, SHGDN_NORMAL, szBuff))
367             return NULL;
368
369         tvi.pszText    = szBuff;
370         tvi.cchTextMax = MAX_PATH;
371         tvi.lParam = (LPARAM)lptvid;
372
373         IShellFolder_AddRef(lpsf);
374         lptvid->lpsfParent = lpsf;
375         lptvid->lpi     = ILClone(pidl);
376         lptvid->lpifq   = pidlParent ? ILCombine(pidlParent, pidl) : ILClone(pidl);
377         lptvid->pEnumIL = pEnumIL;
378         GetNormalAndSelectedIcons(lptvid->lpifq, &tvi);
379
380         tvins.u.item       = tvi;
381         tvins.hInsertAfter = NULL;
382         tvins.hParent      = hParent;
383
384         return TreeView_InsertItemW( info->hwndTreeView, &tvins );
385 }
386
387 /******************************************************************************
388  * FillTreeView [Internal]
389  *
390  * For each child (given by lpe) of the parent shell folder, which is given by 
391  * lpsf and whose PIDL is pidl, insert a treeview-item right under hParent
392  *
393  * PARAMS
394  *  info    [I] data for the dialog
395  *  lpsf    [I] IShellFolder interface of the parent shell folder
396  *  pidl    [I] ITEMIDLIST of the parent shell folder
397  *  hParent [I] The treeview item that represents the parent shell folder
398  *  lpe     [I] An iterator for the children of the parent shell folder
399  */
400 static void FillTreeView( browse_info *info, IShellFolder * lpsf,
401                  LPITEMIDLIST  pidl, HTREEITEM hParent, IEnumIDList* lpe)
402 {
403         HTREEITEM       hPrev = 0;
404         LPITEMIDLIST    pidlTemp = 0;
405         ULONG           ulFetched;
406         HRESULT         hr;
407         HWND            hwnd = GetParent( info->hwndTreeView );
408
409         TRACE("%p %p %p %p\n",lpsf, pidl, hParent, lpe);
410
411         /* No IEnumIDList -> No children */
412         if (!lpe) return;
413         
414         SetCapture( hwnd );
415         SetCursor( LoadCursorA( 0, (LPSTR)IDC_WAIT ) );
416
417         while (NOERROR == IEnumIDList_Next(lpe,1,&pidlTemp,&ulFetched))
418         {
419             ULONG ulAttrs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER;
420             IEnumIDList* pEnumIL = NULL;
421             IShellFolder* pSFChild = NULL;
422             IShellFolder_GetAttributesOf(lpsf, 1, (LPCITEMIDLIST*)&pidlTemp, &ulAttrs);
423             if (ulAttrs & SFGAO_FOLDER)
424             {
425                 hr = IShellFolder_BindToObject(lpsf,pidlTemp,NULL,&IID_IShellFolder,(LPVOID*)&pSFChild);
426                 if (SUCCEEDED(hr))
427                 {
428                     DWORD flags = BrowseFlagsToSHCONTF(info->lpBrowseInfo->ulFlags);
429                     hr = IShellFolder_EnumObjects(pSFChild, hwnd, flags, &pEnumIL);
430                     if (hr == S_OK)
431                     {
432                         if ((IEnumIDList_Skip(pEnumIL, 1) != S_OK) ||
433                              FAILED(IEnumIDList_Reset(pEnumIL)))
434                         {
435                             IEnumIDList_Release(pEnumIL);
436                             pEnumIL = NULL;
437                         }
438                     }
439                     IShellFolder_Release(pSFChild);
440                 }
441             }
442
443             if (!(hPrev = InsertTreeViewItem(info, lpsf, pidlTemp, pidl, pEnumIL, hParent)))
444                 goto done;
445             SHFree(pidlTemp);  /* Finally, free the pidl that the shell gave us... */
446             pidlTemp=NULL;
447         }
448
449 done:
450         ReleaseCapture();
451         SetCursor(LoadCursorW(0, (LPWSTR)IDC_ARROW));
452     SHFree(pidlTemp);
453 }
454
455 static inline BOOL PIDLIsType(LPCITEMIDLIST pidl, PIDLTYPE type)
456 {
457     LPPIDLDATA data = _ILGetDataPointer(pidl);
458     if (!data)
459         return FALSE;
460     return (data->type == type);
461 }
462
463 static void BrsFolder_CheckValidSelection( browse_info *info, LPTV_ITEMDATA lptvid )
464 {
465     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
466     LPCITEMIDLIST pidl = lptvid->lpi;
467     BOOL bEnabled = TRUE;
468     DWORD dwAttributes;
469     HRESULT r;
470
471     if ((lpBrowseInfo->ulFlags & BIF_BROWSEFORCOMPUTER) &&
472         !PIDLIsType(pidl, PT_COMP))
473         bEnabled = FALSE;
474     if (lpBrowseInfo->ulFlags & BIF_RETURNFSANCESTORS)
475     {
476         dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
477         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
478                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
479         if (FAILED(r) || !(dwAttributes & (SFGAO_FILESYSANCESTOR|SFGAO_FILESYSTEM)))
480             bEnabled = FALSE;
481     }
482     if (lpBrowseInfo->ulFlags & BIF_RETURNONLYFSDIRS)
483     {
484         dwAttributes = SFGAO_FOLDER | SFGAO_FILESYSTEM;
485         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
486                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
487         if (FAILED(r) || 
488             ((dwAttributes & (SFGAO_FOLDER|SFGAO_FILESYSTEM)) != (SFGAO_FOLDER|SFGAO_FILESYSTEM)))
489         {
490             bEnabled = FALSE;
491         }
492     }
493     SendMessageW(info->hWnd, BFFM_ENABLEOK, 0, bEnabled);
494 }
495
496 static LRESULT BrsFolder_Treeview_Delete( browse_info *info, NMTREEVIEWW *pnmtv )
497 {
498     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA)pnmtv->itemOld.lParam;
499
500     TRACE("TVN_DELETEITEMA/W %p\n", lptvid);
501
502     IShellFolder_Release(lptvid->lpsfParent);
503     if (lptvid->pEnumIL)
504         IEnumIDList_Release(lptvid->pEnumIL);
505     SHFree(lptvid->lpi);
506     SHFree(lptvid->lpifq);
507     SHFree(lptvid);
508     return 0;
509 }
510
511 static LRESULT BrsFolder_Treeview_Expand( browse_info *info, NMTREEVIEWW *pnmtv )
512 {
513     IShellFolder *lpsf2 = NULL;
514     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
515     HRESULT r;
516
517     TRACE("TVN_ITEMEXPANDINGA/W\n");
518
519     if ((pnmtv->itemNew.state & TVIS_EXPANDEDONCE))
520         return 0;
521
522     if (lptvid->lpi && lptvid->lpi->mkid.cb) {
523         r = IShellFolder_BindToObject( lptvid->lpsfParent, lptvid->lpi, 0,
524                                        &IID_IShellFolder, (LPVOID *)&lpsf2 );
525     } else {
526         lpsf2 = lptvid->lpsfParent;
527         r = IShellFolder_AddRef(lpsf2);
528     }
529
530     if (SUCCEEDED(r))
531         FillTreeView( info, lpsf2, lptvid->lpifq, pnmtv->itemNew.hItem, lptvid->pEnumIL);
532
533     /* My Computer is already sorted and trying to do a simple text
534      * sort will only mess things up */
535     if (!_ILIsMyComputer(lptvid->lpi))
536         SendMessageW( info->hwndTreeView, TVM_SORTCHILDREN,
537                       FALSE, (LPARAM)pnmtv->itemNew.hItem );
538
539     return 0;
540 }
541
542 static HRESULT BrsFolder_Treeview_Changed( browse_info *info, NMTREEVIEWW *pnmtv )
543 {
544     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
545
546     lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
547     info->pidlRet = lptvid->lpifq;
548     browsefolder_callback( info->lpBrowseInfo, info->hWnd, BFFM_SELCHANGED,
549                            (LPARAM)info->pidlRet );
550     BrsFolder_CheckValidSelection( info, lptvid );
551     return 0;
552 }
553
554 static LRESULT BrsFolder_OnNotify( browse_info *info, UINT CtlID, LPNMHDR lpnmh )
555 {
556     NMTREEVIEWW *pnmtv = (NMTREEVIEWW *)lpnmh;
557
558     TRACE("%p %x %p msg=%x\n", info, CtlID, lpnmh, pnmtv->hdr.code);
559
560     if (pnmtv->hdr.idFrom != IDD_TREEVIEW)
561         return 0;
562
563     switch (pnmtv->hdr.code)
564     {
565     case TVN_DELETEITEMA:
566     case TVN_DELETEITEMW:
567         return BrsFolder_Treeview_Delete( info, pnmtv );
568
569     case TVN_ITEMEXPANDINGA:
570     case TVN_ITEMEXPANDINGW:
571         return BrsFolder_Treeview_Expand( info, pnmtv );
572
573     case TVN_SELCHANGEDA:
574     case TVN_SELCHANGEDW:
575         return BrsFolder_Treeview_Changed( info, pnmtv );
576
577     default:
578         WARN("unhandled (%d)\n", pnmtv->hdr.code);
579         break;
580     }
581
582     return 0;
583 }
584
585
586 static BOOL BrsFolder_OnCreate( HWND hWnd, browse_info *info )
587 {
588     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
589
590     info->hWnd = hWnd;
591     SetPropW( hWnd, szBrowseFolderInfo, info );
592
593     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
594         FIXME("flags BIF_NEWDIALOGSTYLE partially implemented\n");
595     if (lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS)
596         FIXME("flags %x not implemented\n", lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS);
597
598     if (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
599     {
600         RECT rcWnd;
601
602         info->layout = LayoutInit(hWnd, g_layout_info, LAYOUT_INFO_COUNT);
603
604         /* TODO: Windows allows shrinking the windows a bit */
605         GetWindowRect(hWnd, &rcWnd);
606         info->szMin.cx = rcWnd.right - rcWnd.left;
607         info->szMin.cy = rcWnd.bottom - rcWnd.top;
608     }
609     else
610     {
611         info->layout = NULL;
612     }
613
614     if (lpBrowseInfo->lpszTitle)
615         SetWindowTextW( GetDlgItem(hWnd, IDD_TITLE), lpBrowseInfo->lpszTitle );
616     else
617         ShowWindow( GetDlgItem(hWnd, IDD_TITLE), SW_HIDE );
618
619     if (!(lpBrowseInfo->ulFlags & BIF_STATUSTEXT)
620         || (lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
621         ShowWindow( GetDlgItem(hWnd, IDD_STATUS), SW_HIDE );
622
623     /* Hide "Make New Folder" Button? */
624     if ((lpBrowseInfo->ulFlags & BIF_NONEWFOLDERBUTTON)
625         || !(lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE))
626         ShowWindow( GetDlgItem(hWnd, IDD_MAKENEWFOLDER), SW_HIDE );
627
628     /* Hide the editbox? */
629     if (!(lpBrowseInfo->ulFlags & BIF_EDITBOX))
630     {
631         ShowWindow( GetDlgItem(hWnd, IDD_FOLDER), SW_HIDE );
632         ShowWindow( GetDlgItem(hWnd, IDD_FOLDERTEXT), SW_HIDE );
633     }
634
635     info->hwndTreeView = GetDlgItem( hWnd, IDD_TREEVIEW );
636     if (info->hwndTreeView)
637     {
638         InitializeTreeView( info );
639
640         /* Resize the treeview if there's not editbox */
641         if ((lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE)
642             && !(lpBrowseInfo->ulFlags & BIF_EDITBOX))
643         {
644             RECT rc;
645             GetClientRect(info->hwndTreeView, &rc);
646             SetWindowPos(info->hwndTreeView, HWND_TOP, 0, 0,
647                          rc.right, rc.bottom + 40, SWP_NOMOVE);
648         }
649     }
650     else
651         ERR("treeview control missing!\n");
652
653     browsefolder_callback( info->lpBrowseInfo, hWnd, BFFM_INITIALIZED, 0 );
654
655     return TRUE;
656 }
657
658 static BOOL BrsFolder_OnCommand( browse_info *info, UINT id )
659 {
660     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
661
662     switch (id)
663     {
664     case IDOK:
665         /* The original pidl is owned by the treeview and will be free'd. */
666         info->pidlRet = ILClone(info->pidlRet);
667         if (info->pidlRet == NULL) /* A null pidl would mean a cancel */
668             info->pidlRet = _ILCreateDesktop();
669         pdump( info->pidlRet );
670         if (lpBrowseInfo->pszDisplayName)
671             SHGetPathFromIDListW( info->pidlRet, lpBrowseInfo->pszDisplayName );
672         EndDialog( info->hWnd, 1 );
673         return TRUE;
674
675     case IDCANCEL:
676         EndDialog( info->hWnd, 0 );
677         return TRUE;
678
679     case IDD_MAKENEWFOLDER:
680         FIXME("make new folder not implemented\n");
681         return TRUE;
682     }
683     return FALSE;
684 }
685
686 static BOOL BrsFolder_OnSetExpanded(browse_info *info, LPVOID selection, 
687     BOOL is_str, HTREEITEM *pItem)
688 {
689     LPITEMIDLIST pidlSelection = selection;
690     LPCITEMIDLIST pidlCurrent, pidlRoot;
691     TVITEMEXW item;
692     BOOL bResult = FALSE;
693     
694     /* If 'selection' is a string, convert to a Shell ID List. */ 
695     if (is_str) {
696         IShellFolder *psfDesktop;
697         HRESULT hr;
698
699         hr = SHGetDesktopFolder(&psfDesktop);
700         if (FAILED(hr))
701             goto done;
702
703         hr = IShellFolder_ParseDisplayName(psfDesktop, NULL, NULL, 
704                      selection, NULL, &pidlSelection, NULL);
705         IShellFolder_Release(psfDesktop);
706         if (FAILED(hr)) 
707             goto done;
708     }
709
710     /* Move pidlCurrent behind the SHITEMIDs in pidlSelection, which are the root of
711      * the sub-tree currently displayed. */
712     pidlRoot = info->lpBrowseInfo->pidlRoot;
713     pidlCurrent = pidlSelection;
714     while (!_ILIsEmpty(pidlRoot) && _ILIsEqualSimple(pidlRoot, pidlCurrent)) {
715         pidlRoot = ILGetNext(pidlRoot);
716         pidlCurrent = ILGetNext(pidlCurrent);
717     }
718
719     /* The given ID List is not part of the SHBrowseForFolder's current sub-tree. */
720     if (!_ILIsEmpty(pidlRoot))
721         goto done;
722
723     /* Initialize item to point to the first child of the root folder. */
724     memset(&item, 0, sizeof(item));
725     item.mask = TVIF_PARAM;
726     item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_ROOT, 0);
727
728     if (item.hItem)
729         item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
730                                              (LPARAM)item.hItem);
731
732     /* Walk the tree along the nodes corresponding to the remaining ITEMIDLIST */
733     while (item.hItem && !_ILIsEmpty(pidlCurrent)) {
734         LPTV_ITEMDATA pItemData;
735
736         SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
737         pItemData = (LPTV_ITEMDATA)item.lParam;
738
739         if (_ILIsEqualSimple(pItemData->lpi, pidlCurrent)) {
740             pidlCurrent = ILGetNext(pidlCurrent);
741             if (!_ILIsEmpty(pidlCurrent)) {
742                 /* Only expand current node and move on to it's first child,
743                  * if we didn't already reach the last SHITEMID */
744                 SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item.hItem);
745                 item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_CHILD,
746                                              (LPARAM)item.hItem);
747             }
748         } else {
749             item.hItem = (HTREEITEM)SendMessageW(info->hwndTreeView, TVM_GETNEXTITEM, TVGN_NEXT,
750                                              (LPARAM)item.hItem);
751         }
752     }
753
754     if (_ILIsEmpty(pidlCurrent) && item.hItem) 
755         bResult = TRUE;
756
757 done:
758     if (pidlSelection && pidlSelection != selection)
759         ILFree(pidlSelection);
760
761     if (pItem) 
762         *pItem = item.hItem;
763     
764     return bResult;
765 }
766
767 static BOOL BrsFolder_OnSetSelectionW(browse_info *info, LPVOID selection, BOOL is_str) {
768     HTREEITEM hItem;
769     BOOL bResult;
770
771     bResult = BrsFolder_OnSetExpanded(info, selection, is_str, &hItem);
772     if (bResult)
773         SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem );
774     return bResult;
775 }
776
777 static BOOL BrsFolder_OnSetSelectionA(browse_info *info, LPVOID selection, BOOL is_str) {
778     LPWSTR selectionW = NULL;
779     BOOL result = FALSE;
780     int length;
781     
782     if (!is_str)
783         return BrsFolder_OnSetSelectionW(info, selection, is_str);
784
785     if ((length = MultiByteToWideChar(CP_ACP, 0, selection, -1, NULL, 0)) &&
786         (selectionW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR))) &&
787         MultiByteToWideChar(CP_ACP, 0, selection, -1, selectionW, length))
788     {
789         result = BrsFolder_OnSetSelectionW(info, selectionW, is_str);
790     }
791
792     HeapFree(GetProcessHeap(), 0, selectionW);
793     return result;
794 }
795
796 static BOOL BrsFolder_OnWindowPosChanging(browse_info *info, WINDOWPOS *pos)
797 {
798     if ((info->lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE) && !(pos->flags & SWP_NOSIZE))
799     {
800         if (pos->cx < info->szMin.cx)
801             pos->cx = info->szMin.cx;
802         if (pos->cy < info->szMin.cy)
803             pos->cy = info->szMin.cy;
804     }
805     return 0;
806 }
807
808 static INT BrsFolder_OnDestroy(browse_info *info)
809 {
810     if (info->layout)
811     {
812         SHFree(info->layout);
813         info->layout = NULL;
814     }
815
816     return 0;
817 }
818
819 /*************************************************************************
820  *             BrsFolderDlgProc32  (not an exported API function)
821  */
822 static INT_PTR CALLBACK BrsFolderDlgProc( HWND hWnd, UINT msg, WPARAM wParam,
823                                           LPARAM lParam )
824 {
825     browse_info *info;
826
827     TRACE("hwnd=%p msg=%04x 0x%08lx 0x%08lx\n", hWnd, msg, wParam, lParam );
828
829     if (msg == WM_INITDIALOG)
830         return BrsFolder_OnCreate( hWnd, (browse_info*) lParam );
831
832     info = GetPropW( hWnd, szBrowseFolderInfo );
833
834     switch (msg)
835     {
836     case WM_NOTIFY:
837         return BrsFolder_OnNotify( info, (UINT)wParam, (LPNMHDR)lParam);
838
839     case WM_COMMAND:
840         return BrsFolder_OnCommand( info, wParam );
841
842     case WM_WINDOWPOSCHANGING:
843         return BrsFolder_OnWindowPosChanging( info, (WINDOWPOS *)lParam);
844
845     case WM_SIZE:
846         if (info->layout)  /* new style dialogs */
847             LayoutUpdate(hWnd, info->layout, g_layout_info, LAYOUT_INFO_COUNT);
848         return 0;
849
850     case BFFM_SETSTATUSTEXTA:
851         TRACE("Set status %s\n", debugstr_a((LPSTR)lParam));
852         SetWindowTextA(GetDlgItem(hWnd, IDD_STATUS), (LPSTR)lParam);
853         break;
854
855     case BFFM_SETSTATUSTEXTW:
856         TRACE("Set status %s\n", debugstr_w((LPWSTR)lParam));
857         SetWindowTextW(GetDlgItem(hWnd, IDD_STATUS), (LPWSTR)lParam);
858         break;
859
860     case BFFM_ENABLEOK:
861         TRACE("Enable %ld\n", lParam);
862         EnableWindow(GetDlgItem(hWnd, 1), (lParam)?TRUE:FALSE);
863         break;
864
865     case BFFM_SETOKTEXT: /* unicode only */
866         TRACE("Set OK text %s\n", debugstr_w((LPWSTR)wParam));
867         SetWindowTextW(GetDlgItem(hWnd, 1), (LPWSTR)wParam);
868         break;
869
870     case BFFM_SETSELECTIONA:
871         return BrsFolder_OnSetSelectionA(info, (LPVOID)lParam, (BOOL)wParam);
872
873     case BFFM_SETSELECTIONW:
874         return BrsFolder_OnSetSelectionW(info, (LPVOID)lParam, (BOOL)wParam);
875
876     case BFFM_SETEXPANDED: /* unicode only */
877         return BrsFolder_OnSetExpanded(info, (LPVOID)lParam, (BOOL)wParam, NULL);
878
879     case WM_DESTROY:
880         return BrsFolder_OnDestroy(info);
881     }
882     return FALSE;
883 }
884
885 static const WCHAR swBrowseTemplateName[] = {
886     'S','H','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
887 static const WCHAR swNewBrowseTemplateName[] = {
888     'S','H','N','E','W','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
889
890 /*************************************************************************
891  * SHBrowseForFolderA [SHELL32.@]
892  * SHBrowseForFolder  [SHELL32.@]
893  */
894 LPITEMIDLIST WINAPI SHBrowseForFolderA (LPBROWSEINFOA lpbi)
895 {
896     BROWSEINFOW bi;
897     LPITEMIDLIST lpid;
898     INT len;
899     LPWSTR title;
900
901     TRACE("%p\n", lpbi);
902
903     bi.hwndOwner = lpbi->hwndOwner;
904     bi.pidlRoot = lpbi->pidlRoot;
905     if (lpbi->pszDisplayName)
906     {
907         bi.pszDisplayName = HeapAlloc( GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR) );
908         MultiByteToWideChar( CP_ACP, 0, lpbi->pszDisplayName, -1, bi.pszDisplayName, MAX_PATH );
909     }
910     else
911         bi.pszDisplayName = NULL;
912
913     if (lpbi->lpszTitle)
914     {
915         len = MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, NULL, 0 );
916         title = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
917         MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, title, len );
918     }
919     else
920         title = NULL;
921
922     bi.lpszTitle = title;
923     bi.ulFlags = lpbi->ulFlags;
924     bi.lpfn = lpbi->lpfn;
925     bi.lParam = lpbi->lParam;
926     bi.iImage = lpbi->iImage;
927     lpid = SHBrowseForFolderW( &bi );
928     if (bi.pszDisplayName)
929     {
930         WideCharToMultiByte( CP_ACP, 0, bi.pszDisplayName, -1,
931                              lpbi->pszDisplayName, MAX_PATH, 0, NULL);
932         HeapFree( GetProcessHeap(), 0, bi.pszDisplayName );
933     }
934     HeapFree(GetProcessHeap(), 0, title);
935     lpbi->iImage = bi.iImage;
936     return lpid;
937 }
938
939
940 /*************************************************************************
941  * SHBrowseForFolderW [SHELL32.@]
942  *
943  * NOTES
944  *  crashes when passed a null pointer
945  */
946 LPITEMIDLIST WINAPI SHBrowseForFolderW (LPBROWSEINFOW lpbi)
947 {
948     browse_info info;
949     DWORD r;
950     HRESULT hr;
951     const WCHAR * templateName;
952
953     info.hWnd = 0;
954     info.pidlRet = NULL;
955     info.lpBrowseInfo = lpbi;
956     info.hwndTreeView = NULL;
957
958     hr = OleInitialize(NULL);
959
960     if (lpbi->ulFlags & BIF_NEWDIALOGSTYLE)
961         templateName = swNewBrowseTemplateName;
962     else
963         templateName = swBrowseTemplateName;
964     r = DialogBoxParamW( shell32_hInstance, templateName, lpbi->hwndOwner,
965                          BrsFolderDlgProc, (LPARAM)&info );
966     if (SUCCEEDED(hr)) 
967         OleUninitialize();
968     if (!r)
969         return NULL;
970
971     return info.pidlRet;
972 }