ws2_32/tests: Avoid sizeof in traces.
[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, (LPARAM)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                                       (REFIID)&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 = TreeView_GetRoot(info->hwndTreeView);
727     if (item.hItem) 
728         item.hItem = TreeView_GetChild(info->hwndTreeView, item.hItem);
729
730     /* Walk the tree along the nodes corresponding to the remaining ITEMIDLIST */
731     while (item.hItem && !_ILIsEmpty(pidlCurrent)) {
732         LPTV_ITEMDATA pItemData;
733
734         SendMessageW(info->hwndTreeView, TVM_GETITEMW, 0, (LPARAM)&item);
735         pItemData = (LPTV_ITEMDATA)item.lParam;
736
737         if (_ILIsEqualSimple(pItemData->lpi, pidlCurrent)) {
738             pidlCurrent = ILGetNext(pidlCurrent);
739             if (!_ILIsEmpty(pidlCurrent)) {
740                 /* Only expand current node and move on to it's first child,
741                  * if we didn't already reach the last SHITEMID */
742                 SendMessageW(info->hwndTreeView, TVM_EXPAND, TVE_EXPAND, (LPARAM)item.hItem);
743                 item.hItem = TreeView_GetChild(info->hwndTreeView, item.hItem);
744             }
745         } else {
746             item.hItem = TreeView_GetNextSibling(info->hwndTreeView, item.hItem);
747         }
748     }
749
750     if (_ILIsEmpty(pidlCurrent) && item.hItem) 
751         bResult = TRUE;
752
753 done:
754     if (pidlSelection && pidlSelection != selection)
755         ILFree(pidlSelection);
756
757     if (pItem) 
758         *pItem = item.hItem;
759     
760     return bResult;
761 }
762
763 static BOOL BrsFolder_OnSetSelectionW(browse_info *info, LPVOID selection, BOOL is_str) {
764     HTREEITEM hItem;
765     BOOL bResult;
766
767     bResult = BrsFolder_OnSetExpanded(info, selection, is_str, &hItem);
768     if (bResult)
769         SendMessageW(info->hwndTreeView, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem );
770     return bResult;
771 }
772
773 static BOOL BrsFolder_OnSetSelectionA(browse_info *info, LPVOID selection, BOOL is_str) {
774     LPWSTR selectionW = NULL;
775     BOOL result = FALSE;
776     int length;
777     
778     if (!is_str)
779         return BrsFolder_OnSetSelectionW(info, selection, is_str);
780
781     if ((length = MultiByteToWideChar(CP_ACP, 0, selection, -1, NULL, 0)) &&
782         (selectionW = HeapAlloc(GetProcessHeap(), 0, length * sizeof(WCHAR))) &&
783         MultiByteToWideChar(CP_ACP, 0, selection, -1, selectionW, length))
784     {
785         result = BrsFolder_OnSetSelectionW(info, selectionW, is_str);
786     }
787
788     HeapFree(GetProcessHeap(), 0, selectionW);
789     return result;
790 }
791
792 static BOOL BrsFolder_OnWindowPosChanging(browse_info *info, WINDOWPOS *pos)
793 {
794     if ((info->lpBrowseInfo->ulFlags & BIF_NEWDIALOGSTYLE) && !(pos->flags & SWP_NOSIZE))
795     {
796         if (pos->cx < info->szMin.cx)
797             pos->cx = info->szMin.cx;
798         if (pos->cy < info->szMin.cy)
799             pos->cy = info->szMin.cy;
800     }
801     return 0;
802 }
803
804 static INT BrsFolder_OnDestroy(browse_info *info)
805 {
806     if (info->layout)
807     {
808         SHFree(info->layout);
809         info->layout = NULL;
810     }
811
812     return 0;
813 }
814
815 /*************************************************************************
816  *             BrsFolderDlgProc32  (not an exported API function)
817  */
818 static INT_PTR CALLBACK BrsFolderDlgProc( HWND hWnd, UINT msg, WPARAM wParam,
819                                           LPARAM lParam )
820 {
821     browse_info *info;
822
823     TRACE("hwnd=%p msg=%04x 0x%08lx 0x%08lx\n", hWnd, msg, wParam, lParam );
824
825     if (msg == WM_INITDIALOG)
826         return BrsFolder_OnCreate( hWnd, (browse_info*) lParam );
827
828     info = GetPropW( hWnd, szBrowseFolderInfo );
829
830     switch (msg)
831     {
832     case WM_NOTIFY:
833         return BrsFolder_OnNotify( info, (UINT)wParam, (LPNMHDR)lParam);
834
835     case WM_COMMAND:
836         return BrsFolder_OnCommand( info, wParam );
837
838     case WM_WINDOWPOSCHANGING:
839         return BrsFolder_OnWindowPosChanging( info, (WINDOWPOS *)lParam);
840
841     case WM_SIZE:
842         if (info->layout)  /* new style dialogs */
843             LayoutUpdate(hWnd, info->layout, g_layout_info, LAYOUT_INFO_COUNT);
844         return 0;
845
846     case BFFM_SETSTATUSTEXTA:
847         TRACE("Set status %s\n", debugstr_a((LPSTR)lParam));
848         SetWindowTextA(GetDlgItem(hWnd, IDD_STATUS), (LPSTR)lParam);
849         break;
850
851     case BFFM_SETSTATUSTEXTW:
852         TRACE("Set status %s\n", debugstr_w((LPWSTR)lParam));
853         SetWindowTextW(GetDlgItem(hWnd, IDD_STATUS), (LPWSTR)lParam);
854         break;
855
856     case BFFM_ENABLEOK:
857         TRACE("Enable %ld\n", lParam);
858         EnableWindow(GetDlgItem(hWnd, 1), (lParam)?TRUE:FALSE);
859         break;
860
861     case BFFM_SETOKTEXT: /* unicode only */
862         TRACE("Set OK text %s\n", debugstr_w((LPWSTR)wParam));
863         SetWindowTextW(GetDlgItem(hWnd, 1), (LPWSTR)wParam);
864         break;
865
866     case BFFM_SETSELECTIONA:
867         return BrsFolder_OnSetSelectionA(info, (LPVOID)lParam, (BOOL)wParam);
868
869     case BFFM_SETSELECTIONW:
870         return BrsFolder_OnSetSelectionW(info, (LPVOID)lParam, (BOOL)wParam);
871
872     case BFFM_SETEXPANDED: /* unicode only */
873         return BrsFolder_OnSetExpanded(info, (LPVOID)lParam, (BOOL)wParam, NULL);
874
875     case WM_DESTROY:
876         return BrsFolder_OnDestroy(info);
877     }
878     return FALSE;
879 }
880
881 static const WCHAR swBrowseTemplateName[] = {
882     'S','H','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
883 static const WCHAR swNewBrowseTemplateName[] = {
884     'S','H','N','E','W','B','R','S','F','O','R','F','O','L','D','E','R','_','M','S','G','B','O','X',0};
885
886 /*************************************************************************
887  * SHBrowseForFolderA [SHELL32.@]
888  * SHBrowseForFolder  [SHELL32.@]
889  */
890 LPITEMIDLIST WINAPI SHBrowseForFolderA (LPBROWSEINFOA lpbi)
891 {
892     BROWSEINFOW bi;
893     LPITEMIDLIST lpid;
894     INT len;
895     LPWSTR title;
896
897     TRACE("%p\n", lpbi);
898
899     bi.hwndOwner = lpbi->hwndOwner;
900     bi.pidlRoot = lpbi->pidlRoot;
901     if (lpbi->pszDisplayName)
902     {
903         bi.pszDisplayName = HeapAlloc( GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR) );
904         MultiByteToWideChar( CP_ACP, 0, lpbi->pszDisplayName, -1, bi.pszDisplayName, MAX_PATH );
905     }
906     else
907         bi.pszDisplayName = NULL;
908
909     if (lpbi->lpszTitle)
910     {
911         len = MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, NULL, 0 );
912         title = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
913         MultiByteToWideChar( CP_ACP, 0, lpbi->lpszTitle, -1, title, len );
914     }
915     else
916         title = NULL;
917
918     bi.lpszTitle = title;
919     bi.ulFlags = lpbi->ulFlags;
920     bi.lpfn = lpbi->lpfn;
921     bi.lParam = lpbi->lParam;
922     bi.iImage = lpbi->iImage;
923     lpid = SHBrowseForFolderW( &bi );
924     if (bi.pszDisplayName)
925     {
926         WideCharToMultiByte( CP_ACP, 0, bi.pszDisplayName, -1,
927                              lpbi->pszDisplayName, MAX_PATH, 0, NULL);
928         HeapFree( GetProcessHeap(), 0, bi.pszDisplayName );
929     }
930     HeapFree(GetProcessHeap(), 0, title);
931     lpbi->iImage = bi.iImage;
932     return lpid;
933 }
934
935
936 /*************************************************************************
937  * SHBrowseForFolderW [SHELL32.@]
938  *
939  * NOTES
940  *  crashes when passed a null pointer
941  */
942 LPITEMIDLIST WINAPI SHBrowseForFolderW (LPBROWSEINFOW lpbi)
943 {
944     browse_info info;
945     DWORD r;
946     HRESULT hr;
947     const WCHAR * templateName;
948
949     info.hWnd = 0;
950     info.pidlRet = NULL;
951     info.lpBrowseInfo = lpbi;
952     info.hwndTreeView = NULL;
953
954     hr = OleInitialize(NULL);
955
956     if (lpbi->ulFlags & BIF_NEWDIALOGSTYLE)
957         templateName = swNewBrowseTemplateName;
958     else
959         templateName = swBrowseTemplateName;
960     r = DialogBoxParamW( shell32_hInstance, templateName, lpbi->hwndOwner,
961                          BrsFolderDlgProc, (LPARAM)&info );
962     if (SUCCEEDED(hr)) 
963         OleUninitialize();
964     if (!r)
965         return NULL;
966
967     return info.pidlRet;
968 }