mshtml: Improve loading document detection in AsyncOpen.
[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  */
22
23 #include <stdlib.h>
24 #include <string.h>
25
26 #define COBJMACROS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29
30 #include "wine/debug.h"
31 #include "undocshell.h"
32 #include "shlguid.h"
33 #include "pidl.h"
34 #include "shell32_main.h"
35 #include "shellapi.h"
36 #include "shresdef.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(shell);
39
40 typedef struct tagbrowse_info
41 {
42     HWND          hWnd;
43     HWND          hwndTreeView;
44     LPBROWSEINFOW lpBrowseInfo;
45     LPITEMIDLIST  pidlRet;
46 } browse_info;
47
48 typedef struct tagTV_ITEMDATA
49 {
50    LPSHELLFOLDER lpsfParent; /* IShellFolder of the parent */
51    LPITEMIDLIST  lpi;        /* PIDL relativ to parent */
52    LPITEMIDLIST  lpifq;      /* Fully qualified PIDL */
53    IEnumIDList*  pEnumIL;    /* Children iterator */ 
54 } TV_ITEMDATA, *LPTV_ITEMDATA;
55
56 #define SUPPORTEDFLAGS (BIF_STATUSTEXT | \
57                         BIF_BROWSEFORCOMPUTER | \
58                         BIF_RETURNFSANCESTORS | \
59                         BIF_RETURNONLYFSDIRS | \
60                         BIF_BROWSEINCLUDEFILES)
61
62 static void FillTreeView(browse_info*, LPSHELLFOLDER,
63                LPITEMIDLIST, HTREEITEM, IEnumIDList*);
64 static HTREEITEM InsertTreeViewItem( browse_info*, IShellFolder *,
65                LPCITEMIDLIST, LPCITEMIDLIST, IEnumIDList*, HTREEITEM);
66
67 static const WCHAR szBrowseFolderInfo[] = {
68     '_','_','W','I','N','E','_',
69     'B','R','S','F','O','L','D','E','R','D','L','G','_',
70     'I','N','F','O',0
71 };
72
73 static inline DWORD BrowseFlagsToSHCONTF(UINT ulFlags)
74 {
75     return SHCONTF_FOLDERS | (ulFlags & BIF_BROWSEINCLUDEFILES ? SHCONTF_NONFOLDERS : 0);
76 }
77
78 static void browsefolder_callback( LPBROWSEINFOW lpBrowseInfo, HWND hWnd,
79                                    UINT msg, LPARAM param )
80 {
81     if (!lpBrowseInfo->lpfn)
82         return;
83     lpBrowseInfo->lpfn( hWnd, msg, param, lpBrowseInfo->lParam );
84 }
85
86 /******************************************************************************
87  * InitializeTreeView [Internal]
88  *
89  * Called from WM_INITDIALOG handler.
90  * 
91  * PARAMS
92  *  hwndParent [I] The BrowseForFolder dialog
93  *  root       [I] ITEMIDLIST of the root shell folder
94  */
95 static void InitializeTreeView( browse_info *info )
96 {
97     LPITEMIDLIST pidlParent, pidlChild;
98     HIMAGELIST hImageList;
99     HRESULT hr;
100     IShellFolder *lpsfParent, *lpsfRoot;
101     IEnumIDList * pEnumChildren = NULL;
102     HTREEITEM item;
103     DWORD flags;
104     LPCITEMIDLIST root = info->lpBrowseInfo->pidlRoot;
105
106     TRACE("%p\n", info );
107     
108     Shell_GetImageList(NULL, &hImageList);
109
110     if (hImageList)
111         SendMessageW( info->hwndTreeView, TVM_SETIMAGELIST, 0, (LPARAM)hImageList );
112
113     /* We want to call InsertTreeViewItem down the code, in order to insert
114      * the root item of the treeview. Due to InsertTreeViewItem's signature, 
115      * we need the following to do this:
116      *
117      * + An ITEMIDLIST corresponding to _the parent_ of root. 
118      * + An ITEMIDLIST, which is a relative path from root's parent to root 
119      *   (containing a single SHITEMID).
120      * + An IShellFolder interface pointer of root's parent folder.
121      *
122      * If root is 'Desktop', then root's parent is also 'Desktop'.
123      */
124
125     pidlParent = ILClone(root);
126     ILRemoveLastID(pidlParent);
127     pidlChild = ILClone(ILFindLastID(root));
128     
129     if (_ILIsDesktop(pidlParent)) {
130         hr = SHGetDesktopFolder(&lpsfParent);
131     } else {
132         IShellFolder *lpsfDesktop;
133         hr = SHGetDesktopFolder(&lpsfDesktop);
134         if (!SUCCEEDED(hr)) {
135             WARN("SHGetDesktopFolder failed! hr = %08x\n", hr);
136             return;
137         }
138         hr = IShellFolder_BindToObject(lpsfDesktop, pidlParent, 0, &IID_IShellFolder, (LPVOID*)&lpsfParent);
139         IShellFolder_Release(lpsfDesktop);
140     }
141     
142     if (!SUCCEEDED(hr)) {
143         WARN("Could not bind to parent shell folder! hr = %08x\n", hr);
144         return;
145     }
146
147     if (pidlChild && pidlChild->mkid.cb) {
148         hr = IShellFolder_BindToObject(lpsfParent, pidlChild, 0, &IID_IShellFolder, (LPVOID*)&lpsfRoot);
149     } else {
150         lpsfRoot = lpsfParent;
151         hr = IShellFolder_AddRef(lpsfParent);
152     }
153     
154     if (!SUCCEEDED(hr)) {
155         WARN("Could not bind to root shell folder! hr = %08x\n", hr);
156         IShellFolder_Release(lpsfParent);
157         return;
158     }
159
160     flags = BrowseFlagsToSHCONTF( info->lpBrowseInfo->ulFlags );
161     hr = IShellFolder_EnumObjects( lpsfRoot, info->hWnd, flags, &pEnumChildren );
162     if (!SUCCEEDED(hr)) {
163         WARN("Could not get child iterator! hr = %08x\n", hr);
164         IShellFolder_Release(lpsfParent);
165         IShellFolder_Release(lpsfRoot);
166         return;
167     }
168
169     SendMessageW( info->hwndTreeView, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT );
170     item = InsertTreeViewItem( info, lpsfParent, pidlChild,
171                                pidlParent, pEnumChildren, TVI_ROOT );
172     SendMessageW( info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item );
173
174     IShellFolder_Release(lpsfRoot);
175     IShellFolder_Release(lpsfParent);
176 }
177
178 static int GetIcon(LPITEMIDLIST lpi, UINT uFlags)
179 {
180     SHFILEINFOW sfi;
181     SHGetFileInfoW((LPCWSTR)lpi, 0 ,&sfi, sizeof(SHFILEINFOW), uFlags);
182     return sfi.iIcon;
183 }
184
185 static void GetNormalAndSelectedIcons(LPITEMIDLIST lpifq, LPTVITEMW lpTV_ITEM)
186 {
187     LPITEMIDLIST pidlDesktop = NULL;
188     DWORD flags;
189
190     TRACE("%p %p\n",lpifq, lpTV_ITEM);
191
192     if (!lpifq)
193     {
194         pidlDesktop = _ILCreateDesktop();
195         lpifq = pidlDesktop;
196     }
197
198     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON;
199     lpTV_ITEM->iImage = GetIcon( lpifq, flags );
200
201     flags = SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_OPENICON;
202     lpTV_ITEM->iSelectedImage = GetIcon( lpifq, flags );
203
204     if (pidlDesktop)
205         ILFree( pidlDesktop );
206 }
207
208 /******************************************************************************
209  * GetName [Internal]
210  *
211  * Query a shell folder for the display name of one of it's children
212  *
213  * PARAMS
214  *  lpsf           [I] IShellFolder interface of the folder to be queried.
215  *  lpi            [I] ITEMIDLIST of the child, relative to parent
216  *  dwFlags        [I] as in IShellFolder::GetDisplayNameOf
217  *  lpFriendlyName [O] The desired display name in unicode
218  *
219  * RETURNS
220  *  Success: TRUE
221  *  Failure: FALSE
222  */
223 static BOOL GetName(LPSHELLFOLDER lpsf, LPCITEMIDLIST lpi, DWORD dwFlags, LPWSTR lpFriendlyName)
224 {
225         BOOL   bSuccess=TRUE;
226         STRRET str;
227
228         TRACE("%p %p %x %p\n", lpsf, lpi, dwFlags, lpFriendlyName);
229         if (SUCCEEDED(IShellFolder_GetDisplayNameOf(lpsf, lpi, dwFlags, &str)))
230           bSuccess = StrRetToStrNW(lpFriendlyName, MAX_PATH, &str, lpi);
231         else
232           bSuccess = FALSE;
233
234         TRACE("-- %s\n", debugstr_w(lpFriendlyName));
235         return bSuccess;
236 }
237
238 /******************************************************************************
239  * InsertTreeViewItem [Internal]
240  *
241  * PARAMS
242  *  info       [I] data for the dialog
243  *  lpsf       [I] IShellFolder interface of the item's parent shell folder 
244  *  pidl       [I] ITEMIDLIST of the child to insert, relativ to parent 
245  *  pidlParent [I] ITEMIDLIST of the parent shell folder
246  *  pEnumIL    [I] Iterator for the children of the item to be inserted
247  *  hParent    [I] The treeview-item that represents the parent shell folder
248  *
249  * RETURNS
250  *  Success: Handle to the created and inserted treeview-item
251  *  Failure: NULL
252  */
253 static HTREEITEM InsertTreeViewItem( browse_info *info, IShellFolder * lpsf,
254     LPCITEMIDLIST pidl, LPCITEMIDLIST pidlParent, IEnumIDList* pEnumIL,
255     HTREEITEM hParent)
256 {
257         TVITEMW         tvi;
258         TVINSERTSTRUCTW tvins;
259         WCHAR           szBuff[MAX_PATH];
260         LPTV_ITEMDATA   lptvid=0;
261
262         tvi.mask  = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM;
263
264         tvi.cChildren= pEnumIL ? 1 : 0;
265         tvi.mask |= TVIF_CHILDREN;
266
267         lptvid = SHAlloc( sizeof(TV_ITEMDATA) );
268         if (!lptvid)
269             return NULL;
270
271         if (!GetName(lpsf, pidl, SHGDN_NORMAL, szBuff))
272             return NULL;
273
274         tvi.pszText    = szBuff;
275         tvi.cchTextMax = MAX_PATH;
276         tvi.lParam = (LPARAM)lptvid;
277
278         IShellFolder_AddRef(lpsf);
279         lptvid->lpsfParent = lpsf;
280         lptvid->lpi     = ILClone(pidl);
281         lptvid->lpifq   = pidlParent ? ILCombine(pidlParent, pidl) : ILClone(pidl);
282         lptvid->pEnumIL = pEnumIL;
283         GetNormalAndSelectedIcons(lptvid->lpifq, &tvi);
284
285         tvins.u.item       = tvi;
286         tvins.hInsertAfter = NULL;
287         tvins.hParent      = hParent;
288
289         return (HTREEITEM)TreeView_InsertItemW( info->hwndTreeView, &tvins );
290 }
291
292 /******************************************************************************
293  * FillTreeView [Internal]
294  *
295  * For each child (given by lpe) of the parent shell folder, which is given by 
296  * lpsf and whose PIDL is pidl, insert a treeview-item right under hParent
297  *
298  * PARAMS
299  *  info    [I] data for the dialog
300  *  lpsf    [I] IShellFolder interface of the parent shell folder
301  *  pidl    [I] ITEMIDLIST of the parent shell folder
302  *  hParent [I] The treeview item that represents the parent shell folder
303  *  lpe     [I] An iterator for the children of the parent shell folder
304  */
305 static void FillTreeView( browse_info *info, IShellFolder * lpsf,
306                  LPITEMIDLIST  pidl, HTREEITEM hParent, IEnumIDList* lpe)
307 {
308         HTREEITEM       hPrev = 0;
309         LPITEMIDLIST    pidlTemp = 0;
310         ULONG           ulFetched;
311         HRESULT         hr;
312         HWND            hwnd = GetParent( info->hwndTreeView );
313
314         TRACE("%p %p %p %p\n",lpsf, pidl, hParent, lpe);
315
316         /* No IEnumIDList -> No children */
317         if (!lpe) return;
318         
319         SetCapture( hwnd );
320         SetCursor( LoadCursorA( 0, (LPSTR)IDC_WAIT ) );
321
322         while (NOERROR == IEnumIDList_Next(lpe,1,&pidlTemp,&ulFetched))
323         {
324             ULONG ulAttrs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER;
325             IEnumIDList* pEnumIL = NULL;
326             IShellFolder* pSFChild = NULL;
327             IShellFolder_GetAttributesOf(lpsf, 1, (LPCITEMIDLIST*)&pidlTemp, &ulAttrs);
328             if (ulAttrs & SFGAO_FOLDER)
329             {
330                 hr = IShellFolder_BindToObject(lpsf,pidlTemp,NULL,&IID_IShellFolder,(LPVOID*)&pSFChild);
331                 if (SUCCEEDED(hr))
332                 {
333                     DWORD flags = BrowseFlagsToSHCONTF(info->lpBrowseInfo->ulFlags);
334                     hr = IShellFolder_EnumObjects(pSFChild, hwnd, flags, &pEnumIL);
335                     if (hr == S_OK)
336                     {
337                         if ((IEnumIDList_Skip(pEnumIL, 1) != S_OK) ||
338                              FAILED(IEnumIDList_Reset(pEnumIL)))
339                         {
340                             IEnumIDList_Release(pEnumIL);
341                             pEnumIL = NULL;
342                         }
343                     }
344                     IShellFolder_Release(pSFChild);
345                 }
346             }
347
348             if (!(hPrev = InsertTreeViewItem(info, lpsf, pidlTemp, pidl, pEnumIL, hParent)))
349                 goto done;
350             SHFree(pidlTemp);  /* Finally, free the pidl that the shell gave us... */
351             pidlTemp=NULL;
352         }
353
354 done:
355         ReleaseCapture();
356         SetCursor(LoadCursorW(0, (LPWSTR)IDC_ARROW));
357     SHFree(pidlTemp);
358 }
359
360 static inline BOOL PIDLIsType(LPCITEMIDLIST pidl, PIDLTYPE type)
361 {
362     LPPIDLDATA data = _ILGetDataPointer(pidl);
363     if (!data)
364         return FALSE;
365     return (data->type == type);
366 }
367
368 static void BrsFolder_CheckValidSelection( browse_info *info, LPTV_ITEMDATA lptvid )
369 {
370     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
371     LPCITEMIDLIST pidl = lptvid->lpi;
372     BOOL bEnabled = TRUE;
373     DWORD dwAttributes;
374     HRESULT r;
375
376     if ((lpBrowseInfo->ulFlags & BIF_BROWSEFORCOMPUTER) &&
377         !PIDLIsType(pidl, PT_COMP))
378         bEnabled = FALSE;
379     if (lpBrowseInfo->ulFlags & BIF_RETURNFSANCESTORS)
380     {
381         dwAttributes = SFGAO_FILESYSANCESTOR | SFGAO_FILESYSTEM;
382         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
383                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
384         if (FAILED(r) || !(dwAttributes & (SFGAO_FILESYSANCESTOR|SFGAO_FILESYSTEM)))
385             bEnabled = FALSE;
386     }
387     if (lpBrowseInfo->ulFlags & BIF_RETURNONLYFSDIRS)
388     {
389         dwAttributes = SFGAO_FOLDER | SFGAO_FILESYSTEM;
390         r = IShellFolder_GetAttributesOf(lptvid->lpsfParent, 1,
391                                 (LPCITEMIDLIST*)&lptvid->lpi, &dwAttributes);
392         if (FAILED(r) || 
393             ((dwAttributes & (SFGAO_FOLDER|SFGAO_FILESYSTEM)) != (SFGAO_FOLDER|SFGAO_FILESYSTEM)))
394         {
395             bEnabled = FALSE;
396         }
397     }
398     SendMessageW(info->hWnd, BFFM_ENABLEOK, 0, (LPARAM)bEnabled);
399 }
400
401 static LRESULT BrsFolder_Treeview_Delete( browse_info *info, NMTREEVIEWW *pnmtv )
402 {
403     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA)pnmtv->itemOld.lParam;
404
405     TRACE("TVN_DELETEITEMA/W %p\n", lptvid);
406
407     IShellFolder_Release(lptvid->lpsfParent);
408     if (lptvid->pEnumIL)
409         IEnumIDList_Release(lptvid->pEnumIL);
410     SHFree(lptvid->lpi);
411     SHFree(lptvid->lpifq);
412     SHFree(lptvid);
413     return 0;
414 }
415
416 static LRESULT BrsFolder_Treeview_Expand( browse_info *info, NMTREEVIEWW *pnmtv )
417 {
418     IShellFolder *lpsf2 = NULL;
419     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
420     HRESULT r;
421
422     TRACE("TVN_ITEMEXPANDINGA/W\n");
423
424     if ((pnmtv->itemNew.state & TVIS_EXPANDEDONCE))
425         return 0;
426
427     if (lptvid->lpi && lptvid->lpi->mkid.cb) {
428         r = IShellFolder_BindToObject( lptvid->lpsfParent, lptvid->lpi, 0,
429                                       (REFIID)&IID_IShellFolder, (LPVOID *)&lpsf2 );
430     } else {
431         lpsf2 = lptvid->lpsfParent;
432         r = IShellFolder_AddRef(lpsf2);
433     }
434
435     if (SUCCEEDED(r))
436         FillTreeView( info, lpsf2, lptvid->lpifq, pnmtv->itemNew.hItem, lptvid->pEnumIL);
437
438     /* My Computer is already sorted and trying to do a simple text
439      * sort will only mess things up */
440     if (!_ILIsMyComputer(lptvid->lpi))
441         SendMessageW( info->hwndTreeView, TVM_SORTCHILDREN,
442                       FALSE, (LPARAM)pnmtv->itemNew.hItem );
443
444     return 0;
445 }
446
447 static HRESULT BrsFolder_Treeview_Changed( browse_info *info, NMTREEVIEWW *pnmtv )
448 {
449     LPTV_ITEMDATA lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
450
451     lptvid = (LPTV_ITEMDATA) pnmtv->itemNew.lParam;
452     info->pidlRet = lptvid->lpifq;
453     browsefolder_callback( info->lpBrowseInfo, info->hWnd, BFFM_SELCHANGED,
454                            (LPARAM)info->pidlRet );
455     BrsFolder_CheckValidSelection( info, lptvid );
456     return 0;
457 }
458
459 static LRESULT BrsFolder_OnNotify( browse_info *info, UINT CtlID, LPNMHDR lpnmh )
460 {
461     NMTREEVIEWW *pnmtv = (NMTREEVIEWW *)lpnmh;
462
463     TRACE("%p %x %p msg=%x\n", info, CtlID, lpnmh, pnmtv->hdr.code);
464
465     if (pnmtv->hdr.idFrom != IDD_TREEVIEW)
466         return 0;
467
468     switch (pnmtv->hdr.code)
469     {
470     case TVN_DELETEITEMA:
471     case TVN_DELETEITEMW:
472         return BrsFolder_Treeview_Delete( info, pnmtv );
473
474     case TVN_ITEMEXPANDINGA:
475     case TVN_ITEMEXPANDINGW:
476         return BrsFolder_Treeview_Expand( info, pnmtv );
477
478     case TVN_SELCHANGEDA:
479     case TVN_SELCHANGEDW:
480         return BrsFolder_Treeview_Changed( info, pnmtv );
481
482     default:
483         WARN("unhandled (%d)\n", pnmtv->hdr.code);
484         break;
485     }
486
487     return 0;
488 }
489
490
491 static BOOL BrsFolder_OnCreate( HWND hWnd, browse_info *info )
492 {
493     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
494
495     info->hWnd = hWnd;
496     SetPropW( hWnd, szBrowseFolderInfo, info );
497
498     if (lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS)
499         FIXME("flags %x not implemented\n", lpBrowseInfo->ulFlags & ~SUPPORTEDFLAGS);
500
501     if (lpBrowseInfo->lpszTitle)
502         SetWindowTextW( GetDlgItem(hWnd, IDD_TITLE), lpBrowseInfo->lpszTitle );
503     else
504         ShowWindow( GetDlgItem(hWnd, IDD_TITLE), SW_HIDE );
505
506     if (!(lpBrowseInfo->ulFlags & BIF_STATUSTEXT))
507         ShowWindow( GetDlgItem(hWnd, IDD_STATUS), SW_HIDE );
508
509     info->hwndTreeView = GetDlgItem( hWnd, IDD_TREEVIEW );
510     if (info->hwndTreeView)
511         InitializeTreeView( info );
512     else
513         ERR("treeview control missing!\n");
514
515     browsefolder_callback( info->lpBrowseInfo, hWnd, BFFM_INITIALIZED, 0 );
516
517     return TRUE;
518 }
519
520 static BOOL BrsFolder_OnCommand( browse_info *info, UINT id )
521 {
522     LPBROWSEINFOW lpBrowseInfo = info->lpBrowseInfo;
523
524     switch (id)
525     {
526     case IDOK:
527         info->pidlRet = ILClone(info->pidlRet); /* The original pidl will be free'd. */
528         pdump( info->pidlRet );
529         if (lpBrowseInfo->pszDisplayName)
530             SHGetPathFromIDListW( info->pidlRet, lpBrowseInfo->pszDisplayName );
531         EndDialog( info->hWnd, 1 );
532         return TRUE;
533
534     case IDCANCEL:
535         EndDialog( info->hWnd, 0 );
536         return TRUE;
537     }
538     return FALSE;
539 }
540
541 static BOOL BrsFolder_OnSetExpanded(browse_info *info, LPVOID selection, 
542     BOOL is_str, HTREEITEM *pItem)
543 {
544     LPITEMIDLIST pidlSelection = (LPITEMIDLIST)selection;
545     LPCITEMIDLIST pidlCurrent, pidlRoot;
546     TVITEMEXW item;
547     BOOL bResult = FALSE;
548     
549     /* If 'selection' is a string, convert to a Shell ID List. */ 
550     if (is_str) {
551         IShellFolder *psfDesktop;
552         HRESULT hr;
553
554         hr = SHGetDesktopFolder(&psfDesktop);
555         if (FAILED(hr))
556             goto done;
557
558         hr = IShellFolder_ParseDisplayName(psfDesktop, NULL, NULL, 
559                      (LPOLESTR)selection, NULL, &pidlSelection, NULL);
560         IShellFolder_Release(psfDesktop);
561         if (FAILED(hr)) 
562             goto done;
563     }
564
565     /* Move pidlCurrent behind the SHITEMIDs in pidlSelection, which are the root of
566      * the sub-tree currently displayed. */
567     pidlRoot = info->lpBrowseInfo->pidlRoot;
568     pidlCurrent = pidlSelection;
569     while (!_ILIsEmpty(pidlRoot) && _ILIsEqualSimple(pidlRoot, pidlCurrent)) {
570         pidlRoot = ILGetNext(pidlRoot);
571         pidlCurrent = ILGetNext(pidlCurrent);
572     }
573
574     /* The given ID List is not part of the SHBrowseForFolder's current sub-tree. */
575     if (!_ILIsEmpty(pidlRoot))
576         goto done;
577
578     /* Initialize item to point to the first child of the root folder. */
579     memset(&item, 0, sizeof(item));
580     item.mask = TVIF_PARAM;
581     item.hItem = TreeView_GetRoot(info->hwndTreeView);
582     if (item.hItem) 
583         item.hItem = TreeView_GetChild(info->hwndTreeView, item.hItem);
584
585     /* Walk the tree along the nodes corresponding to the remaining ITEMIDLIST */
586     while (item.hItem && !_ILIsEmpty(pidlCurrent)) {
587         LPTV_ITEMDATA pItemData;
588
589         SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
590         pItemData = (LPTV_ITEMDATA)item.lParam;
591
592         if (_ILIsEqualSimple(pItemData->lpi, pidlCurrent)) {
593             pidlCurrent = ILGetNext(pidlCurrent);
594             if (!_ILIsEmpty(pidlCurrent)) {
595                 /* Only expand current node and move on to it's first child,
596                  * if we didn't already reach the last SHITEMID */
597                 SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item.hItem);
598                 item.hItem = TreeView_GetChild(info->hwndTreeView, item.hItem);
599             }
600         } else {
601             item.hItem = TreeView_GetNextSibling(info->hwndTreeView, item.hItem);
602         }
603     }
604
605     if (_ILIsEmpty(pidlCurrent) && item.hItem) 
606         bResult = TRUE;
607
608 done:
609     if (pidlSelection && pidlSelection != (LPITEMIDLIST)selection)
610         ILFree(pidlSelection);
611
612     if (pItem) 
613         *pItem = item.hItem;
614     
615     return bResult;
616 }
617
618 static BOOL BrsFolder_OnSetSelectionW(browse_info *info, LPVOID selection, BOOL is_str) {
619     HTREEITEM hItem;
620     BOOL bResult;
621
622     bResult = BrsFolder_OnSetExpanded(info, selection, is_str, &hItem);
623     if (bResult)
624         SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem );
625     return bResult;
626 }
627
628 static BOOL BrsFolder_OnSetSelectionA(browse_info *info, LPVOID selection, BOOL is_str) {
629     LPWSTR selectionW = NULL;
630     BOOL result = FALSE;
631     int length;
632     
633     if (!is_str)
634         return BrsFolder_OnSetSelectionW(info, selection, is_str);
635     
636     if ((length = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)selection, -1, NULL, 0)) &&
637         (selectionW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR))) &&
638         MultiByteToWideChar(CP_ACP, 0, (LPCSTR)selection, -1, selectionW, length))
639     {
640         result = BrsFolder_OnSetSelectionW(info, selectionW, is_str);
641     }
642
643     HeapFree(GetProcessHeap(), 0, selectionW);
644     return result;
645 }
646
647 /*************************************************************************
648  *             BrsFolderDlgProc32  (not an exported API function)
649  */
650 static INT_PTR CALLBACK BrsFolderDlgProc( HWND hWnd, UINT msg, WPARAM wParam,
651                                           LPARAM lParam )
652 {
653     browse_info *info;
654
655     TRACE("hwnd=%p msg=%04x 0x%08x 0x%08lx\n", hWnd,  msg, wParam, lParam );
656
657     if (msg == WM_INITDIALOG)
658         return BrsFolder_OnCreate( hWnd, (browse_info*) lParam );
659
660     info = (browse_info*) GetPropW( hWnd, szBrowseFolderInfo );
661
662     switch (msg)
663     {
664     case WM_NOTIFY:
665         return BrsFolder_OnNotify( info, (UINT)wParam, (LPNMHDR)lParam);
666
667     case WM_COMMAND:
668         return BrsFolder_OnCommand( info, wParam );
669
670     case BFFM_SETSTATUSTEXTA:
671         TRACE("Set status %s\n", debugstr_a((LPSTR)lParam));
672         SetWindowTextA(GetDlgItem(hWnd, IDD_STATUS), (LPSTR)lParam);
673         break;
674
675     case BFFM_SETSTATUSTEXTW:
676         TRACE("Set status %s\n", debugstr_w((LPWSTR)lParam));
677         SetWindowTextW(GetDlgItem(hWnd, IDD_STATUS), (LPWSTR)lParam);
678         break;
679
680     case BFFM_ENABLEOK:
681         TRACE("Enable %ld\n", lParam);
682         EnableWindow(GetDlgItem(hWnd, 1), (lParam)?TRUE:FALSE);
683         break;
684
685     case BFFM_SETOKTEXT: /* unicode only */
686         TRACE("Set OK text %s\n", debugstr_w((LPWSTR)wParam));
687         SetWindowTextW(GetDlgItem(hWnd, 1), (LPWSTR)wParam);
688         break;
689
690     case BFFM_SETSELECTIONA:
691         return BrsFolder_OnSetSelectionA(info, (LPVOID)lParam, (BOOL)wParam);
692
693     case BFFM_SETSELECTIONW:
694         return BrsFolder_OnSetSelectionW(info, (LPVOID)lParam, (BOOL)wParam);
695
696     case BFFM_SETEXPANDED: /* unicode only */
697         return BrsFolder_OnSetExpanded(info, (LPVOID)lParam, (BOOL)wParam, NULL);
698     }
699     return FALSE;
700 }
701
702 static const WCHAR swBrowseTemplateName[] = {
703     'S','H','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
704
705 /*************************************************************************
706  * SHBrowseForFolderA [SHELL32.@]
707  * SHBrowseForFolder  [SHELL32.@]
708  */
709 LPITEMIDLIST WINAPI SHBrowseForFolderA (LPBROWSEINFOA lpbi)
710 {
711     BROWSEINFOW bi;
712     LPITEMIDLIST lpid;
713     INT len;
714     LPWSTR title;
715
716     TRACE("%p\n", lpbi);
717
718     bi.hwndOwner = lpbi->hwndOwner;
719     bi.pidlRoot = lpbi->pidlRoot;
720     if (lpbi->pszDisplayName)
721     {
722         bi.pszDisplayName = HeapAlloc( GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR) );
723         MultiByteToWideChar( CP_ACP, 0, lpbi->pszDisplayName, -1, bi.pszDisplayName, MAX_PATH );
724     }
725     else
726         bi.pszDisplayName = NULL;
727
728     if (lpbi->lpszTitle)
729     {
730         len = MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, NULL, 0 );
731         title = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
732         MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, title, len );
733     }
734     else
735         title = NULL;
736
737     bi.lpszTitle = title;
738     bi.ulFlags = lpbi->ulFlags;
739     bi.lpfn = lpbi->lpfn;
740     bi.lParam = lpbi->lParam;
741     bi.iImage = lpbi->iImage;
742     lpid = SHBrowseForFolderW( &bi );
743     if (bi.pszDisplayName)
744     {
745         WideCharToMultiByte( CP_ACP, 0, bi.pszDisplayName, -1,
746                              lpbi->pszDisplayName, MAX_PATH, 0, NULL);
747         HeapFree( GetProcessHeap(), 0, bi.pszDisplayName );
748     }
749     HeapFree(GetProcessHeap(), 0, title);
750     lpbi->iImage = bi.iImage;
751     return lpid;
752 }
753
754
755 /*************************************************************************
756  * SHBrowseForFolderW [SHELL32.@]
757  *
758  * NOTES
759  *  crashes when passed a null pointer
760  */
761 LPITEMIDLIST WINAPI SHBrowseForFolderW (LPBROWSEINFOW lpbi)
762 {
763     browse_info info;
764     DWORD r;
765     HRESULT hr;
766
767     info.hWnd = 0;
768     info.pidlRet = NULL;
769     info.lpBrowseInfo = lpbi;
770     info.hwndTreeView = NULL;
771
772     hr = OleInitialize(NULL);
773     r = DialogBoxParamW( shell32_hInstance, swBrowseTemplateName, lpbi->hwndOwner,
774                          BrsFolderDlgProc, (LPARAM)&info );
775     if (SUCCEEDED(hr)) 
776         OleUninitialize();
777     if (!r)
778         return NULL;
779
780     return info.pidlRet;
781 }